You need to enable JavaScript to run this app. LIT加载自预训练NER BERT模型时权重未正确初始化致预测失败问题
优惠活动
大模型
产品
解决方案
定价
更多

LIT加载自预训练NER BERT模型时权重未正确初始化致预测失败问题

场景说明

正在使用Language Interpretability Toolkit(LIT) 加载并分析在自定义NER任务上自预训练的BERT模型。

遇到的异常
  • 启动报错:向LIT脚本传入预训练模型路径时,系统提示权重未正确初始化,日志输出如下:
modeling_utils.py:648] loading weights file bert_remote/examples/token-classification/Data/Models/results_21_03_04_cleaned_annotations/04.03._8_16_5e-5_cleaned_annotations/04-03-2021 (15.22.23)/pytorch_model.bin
modeling_utils.py:739] Weights of BertForTokenClassification not initialized from pretrained model: ['bert.pooler.dense.weight', 'bert.pooler.dense.bias']
modeling_utils.py:745] Weights from pretrained model not used in BertForTokenClassification: ['bert.embeddings.position_ids']
  • 流程异常:脚本启动时自动调用bert-base-german-cased版本的BERT,该模型未适配自定义标签集,无法正常输出预测结果。
  • 排查进展:目前怀疑问题和PyTorch相关,但暂未定位到错误根因。
排查相关代码片段

数据集加载代码

基于CoNLL 2003格式编写,修改自官方数据加载脚本,核心实现如下:

def __init__(self):

    # Read ConLL Test Files

    self._examples = []

    data_path = "lit_remote/lit_nlp/examples/datasets/NER_Data"
    with open(os.path.join(data_path, "test.txt"), "r", encoding="utf-8") as f:
        lines = f.readlines()

    for line in lines[:2000]:
        if line != "\n":
            token, label = line.split(" ")
            self._examples.append({
                'token': token,
                'label': label,
            })
        else:
            self._examples.append({
                'token': "\n",
                'label': "O"
            })

    def spec(self):
        return {
            'token': lit_types.Tokens(),
            'label': lit_types.SequenceTags(align="token"),
        }

模型初始化与LIT服务启动代码

修改自官方simple_pytorch_demo.py示例脚本,核心实现如下:

def __init__(self, model_name_or_path):
    self.tokenizer = transformers.AutoTokenizer.from_pretrained(
        model_name_or_path)
    model_config = transformers.AutoConfig.from_pretrained(
        model_name_or_path,
        num_labels=15,  # 自定义标签数
        output_hidden_states=True,
        output_attentions=True,
    )
    # 常规PyTorch模型初始化
    self.model = _from_pretrained(
        transformers.AutoModelForTokenClassification,
        model_name_or_path,
        config=model_config)
    self.model.eval()

## 中间省略部分自定义逻辑代码

def input_spec(self) -> lit_types.Spec:
    return {
        "token": lit_types.Tokens(),
        "label": lit_types.SequenceTags(align="token")
    }

def output_spec(self) -> lit_types.Spec:
    return {
        "tokens": lit_types.Tokens(),
        "probas": lit_types.MulticlassPreds(parent="label", vocab=self.LABELS),
        "cls_emb": lit_types.Embeddings()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 16:36:04