Skip to content

Scalar-operand maps: scale, shift, and a free rsqrt over the existing BinaryOp set - #44

Merged
feitreim merged 4 commits into
mainfrom
issue-38-scalar-maps
Jul 27, 2026
Merged

feitreim merged 4 commits into
mainfrom
issue-38-scalar-maps

Conversation

@feitreim

@feitreim feitreim commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

scale, shift, a free rsqrt(f32), and the rest of what #5 listed and did
not 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 struct
with an associated function. scale(k) cannot be a UnaryOp because there is
nowhere to put k. #5's mechanism covered ~30 functions and left this family
behind not by oversight but because the trait shape could not express it.

The fix reuses the existing BinaryOp set and treats the scalar as the second
operand:

impl<const M: usize, const N: usize, L: FragmentLayout<M, N>> RegTile<M, N, L> {
    pub fn scalar_map<Op: BinaryOp>(self, k: f32) -> Self;
}

Same on RegVec and ColVec. Div against a constant, Sub, Max/Min
against 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 new
one stays one line:

name op
scale(k) Mul
shift(k) Add
clamp_min(k) Max
clamp_max(k) Min

Div/Sub get no wrapper on purpose — scalar_map::<Div>(k) already reads
correctly, and a div_scalar name would be worse than the generic one.

Plus a free rsqrt(f32) beside exp2_approx/log2_approx, with the Rsqrt
op struct now delegating to it so the two cannot drift. groupnorm_tile's
variance is one f32 — it never becomes a vector, so there is nothing for
RegVec::rsqrt to ride on.

RegTile::add_assign is not here. It is in-place, and #31 exists to land
every in-place map variant at once; a one-off would have to be unified later.

Registers, at both widths

scalar_map_probe in device-tests compiles the same flash-shaped tile loop
three 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 difference
is the spelling. modal run modal_app.py::regcount:

spelling 32 columns 128 columns
bin_map::<Mul>(splat(k)) — pre-#38 48 regs, no spill 255 regs, 124 B spill st/ld
scale(k) 48 regs, no spill 255 regs, 60 B spill st/ld
in place, through set 48 regs, no spill 252 regs, no spill

Both 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_roundtrip and #41's tma_store_* (baseline re-captured on a
clean detached checkout of current main after 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.

  1. scale pays for itself. Strictly better than what a kernel had to write
    before it — half the spill at 128 columns, free at 32.

  2. "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 scaled
    tile chained inside another map, so block and its scaled copy are both
    live at the peak — it took 84 B of spill, where the rebinding
    block = block.scale(k) took none. Same op, same width, same by-value
    map. Only the peak liveness differs.

    Read that way, three results that look unrelated line up:

    The variable is how many tiles are live at once, not whether a method takes
    self by 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_rows and groupnorm_tile now spell their scalar
broadcasts in the real API. Neither aspirational kernel is unblocked by this
alone, so examples/README.md writes out exactly what each still fails on:

softmax and gemm run and are untouched by this PR. The scalar-broadcast
entries 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 makes
    this a BinaryOp map and not a second mechanism: for every op, on all three
    families, over all 32 lanes, scalar_map equals bin_map against a splatted
    tile. The only thing it saves is the splat.
  • scalar_names_resolve_to_their_ops — the generated name table per family. A
    transposed line makes shift mean scale, which is a wrong kernel and not a
    slow one. Also asserts the unnamed ops stay reachable.
  • free_rsqrt_is_the_op_struct — the free function and Rsqrt::apply are the
    same number, which is what lets a normalization kernel's host reference use
    ==.

No device test: lane-local arithmetic, no new hardware contract. exp2_hw is
untouched and still untested, for the same reason as before
(ex2_approx_f32's host body is unreachable!()).

Verified, post-rebase

  • modal run modal_app.py::build — clippy on all three crates, host tests, and
    a real cargo oxide build --arch sm_100a of both device-tests and
    kittens-examples. Passes.
  • modal run modal_app.py::regcount — re-measured on 9912ccd, before and
    after. Table above; no pre-existing kernel moved.
  • cargo clippy --all-targets, cargo fmt --check, cargo test --lib clean.
  • No GPU run. The rebase changes nothing a running kernel executes: this PR
    only adds methods, softmax and gemm call none of them, and their generated
    code is unchanged.

src/shared.rs, src/global.rs, src/tmem.rs and src/ldst.rs are untouched,
as are online_rescale and scale_rows. examples/Cargo.lock is deliberately
left out of the diff.

Closes #38

feitreim added 4 commits July 27, 2026 19:40
`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
feitreim force-pushed the issue-38-scalar-maps branch from 1cfdabb to b82dcc8 Compare July 27, 2026 23:46
@feitreim
feitreim merged commit 77de620 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.

Scalar-operand maps: scale, shift, and the ops #5 listed but did not ship

1 participant