Repository navigation
[Bug][Relax][ONNX] ThresholdedRelu multiply-mask lowering changes nonfinite values and hardcodes FLOAT #20851
Description
Problem
For FLOAT input [NaN, -Inf, -2, 0, 0.5, 1, 2, +Inf] and alpha=1, ThresholdedRelu should return [0, 0, 0, 0, 0, 0, 2, +Inf]. TVM returns NaN for the first two elements. The same converter also rejects legal FLOAT16 and DOUBLE input because it forms a FLOAT mask before multiplication. A typed Greater/Where control returns the correct result, including in FLOAT16 and DOUBLE.
ONNX ThresholdedRelu defines a conditional result and its function body uses Where, with constants cast like the input. For the FLOAT witness, ORT and ONNX ReferenceEvaluator agree with NumPy. The finite FLOAT16/DOUBLE variants are checked against the schema, ReferenceEvaluator and NumPy, and their typed Where controls execute in TVM; no ORT execution claim is made for those two dtype variants.
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]
x = np.array([np.nan, -np.inf, -2, 0, 0.5, 1, 2, np.inf], dtype="float32")
expected = np.where(x > np.float32(1), x, np.float32(0))
for select_control in (False, True):
if select_control:
nodes = [h.make_node("Greater", ["x", "alpha"], ["mask"]),
h.make_node("Where", ["mask", "x", "zero"], ["y"])]
constants = [nh.from_array(np.array(1, dtype="float32"), "alpha"),
nh.from_array(np.array(0, dtype="float32"), "zero")]
else:
nodes = [h.make_node("ThresholdedRelu", ["x"], ["y"], alpha=1.0)]
constants = []
model = make(nodes, [h.make_tensor_value_info("x", T.FLOAT, [8])],
[h.make_tensor_value_info("y", T.FLOAT, [8])], constants)
sources(model, {"x": x}, [expected])
actual = tvm_run(model, {"x": x})[0]
print("Where control" if select_control else "ThresholdedRelu",
"expected", expected.tolist(), "TVM", actual.tolist())
if select_control:
np.testing.assert_array_equal(actual, expected)
else:
assert np.isnan(actual[:2]).all() and (expected[:2] == 0).all()
np.testing.assert_array_equal(actual[2:], expected[2:])
# The same converter also hardcodes FLOAT constants/masks for other legal dtypes.
for dtype, element_type in (("float16", T.FLOAT16), ("float64", T.DOUBLE)):
data = np.array([0.5, 2.0], dtype=dtype)
expected = np.array([0.0, 2.0], dtype=dtype)
inputs = [h.make_tensor_value_info("x", element_type, [2])]
outputs = [h.make_tensor_value_info("y", element_type, [2])]
model = make([h.make_node("ThresholdedRelu", ["x"], ["y"], alpha=1.0)], inputs, outputs)
np.testing.assert_array_equal(ReferenceEvaluator(model).run(None, {"x": data})[0], expected)
onnx.save(model, Path("artifacts") / (dtype + ".onnx"))
np.savez(Path("artifacts") / (dtype + "-inputs.npz"), x=data)
try:
from_onnx(model, keep_params_in_input=False)
except Exception as error:
assert "datatype" in str(error), str(error)
print(dtype, "conversion fails:", str(error).splitlines()[-1])
else:
raise AssertionError("Dtype failure did not reproduce")
control = make([h.make_node("Greater", ["x", "alpha"], ["mask"]),
h.make_node("Where", ["mask", "x", "zero"], ["y"])], inputs, outputs,
[nh.from_array(np.array(1, dtype=dtype), "alpha"),
nh.from_array(np.array(0, dtype=dtype), "zero")])
np.testing.assert_array_equal(tvm_run(control, {"x": data})[0], expected)
onnx.save(control, Path("artifacts") / (dtype + "-control.onnx"))
print(dtype, "typed Where control passed")Key output
ThresholdedRelu expected [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, inf] TVM [nan, nan, -0.0, 0.0, 0.0, 0.0, 2.0, inf]
Where control expected [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, inf] TVM [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, inf]
FLOAT16/DOUBLE conversion: float32 mask versus input dtype.
Both typed Where controls passed.
Causal analysis
The ThresholdedRelu converter implements selection as a comparison, conversion of the mask to float32, and multiplication by the input. Multiplying zero by NaN or negative infinity cannot implement the required false-branch zero. The explicit float32 mask also violates same-dtype binary arithmetic for FLOAT16/DOUBLE data. A typed selection, consistent with the ONNX function definition, avoids both problems. These are two consequences of the same converter expression and are reported together.
Related work and discovery scope
Targeted searches for ThresholdedRelu and its nonfinite-value behavior did not find an exact covering report. Generic ONNX activation support work does not correct this converter expression. This report covers only ThresholdedRelu, not other activation converters with dtype issues.
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: efc222bc464fa683e95570dd57ba7b2d69aafd521decff4c5ed26b61a6c59f34. 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. plan: lower ThresholdedRelu as where(x > alpha, x, 0) with alpha and zero built in the input dtype, so nan/-inf give 0 and float16/float64 work; plus a test with nonfinite values and the three float dtypes. pr shortly.