{"id":7462,"library":"onnx2torch","title":"ONNX to PyTorch Converter","description":"onnx2torch is a Python library designed to convert ONNX (Open Neural Network Exchange) models into PyTorch models. It enables users to leverage existing ONNX models within the PyTorch ecosystem, facilitating migration and interoperability between frameworks. The current stable version is 1.6.0, with an active release cadence, typically every few months.","status":"active","version":"1.6.0","language":"en","source_language":"en","source_url":"https://github.com/bhky/onnx2torch","tags":["onnx","pytorch","model conversion","deep learning","machine learning"],"install":[{"cmd":"pip install onnx2torch","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Runtime for converted PyTorch models and core tensor operations.","package":"torch","optional":false},{"reason":"Required for parsing ONNX model files.","package":"onnx","optional":false},{"reason":"Used for internal array operations during conversion.","package":"numpy","optional":false}],"imports":[{"note":"The `convert` function was moved to the top-level `onnx2torch` package in version 1.0.0. Older versions (<1.0.0) required importing from `onnx2torch.converter`.","wrong":"from onnx2torch.converter import convert","symbol":"convert","correct":"from onnx2torch import convert"}],"quickstart":{"code":"import torch\nfrom onnx2torch import convert\nimport os\n\n# Define paths for dummy model\nonnx_model_path = 'dummy_model.onnx'\n\ntry:\n    # 1. Create a dummy PyTorch model and export it to ONNX\n    class SimpleModel(torch.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.linear = torch.nn.Linear(10, 2)\n\n        def forward(self, x):\n            return self.linear(x)\n\n    dummy_torch_model = SimpleModel()\n    dummy_input = torch.randn(1, 10) # Batch size 1, 10 features\n\n    torch.onnx.export(dummy_torch_model, dummy_input, onnx_model_path, \n                       opset_version=11, input_names=['input'], output_names=['output'],\n                       do_constant_folding=True, # Recommended for stable ONNX\n                       dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}})\n    print(f\"Dummy ONNX model saved to {onnx_model_path}\")\n\n    # 2. Convert the ONNX model to a PyTorch model using onnx2torch\n    torch_model_converted = convert(onnx_model_path)\n    print(\"ONNX model converted to PyTorch successfully.\")\n\n    # 3. Perform inference with the converted model\n    inference_input = torch.randn(2, 10) # Example: batch size 2\n    torch_model_converted.eval() # Set to evaluation mode\n    with torch.no_grad():\n        output = torch_model_converted(inference_input)\n    \n    print(f\"Input shape for inference: {inference_input.shape}\")\n    print(f\"Output shape from converted model: {output.shape}\")\n\n    # (Optional) Verify output matches original model if possible\n    # original_output = dummy_torch_model(inference_input)\n    # print(f\"Original model output shape: {original_output.shape}\")\n    # assert torch.allclose(output, original_output, atol=1e-5), \"Outputs do not match!\"\n    # print(\"Outputs of original and converted model match (within tolerance).\")\n\nfinally:\n    # Clean up the dummy ONNX file\n    if os.path.exists(onnx_model_path):\n        os.remove(onnx_model_path)\n        print(f\"Cleaned up {onnx_model_path}\")\n","lang":"python","description":"This quickstart demonstrates the full cycle of using `onnx2torch`. It starts by creating a dummy PyTorch model, exporting it to an ONNX file, converting that ONNX file back into a PyTorch model using `onnx2torch.convert`, and finally running inference with the newly converted model to show its usage."},"warnings":[{"fix":"Update your import statement to `from onnx2torch import convert`. If migrating from pre-1.0 versions, carefully review the new `convert` function signature and API changes in the official documentation.","message":"The primary conversion function signature and its import path underwent significant changes in version 1.0.0. The `convert` function is now directly available from the top-level `onnx2torch` package, and its arguments might differ from older versions.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"Refer to the `onnx2torch` GitHub repository for an up-to-date list of supported ONNX operators. You may need to modify your ONNX model to use only supported operators or explore alternative conversion methods for specific unsupported operations.","message":"Not all ONNX operators are currently implemented or supported by `onnx2torch`. Attempting to convert an ONNX model with unsupported operators will result in an `UnsupportedOperatorException`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Whenever possible, export your ONNX model with fixed input shapes, or use known fixed-size inputs during conversion and inference. If dynamic shapes are critical, perform thorough testing with various input dimensions after conversion.","message":"Models with dynamic input shapes may not always be handled correctly by `onnx2torch`, leading to conversion failures or incorrect runtime behavior in the converted PyTorch model.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure that the `opset_version` specified when exporting your ONNX model is compatible with the `onnx2torch` version you are using. Experiment with different `opset_version` values (e.g., 11, 13, 17) if you encounter conversion failures.","message":"Compatibility issues can arise due to the ONNX `opset_version` used during model export. An `opset_version` mismatch with `onnx2torch`'s internal operator definitions can cause conversion errors.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Check the `onnx2torch` documentation or GitHub for the list of supported ONNX operators. You may need to preprocess your ONNX model to remove or replace unsupported operators, or simplify the model graph.","cause":"The ONNX model contains an operator that `onnx2torch` does not currently support or recognize.","error":"onnx2torch.exception.UnsupportedOperatorException: Unsupported ONNX operator: SomeOperatorName"},{"fix":"Verify the expected input shape of your converted model. If the ONNX model used dynamic axes, ensure your inference input tensors adhere to the model's flexible dimensions. Double-check batch sizes, channels, and spatial dimensions.","cause":"The input tensor provided to the converted PyTorch model does not match the expected shape. This often happens with dynamic axes or incorrect input dimensions during inference.","error":"RuntimeError: shape '[-1, 3, 224, 224]' is invalid for input of size 1x3x224x224"},{"fix":"For `onnx2torch` versions older than 1.0.0, use `from onnx2torch.converter import convert`. For version 1.0.0 and newer, ensure your installation is up-to-date and the import is `from onnx2torch import convert`.","cause":"This error typically occurs if you are using an `onnx2torch` version older than 1.0.0 and attempting to import `convert` from the top-level package, or if there's a typo in the import statement.","error":"AttributeError: module 'onnx2torch' has no attribute 'convert'"}]}