本来也想水一篇博客的,但是前辈已经写的很好了,花了两天时间精读了一下,感觉还是转载一下,记录一下为好
Torch中的AutoGrad
https://zhuanlan.zhihu.com/p/69294347
Torch中的Inplace
操作
https://www.cnblogs.com/jiangkejie/p/13390377.html
Torch中的Hook
https://www.zhihu.com/question/61044004
Torch中的Hook
(详细版)
https://oldpan.me/archives/pytorch-autograd-hook
Torch中Tensor的坑
https://zhuanlan.zhihu.com/p/67184419
Torch中inplace操作与.data和.detach()
https://blog.csdn.net/qq_36653505/article/details/90026373
PyTorch的Variable
的hook
是register_hook
,用于对非叶子节点的Tensor进行提取
后面的两个:register_backward_hook
和register_forward_hook
是针对nn.Module
这个对象的
设计者建议使用tensor
的hook
而不建议使用module
的hook
对于任意一个张量来说,我们可以用 tensor.is_leaf
来判断它是否是叶子张量(leaf tensor
)。在反向传播过程中,只有 is_leaf=True
的时候,需要求导的张量的导数结果才会被最后保留下来。
PyTorch 的求导不支持绝大部分 inplace 操作:, 否则会有如下操作
RuntimeError: leaf variable has been moved into the graph interior
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
tensor.detach()
和 tensor.data
操作类似, 但是 detach
会被自动求导系统追踪,使用起来很安全