{"id":19001225,"url":"https://github.com/oneflow-inc/oneflow_convert","last_synced_at":"2025-09-01T05:32:27.268Z","repository":{"id":37101775,"uuid":"347891709","full_name":"Oneflow-Inc/oneflow_convert","owner":"Oneflow-Inc","description":"OneFlow-\u003eONNX","archived":false,"fork":false,"pushed_at":"2023-04-19T04:02:24.000Z","size":2064,"stargazers_count":43,"open_issues_count":6,"forks_count":8,"subscribers_count":45,"default_branch":"main","last_synced_at":"2025-08-26T07:13:13.457Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Oneflow-Inc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-15T08:32:16.000Z","updated_at":"2025-04-15T01:42:52.000Z","dependencies_parsed_at":"2024-11-08T18:10:32.102Z","dependency_job_id":"2ae22071-06f5-403c-9ab0-b3dc78362680","html_url":"https://github.com/Oneflow-Inc/oneflow_convert","commit_stats":null,"previous_names":["oneflow-inc/oneflow_convert_tools"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/Oneflow-Inc/oneflow_convert","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Oneflow-Inc%2Foneflow_convert","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Oneflow-Inc%2Foneflow_convert/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Oneflow-Inc%2Foneflow_convert/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Oneflow-Inc%2Foneflow_convert/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Oneflow-Inc","download_url":"https://codeload.github.com/Oneflow-Inc/oneflow_convert/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Oneflow-Inc%2Foneflow_convert/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273077227,"owners_count":25041358,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-01T02:00:09.058Z","response_time":120,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T18:10:25.317Z","updated_at":"2025-09-01T05:32:27.220Z","avatar_url":"https://github.com/Oneflow-Inc.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"**简体中文** | [English](README_en.md)\n\n**oneflow-onnx: OneFlow -\u003e ONNX 模型转换工具**\n\n[![PyPI version](https://img.shields.io/pypi/v/oneflow-onnx.svg)](https://pypi.python.org/pypi/oneflow-onnx/)\n[![PyPI pyversions](https://img.shields.io/pypi/pyversions/oneflow-onnx.svg)](https://pypi.python.org/pypi/oneflow-onnx/)\n[![PyPI license](https://img.shields.io/pypi/l/oneflow-onnx.svg)](https://pypi.python.org/pypi/oneflow-onnx/)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/Oneflow-Inc/oneflow_convert_tools/pulls)\n\n- [简介](#简介)\n  - [ONNX 简介](#onnx-简介)\n  - [ONNX 相关库](#onnx-相关库)\n  - [oneflow-onnx 简介](#oneflow-onnx-简介)\n- [安装 oneflow-onnx](#安装-oneflow-onnx)\n  - [环境依赖](#环境依赖)\n  - [安装方式](#安装方式)\n- [oneflow-onnx 的使用方法](#oneflow-onnx-的使用方法)\n  - [基本用法](#基本用法)\n  - [导出模型时的注意点](#导出模型时的注意点)\n- [用法示例](#用法示例)\n  - [导出为 ONNX 模型](#导出为-onnx-模型)\n  - [使用 ONNX 模型进行推理](#使用-onnx-模型进行推理)\n- [相关文档](#相关文档)\n\n## 简介\n\n### ONNX 简介\n\n[ONNX](https://onnx.ai/index.html) 的全称为 Open Neural Network Exchange (开放神经网络交换)，是一种针对机器学习算法所设计的开放式文件格式标准，用于存储训练好的算法模型。许多主流的深度学习框架（如 OneFlow、PyTorch、TensorFlow、MXNet）都支持将模型导出为 ONNX 模型。ONNX 使得不同的深度学习框架可以以一种统一的格式存储模型数据以及进行交互。另外，ONNX 有相应的运行时（Runtime）—— [ONNX Runtime](https://onnxruntime.ai/)，便于在多种平台（Linux、Windows、Mac OS、Android、iOS等）及多种硬件（CPU、GPU等）上进行模型部署和推理。\n\n### ONNX 相关库\n\nONNX 对应多个相关库，常见的几个库的功能如下所述：\n\n1. [onnx](https://github.com/onnx/onnx): ONNX 模型格式标准\n\n2. [onnxruntime](https://github.com/microsoft/onnxruntime): ONNX 运行时，用于加载 ONNX 模型进行推理。\n\n3. [onnx-simplifier](https://github.com/daquexian/onnx-simplifier): 用于简化 ONNX 模型的结构，例如消除结果恒为常量的算子\n   \n4. [onnxoptimizer](https://github.com/onnx/optimizer): 用于通过图变换等方式优化 ONNX 模型\n\n### oneflow-onnx 简介\noneflow-onnx 是 OneFlow 团队提供的模型转换工具，支持将 OneFlow 静态图模型导出为 ONNX 模型。目前稳定支持导出 ONNX Opset10，部分 OneFlow 算子支持更低的 ONNX Opset 转换，详情可以参考  [OneFlow2ONNX 算子列表](docs/oneflow2onnx/op_list.md)。已经通过测试的常用模型可以参考 [OneFlow2ONNX 模型列表](docs/oneflow2onnx/oneflow2onnx_model_zoo.md)。\n\n\n## 安装 oneflow-onnx\n\n### 环境依赖\n\n```text\npython\u003e=3.5\nonnx\u003e=1.8.0\nonnx-simplifier\u003e=0.3.3\nonnxoptimizer\u003e=0.2.5\nonnxruntime-gpu\u003e=1.8.0\noneflow (https://github.com/Oneflow-Inc/oneflow#install-with-pip-package)\n```\n\n### 安装方式\n\n**通过 pip 安装：**\n\n```sh\npip install oneflow_onnx\n```\n\n**通过源码安装：**\n\n```sh\ngit clone https://github.com/Oneflow-Inc/oneflow_convert\ncd oneflow_convert\npython3 setup.py install\n```\n\n## oneflow-onnx 的使用方法\n\n### 基本用法\n\n要将 OneFlow 静态图模型导出为 ONNX 模型，只需调用 `export_onnx_model` 函数。\n\n```python\nfrom oneflow_onnx.oneflow2onnx.util import export_onnx_model\n\nexport_onnx_model(graph,\n                  external_data=False, \n                  opset=None, \n                  onnx_model_path=\"/tmp\", \n                  dynamic_batch_size=False)\n```\n各参数的含义如下:\n\n1. graph: 需要转换的 graph ( [Graph](../basics/08_nn_graph.md) 对象)\n\n2. external_data: 是否将权重另存为 ONNX 模型的外部数据，为 `True` 时通常是为了避免 protobuf 的 2GB 文件大小限制\n\n3. opset: 指定转换模型的版本 ( int，默认为 10 )\n\n4. flow_weight_dir: OneFlow 模型权重的保存路径（如果为空则会直接使用当前 graph 本身的权重）\n\n5. onnx_model_path: 导出的 ONNX 模型保存路径\n\n6. dynamic_batch_size: 导出的 ONNX 模型是否支持动态 batch，默认为False\n\n\n另外，oneflow-onnx 还提供了一个名为 `convert_to_onnx_and_check` 的函数，用于转换并检查转换出的 ONNX 模型。其中的检查指的是将同样的输入分别送入原本的 OneFlow 模型和转换后的 ONNX 模型，然后比较两个输出中对应的每个数值之差是否在合理的误差范围内。\n\n```python\nfrom oneflow_onnx.oneflow2onnx.util import convert_to_onnx_and_check\n\nconvert_to_onnx_and_check(...)\n```\n`convert_to_onnx_and_check` 函数的参数是 `export_onnx_model` 函数的参数的超集，可以额外传入 `print_outlier=True` 来输出检查过程中发现的超出合理误差范围内的异常值；`input_tensor_range` 来指定精度验证时生成随机输入的取值范围；`device` 则用来指定做精度验证的设备类型，有 `cpu/gpu/cpu_global/gpu_global` 4种选择。\n\n### 导出模型时的注意点\n\n- 在导出模型之前，需要将模型设置成 eval 模式，因为 Dropout、Batch Normalization 等操作在训练和推理模型下的行为不同\n- 在构建静态图模型时，需要指定一个输入，此输入的值可以是随机的，但要保证它是正确的数据类型和形状\n- ONNX 模型接受的输入的形状是固定的，batch 维度的大小可以是变化的，通过将 `dynamic_batch_size` 参数设为 `True` 可以使得导出的 ONNX 模型支持动态 batch 大小\n- oneflow-onnx 必须使用静态图模型（Graph 模式）作为导出函数的参数。对于动态图模型（Eager 模式），需要将动态图模型构建为静态图模型，可参见下文的示例。\n\n\n## 用法示例\n我们以常见的 ResNet-34 模型为例，介绍将 OneFlow 模型导出为 ONNX 模型并进行推理的流程。\n\n下面的代码中使用到了 [FlowVision](https://github.com/Oneflow-Inc/vision)，它是基于 OneFlow 搭建的、专用于计算机视觉任务的工具库，包含诸多模型、数据增强方法、数据变换操作、数据集等。我们在此直接使用 FlowVision 库提供的 ResNet-34 模型，并使用 FlowVision 提供的在 ImageNet 数据集上训练得到的 ResNet-34 权重。\n\n### 导出为 ONNX 模型\n\n导入相关依赖：\n```python\nimport oneflow as flow\nfrom oneflow import nn\nfrom flowvision.models import resnet34\nfrom oneflow_onnx.oneflow2onnx.util import convert_to_onnx_and_check\n```\n\n使用动态图模型构建静态图模型，详情请参见：[静态图模块 nn.Graph](../basics/08_nn_graph.md)\n\n```python\nclass ResNet34Graph(nn.Graph):\n    def __init__(self, eager_model):\n        super().__init__()\n        self.model = eager_model\n\n    def build(self, x):\n        return self.model(x)\n```\n\n将 OneFlow 静态图模型导出为 ONNX 模型：\n```python\n# 模型参数存储目录\nMODEL_PARAMS = 'checkpoints/resnet34'\n\nparams = flow.load(MODEL_PARAMS)\nmodel = resnet34()\nmodel.load_state_dict(params)\n\n# 将模型设置为 eval 模式\nmodel.eval()\n\nresnet34_graph = ResNet34Graph(model)\n# 构建出静态图模型\nresnet34_graph._compile(flow.randn(1, 3, 224, 224))\n\n# 导出为 ONNX 模型并进行检查\nconvert_to_onnx_and_check(resnet34_graph, \n                          onnx_model_path=\"./\", \n                          print_outlier=True,\n                          dynamic_batch_size=True)\n```\n运行完毕后，可以在当前目录中找到名为 `model.onnx` 的文件，即导出的 ONNX 模型。\n\n### 使用 ONNX 模型进行推理\n\n进行推理之前，要保证已经安装了 ONNX Runtime, 即 onnxruntime 或 onnxruntime-gpu。在本教程的实验环境中，安装的是 onnxruntime-gpu 以调用 GPU 进行计算，但如果机器上没有 GPU，也可以指定使用 CPU 进行计算，详见下文。\n\n我们使用下面这张图像作为模型的输入：\n\u003cdiv align=\"center\"\u003e\n    \u003cimg alt=\"Demo Image\" src=\"docs/cat.png\" width=\"300px\"\u003e\n\u003c/div\u003e\n\n\n导入依赖：\n```python\nimport numpy as np\nimport cv2\nfrom onnxruntime import InferenceSession\n```\n\n定义一个函数用于将图像预处理为 ONNX 模型所接受的格式和尺寸：\n```python\ndef preprocess_image(img, input_hw = (224, 224)):\n    h, w, _ = img.shape\n    \n    # 使用图像的较长边确定缩放系数\n    is_wider = True if h \u003c= w else False\n    scale = input_hw[1] / w if is_wider else input_hw[0] / h\n\n    # 对图像进行等比例缩放\n    processed_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)\n    # 归一化\n    processed_img = np.array(processed_img, dtype=np.float32) / 255\n\n    # 将图像填充到 ONNX 模型预设尺寸\n    temp_img = np.zeros((input_hw[0], input_hw[1], 3), dtype=np.float32)\n    temp_img[:processed_img.shape[0], :processed_img.shape[1], :] = processed_img\n    processed_img = temp_img\n    \n    # 调整轴的顺序并在最前面添加 batch 轴  \n    processed_img = np.expand_dims(processed_img.transpose(2, 0, 1), axis=0)\n\n    return processed_img\n```\n\n接下来，使用 ONNX 模型进行推理，主要步骤包括：创建一个 InferenceSession 对象，然后调用其 `run` 方法进行推理。\n\n在 onnxruntime(-gpu) 1.9 及以上版本中，创建 InferenceSession 对象时需要显式指定 `providers` 参数来选择使用的硬件。对于 onnxruntime-gpu，可以指定的值包括 `TensorrtExecutionProvider`、`CUDAExecutionProvider`、`CPUExecutionProvider`。如果运行的机器上没有 GPU，可以将 `providers` 参数指定为 `['CPUExecutionProvider']` 来使用 CPU 进行计算。\n\nONNX 模型的输入数据的类型是一个 dict，其 keys 为导出 ONNX 模型时的输入名称 \"input names\"，values 为 NumPy 数组类型的实际输入数据。可以通过 InferenceSession 对象的 `get_inputs` 方法获取\"input names\"，该方法的返回值是 `onnxruntime.NodeArg` 类型的对象组成的 list，对于 NodeArg 对象，可使用其 `name` 属性获取 str 类型的名称。在本教程中，输入只有图像数据本身，因此可以通过在 InferenceSession 对象上调用 `.get_inputs()[0].name`，获取输入对应的 \"input names\"，其值为 `_ResNet34Graph_0-input_0/out`，将此值作为 key 构造输入 ONNX 模型的 dict。当然，也可以不预先指定，而在运行时动态获取。\n\n```python\n# 从文件中读取 ImageNet 数据集的类别名称\nwith open('ImageNet-Class-Names.txt') as f:\n    CLASS_NAMES = f.readlines()\n\n# 读取图像文件并使用 `preprocess_image` 函数进行预处理\nimg = cv2.imread('cat.jpg', cv2.IMREAD_COLOR)\nimg = preprocess_image(img)\n\n# 创建一个 InferenceSession 对象\nort_sess = InferenceSession('model.onnx', providers=['TensorrtExecutionProvider',\n                                                     'CUDAExecutionProvider',\n                                                     'CPUExecutionProvider'])\n# 调用 InferenceSession 对象的 `run` 方法进行推理\nresults = ort_sess.run(None, {\"_ResNet34Graph_0-input_0/out\": img})\n\n# 输出推理结果\nprint(CLASS_NAMES[np.argmax(results[0])])\n```\n\nInferenceSession 对象的 `run` 方法的输出是 NumPy 数组构成的 list，每个 NumPy 数组对应一组输出。因为只有一组输入，所以取出索引为 0 的元素作为输出，此元素的形状是 `(1, 1000)`，对应于 1000 个类别的概率 (如果将 n 张图像作为一个 batch 输入，此元素的形状将是 `(n, 1000)`)。通过 `np.argmax` 获取概率最大的类别对应的索引后，将索引映射为类别名称。\n\n运行以上代码，得到：\n```text\n(base) root@training-notebook-654c6f-654c6f-jupyter-master-0:/workspace# python infer.py \n285: 'Egyptian cat',\n```\n\n以上是在 Python 环境中使用 GPU 或 CPU 进行推理，实际使用时可以根据部署环境选择不同的 ONNX Runtime 来使用导出的 ONNX 模型。\n\n\n## 相关文档\n\n- [OneFlow2ONNX模型列表](docs/oneflow2onnx/oneflow2onnx_model_zoo.md)\n- [OneFlow2ONNX算子列表](docs/oneflow2onnx/op_list.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foneflow-inc%2Foneflow_convert","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foneflow-inc%2Foneflow_convert","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foneflow-inc%2Foneflow_convert/lists"}