亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PyTorch訓(xùn)練LSTM時(shí)loss.backward()報(bào)錯(cuò)的解決方案

 更新時(shí)間:2021年05月31日 14:34:05   作者:Ricky_Yan  
這篇文章主要介紹了PyTorch訓(xùn)練LSTM時(shí)loss.backward()報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

訓(xùn)練用PyTorch編寫的LSTM或RNN時(shí),在loss.backward()上報(bào)錯(cuò):

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.

千萬(wàn)別改成loss.backward(retain_graph=True),會(huì)導(dǎo)致顯卡內(nèi)存隨著訓(xùn)練一直增加直到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模塊初始化時(shí)定義好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):
        # 開(kāi)始時(shí)刻, 沒(méi)有隱狀態(tài)
        # 關(guān)于維度設(shè)置的詳情,請(qǐng)參考 Pytorch 文檔
        # 各個(gè)維度的含義是 (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    

或者其它模塊每次調(diào)用這個(gè)模塊時(shí),其它模塊的forward()都對(duì)這個(gè)LSTM模塊init_hidden()一下。

如定義一個(gè)模型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

這是因?yàn)椋?/p>

根據(jù) 官方tutorial,在 loss 反向傳播的時(shí)候,pytorch 試圖把 hidden state 也反向傳播,但是在新的一輪 batch 的時(shí)候 hidden state 已經(jīng)被內(nèi)存釋放了,所以需要每個(gè) batch 重新 init (clean out hidden state), 或者 detach,從而切斷反向傳播。

補(bǔ)充:pytorch:在執(zhí)行l(wèi)oss.backward()時(shí)out of memory報(bào)錯(cuò)

在自己編寫SurfNet網(wǎng)絡(luò)的過(guò)程中,出現(xiàn)了這個(gè)問(wèn)題,查閱資料后,將得到的解決方法匯總?cè)缦?/p>

可試用的方法:

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

在訓(xùn)練時(shí),在每一個(gè)step后面加上:

torch.cuda.empty_cache()

在每一個(gè)驗(yàn)證時(shí)的step之后加上代碼:

with torch.no_grad()

不要在循環(huán)訓(xùn)練中累積歷史記錄

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在循環(huán)中進(jìn)行了累計(jì),因?yàn)閘oss是一個(gè)具有autograd歷史的可微變量。你可以通過(guò)編寫total_loss += float(loss)來(lái)解決這個(gè)問(wèn)題。

本人遇到這個(gè)問(wèn)題的原因是,自己構(gòu)建的模型輸入到全連接層中的特征圖拉伸為1維向量時(shí)太大導(dǎo)致的,加入pool層或者其他方法將最后的卷積層輸出的特征圖尺寸減小即可。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論