)]}'
{
  "commit": "5e3eb7febc76de36b6d893c6902b58f103d343de",
  "tree": "d7b47eed2f4e81bcd5859fee32b4e2fc3d0aafc8",
  "parents": [
    "ad296ea1670b1e487c5e7480a3520401c3aad9c6"
  ],
  "author": {
    "name": "Florian Walbroel",
    "email": "walbroel@roofline.ai",
    "time": "Fri Nov 13 17:53:35 2026 +0100"
  },
  "committer": {
    "name": "GitHub",
    "email": "noreply@github.com",
    "time": "Fri Nov 13 16:53:35 2026 +0000"
  },
  "message": "[LinalgExt] Add is_stable to sort and replace the bubble sort lowering (#25262)\n\n## Context\n\n`iree_linalg_ext.sort` lowers to a bubble sort:\n`SortOp::generateScalarImplementation` emits one sweep of n-1\ncompare-swaps for each of the n iterations of the loop over the sort\ndimension, with no early exit. Sorting n elements takes O(n^2) steps,\nwhich shows up as soon as the sorted dimension has a few thousand\nelements. We hit this with the argsort of 4420 candidates in the non-max\nsuppression of a detection model, where the sort dispatch alone took\nabout 18 ms on x86-64, many times the rest of the model.\n\nA faster in-place algorithm is not stable, and stability turned out to\nmatter: the bubble sort keeps equal elements in input order when the\ncomparator is non-strict (`oge`, `sle`, ...), because it then never\nswaps them. The Torch frontend emits exactly such comparators, and e.g.\n`onnx.NonMaxSuppression` expects the lowest index first among boxes with\nthe same score (`test_nonmaxsuppression_identical_boxes` failed with a\nplain heapsort). With a strict comparator (`ogt`, `slt`, ...) the bubble\nsort is not stable: keys `1, 1, 2, 2, 0` sorted descending together with\ntheir indices return the indices `3 2 1 0 4`.\n\nSo this PR makes stability explicit and picks the algorithm from it.\n\n## This PR\n\n### `is_stable`\n\nThe op gets an `is_stable` attribute, false by default and only printed\nwhen set:\n\n```mlir\n%0:2 \u003d iree_linalg_ext.sort dimension(0) is_stable(true)\n    ins(%keys, %payload : tensor\u003c?xf32\u003e, tensor\u003c?xi32\u003e)\n    outs(%init0, %init1 : tensor\u003c?xf32\u003e, tensor\u003c?xi32\u003e) {\n  ^bb0(%lhs: f32, %rhs: f32, %lhs_payload: i32, %rhs_payload: i32):\n    %before \u003d arith.cmpf ogt, %lhs, %rhs : f32\n    iree_linalg_ext.yield %before : i1\n} -\u003e tensor\u003c?xf32\u003e, tensor\u003c?xi32\u003e\n```\n\nThe op description now defines the terms. The comparator *does not\norder* two elements if it returns the same value for both argument\norders (both `false` with a strict comparison, both `true` with a\nnon-strict one). Without `is_stable` such elements end up in unspecified\norder. With `is_stable` they keep their input order: an element only\nmoves in front of another one if the comparator returns `true` for that\norder and `false` for the opposite one. This definition is the same for\nstrict and non-strict comparators.\n\n### Lowering variants\n\nAll variants are in place: they need no storage besides the operands, so\nnothing changes for bufferization or stack usage, and they work for\ndynamic sizes and on every backend. The loop nest built from the\niteration domain is unchanged; a slice is sorted in the first iteration\nof the loop over the sort dimension, where the inputs were already\ncopied to the outputs. Operands that are sorted in place are no longer\ncopied onto themselves.\n\n**1. Not stable: heapsort.** O(n log n) comparisons.\n\n```\nfor (root \u003d n/2 - 1; root \u003e\u003d 0; --root)      // build the heap\n  siftDown(root, slice[root], n)\nfor (end \u003d n - 1; end \u003e 0; --end) {          // move its first element\n  last \u003d slice[end]; slice[end] \u003d slice[0]   // behind the shrinking heap\n  siftDown(0, last, end)\n}\n```\n\n`siftDown` is a `scf.while` that moves an element down until neither\nchild has to be placed after it.\n\n**2. Stable: binary insertion sort.** O(n log n) comparisons, but O(n^2)\nelement moves. It is the fallback that always works: a stable sort with\nO(n log n) moves needs scratch storage of the operand size (merge sort),\nwhich a dispatch can only take from the stack and which is unbounded for\ndynamic sizes.\n\n```\nfor (i \u003d 1; i \u003c n; ++i) {\n  element \u003d slice[i]\n  lo \u003d \u003cfirst position in the sorted prefix [0, i) whose element has to stay\n        behind `element`, by binary search\u003e\n  for (j \u003d i; j \u003e lo; --j) slice[j] \u003d slice[j - 1]\n  slice[lo] \u003d element\n}\n```\n\nThe search uses \"strictly before\" (comparator true for this order and\nfalse for the opposite one), so that elements the comparator does not\norder are never reordered.\n\n**3. Stable with a position operand: heapsort with a tie-break\n(canonicalization).** If an operand of a stable sort holds the positions\nalong the sort dimension (a `linalg.generic` yielding `linalg.index`,\nwhich is what `aten.sort` passes as indices), it tells the input order\nof any two elements. `FoldSortStabilityIntoComparator` extends the\ncomparator to order the elements it does not order itself by position,\nand clears `is_stable`:\n\n```mlir\n^bb0(%lhs: f32, %rhs: f32, %lhs_pos: i64, %rhs_pos: i64):\n  %before \u003d arith.cmpf oge, %lhs, %rhs : f32\n  %after \u003d arith.cmpf oge, %rhs, %lhs : f32\n  %ordered \u003d arith.xori %before, %after : i1\n  %lower_pos \u003d arith.cmpi slt, %lhs_pos, %rhs_pos : i64\n  %result \u003d arith.select %ordered, %before, %lower_pos : i1\n  iree_linalg_ext.yield %result : i1\n```\n\nThe comparator is then a strict total order: no two elements are left\nwithout a defined order, so every sorting algorithm returns the result\nof the stable sort and the op can use variant 1. The cost is a second\nevaluation of the comparator per comparison.\n\nThe rewrite only applies if the sorted positions are used. If they are\nnot, `RemoveUnusedSortOpResults` drops the operand as before, instead of\nkeeping its buffer in the dispatch just for the comparator; the sort\nthen stays stable (variant 2, or variant 4).\n\n**4. Stable but unobservable: heapsort (canonicalization).**\n`DropUnobservableSortStability` clears `is_stable` for a single integer\noperand whose comparator is an integer comparison of its two arguments.\nElements that such a comparator does not order are the same value, so\ntheir order cannot be observed. Floats are left alone (`0.0` and `-0.0`\ncompare equal but differ).\n\n### Frontends\n\n* **Torch:** the conversion of `tm_tensor.sort` always sets `is_stable`,\nsince those sorts have relied on the stable behaviour. With the index\noperand of `aten.sort` they get variant 3; a sort that only uses the\nvalues gets variant 2 (floats) or 4 (integers).\n* **StableHLO:** `is_stable` of `stablehlo.sort` is passed on. It was\ndropped before, and since StableHLO comparators are usually strict,\nstable StableHLO sorts were in fact not stable.\n\n### Things to know\n\n* **Unstable sorts order ties differently than before.** That is only\nallowed for sorts without `is_stable`, i.e. StableHLO sorts with\n`is_stable \u003d false` and ops built directly.\n* **NaN.** An ordered float comparison does not order NaN with any\nvalue, which makes the comparator inconsistent (it orders `1.0` and\n`2.0`, but neither with NaN). The op description now requires a\nconsistent comparator. In a simulation of the old lowering on a few\ninputs, NaNs stayed at their input positions and the other values were\nsorted around them. With the new lowerings the other values can come out\nunsorted as well, e.g. `3, NaN, 1, 2, NaN, 5, 4, 0` sorted with `ogt`\ngives `NaN, 1, 0, NaN, 5, 4, 2, 3`. A frontend that has to support NaN\nkeys needs a comparator that orders them (e.g. NaN last, as `torch.sort`\ndoes); the Torch comparators do not do that today.\n* `topk_v2` keeps its bubble sort over the k outputs; it is not touched\nhere.\n\n## Performance\n\nApple M4, llvm-cpu, `local-task`, median of 5 repetitions. Each program\ngenerates pseudo-random keys and sorts them with a single\n`iree_linalg_ext.sort`; the times include generating the keys (about\n0.01 ms for 4420 elements). The `main` column is the same program\nwithout `is_stable`, which `main` does not have.\n\n| program | variant | main | this PR | speedup |\n|---|---|---|---|---|\n| 1024 f32, descending | 1 heapsort | 1.08 ms | 0.032 ms | 34x |\n| 4420 f32, descending | 1 heapsort | 20.7 ms | 0.125 ms | 166x |\n| 4420 f32, already sorted | 1 heapsort | 20.3 ms | 0.113 ms | 180x |\n| 4420 f32, reversed | 1 heapsort | 20.3 ms | 0.107 ms | 190x |\n| 4420 i32, ascending | 1 heapsort | 10.3 ms | 0.113 ms | 91x |\n| 4420 f32 keys + i32 index iota (argsort) | 1 heapsort | 20.1 ms |\n0.127 ms | 158x |\n| 16384 f32, descending | 1 heapsort | 280 ms | 0.515 ms | 544x |\n| 512x128 f32, along the inner dimension | 1 heapsort | 1.82 ms | 0.310\nms | 5.9x |\n| 128x512 f32, along the outer dimension | 1 heapsort | 9.53 ms | 0.394\nms | 24x |\n| stable, 4420 f32 keys + i32 index iota (argsort) | 3 heapsort +\ntie-break | 20.1 ms | 0.236 ms | 85x |\n| stable, 4420 i32, ascending | 4 heapsort | 10.3 ms | 0.115 ms | 90x |\n| stable, 1024 f32, descending | 2 insertion sort | 1.08 ms | 0.131 ms |\n8.2x |\n| stable, 4420 f32, descending | 2 insertion sort | 20.7 ms | 1.48 ms |\n14x |\n| stable, 4420 f32, already sorted | 2 insertion sort | 20.3 ms | 0.067\nms | 303x |\n| stable, 4420 f32, reversed | 2 insertion sort | 20.3 ms | 2.69 ms |\n7.6x |\n| stable, 4420 f32 keys + i32 payload | 2 insertion sort | 20.1 ms |\n1.79 ms | 11x |\n| stable, 16384 f32, descending | 2 insertion sort | 280 ms | 17.9 ms |\n16x |\n\nThe tie-break of variant 3 costs a bit less than 2x over the plain\nheapsort. The element-move loop of the insertion sort is not vectorized\nby LLVM at the moment (about one element per cycle); if stable sorts\nwithout a position operand turn out to matter, that loop is where to\nlook.\n\n## Tests\n\n* `LinalgExt/IR/test/roundtrip.mlir`: the attribute.\n* `LinalgExt/IR/test/canonicalize.mlir`: variant 3 applies with used\npositions along the sort dimension, and not for positions along another\ndimension, unused positions, or a sort that is not stable; variant 4\napplies to a plain integer comparison, and not to floats or a comparator\nthat does more than compare its arguments.\n* `LinalgExt/Transforms/test/convert_to_loops.mlir`: the heapsort and\nthe insertion sort structure; `sort_multi` has one operand that is not\nsorted in place, to cover the copy.\n* Torch and StableHLO conversion tests: `is_stable` is set / passed on.\n* `tests/e2e/linalg_ext_ops/sort.mlir`: eight more tests: odd length\nwith duplicate and negative keys, a single element, the inner dimension,\nkeys with indices, a tie-break comparator on many equal keys, and stable\nsorts of many equal keys with a strict comparator, a non-strict one, and\na position operand.\n* Run locally: the e2e file passes on llvm-cpu, VMVX and Metal, and\ncompiles for Vulkan SPIR-V. `test_nonmaxsuppression_identical_boxes`\nfrom iree-test-suites passes at O0 and O2. I could not run CUDA/ROCm or\nthe full Torch and ONNX suites locally.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\n---------\n\nSigned-off-by: Florian Walbroel \u003cwalbroel@roofline.ai\u003e\nCo-authored-by: Claude Fable 5.2 \u003cnoreply@anthropic.com\u003e",
  "tree_diff": [
    {
      "type": "modify",
      "old_id": "ffd6fa93d0277f349426ad051e03985b70f0c011",
      "old_mode": 33188,
      "old_path": "compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp",
      "new_id": "6615893eb505a8804ff67949897fcb5674052442",
      "new_mode": 33188,
      "new_path": "compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp"
    },
    {
      "type": "modify",
      "old_id": "447615cba73d6e1539ee0fa6ea55d624fd44898c",
      "old_mode": 33188,
      "old_path": "compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir",
      "new_id": "25460220a0d704ad85373fe65c2a6c11b5b71914",
      "new_mode": 33188,
      "new_path": "compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir"
    },
    {
      "type": "modify",
      "old_id": "a85d92c3c399e62ce1bbec7a726156861b54e2df",
      "old_mode": 33188,
      "old_path": "compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp",
      "new_id": "fcda94692647c215b4742400679b857a06c8fd55",
      "new_mode": 33188,
      "new_path": "compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp"
    },
    {
      "type": "modify",
      "old_id": "c63e1573bd9a92330cbc1f18e3e99cb9b9810e48",
      "old_mode": 33188,
      "old_path": "compiler/plugins/input/Torch/InputConversion/test/sort.mlir",
      "new_id": "0b5eaf72fb3e9642e970b1f7314b25a86ec28e01",
      "new_mode": 33188,
      "new_path": "compiler/plugins/input/Torch/InputConversion/test/sort.mlir"
    },
    {
      "type": "modify",
      "old_id": "46cc9aa59120cdfdc1a9a20230d082c6a1f9b54e",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp",
      "new_id": "ca84c5b5696f16a31a2641f020200aac0ec82a03",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp"
    },
    {
      "type": "modify",
      "old_id": "f194ba726d17e81db8bbe6f555b4c1d5a386520c",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td",
      "new_id": "9d38d620a3b6f8c254337866e974495780ae4cea",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td"
    },
    {
      "type": "modify",
      "old_id": "927cde95cbabb9cc186cfe7f5662c026da09d434",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp",
      "new_id": "31697f9cc11ba6941f44b23b0806214e76fc6181",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp"
    },
    {
      "type": "modify",
      "old_id": "9ae12ecf5cc88857068104376da7863d1843b2bc",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir",
      "new_id": "9132c6df9a29df5e55a4fba825aa284a1fb3c4b0",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir"
    },
    {
      "type": "modify",
      "old_id": "c2ee092dd7bcb40c7bbf3c3b3ce6a99b0c6f68d5",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir",
      "new_id": "c3f43d5bd4fa5ef5223841b4f2682535533a185c",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir"
    },
    {
      "type": "modify",
      "old_id": "a938b46f29246d009fa6a9edbafb35fbdce011d6",
      "old_mode": 33188,
      "old_path": "compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir",
      "new_id": "36ae73ebccda3a0bbc7948fe4dcaa8ca12e3f662",
      "new_mode": 33188,
      "new_path": "compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir"
    },
    {
      "type": "modify",
      "old_id": "f1add0b5f401749db0a7e649242921cae1c1b3b0",
      "old_mode": 33188,
      "old_path": "tests/e2e/linalg_ext_ops/sort.mlir",
      "new_id": "06595e6fba1ea3fc13defef818276f7bd63a559a",
      "new_mode": 33188,
      "new_path": "tests/e2e/linalg_ext_ops/sort.mlir"
    }
  ]
}
