[Bug][Relax][ONNX] MeanVarianceNormalization is numerically unstable and can produce NaN

Aperta
#21,042 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 3 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
63/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

Start with the MeanVarianceNormalization converter in the Relax ONNX frontend, reached through from_onnx in tvm.relax.frontend.onnx, and find where it computes sqrt(E[x^2] - E[x]^2). Run repro.py with --target llvm to see the NaN and mismatch. Done means the two-sample cases with eps=1e-4 and 1e-3 match ONNX Runtime output within tolerance, using the ONNX definition (X - E[X]) / sqrt(E[(X - E[X])^2]).

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

needs-triage type: bug
Bug Description

ONNX defines MeanVarianceNormalization as (X - E[X]) / sqrt(E[(X - E[X])^2]). The converter computes the algebraically equal but ill-conditioned sqrt(E[x^2] - E[x]^2) in fp32; for samples close to a common value the subtraction cancels and can even become negative.

Expected Behavior

For x = [[1.0], [1.0 + eps]] with axes=[0]: eps=1e-4 must give about [-1.0012, 0.9988], and eps=1e-3 about [-0.9999, 1.0001], matching onnxruntime.

Actual Behavior

eps=1e-4 gives [nan, nan]; eps=1e-3 gives [-0.836, 0.8362].

Real-world Impact & Practical Relevance

MVN is used as a normalization layer; near-constant input slices (bias fields, padded regions) are common, and the exported model returns NaN instead of the normalized values.

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-0114 -- [Relax ONNX frontend] MeanVarianceNormalization computes sqrt(E[x^2] - E[x]^2) in fp32.

The ONNX definition is (X - E[X]) / sqrt(E[(X - E[X])^2]).  The converter uses
the algebraically equal but numerically unstable sqrt(E[x^2] - E[x]^2).  For
samples that are close to a common value the difference cancels in fp32 and
can even go negative, producing NaN.

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()

    bad = False
    for eps in (1e-4, 1e-3):
        x = np.array([[1.0], [1.0 + eps]], np.float32)
        node = helper.make_node("MeanVarianceNormalization", ["x"], ["y"], axes=[0])
        m = make_model([node], [vi("x", T.FLOAT, [2, 1])], [vi("y", T.FLOAT, [2, 1])])
        ref = run_ort(m, {"x": x})[0]
        got = np.asarray(run_tvm(m, {"x": x}, args.target)[0])
        ok = np.allclose(ref, got, rtol=1e-2, atol=1e-2)
        bad |= not ok
        print("x=[1, 1+%g]: ORT %s  TVM %s  %s"
              % (eps, np.round(ref.ravel(), 4), np.round(got.ravel(), 4),
                 "ok" if ok else "MISMATCH"))
    print("NOT REPRODUCED (fixed?)" if not bad else "BUG REPRODUCED")
    return 0 if not bad else 1


if __name__ == "__main__":
    raise SystemExit(main())

Error Log / Traceback
x=[1, 1+0.0001]: ORT [-1.0012  0.9988]  TVM [nan nan]  MISMATCH
x=[1, 1+0.001]: ORT [-0.9999  1.0001]  TVM [-0.836   0.8362]  MISMATCH
BUG REPRODUCED
Prior Report Search

No earlier public issue about MeanVarianceNormalization was found. Search: MeanVarianceNormalization.

repro.py

Lingua principale
Python
Stelle
13.9k
Fork
4.1k
Merge medio
4g 22h
PR unite (30g)
22

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di apache/tvm

Tutte le issue di apache/tvm

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.