{"id":4663,"library":"onnx2tf","title":"ONNX to TensorFlow/TFLite Converter","description":"onnx2tf is a versatile Python tool designed for converting ONNX model files into various target formats, including LiteRT, TFLite, TensorFlow SavedModel, PyTorch native code (nn.Module), TorchScript (.pt), state_dict (.pt), Exported Program (.pt2), and Dynamo ONNX. It also supports direct conversion from LiteRT to PyTorch. The library maintains a rapid release cadence, with version 2.4.0 being the latest stable release.","status":"active","version":"2.4.0","language":"python","source_language":"en","source_url":"https://github.com/PINTO0309/onnx2tf","tags":["onnx","tensorflow","pytorch","tflite","model conversion","machine learning"],"install":[{"cmd":"pip install onnx2tf","lang":"bash","label":"Default Install"}],"dependencies":[{"reason":"Required for ONNX model processing, core functionality.","package":"onnx","optional":false},{"reason":"Target format for conversion, essential for TensorFlow/TFLite outputs.","package":"tensorflow","optional":false},{"reason":"Required for PyTorch related conversions and for creating ONNX models from PyTorch.","package":"torch","optional":false},{"reason":"Used for direct TFLite backend conversions.","package":"flatbuffers","optional":false},{"reason":"Fundamental library for array operations in ML workflows.","package":"numpy","optional":false},{"reason":"Dependency for ONNX to TensorFlow conversion components.","package":"onnx_tf","optional":false},{"reason":"Used for serializing structured data, essential for model formats.","package":"protobuf","optional":false}],"imports":[{"symbol":"convert","correct":"import onnx2tf\n\n# ... then onnx2tf.convert(...)"}],"quickstart":{"code":"import onnx2tf\nimport torch\nimport torch.nn as nn\nimport os\n\n# 1. Define a simple PyTorch model\nclass SimpleModel(nn.Module):\n    def __init__(self):\n        super(SimpleModel, self).__init__()\n        self.conv = nn.Conv2d(3, 16, 3, 1, 1)\n\n    def forward(self, x):\n        return self.conv(x)\n\n# 2. Instantiate and export to ONNX\nmodel = SimpleModel()\ndummy_input = torch.randn(1, 3, 224, 224)\nonnx_file_path = \"simple_model.onnx\"\ntorch.onnx.export(\n    model,\n    dummy_input,\n    onnx_file_path,\n    opset_version=17,\n    input_names=[\"input\"],\n    output_names=[\"output\"],\n    dynamic_axes={\"input\": {0: \"batch_size\"}, \"output\": {0: \"batch_size\"}}\n)\nprint(f\"PyTorch model exported to {onnx_file_path}\")\n\n# 3. Convert ONNX to TensorFlow SavedModel\noutput_folder = \"./converted_tf_model\"\nos.makedirs(output_folder, exist_ok=True)\n\nonnx2tf.convert(\n    input_onnx_file_path=onnx_file_path,\n    output_folder_path=output_folder,\n    # For TFLite conversion, you might add:\n    # tflite_output_file_path=\"./converted_tf_model/model.tflite\"\n)\nprint(f\"ONNX model converted to TensorFlow SavedModel at {output_folder}\")\n\n# Clean up generated ONNX file\nos.remove(onnx_file_path)\n\n# To use a specific backend for TFLite (e.g., the deprecated tf_converter):\n# onnx2tf.convert(\n#     input_onnx_file_path=onnx_file_path,\n#     output_folder_path=\"./converted_tf_model_tfconv\",\n#     tflite_output_file_path=\"./converted_tf_model_tfconv/model.tflite\",\n#     tflite_backend='tf_converter'\n# )","lang":"python","description":"This quickstart demonstrates the end-to-end process of defining a simple PyTorch model, exporting it to ONNX format, and then using `onnx2tf` to convert the ONNX model into a TensorFlow SavedModel. It highlights the primary `onnx2tf.convert()` function and the necessary input/output paths."},"warnings":[{"fix":"If you require the `tf_converter` backend for TFLite, explicitly set `tflite_backend='tf_converter'` in your `onnx2tf.convert()` call or use the `--tflite_backend tf_converter` CLI option.","message":"Starting with v2.4.0, the default TFLite backend for `onnx2tf.convert()` and the CLI has switched from `tf_converter` to `flatbuffer_direct`. Code relying on the implicit `tf_converter` behavior for TFLite conversion will now use `flatbuffer_direct`.","severity":"breaking","affected_versions":">=2.4.0"},{"fix":"Update your conversion scripts to use the `flatbuffer_direct` backend, which is now the default, or keep an eye on release notes for its eventual removal if `tf_converter` is critical for your workflow.","message":"The `tf_converter` TFLite backend is deprecated starting from v2.4.0. While still available as an explicit option, users are encouraged to migrate to `flatbuffer_direct` as it may be removed in future versions.","severity":"deprecated","affected_versions":">=2.4.0"},{"fix":"Ensure your development environment uses Python 3.12 or a later version. You can manage Python versions using `pyenv` or `conda`.","message":"onnx2tf requires Python 3.12 or newer. Using older Python versions will lead to installation failures or runtime errors.","severity":"gotcha","affected_versions":">=2.3.18"},{"fix":"When performing integer quantization, ensure you provide calibration inputs explicitly rather than relying on the library to download them. Refer to the documentation for the `--calibration_data_path` or equivalent API parameters.","message":"Implicit network downloads for validation sample data have been removed since v2.3.17. For integer quantization (`-oiqt`), explicit calibration input mapping is now required.","severity":"gotcha","affected_versions":">=2.3.17"}],"env_vars":null,"search_vec":"'2.4.0':59 'also':42 'cadenc':56 'code':28 'convers':45,70 'convert':4,13 'design':11 'dict':33 'direct':44 'dynamo':39 'export':35 'file':16 'format':20 'includ':21 'latest':62 'learn':72 'librari':51 'litert':22,47 'machin':71 'maintain':52 'model':15,69 'nativ':27 'nn.module':29 'onnx':1,14,40,65 'onnx2tf':5 'program':36 'pt':31,34 'pt2':37 'python':9 'pytorch':26,49,67 'rapid':54 'releas':55,64 'savedmodel':25 'stabl':63 'state':32 'support':43 'target':19 'tensorflow':24,66 'tensorflow/tflite':3 'tflite':23,68 'tool':10 'torchscript':30 'various':18 'versatil':8 'version':58","created_at":"2026-04-12T14:02:17.449539+00:00","updated_at":"2026-04-17T14:36:43.790995+00:00","problems":[{"fix":"Use `simple-onnx-processing-tools` to preprocess the ONNX model and replace the unsupported operator with a combination of supported operations, or modify the original model's architecture to avoid the problematic operator.","cause":"The ONNX model contains an operator ('OP_NAME') that is not directly supported by onnx2tf or its underlying TensorFlow conversion mechanisms.","error":"ERROR: Unsupported ops: Counter({'OP_NAME': X})"},{"fix":"Fix dynamic input dimensions to a static size during conversion using the `-b` (batch size) or `-ois` (overwrite input shape) options in the `onnx2tf` command. For example, `-b 1` for a fixed batch size of 1.","cause":"The ONNX model has dynamic input dimensions (e.g., a batch size of `None` or other undefined dimensions), which TensorFlow's graph construction or `onnx2tf`'s internal shape calculations cannot resolve.","error":"ValueError: Cannot take the length of shape with unknown rank."},{"fix":"Ensure `ai_edge_litert` is installed in your Python environment. This typically happens automatically with `pip install onnx2tf`, but if not, install it explicitly: `pip install ai-edge-litert`. Also, verify TensorFlow and onnxruntime are installed.","cause":"A crucial dependency for onnx2tf, `ai_edge_litert`, which is part of its modern backend for direct TFLite conversion, is not installed or accessible in the environment.","error":"ModuleNotFoundError: No module named 'ai_edge_litert'"},{"fix":"Investigate the ONNX graph for problematic operations that alter tensor dimensions unexpectedly. Utilize `onnx2tf`'s options for channel transposition (`-kt` or `-kat`) or provide a parameter replacement JSON file (`-prf`) to manually specify correct transpositions or shape manipulations for the problematic layers.","cause":"A dimension mismatch occurs during a TensorFlow operation (like `Add` or `Concat`) within the converted graph, often stemming from incorrect tensor layout handling (e.g., NCHW in ONNX versus NHWC in TensorFlow) or complex shape transformations.","error":"ValueError: Exception encountered when calling layer \"tf.math.add_XX\" (type TFOpLambda). Dimensions must be equal, but are X and Y for '{{node ...}}' with input shapes: [shape1], [shape2]."},{"fix":"Install it using `pip install onnx2tf`, then ensure your terminal is in the correct environment or its installation directory is in your PATH.","cause":"The onnx2tf executable is not installed, not in the system's PATH, or the virtual environment where it's installed is not active.","error":"onnx2tf command not found"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"2.6.8","cli_name":"onnx2tf","cli_version":"","type":"library","homepage":null,"github":"https://github.com/PINTO0309/onnx2tf#readme","docs":"https://github.com/PINTO0309/onnx2tf#readme","changelog":null,"pypi":"https://pypi.org/project/onnx2tf/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["ai-ml","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-30","next_check":"2026-07-28","install_tag":null}}