[LinalgExt] Add is_stable to sort and replace the bubble sort lowering (#25262)

## Context

`iree_linalg_ext.sort` lowers to a bubble sort:
`SortOp::generateScalarImplementation` emits one sweep of n-1
compare-swaps for each of the n iterations of the loop over the sort
dimension, with no early exit. Sorting n elements takes O(n^2) steps,
which shows up as soon as the sorted dimension has a few thousand
elements. We hit this with the argsort of 4420 candidates in the non-max
suppression of a detection model, where the sort dispatch alone took
about 18 ms on x86-64, many times the rest of the model.

A faster in-place algorithm is not stable, and stability turned out to
matter: the bubble sort keeps equal elements in input order when the
comparator is non-strict (`oge`, `sle`, ...), because it then never
swaps them. The Torch frontend emits exactly such comparators, and e.g.
`onnx.NonMaxSuppression` expects the lowest index first among boxes with
the same score (`test_nonmaxsuppression_identical_boxes` failed with a
plain heapsort). With a strict comparator (`ogt`, `slt`, ...) the bubble
sort is not stable: keys `1, 1, 2, 2, 0` sorted descending together with
their indices return the indices `3 2 1 0 4`.

So this PR makes stability explicit and picks the algorithm from it.

## This PR

### `is_stable`

The op gets an `is_stable` attribute, false by default and only printed
when set:

```mlir
%0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
    ins(%keys, %payload : tensor<?xf32>, tensor<?xi32>)
    outs(%init0, %init1 : tensor<?xf32>, tensor<?xi32>) {
  ^bb0(%lhs: f32, %rhs: f32, %lhs_payload: i32, %rhs_payload: i32):
    %before = arith.cmpf ogt, %lhs, %rhs : f32
    iree_linalg_ext.yield %before : i1
} -> tensor<?xf32>, tensor<?xi32>
```

The op description now defines the terms. The comparator *does not
order* two elements if it returns the same value for both argument
orders (both `false` with a strict comparison, both `true` with a
non-strict one). Without `is_stable` such elements end up in unspecified
order. With `is_stable` they keep their input order: an element only
moves in front of another one if the comparator returns `true` for that
order and `false` for the opposite one. This definition is the same for
strict and non-strict comparators.

### Lowering variants

All variants are in place: they need no storage besides the operands, so
nothing changes for bufferization or stack usage, and they work for
dynamic sizes and on every backend. The loop nest built from the
iteration domain is unchanged; a slice is sorted in the first iteration
of the loop over the sort dimension, where the inputs were already
copied to the outputs. Operands that are sorted in place are no longer
copied onto themselves.

**1. Not stable: heapsort.** O(n log n) comparisons.

```
for (root = n/2 - 1; root >= 0; --root)      // build the heap
  siftDown(root, slice[root], n)
for (end = n - 1; end > 0; --end) {          // move its first element
  last = slice[end]; slice[end] = slice[0]   // behind the shrinking heap
  siftDown(0, last, end)
}
```

`siftDown` is a `scf.while` that moves an element down until neither
child has to be placed after it.

**2. Stable: binary insertion sort.** O(n log n) comparisons, but O(n^2)
element moves. It is the fallback that always works: a stable sort with
O(n log n) moves needs scratch storage of the operand size (merge sort),
which a dispatch can only take from the stack and which is unbounded for
dynamic sizes.

```
for (i = 1; i < n; ++i) {
  element = slice[i]
  lo = <first position in the sorted prefix [0, i) whose element has to stay
        behind `element`, by binary search>
  for (j = i; j > lo; --j) slice[j] = slice[j - 1]
  slice[lo] = element
}
```

The search uses "strictly before" (comparator true for this order and
false for the opposite one), so that elements the comparator does not
order are never reordered.

**3. Stable with a position operand: heapsort with a tie-break
(canonicalization).** If an operand of a stable sort holds the positions
along the sort dimension (a `linalg.generic` yielding `linalg.index`,
which is what `aten.sort` passes as indices), it tells the input order
of any two elements. `FoldSortStabilityIntoComparator` extends the
comparator to order the elements it does not order itself by position,
and clears `is_stable`:

```mlir
^bb0(%lhs: f32, %rhs: f32, %lhs_pos: i64, %rhs_pos: i64):
  %before = arith.cmpf oge, %lhs, %rhs : f32
  %after = arith.cmpf oge, %rhs, %lhs : f32
  %ordered = arith.xori %before, %after : i1
  %lower_pos = arith.cmpi slt, %lhs_pos, %rhs_pos : i64
  %result = arith.select %ordered, %before, %lower_pos : i1
  iree_linalg_ext.yield %result : i1
```

The comparator is then a strict total order: no two elements are left
without a defined order, so every sorting algorithm returns the result
of the stable sort and the op can use variant 1. The cost is a second
evaluation of the comparator per comparison.

The rewrite only applies if the sorted positions are used. If they are
not, `RemoveUnusedSortOpResults` drops the operand as before, instead of
keeping its buffer in the dispatch just for the comparator; the sort
then stays stable (variant 2, or variant 4).

**4. Stable but unobservable: heapsort (canonicalization).**
`DropUnobservableSortStability` clears `is_stable` for a single integer
operand whose comparator is an integer comparison of its two arguments.
Elements that such a comparator does not order are the same value, so
their order cannot be observed. Floats are left alone (`0.0` and `-0.0`
compare equal but differ).

### Frontends

* **Torch:** the conversion of `tm_tensor.sort` always sets `is_stable`,
since those sorts have relied on the stable behaviour. With the index
operand of `aten.sort` they get variant 3; a sort that only uses the
values gets variant 2 (floats) or 4 (integers).
* **StableHLO:** `is_stable` of `stablehlo.sort` is passed on. It was
dropped before, and since StableHLO comparators are usually strict,
stable StableHLO sorts were in fact not stable.

### Things to know

* **Unstable sorts order ties differently than before.** That is only
allowed for sorts without `is_stable`, i.e. StableHLO sorts with
`is_stable = false` and ops built directly.
* **NaN.** An ordered float comparison does not order NaN with any
value, which makes the comparator inconsistent (it orders `1.0` and
`2.0`, but neither with NaN). The op description now requires a
consistent comparator. In a simulation of the old lowering on a few
inputs, NaNs stayed at their input positions and the other values were
sorted around them. With the new lowerings the other values can come out
unsorted as well, e.g. `3, NaN, 1, 2, NaN, 5, 4, 0` sorted with `ogt`
gives `NaN, 1, 0, NaN, 5, 4, 2, 3`. A frontend that has to support NaN
keys needs a comparator that orders them (e.g. NaN last, as `torch.sort`
does); the Torch comparators do not do that today.
* `topk_v2` keeps its bubble sort over the k outputs; it is not touched
here.

## Performance

Apple M4, llvm-cpu, `local-task`, median of 5 repetitions. Each program
generates pseudo-random keys and sorts them with a single
`iree_linalg_ext.sort`; the times include generating the keys (about
0.01 ms for 4420 elements). The `main` column is the same program
without `is_stable`, which `main` does not have.

| program | variant | main | this PR | speedup |
|---|---|---|---|---|
| 1024 f32, descending | 1 heapsort | 1.08 ms | 0.032 ms | 34x |
| 4420 f32, descending | 1 heapsort | 20.7 ms | 0.125 ms | 166x |
| 4420 f32, already sorted | 1 heapsort | 20.3 ms | 0.113 ms | 180x |
| 4420 f32, reversed | 1 heapsort | 20.3 ms | 0.107 ms | 190x |
| 4420 i32, ascending | 1 heapsort | 10.3 ms | 0.113 ms | 91x |
| 4420 f32 keys + i32 index iota (argsort) | 1 heapsort | 20.1 ms |
0.127 ms | 158x |
| 16384 f32, descending | 1 heapsort | 280 ms | 0.515 ms | 544x |
| 512x128 f32, along the inner dimension | 1 heapsort | 1.82 ms | 0.310
ms | 5.9x |
| 128x512 f32, along the outer dimension | 1 heapsort | 9.53 ms | 0.394
ms | 24x |
| stable, 4420 f32 keys + i32 index iota (argsort) | 3 heapsort +
tie-break | 20.1 ms | 0.236 ms | 85x |
| stable, 4420 i32, ascending | 4 heapsort | 10.3 ms | 0.115 ms | 90x |
| stable, 1024 f32, descending | 2 insertion sort | 1.08 ms | 0.131 ms |
8.2x |
| stable, 4420 f32, descending | 2 insertion sort | 20.7 ms | 1.48 ms |
14x |
| stable, 4420 f32, already sorted | 2 insertion sort | 20.3 ms | 0.067
ms | 303x |
| stable, 4420 f32, reversed | 2 insertion sort | 20.3 ms | 2.69 ms |
7.6x |
| stable, 4420 f32 keys + i32 payload | 2 insertion sort | 20.1 ms |
1.79 ms | 11x |
| stable, 16384 f32, descending | 2 insertion sort | 280 ms | 17.9 ms |
16x |

The tie-break of variant 3 costs a bit less than 2x over the plain
heapsort. The element-move loop of the insertion sort is not vectorized
by LLVM at the moment (about one element per cycle); if stable sorts
without a position operand turn out to matter, that loop is where to
look.

## Tests

* `LinalgExt/IR/test/roundtrip.mlir`: the attribute.
* `LinalgExt/IR/test/canonicalize.mlir`: variant 3 applies with used
positions along the sort dimension, and not for positions along another
dimension, unused positions, or a sort that is not stable; variant 4
applies to a plain integer comparison, and not to floats or a comparator
that does more than compare its arguments.
* `LinalgExt/Transforms/test/convert_to_loops.mlir`: the heapsort and
the insertion sort structure; `sort_multi` has one operand that is not
sorted in place, to cover the copy.
* Torch and StableHLO conversion tests: `is_stable` is set / passed on.
* `tests/e2e/linalg_ext_ops/sort.mlir`: eight more tests: odd length
with duplicate and negative keys, a single element, the inner dimension,
keys with indices, a tie-break comparator on many equal keys, and stable
sorts of many equal keys with a strict comparator, a non-strict one, and
a position operand.
* Run locally: the e2e file passes on llvm-cpu, VMVX and Metal, and
compiles for Vulkan SPIR-V. `test_nonmaxsuppression_identical_boxes`
from iree-test-suites passes at O0 and O2. I could not run CUDA/ROCm or
the full Torch and ONNX suites locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Florian Walbroel <walbroel@roofline.ai>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
11 files changed
tree: d7b47eed2f4e81bcd5859fee32b4e2fc3d0aafc8
  1. .github/
  2. build_tools/
  3. compiler/
  4. docs/
  5. experimental/
  6. integrations/
  7. lib/
  8. llvm-external-projects/
  9. runtime/
  10. samples/
  11. tests/
  12. third_party/
  13. tools/
  14. .bazel_to_cmake.cfg.py
  15. .bazelignore
  16. .bazelrc
  17. .bazelversion
  18. .clang-format
  19. .git-blame-ignore-revs
  20. .gitattributes
  21. .gitignore
  22. .gitmodules
  23. .pre-commit-config.yaml
  24. .yamllint.yml
  25. AUTHORS
  26. BUILD.bazel
  27. CITATION.cff
  28. CMakeLists.txt
  29. configure_bazel.py
  30. CONTRIBUTING.md
  31. GOVERNANCE.md
  32. LICENSE
  33. MAINTAINERS.md
  34. MODULE.bazel
  35. README.md
  36. RELEASING.md
README.md

IREE: Intermediate Representation Execution Environment

IREE (Intermediate Representation Execution Environment, pronounced as “eerie”) is an MLIR-based end-to-end compiler and runtime that lowers Machine Learning (ML) models to a unified IR that scales up to meet the needs of the datacenter and down to satisfy the constraints and special considerations of mobile and edge deployments.

See our website for project details, user guides, and instructions on building from source.

IREE Discord Status pre-commit OpenSSF Best Practices

Project news

Project status

Release status

Releases notes are published on GitHub releases.

PackageRelease status
GitHub release (stable)GitHub Release
GitHub release (nightly)GitHub Release
iree-base-compilerPyPI version
iree-base-runtimePyPI version

For more details on the release process, see https://iree.dev/developers/general/release-management/.

Build status

CI PkgCI

Nightly build status

Operating systemBuild status
LinuxCI - Linux arm64 clang
macOSCI - macOS arm64 clang

For the full list of workflows see https://iree.dev/developers/general/github-actions/.

Communication channels

Related project channels

  • MLIR topic within LLVM Discourse: IREE is enabled by and heavily relies on MLIR. IREE sometimes is referred to in certain MLIR discussions. Useful if you are also interested in MLIR evolution.

Architecture overview

IREE Architecture IREE Architecture

See our website for more information.

Presentations and talks

Community meeting recordings: IREE YouTube channel

DateTitleRecordingSlides
2025-06-10Data-Tiling in IREE: Achieving High Performance Through Compiler Design (AsiaLLVM)recordingslides
2025-05-17Introduction to GPU architecture and IREE's GPU CodeGen Pipelinerecordingslides
2025-02-12The Long Tail of AI: SPIR-V in IREE and MLIR (Vulkanised)recordingslides
2024-10-01Unveiling the Inner Workings of IREE: An MLIR-Based Compiler for Diverse Hardwarerecording
2021-06-09IREE Runtime Design Tech Talkrecordingslides
2020-08-20IREE CodeGen (MLIR Open Design Meeting)recordingslides
2020-03-18Interactive HAL IR Walkthroughrecording
2020-01-31End-to-end MLIR Workflow in IREE (MLIR Open Design Meeting)recordingslides

License

IREE is licensed under the terms of the Apache 2.0 License with LLVM Exceptions. See LICENSE for more information.