RuntimeError: Output 1 of UnbindBackward is a view and its base or another view of its
项目场景
项目场景:运行项目文件 - train.py
文件时报错。
项目地址:https://github.com/RayneSun/VTPLSTM
问题描述
运行项目文件 - train.py
文件时报错:
RuntimeError: Output 1 of UnbindBackward is a view and its base or another view of its base has been modified inplace. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one.
train.py
文件报错代码区间:
for index, num in enumerate(loss):
loss[index] = num * max(1 / (index + 1), 0.2) # [1,1/2,1/3,1/4,1/5,1/5,...]
原因分析
错误提示:UnbindBackward
的输出1
是一个视图,它的基视图的另一个视图已经被修改了。该视图返回多个视图的函数的输出。不允许就地修改输出视图。应该用一个其它变量来替代当前变量,来完成修改操作。
在for
循环运行的过程中,num
中的元素会被修改,然而在下一轮循环中还会读取num
的值并修改,此时Python
会迷惑:是操作原始的num
值还是在第一轮修改后的num
值。
解决方案
代码不使用遍历方式,改为索引的方式,相当于引入了一个新的变量,避免了原地修改的错误。
for index, num in enumerate(loss):
# 修改: 添加下面的这一条语句。
num = loss[index]
loss[index] = num * max(1 / (index + 1), 0.2) # [1,1/2,1/3,1/4,1/5,1/5,...]