ONNX Runtime lets you run machine learning models fast and on many devices. It helps you use models made in one tool inside another easily.
ONNX Runtime inference in PyTorch
import onnxruntime # Load the ONNX model session = onnxruntime.InferenceSession('model.onnx') # Prepare input as a dictionary inputs = {session.get_inputs()[0].name: input_array} # Run inference outputs = session.run(None, inputs)
You must export your PyTorch model to ONNX format first.
Input data must be a numpy array matching the model input shape.
import onnxruntime import numpy as np session = onnxruntime.InferenceSession('model.onnx') input_name = session.get_inputs()[0].name input_data = np.random.randn(1, 3, 224, 224).astype(np.float32) outputs = session.run(None, {input_name: input_data})
import onnxruntime session = onnxruntime.InferenceSession('model.onnx') input_name = session.get_inputs()[0].name input_data = your_numpy_array outputs = session.run(None, {input_name: input_data})
This code creates a simple linear model in PyTorch, exports it to ONNX format, then loads and runs it using ONNX Runtime. It prints the input and the model's output.
import torch import torch.nn as nn import numpy as np import onnxruntime # Define a simple PyTorch model class SimpleModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(4, 2) def forward(self, x): return self.linear(x) # Create model and dummy input model = SimpleModel() model.eval() dummy_input = torch.randn(1, 4) # Export to ONNX onnx_path = 'simple_model.onnx' torch.onnx.export(model, dummy_input, onnx_path, input_names=['input'], output_names=['output'], opset_version=11) # Prepare input for ONNX Runtime input_data = dummy_input.numpy() # Load ONNX model with ONNX Runtime session = onnxruntime.InferenceSession(onnx_path) input_name = session.get_inputs()[0].name # Run inference outputs = session.run(None, {input_name: input_data}) print('Input:', input_data) print('Output:', outputs[0])
ONNX Runtime supports many hardware accelerators for faster inference.
Make sure the input data type and shape match the model's expected input.
ONNX Runtime can run models exported from many frameworks, not just PyTorch.
ONNX Runtime helps run machine learning models fast and on many devices.
You export your PyTorch model to ONNX format, then load it with ONNX Runtime.
Prepare input as a numpy array and run inference with session.run().
Practice
Solution
Step 1: Understand ONNX Runtime's role
ONNX Runtime is designed to run machine learning models efficiently across various hardware.Step 2: Compare options
Training or converting to TensorFlow is not the main purpose; visualization is unrelated.Final Answer:
To run the model faster and on different devices -> Option CQuick Check:
ONNX Runtime = fast, cross-device inference [OK]
- Confusing inference with training
- Thinking ONNX Runtime converts models to other frameworks
- Assuming it is for visualization
Solution
Step 1: Recall ONNX Runtime loading syntax
ONNX Runtime uses InferenceSession to load ONNX models.Step 2: Check each option
session = onnxruntime.InferenceSession('model.onnx') uses correct syntax. session = onnx.load('model.onnx') is for ONNX library, not runtime. session = torch.load('model.onnx') is PyTorch loading, not ONNX. session = onnxruntime.load_model('model.onnx') is invalid method.Final Answer:
session = onnxruntime.InferenceSession('model.onnx') -> Option DQuick Check:
InferenceSession loads ONNX models [OK]
- Using torch.load for ONNX files
- Confusing onnx.load with onnxruntime
- Trying non-existent load_model method
print(output)?
import onnxruntime
import numpy as np
session = onnxruntime.InferenceSession('model.onnx')
input_name = session.get_inputs()[0].name
input_data = np.array([[1.0, 2.0, 3.0]], dtype=np.float32)
output = session.run(None, {input_name: input_data})
print(output)Solution
Step 1: Understand session.run output
session.run returns a list of numpy arrays with model outputs.Step 2: Analyze code behavior
Input is correctly prepared as numpy array; no error occurs; output is a list with prediction arrays.Final Answer:
A list containing the model's prediction array -> Option AQuick Check:
session.run returns list of outputs [OK]
- Expecting a single numpy array instead of list
- Thinking input must be a PyTorch tensor
- Assuming session.run returns None
TypeError: expected np.ndarray (got list). What is the likely cause?Solution
Step 1: Interpret the error message
The error says input expected is numpy array but got list.Step 2: Identify cause
Passing input as Python list instead of np.ndarray causes this error.Final Answer:
Input data was passed as a Python list instead of a numpy array -> Option BQuick Check:
Input must be numpy array, not list [OK]
- Passing Python lists directly as input
- Assuming model file corruption causes this error
- Ignoring session creation errors
Solution
Step 1: Check input shape requirements
Model expects (batch_size, 3, 224, 224) so batch size 5 means shape (5,3,224,224).Step 2: Validate each option's input shape and type
import numpy as np batch_input = np.random.rand(5, 3, 224, 224).astype(np.float32) output = session.run(None, {input_name: batch_input}) uses correct shape and numpy float32 array. batch_input = torch.rand(5, 3, 224, 224) output = session.run(None, {input_name: batch_input}) uses torch tensor (not accepted). batch_input = np.random.rand(3, 224, 224).astype(np.float32) output = session.run(None, {input_name: batch_input}) misses batch dimension. batch_input = np.random.rand(5, 224, 224, 3).astype(np.float32) output = session.run(None, {input_name: batch_input}) swaps channel and width/height.Final Answer:
import numpy as np batch_input = np.random.rand(5, 3, 224, 224).astype(np.float32) output = session.run(None, {input_name: batch_input}) -> Option AQuick Check:
Correct shape and numpy array input [OK]
- Using torch tensors instead of numpy arrays
- Incorrect input shape order
- Missing batch dimension
Ready to prove it?
Pass the test and this pattern moves unknown
