From 2be3f271c5996de0829f943e0cf5ec4c453315fb Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Sat, 28 Nov 2026 01:26:36 -0800 Subject: [PATCH] [cutedsl] Decline resident carries the rewrite reads or updates out of order For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe backend. Kernels: none gets faster; two wrong-result fixes, both on origin/main and reached by no kernel in the repository. In the AST harness, a resident reduction row whose carry is assigned a value that is the same for every feature of the row kept the carry's old value (over three rows the rewritten loop stored 0 where the loop as written stores 2), and a reduction of a carry over the features, written above the carry's update, summed the updated carry (the rewritten loop stored -1 where the loop as written stores 0). Regression check for attention, which was hillclimbed before this stack: the 12 pull requests of this stack together (#4811 to #4822) against plain main (74ac871e3), on a B200. - Generated code, rendered on CPU for the B200 target: all 1,298 configs that main renders for 145 attention cases generate the same source with the stack, and no seed list changes. The cases are the kernels of examples/attention.py (forward and backward), flex_attention.py, blackwell_attention.py and fp8_attention.py, and of benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs are each case's default and every compiler seed. - The same with the attention stack (#4797 to #4810) under both sides: 759 forward and 626 backward and attention-gym configs (defaults, seeds, pinned configs), 7,493 more configs that the search reaches on 12 forward cases (one knob changed at a time, random draws) and 3,861 with random draws on the backward and attention-gym kernels generate the same source with and without this stack, and the 11 kernels compiled on the GPU (the eight forward shapes below and three fp8 attention inputs) have the same MLIR bytecode. - Time: the eight forward shapes of examples/attention.py (dense and causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned configs, with and without this stack, interleaved, a new process for every reading, 4 to 8 rounds a shape. The best readings with the stack are 0.994 to 1.007 times those without. On this power-capped GPU every implementation, cuDNN SDPA included, reads one of two levels 3 to 5% apart from process to process; both sides read the same two levels. The resident reduction rewrite (`resident_reductions._plan`) runs the statements of a row that read nothing of a feature once for the row, ahead of the loop over the thread's features. That loop loads each feature's carries from their register fragments, runs the feature's statements, adds each reduction's input to its sum and stores the carries back. - An update of a carry that reads nothing of its feature, carry = cutlass.Float32(row) was classified with the row's statements (`_tainted` drops a name that is assigned from values that do not vary) and ran ahead of the feature loop, whose load then replaced the new value by the old one and stored that back. Every schedule of the family did so: resident, grouped and pipelined. `_plan` now declines a loop in which a carry ends up not varying. - A reduction's input is added to its sum when the feature's statements have run (`_emit`), wherever the row has the reduction. A row assigns a name once, so the input holds then what the reduction read, unless it is a carry that the row updates below the reduction: total = # the carry of the rows above carry = old_carry + increment `_plan` now declines a loop whose row assigns a reduction's input below the reduction. A reduction below the update reads the value that the rewrite sums, and keeps its schedules. A config that asks for a resident schedule is refused for such a loop, as for any loop the family cannot prove, and every other config lowers it as written. Compatibility: CuTe only. A kernel of either form no longer has resident configs. Those of the second form summed the wrong carry. Those of the first form stored the wrong carry, with one exception that is declined all the same, because the check does not look at the value: an update that gives the carry the value it already has (`carry = cutlass.Float32(initial)` for a carry that starts as `initial`) stored the right one. The kernels in the repository update their carries from the row's values (`acc += ...`), reduce no carry, and render as before. Tests (test/test_cute_resident_reductions.py): - The update that reads nothing of its feature joins the cases of `test_unknown_effects_aliases_and_loop_carried_values_decline`, which asserts that the rewrite leaves the loop as written. Without the fix the loop is rewritten, and running both forms on the harness's arrays gives 2 as written and 0 rewritten, with one row per group, two, and staged. - `test_a_marker_sums_the_carry_that_its_position_reads` puts the harness's second reduction on the carry. Above the update the loop keeps its form; without the fix it is rewritten, and the test fails. Below the update the loop is rewritten with one row per group, two, and staged, and each rewrite stores what the loop as written stores. - For that comparison the stand-in of the lane reduction in `_assert_grouped_rows_match`, which returned 0, adds its input once for each feature. Every feature holds the same values in the harness's arrays, so that is the reduction's value, and the reductions of the unchanged source have zero inputs: the other tests compare what they compared. Testing: B200, CUDA 13.2, torch 2.15.0+cu132, on origin/main 57009cbae. test/test_cute_resident_reductions.py at this commit: 1139 passed (the module has no device test). `scripts/run_tests.py --backend cute --lane cpu` at this commit: 27185 passed, 684 skipped, 1 failed (test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition, which needs the nightly's decomposition: it fails on torch 2.15.0 at origin/main as well and passes on the 2.16 nightly). The GPU lane ran with the tip of the stack, which holds this commit: `scripts/run_tests.py --backend cute --gpus 2,3`, GPU lane 16024 passed, 2370 skipped; CPU lane 27318 passed, 684 skipped and the same 1 failed. `./lint.sh check` passes. The stack was since rebased onto origin/main 74ac871e3 (after #4766 and #4767 landed, without conflicts), and the lanes ran again at the tip of the stack, which holds this commit: `scripts/run_tests.py --backend cute --gpus 4,5,6,7`, GPU lane 16010 passed, 2374 skipped; CPU lane 27408 passed, 684 skipped, 1 failed (test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition, which fails on torch 2.15.0 at origin/main as well); `scripts/run_tests.py --backend triton --gpus 5`, GPU lane 3408 passed, 2409 skipped, 2 failed (test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and ::test_task_accumulators_get_their_own_rings, the same at origin/main); CPU lane 5168 passed, 627 skipped. Two test modules of the stack's bottom commit changed in its last review after these runs (test_cute_smem_footprint.py, test_cute_resident_reductions_codegen.py); they ran again at the tip, 63 passed. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4813, branch: choijon5/cute-norm-bwd/3 --- helion/_compiler/cute/resident_reductions.py | 18 +++++++++ test/test_cute_resident_reductions.py | 40 ++++++++++++++++++-- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/helion/_compiler/cute/resident_reductions.py b/helion/_compiler/cute/resident_reductions.py index 6b253bece..70e2a82fc 100644 --- a/helion/_compiler/cute/resident_reductions.py +++ b/helion/_compiler/cute/resident_reductions.py @@ -772,6 +772,18 @@ def _plan( # Never reorder an online reduction or a reduction feeding the row carry. if dependent & carries or any(marker.input_name in dependent for marker in markers): return None + # The rewrite sums a marker's input when the row's other statements have + # run for the feature, so the name has to hold then what the marker read. + # A row assigns a name once, and only a carry is read ahead of its + # assignment: a marker above ``carry = old_carry + increment`` sums the + # carry the row started with, where the rewrite would sum the updated one. + for position, statement in enumerate(row_body): + marker = _is_lane_reduce_marker_assign(statement) + if marker is not None and any( + _assignment(later) == marker.input_name + for later in row_body[position + 1 :] + ): + return None if any( _is_lane_reduce_marker_assign(statement) is not None for statement in [*prefix, *suffix] @@ -943,6 +955,12 @@ def _plan( varying = _tainted( [*replay, *producer, *consumer], {lane_name, layout.index_name, *state} ) + # Each feature keeps its own carry, which the feature loop loads and + # stores around the row's statements. An update that reads nothing of + # its feature (``carry = cutlass.Float32(row)``) would run once for the + # row, ahead of that loop, which then stores the carry's old value back. + if not carries <= varying: + return None producer_names = { name for stmt in producer if (name := _assignment(stmt)) is not None } diff --git a/test/test_cute_resident_reductions.py b/test/test_cute_resident_reductions.py index a17195f79..cc6d87fbc 100644 --- a/test/test_cute_resident_reductions.py +++ b/test/test_cute_resident_reductions.py @@ -380,6 +380,16 @@ def test_grouped_rows_keep_int32_endpoint_semantics( _assert_grouped_rows_match(original, rewritten, end - begin, group_rows) +def _lane_sum(value: np.float32, *args: object, **kwargs: object) -> np.float32: + """The lane reduction of a value that every feature holds, as the inputs + of ``_assert_grouped_rows_match`` give each name of a row: the reference + then executes the original serial schedule exactly.""" + total = np.float32(0) + for _ in range(_FEATURES): + total = total + value + return total + + def _assert_grouped_rows_match( original: str, rewritten: str, rows: int, group_rows: int, *, row_limit: int = 0 ) -> None: @@ -408,9 +418,7 @@ def _assert_grouped_rows_match( "initial": -0.0, "limit": _FEATURES, "row_limit": np.int32(row_limit), - # The zero weight makes both reduction inputs zero, so this - # reference executes the original serial schedule exactly. - "_helion_lane_reduce": lambda value, *args, **kwargs: np.float32(0), + "_helion_lane_reduce": _lane_sum, } ) with np.errstate(over="raise", invalid="raise"): @@ -439,6 +447,9 @@ def _assert_grouped_rows_match( ("w = (weight.iterator + cutlass.Int32(column)).load()", "w = weight[column]"), ("carry = cutlass.Float32(initial)", "carry = cutlass.Float64(initial)"), ("carry = old_carry + increment", "carry = old_carry + reduced_product"), + # An update that reads nothing of its feature: hoisted out of the + # feature loop, it would leave the carry its old value. + ("carry = old_carry + increment", "carry = cutlass.Float32(row)"), ( "result = centered_gradient * scale_value", "result = centered_gradient * carry", @@ -512,6 +523,29 @@ def test_unknown_effects_aliases_and_loop_carried_values_decline( assert ast.dump(ast.parse(rewritten)) == ast.dump(ast.parse(source)) +def test_a_marker_sums_the_carry_that_its_position_reads() -> None: + """The rewrite sums a marker's input when the row's other statements have + run for the feature. Below the carry's update that is the carry the + marker reads; above it the loop sums the carry the row started with, and + keeps its form.""" + marker = ( + " reduced_gradient = cutlass.Float32(_helion_lane_reduce(" + "weighted, 'sum', cutlass.Float32(0), threads_in_group=1))\n" + ) + update = " carry = old_carry + increment\n" + source = _source(rows=2) + assert marker in source and update in source + carried = marker.replace("(weighted,", "(carry,") + source = source.replace(marker, "") + above = source.replace(update, carried + update) + assert ast.dump(ast.parse(_rewrite(above))) == ast.dump(ast.parse(above)) + below = source.replace(update, update + carried) + for group_rows, pipelined in ((1, False), (2, False), (2, True)): + rewritten = _rewrite(below, group_rows=group_rows, pipelined=pipelined) + assert "resident_state" in rewritten + _assert_grouped_rows_match(below, rewritten, 2, group_rows) + + def test_resident_requires_nonaliasing_outputs() -> None: assert "resident_state" not in _rewrite(_source(), disjoint=False)