onnx2torch2


Nameonnx2torch2 JSON
Version 2.0.0 PyPI version JSON
download
home_pageNone
SummaryONNX to PyTorch converter
upload_time2024-04-04 15:24:12
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseApache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 ENOT LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
keywords ai onnx torch onnx2torch2 converters
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">
  <img src="assets/logo/onnx2torch_light.png#gh-light-mode-only">
  <img src="assets/logo/onnx2torch_dark.png#gh-dark-mode-only">
</div>

<p align="center">
    <a href="https://pypi.org/project/onnx2torch2">
        <img src="https://badgen.net/pypi/v/onnx2torch2" />
    </a>
    <a href="https://anaconda.org/conda-forge/onnx2torch2">
        <img src="https://img.shields.io/conda/vn/conda-forge/onnx2torch2" />
    </a>
    <a href="https://pypi.org/project/onnx2torch2">
        <img src="https://badgen.net/pypi/license/onnx2torch2" />
    </a>
    <a href="https://github.com/psf/black">
        <img src="https://img.shields.io/badge/code%20style-black-black" />
    </a>
    <a href="https://pypi.org/project/onnx2torch2">
        <img src="https://img.shields.io/pypi/dm/onnx2torch2" />
    </a>
    <a href="https://github.com/untetherai/onnx2torch2/stargazers">
        <img src="https://img.shields.io/github/stars/untetherai/onnx2torch2.svg?style=social&label=Star&maxAge=2592000" />
    </a>
</p>

onnx2torch2 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](https://github.com/untetherai/onnx2torch2/issues)! 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](https://github.com/untetherai/onnx2torch2/discussions).

## Installation

```bash
pip install .
```

## Usage

Below you can find some examples of use.

### Convert

```python
import onnx
import torch
from onnx2torch2 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.

```python
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:
- [x] DeepLabv3plus
- [x] DeepLabv3 resnet50 (torchvision)
- [x] HRNet
- [x] UNet (torchvision)
- [x] FCN resnet50 (torchvision)
- [x] lraspp mobilenetv3 (torchvision)

Detection  from MMdetection:
- [x] [SSDLite with MobileNetV2 backbone](https://github.com/open-mmlab/mmdetection)
- [x] [RetinaNet R50](https://github.com/open-mmlab/mmdetection)
- [x] [SSD300 with VGG backbone](https://github.com/open-mmlab/mmdetection)
- [x] [Yolov3_d53](https://github.com/open-mmlab/mmdetection)
- [x] [Yolov5](https://github.com/ultralytics/yolov5)

Classification from __torchvision__:
- [x] Resnet18
- [x] Resnet50
- [x] MobileNet v2
- [x] MobileNet v3 large
- [x] EfficientNet_b{0, 1, 2, 3}
- [x] WideResNet50
- [x] ResNext50
- [x] VGG16
- [x] GoogleleNet
- [x] MnasNet
- [x] RegNet

Transformers:
- [x] Vit
- [x] Swin
- [x] GPT-J

#### :page_facing_up: List of currently supported operations can be founded [here](operators.md).

## How to add new operations to converter

Here we show how to extend onnx2torch2 with new ONNX operation, that supported by both PyTorch and ONNX
<details>
<summary>and has the same behaviour</summary>

An example of such a module is [Relu](./onnx2torch2/node_converters/activations.py)

```python
@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.
</details>

<details>
<summary>but has different behaviour</summary>

An example of such a module is [ScatterND](./onnx2torch2/node_converters/scatter_nd.py)

```python
# 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``.
</details>

## Opset version workaround

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

[ONNX Version Conversion - Official Docs](https://github.com/onnx/onnx/blob/main/docs/PythonAPIOverview.md#converting-version-of-an-onnx-model-within-default-domain-aionnx)

<details>
<summary>Example</summary>

```python
import onnx
from onnx import version_converter
import torch
from onnx2torch2 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')
```

</details>

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

## Citation

To cite onnx2torch2 use `Cite this repository` button, or:
```
@misc{onnx2torch2,
  title={onnx2torch2},
  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](https://github.com/cakeofwar42) for his contributions.\
Special thanks to Andrey Denisov [@denisovap2013](https://github.com/denisovap2013) for the logo design.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "onnx2torch2",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "AI, onnx, torch, onnx2torch2, converters",
    "author": null,
    "author_email": "untetherai <info@untether.ai>",
    "download_url": "https://files.pythonhosted.org/packages/80/ef/e6d69d0b0e85835bc54a5064c3cd8e3dc8ae7ab284dc06f2746c38550f97/onnx2torch2-2.0.0.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n  <img src=\"assets/logo/onnx2torch_light.png#gh-light-mode-only\">\n  <img src=\"assets/logo/onnx2torch_dark.png#gh-dark-mode-only\">\n</div>\n\n<p align=\"center\">\n    <a href=\"https://pypi.org/project/onnx2torch2\">\n        <img src=\"https://badgen.net/pypi/v/onnx2torch2\" />\n    </a>\n    <a href=\"https://anaconda.org/conda-forge/onnx2torch2\">\n        <img src=\"https://img.shields.io/conda/vn/conda-forge/onnx2torch2\" />\n    </a>\n    <a href=\"https://pypi.org/project/onnx2torch2\">\n        <img src=\"https://badgen.net/pypi/license/onnx2torch2\" />\n    </a>\n    <a href=\"https://github.com/psf/black\">\n        <img src=\"https://img.shields.io/badge/code%20style-black-black\" />\n    </a>\n    <a href=\"https://pypi.org/project/onnx2torch2\">\n        <img src=\"https://img.shields.io/pypi/dm/onnx2torch2\" />\n    </a>\n    <a href=\"https://github.com/untetherai/onnx2torch2/stargazers\">\n        <img src=\"https://img.shields.io/github/stars/untetherai/onnx2torch2.svg?style=social&label=Star&maxAge=2592000\" />\n    </a>\n</p>\n\nonnx2torch2 is an ONNX to PyTorch converter.\nOur converter:\n* Is easy to use \u2013 Convert the ONNX model with the function call ``convert``;\n* Is easy to extend \u2013 Write your own custom layer in PyTorch and register it with ``@add_converter``;\n* Convert back to ONNX \u2013 You can convert the model back to ONNX using the ``torch.onnx.export`` function.\n\nIf you find an issue, please [let us know](https://github.com/untetherai/onnx2torch2/issues)! And feel free to create merge requests.\n\nPlease note that this converter covers only a limited number of PyTorch / ONNX models and operations.\nLet us know which models you use or want to convert from onnx to torch [here](https://github.com/untetherai/onnx2torch2/discussions).\n\n## Installation\n\n```bash\npip install .\n```\n\n## Usage\n\nBelow you can find some examples of use.\n\n### Convert\n\n```python\nimport onnx\nimport torch\nfrom onnx2torch2 import convert\n\n# Path to ONNX model\nonnx_model_path = '/some/path/mobile_net_v2.onnx'\n# You can pass the path to the onnx model to convert it or...\ntorch_model_1 = convert(onnx_model_path)\n\n# Or you can load a regular onnx model and pass it to the converter\nonnx_model = onnx.load(onnx_model_path)\ntorch_model_2 = convert(onnx_model)\n```\n\n### Execute\n\nWe can execute the returned ``PyTorch model`` in the same way as the original torch model.\n\n```python\nimport onnxruntime as ort\n# Create example data\nx = torch.ones((1, 2, 224, 224)).cuda()\n\nout_torch = torch_model_1(x)\n\nort_sess = ort.InferenceSession(onnx_model_path)\noutputs_ort = ort_sess.run(None, {'input': x.numpy()})\n\n# Check the Onnx output against PyTorch\nprint(torch.max(torch.abs(outputs_ort - out_torch.detach().numpy())))\nprint(np.allclose(outputs_ort, out_torch.detach().numpy(), atol=1.e-7))\n```\n\n## Models\n\nWe have tested the following models:\n\nSegmentation models:\n- [x] DeepLabv3plus\n- [x] DeepLabv3 resnet50 (torchvision)\n- [x] HRNet\n- [x] UNet (torchvision)\n- [x] FCN resnet50 (torchvision)\n- [x] lraspp mobilenetv3 (torchvision)\n\nDetection  from MMdetection:\n- [x] [SSDLite with MobileNetV2 backbone](https://github.com/open-mmlab/mmdetection)\n- [x] [RetinaNet R50](https://github.com/open-mmlab/mmdetection)\n- [x] [SSD300 with VGG backbone](https://github.com/open-mmlab/mmdetection)\n- [x] [Yolov3_d53](https://github.com/open-mmlab/mmdetection)\n- [x] [Yolov5](https://github.com/ultralytics/yolov5)\n\nClassification from __torchvision__:\n- [x] Resnet18\n- [x] Resnet50\n- [x] MobileNet v2\n- [x] MobileNet v3 large\n- [x] EfficientNet_b{0, 1, 2, 3}\n- [x] WideResNet50\n- [x] ResNext50\n- [x] VGG16\n- [x] GoogleleNet\n- [x] MnasNet\n- [x] RegNet\n\nTransformers:\n- [x] Vit\n- [x] Swin\n- [x] GPT-J\n\n#### :page_facing_up: List of currently supported operations can be founded [here](operators.md).\n\n## How to add new operations to converter\n\nHere we show how to extend onnx2torch2 with new ONNX operation, that supported by both PyTorch and ONNX\n<details>\n<summary>and has the same behaviour</summary>\n\nAn example of such a module is [Relu](./onnx2torch2/node_converters/activations.py)\n\n```python\n@add_converter(operation_type='Relu', version=6)\n@add_converter(operation_type='Relu', version=13)\n@add_converter(operation_type='Relu', version=14)\ndef _(node: OnnxNode, graph: OnnxGraph) -> OperationConverterResult:\n    return OperationConverterResult(\n        torch_module=nn.ReLU(),\n        onnx_mapping=onnx_mapping_from_node(node=node),\n    )\n```\n\nHere we have registered an operation named ``Relu`` for opset versions 6, 13, 14.\nNote that the ``torch_module`` argument in ``OperationConverterResult`` must be a torch.nn.Module, not just a callable object!\nIf Operation's behaviour differs from one opset version to another, you should implement it separately.\n</details>\n\n<details>\n<summary>but has different behaviour</summary>\n\nAn example of such a module is [ScatterND](./onnx2torch2/node_converters/scatter_nd.py)\n\n```python\n# It is recommended to use Enum for string ONNX attributes.\nclass ReductionOnnxAttr(Enum):\n    NONE = 'none'\n    ADD = 'add'\n    MUL = 'mul'\n\n\nclass OnnxScatterND(nn.Module, OnnxToTorchModuleWithCustomExport):\n    def __init__(self, reduction: ReductionOnnxAttr):\n        super().__init__()\n        self._reduction = reduction\n\n    # The following method should return ONNX attributes with their values as a dictionary.\n    # The number of attributes, their names and values depend on opset version;\n    # method should return correct set of attributes.\n    # Note: add type-postfix for each key: reduction -> reduction_s, where s means \"string\".\n    def _onnx_attrs(self, opset_version: int) -> Dict[str, Any]:\n        onnx_attrs: Dict[str, Any] = {}\n\n        # Here we handle opset versions < 16 where there is no \"reduction\" attribute.\n        if opset_version < 16:\n            if self._reduction != ReductionOnnxAttr.NONE:\n                raise ValueError(\n                    'ScatterND from opset < 16 does not support'\n                    f'reduction attribute != {ReductionOnnxAttr.NONE.value},'\n                    f'got {self._reduction.value}'\n                )\n            return onnx_attrs\n\n        onnx_attrs['reduction_s'] = self._reduction.value\n        return onnx_attrs\n\n    def forward(\n        self,\n        data: torch.Tensor,\n        indices: torch.Tensor,\n        updates: torch.Tensor,\n    ) -> torch.Tensor:\n        def _forward():\n            # ScatterND forward implementation...\n            return output\n\n        if torch.onnx.is_in_onnx_export():\n            # Please follow our convention, args consists of:\n            # forward function, operation type, operation inputs, operation attributes.\n            onnx_attrs = self._onnx_attrs(opset_version=get_onnx_version())\n            return DefaultExportToOnnx.export(_forward, 'ScatterND', data, indices, updates, onnx_attrs)\n\n        return _forward()\n\n\n@add_converter(operation_type='ScatterND', version=11)\n@add_converter(operation_type='ScatterND', version=13)\n@add_converter(operation_type='ScatterND', version=16)\ndef _(node: OnnxNode, graph: OnnxGraph) -> OperationConverterResult:\n    node_attributes = node.attributes\n    reduction = ReductionOnnxAttr(node_attributes.get('reduction', 'none'))\n    return OperationConverterResult(\n        torch_module=OnnxScatterND(reduction=reduction),\n        onnx_mapping=onnx_mapping_from_node(node=node),\n    )\n```\nHere we have used a trick to convert the model from torch back to ONNX by defining the custom ``_ScatterNDExportToOnnx``.\n</details>\n\n## Opset version workaround\n\nIn case you are using a model with older opset, try the following workaround:\n\n[ONNX Version Conversion - Official Docs](https://github.com/onnx/onnx/blob/main/docs/PythonAPIOverview.md#converting-version-of-an-onnx-model-within-default-domain-aionnx)\n\n<details>\n<summary>Example</summary>\n\n```python\nimport onnx\nfrom onnx import version_converter\nimport torch\nfrom onnx2torch2 import convert\n\n# Load the ONNX model.\nmodel = onnx.load('model.onnx')\n# Convert the model to the target version.\ntarget_version = 13\nconverted_model = version_converter.convert_version(model, target_version)\n# Convert to torch.\ntorch_model = convert(converted_model)\ntorch.save(torch_model, 'model.pt')\n```\n\n</details>\n\nNote: use this only when the model does not convert to PyTorch using the existing opset version. Result might vary.\n\n## Citation\n\nTo cite onnx2torch2 use `Cite this repository` button, or:\n```\n@misc{onnx2torch2,\n  title={onnx2torch2},\n  author={ENOT developers and Kalgin, Igor and Yanchenko, Arseny and Ivanov, Pyoter and Goncharenko, Alexander},\n  year={2021},\n  howpublished={\\url{https://enot.ai/}},\n  note={Version: x.y.z}\n}\n```\n\n## Acknowledgments\n\nThanks to Dmitry Chudakov [@cakeofwar42](https://github.com/cakeofwar42) for his contributions.\\\nSpecial thanks to Andrey Denisov [@denisovap2013](https://github.com/denisovap2013) for the logo design.\n",
    "bugtrack_url": null,
    "license": "Apache License Version 2.0, January 2004 http://www.apache.org/licenses/  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION  1. Definitions.  \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.  \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.  \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.  \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.  \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.  \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.  \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).  \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.  \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"  \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.  2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.  3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.  4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:  (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and  (b) You must cause any modified files to carry prominent notices stating that You changed the files; and  (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and  (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.  You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.  5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.  6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.  7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.  8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.  9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.  END OF TERMS AND CONDITIONS  APPENDIX: How to apply the Apache License to your work.  To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!)  The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives.  Copyright 2023 ENOT LLC  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ",
    "summary": "ONNX to PyTorch converter",
    "version": "2.0.0",
    "project_urls": {
        "Issues": "https://github.com/untetherai/onnx2torch2/issues",
        "Repository": "https://github.com/untetherai/onnx2torch2"
    },
    "split_keywords": [
        "ai",
        " onnx",
        " torch",
        " onnx2torch2",
        " converters"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "23382aff8dc531ba619066ca8f14569c8ef9aaf15de6a12f8a07f50a3fbe7d22",
                "md5": "87edc655b334a4864abbeb5569b162ef",
                "sha256": "26fef9a40d7ee1d76bda1c05b19d828560a8de60ee667fd06aefcb519197d5f9"
            },
            "downloads": -1,
            "filename": "onnx2torch2-2.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "87edc655b334a4864abbeb5569b162ef",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 80325,
            "upload_time": "2024-04-04T15:24:09",
            "upload_time_iso_8601": "2024-04-04T15:24:09.896556Z",
            "url": "https://files.pythonhosted.org/packages/23/38/2aff8dc531ba619066ca8f14569c8ef9aaf15de6a12f8a07f50a3fbe7d22/onnx2torch2-2.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "80efe6d69d0b0e85835bc54a5064c3cd8e3dc8ae7ab284dc06f2746c38550f97",
                "md5": "841c54df7587cb910ac39129bd548e47",
                "sha256": "93b162ac088f5169b2df31c70b7a91bac3a02c08a8451030f8cbbae22d1a0165"
            },
            "downloads": -1,
            "filename": "onnx2torch2-2.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "841c54df7587cb910ac39129bd548e47",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 49217,
            "upload_time": "2024-04-04T15:24:12",
            "upload_time_iso_8601": "2024-04-04T15:24:12.859466Z",
            "url": "https://files.pythonhosted.org/packages/80/ef/e6d69d0b0e85835bc54a5064c3cd8e3dc8ae7ab284dc06f2746c38550f97/onnx2torch2-2.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-04 15:24:12",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "untetherai",
    "github_project": "onnx2torch2",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "onnx2torch2"
}
        
Elapsed time: 0.30422s