[Bug][Relax][TOPI] RoiAlign mode=max returns the average of the sample points

オープン 初心者向け
#21,040 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 3 日以内に返信

@hulkbig がすでに取り組んでいます。

2026年12月1日 から。

  • #21108 @hulkbig による — オープン

評価

難易度
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 を実行する(または同じ ONNX RoiAlign ノードを mode=max で再構築する)とともに、tests/python 配下の既存の roi_align topi テストで想定される呼び出し規約を確認します。完了とは、repro.py が 0 で終了し、avg モードの結果を変更せずに max モードが onnxruntime の [1.0125, 1.125, 1.9125, 2.025] と一致することです。

索引モデルが issue の本文から書いたものです。

説明

needs-triage type: bug
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 on main at 3d89c4991c5a37492f470800231a5ea8f57a95c6 (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時間
マージ済み PR(30日)
22

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

apache/tvm のほかの issue

apache/tvm の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。