Home Articles

PyTorch:RuntimeError:变量元组的元素0是易失性的

Asked
Viewed 1774 times
1

我正在PyTorch 0.3.1中训练基于LSTM的模型 .

我的问题是,在提高学习率后,我总是得到一个 RuntimeError 说: element 0 of variables tuple is volatile .

这不是在开始时发生的,而是在经过一些训练后,如在第3,第4,第5纪......等 .

在查看此错误时,我发现this Question on Stackoverflow建议使用 zero_grad() . 但是当错误发生时,这已经被使用了 .

所以我的问题是:

  • 变量的元素是不稳定的是什么意思?

  • 变量元素获取"volatile"的可能原因是什么?

  • 有没有办法测试哪个变量包含volatile元素,以便我可以回溯问题?

非常感谢您的任何帮助!

这是我正在使用的训练步骤的代码:

for epoch in range(num_epochs):
    states = (Var(torch.zeros(num_layers, batch_size, hidden_size)), 
              Var(torch.zeros(num_layers, batch_size, hidden_size)))
    new_batch = True
    step = 0
    epoch_loss = []
    print('Epoch: ', epoch+1)
    for i in range(0, token_ids.size(1) - seq_length, seq_length):
        #print(i)
        input_sequence = Var(token_ids[:,i:i+seq_length])
        target_sequence = Var(token_ids[:,(i+1):(i+1)+seq_length])
        entity_target_sequence = Var(entety_targets[:,(i+1):(i+1)+seq_length]).contiguous()

        if int(input_sequence )== 0:
            states = (Var(torch.zeros(num_layers, batch_size, hidden_size)), 
                      Var(torch.zeros(num_layers, batch_size, hidden_size)))
            print('New Document')
        model.zero_grad()
        states = detach(states)
        out, states, z = model(input_sequence, states)

        if new_batch:
            loss = loss_func(out, target_sequence.view(-1)) + bce_loss(z, entity_target_sequence)
            new_batch = False
        else:
            loss += loss_func(out, target_sequence.view(-1)) + bce_loss(z, entity_target_sequence)
        if (i+1) % wbatch_size == 0:
            step += 1 // seq_length
            if step % 10 == 0:
                epoch_loss.append((loss.data[0]/wbatch_size))
                print ('Epoch [%d/%d], Step[%d/%d], Loss: %.3f' % (epoch+1, num_epochs, step, num_wbatches, (loss.data[0]/wbatch_size)))
                sys.stdout.flush()

            loss.backward(retain_graph=True)
            torch.nn.utils.clip_grad_norm(model.parameters(), 0.5)
            optimizer.step()
            new_batch = True

(我遗漏了模型本身,以避免在这里使用代码墙并保持可读性,但如果这有助于解决问题,我当然可以添加代码 . )

追溯:

Traceback (most recent call last):
  File "ent_lm.py", line 223, in <module>
    loss.backward(retain_graph=True)
  File "/usr/local/lib/python3.6/site-packages/torch/autograd/variable.py", line 167, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph, retain_variables)
  File "/usr/local/lib/python3.6/site-packages/torch/autograd/__init__.py", line 99, in backward
    variables, grad_variables, retain_graph)

1 Answer

  • 0

    你提供的代码似乎没问题 .

    在以下两个函数之一中似乎发生错误 .

    states = detach(states)
    out, states, z = model(input_sequence, states)
    

    我认为部分原因可能是您需要“保留图形”,但是当您分离状态或在模型中执行其他操作时,您会继续重置图形 .

Related