Skip to content

Generic map mechanism and the standard elementwise op set - #26

Merged
feitreim merged 6 commits into
mainfrom
issue-5-map-mechanism
Jul 27, 2026
Merged

feitreim merged 6 commits into
mainfrom
issue-5-map-mechanism

Conversation

@feitreim

@feitreim feitreim commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

What landed

trait UnaryOp / BinaryOp / TernaryOp, five map entry points, and eighteen
op structs — Exp2Approx Exp2Hw Exp Log Log2 Abs Neg Relu Sqrt
Rsqrt Recip Add Sub Mul Div Max Min Fma — with named wrappers,
so t.exp2() reads as it does today and t.div_col(cols) now exists at all.

unary_map bin_map ternary_map row_map col_map
RegTile<M, N, L> yes yes yes yes yes
RegVec<M, L> yes yes yes — —
ColVec<N, L> yes yes — — —

A new op is one scalar_ops! line plus one op_methods! line. Roughly 30
missing functions for ~200 lines of mechanism, which was the point of the issue.

Also here: ColLayout<N>, the column mirror of RowLayout<M>. VALUES and
col_of moved off FragmentLayout into it, and FragmentLayout<M, N> is now
RowLayout<M> + ColLayout<N> plus the tile's joint storage. Both still resolve
through the supertrait, so no call site changed — device-tests compiles
untouched. One base_ldtm_cols! line per column count, same
associated-type-plus-macro dodge as the row and shape macros; no
generic_const_exprs anywhere.

Three departures from the issue's op list, all deliberate:

  • No zero/one/pos_infty/neg_infty ops. TK needs nullary "ops"
    because its maps write through a dst reference. Ours return by value, so
    these are RegTile::splat(c) with the constant written out. zero() stays as
    the name a fresh accumulator deserves.
  • No copy/copy2. Same reason: identity of a by-value map is the
    argument, and broadcast_row/broadcast_col are written directly instead of
    as row_map::<Copy2> over a discarded tile.
  • One fma op, not two. TK has fma_AxBtC and fma_AxCtB because its
    ternary map fixes operand order. Ours doesn't, so fma_AxCtB is Fma with
    the last two arguments swapped at the call site.

The col_map decision: 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 of
RowLayout<M>, and once FragmentLayout is the join of the two halves,
ColVec and col_map fall out with no new concepts. Deferring it would have
meant shipping half a symmetry and re-opening FragmentLayout later to add the
other 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_map means, precisely, so it can't quietly mean something else: the
value at (slot, value) is combined with cols entry value, which is the
scalar for logical column L::col_of(lane, value). Under BaseLdtm a column
depends only on lane % 4, so a ColVec is not warp-uniform — the 8 lanes
of a column group each hold their own copy of the same N/4 entries, and a
whole-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 doc
says 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 for
per-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:

TK ferro-kittens entries
col_vec RegVec<M, L> one per row
row_vec ColVec<N, L> one per column

The type names are inverted. The op names are not: TK's row_map/mul_row
and 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, and RegVec::{max, sub, exp2, mul_assign, add_assign} hand-written, because "the generic loop by
inspection" is not a measurement and there was no way to take one. There is
now.

modal run modal_app.py::regcount builds the harness, runs ptxas -v -arch=sm_100a over the emitted PTX and prints a sorted registers / spills /
stack / shared table. ptxas is 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-tests touched RegVec at all. So
device-tests gains softmax_probe_{32,128}_{hand_written,fused,row_map} —
flash attention's inner loop as the register file sees it (a [32, N] score
block per step, RegVec running maximum and sum, a RegTile<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.

kernel regs spill st spill ld stack after: regs / spills
fragment_map_16x16 18 0 0 0 18 / 0
fragment_map_32x32 40 0 0 0 40 / 0
fragment_map_32x128 32 0 0 512 32 / 0
softmax_probe_32_hand_written 64 0 0 256 64 / 0
softmax_probe_32_fused 56 0 0 416 56 / 0
softmax_probe_32_row_map 64 0 0 256 64 / 0
softmax_probe_128_hand_written 168 0 0 3072 168 / 0
softmax_probe_128_fused 168 0 0 3104 168 / 0
softmax_probe_128_row_map 255 0 0 2560 255 / 0
stmatrix_roundtrip 40 0 0 0 40 / 0
swizzle_roundtrip 31 0 0 0 31 / 0

Byte-identical. Every kernel, every column — registers, spill stores, spill
loads, stack frame, shared. So the five are deleted. max and sub join the
binary op_methods! list, mul_assign/add_assign become a new assign arm
of the same macro, and exp2 folds into unary_op_methods! alongside the
other two families — RegVec no longer has a hand-written max/sub/exp2
sitting beside a generic min/add/exp. Net −21 lines in reg.rs (−77 / +56), most of the additions being doc
comments recording what the numbers said.

RegVec::exp2 still resolves to exp2_approx, and
exp2_stays_the_polynomial_everywhere now guards all three families through
the one macro rather than RegVec's copy separately. Confirmed the hard way:
pointing it at Exp2Hw fails that test on the host.

Positive control

An all-zeroes diff is exactly what a stale mount also produces, so before
believing it: point exp2 at Exp2Hw — a one-line src/reg.rs edit — and
re-run. softmax_probe_128_hand_written moves 168 → 255 registers and 0 → 112
bytes of spill stores; softmax_probe_128_fused 168 → 254. The pipe is live
and 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.approx costs 86 registers and
112 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_rows must stay. It is not free to replace with
    row_map::<Mul>: identical at 32 columns, 168 → 255 registers/thread at
    128
    . scale_rows rewrites the accumulator in place; a row_map builds a
    second 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_rescale is untouched and byte-identical to main. For the
    record, 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::build on the final committed tree: cargo check --features host --all-targets, cargo test --features host (30 pass), and a
    real cargo oxide build device-tests --arch sm_100a. No GPU function was
    run, on any iteration.
  • modal run modal_app.py::regcount before, after, and as a positive control.
  • cargo clippy --all-targets and cargo fmt --check clean.
  • The new ops are now genuinely monomorphized into PTX by the probe kernels,
    which is what the earlier throwaway kernel checked by hand and then deleted:
    Sqrt and Fma bottom out in f32::sqrt/f32::mul_add, std rather than
    core, and lower to llvm.sqrt.f32/llvm.fma.f32 — native NVPTX, no
    libdevice call.

Not verified

  • Nothing here ran on a GPU. ptxas numbers are static register
    allocation, not occupancy or throughput.
  • The probe kernels are never launched and produce no meaningful output; they
    exist to be compiled. Their doc comments say so.
  • No device test for the maps themselves. They are lane-local arithmetic over
    the ownership map the existing fragment map cases already validated on a
    B200; there is no new hardware contract to check.
  • Exp2Hw still has no host test — ex2_approx_f32's host body is
    unreachable!(). 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:

Closes #5

feitreim added 6 commits July 27, 2026 17:05
`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
@feitreim
feitreim merged commit 0e779ed into main Jul 27, 2026
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.

Generic map mechanism and the standard elementwise op set

1 participant