Exporting to ONNX

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page covers the PyTorch side of ONNX export: the arguments of torch.onnx.export, the object it returns, and how to debug a failed export. What ONNX is (graph, initialisers, IR version versus opset) and how to run and inspect the file with ONNX Runtime is explained once, for PyTorch, Keras and scikit-learn together, in ONNX & Model Interoperability; it is not repeated here. The exporter is built on torch.export, so every limitation of export (full graph, data-dependent control flow, static shapes unless declared) applies.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU), onnxscript 0.7, onnx 1.23 and ONNX Runtime 1.31 on 2026-10-31; with opset_version left at None the exporter wrote opset 20. The exporter needs the onnxscript package (pip install onnxscript onnx), which PyTorch does not install.

Installing the dependencies

The exporter needs the onnx and onnxscript packages (the latter expresses the operator translations). onnxruntime is separate and is only needed to run the model.

pip install --upgrade onnx onnxscript onnxruntime

A first export

import torch
from torch import nn


class Classifier(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.net = nn.Sequential(nn.Linear(8, 32), nn.ReLU(), nn.Linear(32, 3))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


model = Classifier().eval()
example = (torch.rand(4, 8),)

onnx_program = torch.onnx.export(
    model,
    example,
    dynamo=True,                 # the default since PyTorch 2.9
    input_names=["x"],
    output_names=["logits"],
)
onnx_program.save("classifier.onnx")

Notes:

  • Since PyTorch 2.9 dynamo=True is the default and selects the torch.export based exporter, which the documentation recommends. It tries an existing ExportedProgram as is, then torch.export.export(strict=False), then strict=True.

  • The call returns an ONNXProgram; with dynamo=True the argument f (a file name) is accepted only for backward compatibility and the documentation recommends calling save() on the result.

  • Only tensor arguments become graph inputs. Non-tensor arguments (Python numbers, strings, flags) are hard-coded into the exported model.

  • Put the model in eval() first so that dropout and batch normalisation are exported in inference behaviour.

  • Without dynamic_shapes the exported model keeps the shapes of the example inputs. A language model exported this way appears to accept only one sequence length.

Arguments that matter

Argument (dynamo=True) Meaning

dynamic_shapes

Which input dimensions may vary; same convention as torch.export. Replaces the old dynamic_axes.

opset_version

Target version of the default ai.onnx operator set. None uses the exporter’s recommended version. Match it to the oldest runtime you must support (see ONNX & Model Interoperability for the opset lag between ONNX and ONNX Runtime).

optimize

Constant folding and redundancy removal; True by default (since 2.7).

external_data

Store weights in a separate file; required when the weights exceed the 2 GB protobuf limit. Default True.

input_names, output_names

Names of the graph inputs and outputs, used by ONNX Runtime callers.

custom_translation_table

Mapping from an operator (for example torch.ops.aten.stft.default) to a function that builds the replacement subgraph with ONNX Script.

verify

Check the exported model against the original with ONNX Runtime.

report, dump_exported_program, artifacts_dir

Write a Markdown report of the export, dump the exported program, and choose where these files go.

profile

Profile the export process itself.

Dynamic shapes

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

onnx_program = torch.onnx.export(
    model,
    example,
    dynamic_shapes={"x": {0: batch}},     # parameter name of forward(); dimension 0 varies
    input_names=["x"],
    output_names=["logits"],
    dynamo=True,
)
print(onnx_program.model.graph.inputs[0].shape)   # first dimension shown as a symbol

onnx_program.rename_axes({onnx_program.model.graph.inputs[0].shape[0]: "batch"})
onnx_program.save("classifier_dynamic.onnx")

In the page’s own example, dynamic_shapes can also be written with plain strings, such as {0: "batch"}, and the exporter turns them into dimension names in the file. Use rename_axes to give symbolic dimensions stable, readable names; downstream tools often key on them. The older dynamic_axes argument belongs to the TorchScript exporter (dynamo=False) and is deprecated for the new path.

The ONNXProgram object

torch.onnx.export returns an ONNXProgram, which wraps the ONNX model and the originating exported program. Its documented members:

Member Purpose

model_proto

The in-memory onnx.ModelProto.

optimize()

In-place constant folding and redundancy removal.

save(path, include_initializers=True, keep_initializers_as_inputs=False, ...)

Serialise to a protobuf file; external data is used for models over 2 GB.

call_reference(*args)

Run the model on the reference backend, to compare with PyTorch without ONNX Runtime.

apply_weights(state_dict)

Replace placeholder (fake) or stale weights, for example after exporting under fake tensors.

initialize_inference_session(), compute_values(names, args), release()

Create an ONNX Runtime session, fetch named intermediate values, free the session.

rename_axes(mapping)

Rename symbolic dimensions.

The two save flags give four layouts: neither flag (no weights stored; attach them later), embedded weights (the default), embedded weights that can also be overridden at inference (both True), and a small file with the weights supplied at inference (include_initializers=False, keep_initializers_as_inputs=True).

Verifying the result

Always compare the ONNX model with the PyTorch model on realistic inputs; an export that loads can still differ numerically.

import numpy as np
import onnxruntime as ort
import torch

x = torch.rand(16, 8)
with torch.no_grad():
    expected = model(x).numpy()

session = ort.InferenceSession("classifier_dynamic.onnx", providers=["CPUExecutionProvider"])
(actual,) = session.run(None, {"x": x.numpy()})

np.testing.assert_allclose(expected, actual, rtol=1e-3, atol=1e-5)

Source: https://docs.pytorch.org/docs/stable/onnx_export.html (the numerical comparison itself is a standard check written for this page and is not copied from the tutorial)

The exporter can also check itself with verify=True. For model families that run with many input shapes, the page documents torch.onnx.InputObserver, which records the real inputs and outputs of a few runs, infers dynamic_shapes and example arguments from them, and then compares the ONNX model with the recording through check_discrepancies. The recommended tolerance is about 1e-4 (absolute) for float32 and about 1e-2 for float16.

observer = torch.onnx.InputObserver()
with observer(model):
    model(torch.rand(4, 8))
    model(torch.rand(16, 8))

onnx_program = torch.onnx.export(model, observer.infer_arguments(), dynamo=True)
rows = observer.check_discrepancies(onnx_program, atol=1e-4, rtol=0.1)

When the export fails

  1. Re-run with report=True (and optionally dump_exported_program=True, artifacts_dir="./onnx_debug"). The Markdown report shows which step failed: capture by torch.export, translation of a specific operator, or optimisation. Exporter errors derive from OnnxExporterError.

  2. If capture failed, debug it as an export problem (see torch.export): draft_export, strict=False, rewriting data-dependent control flow.

  3. If an operator has no translation, supply one with custom_translation_table, written with ONNX Script, or follow the ONNX registry tutorial listed in the references for operators of your own.

  4. If the file loads but the runtime rejects it, lower opset_version to what the runtime implements.

onnx_program = torch.onnx.export(
    model,
    example,
    dynamo=True,
    report=True,
    dump_exported_program=True,
    artifacts_dir="./onnx_debug",
)

The custom-operator path (registering a translation for your own torch.library operator, see Custom Operators, C++/CUDA Extensions & Triton) is the subject of the registry tutorial listed in the references; its content was not read for this page.

The deprecated TorchScript exporter

Before PyTorch 2.9 the default was the TorchScript based exporter (dynamo=False). That path is being retired along with TorchScript itself (see Legacy APIs & Migration). The documentation lists these changes, which matter when you port an older script:

Old usage Status in 2.15

fallback=True (retry with the old exporter)

Removed in 2.11

dynamic_axes

Deprecated for dynamo=True; use dynamic_shapes

training, operator_export_type, do_constant_folding, export_modules_as_functions, autograd_inlining, custom_opsets

Deprecated since 2.6 (constant folding is always on)

register_custom_op_symbolic, unregister_custom_op_symbolic

Deprecated since 2.6; use custom_translation_table

select_model_mode_for_export

Deprecated since 2.7; set the training mode before exporting

Scripts and blog posts that set opset_version=11, pass dynamic_axes and wrap the model with torch.jit.script describe the old exporter; rewrite them for the new one rather than copying them.

Practical advice

  • Export from a clean process with the exact torch, onnx and onnxscript versions pinned in the lock file, and run the verification above in CI.

  • Keep pre- and post-processing outside the exported graph (tokenisation, image decoding), or export it separately, because Python logic is not captured.

  • For large language models the file is usually served by a specialised runtime rather than ONNX Runtime directly; see Deploying & Serving ML Models and Model Formats.

  • Quantise before or after export depending on the runtime; ONNX Runtime has its own quantisation tools (see Model Compression and Quantization, Sparsity & Pruning with torchao).

  • For server-side GPU inference without a framework-neutral file, AOTInductor is an alternative; for devices use ExecuTorch.