python - 将 PyTorch 模型与 CoreML 一起使用时的输入维度 reshape

标签 python pytorch coreml onnx onnx-coreml

我在 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/

相关文章:

python - Docker 容器 - 源文件消失

php - 索引音乐歌词数据库

pytorch - 如何在 PyTorch 中使用多处理?

ios - 减小使用 turicreate 创建的半精度 Core ML 模型的大小

python - 如何将数组转换为模型输入?

python - 如何设置 PyCharm 不打开所有最后的项目?

python - 如何使用Python 3中的帮助函数查看文件处理函数文档?

python - 如何找到 3 channel 图像的均值和标准差

python - torch.jit.save 中 _extra_files arg 的正确用法是什么

swift - coreML 验证输入失败