Programming/Python

[PyTorch][에러 해결] RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [32]], which is output 0 of SelectBackward, is at version 165; expected version 164 instead. H..

영스퀘어 2021. 10. 19. 16:14

<실험 환경>

CUDA 11.1

Pytorch 1.8.0

 

GCN Layer 사이에 Attention mechanism을 구현하는 도중 아래와 같은 에러가 발생했다.

 

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: 

[torch.cuda.FloatTensor [32]], which is output 0 of SelectBackward, is at version 165; expected version 164 instead.

Hint: enable anomaly detection to find the operation that failed to compute its gradient,

with torch.autograd.set_detect_anomaly(True).

 

이러한 에러 같은 경우, 정확히 어떤 라인에서 발생한 에러인지 보여주지 않으므로,

Train을 수행하는 전체 부분을 아래 코드로 감싸면 어떤 라인에서 문제가 있는지 보여준다.

참고로, 아래 코드를 사용하면 속도가 매우 느려지므로 해당 코드를 없애더라도 에러가 발생하지 않으면 없애는 것을 추천한다.

with th.autograd.set_detect_anomaly(True):

 

 

나의 경우, 아래와 같이 기존 변수에 곱셈을 수행한 값을 inplace modification 하는 과정에서 문제가 있었다.

for i in range(b_neighbor_users_feature.size(0)):
	b_neighbor_users_feature[i] = b_neighbor_users_feature[i] * att_score_user[i]

 

따라서, 새로운 변수에 값을 넣는 방식으로 수정하여 해결하였다.

b_neighbor_users_feature_att = th.zeros_like(b_neighbor_users_feature)
for i in range(b_neighbor_users_feature.size(0)):
	b_neighbor_users_feature_att[i] = b_neighbor_users_feature[i] * att_score_user[i]

 

그런데 추가적으로, 아래와 같은 에러가 발생했는데 Tanh 대신 ReLU로 변경하니 문제 없었다.

Error detected in TanhBackward. Traceback of forward call that caused the error~~~