ONNX Script

0.6.2 · active · verified Fri Apr 10

ONNX Script is a Python library that enables developers to naturally author ONNX functions and models using a subset of Python. It provides tools to translate Python functions into serialized ONNX graphs, offering an expressive, simple, and debuggable way to define ONNX models. The library is actively maintained with frequent patch releases addressing bug fixes and minor improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a simple ONNX function `MatmulAdd` using the `@script` decorator and ONNX operators from `opset15`. It shows how to use type annotations for inputs and outputs, evaluate the function in eager mode, convert it to an ONNX ModelProto, and save it to a file. The example includes basic input data generation and ONNX model validation.

import onnx
from onnxscript import script, FLOAT
from onnxscript import opset15 as op
import numpy as np

# Define an ONNX function using the @script decorator
@script()
def MatmulAdd(X: FLOAT['N', 'K'], Wt: FLOAT['K', 'M'], Bias: FLOAT['M',]) -> FLOAT['N', 'M']:
    return op.MatMul(X, Wt) + Bias

# Create some dummy input data
x_data = np.random.rand(64, 128).astype(np.float32)
wt_data = np.random.rand(128, 10).astype(np.float32)
bias_data = np.random.rand(10,).astype(np.float32)

# Evaluate the ONNX Script function in eager mode (for debugging/testing)
result_eager = MatmulAdd(x_data, wt_data, bias_data)
print(f"Eager mode output shape: {result_eager.shape}")

# Convert the ONNX Script function to an ONNX ModelProto
model_proto = MatmulAdd.to_model_proto(
    (x_data, wt_data, bias_data),  # Example inputs for tracing shapes
    output_names=['output']
)

# Save the ONNX model
onnx_file_path = "matmul_add_model.onnx"
onnx.save(model_proto, onnx_file_path)
print(f"ONNX model saved to {onnx_file_path}")

# Optionally, check the model for validity
try:
    onnx.checker.check_model(model_proto)
    print("ONNX model is valid!")
except onnx.checker.ValidationError as e:
    print(f"ONNX model validation error: {e}")

view raw JSON →