Intermediate

ONNX and ONNX Runtime

ONNX (Open Neural Network Exchange) provides a universal format for ML models, enabling cross-platform deployment from any framework to any device.

What is ONNX?

ONNX is an open format for representing ML models. It allows you to train in one framework (PyTorch, TensorFlow, scikit-learn) and deploy in another (ONNX Runtime, CoreML, TensorRT). Think of it as the "PDF of machine learning" - a portable format that works everywhere.

Exporting PyTorch to ONNX

Python - Export PyTorch Model to ONNX
import torch
import torchvision.models as models

# Load pretrained model
model = models.mobilenet_v2(pretrained=True)
model.eval()

# Create dummy input
dummy_input = torch.randn(1, 3, 224, 224)

# Export to ONNX
torch.onnx.export(
    model,
    dummy_input,
    "mobilenet_v2.onnx",
    opset_version=13,
    input_names=["input"],
    output_names=["output"],
    dynamic_axes={"input": {0: "batch"}, "output": {0: "batch"}}
)
print("Model exported to mobilenet_v2.onnx")

Running with ONNX Runtime

Python - ONNX Runtime Inference
import onnxruntime as ort
import numpy as np

# Create inference session
session = ort.InferenceSession("mobilenet_v2.onnx")

# Prepare input
input_name = session.get_inputs()[0].name
image = np.random.randn(1, 3, 224, 224).astype(np.float32)

# Run inference
result = session.run(None, {input_name: image})
prediction = np.argmax(result[0])
print(f"Predicted class: {prediction}")

# ONNX Runtime is typically 2-3x faster than native PyTorch inference

Apple CoreML

CoreML is Apple's framework for on-device ML on iOS, macOS, watchOS, and tvOS. It leverages the Apple Neural Engine for maximum performance:

  • Convert from ONNX: Use coremltools to convert ONNX models to CoreML format (.mlmodel or .mlpackage).
  • Xcode integration: Drag-and-drop .mlmodel files into Xcode projects. Swift code is auto-generated.
  • Performance: CoreML automatically routes computation to the fastest available hardware (CPU, GPU, or Neural Engine).
Python - Convert to CoreML
import coremltools as ct

# Convert from PyTorch (via traced model)
model = models.mobilenet_v2(pretrained=True).eval()
traced = torch.jit.trace(model, torch.randn(1, 3, 224, 224))

mlmodel = ct.convert(
    traced,
    inputs=[ct.ImageType(shape=(1, 3, 224, 224))],
    classifier_config=ct.ClassifierConfig("imagenet_classes.txt")
)

mlmodel.save("MobileNetV2.mlpackage")

Runtime Comparison

RuntimePlatformsBest ForSource Frameworks
ONNX RuntimeWindows, Linux, macOS, Android, iOSCross-platform deploymentPyTorch, TF, sklearn, any
TFLiteAndroid, iOS, Linux, MCUsMobile and microcontrollersTensorFlow / Keras
CoreMLiOS, macOS, watchOSApple ecosystemPyTorch, TF, ONNX
TensorRTNVIDIA GPUsMaximum GPU inference speedONNX, TF, PyTorch
OpenVINOIntel CPUs, GPUs, VPUsIntel hardware optimizationONNX, TF, PyTorch
Key takeaway: ONNX provides a universal model format that decouples training from deployment. Train in PyTorch, deploy anywhere with ONNX Runtime. For Apple devices, convert to CoreML. For NVIDIA hardware, use TensorRT. ONNX Runtime alone gives 2-3x speedups over native framework inference.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.