윤제로의 제로베이스

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn 본문

Issue board/python

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

윤_제로 2023. 9. 25. 14:54

pre trained model을 가져와서 일부 레이어에만 requires_grad=True로 해두었는데 loss를 계산하니 loss.backward() 부분에서 런타임 에러가 났다.

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

아래와 같이 loss.requires_grad_(True)를 추가해주니 잘 돌아간다.

optimizer.zero_grad()
loss.requires_grad_(True) # 추가
loss.backward()
optimizer.step()

 

출처: 

https://yjs-program.tistory.com/210

 

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn 전체 네트워크 모델 중, 일부 레이어만 requires_grad = True로 셋팅했는데, 특정 구간에서 loss.backward()를 수행할 때, 다음과 같은 에러

yjs-program.tistory.com