我在PyTorch中有一个想与CoreML一起运行的seq2seq模型。将模型导出到ONNX时,输入尺寸固定为导出期间使用的张量的形状,并再次从ONNX转换为CoreML。
import torch
from onnx_coreml import convert
x = torch.ones((32, 1, 1000)) # N x C x W
model = Model()
torch.onnx.export(model, x, 'example.onnx')
mlmodel = convert(model='example.onnx', minimum_ios_deployment_target='13')
mlmodel.save('example.mlmodel')
对于ONNX导出,您可以导出动态尺寸-
torch.onnx.export(
model, x, 'example.onnx',
input_names = ['input'],
output_names = ['output'],
dynamic_axes={
'input' : {0 : 'batch', 2: 'width'},
'output' : {0 : 'batch', 1: 'owidth'},
}
)
但这会在转换为RunTimeWarning
时导致CoreML
-
RuntimeWarning:您将无法在此Core ML模型上运行predict()。底层异常消息为:错误编译模型:“编译器错误:找到大小为零的Blob:
对于CoreML的推断,我希望批量(第一个)和宽度(最后一个)尺寸是动态的或具有静态更改尺寸的能力。
有可能吗?
答案 0 :(得分:0)
通过在torch.onnx.export
中指定dynamic_axes
,可以在ONNX中使输入的尺寸动态化。
torch.onnx.export(
model,
x,
'example.onnx',
# Assigning names to the inputs to reference in dynamic_axes
# Your model only has one input: x
input_names=["input"],
# Define which dimensions should be dynamic
# Names of the dimensions are optional, but recommended.
# Could just be: {"input": [0, 2]}
dynamic_axes={"input": {0: "batch", 2: "width"}}
)
现在,导出的模型接受大小为 [批处理,1,宽度] 的输入,其中 batch 和 width 是动态的。