Issue 238303
Summary [mlir][tosa] `tosa-to-linalg` reduce_min/max float initial accumulator value is largest finite instead of ±Infinity
Labels mlir
Assignees
Reporter 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):

```cpp
// mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp, createInitialValueForReduceOp
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 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)

```mlir
module {
  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>
    func.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>
    func.return %r : tensor<1xf32>
  }
}
```

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

```bash
# 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):

```llvm
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        <- +FLT_MAX, not +Inf (wrong)
max -Inf: ff7fffff        <- -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`:

```cpp
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
```

Happy to test a patch.

## Upstream dedup (checked 2026-11-03)

- Tracking issue [#157378](https://github.com/llvm/llvm-project/issues/157378) covers EXT-DYNAMIC lowering support but does not track the init value semantics.
- PR [#155967](https://github.com/llvm/llvm-project/pull/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.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to