pytorch中retain_graph==True的作用說明
pytorch retain_graph==True的作用說明
總的來說進行一次backward之后,各個節(jié)點的值會清除,這樣進行第二次backward會報錯,如果加上retain_graph==True后,可以再來一次backward。
retain_graph參數(shù)的作用
官方定義:
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
大意是如果設置為False,計算圖中的中間變量在計算完后就會被釋放。
但是在平時的使用中這個參數(shù)默認都為False從而提高效率,和creat_graph的值一樣。
具體看一個例子理解
假設一個我們有一個輸入x,y = x **2, z = y*4,然后我們有兩個輸出,一個output_1 = z.mean(),另一個output_2 = z.sum()。
然后我們對兩個output執(zhí)行backward。
import torch x = torch.randn((1,4),dtype=torch.float32,requires_grad=True) y = x ** 2 z = y * 4 print(x) print(y) print(z) loss1 = z.mean() loss2 = z.sum() print(loss1,loss2) loss1.backward() ? ?# 這個代碼執(zhí)行正常,但是執(zhí)行完中間變量都free了,所以下一個出現(xiàn)了問題 print(loss1,loss2) loss2.backward() ? ?# 這時會引發(fā)錯誤
程序正常執(zhí)行到第12行,所有的變量正常保存。
但是在第13行報錯:
RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
分析:計算節(jié)點數(shù)值保存了,但是計算圖x-y-z結構被釋放了,而計算loss2的backward仍然試圖利用x-y-z的結構,因此會報錯。
因此需要retain_graph參數(shù)為True去保留中間參數(shù)從而兩個loss的backward()不會相互影響。
正確的代碼應當把第11行以及之后改成
- 1 # 假如你需要執(zhí)行兩次backward,先執(zhí)行第一個的backward,再執(zhí)行第二個backward
- 2 loss1.backward(retain_graph=True)# 這里參數(shù)表明保留backward后的中間參數(shù)。
- 3 loss2.backward() # 執(zhí)行完這個后,所有中間變量都會被釋放,以便下一次的循環(huán)
- 4 #如果是在訓練網(wǎng)絡optimizer.step() # 更新參數(shù)
create_graph參數(shù)比較簡單,參考官方定義:
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.
Pytorch retain_graph=True錯誤信息
(Pytorch:RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time)
具有多個loss值
retain_graph設置True,一般多用于兩次backward
# 假如有兩個Loss,先執(zhí)行第一個的backward,再執(zhí)行第二個backward loss1.backward(retain_graph=True) # 這樣計算圖就不會立即釋放 loss2.backward() # 執(zhí)行完這個后,所有中間變量都會被釋放,以便下一次的循環(huán) optimizer.step() # 更新參數(shù)
retain_graph設置True后一定要知道釋放,否則顯卡會占用越來越多,代碼速度也會跑的越來越慢。
有的時候我明明僅有一個模型的也會出現(xiàn)這種錯誤
第一種是輸入的原因。
// Example x = torch.randn((100,1), requires_grad = True) y = 1 + 2 * x + 0.3 * torch.randn(100,1) x_train, y_train = x[:70], y[:70] x_val, y_val = x[70:], y[70:] for epoch in range(n_epochs): ?? ?... ?? ?prediction = model(x_train) ?? ?loss.backward() ?? ?...
在多次循環(huán)的過程中,input的梯度沒有清除,而且我們也不需要計算輸入的梯度,因此將x的require_grad設置為False就可以解決問題。
第二種是我在訓練LSTM時候發(fā)現(xiàn)的。
class LSTMpred(nn.Module): ? ? def __init__(self, input_size, hidden_dim): ? ? ?? ?self.hidden = self.init_hidden() ? ? ? ?... ? ? def init_hidden(self):?? ?#這里我們是需要個隱層參數(shù)的 ? ? ? ? return (torch.zeros(1, 1, self.hidden_dim, requires_grad=True), ? ? ? ? ? ? ? ? torch.zeros(1, 1, self.hidden_dim, requires_grad=True)) ? ? def forward(self, seq): ? ? ? ? ...
這里面的self.hidden我們在每一次訓練的時候都要重新初始化隱層參數(shù):
for epoch in range(Epoch): ?? ?... ?? ?model.hidden = model.init_hidden() ?? ?modout = model(seq) ? ? ...
3. 我的看法
其實,想想這幾種情況都是一回事,都是網(wǎng)絡在反向傳播中不允許多個backward(),也就是梯度下降反饋的時候,有多個循環(huán)過程中共用了同一個需要計算梯度的變量,在前一個循環(huán)清除梯度后,后面一個循環(huán)過程就會在這個變量上栽跟頭(個人想法)。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python定時采集攝像頭圖像上傳ftp服務器功能實現(xiàn)
本文程序實現(xiàn)python定時采集攝像頭圖像上傳ftp服務器功能,大家參考使用吧2013-12-12Django shell調試models輸出的SQL語句方法
今天小編就為大家分享一篇Django shell調試models輸出的SQL語句方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08詳解Python 2.6 升級至 Python 2.7 的實踐心得
本篇文章主要介紹了詳解Python 2.6 升級至 Python 2.7 的實踐心得,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04利用python實現(xiàn)xml與數(shù)據(jù)庫讀取轉換的方法
這篇文章主要給大家介紹了關于利用python實現(xiàn)xml與數(shù)據(jù)庫讀取轉換的方法,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-06-06python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作
這篇文章主要介紹了python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07