【问题标题】:How to change max sequence length for transformers.bert?如何更改transformers.bert的最大序列长度?
【发布时间】:2020-10-23 11:59:44
【问题描述】:

我下载了基于 bert 的预训练模型。我编辑 config.json(从 512 到 256)

 "max_position_embeddings": 256,

那我想用bert模型,

from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained(
    MODEL_PATH, 
    num_labels = 2, # The number of output labels--2 for binary classification.       
    output_attentions = False, 
    output_hidden_states = False, 
)
# Tell pytorch to run this model on the GPU.
model.cuda()

但它会引发错误

Error(s) in loading state_dict for BertForSequenceClassification:
    size mismatch for bert.embeddings.position_embeddings.weight: copying a param with shape torch.Size([512, 768]) from checkpoint, the shape in current model is torch.Size([256, 768]).

我知道原因是因为我更改了最大序列长度。如果我想更改最大序列长度,正确的方法是什么?

【问题讨论】:

    标签: pytorch transform bert-language-model


    【解决方案1】:

    错误表示由于层的形状不同,无法将保存的权重加载到初始化模型中。 如果您想在后续任务中微调模型,则不能更改预训练模型配置。相反,您应该在encode_plus 函数中设置 max_length,这会将输入序列截断为 max_length。 但是,如果您想使用特定配置预训练模型,您应该初始化没有权重的模型,或者可以在 huggingface 存储库中找到合适的权重。

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多