[Pytorch] Error : Leaf variable has been moved into the graph interior 해결 방법 공유

2021. 1. 16. 21:02분석 Python/Pytorch

728x90

torch에서 loss.backward()를 할 때 다음과 같은 에러를 경험을 했다

 

특정값에 inplace를 하게 되면 다음과 같은 에러가 생긴다.

필자는 아래와 같은 것이 loss에 들어가 있었다.

## 1
array[array==1] = 0.0
## 2
array[idx] = logit

 

그래서 필자는 다음과 같이 여러개의 글을 보고 수정했다.

 

하나는 새로운 객체로 만드는 것이다

애는 단순히 개수를 세주는 역할이라서 해결됐다.

array[array==1.0] = 1
count = array.sum()

두 번째는 torch.cat을 사용했다. (불확실!)

 

사용하지 않는 것과 사용하는 것들을 모아서 새로운 tensor를 만드니 작동했다.

물론 근데 update는 된 거지만 실제로 반영됐지는 아직 필요하다 

 torch.cat([torch.zeros(first, requires_grad=False),
           torch.cat(use_tensor_list),
           torch.zeros(total_n-first-len(ent_list), requires_grad=False)])

이런 식으로 일단은 해결을 했는데, 잘 됐으면 좋겠다!

 

 

discuss.pytorch.org/t/how-to-get-around-in-place-operation-error-if-index-leaf-variable-for-gradient-update/14554

discuss.pytorch.org/t/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-torch-floattensor-3-1-which-is-output-0-of-tanhbackward-is-at-version-1-expected-version-0-instead/87630

 

discuss.pytorch.org/t/leaf-variable-has-been-moved-into-the-graph-interior/18679/6

728x90