解決Pytorch 訓練與測試時爆顯存(out of memory)的問題
更新時間:2019年08月20日 13:45:37 作者:xiaoxifei
今天小編就為大家分享一篇解決Pytorch 訓練與測試時爆顯存(out of memory)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
Pytorch 訓練時有時候會因為加載的東西過多而爆顯存,有些時候這種情況還可以使用cuda的清理技術進行修整,當然如果模型實在太大,那也沒辦法。
使用torch.cuda.empty_cache()刪除一些不需要的變量代碼示例如下:
try: output = model(input) except RuntimeError as exception: if "out of memory" in str(exception): print("WARNING: out of memory") if hasattr(torch.cuda, 'empty_cache'): torch.cuda.empty_cache() else: raise exception
測試的時候爆顯存有可能是忘記設置no_grad, 示例代碼如下:
with torch.no_grad(): for ii,(inputs,filelist) in tqdm(enumerate(test_loader), desc='predict'): if opt.use_gpu: inputs = inputs.cuda() if len(inputs.shape) < 4: inputs = inputs.unsqueeze(1) else: if len(inputs.shape) < 4: inputs = torch.transpose(inputs, 1, 2) inputs = inputs.unsqueeze(1)
以上這篇解決Pytorch 訓練與測試時爆顯存(out of memory)的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。