From 2a9c03a08435ff6c7cf8309ac43d5b184e3970ad Mon Sep 17 00:00:00 2001 From: Nanmur <1067841003@qq.com> Date: Mon, 30 Nov 2026 00:23:27 +0800 Subject: [PATCH 1/2] [Fix][TOPI] Avoid zero division in unit crop resize --- python/tvm/topi/image/resize.py | 4 +- .../test_frontend_onnx_resize_crop_unit.py | 105 ++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 tests/python/relax/test_frontend_onnx_resize_crop_unit.py 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..169f48ce132b --- /dev/null +++ b/tests/python/relax/test_frontend_onnx_resize_crop_unit.py @@ -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. +"""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): + width = tvm_tirx.tirx.Var("width", "int32") + expression = 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 = tvm_tirx.tirx.stmt_functor.substitute( + expression, {width: tvm_tirx.tirx.const(target_width, "int32")} + ) + coordinate = tvm_tirx.arith.Analyzer().simplify(expression) + expected = 3.0 if target_width == 1 else 1.2 + np.testing.assert_allclose(float(coordinate), expected, rtol=1e-6) From 2b2c7448f8e210c117d257586bb8c6b9d953fc1b Mon Sep 17 00:00:00 2001 From: Nanmur <1067841003@qq.com> Date: Mon, 30 Nov 2026 22:11:46 +0800 Subject: [PATCH 2/2] [Tests][TOPI] Use standalone TIRx for symbolic crop resize --- .../test_frontend_onnx_resize_crop_unit.py | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/tests/python/relax/test_frontend_onnx_resize_crop_unit.py b/tests/python/relax/test_frontend_onnx_resize_crop_unit.py index 169f48ce132b..35763ee6be2a 100644 --- a/tests/python/relax/test_frontend_onnx_resize_crop_unit.py +++ b/tests/python/relax/test_frontend_onnx_resize_crop_unit.py @@ -88,18 +88,19 @@ def test_resize_crop_unit_extent(method, size, roi): @pytest.mark.parametrize("target_width", [1, 2, 5]) def test_resize_crop_symbolic_coordinate(target_width): - width = tvm_tirx.tirx.Var("width", "int32") - expression = 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 = tvm_tirx.tirx.stmt_functor.substitute( - expression, {width: tvm_tirx.tirx.const(target_width, "int32")} + 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, + ), ) - coordinate = tvm_tirx.arith.Analyzer().simplify(expression) + 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 - np.testing.assert_allclose(float(coordinate), expected, rtol=1e-6) + assert isinstance(coordinate, tvm_tirx.ir.FloatImm) + np.testing.assert_allclose(coordinate.value, expected, rtol=1e-6)