- 不要使用inplace操作
比如
out += residual #会导致原来的out被覆盖,反向传播出现问题。
a.add_(10.) # 或者 a += 10.
# RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
需要反向传播,并再次赋值,正确的做法:
a.data.fill_(10.)
# 或者 a.detach().fill_(10.)
参考博客:
PyTorch 的 Autograd