AttributeError: 'str' object has no attribute 'dim' in pytorch

流过昼夜 提交于 2020-12-12 02:06:59

问题


I got the following error output in the PyTorch when sent model predictions into the model. Does anyone know what's going on?

Following are the architecture model that I created, in the error output, it shows the issue exists in the x = self.fc1(cls_hs) line.

class BERT_Arch(nn.Module):

    def __init__(self, bert):
      
      super(BERT_Arch, self).__init__()

      self.bert = bert 
      
      # dropout layer
      self.dropout = nn.Dropout(0.1)
      
      # relu activation function
      self.relu =  nn.ReLU()

      # dense layer 1
      self.fc1 = nn.Linear(768,512)
      
      # dense layer 2 (Output layer)
      self.fc2 = nn.Linear(512,2)

      #softmax activation function
      self.softmax = nn.LogSoftmax(dim=1)

    #define the forward pass
    def forward(self, sent_id, mask):

      #pass the inputs to the model  
      _, cls_hs = self.bert(sent_id, attention_mask=mask)
      print(mask)
      print(type(mask))
      
      x = self.fc1(cls_hs)

      x = self.relu(x)

      x = self.dropout(x)

      # output layer
      x = self.fc2(x)
      
      # apply softmax activation
      x = self.softmax(x)

      return x
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1686         if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(tens_ops):
   1687             return handle_torch_function(linear, tens_ops, input, weight, bias=bias)
-> 1688     if input == 2 and bias is not None:
   1689         print(input)
   1690         # fused op is marginally faster
AttributeError: 'str' object has no attribute 'dim'

回答1:


Get the reason. It is because of the transformers' version upgrade.. Change my version into the old one fix the issue.




回答2:


If you work with transformers==3.0.0, everything should work fine !

There were some updates in transformers==4.0.0

To get transformers==3.0.0, following command can be used:

!pip install transformers==3.0.0


来源:https://stackoverflow.com/questions/65079318/attributeerror-str-object-has-no-attribute-dim-in-pytorch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!