Converting a JAX function to ONNX#

yobx.jax.to_onnx() converts JAX functions directly to onnx-light graphs, without requiring TensorFlow.

The workflow is:

  1. Write a plain JAX function (or wrap a flax/equinox model in a function).

  2. Call yobx.jax.to_onnx() with a representative dummy input.

  3. Run the exported ONNX model with any ONNX runtime — this example uses onnxruntime.

  4. Verify that the ONNX outputs match JAX’s own outputs.

import jax
import jax.numpy as jnp
import numpy as np
import onnxruntime
from yobx.doc import plot_dot
from yobx.helpers import max_diff
from yobx.helpers.onnx_helper import pretty_onnx
from yobx.jax import to_onnx

1. Simple element-wise function#

We start with the simplest possible JAX function: an element-wise sin applied to a float32 matrix.

rng = np.random.default_rng(0)
X = rng.standard_normal((5, 4)).astype(np.float32)


def jax_sin(x):
    return jnp.sin(x)


onx_sin = to_onnx(jax_sin, (X,), target_opset=21)

print("Opset            :", onx_sin.opset_import[0].version)
print("Number of nodes  :", len(onx_sin.graph.node))
print("Node op-types    :", [n.op_type for n in onx_sin.graph.node])
Opset            : 21
Number of nodes  : 1
Node op-types    : ['Sin']

Run and compare#

Verify that the ONNX model reproduces the JAX output.

ref_sin = onnxruntime.InferenceSession(
    onx_sin.SerializeToString(), providers=["CPUExecutionProvider"]
)
input_name = ref_sin.get_inputs()[0].name
(result_sin,) = ref_sin.run(None, {input_name: X})

expected_sin = np.asarray(jax_sin(X))
print("\nJAX  output (first row):", expected_sin[0])
print("ONNX output (first row):", result_sin[0])
assert np.allclose(expected_sin, result_sin, atol=1e-5), "Mismatch!"
print("Outputs match ✓ - ", max_diff(expected_sin, result_sin))
JAX  output (first row): [ 0.12539922 -0.13172095  0.59753436  0.10470783]
ONNX output (first row): [ 0.12539922 -0.13172095  0.5975344   0.10470783]
Outputs match ✓ -  {'abs': 5.960464477539063e-08, 'rel': 9.958433284368885e-08, 'sum': 1.1920928955078125e-07, 'n': 20.0, 'dnan': 0.0, 'argm': (0, 2)}

2. Multi-layer MLP in JAX#

A slightly more complex function: a two-layer MLP with ReLU activations whose weights are stored as JAX arrays captured in a closure.

key = jax.random.PRNGKey(42)
k1, k2 = jax.random.split(key)

W1 = jax.random.normal(k1, (8, 16), dtype=np.float32)
b1 = np.zeros(16, dtype=np.float32)
W2 = jax.random.normal(k2, (16, 4), dtype=np.float32)
b2 = np.zeros(4, dtype=np.float32)


def jax_mlp(x):
    h = jax.nn.relu(x @ W1 + b1)
    return h @ W2 + b2


X_mlp = rng.standard_normal((10, 8)).astype(np.float32)
onx_mlp = to_onnx(jax_mlp, (X_mlp,), target_opset=21)

op_types = [n.op_type for n in onx_mlp.graph.node]
print("\nOp-types in the MLP graph:", op_types)
assert "MatMul" in op_types
Op-types in the MLP graph: ['MatMul', 'Add', 'Relu', 'MatMul', 'Add']

Display the model.

opset: domain='' version=21
input: name='X' type=dtype('float32') shape=['batch', 8]
init: name='constant' type=float32 shape=(8, 16)
init: name='constant_3' type=float32 shape=(16, 4)
init: name='unsqueeze' type=float32 shape=(1, 16)
init: name='unsqueeze_2' type=float32 shape=(1, 4) -- array([0., 0., 0., 0.], dtype=float32)
MatMul(X, constant) -> matmul
  Add(matmul, unsqueeze) -> add
    Relu(add) -> max
      MatMul(max, constant_3) -> matmul_2
        Add(matmul_2, unsqueeze_2) -> add_2
output: name='add_2' type=dtype('float32') shape=['batch', 4]

Verify predictions on a held-out batch.

MLP predictions match ✓ -  {'abs': 1.1920928955078125e-06, 'rel': 1.0611207510033628e-06, 'sum': 8.188188076019287e-06, 'n': 40.0, 'dnan': 0.0, 'argm': (3, 3)}

3. Dynamic batch dimension#

By default to_onnx() marks axis 0 as a dynamic (symbolic) batch dimension. The converted model runs correctly for any batch size.

onx_dyn = to_onnx(jax_mlp, (X_mlp,), target_opset=21, dynamic_shapes=({0: "batch"},))

input_shape = onx_dyn.graph.input[0].type.tensor_type.shape
batch_dim = input_shape.dim[0]
print("\nBatch dimension param  :", batch_dim.dim_param)
assert batch_dim.dim_param, "Expected a named dynamic dimension"

ref_dyn = onnxruntime.InferenceSession(
    onx_dyn.SerializeToString(), providers=["CPUExecutionProvider"]
)
input_name_dyn = ref_dyn.get_inputs()[0].name
for n in (1, 7, 20):
    X_batch = rng.standard_normal((n, 8)).astype(np.float32)
    (out,) = ref_dyn.run(None, {input_name_dyn: X_batch})
    expected = np.asarray(jax_mlp(X_batch))
    np.testing.assert_allclose(expected, out, atol=1e-2)
    print(f"Dynamic-batch model verified for batch sizes {n} ✓ - ", max_diff(expected, out))
Batch dimension param  : batch
Dynamic-batch model verified for batch sizes 1 ✓ -  {'abs': 0.0, 'rel': 0.0, 'sum': 0.0, 'n': 4.0, 'dnan': 0.0, 'argm': (0, 0)}
Dynamic-batch model verified for batch sizes 7 ✓ -  {'abs': 0.0, 'rel': 0.0, 'sum': 0.0, 'n': 28.0, 'dnan': 0.0, 'argm': (0, 0)}
Dynamic-batch model verified for batch sizes 20 ✓ -  {'abs': 1.9073486328125e-06, 'rel': 1.359281320747874e-05, 'sum': 1.6061589121818542e-05, 'n': 80.0, 'dnan': 0.0, 'argm': (6, 3)}

4. Softmax#

Softmax demonstrates a composite JAX operation.

def jax_softmax(x):
    return jax.nn.softmax(x, axis=-1)


X_cls = rng.standard_normal((6, 10)).astype(np.float32)

onx_cls = to_onnx(jax_softmax, (X_cls,), target_opset=21, dynamic_shapes=({0: "batch"},))

ref_cls = onnxruntime.InferenceSession(
    onx_cls.SerializeToString(), providers=["CPUExecutionProvider"]
)
input_name_cls = ref_cls.get_inputs()[0].name
(result_cls,) = ref_cls.run(None, {input_name_cls: X_cls})

expected_cls = np.asarray(jax_softmax(X_cls))
assert np.allclose(expected_cls, result_cls, atol=1e-5), "Softmax mismatch!"
print("Softmax verified ✓ - ", max_diff(expected_cls, result_cls))
Softmax verified ✓ -  {'abs': 2.9802322387695312e-08, 'rel': 1.6314850628220193e-07, 'sum': 3.5297125577926636e-07, 'n': 60.0, 'dnan': 0.0, 'argm': (2, 7)}

5. Visualize the ONNX graph#

plot jax to onnx

Total running time of the script: (0 minutes 2.223 seconds)

Related examples

Converting a TensorFlow/Keras model to ONNX

Converting a TensorFlow/Keras model to ONNX

Gallery generated by Sphinx-Gallery