“运行时错误:需要 grad 的叶变量的视图正在就地操作中使用”,而实际上没有就地操作

esh*_*390 5 python pytorch

我正在做一些纸质复制工作,但遇到了麻烦。

根据日志,它说RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.但是,当我检查错误所指的行时,它只是类内的一个简单的属性设置器:

@pdfvec.setter
def pdfvec(self, value):
   self.param.pdfvec[self.key] = value   # where the error message is referring to 
Run Code Online (Sandbox Code Playgroud)

就地操作不是类似的东西+=*=?我不明白为什么此错误消息出现在这一行中。

我对这条消息真的很困惑,如果有人知道这种情况发生的任何可能原因,我会很高兴。

有关更多信息,这是调用 setter 函数的部分:

def _update_params(params, pdfvecs):
    idx = 0
    for param in params:
        totdim = param.stats.numel()
        shape = param.stats.shape
        param.pdfvec = pdfvecs[idx: idx + totdim].reshape(shape)   # where the setter function was called
        idx += totdim
Run Code Online (Sandbox Code Playgroud)

我知道这仍然缺乏解决问题的信息,但如果您知道出现错误消息的任何可能性,我会很高兴听到。

lar*_*mbr 8

就地操作意味着您所做的分配正在修改张量的底层存储,requires_grad根据您的错误消息,该存储被设置为 True。

也就是说,你的param.pdfvec[self.key]张量不是叶子张量,因为它们将在反向传播期间更新。并且你试图给它赋值,这会干扰 autograd,所以默认情况下禁止此操作。您可以通过直接修改其底层存储(fe,with .data)来做到这一点。