gpt4 book ai didi

python - Pytorch梯度还没有计算

转载 作者:行者123 更新时间:2023-11-28 17:57:19 26 4
gpt4 key购买 nike

我创建了一个神经网络。我在重新计算梯度时遇到问题。问题是我将 2 个张量 u @ v 标量相乘并对其中一个进行归一化。重要的是不能为 h 计算梯度。因此,我使用 detach()。此外,在重新计算梯度时,不应考虑归一化(我不知道该怎么做)。

import torch
from torch import nn


class Nn(nn.Module):
def __init__(self):
super(Nn, self).__init__()
self.ln = nn.Linear(5, 5)

def forward(self, x):
v = self.ln(x)

u = v.clone()
h = v.clone()

u /= u.norm()
h = h.detach()
h /= h.norm()

res = torch.stack([torch.stack([u @ h, u @ h])])

return res


def patches_generator():
while True:
decoder = torch.rand((5, ))
target = torch.randint(2, (1,))
yield decoder, target


net = Nn()

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters())

net.train()
torch.autograd.set_detect_anomaly(True)
for decoder, targets in patches_generator():
optimizer.zero_grad()
outputs = net(decoder)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()

结果,我收到以下错误:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [9, 512, 1, 1]], which is output 0 of ReluBackward1, is at version 3; expected version 2 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

最佳答案

问题是在这一行中应用于 u 的就地除法运算符:

u /= u.norm()

将其更改为

u = u / u.norm()

使代码运行。原因是就地运算符覆盖了这一行的中间结果

u = v.clone()

这使得 Pytorch 无法计算梯度。

(问题中的错误消息包含对 ReluBackward1 层的引用,它不在简化的代码示例中。Pytorch ReLU 层有一个可选的 in_place 参数,它在支持反向传播的同时进行适当的操作。这通常有效,因为在顺序网络中,不需要区分 ReLU 激活的输出和权重的输出来计算梯度,但在更复杂的架构中,它可能是保留权重输出所必需的。)

关于python - Pytorch梯度还没有计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57551783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com