onnx2torch

ENOT-AutoDLApache-2.0长期未更新

把 ONNX 模型直接转成 PyTorch 网络,方便在 PyTorch 里继续微调或调试,省去手工重搭结构的麻烦。

Convert ONNX models to PyTorch.

v1.5.15发布于 2024-08-07 14:06 UTC742star94fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
pip install onnx2torch
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 ONNX 模型转成 PyTorch 模型的转换器,方便在 PyTorch 里继续改和跑

把 ONNX 模型直接转成 PyTorch 网络,方便在 PyTorch 里继续微调或调试,省去手工重搭结构的麻烦。

核心能力

  • 调用 convert 函数一步把 ONNX 模型转成 torch.nn.Module
  • 用 @add_converter 注册自定义算子,方便扩展新操作
  • 转换后的模型可用 torch.onnx.export 再导回 ONNX
  • 已测试分类、分割、检测和 Transformer 等多类模型
  • 按 opset 版本分别注册算子转换实现

容易踩的坑

只覆盖有限的 PyTorch/ONNX 模型和算子,并非所有模型都能转;遇到旧 opset 模型需先用 onnx version_converter 升版本再转换,结果可能不稳定;自定义算子转换要求 torch_module 必须是 torch.nn.Module 而非普通可调用对象

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v1.5.15
  1. v1.5.15最新正式版2024-08-07 · 2024-08-07 14:06 UTC
    feat: squeeze-21
    feat: ArgMax and ArgMin
    

    Thanks to @rosemanmeilof and @ajstarna for their contributions.

    :cake:

  2. v1.5.142024-04-02 · 2024-04-02 11:03 UTC
    查看更新说明
    feat: isinf, isnan and nonzero operations
    fix: reduce keepdim type (int -> bool)
    

    Thanks to @karalinkw and @francis2tm for their contributions.

    :cake:

  3. v1.5.132023-10-27 · 2023-10-27 14:16 UTC
    查看更新说明
    fix: div return type for integer arguments
    docs: missing [import onnx] in main example
    

    Thanks @seriousran for his contribution.

    :cake:

  4. v1.5.122023-10-09 · 2023-10-09 21:25 UTC
    查看更新说明
    fix: export to onnx ConstantOfShape in case of bool value attribute
    

    :cake:

  5. v1.5.112023-07-26 · 2023-07-26 18:56 UTC
    查看更新说明
    feat: DepthToSpace
    

    Thanks @sushanthr for his contribution.

    :cake:

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    onnx2torch is an ONNX to PyTorch converter. Our converter:

    • Is easy to use – Convert the ONNX model with the function call convert;
    • Is easy to extend – Write your own custom layer in PyTorch and register it with @add_converter;
    • Convert back to ONNX – You can convert the model back to ONNX using the torch.onnx.export function.

    If you find an issue, please let us know! And feel free to create merge requests.

    Please note that this converter covers only a limited number of PyTorch / ONNX models and operations. Let us know which models you use or want to convert from ONNX to PyTorch here.

    Installation

    pip install onnx2torch
    

    or

    conda install -c conda-forge onnx2torch
    

    Usage

    Below you can find some examples of use.

    Convert

    import onnx
    import torch
    from onnx2torch import convert
    
    # Path to ONNX model
    onnx_model_path = "/some/path/mobile_net_v2.onnx"
    # You can pass the path to the onnx model to convert it or...
    torch_model_1 = convert(onnx_model_path)
    
    # Or you can load a regular onnx model and pass it to the converter
    onnx_model = onnx.load(onnx_model_path)
    torch_model_2 = convert(onnx_model)
    

    Execute

    We can execute the returned PyTorch model in the same way as the original torch model.

    import onnxruntime as ort
    
    # Create example data
    x = torch.ones((1, 2, 224, 224)).cuda()
    
    out_torch = torch_model_1(x)
    
    ort_sess = ort.InferenceSession(onnx_model_path)
    outputs_ort = ort_sess.run(None, {"input": x.numpy()})
    
    # Check the Onnx output against PyTorch
    print(torch.max(torch.abs(outputs_ort - out_torch.detach().numpy())))
    print(np.allclose(outputs_ort, out_torch.detach().numpy(), atol=1.0e-7))
    

    Models

    We have tested the following models:

    Segmentation models:

    • DeepLabV3+
    • DeepLabV3 ResNet-50 (TorchVision)
    • HRNet
    • UNet (TorchVision)
    • FCN ResNet-50 (TorchVision)
    • LRASPP MobileNetV3 (TorchVision)

    Detection from MMdetection:

    Classification from TorchVision:

    • ResNet-18
    • ResNet-50
    • MobileNetV2
    • MobileNetV3 Large
    • EfficientNet-B{0, 1, 2, 3}
    • WideResNet-50
    • ResNext-50
    • VGG-16
    • GoogLeNet
    • MnasNet
    • RegNet

    Transformers:

    • ViT
    • Swin
    • GPT-J
    :page_facing_up: List of currently supported operations can be founded here.

    How to add new operations to converter

    Here we show how to extend onnx2torch with new ONNX operation, that supported by both PyTorch and ONNX

    An example of such a module is Relu

    @add_converter(operation_type="Relu", version=6)
    @add_converter(operation_type="Relu", version=13)
    @add_converter(operation_type="Relu", version=14)
    def _(node: OnnxNode, graph: OnnxGraph) -> OperationConverterResult:
        return OperationConverterResult(
            torch_module=nn.ReLU(),
            onnx_mapping=onnx_mapping_from_node(node=node),
        )
    

    Here we have registered an operation named Relu for opset versions 6, 13, 14. Note that the torch_module argument in OperationConverterResult must be a torch.nn.Module, not just a callable object! If Operation's behaviour differs from one opset version to another, you should implement it separately.

    An example of such a module is ScatterND

    # It is recommended to use Enum for string ONNX attributes.
    class ReductionOnnxAttr(Enum):
        NONE = "none"
        ADD = "add"
        MUL = "mul"
    
    
    class OnnxScatterND(nn.Module, OnnxToTorchModuleWithCustomExport):
        def __init__(self, reduction: ReductionOnnxAttr):
            super().__init__()
            self._reduction = reduction
    
        # The following method should return ONNX attributes with their values as a dictionary.
        # The number of attributes, their names and values depend on opset version;
        # method should return correct set of attributes.
        # Note: add type-postfix for each key: reduction -> reduction_s, where s means "string".
        def _onnx_attrs(self, opset_version: int) -> Dict[str, Any]:
            onnx_attrs: Dict[str, Any] = {}
    
            # Here we handle opset versions < 16 where there is no "reduction" attribute.
            if opset_version < 16:
                if self._reduction != ReductionOnnxAttr.NONE:
                    raise ValueError(
                        "ScatterND from opset < 16 does not support"
                        f"reduction attribute != {ReductionOnnxAttr.NONE.value},"
                        f"got {self._reduction.value}"
                    )
                return onnx_attrs
    
            onnx_attrs["reduction_s"] = self._reduction.value
            return onnx_attrs
    
        def forward(
            self,
            data: torch.Tensor,
            indices: torch.Tensor,
            updates: torch.Tensor,
        ) -> torch.Tensor:
            def _forward():
                # ScatterND forward implementation...
                return output
    
            if torch.onnx.is_in_onnx_export():
                # Please follow our convention, args consists of:
                # forward function, operation type, operation inputs, operation attributes.
                onnx_attrs = self._onnx_attrs(opset_version=get_onnx_version())
                return DefaultExportToOnnx.export(
                    _forward, "ScatterND", data, indices, updates, onnx_attrs
                )
    
            return _forward()
    
    
    @add_converter(operation_type="ScatterND", version=11)
    @add_converter(operation_type="ScatterND", version=13)
    @add_converter(operation_type="ScatterND", version=16)
    def _(node: OnnxNode, graph: OnnxGraph) -> OperationConverterResult:
        node_attributes = node.attributes
        reduction = ReductionOnnxAttr(node_attributes.get("reduction", "none"))
        return OperationConverterResult(
            torch_module=OnnxScatterND(reduction=reduction),
            onnx_mapping=onnx_mapping_from_node(node=node),
        )
    

    Here we have used a trick to convert the model from torch back to ONNX by defining the custom _ScatterNDExportToOnnx.

    Opset version workaround

    Incase you are using a model with older opset, try the following workaround:

    ONNX Version Conversion - Official Docs

    import onnx
    from onnx import version_converter
    import torch
    from onnx2torch import convert
    
    # Load the ONNX model.
    model = onnx.load("model.onnx")
    # Convert the model to the target version.
    target_version = 13
    converted_model = version_converter.convert_version(model, target_version)
    # Convert to torch.
    torch_model = convert(converted_model)
    torch.save(torch_model, "model.pt")
    

    Note: use this only when the model does not convert to PyTorch using the existing opset version. Result might vary.

    Citation

    To cite onnx2torch use Cite this repository button, or:

    @misc{onnx2torch,
      title={onnx2torch},
      author={ENOT developers and Kalgin, Igor and Yanchenko, Arseny and Ivanov, Pyoter and Goncharenko, Alexander},
      year={2021},
      howpublished={\url{https://enot.ai/}},
      note={Version: x.y.z}
    }
    

    Acknowledgments

    Thanks to Dmitry Chudakov @cakeofwar42 for his contributions.
    Special thanks to Andrey Denisov @denisovap2013 for the logo design.