Repository navigation
Reductions: generic row/column/whole-tile folds over a ReduceOp - #37
Merged
Merged
Conversation
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.
feitreim
force-pushed
the
issue-6-reductions
branch
from
July 27, 2026 22:31
a15bc85 to
af593d7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What landed
row_reduce/col_reduce/tile_reduceonRegTile, each taking areduction op, plus twelve named forms:
RegVec<M, L>row_reduce::<Op>()row_maxrow_minrow_sumrow_prodColVec<N, L>col_reduce::<Op>()col_maxcol_mincol_sumcol_prodf32tile_reduce::<Op>()tile_maxtile_mintile_sumtile_prodThe column case is written once generically and the four names derived from it,
as the issue asked. Whole-tile is
tile_-prefixed becauseRegTile::maxisalready 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_sumwereonly the second half; the first — folding a thread's own registers — was
open-coded in
device-tests,flash_forwardandsoftmax, and those copiesare deleted.
Also here:
quad_reduce/column_group_reduce/warp_reduce, the three lane-groupbutterflies as free functions.
quad_max/quad_sumare nowquad_reduce::<Max>/<Add>and compile to the same thing.RegVec::reduce/ColVec::reduce, which fold the other axis and socomplete a vector to a scalar; and
RegVec::quad_reduce/ColVec::column_group_reduce, the generic forms of the shuffle pass.ReduceOp: BinaryOpwith anIDENTITY, implemented forAddMulMaxMin. Every fold seeds from the identity instead of special-casingelement zero, and
row_reduce::<Sub>is unrepresentable rather than merelymeaningless.
No
Prodop.Mulis the product op; a second unit struct with the samea * bbody would only be a name.row_prodisrow_reduce::<Mul>.The shuffle masks, and how they were verified
Rows vary with
lane / 4andslot; columns vary withlane % 4andvalue.So folding an axis away means shuffling across the lanes the other index
selects:
shuffle_xormasksrow_ofignoreslane % 4)lane % 4Verified three ways, deliberately not by restating the constants:
reduction_masks_are_the_ownership_maps_lane_groups(host) derives thelane groups from
BaseLdtm::row/column— "the lanes that agree withlaneon every slot's row" — and asserts each equals the xor-closure of themask set. It also asserts the groups are complete: a quad's
VALUEScoverevery column of a row exactly once, a column group's
SLOTSevery row.reductions_fold_exactly_their_logical_axis(host) folds over thosemap-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.
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:
That helper costs a whole tile. Even
#[inline(always)], takingselfbyvalue materializes a second copy of the storage:
softmax_probe_32_hand_writtensoftmax_probe_32_row_mapsoftmax_probe_128_row_map30 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:
Re-measured after the rebase onto
12aa4ec: all 24 of main's kernels arebit-identical,
reduction_probeis the only row that is not on main. The A–Fexperiments below were run pre-rebase against the older harness; their
conclusion is unchanged, and F's numbers are the ones above.
softmax_probenow callsRegTile::row_max/row_sumwhere it used to callhand-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:
row_maprow_max/row_sum, no helperRegVec::quad_maxdoesA 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 beforeanyone does. The reason is concrete rather than a matter of PR size:
Scopeas specified cannot express the block reduction. The proposed traitis
WARPS/THREADS/rank()/sync(). A block-scope fold needs none ofthose 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_tileguesses at it today with abare
*mut f32carved 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 notexist yet. Either way #3 and #13 have to be sequenced together, and picking
between them now — with no
SharedVecto hold the answer and no example thatcan 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
Scopewould have to be retrofitted around.This is recorded in
examples/README.mdunder #3 and inlayernorm.rs's headerso it is not lost with this PR.
The device test
New case,
reduction shuffles, over the same MMA-seeded[32, 128]accumulatorthe 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; thehost derives all 4864 expectations from
BaseLdtm's map, so the kernel encodesno 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.
Examples
Rebased onto
12aa4ec, which changed the picture: #21 landedload_fragment,#25 gave
chunk_writerstacked subtiles, and #35 rewrotesoftmax.rsto moveits
[128, 128]tile through both. My pre-rebase report said softmax was stillblocked 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.
softmax— blocked on TMA store path #9 and nothing else. The TMA store, so theresult can leave. Its algorithm is four lines of real API, its movers are
real, and
#22is a cost (the band loop written twice) rather than a hole.It went from five gaps to one; Reductions: column-wise, whole-tile, and a generic reduce #6 was the second-to-last.
layernorm— takesColVecandcol_sum;groupnorm_tiletakestile_sum. Still on Shared vectors, and ops on shared tiles #13, TMA store path #9, Movers work in [16,16] blocks; every kernel rewrites the same composition loop #22 (whole-tile movers — composition only now,since Shared to register load: the missing half of ldst #21/SwizzledChunks cannot span stacked subtiles: only 64-wide bf16 tiles have a register<->shared path #25 fixed the addressing), Block-scope reductions: the fold four warps need, and the fp32 Element under it #3, and the scalar broadcasts.
flash_forward—row_max/row_sumare real; still on Masking and shape utilities: make_causal, tril/triu, fills, transpose #7, Direct global to/from register load and store #11, Movers work in [16,16] blocks; every kernel rewrites the same composition loop #22,RegTile's shape set is closed to out-of-tree kernels #23, The map mechanism needs in-place variants: by-value costs 87 registers at 128 columns #31. Its
#25reference is now historical.main.rs's status stringsupdated. README items 1 and 3 marked shipped rather than merely filed.
A finding worth its own issue: #5's scalar broadcasts never shipped. #5's
own list included
scale/shiftonRegTileandRegVec, a freersqrt(f32), andRegTile::add_assign; the map mechanism landed and these didnot. A tile or vector combined with a bare
f32still has to splat it into awhole operand.
flash_forwardandlayernormname them at call sites, and theyare 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, realcargo oxide build --arch sm_100afordevice-testsandkittens-examples.Clean.
modal run modal_app.py::regcount— nine runs; the table above, including afresh
main-at-12aa4ecbaseline to diff the rebased branch against.modal run modal_app.py— B200, 13 of 13 cases after the rebase (main's12 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::buildbuilds only the default feature set, andcargo check --features aspirationalneeds a CUDA toolkit. Their gap lists areread, not machine-checked, same as before this PR.
Closes #6