Pytorch-RuntimeError:试图第二次反向遍历图形,但缓冲区已被释放

2024-10-01 19:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直遇到这个错误:

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.

我在Pythorch论坛搜索过,但仍然无法找出我在自定义丢失功能中做错了什么。我的模型是nn.GRU,下面是我的自定义损失函数:

def _loss(outputs, session, items):  # `items` is a dict() contains embedding of all items
    def f(output, target):
        pos = torch.from_numpy(np.array([items[target["click"]]])).float()
        neg = torch.from_numpy(np.array([items[idx] for idx in target["suggest_list"] if idx != target["click"]])).float()
        if USE_CUDA:
            pos, neg = pos.cuda(), neg.cuda()
        pos, neg = Variable(pos), Variable(neg)

        pos = F.cosine_similarity(output, pos)
        if neg.size()[0] == 0:
            return torch.mean(F.logsigmoid(pos))
        neg = F.cosine_similarity(output.expand_as(neg), neg)

        return torch.mean(F.logsigmoid(pos - neg))

    loss = map(f, outputs, session)
return -torch.mean(torch.cat(loss))

培训代码:

    # zero the parameter gradients
    model.zero_grad()

    # forward + backward + optimize
    outputs, hidden = model(inputs, hidden)
    loss = _loss(outputs, session, items)
    acc_loss += loss.data[0]

    loss.backward()
    # Add parameters' gradients to their values, multiplied by learning rate
    for p in model.parameters():
        p.data.add_(-learning_rate, p.grad.data)

Tags: thepostargetoutputreturnifsessionitems
1条回答
网友
1楼 · 发布于 2024-10-01 19:17:05

问题来自我的训练循环:它不会在批处理之间分离或重新打包隐藏状态?如果是这样,则loss.backward()尝试一直反向传播到时间的开始,这对第一批有效,但对第二批无效,因为第一批的图形已被丢弃。

有两种可能的解决方案。

1)在批之间分离/重新打包隐藏状态。有(在 至少)三种方法(我选择了这个解决方案):

 hidden.detach_()
 hidden = hidden.detach()

2)将loss.backward()替换为loss.backward(retain_graph=True),但要知道,每个连续批处理将比前一批处理花费更多的时间,因为它必须一直反向传播到第一批处理的开始。

Example

相关问题 更多 >

    热门问题