Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion python/tvm/relax/frontend/onnx/onnx_frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3753,7 +3753,9 @@ def _impl_v13(cls, bb, inputs, attr, params):
new_shape = shape.value.numpy().tolist()
# ONNX Expand operator requires preserving target rank and broadcasting
# according to standard rules. Dimensions are right-aligned.
data_shape = [dim.value for dim in data.ty.shape]
data_shape = [
dim.value if isinstance(dim, tvm_tirx.ir.IntImm) else dim for dim in data.ty.shape
]
original_data_shape = data_shape.copy()
original_new_shape = new_shape.copy()

Expand All @@ -3768,6 +3770,11 @@ def _impl_v13(cls, bb, inputs, attr, params):
if new_shape[i] == -1:
# -1 means preserve the input dimension
new_shape[i] = data_shape[i]
elif not isinstance(data_shape[i], int):
# As in the ShapeExpr path, defer unknown extents to broadcast_to.
# A singleton target must preserve the input extent.
if new_shape[i] == 1:
new_shape[i] = data_shape[i]
elif data_shape[i] == 1:
# Input dimension is 1, can broadcast to any target dimension >= 1
if new_shape[i] < 1:
Expand Down
23 changes: 22 additions & 1 deletion python/tvm/topi/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
# under the License.
"""Broadcast operators"""

import tvm_ffi

from tvm import te
from tvm_tirx import ir, tirx

from . import cpp as _cpp


Expand All @@ -37,7 +42,23 @@ def broadcast_to(data, shape):
-------
ret : tvm.te.Tensor
"""
return _cpp.broadcast_to(data, shape)
output = _cpp.broadcast_to(data, shape)
offset = len(output.shape) - len(data.shape)
if all(
isinstance(dim, ir.IntImm) or tvm_ffi.structural_equal(dim, output.shape[offset + i])
for i, dim in enumerate(data.shape)
):
return output

def compute(*indices):
input_indices = [
tirx.if_then_else(dim == 1, 0, indices[offset + i]) for i, dim in enumerate(data.shape)
]
return data[tuple(input_indices)]

# A symbolic input extent may be one at runtime, even when it cannot
# be proven to be a singleton while constructing the broadcast.
return te.compute(output.shape, compute, name=output.op.name, tag=output.op.tag)


def add(lhs, rhs):
Expand Down
105 changes: 105 additions & 0 deletions tests/python/relax/test_frontend_onnx_expand_symbolic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Expand with a constant target and a symbolic input extent."""

import numpy as np
import pytest

pytest.importorskip("onnx")
pytest.importorskip("onnxruntime")

import onnx
import onnxruntime

import tvm
import tvm_tirx
from tvm import relax, te, topi
from tvm.relax.frontend.onnx import from_onnx
from tvm.topi import cpp as topi_cpp


def make_expand(input_shape, target_shape, output_shape):
return onnx.helper.make_model(
onnx.helper.make_graph(
[onnx.helper.make_node("Expand", ["data", "shape"], ["output"])],
"expand_symbolic_input",
[onnx.helper.make_tensor_value_info("data", onnx.TensorProto.FLOAT, input_shape)],
[onnx.helper.make_tensor_value_info("output", onnx.TensorProto.FLOAT, output_shape)],
[onnx.numpy_helper.from_array(np.array(target_shape, dtype="int64"), "shape")],
),
opset_imports=[onnx.helper.make_opsetid("", 13)],
ir_version=8,
)


@pytest.mark.parametrize("symbolic", [False, True])
@pytest.mark.parametrize(
"declared_shape, concrete_shape, target_shape",
[
(["N", 1], [2, 1], [2, 3]),
(["N", 1], [1, 1], [2, 3]),
(["N", 1], [3, 1], [1, 3]),
(["N", 1], [3, 1], [3]),
(["N", 1], [2, 1], [4, 2, 3]),
(["N", 3], [2, 3], []),
([1, "N"], [1, 3], [2, 1]),
(["N", "M"], [1, 3], [2, 3]),
(["N", "M"], [2, 1], [2, 3]),
(["N", "M"], [1, 1], [2, 3]),
(["N", 1], [0, 1], [1, 3]),
],
)
def test_expand_symbolic_input(symbolic, declared_shape, concrete_shape, target_shape):
data = (np.arange(np.prod(concrete_shape), dtype="float32") + 1).reshape(concrete_shape)
output_shape = list(np.broadcast_shapes(data.shape, tuple(target_shape)))
model = make_expand(declared_shape if symbolic else concrete_shape, target_shape, output_shape)
onnx.checker.check_model(model, full_check=True)
expected = onnxruntime.InferenceSession(
model.SerializeToString(), providers=["CPUExecutionProvider"]
).run(None, {"data": data})[0]
np.testing.assert_array_equal(expected, np.broadcast_to(data, output_shape))

mod = from_onnx(model, keep_params_in_input=False)
mod = relax.transform.LegalizeOps()(mod)
vm = relax.VirtualMachine(tvm.compile(mod, target="llvm"), tvm_tirx.cpu())
actual = vm["main"](tvm_tirx.runtime.tensor(data)).numpy()

assert actual.dtype == expected.dtype
assert actual.shape == expected.shape
np.testing.assert_array_equal(actual, expected)


def test_expand_static_incompatible_input():
model = make_expand([2, 2], [2, 3], [2, 3])
with pytest.raises(ValueError, match="Cannot broadcast"):
from_onnx(model, keep_params_in_input=False)


@pytest.mark.parametrize("with_singleton", [False, True])
def test_broadcast_to_matching_symbolic_axes_preserves_ir(with_singleton):
n = tvm_tirx.tirx.Var("n", "int64")
m = tvm_tirx.tirx.Var("m", "int64")
if with_singleton:
a = tvm_tirx.tirx.Var("a", "int64")
c = tvm_tirx.tirx.Var("c", "int64")
input_shape, output_shape = (n, 1, m), (a, n, c, m)
else:
input_shape, output_shape = (n, n), (1, 1, n, n)
data = te.placeholder(input_shape, dtype="float32", name="data")
expected = te.create_function([data, topi_cpp.broadcast_to(data, output_shape)])
actual = te.create_function([data, topi.broadcast_to(data, output_shape)])
tvm_tirx.ir.assert_structural_equal(actual, expected)
Loading