Skip to content

Commit

Permalink
[ONNX] fix reduce crash on scalar inputs (#10780)
Browse files Browse the repository at this point in the history
* fix reduce crash on scalar inputs

* fix uncovered cases.

* fix on different opset to pass ci
  • Loading branch information
ganler authored Mar 25, 2022
1 parent 1b654e9 commit 31a4267
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
18 changes: 18 additions & 0 deletions python/tvm/relay/frontend/onnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1875,6 +1875,9 @@ def run_calculation(cls, inputs, axis, keepdims):

@classmethod
def _impl_v1(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if "axes" in attr:
axis = attr.get("axes", 0)
else:
Expand All @@ -1885,6 +1888,9 @@ def _impl_v1(cls, inputs, attr, params):

@classmethod
def _impl_v12(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if len(inputs) == 2:
if isinstance(inputs[1], _expr.Constant):
# Get axis and unpack scalar
Expand Down Expand Up @@ -1937,6 +1943,9 @@ class ReduceSumSquare(OnnxOpConverter):

@classmethod
def _impl_v1(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if "axes" in attr:
axis = attr.get("axes", 0)
else:
Expand All @@ -1953,6 +1962,9 @@ class ReduceL1(OnnxOpConverter):

@classmethod
def _impl_v1(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if "axes" in attr:
axis = attr.get("axes", 0)
else:
Expand All @@ -1969,6 +1981,9 @@ class ReduceL2(OnnxOpConverter):

@classmethod
def _impl_v1(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if "axes" in attr:
axis = attr.get("axes", 0)
else:
Expand All @@ -1986,6 +2001,9 @@ class ReduceLogSum(OnnxOpConverter):

@classmethod
def _impl_v1(cls, inputs, attr, params):
if not infer_shape(inputs[0]): # promote scalar to 1-D tensor
inputs[0] = _op.expand_dims(inputs[0], axis=0)

if "axes" in attr:
axis = attr.get("axes", 0)
else:
Expand Down
2 changes: 2 additions & 0 deletions tests/python/frontend/onnx/test_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -1934,6 +1934,8 @@ def verify_reduce_func(func, data, axis, keepdims):
]

for func in funcs:
verify_reduce_func(func, np.array(1.0).astype(np.float32), axis=None, keepdims=False)

for keepdims in [True, False]:
verify_reduce_func(
func, np.random.randn(3, 2, 2).astype(np.float32), axis=None, keepdims=keepdims
Expand Down

0 comments on commit 31a4267

Please sign in to comment.