ONNX模型修改实战:从节点增删到子图提取的完整指南

news2026/4/13 2:13:32
ONNX模型修改实战从节点增删到子图提取的完整指南在深度学习模型部署的工程实践中ONNX作为跨平台中间表示格式已成为行业标准。但当面对实际业务需求时原始导出的模型往往需要经过结构调整才能适配目标环境。本文将深入剖析ONNX模型修改的核心技术通过具体代码示例演示节点操作、子图提取等高级技巧帮助开发者掌握模型定制化改造的完整方法论。1. ONNX模型结构解析与工具链准备理解ONNX的底层表示是进行模型修改的前提。一个ONNX模型由ModelProto、GraphProto、NodeProto等多层结构组成其中GraphProto包含以下关键组件node计算节点列表构成模型的计算图拓扑input/output模型全局输入输出张量描述initializer存储模型权重参数的持久化数据value_info中间张量的形状和类型信息推荐使用以下工具组合进行高效操作# 基础工具链安装 pip install onnx onnxruntime onnx-simplifier # 高级图操作工具 pip install onnx_graphsurgeon --index-url https://pypi.ngc.nvidia.com对于大于2GB的模型需要特别注意内存处理# 大模型加载示例 onnx_model onnx.load(large_model.onnx, load_external_dataTrue, external_data_dir./weights)2. 节点级操作实战2.1 节点增删与属性修改删除节点时需要处理上下游连接关系。以下示例展示如何安全移除Cast节点并维护图完整性def remove_cast_node(onnx_model, target_node_name): graph onnx_model.graph node_map {node.name: (i, node) for i, node in enumerate(graph.node)} if target_node_name not in node_map: raise ValueError(fNode {target_node_name} not found) node_idx, cast_node node_map[target_node_name] if cast_node.op_type ! Cast: raise TypeError(Target node must be Cast operation) # 建立输入输出映射关系 input_name cast_node.input[0] output_name cast_node.output[0] # 删除节点并更新连接 del graph.node[node_idx] for node in graph.node: for i in range(len(node.input)): if node.input[i] output_name: node.input[i] input_name return onnx_model添加新节点时需要注意拓扑排序。以下是在Conv层后插入Pad操作的典型示例def insert_pad_after_conv(onnx_model, conv_node_name, pads): graph onnx_model.graph conv_node, conv_idx None, 0 # 定位目标卷积节点 for idx, node in enumerate(graph.node): if node.name conv_node_name: conv_node, conv_idx node, idx break if not conv_node: raise ValueError(Conv node not found) # 创建Pad节点和常量节点 new_output_name f{conv_node.output[0]}_padded pad_size_name f{conv_node.output[0]}_pad_size # 修改原始卷积输出名称 original_output conv_node.output[0] conv_node.output[0] new_output_name # 创建Pad尺寸常量节点 pad_size_node onnx.helper.make_node( Constant, inputs[], outputs[pad_size_name], valueonnx.helper.make_tensor( namepad_size, data_typeonnx.TensorProto.INT64, dims[len(pads)], valspads ) ) # 创建Pad节点 pad_node onnx.helper.make_node( Pad, inputs[new_output_name, pad_size_name], outputs[original_output], modeconstant ) # 按拓扑顺序插入新节点 graph.node.insert(conv_idx1, pad_size_node) graph.node.insert(conv_idx2, pad_node) return onnx_model2.2 节点属性动态修改ONNX节点的属性存储在attribute字段中修改时需要遵循proto协议规范def update_node_attr(onnx_model, node_name, attr_name, new_value): graph onnx_model.graph target_node next((n for n in graph.node if n.name node_name), None) if not target_node: raise ValueError(Target node not found) # 删除旧属性 attrs [attr for attr in target_node.attribute if attr.name ! attr_name] target_node.attribute[:] attrs # 添加新属性 if isinstance(new_value, int): new_attr onnx.helper.make_attribute(attr_name, new_value) elif isinstance(new_value, list): new_attr onnx.helper.make_attribute(attr_name, new_value) else: raise TypeError(Unsupported attribute type) target_node.attribute.append(new_attr) return onnx_model3. 子图提取高级技巧3.1 基于官方工具的基础提取ONNX提供内置的extract_model函数实现基础子图提取from onnx import utils def extract_submodel(input_path, output_path, input_names, output_names): try: utils.extract_model(input_path, output_path, input_names, output_names) except ValueError as e: if Model larger than 2GB in str(e): print(使用大模型处理方案...) return extract_large_submodel(input_path, output_path, input_names, output_names) raise3.2 大模型子图提取方案对于超过2GB的模型需要使用onnx_graphsurgeon进行处理import onnx_graphsurgeon as gs def extract_large_submodel(input_path, output_path, input_names, output_names): model onnx.load(input_path) graph gs.import_onnx(model) tensors graph.tensors() # 设置新的输入输出 graph.inputs [tensors[name].to_variable(dtypenp.float32) for name in input_names] graph.outputs [tensors[name].to_variable(dtypenp.float32) for name in output_names] # 清理无效节点 graph.cleanup() # 保存子模型 onnx.save(gs.export_onnx(graph), output_path)3.3 动态形状子图提取当处理动态维度模型时需要特别注意形状传播def extract_dynamic_subgraph(onnx_model, input_names, output_names): # 执行形状推断 inferred_model shape_inference.infer_shapes(onnx_model) # 创建新的GraphProto new_graph onnx.GraphProto() new_graph.name fsubgraph_of_{inferred_model.graph.name} # 复制节点和初始化器 node_mapping set() for node in inferred_model.graph.node: if any(out in output_names for out in node.output): new_graph.node.append(node) node_mapping.add(node.name) # 添加初始器 for init in inferred_model.graph.initializer: if init.name in input_names: new_graph.initializer.append(init) # 设置输入输出 for value_info in inferred_model.graph.value_info: if value_info.name in input_names output_names: new_graph.value_info.append(value_info) # 构建新模型 submodel onnx.helper.make_model( new_graph, opset_importsinferred_model.opset_import ) return submodel4. 模型IO系统改造4.1 输入输出重命名批量修改张量名称时需要同步更新所有引用位置def rename_tensors(onnx_model, name_mapping): graph onnx_model.graph # 更新graph input/output for io in graph.input: if io.name in name_mapping: io.name name_mapping[io.name] for io in graph.output: if io.name in name_mapping: io.name name_mapping[io.name] # 更新节点输入输出 for node in graph.node: for i in range(len(node.input)): if node.input[i] in name_mapping: node.input[i] name_mapping[node.input[i]] for i in range(len(node.output)): if node.output[i] in name_mapping: node.output[i] name_mapping[node.output[i]] # 更新initializer for init in graph.initializer: if init.name in name_mapping: init.name name_mapping[init.name] return onnx_model4.2 动态维度修改调整模型输入输出形状是部署时的常见需求def modify_io_shape(onnx_model, io_shapes): graph onnx_model.graph for io in graph.input: if io.name in io_shapes: new_shape io_shapes[io.name] # 清除原有维度 while io.type.tensor_type.shape.dim: io.type.tensor_type.shape.dim.pop() # 添加新维度 for dim in new_shape: new_dim io.type.tensor_type.shape.dim.add() if isinstance(dim, int): new_dim.dim_value dim else: new_dim.dim_param str(dim) # 执行形状推断以传播新形状 inferred_model shape_inference.infer_shapes(onnx_model) return inferred_model4.3 数据类型转换模型精度调整时可能需要修改IO数据类型def convert_io_dtype(onnx_model, type_mapping): graph onnx_model.graph type_map { float32: onnx.TensorProto.FLOAT, int32: onnx.TensorProto.INT32, int64: onnx.TensorProto.INT64 } for io in graph.input: if io.name in type_mapping: io.type.tensor_type.elem_type type_map[type_mapping[io.name]] for io in graph.output: if io.name in type_mapping: io.type.tensor_type.elem_type type_map[type_mapping[io.name]] return onnx_model5. 调试与验证技术5.1 中间结果提取通过修改输出节点获取中间层结果def add_debug_outputs(onnx_model, tensor_names): graph onnx_model.graph tensor_shapes {} # 收集张量形状信息 for info in graph.value_info: tensor_shapes[info.name] ( [d.dim_value for d in info.type.tensor_type.shape.dim], info.type.tensor_type.elem_type ) # 添加调试输出 for name in tensor_names: if name in tensor_shapes: shape, dtype tensor_shapes[name] graph.output.append( onnx.helper.make_tensor_value_info( namename, elem_typedtype, shapeshape ) ) return onnx_model5.2 模型一致性检查修改后的模型需要进行严格验证def validate_model(onnx_model): try: onnx.checker.check_model(onnx_model) print(模型检查通过) # 验证可运行性 sess onnxruntime.InferenceSession(onnx_model.SerializeToString()) print(模型可执行性验证通过) return True except Exception as e: print(f模型验证失败: {str(e)}) return False5.3 修改前后精度对比确保模型修改不影响计算精度def compare_models(original_model, modified_model, test_input): # 原始模型推理 orig_sess onnxruntime.InferenceSession(original_model.SerializeToString()) orig_output orig_sess.run(None, test_input) # 修改后模型推理 mod_sess onnxruntime.InferenceSession(modified_model.SerializeToString()) mod_output mod_sess.run(None, test_input) # 精度比较 for orig, mod in zip(orig_output, mod_output): if not np.allclose(orig, mod, atol1e-5): max_diff np.max(np.abs(orig - mod)) print(f输出差异过大最大差值: {max_diff}) return False print(模型输出一致) return True6. 性能优化技巧6.1 常量折叠优化使用onnx-simplifier进行自动优化def optimize_with_onnxsim(input_path, output_path): import onnxsim model onnx.load(input_path) simplified_model, check onnxsim.simplify(model) if check: onnx.save(simplified_model, output_path) print(模型优化成功) else: raise RuntimeError(模型优化失败)6.2 自定义优化Pass实现特定场景的优化逻辑def custom_optimization_pass(onnx_model): graph onnx_model.graph optimized_nodes [] i 0 while i len(graph.node): node graph.node[i] # 识别连续的Transpose节点 if node.op_type Transpose and i1 len(graph.node): next_node graph.node[i1] if next_node.op_type Transpose: # 检查是否是转置的逆操作 perm1 list(attr.ints for attr in node.attribute if attr.name perm)[0] perm2 list(attr.ints for attr in next_node.attribute if attr.name perm)[0] if perm1 perm2[::-1]: # 创建直接映射关系 input_name node.input[0] output_name next_node.output[0] # 跳过这两个节点 i 2 # 更新后续节点的输入引用 for subsequent_node in graph.node[i:]: for j in range(len(subsequent_node.input)): if subsequent_node.input[j] output_name: subsequent_node.input[j] input_name continue optimized_nodes.append(node) i 1 # 更新图结构 del graph.node[:] graph.node.extend(optimized_nodes) return onnx_model6.3 内存优化策略处理大模型的实用技巧def optimize_large_model(onnx_model, output_path): # 启用外部数据存储 onnx.save_model( onnx_model, output_path, save_as_external_dataTrue, all_tensors_to_one_fileTrue, locationweights.bin, size_threshold1024 ) # 分片保存选项 # onnx.save_model( # onnx_model, # output_path, # save_as_external_dataTrue, # all_tensors_to_one_fileFalse, # size_threshold1024 # )7. 工程实践中的常见问题解决7.1 自定义算子处理集成自定义算子的实用方案def handle_custom_operators(onnx_model): graph onnx_model.graph custom_ops set() # 识别自定义算子 for node in graph.node: if node.domain not in [, ai.onnx]: custom_ops.add((node.op_type, node.domain)) # 为每个自定义算子添加opset导入 for op_type, domain in custom_ops: existing [opset for opset in onnx_model.opset_import if opset.domain domain] if not existing: onnx_model.opset_import.append( onnx.helper.make_opsetid(domain, 1) ) return onnx_model7.2 形状推断异常处理处理形状推断失败的稳健方案def safe_shape_inference(onnx_model): try: return shape_inference.infer_shapes(onnx_model) except Exception as e: print(f形状推断失败: {str(e)}) print(尝试替代方案...) # 方案1使用onnx-simplifier的形状推断 try: import onnxsim simplified, _ onnxsim.simplify(onnx_model) return simplified except: pass # 方案2部分形状推断 partial_model onnx.ModelProto() partial_model.CopyFrom(onnx_model) del partial_model.graph.value_info[:] return partial_model7.3 跨框架兼容性问题解决框架间转换的典型问题def fix_framework_specific_issues(onnx_model): graph onnx_model.graph # 处理PyTorch导出的冗余维度 for node in graph.node: if node.op_type Squeeze: attrs {attr.name: attr for attr in node.attribute} if axes in attrs and attrs[axes].ints [0]: input_shape get_tensor_shape(graph, node.input[0]) if input_shape and input_shape[0] 1: # 直接绕过不必要的Squeeze bypass_redundant_squeeze(graph, node) # 处理TF导出的特殊属性 for node in graph.node: if node.op_type Transpose and len(node.input) 1: # 将动态perm转换为静态属性 perm_input node.input[1] if perm_input in [init.name for init in graph.initializer]: perm_init next(init for init in graph.initializer if init.name perm_input) perm_value onnx.numpy_helper.to_array(perm_init) new_node onnx.helper.make_node( Transpose, inputs[node.input[0]], outputsnode.output, permperm_value.tolist() ) replace_node(graph, node, new_node) return onnx_model掌握这些ONNX模型修改技术后开发者可以灵活应对各种模型部署场景。在实际项目中建议结合具体需求选择合适的技术组合并建立完善的验证流程确保修改后的模型保持原始计算语义。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2418190.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…