PyTorch錯誤解決實戰:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [6, 1]], which is output 0 of TBackward, is at version 4; expected version 3 instead.
最近使用BalancedMetaSoftmax — Classification針對Imbalanced Datasets進行模型訓練的時候遇到的問題。使用作者提出之BALMS方法時,一直出現該項錯誤。
1. Segmentation fault (core dumped)
首先是出現Core dumped的問題,這個Segmentation fault (core dumped)其實最後檢查出來發現與軟體可能無關,而是aiForge中GPU的壞掉產生的錯誤,我檢查了第0、1、2、3顆GPU。分析哪一顆GPU在PyTorch產生Tensor時會遇到錯誤
#一次分析一顆GPU,從0、1、2、依序到3
CUDA_VISIBLE_DEVICES=0 pythonimport torch;torch.cuda.current_device()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.rand(10).to(device)# 結果發現第3顆GPU會出現Segmentation fault (core dumped),因此不使用第3顆
除此之外我也找了其他高手的文章,發現有個叫做gdb的套件能夠進行Segmentation fault追蹤
https://github.com/pytorch/pytorch/issues/926#issuecomment-284239111sudo apt update
sudo apt install gdb
gdb python
r main.py --cfg ./config/Phison/feat_uniform_resnet18.yaml
where
2. 官方指定用1.4版本的PyTorch,我卻使用1.7.1版本訓練
導致了主要錯誤產生:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [6, 1]], which is output 0 of TBackward, is at version 4; expected version 3 instead.
根據GitHub上的Issue:
發現真的是因為版本不同所致,解決方法就是安裝版本1.4的PyTorch,或是在balms_XXXX.yaml中,將num_workers設定成0
舊版本的PyTorch基本上沒任何問題,但是num_workers設定成0後,訓練速度會變得非常的慢,建議以舊版PyTorch方法為主
pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://download.pytorch.org/whl/torch_stable.htmlpip install higher==0.2.1
簡書上也有一篇是關於跟本文類似錯誤的文章
節錄自113. 【torch】反向传播弃inplace操作1)torch版本降为0.3.0(不成功)2)在inplace为True的时候,将其改为Flase,如drop()3)去掉所有的inplace操作4)换掉”-=”“+=”之类的操作,且用b=a代替a = a
a -=c
==>
b = a.clone() # tensor复制方式
a = b — c
避免a.operate(**)不赋值的情况等等作者:十里江城
链接:https://www.jianshu.com/p/9fb0e354c278
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。