pytorch .detach() .detach_() 和 .data用于切断反向传播(转载)

 pytorch中 .detach() .detach_() 和 .data均能用于切断反向传播,取出本体的tensor数据,舍弃了grad,grad_fn等额外反向图计算过程需保存的额外信息。

 .data和.detach()取出本体tensor后仍与原数据共享内存,在使用in-place操作后,会修改原数据的值。如果在反向传播过程中使用到原数据会导致计算错误,使用.detach后,该变量会被会被autograd追踪,如果在反向传播过程中发现原数据被修改过会报错。这里的不同在于.data的修改不会被autograd追踪,这样当进行backward()时它不会报错,会得到一个错误的backward值。

.detach_()和.detach() 两个的区别就是detach_()是对计算图本身进行更改(原来的计算图发生了变化),detach()则是生成了一个新的variable。

参考:https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-autograd/#detachsource

当我们再训练网络的时候可能希望保持一部分的网络参数不变,只对其中一部分的参数进行调整;或者只训练部分分支网络,并不让其梯度对主网络的梯度造成影响,这时候我们就需要使用detach()函数来切断一些分支的反向传播

1   detach()

返回一个新的Variable,从当前计算图中分离下来的,但是仍指向原变量的存放位置,不同之处只是requires_grad为false,得到的这个Variable永远不需要计算其梯度,不具有grad。

即使之后重新将它的requires_grad置为true,它也不会具有梯度grad

这样我们就会继续使用这个新的Variable进行计算,后面当我们进行反向传播时,到该调用detach()的Variable就会停止,不能再继续向前进行传播

源码为:

 1 def detach(self):
 2         """Returns a new Variable, detached from the current graph.
 3         Result will never require gradient. If the input is volatile, the output
 4         will be volatile too.
 5         .. note::
 6           Returned Variable uses the same data tensor, as the original one, and
 7           in-place modifications on either of them will be seen, and may trigger
 8           errors in correctness checks.
 9         """
10         result = NoGrad()(self)  # this is needed, because it merges version counters
11         result._grad_fn = None     return result

可见函数进行的操作有:

  • 将grad_fn设置为None
  • 将Variablerequires_grad设置为False

如果输入 volatile=True(即不需要保存记录,当只需要结果而不需要更新参数时这么设置来加快运算速度),那么返回的Variable volatile=True。(volatile已经弃用)

注意:

返回的Variable和原始的Variable公用同一个data tensorin-place函数修改会在两个Variable上同时体现(因为它们共享data tensor),当要对其调用backward()时可能会导致错误。

举例:

比如正常的例子是:

1 import torch
2 
3 a = torch.tensor([1, 2, 3.], requires_grad=True)
4 print(a.grad)
5 out = a.sigmoid()
6 
7 out.sum().backward()
8 print(a.grad)

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py 
None
tensor([0.1966, 0.1050, 0.0452])

当使用detach()但是没有进行更改时,并不会影响backward():

 1 import torch
 2 
 3 a = torch.tensor([1, 2, 3.], requires_grad=True)
 4 print(a.grad)
 5 out = a.sigmoid()
 6 print(out)
 7 
 8 #添加detach(),c的requires_grad为False
 9 c = out.detach()
10 print(c)
11 
12 #这时候没有对c进行更改,所以并不会影响backward()
13 out.sum().backward()
14 print(a.grad)

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py 
None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0.1966, 0.1050, 0.0452])

可见c,out之间的区别是c是没有梯度的,out是有梯度的。

如果这里使用的是c进行sum()操作并进行backward(),则会报错:

 1 import torch
 2 
 3 a = torch.tensor([1, 2, 3.], requires_grad=True)
 4 print(a.grad)
 5 out = a.sigmoid()
 6 print(out)
 7 
 8 #添加detach(),c的requires_grad为False
 9 c = out.detach()
10 print(c)
11 
12 #使用新生成的Variable进行反向传播
13 c.sum().backward()
14 print(a.grad)

返回:

 1 (deeplearning) userdeMBP:pytorch user$ python test.py 
 2 None
 3 tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
 4 tensor([0.7311, 0.8808, 0.9526])
 5 Traceback (most recent call last):
 6   File "test.py", line 13, in <module>
 7     c.sum().backward()
 8   File "/anaconda3/envs/deeplearning/lib/python3.6/site-packages/torch/tensor.py", line 102, in backward
 9     torch.autograd.backward(self, gradient, retain_graph, create_graph)
10   File "/anaconda3/envs/deeplearning/lib/python3.6/site-packages/torch/autograd/__init__.py", line 90, in backward
11     allow_unreachable=True)  # allow_unreachable flag
12 RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

如果此时对c进行了更改,这个更改会被autograd追踪,在对out.sum()进行backward()时也会报错,因为此时的值进行backward()得到的梯度是错误的:

import torch

a = torch.tensor([1, 2, 3.], requires_grad=True)
print(a.grad)
out = a.sigmoid()
print(out)

#添加detach(),c的requires_grad为False
c = out.detach()
print(c)
c.zero_() #使用in place函数对其进行修改

#会发现c的修改同时会影响out的值
print(c)
print(out)

#这时候对c进行更改,所以会影响backward(),这时候就不能进行backward(),会报错
out.sum().backward()
print(a.grad)

返回:

复制代码
(deeplearning) userdeMBP:pytorch user$ python test.py 
None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0., 0., 0.])
tensor([0., 0., 0.], grad_fn=<SigmoidBackward>)
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    out.sum().backward()
  File "/anaconda3/envs/deeplearning/lib/python3.6/site-packages/torch/tensor.py", line 102, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "/anaconda3/envs/deeplearning/lib/python3.6/site-packages/torch/autograd/__init__.py", line 90, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
复制代码

2   .data

如果上面的操作使用的是.data,效果会不同:

这里的不同在于.data的修改不会被autograd追踪,这样当进行backward()时它不会报错,会得到一个错误的backward值:

 1 import torch
 2 
 3 a = torch.tensor([1, 2, 3.], requires_grad=True)
 4 print(a.grad)
 5 out = a.sigmoid()
 6 print(out)
 7 
 8 
 9 c = out.data
10 print(c)
11 c.zero_() #使用in place函数对其进行修改
12 
13 #会发现c的修改同时也会影响out的值
14 print(c)
15 print(out)
16 
17 #这里的不同在于.data的修改不会被autograd追踪,这样当进行backward()时它不会报错,回得到一个错误的backward值
18 out.sum().backward()
19 print(a.grad)

返回:

复制代码
(deeplearning) userdeMBP:pytorch user$ python test.py 
None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0., 0., 0.])
tensor([0., 0., 0.], grad_fn=<SigmoidBackward>)
tensor([0., 0., 0.])
复制代码

上面的内容实现的原理是:

In-place 正确性检查

所有的Variable都会记录用在他们身上的 in-place operations。如果pytorch检测到variable在一个Function中已经被保存用来backward,但是之后它又被in-place operations修改。当这种情况发生时,在backward的时候,pytorch就会报错。这种机制保证了,如果你用了in-place operations,但是在backward过程中没有报错,那么梯度的计算就是正确的。

⚠️下面结果正确是因为改变的是sum()的结果,中间值a.sigmoid()并没有被影响,所以其对求梯度并没有影响:

 1 import torch
 2 
 3 a = torch.tensor([1, 2, 3.], requires_grad=True)
 4 print(a.grad)
 5 out = a.sigmoid().sum() #但是如果sum写在这里,而不是写在backward()前,得到的结果是正确的
 6 print(out)
 7 
 8 
 9 c = out.data
10 print(c)
11 c.zero_() #使用in place函数对其进行修改
12 
13 #会发现c的修改同时也会影响out的值
14 print(c)
15 print(out)
16 
17 #没有写在这里
18 out.backward()
19 print(a.grad)

返回:

复制代码
(deeplearning) userdeMBP:pytorch user$ python test.py 
None
tensor(2.5644, grad_fn=<SumBackward0>)
tensor(2.5644)
tensor(0.)
tensor(0., grad_fn=<SumBackward0>)
tensor([0.1966, 0.1050, 0.0452])
复制代码

 3   detach_()

将一个Variable从创建它的图中分离,并把它设置成叶子variable

其实就相当于变量之间的关系本来是x -> m -> y,这里的叶子variable是x,但是这个时候对m进行了.detach_()操作,其实就是进行了两个操作:

  • 将m的grad_fn的值设置为None,这样m就不会再与前一个节点x关联,这里的关系就会变成x, m -> y,此时的m就变成了叶子结点
  • 然后会将m的requires_grad设置为False,这样对y进行backward()时就不会求m的梯度

⚠️

这么一看其实detach()和detach_()很像,两个的区别就是detach_()是对本身的更改,detach()则是生成了一个新的variable

比如x -> m -> y中如果对m进行detach(),后面如果反悔想还是对原来的计算图进行操作还是可以的

但是如果是进行了detach_(),那么原来的计算图也发生了变化,就不能反悔了

原文链接:https://www.cnblogs.com/wanghui-garcia/p/10677071.html

原文地址:https://www.cnblogs.com/jiangkejie/p/12978649.html