我在PyTorch中有一个PyTorch模型,我想使用CoreML运行它。当将模型导出到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:您将无法在这个核心ML模型上运行predict()。底层异常消息是:错误编译模型:“编译器错误:零大小Blob找到:
对于CoreML中的推理,我希望批处理(第一)和宽度(最后)维度是动态的,或者能够静态地更改它们。
这有可能吗?
发布于 2020-05-17 11:44:58
通过为dynamic_axes指定torch.onnx.export,可以使输入的维度在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、宽度的输入,其中批处理和宽度是动态的。
https://stackoverflow.com/questions/61850304
复制相似问题