Repository navigation
Generic map mechanism and the standard elementwise op set - #26
Merged
Merged
Conversation
`RowLayout` was already carved out of `FragmentLayout` so a `RegVec` could name a row count without inventing a column count. The column side had no such trait, so nothing could name a per-column vector — the operand a `col_map` or a column reduction needs. Mirror the row split: `ColLayout<N>` owns `VALUES`, `col_of` and the per-thread `[f32; N/4]`, and `FragmentLayout<M, N>` becomes the join of the two halves plus the tile's own storage. `L::VALUES` and `L::col_of` still resolve through the supertrait, so every existing call site is untouched. One `base_ldtm_cols!` line per column count, the same associated-type-plus- macro dodge the row and shape macros use — no `generic_const_exprs`.
Every elementwise op was hand-written against the fragment map, so each new one cost a loop nest and a chance to get the map wrong. Replace that with three op traits, five map entry points (`unary_map`, `bin_map`, `ternary_map`, `row_map`, `col_map`) on `RegTile` and the vector-shaped subset on `RegVec`/`ColVec`, and eighteen op structs. A new op is now one `scalar_ops!` line plus one `op_methods!` line. `ColVec<N, L>` is the per-column mirror of `RegVec<M, L>` and the operand `col_map` takes. It can be carried and broadcast today; producing one from a tile needs the strided shuffle that is #6, and its doc says so rather than implying otherwise. Note the naming inversion against ThunderKittens, which names a vector for the axis it spans: TK's `col_vec` is our `RegVec` and its `row_vec` is our `ColVec`. The op names agree. `exp2_approx` and `exp2_hw` stay distinct ops (`Exp2Approx`/`Exp2Hw`), and every `exp2` method still resolves to the polynomial. Nothing hand-tuned is rewritten in terms of the mechanism: `online_rescale` stays fused per slot for the 206 -> 212 regs/thread reason in its doc, and `scale_rows`, `RegVec::{max, sub, exp2, mul_assign, add_assign}` are untouched. The generic path duplicates a few of them; that is cheaper than an unmeasurable codegen change.
The maps are pure f32 arithmetic over plain arrays, so nearly all of this is provable off-GPU. Cover each op against its scalar definition, that the maps reach every owned value, that the named wrappers resolve to the ops they claim, and — the ones that would actually catch a real bug — that `row_map` and `col_map` broadcast to the coordinates `FragmentLayout` says the register holds, replayed over all 32 lanes. `scale_rows` gets an equivalence test against `row_map::<Mul>` so the hand-written path is pinned to the generic one without being replaced by it, and `exp2` gets one against `exp2_approx` so a silent switch to the SFU form fails a test rather than a kernel. `Exp2Hw` is deliberately uncovered: `ex2_approx_f32`'s host body is `unreachable!()`, so there is nothing to assert against.
`modal run modal_app.py::regcount` builds the harness, runs `ptxas -v` over
the emitted PTX and prints a sorted registers/spills/shared table. ptxas is a
host compiler, so this is the CPU-only path — no B200, no cost.
An op no kernel calls emits no PTX, and nothing in `device-tests` touched
`RegVec` at all, so it also adds `softmax_probe_{32,128}_{hand_written,fused,
row_map}`: flash attention's inner loop as the register file sees it, one
generic body with the correction spelled three ways. Codegen probes, not
tests — nothing launches or checks them.
The measurement, sm_100a / ptxas 13.0.48, before and after routing
`RegVec::{max, sub, exp2, mul_assign, add_assign}` through the generic maps:
byte-identical, every kernel, registers and spills and stack alike. So they
are the maps now, and `exp2` folds into `unary_op_methods!` with the other
two families. `exp2_stays_the_polynomial_everywhere` now guards all three.
Two things the same table says, neither of which was the question:
- `scale_rows` must NOT become `row_map::<Mul>`. Identical at 32 columns,
168 -> 255 registers/thread at 128 — the by-value map builds a second tile
and the allocator will not prove the first one dead at that width.
- `online_rescale` stays untouched. The probe shows the fusion worth 8
registers at 32 columns and nothing at 128, but it holds its accumulator in
registers where the real kernel holds it in TMEM, so it does not get to
overturn the 206 -> 212 datapoint.
# Conflicts: # device-tests/src/main.rs
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
trait UnaryOp/BinaryOp/TernaryOp, five map entry points, and eighteenop structs —
Exp2ApproxExp2HwExpLogLog2AbsNegReluSqrtRsqrtRecipAddSubMulDivMaxMinFma— with named wrappers,so
t.exp2()reads as it does today andt.div_col(cols)now exists at all.unary_mapbin_mapternary_maprow_mapcol_mapRegTile<M, N, L>RegVec<M, L>ColVec<N, L>A new op is one
scalar_ops!line plus oneop_methods!line. Roughly 30missing functions for ~200 lines of mechanism, which was the point of the issue.
Also here:
ColLayout<N>, the column mirror ofRowLayout<M>.VALUESandcol_ofmoved offFragmentLayoutinto it, andFragmentLayout<M, N>is nowRowLayout<M> + ColLayout<N>plus the tile's joint storage. Both still resolvethrough the supertrait, so no call site changed —
device-testscompilesuntouched. One
base_ldtm_cols!line per column count, sameassociated-type-plus-macro dodge as the row and shape macros; no
generic_const_exprsanywhere.Three departures from the issue's op list, all deliberate:
zero/one/pos_infty/neg_inftyops. TK needs nullary "ops"because its maps write through a
dstreference. Ours return by value, sothese are
RegTile::splat(c)with the constant written out.zero()stays asthe name a fresh accumulator deserves.
copy/copy2. Same reason: identity of a by-value map is theargument, and
broadcast_row/broadcast_colare written directly instead ofas
row_map::<Copy2>over a discarded tile.fma_AxBtCandfma_AxCtBbecause itsternary map fixes operand order. Ours doesn't, so
fma_AxCtBisFmawiththe last two arguments swapped at the call site.
The
col_mapdecision: option (a)I added the column-side layout and the broadcast form now, and left the
reduction that fills it to #6.
The reasoning: the layout half was the part with a design question in it, and it
turned out to have a clean answer —
ColLayout<N>is a line-for-line mirror ofRowLayout<M>, and onceFragmentLayoutis the join of the two halves,ColVecandcol_mapfall out with no new concepts. Deferring it would havemeant shipping half a symmetry and re-opening
FragmentLayoutlater to add theother half. It also unblocks #6 cleanly: the shuffle reduction now has a
destination type to write into rather than needing to invent one.
What
col_mapmeans, precisely, so it can't quietly mean something else: thevalue at
(slot, value)is combined withcolsentryvalue, which is thescalar for logical column
L::col_of(lane, value). UnderBaseLdtma columndepends only on
lane % 4, so aColVecis not warp-uniform — the 8 lanesof a column group each hold their own copy of the same
N/4entries, and awhole-warp column statistic is only meaningful once those 8 copies agree. That
is exactly the invariant #6's reduction has to establish, and
ColVec's docsays so instead of implying the type already guarantees it. Today it carries a
splatted or coordinate-derived column vector into
col_map, which is enough forper-column scaling and masking.
ThunderKittens naming — read this before touching either vector type
TK names a register vector for the axis it spans; we name for the axis that
indexes it. So:
col_vecRegVec<M, L>row_vecColVec<N, L>The type names are inverted. The op names are not: TK's
row_map/mul_rowand ours both broadcast a per-row scalar along each row, and both take the
per-row vector. This is in the module docs and on both types, because it will
otherwise bite every future reader.
Measuring register pressure, and what it cost to stop guessing
The first cut left
online_rescale,scale_rows, andRegVec::{max, sub, exp2, mul_assign, add_assign}hand-written, because "the generic loop byinspection" is not a measurement and there was no way to take one. There is
now.
modal run modal_app.py::regcountbuilds the harness, runsptxas -v -arch=sm_100aover the emitted PTX and prints a sorted registers / spills /stack / shared table.
ptxasis a host compiler, so this is the CPU-only path— no B200, no cost. Run it either side of a change and diff. Register pressure
is the number this library lives or dies on, so it is built to be reused, not
thrown away.
The catch it has to work around: an op no kernel calls emits no PTX and
measures nothing, and nothing in
device-teststouchedRegVecat all. Sodevice-testsgainssoftmax_probe_{32,128}_{hand_written,fused,row_map}—flash attention's inner loop as the register file sees it (a
[32, N]scoreblock per step,
RegVecrunning maximum and sum, aRegTile<32, N, BaseLdtm>accumulator rescaled into each new reference), one generic body with the
correction spelled three ways so the variants differ in nothing else. Their doc
comments say codegen probe, not test: nothing launches them, nothing checks
them, they are not in the host case list.
The table
sm_100a, ptxas 13.0.48, release + LTO. Before = this branch with the five
hand-written; after = the same tree with them routed through
bin_map/unary_map.fragment_map_16x16fragment_map_32x32fragment_map_32x128softmax_probe_32_hand_writtensoftmax_probe_32_fusedsoftmax_probe_32_row_mapsoftmax_probe_128_hand_writtensoftmax_probe_128_fusedsoftmax_probe_128_row_mapstmatrix_roundtripswizzle_roundtripByte-identical. Every kernel, every column — registers, spill stores, spill
loads, stack frame, shared. So the five are deleted.
maxandsubjoin thebinary
op_methods!list,mul_assign/add_assignbecome a newassignarmof the same macro, and
exp2folds intounary_op_methods!alongside theother two families —
RegVecno longer has a hand-writtenmax/sub/exp2sitting beside a generic
min/add/exp. Net −21 lines inreg.rs(−77 / +56), most of the additions being doccomments recording what the numbers said.
RegVec::exp2still resolves toexp2_approx, andexp2_stays_the_polynomial_everywherenow guards all three families throughthe one macro rather than
RegVec's copy separately. Confirmed the hard way:pointing it at
Exp2Hwfails that test on the host.Positive control
An all-zeroes diff is exactly what a stale mount also produces, so before
believing it: point
exp2atExp2Hw— a one-linesrc/reg.rsedit — andre-run.
softmax_probe_128_hand_writtenmoves 168 → 255 registers and 0 → 112bytes of spill stores;
softmax_probe_128_fused168 → 254. The pipe is liveand the 128-wide probe sits in the regime where changes show. Reverted.
(That is also a real result about the SFU, incidentally, and it points the
other way from the usual assumption: one
ex2.approxcosts 86 registers and112 bytes of spill against the FMA polynomial at this shape. The polynomial's
chain schedules; the SFU serializes. It is in the module doc now.)
The other two, which I was asked to report on and not change
scale_rowsmust stay. It is not free to replace withrow_map::<Mul>: identical at 32 columns, 168 → 255 registers/thread at128.
scale_rowsrewrites the accumulator in place; arow_mapbuilds asecond tile by value and leaves the allocator to prove the first one dead,
which at a full tile's width it does not manage. The equivalence test stays
and now records why the two are spelled differently. This is the one place
the generic mechanism is measurably not free, and it is worth knowing about
before someone tidies it.
online_rescaleis untouched and byte-identical tomain. For therecord, the probe shows the fusion worth 8 registers at 32 columns (56 vs 64)
and nothing at 128 (168 either way) — it does not reproduce the 206 → 212
gap. But the probe holds its accumulator in registers where the real
persistent kernel holds it in TMEM and drains, so it bounds the fusion's
worth in a shape that is not the one the number came from. It does not get to
overturn it. Undoing the fusion needs a kernel of that shape saying so.
Verified
modal run modal_app.py::buildon the final committed tree:cargo check --features host --all-targets,cargo test --features host(30 pass), and areal
cargo oxide build device-tests --arch sm_100a. No GPU function wasrun, on any iteration.
modal run modal_app.py::regcountbefore, after, and as a positive control.cargo clippy --all-targetsandcargo fmt --checkclean.which is what the earlier throwaway kernel checked by hand and then deleted:
SqrtandFmabottom out inf32::sqrt/f32::mul_add,stdrather thancore, and lower tollvm.sqrt.f32/llvm.fma.f32— native NVPTX, nolibdevice call.
Not verified
ptxasnumbers are static registerallocation, not occupancy or throughput.
exist to be compiled. Their doc comments say so.
the ownership map the existing
fragment mapcases already validated on aB200; there is no new hardware contract to check.
Exp2Hwstill has no host test —ex2_approx_f32's host body isunreachable!(). It is covered by the probe kernels' PTX only.Where the issue's plan needed adjusting
Nothing structural — the trait shape works as specified. Two smaller things:
col_mapas "driven by the layout from Generalize RegTile to a logical shape with a layout parameter #1", but Generalize RegTile to a logical shape with a layout parameter #1'sFragmentLayoutcouldn't express a column vector's type:ColVecneeds toname
Nalone, andFragmentLayout<M, N>needs both. Option (a) thereforeisn't purely additive — it required splitting
FragmentLayoutthe way Generalize RegTile to a logical shape with a layout parameter #1split
RowLayoutout of it. That split is the first commit, and it is thereason (a) was worth doing now rather than twice.
Rsqrtis1/sqrt(x), not the SFUrsqrt.approx.f32. Two instructionsinstead of one, but identical on host and device, so it is testable and its
numerics are a decision someone makes explicitly — the same call
exp2_approxvsexp2_hwalready encodes. If a kernel wants the SFU form,that is an
Rsqrt-shaped sibling op and a measurement, not a silent swap.Closes #5