RuntimeError: Output 0 of UnbindBackward is a view and is being modified inplace.
程序员文章站
2022-06-15 18:44:32
...
1.问题描述
运行如下代码:
for logit in logits:
indices_to_remove = logit < torch.topk(logit, top_k)[0][..., -1, None] # ...表示其他维度由计算机自行推断
logit[indices_to_remove] = filter_value # 对于topk之外的其他元素的logits值设为负无穷
报错:
RuntimeError: Output 0 of UnbindBackward is a view and is being 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.
解释:
UnbindBackward的输出1是一个视图,它的基视图的另一个视图已经被修改了。该视图返回多个视图的函数的输出。不允许就地修改输出视图。应该用一个其它变量来替代当前变量,来完成修改操作。
在for循环运行的过程中,logits中的元素会被修改,然而下一轮循环还会读取logits并修改,此时Python会迷惑:是操作原始的logits还是在第一轮修改后的logits?
2.解决
不要用这种遍历方式,改为索引的方式,这样等于引入了一个新的变量,避免了原地修改:
for i in range(logits.size(0)): # logits.size(0)来获取logits的元素个数
logit = logits[i]
indices_to_remove = logit < torch.topk(logit, top_k)[0][..., -1, None]
logit[indices_to_remove] = filter_value
上一篇: 笨办法09打印,打印,打印
下一篇: java连接带密码的mongodb集群
推荐阅读
-
RuntimeError: Output 0 of UnbindBackward is a view and is being modified inplace.
-
runtimeerror: output 0 of unbindbackward is a view and is being modified inplace.
-
RuntimeError: Output 0 of SelectBackward is a view and is being modified inplace.
-
RuntimeError: Output 0 of UnbindBackward is a view and is being modified inplace.