[Bug] [ONNX] TopK opset 10 ignores K input and returns one element
Les mainteneurs répondent en général sous 3 jours
Évaluation
- Difficulté
- 3/5
- Temps estimé
- 1-2 jours
- Accessibilité débutants
- 75/100
- Type d'issue
- Bug
- Clarté
- Clairement spécifiée
- Activité
- Active
- Stack technique
- python
- Domaine
- compilers, machine-learning
Piste de recherche
Start with the ONNX frontend converter and dispatcher linked in the issue, especially the TopK implementations for opsets 1 and 11. Reproduce the reported opset 10 behavior with the supplied script, then check existing TopK frontend tests for where version coverage belongs. Done means opset 10 uses its K input and regression coverage checks values and indices for opsets 1, 10, and 11.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
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 a valid ONNX TopK opset 10 model with X=[1, 4, 2, 3], axis=0 and constant K=[2], return values [4, 3] and int64 indices [1, 3], both with shape (2,). TopK-10 takes K as its second input according to the ONNX specification.
Actual behavior
Import, compilation and execution succeed, but TVM returns values [4] and indices [1], both with shape (1,). ONNX Runtime returns the expected arrays. With K=[3], TVM still returns one element; K=[1] happens to match. Opset 1 with the k=2 attribute and opset 11 with K=[2] both return the expected two elements.
In the executed commit's frontend, TopK implements versions 1 and 11. The dispatcher selects version 1 for opset 10; that implementation reads the old k attribute and defaults to 1, rather than reading inputs[1].
Environment
- TVM
0.28.dev0, commit3d89c4991c5a37492f470800231a5ea8f57a95c6(built and executed). - Ubuntu 26.04.1 LTS, WSL2 Linux 6.18.58.1, x86_64, Intel Core i7-14700KF.
- Python 3.10.22; NumPy 1.26.4; ONNX 1.21.0; ONNX Runtime 1.23.2.
- Target: LLVM; runtime: Relax VM on CPU. CMake build type: Release;
TVM_TIRX_USE_CUDA=OFF,TVM_TIRX_USE_LLVMpoints to the environment'sllvm-config. - A later commit,
1091f2fc97187bdef99272cb2c598dc3dd572d7c, was source-inspected only; it was not built or executed for this report.
Steps to reproduce
Run the following standalone script with the dependencies above. It checks the ONNX models, executes ONNX Runtime and TVM, and checks both outputs against a NumPy reference. The script prints FAIL for incorrect outputs but exits with status 0; inspect the printed results. K is both an initializer and graph input; ONNX Runtime warns about this, and the script explicitly feeds the same K value.
import numpy as np
import onnx
import onnxruntime as ort
from onnx import TensorProto as T, helper as h, numpy_helper as nh
import tvm
import tvm_tirx
import tvm_tirx.ir
from tvm import relax
from tvm.relax.frontend.onnx import from_onnx
DATA = np.array([1.0, 4.0, 2.0, 3.0], dtype=np.float32)
CASES = [
("opset1_k2", 1, 2, True),
("opset10_k1", 10, 1, False),
("opset10_k2", 10, 2, False),
("opset10_k3", 10, 3, False),
("opset11_k2", 11, 2, False),
]
def build_model(opset, k, attr_form):
X = h.make_tensor_value_info("X", T.FLOAT, [4])
if attr_form:
node = h.make_node("TopK", ["X"], ["values", "indices"], axis=0, k=k)
inputs, inits = [X], []
else:
K = h.make_tensor_value_info("K", T.INT64, [1])
node = h.make_node("TopK", ["X", "K"], ["values", "indices"], axis=0)
inputs = [X, K]
inits = [nh.from_array(np.array([k], dtype=np.int64), "K")]
graph = h.make_graph(
[node], "topk_repro", inputs,
[h.make_tensor_value_info("values", T.FLOAT, [k]),
h.make_tensor_value_info("indices", T.INT64, [k])],
initializer=inits)
model = h.make_model(graph, opset_imports=[h.make_opsetid("", opset)])
model.ir_version = 11
return model
def manual(k):
order = np.argsort(-DATA, kind="stable")[:k]
return DATA[order].astype(np.float32), order.astype(np.int64)
def check(name, got, expected, expected_dtype):
got = np.asarray(got)
ok = (got.shape == expected.shape
and got.dtype == np.dtype(expected_dtype)
and np.array_equal(got, expected))
print(name, got.shape, got.dtype, got.tolist(), "expect",
expected.shape, expected_dtype, expected.tolist(), "OK" if ok else "FAIL")
return ok
def run_tvm(model, feeds):
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)
names = [p.name for p in mod["main"].params]
args = [tvm_tirx.runtime.tensor(feeds[n], device) for n in names]
return [v.numpy() if hasattr(v, "numpy") else np.asarray(v)
for v in vm["main"](*args)], str(mod)
def main():
opts = ort.SessionOptions()
opts.intra_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
for tag, opset, k, attr_form in CASES:
print("\n===", tag, "===")
model = build_model(opset, k, attr_form)
onnx.checker.check_model(model, full_check=True)
feeds = {"X": DATA}
if not attr_form:
feeds["K"] = np.array([k], dtype=np.int64)
ort_out = ort.InferenceSession(
model.SerializeToString(), providers=["CPUExecutionProvider"]).run(None, feeds)
exp_v, exp_i = manual(k)
check("ORT values", ort_out[0], exp_v, "float32")
check("ORT indices", ort_out[1], exp_i, "int64")
out, ir = run_tvm(model, feeds)
print("IR:", [ln.strip() for ln in ir.splitlines() if "topk" in ln][:1])
check("TVM values", out[0], exp_v, "float32")
check("TVM indices", out[1], exp_i, "int64")
if __name__ == "__main__":
main()
For opset 10, K=2 and K=3 print FAIL for both TVM outputs; the other three TVM cases and all ORT cases print OK. No exception or stack trace is produced.
Triage
- needs-triage
A search of related TopK issues and PRs did not find the same root cause. The previously reported indices dtype issue (#19972/#19973) concerns a different behavior; indices here are int64. A possible fix is to add an opset-10 TopK converter that reads the constant K input, retaining the opset-1 attribute implementation. Regression coverage should check both outputs for opsets 1, 10 and 11.
- Langage dominant
- Python
- Étoiles
- 13.9k
- Forks
- 4.1k
- Merge moyen
- 4 j 22 h
- PR mergées (30 j)
- 22
Préparer son environnement
Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de apache/tvm
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is NonePeut-être pris Une pull request liée à cette issue est ouverte ou déjà fusionnée. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
Les mainteneurs répondent en général sous 3 jours
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensorsOuverteneeds-triage type: bug
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
Les mainteneurs répondent en général sous 3 jours
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradientsPeut-être pris @pierceluu10 l’a pris il y a 5 jours. Ouverteneeds-triage type: bug
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
Les mainteneurs répondent en général sous 3 jours
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputsPeut-être pris @tandede l’a pris il y a 9 jours. Ouverteneeds-triage type: bug
Difficulté 2/5 1-3 heures Accessibilité débutants 70/100
Les mainteneurs répondent en général sous 3 jours
-
needs-triage type: bug
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
apache/tvm#21043 · 1 commentaire ·
Les mainteneurs répondent en général sous 3 jours
Toutes les issues de apache/tvm
Issues similaires
-
Difficulté 1/5 Moins d'une heure Accessibilité débutants 92/100
Techiebutler/freeframe#687 ·
Les mainteneurs répondent en général sous 1 jour
-
bug verbose GC
Difficulté 2/5 1-3 heures Accessibilité débutants 74/100
IBM/javacore-analyser#677 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 79/100
Les mainteneurs répondent en général sous 2 jours
-
area/config comp/plugins P1 platform/qqbot tool/file type/bug
Difficulté 2/5 1-3 heures Accessibilité débutants 75/100
NousResearch/hermes-agent#163932 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
plugins/dsh: todayStr() computes UTC but is documented as local — journal entries written 00:00–08:00 local land in the previous day's filePeut-être pris @Beehtrix l’a pris aujourd’hui. Ouvertebug
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
zilliztech/memsearch#907 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour