Skip to content

Reductions: generic row/column/whole-tile folds over a ReduceOp - #37

Merged
feitreim merged 4 commits into
mainfrom
issue-6-reductions
Jul 27, 2026
Merged

feitreim merged 4 commits into
mainfrom
issue-6-reductions

Conversation

@feitreim

@feitreim feitreim commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

What landed

row_reduce / col_reduce / tile_reduce on RegTile, each taking a
reduction op, plus twelve named forms:

generic named
rows → RegVec<M, L> row_reduce::<Op>() row_max row_min row_sum row_prod
columns → ColVec<N, L> col_reduce::<Op>() col_max col_min col_sum col_prod
whole tile → f32 tile_reduce::<Op>() tile_max tile_min tile_sum tile_prod

The column case is written once generically and the four names derived from it,
as the issue asked. Whole-tile is tile_-prefixed because RegTile::max is
already the elementwise binary op — TK separates those two by C++ overloading,
which Rust has no equivalent of.

Both halves of a reduction are in the library now. quad_max/quad_sum were
only the second half; the first — folding a thread's own registers — was
open-coded in device-tests, flash_forward and softmax, and those copies
are deleted.

Also here:

  • quad_reduce / column_group_reduce / warp_reduce, the three lane-group
    butterflies as free functions. quad_max/quad_sum are now
    quad_reduce::<Max>/<Add> and compile to the same thing.
  • RegVec::reduce / ColVec::reduce, which fold the other axis and so
    complete a vector to a scalar; and RegVec::quad_reduce /
    ColVec::column_group_reduce, the generic forms of the shuffle pass.
  • ReduceOp: BinaryOp with an IDENTITY, implemented for Add Mul
    Max Min. Every fold seeds from the identity instead of special-casing
    element zero, and row_reduce::<Sub> is unrepresentable rather than merely
    meaningless.

No Prod op. Mul is the product op; a second unit struct with the same
a * b body would only be a name. row_prod is row_reduce::<Mul>.

The shuffle masks, and how they were verified

Rows vary with lane / 4 and slot; columns vary with lane % 4 and value.
So folding an axis away means shuffling across the lanes the other index
selects:

reduction folds away shuffle_xor masks
row a row's columns 1, 2 — the quad (row_of ignores lane % 4)
column a column's rows 4, 8, 16 — the 8 lanes sharing lane % 4
whole tile both 1, 2, 4, 8, 16

Verified three ways, deliberately not by restating the constants:

  1. reduction_masks_are_the_ownership_maps_lane_groups (host) derives the
    lane groups from BaseLdtm::row/column — "the lanes that agree with
    lane on every slot's row" — and asserts each equals the xor-closure of the
    mask set. It also asserts the groups are complete: a quad's VALUES cover
    every column of a row exactly once, a column group's SLOTS every row.
  2. reductions_fold_exactly_their_logical_axis (host) folds over those
    map-derived groups and compares against the reduction of the logical tile,
    so a fold reaching the wrong registers or the wrong lanes lands on a
    different number.
  3. reduction shuffles (B200) — below.

The arithmetic in the plan held up exactly; nothing had to be adjusted.

Register pressure: one finding, and it cost five runs to isolate

The first cut factored the lane-local fold into one helper:

fn fold_values<Op: ReduceOp>(self, slot: usize) -> f32 { ... }

That helper costs a whole tile. Even #[inline(always)], taking self by
value materializes a second copy of the storage:

kernel baseline with the helper
softmax_probe_32_hand_written 64 94
softmax_probe_32_row_map 64 94
softmax_probe_128_row_map 255, no spill 255, 456 B spill st / 364 B spill ld

30 registers at 32 columns is almost exactly the 32 floats of a [32, 32]
tile. Spelled out inline at each of the three reductions, every kernel in the
harness is bit-identical to its pre-#6 count:

kernel                            regs  spill st  spill ld   stack
fragment_map_16x16                  18         0         0       0
fragment_map_32x128                 32         0         0     512
fragment_map_32x32                  40         0         0       0
fragment_restage_32x128             40         0         0     512
lane_probe_128_hoisted             168         0         0    2816
lane_probe_128_per_op              168         0         0    2816
lane_probe_128_per_query           168         0         0    2816
lane_probe_32_hoisted               56         0         0     384
lane_probe_32_per_op                40         0         0     512
lane_probe_32_per_query             40         0         0     512
ldmatrix_map                        32         0         0       0
ldmatrix_map_wide                   32         0         0       0
reduction_probe                    255         0         0    1024   (new)
softmax_probe_128_fused            168         0         0    3104
softmax_probe_128_hand_written     168         0         0    3072
softmax_probe_128_row_map          255         0         0    2560
softmax_probe_32_fused              56         0         0     416
softmax_probe_32_hand_written       64         0         0     256
softmax_probe_32_row_map            64         0         0     256
stmatrix_roundtrip                  40         0         0       0
stmatrix_roundtrip_wide             32         0         0       0
sttm_roundtrip                      34         0         0    1024
swizzle_roundtrip                   31         0         0       0
swizzle_roundtrip_short             32         0         0       0
swizzle_roundtrip_wide              32         0         0       0

Re-measured after the rebase onto 12aa4ec: all 24 of main's kernels are
bit-identical
, reduction_probe is the only row that is not on main. The A–F
experiments below were run pre-rebase against the older harness; their
conclusion is unchanged, and F's numbers are the ones above.

softmax_probe now calls RegTile::row_max/row_sum where it used to call
hand-written copies, so those numbers are the generic reduction being measured,
not the old code still in place.

Four other hypotheses were measured and rejected before the right one — worth
recording so nobody re-runs them:

change 32-wide 128 row_map
A new kernel present, probe still hand-written 64 255, no spill
B batched folds then batched shuffles 94 spills
C hand-written row_max/row_sum, no helper 64 255, no spill
D identity seed instead of element zero 94 spills
E shuffle pass reads a snapshot, as RegVec::quad_max does 96 spills
F inner loop inlined, no by-value helper 64 255, no spill

A rules out the new kernel's presence (LTO noise). C and F together isolate the
helper as the whole cause. Note that the 32-wide probe was the sensitive one
here
— the reverse of #5's experience — so both widths are worth keeping.

Scope (#3): option (b), warp scope only

I did not introduce a Scope, and I think #3 as filed needs amending before
anyone does. The reason is concrete rather than a matter of PR size:

Scope as specified cannot express the block reduction. The proposed trait
is WARPS / THREADS / rank() / sync(). A block-scope fold needs none of
those nearly as much as it needs storage — somewhere for each warp's partial
to live between the two barriers — and the library cannot supply it: the shared
memory plan belongs to the kernel. groupnorm_tile guesses at it today with a
bare *mut f32 carved out of its own plan.

So a block reduction's signature is either "take a scratch pointer", which is
not scope parameterization at all, or "take #13's SharedVec", which does not
exist yet. Either way #3 and #13 have to be sequenced together, and picking
between them now — with no SharedVec to hold the answer and no example that
can compile against it — would fix the shape before the type that carries it
exists. Every reduction here is warp scope and says so in its docs; nothing was
written that a later Scope would have to be retrofitted around.

This is recorded in examples/README.md under #3 and in layernorm.rs's header
so it is not lost with this PR.

The device test

New case, reduction shuffles, over the same MMA-seeded [32, 128] accumulator
the fragment-map cases use — every value is 128 * row + column,
hardware-delivered. Each warp reduces its own band and dumps row sums, column
sums, a band max and a [32, 32] band sum indexed by (warp, lane) alone; the
host derives all 4864 expectations from BaseLdtm's map, so the kernel encodes
no answer.

The column sums are the point: masks 4/8/16, a butterfly nothing in this crate
had ever run. The whole-tile sum is taken over the narrow band so every partial
stays an exact fp32 integer — the wide band's total is 58.7M, past 2^24, where
an equality assertion would be measuring rounding instead of the reduction. The
checker also refuses to run on an expectation fp32 cannot hold exactly, as a
harness error rather than a case failure.

pass  reduction shuffles        4864 statistics exact
8 of 8 cases passed

Examples

Rebased onto 12aa4ec, which changed the picture: #21 landed load_fragment,
#25 gave chunk_writer stacked subtiles, and #35 rewrote softmax.rs to move
its [128, 128] tile through both. My pre-rebase report said softmax was still
blocked on the movers — that is no longer true, and the README and headers
say what is true now rather than carrying the old list forward.

A finding worth its own issue: #5's scalar broadcasts never shipped. #5's
own list included scale/shift on RegTile and RegVec, a free
rsqrt(f32), and RegTile::add_assign; the map mechanism landed and these did
not. A tile or vector combined with a bare f32 still has to splat it into a
whole operand. flash_forward and layernorm name them at call sites, and they
are the only arithmetic left on any blocked-on list. #31 covers the in-place
half of the argument; the scalar half has no issue.

Verified

  • modal run modal_app.py::build — clippy (both crates), host tests, real
    cargo oxide build --arch sm_100a for device-tests and kittens-examples.
    Clean.
  • modal run modal_app.py::regcount — nine runs; the table above, including a
    fresh main-at-12aa4ec baseline to diff the rebased branch against.
  • modal run modal_app.py — B200, 13 of 13 cases after the rebase (main's
    12 plus reduction shuffles).
  • cargo clippy --all-targets, cargo fmt --check, 46 host tests. Clean.

Not verified: the aspirational kernels are not compiled by anything —
modal_app.py::build builds only the default feature set, and
cargo check --features aspirational needs a CUDA toolkit. Their gap lists are
read, not machine-checked, same as before this PR.

Closes #6

feitreim added 4 commits July 27, 2026 18:23
The two halves of a fragment reduction, both in the library: fold a
thread's own registers, then shuffle_xor across the lanes the ownership
map spreads the folded axis over. row_of ignores lane % 4 and col_of
ignores lane / 4, so rows fold across masks 1,2 (what quad_max/quad_sum
already were), columns across 4,8,16, and the whole tile across all five.

quad_max/quad_sum are now quad_reduce::<Max>/<Add>; the column-group and
whole-warp butterflies are new. RegTile gains row_reduce/col_reduce/
tile_reduce plus twelve named forms, RegVec and ColVec a reduce that
completes the other axis.

The mask choice is tested against BaseLdtm's maps rather than restated:
a mask set is right exactly when its xor-closure is the lane set the map
says shares the folded axis.
A new case over the same MMA-seeded [32, 128] accumulator the fragment-map
cases use: each warp reduces its own band and dumps row sums, column sums,
a band max and a [32, 32] band sum by (warp, lane). The host derives every
expectation from BaseLdtm's map alone, so the kernel encodes no answer.

The column sums are the point — they fold across the 8 lanes sharing
lane % 4, masks 4/8/16, a butterfly nothing in this crate has run before.
The whole-tile sum is taken over the narrow band so every partial stays an
exact fp32 integer; the wide band's total is 58.7M, past 2^24.

softmax_probe's open-coded quad_row_max/quad_row_sum are deleted in favour
of RegTile::row_max/row_sum, which is also the register measurement.
softmax's algorithm and flash's softmax numerator are the real API now;
layernorm takes ColVec and col_sum and its groupnorm kernel takes
tile_sum. None of the three is unblocked: every remaining gap is a mover
(#21, #22, #25), the store side (#9), masking (#7), or #3 + #13.

Two findings recorded rather than worked around. #5's scalar broadcasts
(`scale`/`shift`, free `rsqrt`, `RegTile::add_assign`) were on its list
and did not ship, so they are still WANTs at the call sites. And `Scope`
as #3 filed it cannot express layernorm's block reduction: what that
needs is storage for the per-warp partials, which WARPS/THREADS/rank/sync
does not supply and only the kernel can allocate.

Stale "no open issue" fences updated to #21/#22/#23/#24/#25.
The first cut factored the lane-local fold into one
`fold_values(self, slot)` helper. It costs a whole tile: even
#[inline(always)], taking `self` by value materializes a second copy of
the storage. softmax_probe_32 went 64 -> 94 registers/thread and
softmax_probe_128_row_map picked up 456 bytes of spill stores. Written
out at each of the three reductions, every kernel in the harness is
bit-identical to its pre-#6 count. Same shape of finding as scale_rows.

Four spellings were measured before that one landed, all at 128 as well
as 32 (regcount labels A-F in the PR): the new kernel's mere presence,
interleaved vs batched shuffles, and reading the partials from a
snapshot all made no difference or made it worse.

ReduceOp narrows the reduction bound from BinaryOp to the four ops with
identities, so every fold seeds the same way and row_reduce::<Sub> is
unrepresentable rather than merely meaningless.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reductions: column-wise, whole-tile, and a generic reduce

1 participant