報錯提示
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument find_unused_parameters=True to torch.nn.parallel.DistributedDataParallel; (2) making sure all forward function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn’t able to locate the output tensors in the return value of your module’s forward function. Please include the loss function and the structure of the return value of forward of your module when reporting this issue (e.g. list, dict, iterable).
問題來源
在原網(wǎng)絡(luò)中新加了一個特征提取的模塊,單卡不報錯,雙卡報上面的錯
排查
出現(xiàn)這個錯最本質(zhì)的原因是有一部分網(wǎng)絡(luò)的參數(shù)無法正常反向傳播。
首先通過在loss.backward()后添加下面代碼,找出是哪一處的參數(shù)梯度為None:
for name, param in model.named_parameters():
if param.grad is None:
print(name, param.grad_fn)
然后發(fā)現(xiàn)確實是我加的那一部分的模塊的參數(shù)有問題,梯度都是None
參考博客
下面的博客給出了一些參考
參考博客1
參考博客2
我的解決思路
由于我加的這一部分是特征提取,不需要在這一步計算loss,而原來后面那一部分的網(wǎng)絡(luò)的反向傳播是沒問題的,所以問題應(yīng)該就是出在我寫的這塊。
排除了一系列l(wèi)oss沒算、初始化沒刪、requires_grad沒開等等一系列問題后,
我認(rèn)為不能反向傳播的原因可能是我把特征提取這一部分的輸出后面加了一系列復(fù)雜的操作(涉及到一些復(fù)雜的維度變換),
然后才傳到下一個網(wǎng)絡(luò)中去,導(dǎo)致有些操作無法正確的追溯(比如for循環(huán)、scatter操作以及一些其他復(fù)雜的操作函數(shù))。
接著我把所有的for循環(huán)刪除,把直接計算的池化部分改為通過AvgPool2d()實現(xiàn),就可以正常反向傳播了!
所以出現(xiàn)了這個問題,且你對代碼做了魔改的基礎(chǔ)上,可以檢查一下自己有沒有在輸出的特征向量上做一些復(fù)雜的操作,盡量把這些操作簡化,同時也要注意盡量不要初始化一個新的tensor(這種中間變量的梯度也是沒有的),沒準(zhǔn)就能行得通!文章來源:http://www.zghlxwxcb.cn/news/detail-667568.html
大半夜終于解決了困擾了好幾天的bug,共勉!?。?/em>文章來源地址http://www.zghlxwxcb.cn/news/detail-667568.html
到了這里,關(guān)于網(wǎng)絡(luò)梯度為None、參數(shù)不更新解決思路(又名“魔改代碼的報應(yīng)”)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!