Skip to content

[Bug][Relax][ONNX] Resize silently drops non-unit batch scaling #20865

Open

Description

@Yuhx141

Summary

For a four-dimensional Resize input [4,2,2,2] and scales [0.3,1,0.7,2.5], Relax returns [4,2,1,5] rather than [1,2,1,5]. The model is accepted and executed, but the leading scale has no effect.

Environment

Linux x86_64 CPU/LLVM; Python 3.12.3; TVM 0.28.dev0; LLVM 18.1.3; ONNX 1.22.0; NumPy 2.5.4; ONNX Runtime 1.29.0 (CPUExecutionProvider).

The installed TVM binary's exact build source revision is UNKNOWN. Source links are a separate static inspection of main at 70ec7d5bf20326ef301ee3f06eb6aed51760331d; that revision was not built or executed for this report.

Loaded binary SHA256 identities:

  • libtvm_ffi.so: 12072d0ccd9d5cb2c6dac80d42f4217ab50dbf795db03197000614a7a770a816
  • libtvm_compiler.so: 574a573fe994e5eda7352ddd8d685e64e45c7934bdeeaab57a5a272a77792ab1
  • libtvm_runtime.so: 4175916fc0ce6266c912629d2255094b94087425c6ab53ffd5e004d4c292c828
  • libtvm_runtime_extra.so: 79c93351fca12dd7851964890cea7da65dd2b2e0e64e5c28bfed56c878b70817

Expected and observed behavior

Expected shape (1,2,1,5); TVM shape (4,2,1,5). Setting only the batch scale to 1 preserves the spatial workload and passes both shape and value checks.

Resize-11 supplies one positive scale per input dimension. This nearest/asymmetric/floor witness has an independent integer-index formula; ONNX ReferenceEvaluator and unoptimized ORT CPU agree with it.

Standalone reproduction

Save this as repro.py in an LLVM-enabled TVM environment, then run:

OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 python repro.py
from pathlib import Path
import hashlib
import numpy as np
import onnx
import onnxruntime as ort
import tvm
from onnx import TensorProto as T, helper as h, numpy_helper as nh
from onnx.reference import ReferenceEvaluator
from tvm import relax
from tvm.relax.frontend.onnx import from_onnx


def make(nodes, inputs, outputs, initializers=(), opset=18):
    model = h.make_model(h.make_graph(nodes, "repro", inputs, outputs, list(initializers)),
                         opset_imports=[h.make_opsetid("", opset)], ir_version=10)
    onnx.checker.check_model(model, full_check=True)
    return model


def tvm_run(model, feeds):
    mod = from_onnx(model, keep_params_in_input=False)
    names = [value.name for value in model.graph.input]
    executable = relax.build(mod, target="llvm", relax_pipeline="default")
    result = relax.VirtualMachine(executable, tvm.cpu())["main"](
        *[tvm.runtime.tensor(feeds[name]) for name in names])
    return [result.numpy()] if hasattr(result, "numpy") else [v.numpy() for v in result]


def save(label, model, feeds):
    folder = Path("artifacts") / label
    folder.mkdir(parents=True, exist_ok=True)
    onnx.checker.check_model(model, full_check=True)
    onnx.save(model, folder / "model.onnx")
    np.savez(folder / "inputs.npz", **feeds)
    print(label, "model_sha256", hashlib.sha256((folder / "model.onnx").read_bytes()).hexdigest())
    print(label, "inputs_sha256", hashlib.sha256((folder / "inputs.npz").read_bytes()).hexdigest())


def reference(model, feeds, expected, check_ort=True):
    outputs = ReferenceEvaluator(model).run(None, feeds)
    for a, b in zip(outputs, expected, strict=True):
        assert a.shape == b.shape and a.dtype == b.dtype, (a.shape, a.dtype, b.shape, b.dtype)
        np.testing.assert_allclose(a, b, rtol=1e-5, atol=1e-6)
    if check_ort:
        opts = ort.SessionOptions()
        opts.intra_op_num_threads = opts.inter_op_num_threads = 1
        opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
        outputs = ort.InferenceSession(model.SerializeToString(), opts,
            providers=["CPUExecutionProvider"]).run(None, feeds)
        for a, b in zip(outputs, expected, strict=True):
            assert a.shape == b.shape and a.dtype == b.dtype
            np.testing.assert_allclose(a, b, rtol=1e-5, atol=1e-6)


def error_line(error):
    return type(error).__name__ + ": " + str(error).splitlines()[-1]


def same(actual, expected):
    assert actual.shape == expected.shape and actual.dtype == expected.dtype
    np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)


x = np.arange(32, dtype="float32").reshape(4, 2, 2, 2)
for nc_scale in (0.3, 1.0):
    scales = np.array([nc_scale, 1, 0.7, 2.5], dtype="float32")
    shape = [1 if nc_scale == 0.3 else 4, 2, 1, 5]
    model = make([h.make_node("Resize", ["x", "roi", "scales"], ["y"],
        mode="nearest", coordinate_transformation_mode="asymmetric", nearest_mode="floor")],
        [h.make_tensor_value_info("x", T.FLOAT, [4, 2, 2, 2])],
        [h.make_tensor_value_info("y", T.FLOAT, shape)],
        [nh.from_array(np.zeros(8, dtype="float32"), "roi"), nh.from_array(scales, "scales")], opset=11)
    # ONNX asymmetric/floor indexing uses the supplied scale on every axis.
    expected = x
    for axis, (size, scale) in enumerate(zip(shape, scales)):
        indices = np.floor(np.arange(size) / scale).astype("int64")
        expected = np.take(expected, indices, axis=axis)
    save(str(nc_scale), model, {"x": x})
    reference(model, {"x": x}, [expected])
    actual = tvm_run(model, {"x": x})[0]
    print("batch scale", nc_scale, "expected shape", expected.shape, "TVM shape", actual.shape)
    if nc_scale == 0.3:
        assert actual.shape == (4, 2, 1, 5) and expected.shape == (1, 2, 1, 5)
    else:
        same(actual, expected)
        print("batch/channel scale-one control passed")

Recorded output

batch scale 0.3 expected shape (1, 2, 1, 5) TVM shape (4, 2, 1, 5)
batch scale 1.0 expected shape (4, 2, 1, 5) TVM shape (4, 2, 1, 5)
batch/channel scale-one control passed

Causal isolation and related work

The Resize converter computes all output dimensions and then retains only sizes[2:] before calling a spatial resize primitive. The batch/channel dimensions are consequently inherited from the input. If scaling those axes is unsupported, conversion should reject it explicitly rather than silently return a differently shaped result.

#19570 / #19698 concern spatial coordinates recomputed from rounded sizes. This report concerns a discarded leading dimension. #20415 covers Upsample/Resize-10 and explicitly retains the existing Resize-11 through Resize-17 path used here.

This self-contained script is a newly constructed minimal diagnostic from the same graph-testing investigation, not a byte-identical replay of an archived model. It needs only TVM, ONNX, NumPy and ONNX Runtime, downloads no files, and writes its generated models and inputs to artifacts/. The assertions check both the observed failure/wrong result and the normal controls; exit code zero means that diagnostic reproduced. No global novelty or current-main execution claim is made.

Diagnostic and artifact checksums

Reproducer SHA256: bcda75b8491c797e6ed33bfb6bba6fe1f22c703cdc892924cffd1b81a1b0959f

  • artifacts/0.3/inputs.npz: 291a13198c9dbfa5933ac99ef001fe2dd80f7debc7da24288aa9f5aeef9a6dc1
  • artifacts/0.3/model.onnx: 07adc040dfdd50a3b1bbbc78709b5d2336a8d1e2af611151a59d92d81567bd2c
  • artifacts/1.0/inputs.npz: 291a13198c9dbfa5933ac99ef001fe2dd80f7debc7da24288aa9f5aeef9a6dc1
  • artifacts/1.0/model.onnx: dffdf71f21f0b99d88b20966dd3eddff964c8e8c90f89740dafb68ef313f0ff4

I am happy to help add an in-tree regression test or check a proposed correction.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions