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
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
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).
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
| Runtime | Platforms | Best For | Source Frameworks |
|---|---|---|---|
| ONNX Runtime | Windows, Linux, macOS, Android, iOS | Cross-platform deployment | PyTorch, TF, sklearn, any |
| TFLite | Android, iOS, Linux, MCUs | Mobile and microcontrollers | TensorFlow / Keras |
| CoreML | iOS, macOS, watchOS | Apple ecosystem | PyTorch, TF, ONNX |
| TensorRT | NVIDIA GPUs | Maximum GPU inference speed | ONNX, TF, PyTorch |
| OpenVINO | Intel CPUs, GPUs, VPUs | Intel hardware optimization | ONNX, TF, PyTorch |
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX