Repository navigation
Scalar-operand maps: scale, shift, and a free rsqrt over the existing BinaryOp set - #44
Merged
Merged
Conversation
`trait UnaryOp { fn apply(x: f32) -> f32; }` is stateless — a unit struct
with an associated function — so `scale(k)` has nowhere to put `k`. That
is why #5's map mechanism covered ~30 functions and left the scalar
family behind: a hole in the trait shape, not a missed line item.
Rather than a stateful op trait, take the scalar as the *second* operand
of the ops that already exist. `scalar_map::<Op>(k)` is one method on
each of `RegTile`, `RegVec` and `ColVec`, and `scale`/`shift`/`clamp_min`/
`clamp_max` are `Mul`/`Add`/`Max`/`Min` through the existing method
macro. `Div` and `Sub` against a constant need no wrapper to be callable,
which is the point.
Also a free `rsqrt(f32)` beside `exp2_approx`/`log2_approx`, with the
`Rsqrt` op struct delegating to it so the two cannot drift: layernorm's
variance is one `f32` and has no vector to reach the op struct through.
`RegTile::add_assign` is deliberately absent — it is in-place, and #31
exists to land every in-place map variant at once.
`row_map::<Mul>` measured 168 -> 255 registers/thread against the in-place `scale_rows`, so a by-value scalar map gets the same treatment. `scalar_map_probe` compiles the same tile loop three ways — the pre-#38 `bin_map::<Mul>(splat(k))`, the new `scale(k)`, and an in-place multiply through `set` — all computing the same tile, at 32 and 128 columns. At 32 all three are 48 registers with no spill. At 128: 255/124 B spill splatted, 255/60 B scaled, 252/no spill in place. `scale` halves the spill against what a kernel had to write before it, and the by-value/in-place gap #31 was filed about reproduces for a scalar operand.
`flash_forward`'s `s.scale(scale * LOG2E)`, `layernorm_rows`'s `row_sum().scale(1/N)` and `variance.shift(epsilon).rsqrt()`, and `groupnorm_tile`'s `shift(-mean)`/`scale(rsqrt(variance + epsilon))` all resolve; only the prose around them changed. Neither kernel is unblocked by this alone, so the README now writes out exactly what each one still fails on, read off the compiler: - softmax: `tma_store*` (#9), and nothing else - flash: `TmemTile::drain`/`store_tile` (#22), `FragmentLayout<32, 64>` (#23), `store_rows` (#11), `add_assign` (#31), and `make_causal_at` (#7), which does not appear as its own error because the band whose layout bound failed suppresses method resolution on it - layernorm: `load_tile`/`store_tile` (#22), `SharedVec` (#13), `tma_store*` (#9), `block_reduce_sum` (#3) Plus the register table, and what it implies for #31.
An intermediate form of the same probe took 84 B of spill written as `out_acc.add(block.scale(k))` and none as `block = block.scale(k)` — same op, same width, same by-value map, differing only in how many tiles are live at the peak. That reading lines up three results that look unrelated: #5's `row_map` cliff, #38's 60 B, and #22's composed movers coming out cheaper (36 vs 52) than the loops they replaced. So the variable is peak liveness, not by-value-ness, which makes #31's job narrower than "add in-place forms": a by-value map whose input dies at the call already costs nothing.
feitreim
force-pushed
the
issue-38-scalar-maps
branch
from
July 27, 2026 23:46
1cfdabb to
b82dcc8
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.
scale,shift, a freersqrt(f32), and the rest of what #5 listed and didnot ship — as one mechanism rather than a list of methods.
Rebased onto
9912ccd(#41 and #43). All measurements below are from that base.Why it was missed, and why that decided the fix
trait UnaryOp { fn apply(x: f32) -> f32; }is stateless: a unit structwith an associated function.
scale(k)cannot be aUnaryOpbecause there isnowhere to put
k. #5's mechanism covered ~30 functions and left this familybehind not by oversight but because the trait shape could not express it.
The fix reuses the existing
BinaryOpset and treats the scalar as the secondoperand:
Same on
RegVecandColVec.Divagainst a constant,Sub,Max/Minagainst a bound are all reachable the day they are written — no new op, no new
trait. The named wrappers go through the existing
op_methods!macro, so a newone stays one line:
scale(k)Mulshift(k)Addclamp_min(k)Maxclamp_max(k)MinDiv/Subget no wrapper on purpose —scalar_map::<Div>(k)already readscorrectly, and a
div_scalarname would be worse than the generic one.Plus a free
rsqrt(f32)besideexp2_approx/log2_approx, with theRsqrtop struct now delegating to it so the two cannot drift.
groupnorm_tile'svariance is one
f32— it never becomes a vector, so there is nothing forRegVec::rsqrtto ride on.RegTile::add_assignis not here. It is in-place, and #31 exists to landevery in-place map variant at once; a one-off would have to be unified later.
Registers, at both widths
scalar_map_probeindevice-testscompiles the same flash-shaped tile loopthree ways — the pre-#38 spelling, the new one, and an in-place multiply
written through
set. All three compute the same tile, so the only differenceis the spelling.
modal run modal_app.py::regcount:bin_map::<Mul>(splat(k))— pre-#38scale(k)setBoth probe widths were measured rather than trusted — #5 found the 32-wide
probes insensitive and #6 found the reverse at its shapes. Here 32 is flat and
128 is the one that separates them.
Every pre-existing kernel on the table is byte-identical to
9912ccd, including#43's new
band_roundtripand #41'stma_store_*(baseline re-captured on aclean detached checkout of current
mainafter the rebase, not carried forward).What this implies for #31 — and I think #31's framing needs rewriting
Two results, and the second matters more than the first.
scalepays for itself. Strictly better than what a kernel had to writebefore it — half the spill at 128 columns, free at 32.
"By-value costs registers" is probably the wrong lesson. The by-value /
in-place gap does reproduce here (60 B and 124 B of spill against 0), which
read naively says "add in-place forms." But an intermediate form of the same
probe says otherwise: written as
out_acc.add(block.scale(k))— the scaledtile chained inside another map, so
blockand its scaled copy are bothlive at the peak — it took 84 B of spill, where the rebinding
block = block.scale(k)took none. Same op, same width, same by-valuemap. Only the peak liveness differs.
Read that way, three results that look unrelated line up:
row_mapcliff at 128 columns — a second tile live beside theaccumulator it is replacing.
(36 registers against 52) — the composed form keeps one band live where
the hand-written loop kept a band and a fragment.
The variable is how many tiles are live at once, not whether a method takes
selfby value. If that holds, The map mechanism needs in-place variants: by-value costs 87 registers at 128 columns #31's job is narrower than it looks:in-place forms pay only where the input is live across the op, and a
by-value map whose input dies at the call already costs nothing. That also
predicts which call sites are worth converting and which are noise, which
"add in-place variants" does not.
Examples
flash_forward,layernorm_rowsandgroupnorm_tilenow spell their scalarbroadcasts in the real API. Neither aspirational kernel is unblocked by this
alone, so
examples/README.mdwrites out exactly what each still fails on:flash_forward—FragmentLayout<32, 64>(RegTile's shape set is closed to out-of-tree kernels #23),global::store_rows(Direct global to/from register load and store #11),
RegTile::add_assign(The map mechanism needs in-place variants: by-value costs 87 registers at 128 columns #31).make_causal_at(Masking and shape utilities: make_causal, tril/triu, fills, transpose #7) is wanted too anddoes not appear as its own error — it is called on the
[32, 64]bandwhose layout bound already failed, and an unsatisfied bound on the receiver
suppresses method resolution on it. Closing RegTile's shape set is closed to out-of-tree kernels #23 would make Masking and shape utilities: make_causal, tril/triu, fills, transpose #7 surface, not
disappear. Called out in the README because a reader counting compiler errors
would otherwise conclude Masking and shape utilities: make_causal, tril/triu, fills, transpose #7 has landed.
layernorm—SharedVec(Shared vectors, and ops on shared tiles #13), andsync::block_reduce_sum(Block-scope reductions: the fold four warps need, and the fp32 Element under it #3), thelatter only in
groupnorm_tile.softmaxandgemmrun and are untouched by this PR. The scalar-broadcastentries are gone from every blocked-on list, and layernorm's module doc no
longer names them.
Testing
Pure f32 arithmetic over plain arrays, so it is host-testable — three new tests
in
src/reg.rs:scalar_map_is_bin_map_against_the_splatted_scalar— the claim that makesthis a
BinaryOpmap and not a second mechanism: for every op, on all threefamilies, over all 32 lanes,
scalar_mapequalsbin_mapagainst a splattedtile. The only thing it saves is the splat.
scalar_names_resolve_to_their_ops— the generated name table per family. Atransposed line makes
shiftmeanscale, which is a wrong kernel and not aslow one. Also asserts the unnamed ops stay reachable.
free_rsqrt_is_the_op_struct— the free function andRsqrt::applyare thesame number, which is what lets a normalization kernel's host reference use
==.No device test: lane-local arithmetic, no new hardware contract.
exp2_hwisuntouched and still untested, for the same reason as before
(
ex2_approx_f32's host body isunreachable!()).Verified, post-rebase
modal run modal_app.py::build— clippy on all three crates, host tests, anda real
cargo oxide build --arch sm_100aof bothdevice-testsandkittens-examples. Passes.modal run modal_app.py::regcount— re-measured on9912ccd, before andafter. Table above; no pre-existing kernel moved.
cargo clippy --all-targets,cargo fmt --check,cargo test --libclean.only adds methods,
softmaxandgemmcall none of them, and their generatedcode is unchanged.
src/shared.rs,src/global.rs,src/tmem.rsandsrc/ldst.rsare untouched,as are
online_rescaleandscale_rows.examples/Cargo.lockis deliberatelyleft out of the diff.
Closes #38