【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(),观察是否报错,若没有,则之前没错。
本文详细解析了PyTorch中常见的inplace操作错误,包括错误原因、影响的版本及解决方法。针对0.4.0及以上版本,提供了解决inplace操作问题的具体步骤,帮助读者理解和修复代码。
5159





