diff --git a/python/tvm/topi/image/resize.py b/python/tvm/topi/image/resize.py index 8d0a984982e1..fe93ab60061c 100644 --- a/python/tvm/topi/image/resize.py +++ b/python/tvm/topi/image/resize.py @@ -163,10 +163,12 @@ def get_inx( elif coordinate_transformation_mode == "tf_half_pixel_for_nn": in_x = (x + 0.5) * scale_x elif coordinate_transformation_mode == "tf_crop_and_resize": + # Both branches are built eagerly, even for a unit output extent. + denominator = te.max(target_width - 1, 1) in_x = te.if_then_else( target_width > 1, start_x * (image_width - 1) - + x * (end_x - start_x) * (image_width - 1).astype("float") / (target_width - 1), + + x * (end_x - start_x) * (image_width - 1).astype("float") / denominator, 0.5 * (start_x + end_x) * (image_width - 1), ) else: diff --git a/tests/python/relax/test_frontend_onnx_resize_crop_unit.py b/tests/python/relax/test_frontend_onnx_resize_crop_unit.py new file mode 100644 index 000000000000..35763ee6be2a --- /dev/null +++ b/tests/python/relax/test_frontend_onnx_resize_crop_unit.py @@ -0,0 +1,106 @@ +# 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. +"""ROI-center coordinates for unit-sized tf_crop_and_resize output axes.""" + +import numpy as np +import pytest + +pytest.importorskip("onnx") +pytest.importorskip("onnxruntime") + +import onnx +import onnxruntime as ort + +import tvm +import tvm_tirx +from tvm import relax +from tvm.relax.frontend.onnx import from_onnx +from tvm.topi.image.resize import get_inx + + +@pytest.mark.parametrize("method", ["nearest", "linear"]) +@pytest.mark.parametrize("size", [(1, 5), (4, 1), (1, 1), (4, 5)]) +@pytest.mark.parametrize( + "roi", + [ + [0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0.2, 0.1, 1, 1, 0.8, 0.9], + [0, 0, 1, 1, 1, 1, 0, 0], + ], +) +def test_resize_crop_unit_extent(method, size, roi): + data = np.arange(12, dtype="float32").reshape(1, 1, 3, 4) / 7 + output_shape = [1, 1, *size] + model = onnx.helper.make_model( + onnx.helper.make_graph( + [ + onnx.helper.make_node( + "Resize", + ["data", "roi", "", "sizes"], + ["output"], + mode=method, + nearest_mode="round_prefer_ceil", + coordinate_transformation_mode="tf_crop_and_resize", + ) + ], + "resize_crop_unit_extent", + [onnx.helper.make_tensor_value_info("data", onnx.TensorProto.FLOAT, list(data.shape))], + [onnx.helper.make_tensor_value_info("output", onnx.TensorProto.FLOAT, output_shape)], + [ + onnx.numpy_helper.from_array(np.array(roi, dtype="float32"), "roi"), + onnx.numpy_helper.from_array(np.array(output_shape, dtype="int64"), "sizes"), + ], + ), + opset_imports=[onnx.helper.make_opsetid("", 13)], + ir_version=8, + ) + onnx.checker.check_model(model, full_check=True) + options = ort.SessionOptions() + options.intra_op_num_threads = options.inter_op_num_threads = 1 + options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL + expected = ort.InferenceSession( + model.SerializeToString(), options, providers=["CPUExecutionProvider"] + ).run(None, {"data": data})[0] + + 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 == np.dtype("float32") + assert actual.shape == expected.shape == tuple(output_shape) + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6) + + +@pytest.mark.parametrize("target_width", [1, 2, 5]) +def test_resize_crop_symbolic_coordinate(target_width): + symbolic_coordinate = tvm_tirx.ir.LambdaExpr( + ["int32"], + lambda width: get_inx( + tvm_tirx.tirx.const(0, "int32"), + tvm_tirx.tirx.const(7, "int32"), + width, + "tf_crop_and_resize", + start_x=0.2, + end_x=0.8, + ), + ) + expression = symbolic_coordinate.apply([tvm_tirx.tirx.const(target_width, "int32")]) + coordinate = tvm_tirx.sym.Analyzer().simplify(expression) + expected = 3.0 if target_width == 1 else 1.2 + assert isinstance(coordinate, tvm_tirx.ir.FloatImm) + np.testing.assert_allclose(coordinate.value, expected, rtol=1e-6)