DeBERTa模型导出ONNX时token_type_ids参数报错求助
问题分析
错误提示Invalid Feed Input Name:token_type_ids,核心原因是DeBERTaV2模型结构默认不需要token_type_ids输入,但代码运行时自动传入了该参数,而导出的ONNX模型并未包含这个输入节点,导致ONNX Runtime报错。BERT类模型依赖token_type_ids做句对区分,因此不会出现该问题。
解决方案
方案1:手动导出ONNX模型(推荐)
跳过from_pretrained(export=True)的自动导出流程,手动控制导出时的输入参数,确保只保留模型需要的输入:
from transformers import AutoTokenizer, AutoModelForTokenClassification from optimum.onnxruntime import ORTModelForTokenClassification from optimum.exporters.onnx import export # 加载微调后的模型和tokenizer tokenizer = AutoTokenizer.from_pretrained("{custom_fine_tuned_NER_DeBERTaV2}", use_auth_token=True) model = AutoModelForTokenClassification.from_pretrained("{custom_fine_tuned_NER_DeBERTaV2}", use_auth_token=True) # 手动导出ONNX模型,仅保留必要输入 export( model=model, tokenizer=tokenizer, output="./deberta_ner_onnx", task="token-classification", input_shapes={"input_ids": [1, 128], "attention_mask": [1, 128]} ) # 加载手动导出的ONNX模型并运行 ort_model = ORTModelForTokenClassification.from_pretrained("./deberta_ner_onnx") pipe = pipeline("ner", model=ort_model, tokenizer=tokenizer) pipe("MY TEXT GOES HERE")
方案2:修改Pipeline预处理逻辑
自定义预处理函数,在传入模型前移除token_type_ids参数:
from transformers import AutoTokenizer, pipeline from optimum.onnxruntime import ORTModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("{custom_fine_tuned_NER_DeBERTaV2}", use_auth_token=True) model = ORTModelForTokenClassification.from_pretrained("{custom_fine_tuned_NER_DeBERTaV2}", export=True, use_auth_token=True) # 自定义预处理,删除token_type_ids def custom_preprocess(inputs, **kwargs): processed = tokenizer(inputs, return_tensors="pt", **kwargs) processed.pop("token_type_ids", None) return processed # 创建Pipeline时指定自定义预处理 pipe = pipeline( "ner", model=model, tokenizer=tokenizer, preprocess_function=custom_preprocess ) pipe("MY TEXT GOES HERE")
方案3:升级依赖版本
你使用的optimum 1.7.3版本较早,对DeBERTaV2的ONNX支持存在兼容问题。升级到最新稳定版后重新尝试原代码:
pip install --upgrade optimum onnxruntime
内容的提问来源于stack exchange,提问作者SRC
相关产品推荐
相关产品推荐

