ValueError:运行转换的PyTorch模型时,不知道如何翻译op Unsqueeze

时间:2018-10-07 01:39:34

标签: python python-3.x pytorch caffe2 onnx

尝试在Caffe2中使用作为ONNX模型导出的PyTorch模型时遇到了问题。这是我的导出代码

the_model = torchvision.models.densenet121(pretrained=True)
garbage, model_inputs = preprocessing("test.jpg")
torch_out = torch.onnx._export(the_model,             
                           model_inputs,                       
                           "model_weights/chexnet-py.onnx",
                           export_params=True)

现在这是我的测试代码

model = onnx.load("model_weights/chexnet-py.onnx")
garbage, model_inputs = preprocessing("text.jpg")
prepared_backend = onnx_caffe2.backend.prepare(model)
W = {model.graph.input[0].name: model_inputs.numpy()}
c2_out = prepared_backend.run(W)[0]

这将返回以下错误

ValueError: Don't know how to translate op Unsqueeze when running    converted PyTorch Model

其他信息 pytorch版本1.0.0a0 + 6f664d3 Caffe2是最新版本(尝试从源代码,pip和conda构建)。都给出了相同的结果。

1 个答案:

答案 0 :(得分:1)

如果必须编辑名为onnx-caffe2的软件包以将映射黑白添加到ExpandDims中,请尝试研究此问题 https://github.com/onnx/onnx/issues/1481

寻找答案:

我发现ONNX中Unsqueeze的Caffe2等价物是ExpandDims,在onnx_caffe2 / backend.py中,第121行有一个特殊的映射,用于那些名称和属性名称不同的运算符,但是不知何故,Unsqueeze是“在那里出现(不知道为什么)。因此,我在_renamed_operators和_per_op_renamed_attrs字典中手动为其添加了映射规则,代码如下所示:

_renamed_operators = {
    'Caffe2ConvTranspose':   'ConvTranspose',
    'GlobalMaxPool':         'MaxPool',
    'GlobalAveragePool':     'AveragePool',
    'Pad':                   'PadImage',
    'Neg':                   'Negative',
    'BatchNormalization':    'SpatialBN',
    'InstanceNormalization': 'InstanceNorm',
    'MatMul':                'BatchMatMul',
    'Upsample':              'ResizeNearest',
    'Equal':                 'EQ',
    'Unsqueeze':             'ExpandDims',  # add this line
}

_global_renamed_attrs = {'kernel_shape': 'kernels'}
_per_op_renamed_attrs = {
    'Squeeze':              {'axes': 'dims'},
    'Transpose':            {'perm': 'axes'},
    'Upsample':             {'mode': ''},
    'Unsqueeze':            {'axes': 'dims'},  # add this line
}

一切都按预期进行。

尽管有OP,但我不是OP。

相关问题