无法将torchvision FasterRCNN-ResNet50模型导出为ONNX文件的问题求助
问题描述
我编写了一段简单的Python脚本,加载torchvision的fasterrcnn_resnet50_fpn_v2模型(使用默认权重),尝试通过torch.onnx.export和torch.onnx.dynamo_export两种方式将其导出为ONNX文件,但均出现错误。
脚本代码:
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'}})
错误信息:
- 使用
dynamo_export时:
File "C:\\tools\\Python311\\Lib\\site-packages\\torch\\onnx\\_internal\\exporter.py", line 1439, in dynamo_export raise OnnxExporterError( torch.onnx.OnnxExporterError: Failed to export the model to ONNX. Generating SARIF report at 'report_dynamo_export.sarif'. SARIF is a standard format for the output of static analysis tools. SARIF logs can be loaded in VS Code SARIF viewer extension, or SARIF web viewer. Please report a bug on PyTorch Github.
- 使用普通
torch.onnx.export时:
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::
注:两种导出方式对自定义简单模型均可正常工作,自定义模型代码:
import torch.nn as nn import torch.nn.functional as F 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
解决方法
修复普通torch.onnx.export的报错
报错已明确提示Pad操作在opset 9/10不支持动态padding,需做以下调整:
- 升级opset版本:将
opset_version=10改为opset_version=11或更高(推荐16以上,适配更多模型操作)。 - 修正输出配置:Faster RCNN的输出是包含
boxes、labels、scores的字典,不能用单一的output作为输出名,需对应修改:output_names = ['boxes', 'labels', 'scores'], dynamic_axes={ 'input' : {0 : 'batch_size'}, 'boxes' : {0 : 'batch_size'}, 'labels' : {0 : 'batch_size'}, 'scores' : {0 : 'batch_size'} }
修复torch.onnx.dynamo_export的报错
Dynamo导出对检测类复杂模型的兼容性仍不完善,可尝试:
- 升级PyTorch到最新稳定版,新版本通常修复了更多Dynamo导出的适配问题。
- 优先使用调整后的普通
torch.onnx.export方式,该方式对经典检测模型的支持更成熟。 - 若必须使用Dynamo导出,添加动态形状配置参数:
onnx_program = torch.onnx.dynamo_export( torch_model, torch_input, export_options=torch.onnx.ExportOptions(dynamic_shapes=True) )
额外注意事项
- 检测模型在eval模式下默认返回字典,可修改forward方法转为tuple输出,适配ONNX要求:
def modified_forward(self, x): outputs = self.__original_forward(x) return outputs['boxes'], outputs['labels'], outputs['scores'] torch_model.__original_forward = torch_model.forward torch_model.forward = modified_forward.__get__(torch_model) - 输入张量尺寸建议贴合实际检测场景,比如改用640x640这类常见尺寸,避免过小尺寸导致模型内部计算异常。
内容的提问来源于stack exchange,提问作者ghost113116
相关产品推荐
相关产品推荐

