[Bug][Relax][TOPI] RoiAlign mode=max returns the average of the sample points
维护者通常 3 天内回复
评估
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 新手友好度
- 70/100
- Issue 类型
- 缺陷
- 描述清晰度
- 描述清楚
- 活跃度
- 活跃
- 技术栈
- python
调研方向
从 python/tvm/topi/vision/roi_align.py 开始:阅读 _sample_common,它只实现 average pooling,然后阅读 roi_align_nchw,它计算 max_mode 却把 avg_mode 传入两个分支。运行附带的 repro.py(或用 mode=max 重新构建相同的 ONNX RoiAlign 节点)以在编辑前确认不匹配,并检查 tests/python 下现有的 roi_align topi 测试以了解预期的调用约定。完成意味着 repro.py 以 0 退出,并且 max 模式与 onnxruntime 的 [1.0125, 1.125, 1.9125, 2.025] 匹配,同时不改变 avg 模式的结果。
由索引模型根据 Issue 内容生成。
描述
Bug Description
topi.vision.roi_align._sample_common accepts only avg_mode; roi_align_nchw computes max_mode but forwards avg_mode in both branches, so mode=max silently computes the mean over the sample grid.
Expected Behavior
RoiAlign with mode=max, output_height=output_width=2, sampling_ratio=1 must return onnxruntime's [1.0125, 1.125, 1.9125, 2.025].
Actual Behavior
TVM returns [1.575, 1.825, 3.575, 3.825], the average of the same sample points.
Real-world Impact & Practical Relevance
Detection/segmentation models that use max-pooling RoiAlign get average-pooled features and silently lose accuracy; the shape and dtype remain correct.
Environment
- Apache TVM:
0.27.0.post1(PyPI wheel, published 2026-09-29); the buggy code path is unchanged onmainat3d89c4991c5a37492f470800231a5ea8f57a95c6(2026-11-22, static inspection). - OS / Python: Ubuntu 22.04.5 / Python 3.10.12, LLVM CPU target.
- onnx 1.13.1, onnxruntime 1.20.0, NumPy 1.26.4.
Steps to Reproduce
Save the following as repro.py and run python repro.py (exit status 1
means the bug is reproduced):
#!/usr/bin/env python3
"""BUG-0106 -- [Relax ONNX frontend / topi] RoiAlign mode=max returns the average.
topi's roi_align_nchw computes max_mode but only forwards avg_mode to the
sampling helper (_sample_common), so mode=max silently computes the average
of the sample points.
Exit status: 0 if TVM matches ONNX Runtime, 1 if the bug is reproduced.
Run: python repro.py [--target llvm]
"""
import argparse
import os
os.environ.update({k: "1" for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS",
"OPENBLAS_NUM_THREADS", "TVM_NUM_THREADS")})
import numpy as np
import onnx
import onnxruntime as ort
import tvm
from onnx import TensorProto as T
from onnx import helper
from tvm import relax
from tvm.relax.frontend.onnx import from_onnx
def vi(name, dt, shape):
return helper.make_tensor_value_info(name, dt, shape)
def make_model(nodes, inputs, outputs, inits=(), opset=17):
g = helper.make_graph(nodes, "g", inputs, outputs, initializer=list(inits))
m = helper.make_model(g, opset_imports=[helper.make_opsetid("", opset)])
m.ir_version = 8
onnx.checker.check_model(m)
return m
def run_ort(m, feeds):
s = ort.InferenceSession(m.SerializeToString(), providers=["CPUExecutionProvider"])
return s.run(None, feeds)
def run_tvm(m, feeds, target):
mod = from_onnx(m, shape_dict={k: list(v.shape) for k, v in feeds.items()})
mod = relax.transform.LegalizeOps()(mod)
ex = tvm.compile(mod, target=target)
vm = relax.VirtualMachine(ex, tvm.cpu())
out = vm["main"](*feeds.values())
if not isinstance(out, (list, tuple)):
out = [out]
return [o.numpy() if hasattr(o, "numpy") else o for o in out]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--target", default="llvm")
args = ap.parse_args()
x = (np.arange(64, dtype="float32").reshape(1, 1, 8, 8) / 10.0)
rois = np.array([[1.0, 1.0, 6.0, 6.0]], np.float32)
bidx = np.zeros((1,), np.int64)
node = helper.make_node("RoiAlign", ["x", "rois", "bidx"], ["y"], mode="max",
coordinate_transformation_mode="half_pixel",
sampling_ratio=1, output_height=2, output_width=2,
spatial_scale=1.0)
m = make_model([node],
[vi("x", T.FLOAT, [1, 1, 8, 8]), vi("rois", T.FLOAT, [1, 4]),
vi("bidx", T.INT64, [1])],
[vi("y", T.FLOAT, [1, 1, 2, 2])], opset=16)
feeds = {"x": x, "rois": rois, "bidx": bidx}
ref = run_ort(m, feeds)[0]
got = np.asarray(run_tvm(m, feeds, args.target)[0])
print("RoiAlign mode=max, output 2x2, sampling_ratio=1")
print("ONNX Runtime:", np.round(ref.ravel(), 4))
print("TVM :", np.round(got.ravel(), 4))
ok = np.allclose(ref, got, rtol=1e-5, atol=1e-6)
print("NOT REPRODUCED (fixed?)" if ok else "BUG REPRODUCED")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())
Error Log / Traceback
RoiAlign mode=max, output 2x2, sampling_ratio=1
ONNX Runtime: [1.0125 1.125 1.9125 2.025 ]
TVM : [1.575 1.825 3.575 3.825]
BUG REPRODUCED
Prior Report Search
No existing issue for the max/avg mix-up. #11383 (closed) was a Relay aligned=True rounding discrepancy, and #19501 a half_pixel handling issue; both differ.
repro.py
- 主要语言
- Python
- 星标
- 13.9k
- 派生
- 4.1k
- 平均合并
- 4 天 22 小时
- 30 天内合并 PR
- 22
环境准备
这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
apache/tvm 的其他 Issue
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is None可能已有人在做 关联的 PR 仍在进行中或已合并。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 3 天内回复
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensors未关闭needs-triage type: bug
难度 2/5 1-3 小时 新手友好度 82/100
维护者通常 3 天内回复
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradients可能已有人在做 @pierceluu10 于 4 天前认领。 未关闭needs-triage type: bug
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 3 天内回复
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputs可能已有人在做 @tandede 于 9 天前认领。 未关闭needs-triage type: bug
难度 2/5 1-3 小时 新手友好度 70/100
维护者通常 3 天内回复
-
needs-triage type: bug
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 3 天内回复
相似的 Issue
-
难度 1/5 1-3 小时 新手友好度 78/100
web-push-libs/pywebpush#216 · 1 条评论 ·
-
难度 2/5 1-3 小时 新手友好度 72/100
AgriciDaniel/claude-seo#572 ·
维护者通常 5 天内回复
-
area:print-dispatch
难度 2/5 1-3 小时 新手友好度 92/100
维护者通常 1 天内回复
-
area: docs domain: technical-writing good first issue type: documentation
难度 2/5 1-3 小时 新手友好度 80/100
Deepak3699/Ai_Mentor#919 ·
维护者通常 2 天内回复
-
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 1 天内回复