Skip to main content

ONNX to PyTorch converter

Project description

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 torch here.

Installation

pip install onnx2torch

or

conda install -c conda-forge onnx2torch

Usage

Below you can find some examples of use.

Convert

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.e-7))

Models

We have tested the following models:

Segmentation models:

  • DeepLabv3plus
  • DeepLabv3 resnet50 (torchvision)
  • HRNet
  • UNet (torchvision)
  • FCN resnet50 (torchvision)
  • lraspp mobilenetv3 (torchvision)

Detection from MMdetection:

Classification from torchvision:

  • Resnet18
  • Resnet50
  • MobileNet v2
  • MobileNet v3 large
  • EfficientNet_b{0, 1, 2, 3}
  • WideResNet50
  • ResNext50
  • VGG16
  • GoogleleNet
  • 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

and has the same behaviour

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.

but has different behaviour

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

Example
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.

Acknowledgments

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

onnx2torch-1.5.11.tar.gz (47.7 kB view details)

Uploaded Source

Built Distribution

onnx2torch-1.5.11-py3-none-any.whl (78.1 kB view details)

Uploaded Python 3

File details

Details for the file onnx2torch-1.5.11.tar.gz.

File metadata

  • Download URL: onnx2torch-1.5.11.tar.gz
  • Upload date:
  • Size: 47.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.17

File hashes

Hashes for onnx2torch-1.5.11.tar.gz
Algorithm Hash digest
SHA256 5254522279fb15c2e3ccd33ca9104dbd08cf4e188341338b4a3aead50475c419
MD5 a0d1a6e3af4c5dfe28685d4cd3abcb3f
BLAKE2b-256 1f699de24894df64211ffed57dcc4a19729598f3a34e722d8a639ce0c8841730

See more details on using hashes here.

File details

Details for the file onnx2torch-1.5.11-py3-none-any.whl.

File metadata

  • Download URL: onnx2torch-1.5.11-py3-none-any.whl
  • Upload date:
  • Size: 78.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.17

File hashes

Hashes for onnx2torch-1.5.11-py3-none-any.whl
Algorithm Hash digest
SHA256 7dd22a7d2bd06a71d9cde1b38888fb6d2234e55ee1e28a16221f1fae8197acce
MD5 eb7d05d5c7dcc09c2c06499304199b43
BLAKE2b-256 9a18bd6e87bf2e6b0ccf98e9986d3fae0beba5b9ff67e30a4b393c595a99c2e9

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page