onnx2torch


Nameonnx2torch JSON
Version 1.5.14 PyPI version JSON
download
home_pageNone
SummaryONNX to PyTorch converter
upload_time2024-04-02 10:52:33
maintainerNone
docs_urlNone
authorNone
requires_python>=3.6
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 onnx2torch 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/onnx2torch">
        <img src="https://badgen.net/pypi/v/onnx2torch" />
    </a>
    <a href="https://anaconda.org/conda-forge/onnx2torch">
        <img src="https://img.shields.io/conda/vn/conda-forge/onnx2torch" />
    </a>
    <a href="https://pypi.org/project/onnx2torch">
        <img src="https://img.shields.io/github/license/ENOT-AutoDL/onnx2torch?color=blue" />
    </a>
    <a href="https://pypi.org/project/onnx2torch">
        <img src="https://img.shields.io/pypi/dm/onnx2torch?color=blue" />
    </a>
    <a href="https://github.com/ENOT-AutoDL/onnx2torch/stargazers">
        <img src="https://img.shields.io/github/stars/ENOT-AutoDL/onnx2torch.svg?style=social&label=Star&maxAge=2592000" />
    </a>
    <br>
    <a href="https://github.com/psf/black">
        <img src="https://img.shields.io/badge/code%20style-black-black?color=blue" />
    </a>
    <a href="https://github.com/pre-commit/pre-commit">
        <img src="https://img.shields.io/badge/pre--commit-enabled-blue?logo=pre-commit" />
    </a>
    <a href="https://conventionalcommits.org">
        <img src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white&color=blue" />
    </a>
</p>

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](https://github.com/ENOT-AutoDL/onnx2torch/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 PyTorch [here](https://github.com/ENOT-AutoDL/onnx2torch/discussions).

## Installation

```bash
pip install onnx2torch
```

or

```bash
conda install -c conda-forge onnx2torch
```

## Usage

Below you can find some examples of use.

### Convert

```python
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.

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

## Models

We have tested the following models:

Segmentation models:

- [x] DeepLabV3+
- [x] DeepLabV3 ResNet-50 (TorchVision)
- [x] HRNet
- [x] UNet (TorchVision)
- [x] FCN ResNet-50 (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] ResNet-18
- [x] ResNet-50
- [x] MobileNetV2
- [x] MobileNetV3 Large
- [x] EfficientNet-B{0, 1, 2, 3}
- [x] WideResNet-50
- [x] ResNext-50
- [x] VGG-16
- [x] GoogLeNet
- [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 onnx2torch 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](./onnx2torch/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](./onnx2torch/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

Incase 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 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")
```

</details>

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](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": "onnx2torch",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": "AI, onnx, torch, onnx2torch, converters",
    "author": null,
    "author_email": "ENOT LLC <enot@enot.ai>",
    "download_url": "https://files.pythonhosted.org/packages/8d/53/1144a76a50b2c62b4d1b1ffd1183017b1dd772707595372bf61785d89c03/onnx2torch-1.5.14.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/onnx2torch\">\n        <img src=\"https://badgen.net/pypi/v/onnx2torch\" />\n    </a>\n    <a href=\"https://anaconda.org/conda-forge/onnx2torch\">\n        <img src=\"https://img.shields.io/conda/vn/conda-forge/onnx2torch\" />\n    </a>\n    <a href=\"https://pypi.org/project/onnx2torch\">\n        <img src=\"https://img.shields.io/github/license/ENOT-AutoDL/onnx2torch?color=blue\" />\n    </a>\n    <a href=\"https://pypi.org/project/onnx2torch\">\n        <img src=\"https://img.shields.io/pypi/dm/onnx2torch?color=blue\" />\n    </a>\n    <a href=\"https://github.com/ENOT-AutoDL/onnx2torch/stargazers\">\n        <img src=\"https://img.shields.io/github/stars/ENOT-AutoDL/onnx2torch.svg?style=social&label=Star&maxAge=2592000\" />\n    </a>\n    <br>\n    <a href=\"https://github.com/psf/black\">\n        <img src=\"https://img.shields.io/badge/code%20style-black-black?color=blue\" />\n    </a>\n    <a href=\"https://github.com/pre-commit/pre-commit\">\n        <img src=\"https://img.shields.io/badge/pre--commit-enabled-blue?logo=pre-commit\" />\n    </a>\n    <a href=\"https://conventionalcommits.org\">\n        <img src=\"https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white&color=blue\" />\n    </a>\n</p>\n\nonnx2torch is an ONNX to PyTorch converter.\nOur converter:\n\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/ENOT-AutoDL/onnx2torch/issues)!\nAnd 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 PyTorch [here](https://github.com/ENOT-AutoDL/onnx2torch/discussions).\n\n## Installation\n\n```bash\npip install onnx2torch\n```\n\nor\n\n```bash\nconda install -c conda-forge onnx2torch\n```\n\n## Usage\n\nBelow you can find some examples of use.\n\n### Convert\n\n```python\nimport onnx\nimport torch\nfrom onnx2torch 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\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.0e-7))\n```\n\n## Models\n\nWe have tested the following models:\n\nSegmentation models:\n\n- [x] DeepLabV3+\n- [x] DeepLabV3 ResNet-50 (TorchVision)\n- [x] HRNet\n- [x] UNet (TorchVision)\n- [x] FCN ResNet-50 (TorchVision)\n- [x] LRASPP MobileNetV3 (TorchVision)\n\nDetection from MMdetection:\n\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\n- [x] ResNet-18\n- [x] ResNet-50\n- [x] MobileNetV2\n- [x] MobileNetV3 Large\n- [x] EfficientNet-B{0, 1, 2, 3}\n- [x] WideResNet-50\n- [x] ResNext-50\n- [x] VGG-16\n- [x] GoogLeNet\n- [x] MnasNet\n- [x] RegNet\n\nTransformers:\n\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 onnx2torch with new ONNX operation, that supported by both PyTorch and ONNX\n\n<details>\n<summary>and has the same behaviour</summary>\n\nAn example of such a module is [Relu](./onnx2torch/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\n</details>\n\n<details>\n<summary>but has different behaviour</summary>\n\nAn example of such a module is [ScatterND](./onnx2torch/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(\n                _forward, \"ScatterND\", data, indices, updates, onnx_attrs\n            )\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```\n\nHere we have used a trick to convert the model from torch back to ONNX by defining the custom `_ScatterNDExportToOnnx`.\n\n</details>\n\n## Opset version workaround\n\nIncase 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 onnx2torch 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 onnx2torch use `Cite this repository` button, or:\n\n```\n@misc{onnx2torch,\n  title={onnx2torch},\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": "1.5.14",
    "project_urls": {
        "homepage": "https://enot.ai",
        "repository": "https://github.com/ENOT-AutoDL/onnx2torch"
    },
    "split_keywords": [
        "ai",
        " onnx",
        " torch",
        " onnx2torch",
        " converters"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f5f906ba0ae26a0a7beb3ae94bf6561db64ae00aae3db2402bbc762e8181e0aa",
                "md5": "eac0b8149c1e4110a396e7ea27b0fab5",
                "sha256": "bf34be63533ceac8def0504545a04f223c047bd1297d5e734005576df88cf305"
            },
            "downloads": -1,
            "filename": "onnx2torch-1.5.14-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "eac0b8149c1e4110a396e7ea27b0fab5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 80088,
            "upload_time": "2024-04-02T10:51:37",
            "upload_time_iso_8601": "2024-04-02T10:51:37.710143Z",
            "url": "https://files.pythonhosted.org/packages/f5/f9/06ba0ae26a0a7beb3ae94bf6561db64ae00aae3db2402bbc762e8181e0aa/onnx2torch-1.5.14-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8d531144a76a50b2c62b4d1b1ffd1183017b1dd772707595372bf61785d89c03",
                "md5": "aa8474f86cfe60f9d094e5f562daca51",
                "sha256": "f7185ffe3030410c34d579769bfcefcdce3e23a902e0f8b5472d3d0aae794740"
            },
            "downloads": -1,
            "filename": "onnx2torch-1.5.14.tar.gz",
            "has_sig": false,
            "md5_digest": "aa8474f86cfe60f9d094e5f562daca51",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 49607,
            "upload_time": "2024-04-02T10:52:33",
            "upload_time_iso_8601": "2024-04-02T10:52:33.007821Z",
            "url": "https://files.pythonhosted.org/packages/8d/53/1144a76a50b2c62b4d1b1ffd1183017b1dd772707595372bf61785d89c03/onnx2torch-1.5.14.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-02 10:52:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ENOT-AutoDL",
    "github_project": "onnx2torch",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "onnx2torch"
}
        
Elapsed time: 0.24058s