Skip to content

Split the GEMM lab notebook out of the examples, into a fourth crate - #134

Merged
feitreim merged 8 commits into
mainfrom
experiments-crate
Jul 29, 2026
Merged

feitreim merged 8 commits into
mainfrom
experiments-crate

Conversation

@feitreim

@feitreim feitreim commented Jul 29, 2026 •

Copy link
Copy Markdown
Owner

examples/src/gemm.rs was 8107 lines and 30 entry points, about a third of
which compute a deliberately wrong C. It is 1095 lines and one kernel now.
Everything else is experiments/, a fourth standalone crate.

src/            the library
examples/       teaching: gemm.rs (one kernel), softmax, layernorm, flash_forward
experiments/    every rung, probe, ablation, bench.rs, cublaslt.rs, README.md
device-tests/   correctness on device

Nothing is deleted. All 30 GEMM entry points, gemm_ws, every sweep and
every probe are still launchable and still on the correctness gate they were on,
from experiments/. scripts/modal-run examples now runs two binaries and
checks the same set it always did.

Verification

result
scripts/fmt --check, four manifests clean
scripts/modal-run build passes; the only clippy warnings in kittens-examples are the two pre-existing missing_safety_doc on softmax.rs and flash_forward.rs
scripts/modal-run regcount see below — one real defect found and fixed
scripts/modal-run examples gemm, softmax, layernorm pass in examples/; gemm, gemm_ws pass in experiments/ — both check sizes, all traversal widths, both schedulers where a rung has both
scripts/modal-run bench --case gemm --m 8192 --n 8192 --k 8192 1740.8 TFLOP/s, 0.943 of cuBLASLt (cuBLASLt 1846.4 in the same container), against #119's published 1645.0 / 0.939 and #117's 1668 / 0.944

The regcount diff against main, in full

main at 81c90da, this branch rebased on bd74bee. Every table compared row
by row.

  • device-tests, 184 kernels: identical, every counter.
  • experiments/, 42 kernels: identical to main's examples/, every
    counter — registers, spill stores, spill loads, stack, smem. The 43rd is
    flash_forward, which stayed in examples/.
  • Opcode census, 39 gemm_* rows: identical, every column.
  • examples/, 5 kernels: three identical (flash_forward,
    layernorm_rows, softmax_rows) and two moved. Crate composition and not
    source is what moved them — layernorm.rs is byte-identical apart from one
    README path in a doc comment, and the same file read 168 compiled into the
    42-kernel module and 236 into the 5-kernel one.

One of the two was a defect, and it is fixed. The first version of this PR
said "neither crosses its occupancy step". That was wrong for groupnorm_tile,
and the repo's own model — _ctas_by_registers, which regcount checks against
cuda_occupancy.h at all 255 register counts — is what says so:

_ctas_by_registers(168, 128) = 3        _register_ceiling(3, 128) = 168
_ctas_by_registers(236, 128) = 2        widest count still giving 3 = 168

So groupnorm_tile went 3 CTAs/SM to 2, and 168 was not a coincidence: it
is exactly the 3-CTA ceiling at 128 threads. Shared memory admits six or seven
CTAs at its 33 344 B plan (the driver reports 6 for its sibling at the same
plan), so registers are this kernel's binding term and nothing else was
going to hold the line. It had been sitting on its step without declaring one,
and the split knocked it off with nothing in the tree watching.

The fix is #[launch_bounds(128, 3)] on the kernel — __launch_bounds__,
so .maxntid 128, 1, 1 and .minnctapersm 3 go on the entry and ptxas is
told the residency the kernel is written for rather than reaching it by luck.
Measured:

groupnorm_tile regs spill st/ld stack CTAs/SM
main 168 0 / 0 1536 3
this branch, examples/, before 236 0 / 0 1536 2
this branch, examples/, after 168 8 / 8 1544 3
this branch, experiments/, after 168 0 / 0 1536 3

The recovery is not free and I am not going to round it off: the examples/
copy pays 8 bytes of spill store and 8 of spill load that main did not.

experiments/' copy is unaffected — it was already at 168, so the attribute
costs it nothing and its row stays byte-identical to main. On a memory-bound
normalization kernel, +50% CTAs against 8 bytes on a stack frame that was
already 1536 is the right side of the trade, but it is a trade.

And it cannot be timed, which is the same fact that let the loss happen.
groupnorm_tile has no launcher anywhere in the repo — it is the "compiles"
half of layernorm's status line — so there is nothing to measure before or
after. That is precisely why it needed a gate rather than a benchmark.

Both copies are now in GATED_KERNELS, so this is watched from here on.

The GEMM's move is the benign one: residency there is tensor-memory-bound at
512 / 256 = 2 CTAs/SM, and 80 and 96 registers allow 6 and 5, so neither count
reaches the binding term. And there is a stronger statement than the register
column for it — its opcode census is identical to main's, instruction for
instruction
: 4 tcgen05.mma, 2 tcgen05.ld, 2 cp.async.bulk.tensor, 2
stmatrix, 1 ld.shared.v4, 1 st.global.v4, 4 st.global.b32, 8
cvt.rn.bf16x2, 2 bar.sync, 1 bar.warp.sync, 1 mbarrier.arrive.
regcount now prints that comparison itself and says
1 kernel(s) in both crates: identical opcode counts.

What this still does not prove: nothing times the examples/ copy of the
GEMM either. bench lives in experiments/ and launches the byte-identical
96-register one, which is what the throughput numbers above are. The argument
that the two cannot differ is the identical census plus a residency neither
register count reaches — an argument, not a measurement, and giving the teaching
copy a clock would mean giving the teaching crate a benchmark.

Everything that is not a pure move

  1. examples/src/gemm.rs is a rewrite, not a subset. One kernel, so the
    const-generic axes it was written against have one instantiation each and are
    resolved: Tile<BLOCK_N, HALF_N, BLOCK_K, STAGES> is Tile,
    Staged<DRAIN, WIDE, X4> folds its staging tile into Tile and disappears,
    produce::<LOADS>/multiply::<MMA>/drain_staged::<WIDE, X4> lose their
    parameters, and cta_origin folds into origin — the CTA-scope TMA ring was
    its only other caller and that rung moved. Bodies are otherwise verbatim.
  2. ClcQueue is out of the teaching crate's shared plan. Nothing there
    steals work. Its 24 bytes moved SHARED_BYTES 98 392 → 98 368, and the
    declared envelope does not move at all: both round to a STAGE_OFFSET of
    98 432, so STAGED_SHARED_BYTES is 114 816 and the #[launch_contract]
    literal is unchanged. The const _: () = assert!(..) reads 98 368 there and
    98 392 in experiments/, which still declares both plans.
  3. shared_plan(block_n, block_k, stages) and scratch_bytes(stages) lose
    their parameters
    in the teaching crate — the sweep that varied them moved —
    and become SHARED_BYTES and SCRATCH_BYTES. pair_shape(block_n) keeps
    its parameter: it is a lookup from a tile width to an ISA shape, which is the
    gap GAPS.md §7.5 names, not scaffolding.
  4. CHECK_GROUPS is [GROUP, 1, 3, 6] there, where it was [1, 3, 6].
    GROUP is the width a launch actually uses and bench was its only caller;
    rather than delete a measured constant or leave it unreachable, the gate now
    launches it. One extra launch per size, same kernel.
  5. bench.rs is split, and examples/src/bench.rs is the seam. softmax.rs
    and layernorm.rs are untouched and say crate::bench::{Shape, Timings, time}; the sweeps that call their bench entry points are in
    experiments/. So the clock — Shape, Timings, time, WARMUP,
    ITERATIONS — stays in examples/src/bench.rs and
    experiments/src/bench.rs includes it with #[path] and re-exports it. One
    copy of the source, compiled by both crates. WARMUP and ITERATIONS became
    pub for the re-export.
  6. experiments/ compiles examples/src/softmax.rs and
    examples/src/layernorm.rs through #[path]
    , for the same reason — the
    softmax and layernorm rows of bench would otherwise have been deleted.
    No kernel source is duplicated anywhere in this PR.
  7. experiments/ gains a check argument running gemm::check and
    gemm_ws::check, because examples/' main was what used to call them.
    modal_app.py::examples invokes both binaries.
  8. modal_app.py::regcount is crate-aware in three places. _print_census
    prints a section per crate and states whether the kernel both crates emit
    agrees. _check_occupancy_step keys on (crate, kernel) rather than on the
    name alone — without that the gate would silently read whichever crate
    PTX_CRATES visited last, which is the failure mode gemm_cg2 is three registers from losing a third of its occupancy, and nothing is watching #95 exists to prevent.
    And GATED_KERNELS entries are (kernel, crate, source) rather than
    (kernel, source), because with #[path] the two diverge: both copies of
    groupnorm_tile are compiled from the one examples/src/layernorm.rs. It
    gains three entries — examples/' GEMM and both groupnorm_tiles.
  9. _launch_geometry reads #[launch_bounds(threads, ctas)] as an
    alternative to the #[launch_contract(block = ...)] + const CTAS_PER_SM
    pair, which is what let groupnorm_tile be gated at all. This was the
    smaller and the more honest of the two options offered: the alternative was a
    new hand-written const CTAS_PER_SM in layernorm.rs, which would be a
    claim about a launch nobody makes and a second copy of a number ptxas is
    also told. Reading the attribute means the compiler and the gate cannot be
    given different residencies. The GEMM keeps the CTAS_PER_SM spelling,
    correctly: there the number is what the grid is sized from, a host fact
    launch_bounds has no way to state.
  10. experiments/build.rs and cublaslt_abi.c moved with the cublas
    feature.
    examples/ has no features at all now and needs no CUDA toolkit
    to link.
  11. src/pipeline.rs and src/epilogue.rs: six examples/README.md →
    experiments/README.md
    , in //!//// prose. This is the one place the PR
    touches src/. They are dangling paths this move creates and nothing else in
    those files changed; drop the hunk if you would rather it were a follow-up.
  12. #[launch_bounds(128, 3)] on groupnorm_tile in
    examples/src/layernorm.rs, plus the launch_bounds import. This is the
    one change to a file the brief said stays unchanged, and item 3 of the
    verification section is why. Both crates compile that file, so both get it,
    and experiments/' copy is unaffected by it.
  13. Three small corrections in the teaching file, which is new code and not a
    moved body.
    The size check is is_multiple_of where the original was
    n % BLOCK_N != 0 (clippy asks for it, and -D warnings is coming for this
    crate eventually); N's doc said "two BLOCK_N tiles" and 256 columns is
    one, so the check size is two items wide in M and one in N and now says
    so; ITEMS_M x ITEMS_N's doc said M x N is four tiles, which it was at the
    [256, 128] pair tile and is two at this one. All three were stale in the
    file this was extracted from and are left alone in experiments/, where the
    move stays pure.
  14. GAPS.md §7 and §1.3/§4/§6 citations follow the code. Paths only, no
    claim and no numbering touched. Every cited line number survived the move
    unchanged, so only the directory moved — except §7.4's epilogue bullet, which
    now also cites examples/src/gemm.rs:496-520 as the same loop with the two
    const parameters resolved.

Build system

  • scripts/fmt and .github/workflows/ci.yml (tier 1) take a fourth manifest.
    experiments/ reaches into examples/src through #[path], so rustfmt visits
    those files twice — idempotent, and the reason the loop stays a loop.
  • modal_app.py: EXPERIMENTS_DIR, three new mounts, build compiles three
    kernel crates (and experiments/ twice, once with cublas), PTX_CRATES has
    three entries, and bench / clc_bench / ws_bench / profile point at
    kittens-experiments. Every existing entry point still works.
  • CI.md documents the fourth crate, the second binary on the tier-3 correctness
    gate, and why the register table carries two rows for one kernel.
  • Root Cargo.toml excludes experiments, .gitignore ignores its target dir,
    experiments/Cargo.lock is checked in and cargo metadata --locked passes on
    all four.

examples/ has no README, and that is a decision

The 4765-line one went to experiments/ with the sweeps it describes, and
nothing replaced it. The teaching crate's module docs are meant to carry it:
gemm.rs's header is the kernel's whole design, and main.rs's is the
four-kernel table plus a section saying what moved and where. A short new README
would duplicate those and go stale against them, and restoring the big one here
would undo the point of the split — so the absence is deliberate, not an
oversight.

Not in this PR

SHIPPED_EPILOGUE is still Epilogue::StagedWideX4 and gemm_ws::SHIPPED_ENTRY
is still Entry::StagedX8; they still differ, deliberately (#119/#120/#122).
Plan::new is still on the register drain, so the ablation cube, bench --case epilogue, bench --case staged and the scheduler A/B keep their control arm and
clc_bench keeps an entry point to launch. No pruning of scaffolding beyond what
the extraction made unreachable — that is a separate decision.

feitreim added 8 commits July 29, 2026 13:19
`examples/src/gemm.rs` was 8107 lines and 30 entry points, a third of which
compute a deliberately wrong `C`. It is now ~1100 lines and one kernel — the
one the library ships — and everything else is `experiments/`, a fourth
standalone crate holding every rung, probe, ablation, sweep, the cuBLASLt
denominator and the measurement record.

Nothing is deleted. Every entry point that existed is still launchable and
still on the correctness gate it was on, from its new home.
Splitting the crates took groupnorm_tile 168 -> 236 registers and 3 CTAs an SM
to 2, in the crate that is meant to be the clean one, with nothing in the tree
watching. 168 is exactly _register_ceiling(3, 128), so it had been sitting on
its step by luck rather than by declaration.

#[launch_bounds(128, 3)] is that declaration, in the one place ptxas reads it
too. The gate reads it as an alternative to the launch_contract/CTAS_PER_SM
pair, so the compiler and the gate cannot be told different numbers.
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.

1 participant