RuntimeError: CUDA out of memory. Tried to allocate 30.00 MiB

問題

GPU跑模型報錯

RuntimeError: CUDA out of memory. Tried to allocate 38.00 MiB (GPU 0; 10.76 GiB total capacity; 9.71 GiB already allocated; 5.56 MiB free; 9.82 GiB reserved in total by PyTorch)

分析

應該有三個原因

  • GPU還有其他進程佔用顯存,導致本進程無法分配到足夠的顯存

  • 緩存過多,使用torch.cuda.empty_cache()清理緩存

  • 卡不行,換塊顯存更大的卡吧

解決

解決方法總述

1.最直接的解決辦法是減小batch_size(常用),或者減小模型參數和輸入大小(一般很少這樣做);

2.如果測試過程遇到這種情況,加上
with torch.no_grad():
內存就不會分配參數梯度的空間

3.如果在訓練過程遇到這種情況,可以嘗試在訓練前先釋放CUDA內存
nvidia-smi查看GPU使用率,如果使用率不高,就使用torch.cuda.empty_cache()釋放內存
官網對於torch.cuda.empty_cache()的說明:
Releases all unoccupied cached memory currently held by the caching allocator so that those can be used in other GPU application and visible in nvidia-smi.
釋放當前由緩存分配器保留的所有未佔用的緩存內存,以便這些內存可在其他GPU應用程序中使用,並在nvidia-smi中可見 。該語句是釋放沒有被使用的緩存,所以可以放心大膽地使用.

版權聲明:本文爲CSDN博主「Jumi愛笑笑」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_39326879/article/details/106137586

方式二:測試代碼不進行梯度傳播

將測試代碼放到以下的位置

with torch.no_grad():
    (your test code)

測試時報錯 RuntimeError: CUDA out of memory._python_齊天大勝-CSDN博客
https://blog.csdn.net/qq_34475584/article/details/103616674

方式3:緩存過多,使用torch.cuda.empty_cache()清理緩存

Pytorch—訓練與測試時爆顯存(out of memory)的一個解決方案(torch.cuda.empty_cache())_python_zxyhhjs2017的博客-CSDN博客
https://blog.csdn.net/zxyhhjs2017/article/details/92795831

  • 參考文獻
    2020-03-19 RuntimeError: CUDA out of memory. Tried to allocate 38.00 MiB (GPU 0; 10.76 GiB total … – Python量化投資
    https://www.lizenghai.com/archives/56659.html

如何解決RuntimeError: CUDA error: out of memory?_python_weixin_43509263的博客-CSDN博客
https://blog.csdn.net/weixin_43509263/article/details/103841657

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章