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

未关闭
#20,865 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
50/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
compilers

调研方向

Start in the Resize converter in python/tvm/relax/frontend/onnx/onnx_frontend.py, where all output sizes are computed and then only sizes[2:] is kept before the spatial resize call. Run the standalone repro.py from the issue to confirm the batch dimension becomes 4 instead of 1. Done means either the output shape and values match the ONNX reference for a non-unit batch scale, or conversion rejects that case with a clear error. Check the existing ONNX frontend Resize tests before adding a regression case.

由索引模型根据 Issue 内容生成。

描述

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.

主要语言
Python
星标
13.9k
派生
4k
平均合并
7 小时 59 分钟
30 天内合并 PR
159

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

apache/tvm 的其他 Issue

查看 apache/tvm 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。