Compute gradient
gradient of current tensor w.r.t. graph leaves
gradients값들을 추후에 backward를 해줄때 계속 더해주기 때문에 항상 backpropagation을 하기전에 gradients를 zero로 만들어주고 시작
retain_graph- Computational Graph 유지한다 memory
gradient
create_graph
inputs
With this straightforward PyTorch method, you can reduce your GPU memory consumption by up to half or essentially increase your batch size twofold. Rather than aggregating multiple losses and subsequently invoking backward(), you should invoke backward() on each loss individually. This strategy is only effective if you have numerous losses with separate computational graphs.
Pytorch에서는 왜 항상 optimizer.zero_grad()를 해줄까?
바로 질문에 대한 답을 말씀드리자면 "Pytorch에서는 gradients값들을 추후에 backward를 해줄때 계속 더해주기 때문"에 우리는 항상 backpropagation을 하기전에 gradients를 zero로 만들어주고 시작을 해야합니다. 이렇게 gradients을 더해주는 방식은 RNN을 학습시킬때 매우 편리한 방식입니다. 따라서 매번 loss.backward()를 호출할때 초기설정은 매번 gradient를 더해주는 것으로 설정되어있습니다. 그렇기 때문에 학습 loop를 돌때 이상적으로 학습이 이루어지기 위해선 한번의 학습이 완료되어지면(즉, Iteration이 한번 끝나면) gradients를 항상 0으로 만들어 주어야 합니다. 만약 gradients를 0으로 초기화해주지 않으면 gradie..
https://algopoolja.tistory.com/55
torch.Tensor.backward — PyTorch 2.0 documentation
https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html

Seonglae Cho