简体   繁体   English

将 PyTorch model 与 CoreML 一起使用时输入维度重塑

[英]Input dimension reshape when using PyTorch model with CoreML

I have a seq2seq model in PyTorch that I want to run with CoreML.我在 PyTorch 中有一个 seq2seq model 我想用 CoreML 运行。 When exporting the model to ONNX the input dimensions are fixed to the shape of the tensor used during export, and again with the conversion from ONNX to CoreML.将 model 导出到 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')

For the ONNX export you can export dynamic dimension -对于 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'},
    }
)

But this leads to a RunTimeWarning when converting to CoreML -但这会在转换为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: RuntimeWarning:您将无法在此 Core ML model 上运行 predict()。底层异常消息是:编译 model 时出错:“编译器错误:找到大小为零的 Blob:

For inference in CoreML I would like the batch (first) and width (last) dimension to either be dynamic or have the ability to statically change them.对于 CoreML 中的推理,我希望批处理(第一个)和宽度(最后一个)维度要么是动态的,要么能够静态地改变它们。

Is that possible?那可能吗?

The dimensions of the input can be made dynamic in ONNX by specifying dynamic_axes for torch.onnx.export .通过为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"}}
)

Now the exported model accepts inputs of size [batch, 1, width] , where batch and width are dynamic.现在导出的 model 接受大小为[batch, 1, width]的输入,其中batchwidth是动态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM