【PyTorch】常見錯誤
錯誤:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation.
問題原因:
pytorch版本導致的,0.3.0版本不會報錯,0.4.0就報錯;由於後者版本將Variable和Tensor合併爲Tensor,但是inplace操作對Tensor不能用,因此報錯。
解決方法:
查閱網上資料,可執行方案有以下幾點:
- 找到網絡模型中的 inplace 操作,將
inplace=True
改成inplace=False
; - 將網絡結構中的
+=
操作進行修改,如下所示:
out = out + res # not inplace
out += res # inplace
若網絡結構很大,那就需要慢慢調試,加一句out.backward(),觀察是否報錯,若沒有,則之前沒錯。