Skip to content

Block-scope reductions: the fold four warps need, and the fp32 Element under it #3

Closed

Description

@feitreim

Redesigned 2026-07-27. The original ask — parameterize every op over a Scope trait — is preserved at the bottom. It is not what this issue delivers any more, and the reasons are below.

Why the original shape was retired

1. Its own rationale has expired. The issue argued: "Rust has no partial specialization, so this is a trait plus a mechanical sweep of every signature — cheap at 1851 lines, expensive after #5, #6, and #7 land another few hundred functions. Do it before the op surface widens, not after."

#5, #6, #7, #31 and #38 have all landed. The op surface roughly tripled. The window the issue was written to catch is closed, so a mechanical sweep is now the most expensive it has ever been — and it would still not produce the one thing an actual kernel is waiting for.

2. A Scope trait cannot supply what the only real consumer needs. groupnorm_tile in examples/src/layernorm.rs wants block_reduce_sum. RegTile::tile_sum (#6) is warp scope: it folds one warp's band across its 32 lanes via shuffle_xor and stops. A [128, COLUMNS] tile is four warps' bands, so the warps must agree — and warps cannot shuffle to each other. That needs a shared staging buffer and a block barrier: storage, which { WARPS, THREADS, rank(), sync() } does not have and cannot have. Scope-parameterizing the whole library would leave groupnorm_tile exactly as blocked as it is today.

3. #13 changed the shape of the answer. The open design question used to be whether a block reduction takes a raw scratch pointer or something typed. SharedVec<F32, WARPS> is now a type a signature can name, and set(warp, partial) / get(w) is precisely the access a fold over four partials wants — the vector's scalar accessors are per element rather than per packed word specifically so two lanes writing neighbours cannot clobber each other.

What this issue delivers now

1. impl Element for F32 — a prerequisite that fell through a crack

#2 closed on 2026-07-26 without it. Both layernorm.rs's doc and #13's report refer to "#2's impl Element for F32" as though it exists; it does not, and src/shared.rs still has exactly one impl Element, for Bf16. So SharedVec<F32, 4> is not constructible today and this issue is blocked on it.

It is small — Unpacked = [f32; 1], BYTES = 4, PER_WORD = 1, pack is to_bits, unpack is from_bits, read/write are plain loads. Note PER_WORD is 1 here where bf16's is 2; check that nothing assumes 2, and that SharedVec's BOX_OK assert (bytes a multiple of 16) still admits the sizes wanted — SharedVec<F32, 4> is 16 bytes exactly, which is the minimum legal box and worth an explicit test rather than luck.

2. sync::block_reduce_sum and the collective under it

pub unsafe fn block_reduce<Op: BinaryOp, const WARPS: usize>(
    scratch: SharedVec<F32, WARPS>, value: f32,
) -> f32;
pub unsafe fn block_reduce_sum<const WARPS: usize>(
    scratch: SharedVec<F32, WARPS>, value: f32,
) -> f32;

Reuse reg.rs's BinaryOp — sum should be block_reduce::<Add, _>, not a hand-written twin, for the same reason scale_rows became a row_map_assign wrapper in #31.

Semantics to pin down and document as safety conditions, because every one of them is a way to get a wrong answer silently:

  • Every thread of the block calls it, with the same scratch.
  • The input is warp-uniform (it is a tile_sum result). State whether you require that or fold across lanes first — and say which, because a caller passing a non-uniform value gets a plausible wrong number, not a crash.
  • The result is block-uniform — every thread returns the same value. groupnorm_tile uses it as a scalar operand immediately after.
  • It is called twice in a row on the same scratch (mean, then variance). Reuse must be safe without the caller inserting a barrier, or the doc must say a barrier is owed. Get this wrong and the second call reads the first's partials.

3. Close the example

groupnorm_tile leaves its feature gate, layernorm.rs's WANT block and the raw partials pointer go, and examples/README.md's status table and per-kernel error list update. This is currently the only error left across all four example kernels — modal run modal_app.py::gaps prints exactly one, and closing it should print none.

Verify with a real device build, not just cargo check: cargo oxide build kittens-examples --arch sm_100a --features layernorm. A post-monomorphization const { assert!(..) } fires at codegen and is invisible to a type-check — SharedVec's box asserts are exactly that kind.

4. A device case

The reduction is genuinely cross-warp, so unlike #7's masking it is not re-testing something the suite already covers four ways. Follow the harness discipline: seed a pattern that identifies a position exactly, dump by thread coordinate, host applies the map, kernel never encodes the answer. A case where each warp's partial is distinct and the fold is order-sensitive would catch a warp reading its own slot instead of the block's.

On Scope itself

Do not do the sweep as part of this. If WARPS wants to come from somewhere other than a bare const parameter, argue for the smallest thing that serves this reduction and say what a later sweep would still owe. Two things to weigh:

If after building this you think a Scope trait is still worth having, file it fresh with the evidence this work produced. If you think it is not, say so — that is a legitimate outcome and better recorded than left open.

Acceptance

  • modal run modal_app.py::gaps prints no errors for either feature.
  • modal run modal_app.py::build green (it now includes cargo doc --features host with -D warnings).
  • Device suite passes with the new case; ::examples still exact for gemm and within tolerance for softmax.
  • CI green — tier 1 runs clippy -D warnings and cargo metadata --locked on all three crates.

Depends on nothing open. Related: #6 (tile_sum, the warp half), #13 (SharedVec, the storage), #27 (implicit lane), #2 (closed, but see §1).


Original issue text, as filed

ThunderKittens templates every memory, register, shared, and MMA op over warp count via group<N>, with warp = group<1> and warpgroup = group<4> as aliases. One implementation serves every collective width.

We hardcode scope per function and encode it in the index math rather than the type:

  • ldst.rs — warp scope
  • mma.rs — warpgroup scope
  • pipeline.rs — block scope
  • sync.rs — mixed, with the arriving count passed as a runtime u32

Nothing in a signature says which, so a caller finds out by reading the body.

Shape

trait Scope {
    const WARPS: usize;
    const THREADS: usize = Self::WARPS * 32;
    fn rank() -> u32;   // lane index within the scope
    fn sync();
}
struct Warp;       // WARPS = 1
struct Warpgroup;  // WARPS = 4
struct Block<const N: usize>;

Ops take S: Scope and derive their lane/warp arithmetic from it.

Why now. Rust has no partial specialization, so this is a trait plus a mechanical sweep of every signature — cheap at 1851 lines, expensive after #5, #6, and #7 land another few hundred functions. Do it before the op surface widens, not after.

Depends on #1 (the sweep should happen once, over the final RegTile signature).

Activity

  1. added
    enhancement
    area:types
    on Jul 26, 2026
  2. feitreim commented on Jul 27, 2026

    @feitreim
    OwnerAuthor

    Acceptance: update examples/ as part of closing this.

    layernorm wants a block-scope reduction for its whole-tile statistic — a tile owned by four warps needs the warps to agree.

    The examples crate (#18) exists so that "done" is checkable in the terms a kernel author cares about, rather than as a claim about a primitive nobody has tried to hold. Concretely, on closing this:

    • Delete any workaround or GAP fence in examples/src/ that this issue removes the need for, and replace it with the real API.
    • If a kernel becomes fully unblocked, move it from aspirational to compiles: flip its header, take it out of its feature gate, and confirm modal run modal_app.py::build builds it for sm_100a.
    • Update the status table and the blocked-on lists in examples/README.md.

    If the example still does not compile afterwards, that is a finding worth writing down — say what is still missing rather than leaving the README stale.

  3. feitreim commented on Jul 27, 2026

    @feitreim
    OwnerAuthor

    This issue as filed cannot do the job it was deferred for, found while implementing #6.

    #3 was deferred to be decided as part of #6, on the theory that reductions would be its first real consumer — layernorm wants a whole-tile statistic across a tile owned by four warps.

    They are its first real consumer, and they show the proposed Scope is not sufficient:

    trait Scope { const WARPS; const THREADS; fn rank() -> u32; fn sync(); }

    A block-scope reduction needs storage for the per-warp partials — each warp folds its own rows, writes one value to shared memory, syncs, and one warp folds the four. WARPS/THREADS/rank()/sync() supplies none of that, and the library cannot allocate it: the shared-memory plan belongs to the kernel, which is why every SharedTile here is constructed from a caller-supplied base pointer.

    So a block-scope reduction's signature is either:

    1. take a scratch pointer — which is not scope parameterization, it is a scratch parameter wearing a Scope type; or
    2. take a SharedVec — which is Shared vectors, and ops on shared tiles #13, and does not exist.

    #3 and #13 have to be sequenced together. Option 2 is the right shape, and it means #13 is a prerequisite for the part of #3 that anyone actually needs, rather than an unrelated item further down the list. Filed order has them the wrong way round.

    #6 therefore shipped warp-scope reductions only (option (b) of the two it was offered) and recorded the finding in examples/README.md and layernorm.rs rather than inventing an allocation strategy.

    Worth noting what this does not undermine: the argument for doing #3 before the op surface widens still holds, and has if anything got stronger — #5, #6, #21, #25 and #30 have all landed since it was filed. It is the design that needs revisiting, not the timing.

  4. changed the title [-]Scope parameterization: one implementation per op, not per warp count[/-] [+]Block-scope reductions: the fold four warps need, and the fp32 Element under it[/+] on Jul 28, 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

    area:typesenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions