Skip to main content

PyTorch to ONNX Exporter

PyPI version

Standalone native ONNX exporter synchronized with the modern torch.export-based PyTorch exporter. Development follows PyTorch 2.15 and requires Python 3.11+. Compatibility CI tests the stable PyTorch releases published in the past year: 2.10.0, 2.11.0, 2.12.0, 2.12.1, 2.13.0, 2.14.0, 2.14.1 and 2.15.0. Installation preserves your chosen PyTorch version. Other versions may work; unvalidated or incompatible installations receive an actionable warning once. This project is experimental.

Exporter releases use the current development PyTorch major/minor version and increment their own patch number for each release; see AGENTS.md.

Release notes for 2.15.0 describe the version transition and runtime boundaries.

Installation

pip install --upgrade torch-onnx

Install onnxruntime as well to execute or numerically verify exported ONNXProgram instances locally.

Quick start

torch_onnx.export returns a torch.onnx.ONNXProgram (also exposed as torch_onnx.ONNXProgram) targeting opset 28 with graph optimization enabled by default:

import torch
import torch_onnx

model = torch.nn.Sequential(torch.nn.Linear(32, 16), torch.nn.ReLU()).eval()
x = torch.randn(4, 8, 32)

onnx_program = torch_onnx.export(model, (x,))
onnx_program.save("model.onnx")

# Execute with ONNX Runtime and compare against the captured PyTorch program
outputs = onnx_program(x)
torch_onnx.testing.assert_onnx_program(onnx_program)
onnx_program.release()

Hugging Face Transformers

torch_onnx.patch_torch() supports Transformers’ OnnxExporter, including its custom translations and export patches. See integration and CI coverage for forward and generation exports, dynamic shapes, and saving/reloading. The native implementation audit records operator implementations and measured performance.

Dynamic shapes

Explicit constraints with torch.export.Dim

Use torch.export.Dim (or string axis names / torch.export.Dim.DYNAMIC) to mark variable dimensions:

import torch
import torch_onnx


class MLP(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.net = torch.nn.Sequential(torch.nn.Linear(32, 16), torch.nn.ReLU())

    def forward(self, x):
        return self.net(x)


model = MLP().eval()
x = torch.randn(4, 8, 32)

batch = torch.export.Dim("batch", min=1, max=64)
seq_len = torch.export.Dim("seq_len", min=1)

onnx_program = torch_onnx.export(
    model,
    (x,),
    input_names=["x"],
    output_names=["y"],
    dynamic_shapes={"x": {0: batch, 1: seq_len}},
)
onnx_program.save("mlp_dynamic.onnx")

# String axis names are also accepted as shorthand:
# dynamic_shapes=({0: "batch", 1: "seq_len"},)
torch_onnx.testing.assert_onnx_program(onnx_program, args=(torch.randn(7, 13, 32),))
onnx_program.release()

Automatic inference with InputObserver

InputObserver records sample forward calls and infers dynamic_shapes and export arguments automatically:

observer = torch_onnx.InputObserver()
with observer(model):
    model(torch.randn(2, 8, 32))
    model(torch.randn(5, 12, 32))

onnx_program = torch_onnx.export(
    model,
    observer.infer_arguments(),
    dynamic_shapes=observer.infer_dynamic_shapes(),
)
onnx_program.save("mlp_observed.onnx")
onnx_program.release()

Common workflows

Opset selection, verification, and diagnostics

onnx_program = torch_onnx.export(
    model,
    (x,),
    opset_version=24,
    verify=True,  # numerically check outputs during export
    report=True,  # write an export report to artifacts_dir
)
ref_outputs = onnx_program.call_reference(x)  # evaluate with the ONNX reference runtime
onnx_program.release()

Pass profile=True (requires pyinstrument) to capture an HTML timing profile alongside the export report.

Fake tensors and deferred weights for large models

Export without materializing full weights in memory by disabling eager optimization until real weights are applied:

from torch._subclasses.fake_tensor import FakeTensorMode

state_dict = model.state_dict()
with FakeTensorMode():
    fake_model = MLP().eval()
    fake_x = torch.randn(4, 8, 32)
    onnx_program = torch_onnx.export(fake_model, (fake_x,), optimize=False)

onnx_program.apply_weights(state_dict)
onnx_program.optimize()
onnx_program.save("large_model.onnx", external_data=True)
onnx_program.release()

ExportedProgram conversion and torch.onnx patching

import onnx_ir as ir

# Convert an existing ExportedProgram directly to an onnx_ir.Model
exported = torch.export.export(model, (x,))
torch_onnx.analyze(exported)
ir_model = torch_onnx.exported_program_to_ir(exported)
proto = ir.to_proto(ir_model)

# Route torch.onnx.export calls to torch_onnx
torch_onnx.patch_torch()
onnx_program = torch.onnx.export(model, (x,))
onnx_program.save("patched.onnx")
onnx_program.release()
torch_onnx.unpatch_torch()

Custom operator translations

Register native ONNX IR translations globally with TranslationContext. Native translations own type promotion and must cast mismatched tensor inputs explicitly:

@torch_onnx.register_custom_translation(torch.ops.aten.add.Tensor)
def custom_add(op: torch_onnx.TranslationContext, self, other, alpha=1):
    if alpha != 1:
        other = op.Mul(other, alpha)
    return op.Add(self, other)


torch_onnx.unregister_custom_translation(torch.ops.aten.add.Tensor)

Use op.constant(value, dtype=...) to create explicitly typed constants. It shares the builder's graph-local constant cache. Native nodes receive incremental dtype and symbolic shape inference through onnx-shape-inference, including shape-tensor propagation between operations. Missing rules or incomplete metadata leave values partially inferred. Failed inference attempts roll back metadata and propagated shape data before logging a debug diagnostic. Translations still own tensor casts and type promotion. Construct nested graphs with op.builder.subgraph(graph) so they share this export's symbol allocation and captured shape data while retaining separate constant caches. When constructing graphs incrementally, declare input shapes before inference or use builder.reserve_symbol_names(...) to reserve symbols for graphs built later.

For per-export overrides, custom_translation_table accepts ONNX Script functions and takes precedence over global native registrations, which override built-in translations. PyTorch's torch.onnx.ops.symbolic and symbolic_multi_out are supported through both export entry points; torch_onnx.ops also re-exports these APIs. See the custom-domain example and CI coverage.

Limitations and documentation

  • Modern exporter only: dynamo=False, the legacy TorchScript exporter, and pre-0.2 dynamo_export / ExportOptions are unsupported. Use unpatched torch.onnx.export(..., dynamo=False) when legacy export is required.
  • Python scalar inputs: Preserved in ONNX input order for ONNXProgram callable compatibility, though torch.export specializes scalar values and Python control flow during capture.
  • Opset support and custom-opset extensibility — built-in opsets 18–29, custom domains, and unbounded opset targets.
  • Recovered regression inventory — migrated PyTorch ONNX regression suites.
  • Upstream synchronization and migration inventory — pinned PyTorch commits, operator coverage, and architecture details.

Metadata

Release files for torch-onnx 2.15.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for torch-onnx 2.15.0
File Size Uploaded Provenance Actions
torch_onnx-2.15.0.tar.gz 200.2 kB With provenance Details for torch_onnx-2.15.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for torch-onnx 2.15.0
File Interpreter ABI Platform Actions
torch_onnx-2.15.0-py3-none-any.whl Python 3 none any Details for torch_onnx-2.15.0-py3-none-any.whl

Total release size: 424.3 kB

Release files / torch_onnx-2.15.0.tar.gz

Download URL torch_onnx-2.15.0.tar.gz
Size 200.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ab7b54ec43964e415a0268f0337c0770fdabeb40d3bf78f7ac940faf9ccd76cc
BLAKE2b-256 checksum
How to use checksums
6690f31f4b743cc4e44e5089c1e262c56f8286197d06c1d5bab3e1c80cc2d4bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / torch_onnx-2.15.0-py3-none-any.whl

Download URL torch_onnx-2.15.0-py3-none-any.whl
Size 224.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c7eff1565b201b4a0699a6990e85a094c5b10df5f49773a9f98c01060f2aeb61
BLAKE2b-256 checksum
How to use checksums
e85e3b408b78c202f380898147ea584aa8378dfd4b8cfdb8d159da546632bfa4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for torch-onnx 2.15.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for torch_onnx-2.15.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.15.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page