修改解压张量时出现Pytorch错误

问题描述 投票:0回答:1

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

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()

我不知道为什么解包张量会导致该错误。非常感谢任何帮助

python pytorch tensor
1个回答
5
投票

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

  • 您在

    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

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

© www.soinside.com 2019 - 2024. All rights reserved.