llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[mlir][tosa] `tosa-to-linalg`: `reduce_min/max` initializes accumulator with largest finite float instead of ±Infinity

Open lin334141-cell opened this issue 1 month ago • 5 comments

[mlir][tosa] tosa-to-linalg: reduce_min/max initializes accumulator with largest finite float instead of ±Infinity

Summary

In mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp, createInitialValueForReduceOp initializes the accumulator for floating-point tosa.reduce_min with +FLT_MAX (largest finite positive value) and tosa.reduce_max with -FLT_MAX (largest finite negative value):

if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getLargest(
                       cast<FloatType>(elementTy).getFloatSemantics(), false)); // +FLT_MAX

if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getLargest(
                       cast<FloatType>(elementTy).getFloatSemantics(), true));  // -FLT_MAX

Per the TOSA specification (Section REDUCE_MIN / REDUCE_MAX), these operators compute the mathematical minimum and maximum over the reduced axis.

When an entire reduction slice consists of +Infinity, the minimum is mathematically +Infinity. However, because +FLT_MAX < +Infinity, the finite accumulator "wins" during minimum(+FLT_MAX, +Inf), incorrectly returning +FLT_MAX. Symmetrically, a slice of -Infinity reduces to -FLT_MAX instead of -Infinity.

Minimal Reproducer

// min.mlir
func.func @min_inf(%a: tensor<4xf32>) -> tensor<1xf32> {
  %r = "tosa.reduce_min"(%a) <{axis = 0 : i32, nan_mode = #tosa.nan_mode<IGNORE>}> : (tensor<4xf32>) -> tensor<1xf32>
  return %r : tensor<1xf32>
}

func.func @max_ninf(%a: tensor<4xf32>) -> tensor<1xf32> {
  %r = "tosa.reduce_max"(%a) <{axis = 0 : i32, nan_mode = #tosa.nan_mode<IGNORE>}> : (tensor<4xf32>) -> tensor<1xf32>
  return %r : tensor<1xf32>
}

Run lowering:

mlir-opt min.mlir --tosa-to-linalg

Actual Behavior (IR Level)

The lowering initializes the reduction accumulators with finite extremes:

// In @min_inf:
%cst = arith.constant 3.40282347E+38 : f32 // +FLT_MAX (0x7f7fffff)
%0 = linalg.fill ins(%cst : f32) ...

// In @max_ninf:
%cst_0 = arith.constant -3.40282347E+38 : f32 // -FLT_MAX (0xff7fffff)
%1 = linalg.fill ins(%cst_0 : f32) ...

Expected Behavior

Per the TOSA specification, the reduction accumulator should be initialized with positive/negative infinity:

  • For reduce_min: +Infinity (0x7f800000).
  • For reduce_max: -Infinity (0xff800000).

(When compiled and executed with all-+Inf / all--Inf input buffers, the compiled binary returns 0x7f7fffff (+FLT_MAX) and 0xff7fffff (-FLT_MAX) instead of the expected 0x7f800000 (+Inf) and 0xff800000 (-Inf)).

Suggested Fix

Replace APFloat::getLargest() with APFloat::getInf() in createInitialValueForReduceOp:

if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getInf(
                       cast<FloatType>(elementTy).getFloatSemantics(), false)); // +Inf

if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getInf(
                       cast<FloatType>(elementTy).getFloatSemantics(), true));  // -Inf

Tested Versions

  • LLVM main at commit b58145793359ad4e9bacf9a9da07aec18b9f6e94 (mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp:1092)
  • LLVM 24.0.0git (67005b724c917e1bdca50c82ecaa1b21a69244ed, macOS arm64)

lin334141-cell avatar Nov 03 '26 12:11 lin334141-cell

@llvm/issue-subscribers-mlir

Author: lin334141-cell

# [mlir][tosa] `tosa-to-linalg` reduce_min/max uses largest finite value instead of ±Infinity as the initial accumulator value

Versions

  • Reproduced (executed end-to-end with linked native binary) on LLVM 24.0.0git at 67005b724c917e1bdca50c82ecaa1b21a69244ed (same-source rebuild, Release+assertions, macOS arm64).
  • The responsible code is unchanged on today's main HEAD b58145793359 (2026-11-03, source-level check only — not executed).
  • Independently observed in SEMA S007 development/validation programs on Linux x86_64: 8 reduction-related candidate IDs with a combined ~692 raw-bit differences showing the "finite result instead of ±Infinity" signature.

Description

The tosa-to-linalg pass initializes the reduction accumulator for tosa.reduce_min (float) with APFloat::getLargest(semantics, false) = +FLT_MAX (largest finite positive), and for tosa.reduce_max (float) with APFloat::getLargest(semantics, true) = −FLT_MAX (largest finite negative):

// mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp, createInitialValueForReduceOp
if (isa&lt;tosa::ReduceMinOp&gt;(op) &amp;&amp; isa&lt;FloatType&gt;(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getLargest(
                       cast&lt;FloatType&gt;(elementTy).getFloatSemantics(), false)); // +FLT_MAX
if (isa&lt;tosa::ReduceMaxOp&gt;(op) &amp;&amp; isa&lt;FloatType&gt;(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getLargest(
                       cast&lt;FloatType&gt;(elementTy).getFloatSemantics(), true));  // -FLT_MAX

Per the TOSA 1.0.1 specification, REDUCE_MIN computes the mathematical minimum and REDUCE_MAX the mathematical maximum. When all elements in a reduction slice are +Infinity, the correct result for REDUCE_MIN is +Infinity, not +FLT_MAX. Similarly, when all elements are -Infinity, REDUCE_MAX should return -Infinity, not -FLT_MAX.

Using the largest finite value instead of ±Infinity as the initial accumulator causes the finite init to "win" when all inputs are ±Infinity: minimum(+FLT_MAX, +Inf) = +FLT_MAX (the init is smaller than +Inf), and maximum(−FLT_MAX, −Inf) = −FLT_MAX (the init is larger than −Inf). The result is always the finite init value, not the mathematically correct ±Infinity.

Minimal reproducer (min side; max side is symmetric with −Inf)

module {
  func.func @<!-- -->min_inf(%a: tensor&lt;4xf32&gt;) -&gt; tensor&lt;1xf32&gt; {
    %r = "tosa.reduce_min"(%a) &lt;{axis = 0 : i32, nan_mode = #tosa.nan_mode&lt;IGNORE&gt;}&gt; : (tensor&lt;4xf32&gt;) -&gt; tensor&lt;1xf32&gt;
    func.return %r : tensor&lt;1xf32&gt;
  }
  func.func @<!-- -->max_ninf(%a: tensor&lt;4xf32&gt;) -&gt; tensor&lt;1xf32&gt; {
    %r = "tosa.reduce_max"(%a) &lt;{axis = 0 : i32, nan_mode = #tosa.nan_mode&lt;IGNORE&gt;}&gt; : (tensor&lt;4xf32&gt;) -&gt; tensor&lt;1xf32&gt;
    func.return %r : tensor&lt;1xf32&gt;
  }
}

Commands (verified end-to-end in a clean directory)

# 1) lower to LLVM dialect (defect visible in the fill-value constant)
mlir-opt min.mlir --mlir-disable-threading --verify-each \
  '--pass-pipeline=builtin.module(canonicalize,func.func(tosa-to-linalg),tosa-to-tensor,tosa-to-arith{include-apply-rescale=true},one-shot-bufferize{allow-return-allocs-from-loops=true bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-math-to-funcs,convert-math-to-llvm,expand-strided-metadata,lower-affine,convert-scf-to-cf,finalize-memref-to-llvm,convert-index-to-llvm,convert-arith-to-llvm,convert-cf-to-llvm,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o lowered.mlir
# 2) translate to LLVM IR
mlir-translate --mlir-to-llvmir lowered.mlir -o program.ll
# 3) link the driver (fills input with ±Inf, calls both functions, prints result bits)
llvm-link program.ll driver.ll -o linked.bc
# 4) generate code and link executable
llc -O2 -filetype=obj linked.bc -o program.o
clang program.o -o program
# 5) run
./program

Driver (driver.ll)

The driver fills two input arrays with all-+Inf and all-−Inf floats respectively, calls min_inf and max_ninf, and prints the bit patterns of the returned scalars. It does not precompute expected values. Full source (self-contained, no external dependencies):

declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->min_inf(ptr, ptr, i64, i64, i64)
declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->max_ninf(ptr, ptr, i64, i64, i64)
declare i32 @<!-- -->printf(ptr, ...)
@<!-- -->fmt0 = private unnamed_addr constant [16 x i8] c"min +Inf: %08x\0A\00"
@<!-- -->fmt1 = private unnamed_addr constant [16 x i8] c"max -Inf: %08x\0A\00"
@<!-- -->fmt2 = private unnamed_addr constant [24 x i8] c"expected min: 7f800000\0A\00"
@<!-- -->fmt3 = private unnamed_addr constant [24 x i8] c"expected max: ff800000\0A\00"
@<!-- -->pos_inf = global [4 x i32] [i32 2139095040, i32 2139095040, i32 2139095040, i32 2139095040]
@<!-- -->neg_inf = global [4 x i32] [i32 -8388608, i32 -8388608, i32 -8388608, i32 -8388608]
define i32 @<!-- -->main() {
entry:
  %pp = getelementptr [4 x i32], ptr @<!-- -->pos_inf, i64 0, i64 0
  %np = getelementptr [4 x i32], ptr @<!-- -->neg_inf, i64 0, i64 0
  %r1 = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->min_inf(ptr %pp, ptr %pp, i64 0, i64 4, i64 1)
  %al1 = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %r1, 1
  %v1 = load float, ptr %al1
  %b1 = bitcast float %v1 to i32
  call i32 (ptr,...) @<!-- -->printf(ptr @<!-- -->fmt0, i32 %b1)
  %r2 = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->max_ninf(ptr %np, ptr %np, i64 0, i64 4, i64 1)
  %al2 = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %r2, 1
  %v2 = load float, ptr %al2
  %b2 = bitcast float %v2 to i32
  call i32 (ptr,...) @<!-- -->printf(ptr @<!-- -->fmt1, i32 %b2)
  ret i32 0
}

Note: min.mlir uses nan_mode = IGNORE but the defect also affects PROPAGATE mode, because the init value is shared across both modes. The IGNORE mode adds extra NaN-tracking logic but does not change the init value.

Expected behavior

reduce_min of all-+Inf elements should return +Inf (0x7f800000). reduce_max of all-−Inf elements should return −Inf (0xff800000).

Actual behavior (executed, both builds)

min +Inf: 7f7fffff        &lt;- +FLT_MAX, not +Inf (wrong)
max -Inf: ff7fffff        &lt;- -FLT_MAX, not -Inf (wrong)

The min result is exactly the init value (+FLT_MAX), and the max result is exactly the init value (−FLT_MAX). Both confirm that the init wins over all ±Inf inputs.

Impact

tosa.reduce_min on float tensors where a reduction slice contains only +Infinity returns +FLT_MAX instead of +Infinity. tosa.reduce_max where a reduction slice contains only -Infinity returns -FLT_MAX instead of -Infinity. Both are silent numeric miscompilations confirmed by execution on two builds.

Suggested fix

Replace APFloat::getLargest() with APFloat::getInf() in createInitialValueForReduceOp:

if (isa&lt;tosa::ReduceMinOp&gt;(op) &amp;&amp; isa&lt;FloatType&gt;(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getInf(
                       cast&lt;FloatType&gt;(elementTy).getFloatSemantics(), false)); // +Inf

if (isa&lt;tosa::ReduceMaxOp&gt;(op) &amp;&amp; isa&lt;FloatType&gt;(elementTy))
    return rewriter.getFloatAttr(
        elementTy, APFloat::getInf(
                       cast&lt;FloatType&gt;(elementTy).getFloatSemantics(), true));  // -Inf

Happy to test a patch.

Upstream dedup (checked 2026-11-03)

  • Tracking issue #157378 covers EXT-DYNAMIC lowering support but does not track the init value semantics.
  • PR #155967 added dynamic parameter support to RescaleOp but is unrelated to reduce init values.
  • Targeted searches for reduce_min infinity init, tosa reduce infinite accumulator, tosa-to-linalg reduce fill value, and related phrasings found no report of this mechanism.
  • Unrelated: #238030 (arith.select i1 whole-value mode), #237680 (SpecConstantOperation constant hoisting), #237682 (GPU warp region block splitting) — different passes, different mechanisms.

We could not find an existing report covering this specific failure mechanism as of 2026-11-03.

Context

Found in SEMA S007 development/validation programs (independent integer/FP reference vs two compiled arms) across 8 reduction-related candidate IDs with a combined ~692 raw-bit differences. The dominant pattern (604/~692 differences) is exactly "R expects ±Infinity, P/Q return the finite init value" across all 8 reduction-related candidate IDs — confirming this is a single root cause, not multiple bugs.

Thank you for taking the time to review this report. I would greatly appreciate it if the maintainers could take a look when possible and help confirm whether this is indeed a compiler bug.

If you encounter any difficulties reproducing the issue, or if additional information or test cases would be helpful, please let me know. I would be happy to provide further details or assist with reproduction.

Thank you very much for your time and help!

lin334141-cell avatar Nov 05 '26 09:11 lin334141-cell

Hi, could you try the --tosa-to-linalg="allow-non-finites=true" pass option? There was a patch related to fixing this recently here. We haven't enabled this by default yet, but I think it would be good to consider soon.

lhutton1 avatar Nov 05 '26 22:11 lhutton1

Thanks for pointing me to #222140!

I tested the original reproducer on LLVM main at c1856996d677c1b3578752e6781d0df46617fd68.

The results confirm that the option works as expected:

  • Default configuration: reduce_min still uses +FLT_MAX, and reduce_max uses -FLT_MAX.
  • With allow-non-finites=true: reduce_min uses +Inf (0x7F800000), and reduce_max uses -Inf (0xFF800000).
  • The nan_mode=IGNORE qNaN constant remains unchanged.

Both lowering runs completed successfully. This confirms the fix at the IR level; I have not repeated the native execution with the option enabled.

Since the default configuration still exhibits the originally reported behavior, would you recommend keeping this issue open to track changing the default, or closing it as addressed by the opt-in option?

Thank you for your help and for pointing me to the existing patch!

lin334141-cell avatar Nov 06 '26 18:11 lin334141-cell

Thanks, I think we can keep it open for now. I’ve uploaded a PR to make this option default https://github.com/llvm/llvm-project/pull/239407

lhutton1 avatar Nov 06 '26 22:11 lhutton1