Skip to content

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

Closed

Description

@feitreim

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 stmatrix

Phases

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 -v register/spill regression check to bench-util so every later phase has an objective gate
  • Phase 1 — shared.rs + global.rs + sync.rs: SharedTile/swizzle, TMA GlobalLayout, Semaphore. Rewrite the loader warp of flash_forward_pipelined on it. Pure refactor.
  • Phase 2 — reg.rs: RegTile/RegVec, maps + reductions (incl. ex2.approx); port softmax_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 from flash_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 by tcgen05.st) as a dedicated correction warpgroup

Risks / open questions

  1. Register allocation through abstraction. Tiles must fully scalarize: #[inline(always)] everywhere, compile-time-unrolled fragment iteration (const-generic recursion or macro unrolls — plain while loops may not unroll). Phase 0's ptxas gate is the enforcement mechanism.
  2. 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); ship exp2/log2 via ex2.approx + the existing software log2.
  3. Swizzle generality. v0.2.1 code exploits the 64-wide-subtile coincidence (swizzle phase == row). The Swizzle type must encode the general SWIZZLE_128B pattern or honestly restrict supported widths — decide in phase 1.
  4. No named barriers upstream — warpgroup handoffs stay mbarrier phase-parity spins; sync.rs should make that idiom first-class rather than pretend otherwise.
  5. 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.
  6. TMEM lane-ownership ergonomics. tcgen05.ld/st lane 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.rs and 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

  1. feitreim commented on Jul 26, 2026

    @feitreim
    OwnerAuthor

    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_bf16x2 and stmatrix_m8n8_x2 are not imported by tcgen05.rs at all. tcgen05.rs 2963 → 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_pipelined and flash_backward_kv_pipelined warp-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.

    sync pipelined
    backward q 2.370 ms / 277.3 TF 2.135 ms / 307.8 TF −9.9%
    backward kv 3.171 ms / 276.3 TF 2.664 ms / 328.8 TF −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. 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 13 run.sh model gates 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 off step).

    Phase-5 leftovers and the follow-ups this generated are tracked in #63.

  2. added a commit that references this issue on Jul 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions