I need to convert to ONNX a model from PyTorch, but model has 2 inputs, one of which can…
- User
I need to convert to ONNX a model from PyTorch, but model has 2 inputs, one of which can be of varying shape at position 0. How can I do that?
- Assistant
I need to convert to ONNX a model from PyTorch, but model has 2 inputs, one of which can be of varying shape at position 0. How can I do that?
Converting a PyTorch model with dynamic input shapes to ONNX can be done using the torch.onnx.export function, which allows you to specify dynamic axes for inputs and outputs. This is particularly useful when your model's input or output tensors have dimensions that can vary in size. In your case, since one of the inputs has a variable shape at position 0 (the first dimension), you can specify this when exporting the model.
Here's how you can do it:
Prepare Your Model and Inputs:
Make sure your model is ready and you have example inputs that match the expected input types of your model. For the purposes of exporting, these inputs don't need to cover every possible input size but should be representative.
import torch
# Assuming `model` is your PyTorch model
# Create example inputs with dummy data
input1 = torch.randn(batch_size, other_dimensions)
input2 = torch.randn(variable_size, other_dimensions) # This input has variable size at dimension 0
Use torch.onnx.export with Dynamic Axes:
The torch.onnx.export function accepts a dynamic_axes argument, where you can specify which dimensions of your inputs or outputs are dynamic (i.e., can vary in size). You need to provide a dictionary mapping input/output names to their dynamic dimensions.
Here's how you can specify that the first dimension of input2 is dynamic:
torch.onnx.export(
model, # Your model
(input1, input2), # Example inputs
'model.onnx', # Output file name
input_names=['input1', 'input2'], # Names of your inputs
output_names=['output'], # Names of the outputs
dynamic_axes={
'input2': {0: 'variable_length'} # Specify that dimension 0 of input2 is dynamic
}
)
In the dynamic_axes dictionary:
input_names and output_names.Handling Multiple Dynamic Dimensions (if needed):
If you have multiple dimensions that are dynamic, you can specify each one in the dictionary. For example:
dynamic_axes={
'input2': {0: 'variable_length', 2: 'variable_height'},
'output': {0: 'variable_length_output'}
}
This example marks dimension 0 and 2 of input2 as dynamic, and dimension 0 of output as dynamic.
Export the Model:
Run the torch.onnx.export function with the proper parameters. This will generate an ONNX file (model.onnx) with the dynamic axes specified.
Verify the Exported Model (Optional):
It's a good practice to verify that the exported ONNX model works as expected. You can use the ONNX Runtime or another compatible runtime to load and test the model.
import onnx
from onnxruntime import InferenceSession
# Load the ONNX model
model_onnx = onnx.load('model.onnx')
# Check that the model is well formed
onnx.checker.check_model(model_onnx)
# Create an inference session
session = InferenceSession('model.onnx')
# Prepare inputs (matching the dynamic dimensions)
test_input1 = ... # Provide test data
test_input2 = ... # Provide test data with variable dimension 0
# Run inference
result = session.run(
None,
{
'input1': test_input1.numpy(),
'input2': test_input2.numpy()
}
)
By specifying the dynamic axes during export, the ONNX model will be able to handle inputs where the specified dimensions can vary in size, just like your original PyTorch model.
Note: Make sure that any downstream tools or runtimes that consume the ONNX model support dynamic shapes.
Summary: To handle varying input shapes when converting a PyTorch model to ONNX, use the dynamic_axes parameter in torch.onnx.export to specify which dimensions are dynamic.
Example Code:
import torch
# Assume 'model' is your PyTorch model with two inputs
model = ...
# Example inputs
input1 = torch.randn(1, 3, 224, 224) # Static shape
input2 = torch.randn(variable_length, feature_size) # Variable shape at dimension 0
# Export the model to ONNX
torch.onnx.export(
model,
(input1, input2),
'model.onnx',
input_names=['input1', 'input2'],
output_names=['output'],
dynamic_axes={
'input2': {0: 'variable_length'}
}
)
References:
Not yet included in a published release.