Skip to content

kittens: a tcgen05 tile library for cuda-oxide, with flash-attn and gemm ported onto it (#61) - #64

Merged
feitreim merged 13 commits into
mainfrom
feat/issue-61-kittens-phase1
Jul 26, 2026
Merged

feitreim merged 13 commits into
mainfrom
feat/issue-61-kittens-phase1

Conversation

@feitreim

Copy link
Copy Markdown
Owner

Closes #61. Follow-ups tracked in #63.

gpu/kittens — a ThunderKittens-style tile library for cuda-oxide, tcgen05/sm_100a only — plus every flash-attn and gemm kernel ported onto it, plus two new kernels written against it. Phases 0–5 of #61.

What this is

New kernels are written against typed shared/register/TMEM tiles instead of raw intrinsics and hand-threaded index math. The crate ships no kernels and no #[cuda_module]: everything is #[inline(always)] functions and Copy structs of pointers + const generics, monomorphizing into the calling crate's artifact, and nothing in it touches libdevice-lowered math so it stays linkable into pure-PTX artifacts like flash.ptx.

gpu/kittens/src/
  shared.rs   SharedTile/SharedTileRing, SWIZZLE_128B subtile stacking, TMA box loads, operand descriptors, OperandWalk
  reg.rs      RegVec/RegTile/Fragment, quad reductions, software exp2/log2, fused online_rescale, value_column
  tmem.rs     TmemTile: base + (row << 16) + column, the 16x256b fragment drain, block alloc/dealloc
  sync.rs     Semaphore / SemaphoreRing<N> / PhasedSemaphore — mbarrier phase parity, first-class
  mma.rs      the chained K=16 walks (mma_abt / mma_ab / mma_walk_cg2) + commits
  ldst.rs     swizzled stmatrix fragment stores
  pipeline.rs the persistent producer/consumer harness (Job trait)
  global.rs   host-side TMA descriptor builders

Every abstraction was extracted from a working kernel, not designed first (SPEC decision 15). Where a typed abstraction cost performance it was rejected in favour of a value-level one — OperandWalk exists because gemm picks K-major vs MN-major from a runtime launch parameter, and a typed two-arm branch duplicated the MMA chain (+59 instructions, 48→80 regs).

Enforcement: same SASS, fewer lines

Phase 0 turned the printed ptxas table into a regression gate (bench_util::enforce_kernel_budgets) — every kernel carries a pinned register/spill ceiling, a hard error past it, a ratchet hint under it. Each phase was gated on parity at every shape plus that budget, and every claim below is a B200 measurement, not an assertion.

The library's cost, stated plainly: one register. The new pipelined backward runs three warp roles, two S/dP buffers and six barrier sets, and allocates 53 against the synchronous kernel's 52.

Results

flash-attn — every kernel kittens-native; no raw mbarrier, swizzle, or fragment math remains, and cvt_f32x2_bf16x2/stmatrix_m8n8_x2 are no longer imported at all. tcgen05.rs 2783 → 2333 lines (peak 2963 mid-series; the phase-5 port alone removed 612, including ~250 lines of dead Design-A register passes with no call sites).

Two new kernels, written kittens-first (#61's acceptance criterion). flash_backward_q_pipelined / flash_backward_kv_pipelined warp-specialize the backward pair over unchanged Design-B math — these were the last synchronous tcgen05 kernels in the repo, running four block syncs per key tile with the tensor cores idle through every register pass:

sync pipelined
backward q 2.370 ms / 277.3 TFLOP/s 2.135 ms / 307.8 −9.9%
backward kv 3.171 ms / 276.3 TFLOP/s 2.664 ms / 328.8 −16.0%
attention backward 5.541 ms 4.799 ms −13.4%

dq/dk/dv are bit-identical to the kernels they replace at all three gate shapes — a pure scheduling change must be, so assert_identical gates it rather than a tolerance that would hide a dropped or reordered tile.

Forwards (ported): persistent 231.8 TFLOP/s, pipelined 191.5, sync 125.8 — against 230.3 / 182.0 / 126 at main.

gemm: both #[cuda_module]s rewritten, 48 regs / 0 spill, identical to the pre-port allocation.

Gates

  • flash: parity at 5 forward shapes × 3 kernels + 3 backward shapes, plus bit-identical asserts for the new kernels; ptxas budgets for all 7 kernels
  • gemm: parity in four gated runs including the MN-major weight-gradient gate
  • trainer: all 13 run.sh model gates green, MoE overfit at its recorded 2.949433 → 0.000060 to the digit
  • gpu/kittens has CPU unit tests for every piece of address/descriptor/parity math (cargo test, no GPU needed)

Two costs taken deliberately

Both are recorded with their numbers in SPEC 7e17 rather than smoothed over:

  1. gemm's fp32 epilogue, +1.3% full step. Packed-mode rows are flat; the fp32-store/accum rows regressed ~3–6%. The investigation eliminated every source-visible cause — identical allocation, instruction-identical drain loops, 13 lines of surviving PTX that are LLVM block-layout choices. Kept and measured end-to-end (572.4 → 579.9 ms).
  2. The unified P-store, ~1.3% on the persistent forward. Routing softmax_tile's last hand-rolled fragment store through the library costs 234.7 → 231.8 TFLOP/s, reproducible across two runs. The instruction stream is strictly smaller (13–28 fewer per kernel, frame and local traffic identical to the byte) — the cost is entirely ptxas re-rolling its schedule. Taken for the single store path; the lever to reclaim it is schedule-level, not source.

Notes for review

  • gpu/kittens is a standalone crate (not in the CPU workspace), depended on by path from flash-attn and gemm.
  • The ptxas pins in gpu/flash-attn/src/bin/flash.rs carry a per-phase changelog explaining every movement, including one ordering constraint that is load-bearing (barrier init must precede the TMEM allocation; moving it cost +3 registers and was reverted).
  • Register counts moved a lot across phases in both directions. Occupancy is TMEM-pinned at one CTA/SM throughout, so the pins track measured allocation rather than fighting the allocator's ordering sensitivity — the bench is the arbiter, and it is quoted at every step.

feitreim added 13 commits July 26, 2026 09:40
New gpu/kittens crate: SharedTile (swizzled layouts, TMA descriptors,
operand descriptors), TmemTile, Semaphore/SemaphoreRing mbarrier wrappers,
tcgen05 mma/commit, ldst fragment movement, register tiles. tcgen05 /
sm_100a only, no arch dispatch. bench-util grows the KernelBudget ptxas
regression gate; flash-attn kernels rewritten on the library (register
pins: sync 40, pipelined 179, persistent 239 - identical to base).
Both #[cuda_module]s on the library: OperandWalk keeps the runtime
K-major/MN-major select as data so the cg2 pair-UMMA chain stays one
loop (a typed two-arm branch cost +59 instr, 48->80 regs), multicast
TMA loads and the cluster semaphore alias move into kittens, barriers
become SemaphoreRing with literal-stage selection. ptxas gate extended
to gemm, pinned at the pre-port allocation (48 regs, 0 spill). Parity
green x4 on B200. Known cost: f32-epilogue SASS-schedule artifact,
+1.3% full model step (572.4 -> 579.9 ms), accepted in SPEC 7e17.
kittens::pipeline::run extracts flash_forward_persistent's scaffold
(strided work-item loop, per-item barrier lifecycle, tcgen05 fence
pairing) behind a Job trait; tmem::alloc_block/dealloc_block own the
warp-0 TMEM lifecycle. All three forwards drop their raw mbarrier math:
the hand-threaded parity bits were SemaphoreRing arithmetic in disguise
(double_s = ring depth 2 vs 1; the persistent (i-1)&1 wait is
wait_recycled), and Stream<S_BUFFERS> bundles a softmax workstream's
TMEM/P/barrier set for both warp-specialized kernels. PTX vs base:
backwards byte-identical, persistent net -1 instruction. Parity green
at every shape; bench pipelined 187.6 -> 192.2 TFLOP/s, persistent
flat 234.9. ptxas re-pins 179->180 / 239->240 (+1 each, stable across
opcode-identical formulations; init-before-alloc ordering is
load-bearing and documented at the pins).
The last raw mbarrier/swizzle/fragment math in flash-attn moves onto the
tile library, so every kernel in the crate is now kittens-native.

Library, extracted from the working backward kernels (decision 15):
- reg: `Fragment` (= RegTile<2,4>, one TMEM drain's worth per thread) and
  `value_column`, the {0,1,8,9}-per-16-block offset every masking and
  per-column-statistic site used to transcribe by hand.
- tmem: `fragment_tile` — `fragment`'s simd pair resolved into
  [slot][value] order, so register passes index by row and column.
- ldst: `store_fragment_bf16` — the store twin, addressed by the same
  (row, column) the drain used. Replaces `write_bf16_fragment`'s eight
  loose f32 arguments.
- sync: `PhasedSemaphore` — a semaphore owning its phase counter, which
  is what the `tma_phase`/`mma_phase` locals were. `wait_next()` also
  dissolves the "starts at 1 because the resident load took phase 0"
  subtlety.
- shared: `tma_load_at` — a box landing at a destination row, i.e. how
  two adjacent 64-row tiles stack into one 128-row paired operand.

Kernel side: both paired register passes rewritten as loops over
Fragment; both backward kernels and both probes on Semaphore/
alloc_block/tma_load; `load_panel`, `load_q_paired`, `score_mma_paired`,
`grad_mma` and `write_bf16_fragment` deleted as shims over library
calls; `backward_q_tile`/`backward_kv_tile` deleted as dead Design-A
leftovers with no call sites since the paired kernels landed.
tcgen05.rs 2963 -> 2351 lines.

Gate green: parity at five forward shapes x three kernels plus three
backward shapes; bench 114.0 / 192.0 / 234.7 forward, 197.7 backward
(phase 4: 114.2 / 192.2 / 234.9 / 198.2). ptxas ratchets DOWN for the
first time in this series -- backward q 62->52, kv 64->60, forwards
unchanged at 40/180/240, local frames unchanged to the byte. PTX is
+9/+8 instructions on the backwards, all of it alloc_block's
fall-through `bra.uni` block splits; the kv register pass gave back
five `or.pred`s (looped masking shares the `masked_all` term) and three
`cvta.shared`s.
…result

Records the flash side of phase 5 (every kernel in the crate now
kittens-native, tcgen05.rs 2963->2351, ptxas ratcheting down for the
first time) and the measured reason softmax_tile's pass-2 store stayed
hand-written: both formulations are documented, including the one whose
indexed fragment fill lands in the local depot inside the softmax inner
loop, and the literal-construction one that is clean by every static
measure but re-rolls ptxas into a 1.3% persistent-forward regression.
…e 5)

The first kernel written against the tile library rather than ported onto
it, and the last synchronous tcgen05 kernel's replacement: the
query-parallel backward ran TMA -> sync -> MMA -> sync -> register pass
-> sync -> gradient MMA -> sync per key tile, with the tensor cores idle
through every register pass. `flash_backward_q_pipelined` runs the
forward's three-role specialization over the same Design-B math -- a TMA
warp streaming a BACKWARD_STAGES-deep K/V ring, an MMA warp staggering
S/dP-MMA(i) ahead of dQ-MMA(i-1), and the 128-thread gradient warpgroup
in between.

The one structural difference from the forward: K(i) is read twice, by
the score MMA immediately and by dQ-MMA(i) a full stage later, so
`kv_free(i)` hangs off `dq_done(i)` rather than off the score barrier.
That same wait then proves the gradient MMA finished reading dS, which
is what lets dS stay single-buffered (16 KiB saved) exactly as P does in
the forward.

Everything below the scheduling is library: SharedTileRing/SemaphoreRing
for the ring and its parities, TmemTile::columns_right for the S/dP
double buffer, and backward_q_tile_paired reused verbatim from the
synchronous kernel.

B200: 2.370 -> 2.135 ms (-9.9%), 277.3 -> 307.8 TFLOP/s. `dq` is
BIT-IDENTICAL to the synchronous kernel at all three gate shapes (a pure
scheduling change must be, so `assert_identical` gates it rather than a
tolerance). ptxas 53 regs / 512 B frame -- one register more than the
kernel it replaces, for three warp roles and six barrier sets. Forwards
byte-identical in PTX and flat on the bench.
Kernel B's half of the kittens-first pair, same three roles as kernel A
over the same Design-B transposed math. Two structural differences, both
forced by the transpose:

- The loop streams query tiles `key_a..T/64`, so it starts at a runtime
  value. Every ring index and phase parity runs off `step = query -
  key_a` while data addressing keeps the absolute tile: a SemaphoreRing
  derives parity from the barrier's visit count, which is the step. (A
  bug here would have hung exactly the CTAs with key_a > 0.)
- `lse2`/`dot` index by query COLUMN here, so they are re-staged every
  streamed tile -- which the synchronous kernel did behind a block sync
  that warp specialization deletes. They now ride the ring: the TMA
  warp's 32 lanes each stage two of the 64 rows, `warp::sync_mask`
  orders those stores ahead of the leader's `expect_tx`, and the stage's
  own `qdy_full` publishes them alongside the tiles they describe.

Q and dY are each read twice (score MMA, then gradient MMA a stage
later), so `qdy_free` hangs off `grad_done` exactly as kernel A's K
does, which also keeps both Pᵀ and dSᵀ single-buffered.

B200: 3.171 -> 2.664 ms (-16.0%), 276.3 -> 328.8 TFLOP/s; `dk` and `dv`
BIT-IDENTICAL to the synchronous kernel at all three gate shapes. With
kernel A the whole attention backward is 5.541 -> 4.799 ms (-13.4%).
ptxas 72 regs / 1024 B frame; the +12 over the synchronous kernel is the
second gradient accumulator's drain, and occupancy is TMEM-pinned at one
CTA/SM regardless (this kernel uses all 512 columns).
Points gpu/model's tcgen05 attention backward at
backward_q_pipelined/backward_kv_pipelined and records the phase-5
kittens-first kernels in SPEC 7e17.

All thirteen `run.sh model` gates pass, MoE overfit at its recorded
2.949433 -> 0.000060 (bit-identical kernels, so the trajectory is
unchanged to the digit). Candidate-side profile at B=12 T=2048: full
step 567.59 ms, backward.attention.flash_q 32.59 ms (5.74%) + flash_kv
38.44 ms (6.77%) = 12.51% of step in the two spans this work owns. That
is single-sided; the same-container A/B needs the branch pushed, and the
SPEC entry says so rather than quoting a step delta as measured.
softmax_tile's pass-2 P-write moves onto `store_fragment_bf16`, making
kittens the only fragment-store path in flash-attn: `cvt_f32x2_bf16x2`
and `stmatrix_m8n8_x2` are no longer imported by tcgen05.rs at all.

The fragment is built as a LITERAL over an `#[inline(always)]`
`masked_exp2` helper, not filled through an indexed loop -- the loop
form does not scalarize and puts 64 B of frame and 76 `st.local` into
the softmax inner loop (issue #61's risk 1). As a literal the tile
evaporates: frame unchanged at 592 B, `ld/st.local` and the
FMA/mul/select histogram identical to the byte, 13-28 fewer
instructions per forward kernel. Pass 1 stays hand-written on purpose:
its diagonal/else split is a TREE reduction that a uniform masked loop
would flatten into a 4-deep dependent fmax chain.

ptxas re-rolls the schedule against it -- sync 40->32, pipelined
180->216, persistent 240->236, reproducible to the register across two
runs -- and persistent benches 231.6/231.8 TFLOP/s against 234.7/234.9/
234.7 before, a reproducible ~1.3%; pipelined 191.5 flat, sync 125.8
(+10%, undoing phase 2's 126->115 dip). Finn's call to take the 3
TFLOP/s for the single store path. Occupancy untouched (TMEM pins 1
CTA/SM), forward parity identical to the digit at every gate shape,
backwards unaffected and still bit-identical. Pins re-set to measured.
@feitreim
feitreim merged commit 1458b67 into main Jul 26, 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.

kittens: ThunderKittens-style tile library for cuda-oxide (tcgen05-only)

1 participant