如何将微调后BERT模型的输出输入至另一微调BERT?遇报错求助
问题根源
你遇到的错误是因为encoder_hidden_states并不是单独BERT模型(encoder-only架构)forward方法的有效参数。这个参数主要用于seq2seq类模型(比如T5)中,给解码器传递编码器的隐藏状态,而不是用来替代BERT自身的输入嵌入。
你想要把词性标注模型输出的隐藏状态直接传入情感分析模型的BERT,正确的做法是使用inputs_embeds参数——这个参数专门用来接收预计算的嵌入张量(形状为(batch_size, sequence_length, hidden_size)),正好匹配你从PosTagModel得到的输出形状。
修改后的代码
首先修正SentimentModel的forward方法:
class SentimentModel(nn.Module): def __init__(self,): super(SentimentModel, self).__init__() self.bert_layer = BertModel.from_pretrained('bertModel/') self.cls_layer = nn.Linear(768, 1) def forward(self, input_embeds, attn_masks): # 替换encoder_hidden_states为inputs_embeds cont_reps, _ = self.bert_layer(inputs_embeds=input_embeds, attention_mask=attn_masks) cls_rep = cont_reps[:, 0] return cls_rep
同时可以优化DeepSequentialModel的参数命名,提升代码可读性:
class DeepSequentialModel(nn.Module): def __init__(self, sentiment_model_file, postag_model_file, device): super(DeepSequentialModel, self).__init__() self.sentiment_model = SentimentModel().to(device) self.sentiment_model.load_state_dict(torch.load(sentiment_model_file, map_location=device)) self.postag_model = PosTagModel().to(device) self.postag_model.load_state_dict(torch.load(postag_model_file, map_location=device)) self.classificationLayer = nn.Linear(768, 1) def forward(self, seq, attn_masks): postag_hidden_states = self.postag_model(seq, attn_masks) sent_context = self.sentiment_model(postag_hidden_states, attn_masks) logits = self.classificationLayer(sent_context) return logits
额外注意事项
如果你的transformers库版本过于老旧,可能会缺少inputs_embeds参数支持,建议升级到最新稳定版:
pip install --upgrade transformers
内容的提问来源于stack exchange,提问作者Erfan
相关产品推荐
相关产品推荐

