AI/PyTorch

[Pytorch Error] RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation 해결

LiDARian 2022. 8. 3. 23:37
반응형

 

[Pytorch Error] RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: 
[torch.FloatTensor [21, 21, 4, 4]] is at version 2; expected version 1 instead. 
Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

위와같은 inplace operation이 gradient flow를 방해하는 이유는, computational graph를 생성하지는 않으면서, gradient chain rule 계산에 필요한 원래의 메모리에 대해서 조작을 일으키기 때문이다.

single operation (indexing, slicing 등의 output이 input과 동일한 메모리를 사용하는 연산)은 불가능하다. 만약 이런 연산을 수행한다면, 반드시 .clone()으로 메모리를 분리해야한다.

다음 예를 보자.

아래와 같은 코드는 b 의 gradient를 계산하는데 a가 필요하지 않아서 에러가 발생하지 않는다.

c = a + b
a.div_(2)
(c + a).sum().backward()

아래와 같은 코드는 b 의 gradient를 계산하는데 a가 필요한 상황이다. 하지만 a 값이 a.div_(2)에 의하여 메모리 내부에서 변화하고, 이는 computational graph에 node를 추가하지 않게 되어서, backward progress 중에 에러가 발생하는 원인이 된다.

c = a * b
a.div_(2)
(c + a).sum().backward()

즉, inplace operation을 사용하지 않고, 되도록 새로운 변수를 새로 선언해주는 것이 안전하며, 또한 inplace operation을 불가피하게 사용하게 된다면 .clone() 메서드를 사용해야한다.

또한 PyTorch에서 backward 과정인 다음 과정의 순서를 지키지 않을 경우 inplace operation error가 발생하기도 한다.

필자의 경우가 그랬다.

optimizer.zero_grad()
loss.backward()
optimizer.step()

자세한 사항은 다음 링크를 참조하는 것이 좋을 것이다.

https://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

https://discuss.pytorch.org/t/gru-model-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation/57312/9

반응형

'AI > PyTorch' 카테고리의 다른 글

[PyTorch] PyTorch 새로운 Module 개발 & 구현 기록  (0) 2023.02.15