You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AutoModelForQuestionAnswering加载indobert-base-p1报错ValueError求助

问题根源

indobenchmark/indobert-base-p1 只是完成预训练的基础印尼语BERT模型,没针对问答(QA)任务做过微调,也没有自带QA任务所需的输出层。当你用AutoModelForQuestionAnswering加载它时,transformers框架会自动给模型添加一个QA输出层,但这个自动生成的层和原模型权重不兼容,导致输出的logits维度不符合QA任务预期(本该最后一维为2,对应start和end位置预测,实际不是),因此触发too many values to unpack错误。

而indolem/indobert-base-uncased是已经在QA任务上微调过的模型,自带适配的QA输出层,所以能正常运行代码。

解决办法

有两种可选方案:

  • 方案1:直接换用适配QA任务的印尼语BERT模型,比如你已经验证可用的indolem/indobert-base-uncased,或者其他明确标注支持QA的印尼语预训练模型。
  • 方案2:如果必须使用indobenchmark/indobert-base-p1,需要手动给它添加QA输出层,并用印尼语QA数据集(如IndoQA)微调后再使用。代码框架参考:
from transformers import BertModel, BertPreTrainedModel, AutoTokenizer
import torch.nn as nn

class BertForQA(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.bert = BertModel(config)
        # 添加QA任务所需的输出层,输出维度为2(对应start和end位置)
        self.qa_outputs = nn.Linear(config.hidden_size, 2)
        self.init_weights()

    def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, **kwargs):
        bert_outputs = self.bert(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
        sequence_output = bert_outputs[0]
        logits = self.qa_outputs(sequence_output)
        start_logits, end_logits = logits.split(1, dim=-1)
        start_logits = start_logits.squeeze(-1)
        end_logits = end_logits.squeeze(-1)
        # 返回符合QA模型格式的输出
        return (start_logits, end_logits) + bert_outputs[2:]

# 加载基础模型和tokenizer
model = BertForQA.from_pretrained('indobenchmark/indobert-base-p1')
tokenizer = AutoTokenizer.from_pretrained('indobenchmark/indobert-base-p1')

# 后续需用印尼语QA数据集对模型进行微调,才能用于实际问答预测
额外提示

AutoModelForQuestionAnswering类的设计目标是加载已经完成QA任务微调的模型,不是给基础预训练模型自动补全QA层直接使用的。哪怕框架自动补了层,那也是随机初始化的权重,无法直接用于预测,必须经过QA数据微调才行,且未微调前还可能因维度不兼容出现各种错误。

内容的提问来源于stack exchange,提问作者BlueRey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:15