Repository navigation
Description
Summary
Build gpu/kittens: a ThunderKittens-style tile library for cuda-oxide, so new kernels are written against typed register/shared/TMEM tiles with warp- and warpgroup-scoped ops instead of raw intrinsics. Blackwell only: the MMA layer targets tcgen05/sm_100a exclusively — no wmma/wgmma backends, no arch dispatch.
Depends on #56 (bump to upstream main): the generated-intrinsics catalog (register_mma, stmatrix, ldmatrix, movmatrix, mbarrier_basic/extended, generated tcgen05 incl. tcgen05.st, tma, ex2_approx_f32) is the primitive layer this library composes. Nothing below requires new inline PTX; ptx_asm! (multi-output since upstream #411/#443) is the escape hatch if a gap appears.
Why
gpu/flash-attn/src/tcgen05.rs (~2.9k lines) is a hand-rolled, monomorphic ThunderKittens kernel: swizzled SWIZZLE_128B subtiles, mbarrier phase-parity rings, warp specialization, TMEM accumulators — all encoded in comments and index math rather than types. The gemm crate re-derives overlapping machinery. Every new fused kernel (gpu/ops, router/scatter work in #53/#54/#55) currently pays that cost again. The tile library extracts the validated idioms once, behind types that make shape/layout mismatches compile errors.
Concept mapping (TK → Rust/cuda-oxide)
| ThunderKittens | kittens-rs |
|---|---|
rt<T, R, C, layout> register tile |
RegTile<T, const R: usize, const C: usize, L: Layout> — fragment arrays, fully scalarized |
rv register vector (row stats) |
RegVec<T, const N: usize, L> |
st<T, R, C> shared tile, swizzle in the type |
SharedTile<T, const R: usize, const C: usize, S: Swizzle> over SharedArray/DynamicSharedArray; swizzle math lifted from flash-attn's tcgen05.rs |
tt TMEM tile (Blackwell) |
TmemTile<T, const R: usize, const C: usize> over generated tcgen05 alloc/ld/st |
gl global layout + TMA map |
host-side descriptor builder + device TmaDescriptor |
scoped ops warp:: / warpgroup:: / group<N>:: |
free generic fns / traits; scope as module or Group<const WARPS: usize> marker |
semaphore, expect_bytes, wait |
Semaphore over mbarrier intrinsics, tracking phase parity internally (today parity bits are threaded by hand) |
prototype::lcf persistent harness |
pipeline::run::<Job, const STAGES: usize> — extraction of flash_forward_persistent's scaffold |
Proposed crate layout
gpu/kittens/
src/
lib.rs // re-exports, scope markers
reg.rs // RegTile, RegVec, layouts, maps (exp2/mul/sub_row/...), reductions (row_max/row_sum)
shared.rs // SharedTile + Swizzle (None/32B/64B/128B), subtile stacking for wide panels
tmem.rs // TmemTile: alloc/dealloc, ld/st fragments, fences
global.rs // GlobalLayout + host TMA descriptor builder
ldst.rs // warp/warpgroup load/store: ldmatrix/stmatrix/movmatrix, TMA issue g2s/s2g
mma.rs // tile-level mma over tcgen05 ONLY (instruction descriptors, shapes, transpose forms)
sync.rs // Semaphore (mbarrier + phase), expect_tx, commit
pipeline.rs // producer/consumer ring + persistent-grid harness
Cross-crate device code is viable the same way cuda-device is (#[inline(always)] monomorphized into the kernel crate); upstream -Zalways-encode-mir fix (#454) covers the remaining linking edge.
Target kernel style:
let q = SharedTile::<bf16, 64, 128, Swizzle128B>::alloc(&mut smem);
let mut s = TmemTile::<f32, 64, 64>::alloc();
let mut row_max = RegVec::<f32, 64, Col>::neg_infinity();
tma::load_async(&q, &q_gl, (bh, tile, 0), &load_sem);
load_sem.wait(phase);
mma::<Trans::B>(&mut s, &q, &k); // S = Q·Kᵀ
let mut p = s.load_regs();
row_max.max_assign(p.row_max());
p.sub_row(&row_max);
p.exp2(); // hardware ex2.approx post-#56
p.store_bf16(&p_shared); // swizzled stmatrixPhases
Success criterion for phases 1–4: same SASS, fewer lines. Each phase refactors an existing, gated kernel; parity oracles and same-container profiles (SPEC §10.1) must stay green/within noise. If the abstraction costs registers or occupancy, that is a library bug, not an acceptable tax.
- Phase 0 — land Bump cuda-oxide pin to upstream main @ b099f64 (tcgen05.st landed) #56; add a
ptxas -vregister/spill regression check to bench-util so every later phase has an objective gate - Phase 1 —
shared.rs+global.rs+sync.rs:SharedTile/swizzle, TMAGlobalLayout,Semaphore. Rewrite the loader warp offlash_forward_pipelinedon it. Pure refactor. - Phase 2 —
reg.rs:RegTile/RegVec, maps + reductions (incl.ex2.approx); portsoftmax_tile - Phase 3 —
mma.rs+tmem.rs: tile-level tcgen05 mma (M128 pairing, transpose descriptor forms from the backward kernels) and TMEM tiles incl.tcgen05.st; port the gemm crate as the clean A/B perf harness - Phase 4 —
pipeline.rs: extract the persistent producer/consumer scaffold fromflash_forward_persistent; port the full forward kernels - Phase 5 — new kernels written kittens-style: flash backward cleanup, fused
gpu/ops, router/scatter (Router phase 2: weight-reuse pass for backward input/weight #54/scatter_dy phase 2: vectorized row copy + fold zero_dy_bins #55); revisit FA4 conditional rescaling in TMEM (unblocked bytcgen05.st) as a dedicated correction warpgroup
Risks / open questions
- Register allocation through abstraction. Tiles must fully scalarize:
#[inline(always)]everywhere, compile-time-unrolled fragment iteration (const-generic recursion or macro unrolls — plainwhileloops may not unroll). Phase 0's ptxas gate is the enforcement mechanism. - Libdevice discipline. Until Bump cuda-oxide pin to upstream main @ b099f64 (tcgen05.st landed) #56's verification says otherwise, the library must be pure-PTX-safe throughout (no
f32::exp/ln/sqrt/floor); shipexp2/log2viaex2.approx+ the existing softwarelog2. - Swizzle generality. v0.2.1 code exploits the 64-wide-subtile coincidence (swizzle phase == row). The
Swizzletype must encode the general SWIZZLE_128B pattern or honestly restrict supported widths — decide in phase 1. - No named barriers upstream — warpgroup handoffs stay mbarrier phase-parity spins;
sync.rsshould make that idiom first-class rather than pretend otherwise. - SWEEP interaction. Tile shapes become const generics on kernel entries; upstream const-generic kernel entries (#316) may let SWEEP select monomorphizations instead of rewriting source constants. Out of scope here; file separately when phase 3 hits it.
- TMEM lane-ownership ergonomics.
tcgen05.ld/stlane mapping pins drains to warps 0–3 of a warpgroup;TmemTile's API must make ownership explicit so misuse is a type error, not a hang.
Acceptance
- Phases 1–4 merged with all existing correctness gates green and profiles within noise of the hand-written kernels
- Register/spill counts unchanged (ptxas gate) for each ported kernel
- flash-attn
tcgen05.rsand gemm reduced to kernel-specific logic only (no raw swizzle math, no hand-threaded phase bits) - One new kernel (phase 5) shipped kittens-first as the end-to-end validation
Activity
feitreim commentedon Jul 26, 2026
Phase 5 complete on
feat/issue-61-kittens-phase1(pushed).Ported half: the backward kernels and both probes moved onto the library, so no raw mbarrier, swizzle, or fragment math remains in flash-attn —
cvt_f32x2_bf16x2andstmatrix_m8n8_x2are not imported bytcgen05.rsat all.tcgen05.rs2963 → 2333 lines. New library surface, all extracted from working kernels:reg::Fragment/value_column,tmem::fragment_tile,ldst::store_fragment_bf16,sync::PhasedSemaphore,shared::tma_load_at. Backward pins ratcheted down (q 62→52, kv 64→60) — the first port in the series where the allocator gave registers back. The port also found ~250 lines of dead Design-A register passes with no call sites.Kittens-first half (the acceptance criterion):
flash_backward_q_pipelinedandflash_backward_kv_pipelinedwarp-specialize the backward pair over unchanged Design-B math — the last synchronous tcgen05 kernels in the repo, which ran four block syncs per key tile with the tensor cores idle through every register pass.dq/dk/dvare bit-identical to the kernels they replace at all three gate shapes — a pure scheduling change must be, soassert_identicalgates it rather than a tolerance. On risk 1 ("register allocation through abstraction"): kernel A costs one register over the synchronous kernel it replaces (52 → 53) for three warp roles, two S/dP buffers and six barrier sets. Trainer switched to both; all 13run.sh modelgates green with the MoE overfit at its recorded 2.949433 → 0.000060.Full record in SPEC 7e17, including the two non-obvious design points (the streamed operand is read twice a stage apart, so the ring's free-barrier hangs off the gradient commit; and a
SemaphoreRing's parity is a visit count, so kernel B's runtime loop start drives every index offstep).Phase-5 leftovers and the follow-ups this generated are tracked in #63.
Merge pull request #64 from feitreim/feat/issue-61-kittens-phase1