訓練用PyTorch編寫的LSTM或RNN時,在loss.backward()上報錯:
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.backward(retain_graph=True),會導致顯卡內存隨著訓練一直增加直到OOM:
RuntimeError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 10.73 GiB total capacity; 9.79 GiB already allocated; 13.62 MiB free; 162.76 MiB cached)
正確做法:
LSRM / RNN模塊初始化時定義好hidden,每次forward都要加上self.hidden = self.init_hidden(): Class LSTMClassifier(nn.Module): def __init__(self, embedding_dim, hidden_dim): # 此次省略其它代碼 self.rnn_cell = nn.LSTM(embedding_dim, hidden_dim) self.hidden = self.init_hidden() # 此次省略其它代碼 def init_hidden(self): # 開始時刻, 沒有隱狀態 # 關於維度設置的詳情,請參考 Pytorch 文檔 # 各個維度的含義是 (Seguence, minibatch_size, hidden_dim) return (torch.zeros(1, 1, self.hidden_dim), torch.zeros(1, 1, self.hidden_dim)) def forward(self, x): # 此次省略其它代碼 self.hidden = self.init_hidden() # 就是加上這句!!!! out, self.hidden = self.rnn_cell(x, self.hidden) # 此次省略其它代碼 return out
或者其它模塊每次調用這個模塊時,其它模塊的forward()都對這個LSTM模塊init_hidden()一下。
如定義一個模型LSTM_Model():
Class LSTM_Model(nn.Module): def __init__(self, embedding_dim, hidden_dim): # 此次省略其它代碼 self.rnn = LSTMClassifier(embedding_dim, hidden_dim) # 此次省略其它代碼 def forward(self, x): # 此次省略其它代碼 self.rnn.hidden = self.rnn.init_hidden() # 就是加上這句!!!! out = self.rnn(x) # 此次省略其它代碼 return out
這是因為:
根據 官方tutorial,在 loss 反向傳播的時候,pytorch 試圖把 hidden state 也反向傳播,但是在新的一輪 batch 的時候 hidden state 已經被內存釋放瞭,所以需要每個 batch 重新 init (clean out hidden state), 或者 detach,從而切斷反向傳播。
補充:pytorch:在執行loss.backward()時out of memory報錯
在自己編寫SurfNet網絡的過程中,出現瞭這個問題,查閱資料後,將得到的解決方法匯總如下
可試用的方法:
1、reduce batch size, all the way down to 1
2、remove everything to CPU leaving only the network on the GPU
3、remove validation code, and only executing the training code
4、reduce the size of the network (I reduced it significantly: details below)
5、I tried scaling the magnitude of the loss that is backpropagating as well to a much smaller value
在訓練時,在每一個step後面加上:
torch.cuda.empty_cache()
在每一個驗證時的step之後加上代碼:
with torch.no_grad()
不要在循環訓練中累積歷史記錄
total_loss = 0 for i in range(10000): optimizer.zero_grad() output = model(input) loss = criterion(output) loss.backward() optimizer.step() total_loss += loss
total_loss在循環中進行瞭累計,因為loss是一個具有autograd歷史的可微變量。你可以通過編寫total_loss += float(loss)來解決這個問題。
本人遇到這個問題的原因是,自己構建的模型輸入到全連接層中的特征圖拉伸為1維向量時太大導致的,加入pool層或者其他方法將最後的卷積層輸出的特征圖尺寸減小即可。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支援。