Repository navigation
[Bug][Relax][ONNX] ReduceLogSumExp produces NaN for a positive-infinity input #20852
Description
Problem
ReduceLogSumExp of FLOAT input [+Inf, 0, 1] should be [+Inf], but TVM returns [NaN]. The script reproduces both opset 13 and opset 18. Unoptimized ORT, ONNX ReferenceEvaluator and NumPy logaddexp agree on this mixed finite/infinite input. A finite-input control passes, and an explicit expansion of the ONNX function also returns +Inf in TVM on the same input.
ONNX ReduceLogSumExp-18 includes the Cast/Exp/ReduceSum/Log/CastLike function expansion. The mathematical result and that function are +Inf for this witness. The script intentionally uses a mixed finite/infinite input: ONNX ReferenceEvaluator 1.22.0 has a separate discrepancy on an all-positive-infinity input, so no reference-agreement claim is made for that other input.
Minimal reproduction
Use an LLVM-enabled TVM environment with onnx==1.22.0, numpy==2.5.4 and onnxruntime==1.29.0. Save the following as repro.py and run:
OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 python repro.pyNo downloaded model, private package or external input file is required. The script constructs and checks the models, saves the generated models/inputs under artifacts/, and asserts the observed failure as well as its controls. It exits successfully only when those checks reproduce the reported behavior.
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 sources(model, feeds, expected):
artifacts = Path("artifacts")
artifacts.mkdir(exist_ok=True)
identity = hashlib.sha256(model.SerializeToString()).hexdigest()
onnx.save(model, artifacts / (identity + ".onnx"))
np.savez(artifacts / (identity + "-inputs.npz"), **feeds)
options = ort.SessionOptions()
options.intra_op_num_threads = options.inter_op_num_threads = 1
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
actual = ort.InferenceSession(model.SerializeToString(), options,
providers=["CPUExecutionProvider"]).run(None, feeds)
reference = ReferenceEvaluator(model).run(None, feeds)
for values in (actual, reference):
for a, b in zip(values, expected, strict=True):
np.testing.assert_allclose(a, b, rtol=1e-5, atol=1e-6)
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]
for opset in (13, 18):
attrs = {"keepdims": 1}
if opset == 13:
attrs["axes"] = [0]
model = make([h.make_node("ReduceLogSumExp", ["x"] if opset == 13 else ["x", "axes"],
["y"], **attrs)],
[h.make_tensor_value_info("x", T.FLOAT, [3])],
[h.make_tensor_value_info("y", T.FLOAT, [1])],
[] if opset == 13 else [nh.from_array(np.array([0], dtype="int64"), "axes")],
opset=opset)
control = make([
h.make_node("Cast", ["x"], ["dx"], to=T.DOUBLE),
h.make_node("Exp", ["dx"], ["ex"]),
h.make_node("ReduceSum", ["ex", "axes"], ["sum"], keepdims=1),
h.make_node("Log", ["sum"], ["log"]),
h.make_node("Cast", ["log"], ["y"], to=T.FLOAT)],
[h.make_tensor_value_info("x", T.FLOAT, [3])],
[h.make_tensor_value_info("y", T.FLOAT, [1])],
[nh.from_array(np.array([0], dtype="int64"), "axes")], opset=opset)
for values in ([float("inf"), 0.0, 1.0], [-1.0, 0.0, 1.0]):
x = np.array(values, dtype="float32")
expected = np.logaddexp.reduce(x).reshape(1)
sources(model, {"x": x}, [expected])
actual = tvm_run(model, {"x": x})[0]
print("opset", opset, "input", x.tolist(), "expected", expected.tolist(),
"TVM", actual.tolist())
if np.isposinf(x).any():
assert np.isposinf(expected).all() and np.isnan(actual).all()
else:
np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)
sources(control, {"x": x}, [expected])
expanded = tvm_run(control, {"x": x})[0]
np.testing.assert_allclose(expanded, expected, rtol=1e-5, atol=1e-6)
print("expanded ONNX function control", expanded.tolist())Key output
opset 13 input [inf, 0.0, 1.0] expected [inf] TVM [nan]
expanded ONNX function control [inf]
opset 13 input [-1.0, 0.0, 1.0] expected [1.4076058864593506] TVM [1.4076058864593506]
expanded ONNX function control [1.4076060056686401]
opset 18 input [inf, 0.0, 1.0] expected [inf] TVM [nan]
expanded ONNX function control [inf]
opset 18 input [-1.0, 0.0, 1.0] expected [1.4076058864593506] TVM [1.4076058864593506]
expanded ONNX function control [1.4076060056686401]
Causal analysis
The ReduceLogSumExp converter subtracts the maximum before exponentiation. With a positive-infinite maximum, the infinite input element becomes Inf - Inf, introducing NaN into the reduction. The numerical-stability transformation needs to preserve the infinite-input result instead of applying the subtraction unconditionally. The explicit Cast-to-double/Exp/ReduceSum/Log/Cast-back control follows the ONNX function and avoids that invalid intermediate.
Related work and discovery scope
Targeted ReduceLogSumExp/logsumexp searches did not find a covering report. The older Relay operator-support PR #5453 is not a correction of this Relax conversion. This report concerns the stable decomposition introducing NaN, not floating max/min identity handling or an empty reduction.
The original observation came from a graph-testing workflow. The self-contained script above is a subsequently constructed minimal diagnostic, not a byte-identical replay of a historical generated model. No global novelty claim is made.
Environment
Linux x86_64 CPU, LLVM target; Python 3.12.3, TVM 0.28.dev0, ONNX 1.22.0, NumPy 2.5.4, ORT 1.29.0, tvm-ffi 0.1.14.post2.dev22+gdf463f9bd.
The exact source revision used to build the installed TVM binaries is unknown. The current-source links below are a separate static inspection at 2bf0532998d4dc7879cb342e873608b90c1d4497; that revision was not built or executed for this report. The observed runtime results refer to these loaded binary identities:
libtvm_compiler.soSHA256574a573fe994e5eda7352ddd8d685e64e45c7934bdeeaab57a5a272a77792ab1libtvm_runtime.soSHA2564175916fc0ce6266c912629d2255094b94087425c6ab53ffd5e004d4c292c828libtvm_runtime_extra.soSHA25679c93351fca12dd7851964890cea7da65dd2b2e0e64e5c28bfed56c878b70817libtvm_ffi.soSHA25612072d0ccd9d5cb2c6dac80d42f4217ab50dbf795db03197000614a7a770a816
Reproducer SHA256: 538962f96a42371c540a80b03d72e09c1d78b7c092ec81e73641f75511025f75. Model and input hashes can be computed from the files saved by the script. No compiler/library rebuild or environment upgrade was used for the reported checks.
Activity
dundysm commentedon Oct 31, 2026
hi; i'd like to take this one. the converter subtracts the reduced max before exp, so a +inf max gives inf - inf = nan. plan: replace a non-finite max with 0 before the shift (same trick numpy and torch use), shared by the v13 and v18 converters, plus a test with +inf and all -inf inputs. pr shortly.