I made very simple python script which loads torchvision ResNet50 model and tries to export to onnx file in two ways (torch.onnx.export and torch.onnx.dynamo_export )
import torch
import torch.onnx
import torchvision
torch_model = torchvision.models.detection.fasterrcnn_resnet50_fpn_v2( weights='DEFAULT')
torch_model.eval()
torch_input = torch.randn(1, 3, 32, 32)
is_dynamo_export = False
if (is_dynamo_export):
onnx_program = torch.onnx.dynamo_export(torch_model, torch_input)
onnx_program.save("onnx_dynamo_export_ResNET50.onnx")
else:
torch.onnx.export(torch_model, # model being run
torch_input, # model input (or a tuple for multiple inputs)
"onnx_export_ResNET50.onnx", # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=10, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes
'output' : {0 : 'batch_size'}})
The errors were appeared:
torch\onnx\_internal\exporter.py", line 1439, in dynamo_export
raise OnnxExporterError(
torch.onnx.OnnxExporterError: Failed to export the model to ONNX. Generating SARIF
torch.onnx.errors.SymbolicValueError: Unsupported: ONNX export of Pad in opset 9. The sizes of the padding must be constant. Please try opset version 11. [Caused by the value '535 defined in (%535 : int[] = prim::ListConstruct(%405, %534, %405, %533, %405, %532), scope: torchvision.models.detection.faster_rcnn.FasterRCNN::
Both methods works good with extremally simple models such as
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = torch.flatten(x, 1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x