Repository navigation
The shared plan is one walk now, and the two ends of it cannot share a pointer add (#125) - #137
Merged
Merged
Conversation
feitreim
force-pushed
the
shared-plan-cursor
branch
2 times, most recently
from
July 29, 2026 19:22
0704bee to
292062c
Compare
…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.
feitreim
force-pushed
the
shared-plan-cursor
branch
from
July 29, 2026 19:37
292062c to
a0d44ba
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #125.
GAPS.md§7.4's first bullet is rewritten from missing tolanded, 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) isSharedPlan: aCopycursor over the launch'sdynamic 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.
That is
examples/src/gemm.rs. The number the launch declares is the end ofthe 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.rsandflash_forward.rs.Alignments the plan owns, and what each one is: 128 for
tile/tile_ring/vec(the TMA's shared destination alignment, andSwizzle128B::ATOM_BYTES), 8 forsemaphore/semaphores/barriers(
align_of::<Barrier>()), 4 fortmem_slot(tcgen05.allocwrites au32,and
alloc_block's own contract saysSharedArray<u32, 1, 4>), 16 forclc_queue(ClcQueue::ALIGNMENT, the.b128response).Safety is stated once.
SharedPlan::attachisunsafe— the launch mustdeclare at least the finished walk's
bytes()— and every reservation on it issafe, because a handle is inert: every operation this crate offers on a
SharedTile,SharedVecorSemaphoreis itselfunsafe, so a handle carvedoff a sizing cursor cannot be dereferenced by safe code.
The four leaks §7.4 named are closed
DynamicSharedArray::<u8, 128>::get_raw()in every kernelSharedPlan::attach()cuda_device::barrier::Barrierimported purely as a cast targetplan.semaphore()/plan.semaphores::<N>()alloc_cluster's staging wordplan.tmem_slot()const { assert!(offset % ClcQueue::ALIGNMENT == 0) }in both GEMMsplan.clc_queue()Established by:
grep -rn "DynamicSharedArray\|barrier::Barrier\|as \*mut Barrier" examples/src experiments/srcreturns nothing on this branch, and bothALIGNMENTblocks and both ring-BYTESasserts are visibly deleted in thediffs of
experiments/src/gemm.rsandgemm_ws.rs.Also gone: the barrier count spelled
2 * STAGES * 8in bytes at one end of akernel and
.add(STAGES)inBarrierunits at the other;STAGE_OFFSETinall three GEMMs (the staging run is a
SharedTileRingand the per-warp offsetis
SharedTileRing::tile's);scratch_bytesin both experiment GEMMs.The alignment argument the issue named as the test
layernorm.rscarried this as a comment: "The partials first, becauseTile::BYTESis the only offset in this plan a vector's 128-byte alignment ispromised 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::vectakes the 128-byte ruleunconditionally — 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::BYTESrule aget/set-only vector could live with was rejected for exactly this reason: itwould 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 callsshared_plan(block_n, block_k, stages)atruntime, for rungs
UNBUILTnames and no kernel instantiates. Aconst fnover values cannot instantiate
SharedTileRing<Bf16, R, C, S, N>, because aconst 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 thesame 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 threekernels 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-PRconst _: () = { assert!(shared_plan(128, 64, 2) == 49_224); … }block atgemm.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
reservewithwrapping_add, because a sizing cursor's base has noprovenance and const eval will not let
addleave an allocation.cargo testand
cargo clippy --all-targets -- -D warningsare both happy with that.scripts/modal-run buildis not:So
wrapping_adddoes not compile for the device,adddoes not evaluate onthe host, and there is no third operation.
reservecarries a branch on anattachedflag, which is a literal in both constructors (attach→true,sizing→false) with every method#[inline(always)], so it is a constantthe optimizer resolves. It is deliberately not
self.base.is_null(): a nullcheck 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 fromthe response's.
SharedPlan::clc_queuereserves the two objects separatelyinstead — 16 at 16, then 8 at 8 — which is
ClcQueue::BYTESon the nose(asserted in
src/plan.rs) and is a more honest statement of what a queue is.ClcQueue::attachis unchanged for callers that have a raw base.Established by: the failing
scripts/modal-run buildquoted above and thepassing 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 stagingrun's 128-byte alignment in
examples/src/gemm.rs.experiments::gemm::SHARED_BYTESexperiments::gemm::STAGED_SHARED_BYTESexperiments::gemm::shared_plan, all 8 asserted rungsgemm_ws::SHARED_BYTES/STAGED_SHARED_BYTES/shared_plan(6)examples::gemm::STAGED_SHARED_BYTES— the launched oneexamples::gemm::SHARED_BYTES— internal, nothing launches itsoftmax::SHARED_BYTESlayernorm::SHARED_BYTESflash_forward::SHARED_BYTESThe last three moved because the old numbers were slack from this repo's first
examples commit (
b9c26c3) —Tile::BYTES + 32for one 8-byte barrier,+ 64for 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 examplesprints the occupancy census on aB200:
6, 6 and 1 — the same three integers
examples/src/layernorm.rs's header andflash_forward.rs's header record at 32 800, 33 344 and 147 536. Independently:233 472 / 32 800and233 472 / 32 776are both 7,233 472 / 33 344and233 472 / 33 288are both 7, and 147 5xx is over the 116 736 half of an SMeither way.
Registers, row by row against
mainscripts/modal-run regcountonmainatf5e9735and on this branch, diffedrow 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 whilethis was measuring, and the whole measurement was redone from CI's own logs:
regcountonmain(run30482936614) is byte-identical tof5e9735's in all 231 register rows, so Every register-side entry point takes a lane the library gives no way to obtain #127 moved nothing and thepre-rebase baseline was already the right one.
regcountafter the rebase (run30484125322) is byte-identicalto my pre-rebase run in all 231 rows, so the rebase moved nothing either.
mainagainst the rebased branch reproduces exactly the seven rowsin the table below and no others.
So every count here is this diff's, established twice.
Post-rebase,
examples/src/gemm.rsuseskittens::warp_id()where it usedwarp::warp_id(),softmax/layernorm/flash_forwarddrop thecuda_device::barrierandcuda_device::sharedimports entirely, andflash_forward's header paragraph naming the shared plan as the last thingreaching past the library is updated, since it no longer does.
Unchanged: all 184
device-testskernels. Every counter of the opcodecensus 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 registerladder ("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, thekernel
examples/ships andexperiments/keeps as every A/B's control arm, isunchanged in both crates (80 and 96); so are
gemm_cg2(166),gemm_cg2_staged(42),flash_forward(168),softmax_rows(32) andgroupnorm_tile(168 — the one row with zero headroom).Moved, in both directions, with no spill and no stack frame moving with any
of them:
examples/layernorm_rowsexperiments/layernorm_rowsexperiments/gemm_cg2_staged_x8x4_hotexperiments/gemm_cg2_staged_x8x4_2xexperiments/gemm_cg2_dryexperiments/gemm_ws_stagedexperiments/gemm_ws_staged_x8The
CTAs by registerscolumn ismodal_app.py's_ctas_by_registerstranscribed 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_rowsis 6 CTAs by shared memory at both33 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 atBLOCK_N = 256(
512 / 256) and 2 by shared memory at 114 816, and 4 > 2 either way. #134'slesson — 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'sif self.attachedis two side-effect-free pointer values under anif, whichis the shape LLVM if-converts to a
select— so a branch that survived would bea
selpin the PTX.modal_app.py's opcode census gains aselpcolumn inthis PR to count them.
gemm_cg2_idleis the decisive row: it callsattach, which is eightreservecalls (two rings, two semaphore rings, one semaphore, the stagingword, and the queue's two), and then runs a
Jobwhoseworkdoes nothing. Anunfolded flag would give it eight
selp.Zero, at an unchanged 17 registers (identical to post-#127
main). Theselpthe other kernels carry aregrouped's short-last-group arithmetic andthe epilogue's band selection, none of which
gemm_cg2_idleruns. So the branchthis 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_x8x4andgemm_cg2_staged_x8x4_hotgo through the sameattach_stagedwith only one of them moving — all of which reads as ptxasallocating 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(onmainatf5e9735) andpost-rebase
292062c(onmainat3236455, #127) — and the distinctionturned out to matter, so every row says which.
scripts/fmt --checka0d44bacargo clippy --all-targets -- -D warningsa0d44bacargo test— 98 lib + 1tests/gaps.rs+ 2 doctestsa0d44baRUSTDOCFLAGS="-D warnings" cargo doc --no-depsa0d44bascripts/modal-run buildb2e8098and0704beebuild292062cscripts/modal-run regcountb2e8098regcount292062cb2e8098's in all 231 rowsscripts/modal-run regcount+selpcensusa0d44bascripts/modal-run examplesb2e8098and292062cdevice-surface(tier 1, four manifests)292062cAn earlier revision of this description said
exampleshad been run pre-rebaseonly. 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
attachfunctions this PR rewrites, and a mis-threaded lane compiles andcomputes wrong numbers, so
buildandregcountwere never enough on their own.examplescorrectness on a B200 at292062c:gemmelement-exact at512×256×256 and
4096×4096×256;
softmaxandlayernormpass;experiments'gemmexact onevery 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_wsexact at 147 584 and 196 744 B. Both GEMMs checkCelement-exact,which is what catches a moved offset where a total-only assert would not.
src/plan.rsalso 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 incargo testbefore it reaches a B200.
What I could not establish
layernorm_rowsgains 3 registers. Its plan offsets arebyte-identical to before (tile at 0,
gammaat 32 768,betaat 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 theSettled — see The mode branchattachedflag folds.folds above. It was an argument on the first pass and is a
selpcount now.The guaranteed-fold alternative, a
const ATTACHED: boolonSharedPlanthat would travel into every kernel's own plan struct, is therefore not
needed.
device-testsis untouched, deliberately. Its ~25get_raw()sites areraw probes —
main.rs:1869says outright that one of them uses intrinsics"rather than
kittens::pipeline::ClcQueue" — and migrating them would put 184kernels' register counts at risk for no statement gained. Not attempted, not
claimed.
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.rsnow callskittens::warp_id().gemm_cg2_staged_x8x4_hotgains 11 registers, the largest of the sixmoves. Its opcode counts including
selpare identical togemm_cg2_staged_x8x4's, which did not move, and both go through the sameattach_staged. I did not diff their PTX. Its residency is 2 either way andthe claim above does not depend on this.