我在 PyTorch 中有一个 seq2seq 模型,我想用 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: You will not be able to run predict() on this Core ML model. Underlying exception message was: Error compiling model: "compiler error: Blob with zero size found:
对于 CoreML 中的推理,我希望批次(第一)和宽度(最后)维度要么是动态的,要么能够静态更改它们。
那可能吗?
最佳答案
通过指定 dynamic_axes
,可以在 ONNX 中使输入的维度动态化。为 torch.onnx.export
.
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"}}
)
现在导出的模型接受大小为 [batch, 1, width] 的输入,其中批处理和宽度是动态的。
关于python - 将 PyTorch 模型与 CoreML 一起使用时的输入维度 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61850304/