Skip to content

The shared plan is one walk now, and the two ends of it cannot share a pointer add (#125) - #137

Merged
feitreim merged 1 commit into
mainfrom
shared-plan-cursor
Jul 29, 2026
Merged

feitreim merged 1 commit into
mainfrom
shared-plan-cursor

Conversation

@feitreim

@feitreim feitreim commented Jul 29, 2026 •

Copy link
Copy Markdown
Owner

Closes #125. GAPS.md §7.4's first bullet is rewritten from missing to
landed, with one half left standing, and #125 comes off the work-order table.

Every claim below says how it was established. A list of things I could not
establish is at the end.

What landed

src/plan.rs (+527 lines) is SharedPlan: a Copy cursor over the launch's
dynamic shared memory. It starts at the base, hands out one typed handle per
reservation, aligns each to what that handle's type requires, and accumulates
the total as it goes.

struct Shared { a_ring: ARing, b_ring: BRing, load: SemaphoreRing<STAGES>, /* … */ plan: SharedPlan }

const fn shared(at: SharedPlan) -> Shared {
    let (a_ring, at)    = at.tile_ring::<Bf16, BLOCK_M, BLOCK_K, Swizzle128B, STAGES>();
    let (b_ring, at)    = at.tile_ring::<Bf16, HALF_N,  BLOCK_K, Swizzle128B, STAGES>();
    let (load, at)      = at.semaphores::<STAGES>();
    let (free, at)      = at.semaphores::<STAGES>();
    let (done, at)      = at.semaphore();
    let (tmem_slot, at) = at.tmem_slot();
    Shared { a_ring, b_ring, load, free, done, tmem_slot, plan: at }
}

const SHARED_BYTES: usize = shared(SharedPlan::sizing()).plan.bytes();   // host
let shared = shared(SharedPlan::attach());                              // device

That is examples/src/gemm.rs. The number the launch declares is the end of
the same walk that produced the pointers
— there is no second expression and
no const { assert!(..) } relating them, because there is nothing to relate.
Same shape in softmax.rs, layernorm.rs and flash_forward.rs.

Alignments the plan owns, and what each one is: 128 for
tile/tile_ring/vec (the TMA's shared destination alignment, and
Swizzle128B::ATOM_BYTES), 8 for semaphore/semaphores/barriers
(align_of::<Barrier>()), 4 for tmem_slot (tcgen05.alloc writes a u32,
and alloc_block's own contract says SharedArray<u32, 1, 4>), 16 for
clc_queue (ClcQueue::ALIGNMENT, the .b128 response).

Safety is stated once. SharedPlan::attach is unsafe — the launch must
declare at least the finished walk's bytes() — and every reservation on it is
safe, because a handle is inert: every operation this crate offers on a
SharedTile, SharedVec or Semaphore is itself unsafe, so a handle carved
off a sizing cursor cannot be dereferenced by safe code.

The four leaks §7.4 named are closed

leak before after
1 DynamicSharedArray::<u8, 128>::get_raw() in every kernel SharedPlan::attach()
2 cuda_device::barrier::Barrier imported purely as a cast target plan.semaphore() / plan.semaphores::<N>()
3 the caller finds, aligns and accounts for alloc_cluster's staging word plan.tmem_slot()
4 an identical const { assert!(offset % ClcQueue::ALIGNMENT == 0) } in both GEMMs plan.clc_queue()

Established by: grep -rn "DynamicSharedArray\|barrier::Barrier\|as \*mut Barrier" examples/src experiments/src returns nothing on this branch, and both
ALIGNMENT blocks and both ring-BYTES asserts are visibly deleted in the
diffs of experiments/src/gemm.rs and gemm_ws.rs.

Also gone: the barrier count spelled 2 * STAGES * 8 in bytes at one end of a
kernel and .add(STAGES) in Barrier units at the other; STAGE_OFFSET in
all three GEMMs (the staging run is a SharedTileRing and the per-warp offset
is SharedTileRing::tile's); scratch_bytes in both experiment GEMMs.

The alignment argument the issue named as the test

layernorm.rs carried this as a comment: "The partials first, because
Tile::BYTES is the only offset in this plan a vector's 128-byte alignment is
promised at; the barrier behind it needs eight."
That is a correctness
argument about ordering, made in prose because nothing else would make it.

Under the cursor it is not one. SharedPlan::vec takes the 128-byte rule
unconditionally — the rule a TMA-touched vector owes — so a vector reserved
behind a barrier is padded rather than misaligned, and the order decides how
many bytes the plan spends and no longer whether the vector is legal. Both
spellings and the 120 bytes between them are asserted in src/plan.rs's tests,
so the fact is a test now rather than a comment. The weaker E::BYTES rule a
get/set-only vector could live with was rejected for exactly this reason: it
would put correctness back on the ordering to save at most 127 bytes.

What did NOT close, and why

A const-generic walk and a value-parameterized total are still two programs.
experiments' rung table calls shared_plan(block_n, block_k, stages) at
runtime, for rungs UNBUILT names and no kernel instantiates. A const fn
over values cannot instantiate SharedTileRing<Bf16, R, C, S, N>, because a
const parameter is not a function argument. That is a language limit
(generic_const_exprs), not a design one.

SharedPlan::reserve(bytes, align) is what it costs: the value form spells the
same reservations in bytes, through the same cursor with the same alignment
rules, and one assert per GEMM joins the two —
shared::<..>(SharedPlan::sizing()).plan.bytes() == shared_plan(..). The three
kernels whose plan parameters are module constants carry neither. This is the
only place in the repo a plan is still written twice, and it is now one
expression where it was three assert blocks.

Established by: reading Rung::shared (experiments/src/gemm.rs:889),
Entry::shared (gemm_ws.rs:1660), and the pre-PR
const _: () = { assert!(shared_plan(128, 64, 2) == 49_224); … } block at
gemm.rs:1020, which asserts eight rungs including ones with no entry point.

The thing that had to be discovered: the two ends want different pointer adds

I wrote reserve with wrapping_add, because a sizing cursor's base has no
provenance and const eval will not let add leave an allocation. cargo test
and cargo clippy --all-targets -- -D warnings are both happy with that.
scripts/modal-run build is not:

error: [rustc_codegen_cuda] Device codegen failed: PTX generation failed:
Translation failed: kittens::SharedPlan::reserve: [core/src/ptr/mut_ptr.rs:470]
Unsupported construct: rustc intrinsic `std::intrinsics::arith_offset` is not
yet supported on the device

So wrapping_add does not compile for the device, add does not evaluate on
the host, and there is no third operation. reserve carries a branch on an
attached flag, which is a literal in both constructors (attach → true,
sizing → false) with every method #[inline(always)], so it is a constant
the optimizer resolves. It is deliberately not self.base.is_null(): a null
check folds only if LLVM can prove get_raw() returns non-null, and it cannot.

The same wall hits ClcQueue::attach, which derives the barrier's address from
the response's. SharedPlan::clc_queue reserves the two objects separately
instead — 16 at 16, then 8 at 8 — which is ClcQueue::BYTES on the nose
(asserted in src/plan.rs) and is a more honest statement of what a queue is.
ClcQueue::attach is unchanged for callers that have a raw base.

Established by: the failing scripts/modal-run build quoted above and the
passing one on the current tree.

Totals: what moved and what did not

Every number the three GEMM envelopes declare is byte-identical. The
staging word going from a charged 8 bytes to its real 4 is absorbed by
ClcQueue's 16-byte alignment in both experiment GEMMs, and by the staging
run's 128-byte alignment in examples/src/gemm.rs.

before after
experiments::gemm::SHARED_BYTES 98 392 98 392
experiments::gemm::STAGED_SHARED_BYTES 114 816 114 816
experiments::gemm::shared_plan, all 8 asserted rungs — unchanged
gemm_ws::SHARED_BYTES / STAGED_SHARED_BYTES / shared_plan(6) 131 176 / 147 584 / 196 744 unchanged
examples::gemm::STAGED_SHARED_BYTES — the launched one 114 816 114 816
examples::gemm::SHARED_BYTES — internal, nothing launches it 98 368 98 364
softmax::SHARED_BYTES 32 800 32 776
layernorm::SHARED_BYTES 33 344 33 288
flash_forward::SHARED_BYTES 147 536 147 532

The last three moved because the old numbers were slack from this repo's first
examples commit (b9c26c3) — Tile::BYTES + 32 for one 8-byte barrier, + 64
for one — and a cursor that aligns each handle to its own type's rule cannot
reproduce a round number nobody had a reason for. All three shrink.

Residency for all three is unchanged, and the driver says so rather than my
arithmetic.
scripts/modal-run examples prints the occupancy census on a
B200:

kernel           threads        shared   blocks/SM   warps/SM
gemm                 128      114816 B     cluster          —
softmax              128       32776 B           6         24
layernorm            128       33288 B           6         24
flash_forward        128      147532 B           1          4

6, 6 and 1 — the same three integers examples/src/layernorm.rs's header and
flash_forward.rs's header record at 32 800, 33 344 and 147 536. Independently:
233 472 / 32 800 and 233 472 / 32 776 are both 7, 233 472 / 33 344 and
233 472 / 33 288 are both 7, and 147 5xx is over the 116 736 half of an SM
either way.

Registers, row by row against main

scripts/modal-run regcount on main at f5e9735 and on this branch, diffed
row by row. 231 register rows and 40 opcode-census rows; 7 register rows
moved, on 6 distinct kernels, and no census row did.

The branch has since been rebased onto #127 (3236455), which merged while
this was measuring, and the whole measurement was redone from CI's own logs:

So every count here is this diff's, established twice.
Post-rebase, examples/src/gemm.rs uses kittens::warp_id() where it used
warp::warp_id(), softmax/layernorm/flash_forward drop the
cuda_device::barrier and cuda_device::shared imports entirely, and
flash_forward's header paragraph naming the shared plan as the last thing
reaching past the library is updated, since it no longer does.

Unchanged: all 184 device-tests kernels. Every counter of the opcode
census for every gemm_* kernel in both crates — mma, ldtm, tma,
stmatrix, ld.sh.v4, st.g.v4, st.g.b32, cvt.bf16x2, bar.sync,
bar.warp, mbar.arrive — so no instruction moved anywhere. The register
ladder ("identical at all 20 rungs, every counter"), #63's timed twins and
#95's occupancy-step gate table are byte-identical. gemm_cg2_staged_x8x4, the
kernel examples/ ships and experiments/ keeps as every A/B's control arm, is
unchanged in both crates (80 and 96); so are gemm_cg2 (166),
gemm_cg2_staged (42), flash_forward (168), softmax_rows (32) and
groupnorm_tile (168 — the one row with zero headroom).

Moved, in both directions, with no spill and no stack frame moving with any
of them:

kernel threads regs CTAs by registers binding term residency
examples/layernorm_rows 128 47 → 50 10 → 9 shared, 6 6, unchanged
experiments/layernorm_rows 128 47 → 50 10 → 9 shared, 6 6, unchanged
experiments/gemm_cg2_staged_x8x4_hot 128 93 → 104 5 → 4 tensor memory, 2 2, unchanged
experiments/gemm_cg2_staged_x8x4_2x 128 106 → 110 4 → 4 tensor memory, 2 unchanged
experiments/gemm_cg2_dry 128 20 → 19 21 → 21 — unchanged
experiments/gemm_ws_staged 192 44 → 43 6 → 6 tensor memory, 1 unchanged
experiments/gemm_ws_staged_x8 192 94 → 90 3 → 3 tensor memory, 1 unchanged

The CTAs by registers column is modal_app.py's _ctas_by_registers
transcribed and run, not cuOccupancyMaxActiveBlocksPerMultiprocessor (#77).
Two rows cross a register-term step and neither crosses a real one, because
another term binds in both: layernorm_rows is 6 CTAs by shared memory at both
33 344 and 33 288 (the census above, measured) and 9 > 6 either way; the two
gemm_cg2_staged_x8x4_* probes are 2 by tensor memory at BLOCK_N = 256
(512 / 256) and 2 by shared memory at 114 816, and 4 > 2 either way. #134's
lesson — one of these steps was crossed silently last round — is why this is a
table and not a sentence.

The mode branch folds, and it is measured

This was the last open question and it is now closed. SharedPlan::reserve's
if self.attached is two side-effect-free pointer values under an if, which
is the shape LLVM if-converts to a select — so a branch that survived would be
a selp in the PTX. modal_app.py's opcode census gains a selp column in
this PR to count them.

gemm_cg2_idle is the decisive row: it calls attach, which is eight
reserve calls (two rings, two semaphore rings, one semaphore, the staging
word, and the queue's two), and then runs a Job whose work does nothing. An
unfolded flag would give it eight selp.

  kernel                    …  bar.warp  mbar.arrive  selp
  gemm_cg2_idle             …         0            0     0
  gemm_cg2_dry              …         0            1     3
  gemm_cg2                  …         0            1     4
  gemm_cg2_staged           …         1            1     8

Zero, at an unchanged 17 registers (identical to post-#127 main). The
selp the other kernels carry are grouped's short-last-group arithmetic and
the epilogue's band selection, none of which gemm_cg2_idle runs. So the branch
this type introduces is gone by codegen, and the six moved register counts are
not it.

What that still does not settle is which of the six they are. The movement
is bidirectional (three down, four up), the instruction counts are identical,
and gemm_cg2_staged_x8x4 and gemm_cg2_staged_x8x4_hot go through the same
attach_staged with only one of them moving — all of which reads as ptxas
allocating rather than as a live value this type added, but I did not chase it
further. The claim being made is "no kernel's residency moved, no instruction
did, and the branch this type introduces is gone by codegen".

Gates, and the commit each ran on

The branch has two trees — pre-rebase b2e8098 (on main at f5e9735) and
post-rebase 292062c (on main at 3236455, #127) — and the distinction
turned out to matter, so every row says which.

gate commit result
scripts/fmt --check a0d44ba pass
cargo clippy --all-targets -- -D warnings a0d44ba pass
cargo test — 98 lib + 1 tests/gaps.rs + 2 doctests a0d44ba pass
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps a0d44ba pass
scripts/modal-run build b2e8098 and 0704bee pass on both
CI build 292062c pass
scripts/modal-run regcount b2e8098 pass, diffed above
CI regcount 292062c pass, byte-identical to b2e8098's in all 231 rows
scripts/modal-run regcount + selp census a0d44ba pass, table above
scripts/modal-run examples b2e8098 and 292062c pass on both
CI device-surface (tier 1, four manifests) 292062c pass

An earlier revision of this description said examples had been run pre-rebase
only. That was true when written and is no longer: it was re-run on the current
head, and the rest of this section is the correction that the two statements
disagreed at all. The rebase took #127's side of four conflicts inside the
attach functions this PR rewrites
, and a mis-threaded lane compiles and
computes wrong numbers, so build and regcount were never enough on their own.

examples correctness on a B200 at 292062c: gemm element-exact at
512×256×256 and
4096×4096×256; softmax and layernorm pass; experiments' gemm exact on
every scheduler, every epilogue rung and every tile rung (49 224, 73 816,
98 408, 32 824, 65 592, 65 608, 98 392, 114 816 B — every pre-PR number);
gemm_ws exact at 147 584 and 196 744 B. Both GEMMs check C element-exact,
which is what catches a moved offset where a total-only assert would not.

src/plan.rs also carries the five plans as host tests against their literals —
98 364 / 114 816 / 98 392 / 131 176 / 147 584 / 32 776 / 33 288 / 32 792 /
147 532 — so a change to reserve's alignment rules fires in cargo test
before it reaches a B200.

What I could not establish

  • Why layernorm_rows gains 3 registers. Its plan offsets are
    byte-identical to before (tile at 0, gamma at 32 768, beta at 33 024,
    barrier at 33 280) and it is not in the opcode census, which covers gemm_*
    only. I did not read its PTX. The residency claim above does not depend on
    this.
  • Whether the attached flag folds. Settled — see The mode branch
    folds
    above. It was an argument on the first pass and is a selp count now.
    The guaranteed-fold alternative, a const ATTACHED: bool on SharedPlan
    that would travel into every kernel's own plan struct, is therefore not
    needed.
  • device-tests is untouched, deliberately. Its ~25 get_raw() sites are
    raw probes — main.rs:1869 says outright that one of them uses intrinsics
    "rather than kittens::pipeline::ClcQueue" — and migrating them would put 184
    kernels' register counts at risk for no statement gained. Not attempted, not
    claimed.
  • Every register-side entry point takes a lane the library gives no way to obtain #127's call sites were never edited by this work. No lane_id(),
    warp_id() or proxy-fence call site was modified while Every register-side entry point takes a lane the library gives no way to obtain #127 was in flight,
    including where they sat two lines from an edit. The rebase then took Every register-side entry point takes a lane the library gives no way to obtain #127's
    side of all four conflicts, so examples/src/gemm.rs now calls
    kittens::warp_id().
  • Why gemm_cg2_staged_x8x4_hot gains 11 registers, the largest of the six
    moves. Its opcode counts including selp are identical to
    gemm_cg2_staged_x8x4's, which did not move, and both go through the same
    attach_staged. I did not diff their PTX. Its residency is 2 either way and
    the claim above does not depend on this.

@feitreim
feitreim force-pushed the shared-plan-cursor branch 2 times, most recently from 0704bee to 292062c Compare July 29, 2026 19:22
…a pointer add (#125)

`kittens::plan::SharedPlan` is a `Copy` cursor over the launch's dynamic
shared memory: it starts at the base, hands out one typed handle per
reservation, aligns each to what that handle's own type requires, and its
`bytes()` is the total the launch declares. All five kernels are on it.

Four of the five now compute their plan **once**. `SHARED_BYTES` is
`shared(SharedPlan::sizing()).plan.bytes()` of the same walk that produces the
pointers, so there is no second expression and no `const { assert!(..) }`
relating them. `experiments`' rung table is the exception and it is a language
limit, not a design one — a `const fn` over values cannot instantiate a
const-generic `SharedTileRing`, and that table answers for rungs no kernel
implements. It spells its reservations through `SharedPlan::reserve` instead,
and one assert per GEMM joins the two.

All four leaks GAPS.md §7.4 named are closed: `DynamicSharedArray::get_raw` is
`SharedPlan::attach`, the `*mut Barrier` cast is `semaphore`/`semaphores`,
`alloc_cluster`'s staging word is `tmem_slot`, and `ClcQueue::ALIGNMENT`'s
proof obligation is `clc_queue`. No kernel crate imports `DynamicSharedArray`
or `cuda_device::barrier::Barrier` any more.

`layernorm`'s ordering argument — "the partials first, because `Tile::BYTES`
is the only offset in this plan a vector's 128-byte alignment is promised at" —
is discharged by the type: `SharedPlan::vec` aligns to 128 whatever precedes
it, so the other order is legal and merely costs 120 bytes. Both spellings and
the difference between them are asserted in `src/plan.rs`'s tests.

The device and the host want different pointer arithmetic and neither
operation serves both: `rustc_codegen_cuda` rejects `arith_offset`, so
`wrapping_add` does not compile for the device, and const eval will not let
`add` leave an allocation, which a sizing cursor does not have. `reserve`
carries the branch, on a flag that is a literal in both constructors.

Totals: every number the three GEMM envelopes declare is byte-identical.
`softmax` loses 24 bytes, `layernorm` 56 and `flash_forward` 4 — slack a
cursor cannot reproduce — and the driver reports the same blocks/SM for all
three.

The census gains a `selp` column, and it is load-bearing rather than
decoration: `reserve`'s mode branch is two side-effect-free pointer values
under an `if`, which LLVM if-converts to a select, so a branch that survived
would be a `selp`. `gemm_cg2_idle` runs the whole eight-reservation walk and
then does nothing; it carries zero, at an unchanged 17 registers. The claim
that the flag folds is therefore measured rather than argued.
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.

A kernel's shared plan is entirely open-coded, in bytes, twice per kernel

1 participant