关于PyTorch中的inplace操作和Hook

本来也想水一篇博客的,但是前辈已经写的很好了,花了两天时间精读了一下,感觉还是转载一下,记录一下为好


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的Variablehookregister_hook,用于对非叶子节点的Tensor进行提取
后面的两个:register_backward_hookregister_forward_hook是针对nn.Module这个对象的

设计者建议使用tensorhook而不建议使用modulehook

对于任意一个张量来说,我们可以用 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 会被自动求导系统追踪,使用起来很安全

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值