tvm icon indicating copy to clipboard operation
tvm copied to clipboard

[Bug][Relax][ONNX] Boolean ReduceMax and ReduceMin lower to unsupported bool extrema

Open Yuhx141 opened this issue 1 month ago • 1 comments

Problem

Valid opset-20 Boolean ReduceMax and ReduceMin models import into Relax but fail during CPU lowering: ReduceMax requests an unsupported Boolean minimum identity; ReduceMin requests an unsupported Boolean maximum identity. Unoptimized ORT, ONNX ReferenceEvaluator and NumPy agree on the source outputs. Casting the same Boolean input to INT8 before the reduction and casting its result back to Boolean works in TVM and exactly preserves the outputs.

ONNX ReduceMax-20 and ReduceMin-20 explicitly accept Boolean inputs with False ordered below True. The script uses opset 20, rather than an older opset that lacks that type contract.

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.py

No 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([[False, True, False], [True, True, True]], dtype="bool")
for op, formula, identity in (("ReduceMax", np.any, "min_value"),
                              ("ReduceMin", np.all, "max_value")):
    expected = formula(x, axis=1)
    for cast_control in (False, True):
        nodes = []
        if cast_control:
            nodes.append(h.make_node("Cast", ["x"], ["ix"], to=T.INT8))
        nodes.append(h.make_node(op, ["ix" if cast_control else "x", "axes"],
                                 ["iy" if cast_control else "y"], keepdims=0))
        if cast_control:
            nodes.append(h.make_node("Cast", ["iy"], ["y"], to=T.BOOL))
        model = make(nodes, [h.make_tensor_value_info("x", T.BOOL, [2, 3])],
                     [h.make_tensor_value_info("y", T.BOOL, [2])],
                     [nh.from_array(np.array([1], dtype="int64"), "axes")], opset=20)
        sources(model, {"x": x}, [expected])
        try:
            actual = tvm_run(model, {"x": x})[0]
        except Exception as error:
            assert not cast_control and identity in str(error) and "bool" in str(error), str(error)
            print(op, str(error).splitlines()[-1])
        else:
            assert cast_control, "Reported failure did not reproduce"
            np.testing.assert_array_equal(actual, expected)
            print(op, "int8 control", actual.tolist())

Key output

ReduceMax Cannot decide min_value for typeT.bool
ReduceMax int8 control [True, True]
ReduceMin Cannot decide max_value for typeT.bool
ReduceMin int8 control [False, True]

Causal analysis

The ONNX ReduceMax and ReduceMin converters pass Boolean tensors directly to Relax max/min, while their downstream extrema identities do not support bool. The ONNX adapter needs a Boolean-aware path, such as an appropriate logical reduction or the tested integer-cast adaptation. Both operators are grouped here because they violate the same adapter precondition.

Related work and discovery scope

PR #19415 already fixed the same primitive restriction for TFLite REDUCE_ANY/REDUCE_ALL by adapting Boolean reductions through INT8. Its changes are confined to the TFLite converter/tests and do not adapt these ONNX converters. This is an ONNX-specific follow-up, not a claim that the underlying bool-identity limitation is newly discovered.

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.so SHA256 574a573fe994e5eda7352ddd8d685e64e45c7934bdeeaab57a5a272a77792ab1
  • libtvm_runtime.so SHA256 4175916fc0ce6266c912629d2255094b94087425c6ab53ffd5e004d4c292c828
  • libtvm_runtime_extra.so SHA256 79c93351fca12dd7851964890cea7da65dd2b2e0e64e5c28bfed56c878b70817
  • libtvm_ffi.so SHA256 12072d0ccd9d5cb2c6dac80d42f4217ab50dbf795db03197000614a7a770a816

Reproducer SHA256: 497d8f1b4d0a7332546580a72b7c796a7e032a574b1f1bd22cf4693d3a83d2ba. 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.

Yuhx141 avatar Oct 29 '26 06:10 Yuhx141

I’d like to take this. Will follow the int8 cast approach from #19415 and open a PR with tests.

Abhi2939 avatar Oct 30 '26 21:10 Abhi2939