onnx报错解决-bert

一、定义

UserWarning: Provided key output for dynamic axes is not a valid input/output name warnings.warn(

案例

实体识别bert 案例

转transformers 模型到onnx 接口解读

二、实现

https://huggingface.co/docs/transformers/main_classes/onnx#transformers.onnx.FeaturesManager

UserWarning: Provided key output for dynamic axes is not a valid input/output name warnings.warn(

代码:

python 复制代码
with torch.no_grad():
    symbolic_names = {0: 'batch_size', 1: 'max_seq_len'}
    torch.onnx.export(model,
                      (inputs["input_ids"], inputs["token_type_ids"], inputs["attention_mask"]),
                      "./saves/bertclassify.onnx",
                      opset_version=14,
                      input_names=["input_ids", "token_type_ids", "attention_mask"],        
                       output_names=["logits"],                                             
                      dynamic_axes =    {'input_ids': symbolic_names,
                                        'attention_mask': symbolic_names,
                                        'token_type_ids': symbolic_names,
                                        'logits': symbolic_names
                                         }
                      )

改正后:原因: input_names 名字顺序与模型定义不一致导致。为了避免错误产生,应该标准化。如下2所示。

python 复制代码
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path)
model.eval()
onnx_config = FeaturesManager._SUPPORTED_MODEL_TYPE['bert']['sequence-classification']("./saves")
dummy_inputs = onnx_config.generate_dummy_inputs(tokenizer, framework='pt')
from itertools import chain
with torch.no_grad():
    symbolic_names = {0: 'batch_size', 1: 'max_seq_len'}
    torch.onnx.export(model,
                      (inputs["input_ids"],inputs["attention_mask"], inputs["token_type_ids"]),
                      "./saves/bertclassify.onnx",
                      opset_version=14,
                      input_names=["input_ids", "attention_mask", "token_type_ids"],      
                       output_names=["logits"],                                            
                      dynamic_axes =    {
        name: axes for name, axes in chain(onnx_config.inputs.items(), onnx_config.outputs.items())
    }
)
# #验证是否成功
import onnx
onnx_model=onnx.load("./saves/bertclassify.onnx")
onnx.checker.check_model(onnx_model)
print("无报错,转换成功")

# #推理
import onnxruntime
ort_session=onnxruntime.InferenceSession("./saves/bertclassify.onnx", providers=['CPUExecutionProvider'])    #加载模型
ort_input={"input_ids":inputs["input_ids"].cpu().numpy(),"token_type_ids":inputs["token_type_ids"].cpu().numpy(),
           "attention_mask":inputs["attention_mask"].cpu().numpy()}
output_on = ort_session.run(["logits"], ort_input)[0]   #推理


print(output_org.detach().numpy())
print(output_on)
assert np.allclose(output_org.detach().numpy(), output_on, 10-5)  #无报错

标准化:

python 复制代码
output_onnx_path = "./saves/bertclassify.onnx"
from itertools import chain
dummy_inputs = onnx_config.generate_dummy_inputs(tokenizer, framework='pt')

torch.onnx.export(
    model,
    (dummy_inputs,),
    f=output_onnx_path,
    input_names=list(onnx_config.inputs.keys()),
    output_names=list(onnx_config.outputs.keys()),
    dynamic_axes={
        name: axes for name, axes in chain(onnx_config.inputs.items(), onnx_config.outputs.items())
    },
    do_constant_folding=True,
    opset_version=14,
)

全部:

python 复制代码
import torch
devices=torch.device("cpu")
from transformers.onnx.features import FeaturesManager
import torch
from transformers import AutoTokenizer, BertForSequenceClassification
import numpy as np
model_path = "./saves"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path)

words = ["你叫什么名字"]
inputs = tokenizer(words, return_tensors='pt', padding=True)
model.eval()

onnx_config = FeaturesManager._SUPPORTED_MODEL_TYPE['bert']['sequence-classification']("./saves")
dummy_inputs = onnx_config.generate_dummy_inputs(tokenizer, framework='pt')
from itertools import chain

output_org = model(**inputs).logits

torch.onnx.export(
    model,
    (dummy_inputs,),
    f=output_onnx_path,
    input_names=list(onnx_config.inputs.keys()),
    output_names=list(onnx_config.outputs.keys()),
    dynamic_axes={
        name: axes for name, axes in chain(onnx_config.inputs.items(), onnx_config.outputs.items())
    },
    do_constant_folding=True,
    opset_version=14,
)

# #验证是否成功
import onnx
onnx_model=onnx.load("./saves/bertclassify.onnx")
onnx.checker.check_model(onnx_model)
print("无报错,转换成功")

# #推理
import onnxruntime
ort_session=onnxruntime.InferenceSession("./saves/bertclassify.onnx", providers=['CPUExecutionProvider'])    #加载模型
ort_input={"input_ids":inputs["input_ids"].cpu().numpy(),"token_type_ids":inputs["token_type_ids"].cpu().numpy(),
           "attention_mask":inputs["attention_mask"].cpu().numpy()}
output_on = ort_session.run(["logits"], ort_input)[0]   #推理


print(output_org.detach().numpy())
print(output_on)
assert np.allclose(output_org.detach().numpy(), output_on, 10-5)  #无报错

无任何警告产生

实体识别案例

python 复制代码
import onnxruntime
from itertools import chain
from transformers.onnx.features import FeaturesManager

config = ner_config
tokenizer = ner_tokenizer
model = ner_model
output_onnx_path = "bert-ner.onnx"

onnx_config = FeaturesManager._SUPPORTED_MODEL_TYPE['bert']['sequence-classification'](config)
dummy_inputs = onnx_config.generate_dummy_inputs(tokenizer, framework='pt')

torch.onnx.export(
    model,
    (dummy_inputs,),
    f=output_onnx_path,
    input_names=list(onnx_config.inputs.keys()),
    output_names=list(onnx_config.outputs.keys()),
    dynamic_axes={
        name: axes for name, axes in chain(onnx_config.inputs.items(), onnx_config.outputs.items())
    },
    do_constant_folding=True,
    opset_version=onnx_config.default_onnx_opset,       #默认,报错改为14
)

转transformers 模型到onnx 接口解读

Huggingface:导出transformers模型到onnx_ONNX_程序员架构进阶_InfoQ写作社区

https://zhuanlan.zhihu.com/p/684444410

相关推荐
Source.Liu17 分钟前
【A11】服务器数据库结构笔记
服务器·数据库·笔记
火星机器人life38 分钟前
深度学习如何重塑移动机器人SLAM?一篇综述讲透视觉里程计、闭环检测与语义建图
深度学习·视觉里程计·slam·语义建图
1314lay_10071 小时前
ABAP 读取服务器的文件 OPEN DATASET,READ DATASET f_filepath INTO l_file.
经验分享·笔记
MichaelJohn1 小时前
我用 Obsidian + Claude Code + GitHub 搭了个真正「会生长」的第二大脑
笔记
qq_25294131682 小时前
多模态屋顶损伤与杂物检测数据集 | 屋顶检测 多模态 红外可见光 建筑巡检 目标检测9232期
人工智能·深度学习·yolo·目标检测·计算机视觉·屋顶
zhangrelay2 小时前
手机长周期测评十周年终结版本-2026
笔记·学习·智能手机
海海不掉头发2 小时前
图论与应用_课堂笔记
笔记·图论
jay神2 小时前
基于 YOLOv11 的无人机航拍小目标检测系统
人工智能·深度学习·yolo·目标检测·计算机视觉·无人机·计算机毕业设计
jay神2 小时前
基于 YOLOv8 的手势识别系统
人工智能·深度学习·yolo·机器学习·计算机视觉·目标跟踪·课程设计
杨逢昌工厂6S管理3 小时前
127-钣金产线6S改善后总反弹?杨逢昌一线现场诊断笔记:反弹背后的熵增机理与基准化治理
经验分享·笔记·职场和发展·学习方法