Skip to content

ONNX Sub operator ignores order and always subtracts constant from blob #20852

@galchinsky

Description

@galchinsky
System information (version)

Found on 4.5.3, but master looks also affected

Detailed description

constant - blob and blob - constant are different expressions, but onnx_importer.cpp seems to always interpret it as blob - constant

if (blob_total == 1) {
layerParams.type = "Power";
layerParams.set("shift", (isSub ? -1 : 1) * blob.ptr<float>()[0]);
}
else {
MatShape inpShape = outShapes[node_proto.input(1 - const_blob_id)];
if (shape(blob) == inpShape)
{
LayerParams constParams;

if (blob_total == 1) {

Steps to reproduce

onnx file: sub.zip

To create it:

import onnx
import numpy as np

X = onnx.helper.make_tensor_value_info('X', onnx.TensorProto.FLOAT, [5])

value = np.array([1], dtype=np.float32)
weight = onnx.helper.make_node(
    'Constant', inputs=[], outputs=['one'],
    value=onnx.helper.make_tensor(
        name='oneconst',
        data_type=onnx.TensorProto.FLOAT,
        dims=value.shape,
        vals=value.flatten(),
    ))
sub = onnx.helper.make_node('Sub', inputs=['one', 'X'], outputs=['y'])

Y = onnx.helper.make_tensor_value_info('y', onnx.TensorProto.FLOAT, [5])
graph_def = onnx.helper.make_graph([weight, sub], "name", [X], [Y])

imp = onnx.OperatorSetIdProto()
imp.version = 13 # doesn't matter

model_def = onnx.helper.make_model(graph_def,
                                   producer_name='onnx-example',
                                   opset_imports=[imp])

onnx.save(model_def, 'sub.onnx')

Testing

import cv2
import numpy as np
net=cv2.dnn.readNetFromONNX("sub.onnx")
net.setInput(np.array([1,2,3,4,5]))
# outputs [0, 1, 2, 3, 4] instead of [0, -1, -2, -3, -4]
print (net.forward())

import onnxruntime
session = onnxruntime.InferenceSession('sub.onnx', None)
input_name = session.get_inputs()[0].name
# outputs [0, -1, -2, -3, -4]
print ( session.run([], {input_name: [1, 2, 3, 4, 5]})[0] )
Issue submission checklist
  • [ x] I report the issue, it's not a question
  • [ x] I checked the problem with documentation, FAQ, open issues,
    forum.opencv.org, Stack Overflow, etc and have not found solution
  • I updated to latest OpenCV version and the issue is still there
  • [x ] There is reproducer code and related data files: videos, images, onnx, etc

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions