TypeError:无法将“torch.cuda.FloatTensor”分配为参数“weight_hh_l0”(torch.nn.Parameter或无预期)

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

我正在尝试训练此存储库中实现的模型https://bitbucket.org/VioletPeng/language-model/src/master/(第二个模型:标题到标题-故事情节到故事模型)

第一个时期的训练会顺利进行,但是一旦它尝试调用训练函数来开始第二个时期,一切都会中断,我会收到以下错误:

TypeError: cannot assign 'torch.cuda.FloatTensor' as parameter 'weight_hh_l0' (torch.nn.Parameter or None expected)

我不知道问题是什么,我尝试查找此错误并尝试将 .cuda 更改为 .to(device) 并在可能的情况下在张量初始化中使用 device= 。

但是这些似乎都没有起到任何作用。

下面是完整的异常堆栈跟踪:

  File "pytorch_src/main.py", line 253, in <module>
    train()
  File "pytorch_src/main.py", line 209, in train
    output, hidden, rnn_hs, dropped_rnn_hs = model(data, hidden, return_h=True)
  File "/home/e/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/e/Documents/Amal/language-model/pytorch_src/model.py", line 81, in forward
    raw_output, new_h = rnn(raw_output, hidden[l])
  File "/home/e/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/e/Documents/Amal/language-model/pytorch_src/weight_drop.py", line 47, in forward
    self._setweights()
  File "/home/e/Documents/Amal/language-model/pytorch_src/weight_drop.py", line 44, in _setweights
    setattr(self.module, name_w, w)
  File "/home/e/anaconda3/lib/python3.7/site-packages/torch/nn/modules/rnn.py", line 108, in __setattr__
    super(RNNBase, self).__setattr__(attr, value)
  File "/home/e/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 801, in __setattr__
    .format(torch.typename(value), name))
pytorch
3个回答
0
投票

我将 python 降级到 3.6 并重新安装了所有要求,它起作用了。

所以问题可能是火炬版本不兼容。


0
投票

较新版本的 PyTorch 需要参数为 torch.nn.Parameter。 我认为您需要按如下方式更改代码,至少它帮助我解决了基于相同代码库的代码中的相同错误:

def _setweights(self):
    for name_w in self.weights:
        raw_w = getattr(self.module, name_w + '_raw')
        w = None
        w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training)
        setattr(self.module, name_w, torch.nn.Parameter(w))

0
投票

我相信问题可能是在新的 pytorch 版本中的典型运行过程中自动删除

w
的问题,但是,在使用其他一些模型调用时,例如使用 torchinfo 进行可视化期间(可能是优化器或向后调用在做什么? )。因此,有时仍然分配权重,并且 setattr 尝试用函数覆盖参数,但它不喜欢这样做。

对我来说有效的是:

for name_w in weights:
    raw_w = getattr(module, name_w + "_raw")
    if name_w in module._parameters.keys():
        del module._parameters[name_w]
    w = torch.nn.functional.dropout(raw_w, p=dropout,training=module.training)
    setattr(module, name_w, w)
© www.soinside.com 2019 - 2024. All rights reserved.