pytorch中hook的使用

在pytorch中,可以利用Hook获取、改变网络中间某一层变量的值和梯度,从而便捷地分析网络,而不用专门改变网络结构。

一、torch.Tensor中的hook

在使用pytorch时,只有叶节点(即直接指定数值的节点,而不是由其他变量计算得到的节点,比如网络输入)的梯度会保留,其余中间节点梯度在反向传播完成后就会自动释放以节省显存。

比如:

import torch

x=torch.Tensor([1,2]).requires_grad_(True)
y=torch.Tensor([3,4]).requires_grad_(True)
z=((y-x)**2).mean()
# z.retain_grad()
z.backward()

print('x.requires_grad:',x.requires_grad)
print('y.requires_grad:',y.requires_grad)
print('z.requires_grad:',z.requires_grad)

print('x.grad:',x.grad)
print('y.grad:',y.grad)
print('z.grad:',z.grad)

输出:

x.requires_grad: True
y.requires_grad: True
z.requires_grad: True
x.grad: tensor([-2., -2.])
y.grad: tensor([2., 2.])
/home/wangguoyu/test.py:14: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more information.
  print('z.grad:',z.grad)
z.grad: None

这里x和y是叶子节点,因此在backward后会保留grad,而z的requires_grad虽然为True,但是由于它不是叶子节点,因此梯度没有保留。如果我们确实需要非叶子节点的梯度信息,那么我们需要在backward前使用retain_grad方法(即将上面的注释去掉),这就可以访问z的梯度信息。但是,使用retain_grad保留的grad会占用显存,如果不想要占用显存,那么我们可以使用hook。对于中间节点的变量a,我们可以使用a.register_hook(hook_fn)对其梯度进行操作(可以进行修改或者保存等操作)。这里hook_fn是以恶自定义的函数,其函数声明为:

hook_fn(grad) -> Tensor or None

其输入变量为a的grad,如果返回Tensor,则该Tensor取代a原有的grad,并向前传播;如果不反悔或者返回None,那么a的grad不变,继续向前传播。

import torch

def hook_fn(grad):
  print('here is the hook_fn')
  print(grad)
  
x=torch.Tensor([1,2]).requires_grad_(True)
y=torch.Tensor([3,4]).requires_grad_(True)
z=((y-x)**2).mean()

z.register_hook(hook_fn)

print('before backward')
z.backward()
print('after backward')

print('x.requires_grad:',x.requires_grad)
print('y.requires_grad:',y.requires_grad)
print('z.requires_grad:',z.requires_grad)

print('x.grad:',x.grad)
print('y.grad:',y.grad)
print('z.grad:',z.grad)

输出:

before backward
here is the hook_fn
tensor(1.)
after backward
x.requires_grad: True
y.requires_grad: True
z.requires_grad: True
x.grad: tensor([-2., -2.])
y.grad: tensor([2., 2.])
z.grad: None

可以看到,在z绑定了hook_fn后,backward时,打印了z的grad,因为我们返回None,最后z的grad不变,接下来我们改变z的grad:

import torch

def hook_fn(grad):
  grad*=2
  print('here is the hook_fn')
  print(grad)
  return grad
  
x=torch.Tensor([1,2]).requires_grad_(True)
y=torch.Tensor([3,4]).requires_grad_(True)
z=((y-x)**2).mean()

# z.register_hook(lambda x: 2*x)
z.register_hook(hook_fn)

print('before backward')
z.backward()
print('after backward')

print('x.requires_grad:',x.requires_grad)
print('y.requires_grad:',y.requires_grad)
print('z.requires_grad:',z.requires_grad)

print('x.grad:',x.grad)
print('y.grad:',y.grad)
print('z.grad:',z.grad)

输出:

before backward
here is the hook_fn
tensor(2.)
after backward
x.requires_grad: True
y.requires_grad: True
z.requires_grad: True
x.grad: tensor([-4., -4.])
y.grad: tensor([4., 4.])
z.grad: None

可以看到x和y的grad都变为原来的两倍,这是因为链式求导时z自身的导数发生了变化,这说明hook_fn改变了z的grad。此外,hook_fn也可以是lambda表达式,将上面代码中的注释去掉和使用hook_fn起到的效果是一样的。

待补充
https://zhuanlan.zhihu.com/p/267800207

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorchhook机制是一种用于在计算图注册回调函数的机制。当计算图被执行时,这些回调函数会被调用,并且可以对计算图间结果进行操作或记录。 在PyTorch,每个张量都有一个grad_fn属性,该属性表示该张量是如何计算得到的。通过在这个grad_fn上注册一个hook函数,可以在计算图的每一步获取该张量的梯度,或者在该张量被使用时获取该张量的值。这些hook函数可以被用来实现一些调试、可视化或者改变计算图的操作。 下面是一个简单的例子,其我们在计算图的每一步都打印出间结果和梯度: ```python import torch def print_tensor_info(tensor): print('Tensor shape:', tensor.shape) print('Tensor value:', tensor) print('Tensor gradient:', tensor.grad) x = torch.randn(2, 2, requires_grad=True) y = x * 2 z = y.mean() # 注册一个hook函数,用来打印间结果和梯度 y.register_hook(print_tensor_info) # 执行计算图 z.backward() # 输出结果 print('x gradient:', x.grad) ``` 在这个例子,我们定义了一个张量x,并计算了y和z。我们在y上注册了一个hook函数,该函数在计算图的每一步都会被调用。然后我们执行了z的反向传播,计算出了x的梯度。最后,我们打印出了x的梯度。 需要注意的是,hook函数不能修改张量的值或梯度,否则会影响计算图的正确性。此外,hook函数只会在计算图的正向传播和反向传播时被调用,而不会在张量被直接使用时被调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值