修改解包张量时出现错误。
import torch
a1, a2 = torch.tensor([1,2], dtype = torch.float64)
b = torch.rand(2, requires_grad = True)
a1 += b.sum()
此代码会产生以下错误:
RuntimeError: A view was created in no_grad mode and is being modified inplace with grad mode enabled. 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.
但是,当我分别创建a1和a2时,我没有收到该错误,如下所示:
a1 = torch.tensor([1], dtype = torch.float64)
a1 += b.sum()
我不知道为什么解包张量会导致该错误。非常感谢任何帮助
错误消息很清楚并解释说:
您在
no_grad mode
中创建了两个视图 a1 和 a2,并在 grad mode enabled
中创建了视图 b。
此类函数(解包)不允许就地修改输出视图(a1,a2)(就地操作+=)
解决方案:您应该将就地操作替换为异地操作。您可以在此操作之前将
a1
克隆到 a
,如下所示:
a = a1.clone()
a += b.sum()
这是因为tensor.clone() 使用
requires_grad
字段创建原始张量的副本。因此,您现在会发现a
和b
有requires_grad
。如果您打印
print(a.requires_grad) #True
print(b.requires_grad) #True
print(a1.requires_grad) #False