Pytorch 修改解压张量时出​​错

PPh*_*Pho 3 python pytorch tensor

修改解包张量时出现错误。

import torch
a1, a2 = torch.tensor([1,2], dtype = torch.float64)
b = torch.rand(2, requires_grad = True)

a1 += b.sum()
Run Code Online (Sandbox Code Playgroud)

此代码产生以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

但是,当我分别创建 a1 和 a2 时,没有收到该错误,如下所示:

a1 = torch.tensor([1], dtype = torch.float64)
a1 += b.sum()
Run Code Online (Sandbox Code Playgroud)

我不知道为什么解包张量会导致该错误。任何帮助是极大的赞赏

Ham*_*zah 5

错误消息很清楚并解释说:

  • 您在 中创建了两个视图 a1 和 a2 ,no_grad mode并在 中创建了视图 b grad mode enabled

  • 此类函数(解包)不允许就地修改输出视图 (a1,a2)(就地操作 +=)

  • 解决方案:您应该将 inplace 操作替换为 out-of-place 操作。您可以克隆a1到此a操作之前,如下所示:

    a = a1.clone()
    a += b.sum()
    
    Run Code Online (Sandbox Code Playgroud)

这是因为 tensor.clone() 使用字段创建原始张量的副本requires_grad。因此,您会发现 nowab拥有requires_grad。如果您打印

print(a.requires_grad)        #True
print(b.requires_grad)        #True
print(a1.requires_grad)       #False
Run Code Online (Sandbox Code Playgroud)

您可以阅读有关就地操作的更多信息1 2