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 #如果是在訓練網絡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. 我的看法
其實,想想這幾種情況都是一回事,都是網絡在反向傳播中不允許多個backward(),也就是梯度下降反饋的時候,有多個循環(huán)過程中共用了同一個需要計算梯度的變量,在前一個循環(huán)清除梯度后,后面一個循環(huán)過程就會在這個變量上栽跟頭(個人想法)。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python庫textract提取各種文檔類型中文本數(shù)據(jù)
Python的textract庫是一個強大的工具,它可以從各種文檔類型中提取文本數(shù)據(jù),無論是PDF、Word文檔、圖片還是其他格式的文件,textract都可以輕松地將文本提取出來,本文將詳細介紹textract的功能和用法,并提供豐富的示例代碼來幫助大家深入了解2024-01-01
一文詳解Python中的Map,Filter和Reduce函數(shù)
這篇文章主要介紹了一文詳解Python中的Map,Filter和Reduce函數(shù),本文重點介紹Python中的三個特殊函數(shù)Map,Filter和Reduce,以及如何使用它們進行代碼編程2022-08-08
Python實現(xiàn)爬蟲IP負載均衡和高可用集群的示例代碼
做大型爬蟲項目經常遇到請求頻率過高的問題,這里需要說的是使用爬蟲IP可以提高抓取效率,本文主要介紹了Python實現(xiàn)爬蟲IP負載均衡和高可用集群的示例代碼,感興趣的可以了解一下2023-12-12

