您好,登錄后才能下訂單哦!
當(dāng)我們?cè)儆?xùn)練網(wǎng)絡(luò)的時(shí)候可能希望保持一部分的網(wǎng)絡(luò)參數(shù)不變,只對(duì)其中一部分的參數(shù)進(jìn)行調(diào)整;或者值訓(xùn)練部分分支網(wǎng)絡(luò),并不讓其梯度對(duì)主網(wǎng)絡(luò)的梯度造成影響,這時(shí)候我們就需要使用detach()函數(shù)來切斷一些分支的反向傳播
1 detach()[source]
返回一個(gè)新的Variable,從當(dāng)前計(jì)算圖中分離下來的,但是仍指向原變量的存放位置,不同之處只是requires_grad為false,得到的這個(gè)Variable永遠(yuǎn)不需要計(jì)算其梯度,不具有g(shù)rad。
即使之后重新將它的requires_grad置為true,它也不會(huì)具有梯度grad
這樣我們就會(huì)繼續(xù)使用這個(gè)新的Variable進(jìn)行計(jì)算,后面當(dāng)我們進(jìn)行反向傳播時(shí),到該調(diào)用detach()的Variable就會(huì)停止,不能再繼續(xù)向前進(jìn)行傳播
源碼為:
def detach(self): """Returns a new Variable, detached from the current graph. Result will never require gradient. If the input is volatile, the output will be volatile too. .. note:: Returned Variable uses the same data tensor, as the original one, and in-place modifications on either of them will be seen, and may trigger errors in correctness checks. """ result = NoGrad()(self) # this is needed, because it merges version counters result._grad_fn = None return result
可見函數(shù)進(jìn)行的操作有:
如果輸入 volatile=True(即不需要保存記錄,當(dāng)只需要結(jié)果而不需要更新參數(shù)時(shí)這么設(shè)置來加快運(yùn)算速度),那么返回的Variable volatile=True。(volatile已經(jīng)棄用)
注意:
返回的Variable和原始的Variable公用同一個(gè)data tensor。in-place函數(shù)修改會(huì)在兩個(gè)Variable上同時(shí)體現(xiàn)(因?yàn)樗鼈児蚕韉ata tensor),當(dāng)要對(duì)其調(diào)用backward()時(shí)可能會(huì)導(dǎo)致錯(cuò)誤。
舉例:
比如正常的例子是:
import torch a = torch.tensor([1, 2, 3.], requires_grad=True) print(a.grad) out = a.sigmoid() out.sum().backward() print(a.grad)
返回:
(deeplearning) userdeMBP:pytorch user$ python test.py
None
tensor([0.1966, 0.1050, 0.0452])
當(dāng)使用detach()但是沒有進(jìn)行更改時(shí),并不會(huì)影響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) #這時(shí)候沒有對(duì)c進(jìn)行更改,所以并不會(huì)影響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.1966, 0.1050, 0.0452])
可見c,out之間的區(qū)別是c是沒有梯度的,out是有梯度的
如果這里使用的是c進(jìn)行sum()操作并進(jìn)行backward(),則會(huì)報(bào)錯(cuò):
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) #使用新生成的Variable進(jìn)行反向傳播 c.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])
Traceback (most recent call last):
File "test.py", line 13, in <module>
c.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: element 0 of tensors does not require grad and does not have a grad_fn
如果此時(shí)對(duì)c進(jìn)行了更改,這個(gè)更改會(huì)被autograd追蹤,在對(duì)out.sum()進(jìn)行backward()時(shí)也會(huì)報(bào)錯(cuò),因?yàn)榇藭r(shí)的值進(jìn)行backward()得到的梯度是錯(cuò)誤的:
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函數(shù)對(duì)其進(jìn)行修改 #會(huì)發(fā)現(xiàn)c的修改同時(shí)會(huì)影響out的值 print(c) print(out) #這時(shí)候?qū)進(jìn)行更改,所以會(huì)影響backward(),這時(shí)候就不能進(jìn)行backward(),會(huì)報(bào)錯(cuò) 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,效果會(huì)不同:
這里的不同在于.data的修改不會(huì)被autograd追蹤,這樣當(dāng)進(jìn)行backward()時(shí)它不會(huì)報(bào)錯(cuò),回得到一個(gè)錯(cuò)誤的backward值
import torch a = torch.tensor([1, 2, 3.], requires_grad=True) print(a.grad) out = a.sigmoid() print(out) c = out.data print(c) c.zero_() #使用in place函數(shù)對(duì)其進(jìn)行修改 #會(huì)發(fā)現(xiàn)c的修改同時(shí)也會(huì)影響out的值 print(c) print(out) #這里的不同在于.data的修改不會(huì)被autograd追蹤,這樣當(dāng)進(jìn)行backward()時(shí)它不會(huì)報(bào)錯(cuò),回得到一個(gè)錯(cuò)誤的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>)
tensor([0., 0., 0.])
上面的內(nèi)容實(shí)現(xiàn)的原理是:
In-place 正確性檢查
所有的Variable都會(huì)記錄用在他們身上的 in-place operations。如果pytorch檢測(cè)到variable在一個(gè)Function中已經(jīng)被保存用來backward,但是之后它又被in-place operations修改。當(dāng)這種情況發(fā)生時(shí),在backward的時(shí)候,pytorch就會(huì)報(bào)錯(cuò)。這種機(jī)制保證了,如果你用了in-place operations,但是在backward過程中沒有報(bào)錯(cuò),那么梯度的計(jì)算就是正確的。
⚠️下面結(jié)果正確是因?yàn)楦淖兊氖莝um()的結(jié)果,中間值a.sigmoid()并沒有被影響,所以其對(duì)求梯度并沒有影響:
import torch a = torch.tensor([1, 2, 3.], requires_grad=True) print(a.grad) out = a.sigmoid().sum() #但是如果sum寫在這里,而不是寫在backward()前,得到的結(jié)果是正確的 print(out) c = out.data print(c) c.zero_() #使用in place函數(shù)對(duì)其進(jìn)行修改 #會(huì)發(fā)現(xiàn)c的修改同時(shí)也會(huì)影響out的值 print(c) print(out) #沒有寫在這里 out.backward() 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_()[source]
將一個(gè)Variable從創(chuàng)建它的圖中分離,并把它設(shè)置成葉子variable
其實(shí)就相當(dāng)于變量之間的關(guān)系本來是x -> m -> y,這里的葉子variable是x,但是這個(gè)時(shí)候?qū)進(jìn)行了.detach_()操作,其實(shí)就是進(jìn)行了兩個(gè)操作:
這么一看其實(shí)detach()和detach_()很像,兩個(gè)的區(qū)別就是detach_()是對(duì)本身的更改,detach()則是生成了一個(gè)新的variable
比如x -> m -> y中如果對(duì)m進(jìn)行detach(),后面如果反悔想還是對(duì)原來的計(jì)算圖進(jìn)行操作還是可以的
但是如果是進(jìn)行了detach_(),那么原來的計(jì)算圖也發(fā)生了變化,就不能反悔了
參考:https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-autograd/#detachsource
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。