[Bug] [Relax][ONNX] RoiAlign half_pixel applies the -0.5 offset before spatial_scale
Los mantenedores suelen responder en 3 días
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 45/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Área
- backend, machine-learning
Línea de trabajo
Read the ONNX RoiAlign converter in python/tvm/relax/frontend/onnx/onnx_frontend.py and the PyTorch converter in python/tvm/relax/frontend/torch/exported_program_translator.py; compare their offset handling with TOPI's python/tvm/topi/vision/roi_align.py. Start by running the self-contained repro from the issue. Done means half_pixel returns 38.5 and output_half_pixel returns 44.0, with the corresponding aligned PyTorch case corrected and existing behavior preserved.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Thanks for participating in the TVM community! We use https://discuss.tvm.apache.org/ for any general usage questions and discussions. The issue tracker is used for actionable items such as feature proposals discussion, roadmaps, and bug tracking. You are always welcomed to post on the forum first 😸
Issues that are inactive for a period of time may get closed. We adopt this policy so that we won't lose track of actionable issues that may fall at the bottom of the pile. Feel free to reopen a new one if you feel there is an additional problem that needs attention when an old one gets closed.
Expected behavior
For ONNX RoiAlign opset 16 with coordinate_transformation_mode="half_pixel", the -0.5 pixel
shift must be applied in feature-map coordinates, i.e. after multiplying ROI coordinates by
spatial_scale: roi * spatial_scale - 0.5 (ONNX reference implementation:
roi_start_w = bottom_rois[...] * spatial_scale - offset, offset = 0.5 for half_pixel).
output_half_pixel must omit the shift. See the ONNX reference implementation.
With the model below (spatial_scale=0.5, ROI center 8), the sampling center is 3.5 for
half_pixel and 4 for output_half_pixel. Both ONNX Runtime and the ONNX ReferenceEvaluator
return 38.5 and 44.0 respectively.
Actual behavior
| coordinate_transformation_mode | manual / ReferenceEvaluator / ORT | TVM |
|---|---|---|
half_pixel |
[38.5] |
[41.25] |
output_half_pixel |
[44.0] |
[44.0] |
All outputs have shape [1, 1, 1, 1] and dtype float32; the mismatch is numeric only.
41.25 corresponds to a sampling center of 3.75, i.e. (8 - 0.5) * 0.5 — the offset was
applied to the input-image ROI coordinates before scaling.
The following excerpt abbreviates the imported IR:
lv2 = R.add(R_1, metadata["ir.GenericConst"][0], ...) # rois - 0.5, before roi_align
gv = R.vision.roi_align(X, lv3, aligned=True, pooled_size=[1, 1],
sample_ratio=1, spatial_scale=0.5) # scale happens here
Both models pass ONNX full checking and compile and execute successfully. The mismatch also reproduces in a fresh process.
Environment
- Actual execution TVM commit (full):
3d89c4991c5a37492f470800231a5ea8f57a95c6(2026-11-22),
LLVM CPU target, Relax VirtualMachine. - Python 3.10.22 (conda-forge), NumPy 1.26.4, ONNX 1.21.0, ONNX Runtime 1.23.2.
- OS: Linux x86_64 (WSL2, kernel 6.18.58.1), CPU: Intel Core i7-14700KF.
- A newer commit
1091f2fc97187bdef99272cb2c598dc3dd572d7c(2026-11-24) was inspected by
source check only (git show <commit>:<path>); it was not built or executed. The same
frontend, PyTorch frontend converter and TOPI code is present there. - PyTorch cross-check: torch 2.14.1+cu130, torchvision 0.29.2+cu132.
Steps to reproduce
Save the following script as repro.py and run python repro.py in the environment above.
It builds both models in memory and prints the complete output shape, dtype and values.
It needs no model downloads or repository-specific helpers. The process exits with status 0;
the incorrect value is visible in the printed TVM result.
# Self-contained repro for: ONNX Relax RoiAlign applies half_pixel -0.5 before spatial_scale.
# Requires only numpy, onnx, onnxruntime, tvm and tvm_tirx (no helpers from this repository).
import numpy as np
import onnx
import onnxruntime as ort
from onnx import TensorProto as T, helper as h
from onnx.reference import ReferenceEvaluator
import tvm
import tvm_tirx
import tvm_tirx.ir
from tvm import relax
from tvm.relax.frontend.onnx import from_onnx
def build_model(coordinate_transformation_mode):
node = h.make_node(
"RoiAlign", ["X", "R", "B"], ["Y"],
coordinate_transformation_mode=coordinate_transformation_mode,
mode="avg", output_height=1, output_width=1,
sampling_ratio=1, spatial_scale=0.5)
graph = h.make_graph(
[node], "roi_align_repro",
[h.make_tensor_value_info("X", T.FLOAT, [1, 1, 10, 10]),
h.make_tensor_value_info("R", T.FLOAT, [1, 4]),
h.make_tensor_value_info("B", T.INT64, [1])],
[h.make_tensor_value_info("Y", T.FLOAT, [1, 1, 1, 1])])
model = h.make_model(graph, opset_imports=[h.make_opsetid("", 16)])
model.ir_version = 11
return model
def to_numpy(value):
return np.asarray(value.numpy() if hasattr(value, "numpy") else value)
def run_one(coordinate_transformation_mode, expected_value):
model = build_model(coordinate_transformation_mode)
onnx.checker.check_model(model, full_check=True)
y, x = np.arange(10)[:, None], np.arange(10)[None, :]
feeds = {
"X": (10 * y + x).astype(np.float32)[None, None],
"R": np.array([[4, 4, 12, 12]], dtype=np.float32),
"B": np.array([0], dtype=np.int64),
}
expected = np.full((1, 1, 1, 1), expected_value, dtype=np.float32)
ref_out = to_numpy(ReferenceEvaluator(model).run(None, feeds)[0])
sess_opts = ort.SessionOptions()
sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
ort_out = to_numpy(ort.InferenceSession(
model.SerializeToString(), providers=["CPUExecutionProvider"], sess_options=sess_opts
).run(None, feeds)[0])
mod = from_onnx(model, keep_params_in_input=False, sanitize_input_names=False)
mod = relax.transform.DecomposeOpsForInference()(mod)
mod = relax.transform.LegalizeOps()(mod)
with tvm_tirx.ir.transform.PassContext(opt_level=3):
exe = tvm.compile(mod, target="llvm")
device = tvm_tirx.cpu()
vm = relax.VirtualMachine(exe, device)
param_names = [p.name for p in mod["main"].params]
args = [tvm_tirx.runtime.tensor(feeds[n], device) for n in param_names]
raw = vm["main"](*args)
outs = raw if isinstance(raw, (list, tuple)) else [raw]
tvm_out = to_numpy(outs[0])
print("=== coordinate_transformation_mode =", coordinate_transformation_mode, "===")
for name, arr in [("manual", expected), ("ReferenceEvaluator", ref_out),
("ORT", ort_out), ("TVM", tvm_out)]:
print(f"{name:19s} shape={list(arr.shape)} dtype={arr.dtype} value={arr.ravel().tolist()}")
if __name__ == "__main__":
run_one("half_pixel", 38.5) # spec: 8*0.5 - 0.5 = 3.5 -> 38.5
run_one("output_half_pixel", 44.0) # no offset: 8*0.5 = 4 -> 44
Observed output:
=== coordinate_transformation_mode = half_pixel ===
manual shape=[1, 1, 1, 1] dtype=float32 value=[38.5]
ReferenceEvaluator shape=[1, 1, 1, 1] dtype=float32 value=[38.5]
ORT shape=[1, 1, 1, 1] dtype=float32 value=[38.5]
TVM shape=[1, 1, 1, 1] dtype=float32 value=[41.25]
=== coordinate_transformation_mode = output_half_pixel ===
manual shape=[1, 1, 1, 1] dtype=float32 value=[44.0]
ReferenceEvaluator shape=[1, 1, 1, 1] dtype=float32 value=[44.0]
ORT shape=[1, 1, 1, 1] dtype=float32 value=[44.0]
TVM shape=[1, 1, 1, 1] dtype=float32 value=[44.0]
Additional evidence from the PyTorch frontend (same root cause, not a second bug)
The PyTorch frontend converter _torchvision_roi_align contains the same offset order. A
torch.export of a wrapper around torchvision.ops.roi_align was confirmed to hit
torch.ops.torchvision.roi_align.default. With the same linear feature map and ROI
(spatial_scale=0.5, sampling_ratio=1), native torchvision and TVM give:
| aligned | native torchvision | TVM via PyTorch frontend |
|---|---|---|
True |
[38.5] |
[41.25] |
False |
[44.0] |
[44.0] |
The imported IR shows R.subtract(boxes, R.const(0.5, ...)) before
R.vision.roi_align(..., aligned=True, spatial_scale=0.5). This was also reproduced in a fresh
process from frozen ExportedPrograms. It is included as additional evidence for the same
offset-order root cause, not as an independent second bug.
PyTorch converter at the executed commit:
https://github.com/apache/tvm/blob/3d89c4991c5a37492f470800231a5ea8f57a95c6/python/tvm/relax/frontend/torch/exported_program_translator.py#L1360-L1394
The same code was confirmed at commit 1091f2fc97187bdef99272cb2c598dc3dd572d7c by source
inspection only (not built or executed).
Root cause and source evidence
- ONNX frontend
RoiAlignconverter, executed commit:
https://github.com/apache/tvm/blob/3d89c4991c5a37492f470800231a5ea8f57a95c6/python/tvm/relax/frontend/onnx/onnx_frontend.py#L4277-L4280
(offset = relax.const([-0.5, ...]),rois = relax.op.add(rois, offset),aligned = True).
The same code was confirmed at the later commit by source inspection only:
https://github.com/apache/tvm/blob/1091f2fc97187bdef99272cb2c598dc3dd572d7c/python/tvm/relax/frontend/onnx/onnx_frontend.py#L4277-L4280 - TOPI
_sample_commonappliesspatial_scaleto ROIs and usesalignedonly to skip the legacy
max(..., 1.0)clamp; it does not apply any-0.5shift:
https://github.com/apache/tvm/blob/3d89c4991c5a37492f470800231a5ea8f57a95c6/python/tvm/topi/vision/roi_align.py#L41-L53 - Relax op contract for
aligned("without the legacy 1-pixel clamp"):
https://github.com/apache/tvm/blob/3d89c4991c5a37492f470800231a5ea8f57a95c6/python/tvm/relax/op/vision/roi_align.py#L68-L69
Possible fix direction
Ensure the half-pixel shift is applied after spatial scaling in both frontends that currently
apply it before scaling: the ONNX half_pixel path and the PyTorch aligned=True path. Preserve
the output_half_pixel / aligned=False behavior. The current TOPI implementation uses aligned
to control minimum ROI extent, not to apply a coordinate shift, and other callers already pass
aligned=True with their own semantics. Adding a global offset in TOPI while the frontends keep
their existing offsets would shift the coordinates twice. This report contains no proposed or
tested patch.
Triage
- needs-triage
Related reports inspected include #19501,
#11383,
#21040,
#12869, and
#12906.
I did not find a report specifically identifying the offset-before-scaling behavior; this is not
a claim of first discovery. The reproduction covers ONNX opset 16 and the PyTorch frontend, both
with average pooling and a non-unit spatial scale.
- Lenguaje dominante
- Python
- Estrellas
- 13.9k
- Forks
- 4.1k
- Merge medio
- 4 d 22 h
- PR fusionados (30 d)
- 22
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de apache/tvm
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is NonePosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensorsAbiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 3 días
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradientsPosiblemente ocupada @pierceluu10 la tomó hace 4 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputsPosiblemente ocupada @tandede la tomó hace 9 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 3 días
-
needs-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
apache/tvm#21043 · 1 comentario ·
Los mantenedores suelen responder en 3 días
Todos los issues de apache/tvm
Issues similares
-
Dificultad 1/5 1-3 horas Aptitud para principiantes 78/100
web-push-libs/pywebpush#216 · 1 comentario ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
AgriciDaniel/claude-seo#572 ·
Los mantenedores suelen responder en 5 días
-
area:print-dispatch
Dificultad 2/5 1-3 horas Aptitud para principiantes 92/100
Los mantenedores suelen responder en 1 día
-
area: docs domain: technical-writing good first issue type: documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
Deepak3699/Ai_Mentor#919 ·
Los mantenedores suelen responder en 2 días
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día