[Bug][TOPI][Relax] ArgMin returns -1 for a nonempty tensor of largest finite values

Abierto
#20,866 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
Medio día
Aptitud para principiantes
55/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
cpp, python
Área
compilers

Línea de trabajo

The bug is in MakeArgminReducer in include/tvm/topi/reduction.h, which initializes the index to -1 and the value to the max identity, so the sentinel can win the first-index tie when the input equals that identity. Run the attached repro.py to confirm that the largest-finite and +Inf cases return -1 while the adjacent-finite control returns 0. Done means those cases return 0, the control still passes, and a regression test covers the tie.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Summary

ArgMin(axis=0, select_last_index=0) of three identical FLOAT32 maximum finite values returns -1. Index 0 is the required first minimum. Replacing the values with the immediately adjacent lower finite value returns 0. The script also checks an all-positive-infinity input, which returns -1 in TVM.

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

Largest finite: expected [0], TVM [-1]. Adjacent finite control: expected [0], TVM [0]. All +Inf: expected [0], TVM [-1].

ArgMin-13 selects the first occurrence by default. A nonempty three-element input must yield an index in [0,3). NumPy, ONNX ReferenceEvaluator and unoptimized ORT CPU return 0. The primary finite witness contains no NaN or infinity.

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)


model = make([h.make_node("ArgMin", ["x"], ["y"], axis=0, keepdims=1, select_last_index=0)],
    [h.make_tensor_value_info("x", T.FLOAT, [3])],
    [h.make_tensor_value_info("y", T.INT64, [1])], opset=13)
largest = np.full(3, np.finfo("float32").max, dtype="float32")
for label, x in (("largest_finite", largest),
                 ("adjacent_finite", np.nextafter(largest, np.zeros_like(largest))),
                 ("positive_infinity", np.full(3, np.inf, dtype="float32"))):
    expected = np.argmin(x, axis=0, keepdims=True).astype("int64")
    save(label, model, {"x": x})
    reference(model, {"x": x}, [expected])
    actual = tvm_run(model, {"x": x})[0]
    print(label, "expected", expected.tolist(), "TVM", actual.tolist())
    if label == "adjacent_finite":
        same(actual, expected)
        print("adjacent finite control passed")
    else:
        assert actual.tolist() == [-1] and expected.tolist() == [0]

Recorded output

largest_finite expected [0] TVM [-1]
adjacent_finite expected [0] TVM [0]
adjacent finite control passed
positive_infinity expected [0] TVM [-1]

Causal isolation and related work

MakeArgminReducer initializes the index to -1 and value to max_value. Its first-index tie comparison lets the artificial index beat real indices when the input equals the identity value. The sentinel must not compete as a real input index. An infinite identity alone also leaves the all-+Inf tie case to address.

#19558 and #19671 discuss NaN compatibility in the ONNX frontend. This finite-only case reaches a reducer identity/tie invariant and yields an out-of-range index, independently of NaN ordering. It is also distinct from value-only max/min reductions using finite rather than infinite identities.

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: a6ffa61a17f25396fedbb9b810e091eda37528b09d411d5834ba721c757e47ae

  • artifacts/adjacent_finite/inputs.npz: 7668fc975d5bc9a94d1e334e90ecc857d74308556f6d78973565944382eb8e68
  • artifacts/adjacent_finite/model.onnx: f65d7dd00c6c97044e804973eabe84c00dc2b67cd535a257204ca995de810ab6
  • artifacts/largest_finite/inputs.npz: 2c5681b3f4facef395be01233dfd3baea91addd5dda537d5283cf9fff35ea22a
  • artifacts/largest_finite/model.onnx: f65d7dd00c6c97044e804973eabe84c00dc2b67cd535a257204ca995de810ab6
  • artifacts/positive_infinity/inputs.npz: 5d993725260454f464463e0ee7841df62d36a43e96c6dc819fb909445a9bf1f3
  • artifacts/positive_infinity/model.onnx: f65d7dd00c6c97044e804973eabe84c00dc2b67cd535a257204ca995de810ab6

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

Lenguaje dominante
Python
Estrellas
13.9k
Forks
4k
Merge medio
8 h 2 min
PR fusionados (30 d)
180

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

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de apache/tvm

Todos los issues de apache/tvm

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.