Skip to content

TMA store path, and softmax runs - #41

Merged
feitreim merged 3 commits into
mainfrom
issue-9-tma-store
Jul 27, 2026
Merged

feitreim merged 3 commits into
mainfrom
issue-9-tma-store

Conversation

@feitreim

Copy link
Copy Markdown
Owner

Four TMA load paths and zero stores; now two stores, the commit/wait surface, and the first aspirational example to go all the way to runs.

The API

impl SharedTile<E, R, C, S> {
    unsafe fn tma_store(self, map: *const TmaDescriptor, row: i32, plane: i32);
    unsafe fn tma_store_2d(self, map: *const TmaDescriptor, leading: i32, minor: i32);
}
fn tma_store_commit();
fn tma_store_wait<const N: u32>();
fn tma_store_wait_read<const N: u32>();

The stores mirror tma_load / tma_load_2d box for box: one cp.async.bulk.tensor.*.s2g per stacked subtile, leading coordinate lifted by SUBTILE_COLS per stack level, same coordinate order. The box shape is shared with the load path — GlobalLayout::tensor_map::<Tile>() reads it off the tile, so one map feeds both directions and the device test uses the same map type for the source and one of the destinations. Plain stores only: reduction stores stay tracked separately, as the issue asked, and the note below says what I learned about that question.

The completion model, and why it is not a Semaphore

A TMA load's destination is shared memory, where an mbarrier can live and count arriving bytes. A bulk store's destination is global memory, where none can. There is nowhere for the hardware to signal, so a store completes by counting per-thread groups: everything issued since the last tma_store_commit becomes the youngest group, and a wait names how many groups may still be outstanding. No barrier, no transaction bytes, no expect_tx.

I did not build anything Semaphore-shaped over that, because the obligations it leaves the caller are real and a symmetric-looking API would hide them. Both are in the # Safety section of tma_store:

  • The tile must stay live and unwritten until the issuing thread waits on its group. Nothing else republishes it — not dropping the handle, not sync_threads, not the kernel ending.
  • A tile filled through the generic proxy needs fence.proxy.async.shared::cta first. The TMA engine reads through the async proxy. This is the same obligation ldst::store_fragment already documents for an MMA reading the tile, stated the same way. A tile that arrived by tma_load needs no fence: async proxy on both sides, ordered by the load's own barrier. (layernorm was missing this fence; it now has it.)

wait_group vs wait_group_read

Both are exposed, because they answer different questions and a kernel needs both at different points:

  • tma_store_wait::<N> — the older groups are complete: the bytes are in global memory and visible to anything that reads them there. This is what a kernel owes its caller, and ::<0> is the last thing a kernel that wrote a result does. Softmax and layernorm use this form.
  • tma_store_wait_read::<N> — the older groups have finished reading their source. The shared tile is free to overwrite; the bytes may still be in flight. Cheaper, and the whole point of the distinction: a pipelined epilogue that stores stage i and immediately refills that buffer for stage i + 1 needs only this, and blocking on global visibility to recycle a buffer serializes the overlap the pipeline exists for. That is exactly lcsf and the rest of the prototype layer #15's lcsf motivation, and the doc says it is never a kernel's last wait — a result read out of shared memory has not arrived anywhere.

N is a const parameter in both because the group count is an instruction immediate.

What the device test proves

Three cases, 17 of 17 on a B200 (was 14/14; the existing 14 are untouched and still pass).

Each stages position identities, TMAs them in through the already-verified load path, and TMAs them straight back out to two fresh global buffers under one committed group. The kernel computes nothing and encodes no expected answer — the host expects the staging buffer it wrote.

  • packed destination — a 3-D panel map, the form softmax and layernorm actually end with.
  • pitched destination — a rank-2 GlobalLayout::strided whose rows are twice as far apart as they are wide, gaps filled with a word cell_bits cannot produce. Copied from Generalize the global layout beyond PanelMap #8's 2d tensor map case and for its reason: a store that inherited the source's stride, or the row extent's, reports padding at a position rather than a plausible neighbouring element.
case what only it can fail
tma store round trip box geometry and both destination strides
tma store round trip wide the store's share of the subtile walk — the second box has to leave with its leading coordinate lifted by 64
tma store early recycle that wait_read means what the API says: the tile is overwritten with poison between tma_store_wait_read::<0>() and tma_store_wait::<0>(), so if the read wait were a no-op both destinations come back full of it

regcount: the store kernels are 4 and 8 registers, no spills, and no existing kernel moved.

softmax: promoted to runs, not just compiles

Its blocked-on list was #9 and nothing else, and that held — no other gap turned up. Out of its feature gate, into the default build, sm_100a device build confirmed, and it has a launcher and a CPU reference now:

kernel          status              threads        shared
gemm            runs                    128        73792 B
softmax         runs                    128        32800 B

pass  gemm              512x256x256 exact
pass  softmax           2x256x128 rows normalized, worst relative error 1.97e-3

A softmax has an exp2 and a divide in it, so the GEMM's == is not available and claiming it would be the wrong kind of rigour. The strength comes from the input instead: each row's 128 values are a stride-11 permutation of the multiples of 1/8 below 16 (exact in bf16), so each row's 128 outputs are distinct and the closest pair is 9% apart against a 2⁻⁸ tolerance — forty times the noise floor. A swapped column, a swapped row, a wrong plane, or a row normalized against another row's sum all fail loudly. Two planes and two row-blocks, so blockIdx.x and blockIdx.y are both on trial. The observed 1.97e-3 is half a bf16 ulp, i.e. correctly-rounded output, with 2x headroom to the tolerance.

layernorm gets the real ending too and stays aspirational on #3/#13/#22.

What the plan got wrong, and two findings

  • Nothing in the plan was wrong. Every upstream fact held: the s2g intrinsics lower for sm_100a, the commit/wait surface is there, the box shape is shared with the load path, and reduction stores are genuinely absent.
  • The reduction-store question now has an obvious answer, and it is "upstream". cp.reduce.async.bulk.tensor is absent in every form — no rank, no op, and no prefetch either — while the plain s2g family is complete at all five ranks and lowered without a workaround. That is a hole in cuda-oxide's generated catalog rather than something specific to what this crate wants, and a local ptx_asm! would be reimplementing a 15-function family that the generator should be emitting. stmatrix set the local-intrinsic precedent because it was one broken declaration; this is not that. Worth a separate issue, and I have not written store_add_async here.
  • softmax is the second kernel this library can run, which makes the examples crate's promotion ladder do the thing it was built for: the claim that TMA store path #9 is finished is now checkable as a number rather than as a compile.

Verified

  • modal run modal_app.py::build — clippy on all three crates, host tests, real cargo oxide build --arch sm_100a for both kernel crates. Clean.
  • modal run modal_app.py — 17 of 17 on a B200.
  • modal run modal_app.py::examples — gemm exact, softmax within 2e-3, on a B200.
  • modal run modal_app.py::regcount — no regression anywhere.
  • cargo fmt --check clean in all three crates; cargo clippy --all-targets clean (the two kernel crates only typecheck where cuda.h is, so theirs ran on the Modal box).

Closes #9

feitreim added 3 commits July 27, 2026 19:19
`SharedTile::tma_store` / `tma_store_2d` walk the same per-subtile boxes
`tma_load` / `tma_load_2d` do, with the leading coordinate lifted by
SUBTILE_COLS per stack level, so a map built for a tile feeds both directions
without restating a shape.

Completion is deliberately not Semaphore-shaped. A load's destination is
shared memory, where an mbarrier can live and count arriving bytes; a store's
is global memory, where none can. So a bulk store completes by counting
per-thread groups — `tma_store_commit`, then `tma_store_wait::<N>` or
`tma_store_wait_read::<N>` — with no barrier and no byte accounting, and the
docs state what that leaves the caller owing: the tile must stay live and
unwritten until the group is waited on, and a tile filled through the generic
proxy needs a `fence.proxy.async.shared::cta` first, the same obligation
`ldst::store_fragment` documents in the opposite direction.

The two waits mean different things and both are exposed. `wait` is complete —
the bytes are in global memory — and is what a kernel owes anything that reads
its result. `wait_read` is only "the engine has finished reading the tile",
which is all a pipelined epilogue needs to recycle its buffer (#15's `lcsf`),
and is never a kernel's last wait.

`N` is a const parameter in both: the group count is an instruction immediate.
A round trip against the load path this harness already pinned to silicon:
stage position identities, TMA them in, TMA them straight back out, expect the
staging buffer. The kernel applies no map of its own, so a failure is a wrong
coordinate, a wrong subtile stride or a wrong destination stride.

Two destinations per case, because a kernel writes through two forms. The
packed 3-D panel map is what `softmax` and `layernorm` end with. The pitched
rank-2 map spaces its rows twice as far apart as they are wide and fills the
gaps with a word `cell_bits` cannot produce — #8's `2d tensor map` case made
that choice and it is the right one here too: a store that inherited the
source's stride reports *padding* at a position rather than a plausible
neighbour.

The wide case is the store's share of the subtile walk. The recycle case is a
different claim rather than a repeat: it overwrites the tile between
`tma_store_wait_read::<0>()` and `tma_store_wait::<0>()`, so if the read wait
did not mean what the API says, both destinations come back full of poison.

Costs nothing: 4 registers, no spills.
#9 was softmax's last gap, so it goes straight past *compiles* to **runs**:
out of its feature gate, into the default build, with a launcher and a CPU
reference like the GEMM's. 2x256 rows over two planes, exercising blockIdx.x
and blockIdx.y both. Worst observed relative error 1.97e-3, against a 2^-8
tolerance.

What that check can claim is weaker than the GEMM's `==` and deliberately so:
a softmax has an exp2 and a divide in it. The strength comes from the input
instead — each row's 128 values are a stride-11 permutation of the multiples
of 1/8 below 16, so each row's 128 outputs are distinct and the closest pair
is 9% apart, forty times the tolerance. A swapped column, a swapped row, a
wrong plane or a row normalized against another row's sum all fail loudly.

`layernorm` gets the same ending and stays aspirational on #3/#13/#22 — and
gains the `fence.proxy.async.shared::cta` its `store_tile` owed before the TMA
engine reads the tile.

GAPS 2.3 now names what is actually left of the store side: the reduction
stores, which are absent from cuda-oxide in every form and so are a `ptx_asm!`
intrinsic or an upstream PR rather than a transcription.
@feitreim
feitreim merged commit 085cf3d into main Jul 27, 2026
feitreim added a commit that referenced this pull request Jul 28, 2026
#41 promoted softmax to running while this branch was in flight, so the skip
list was wrong: it is not aspirational any more, and the first thing the
harness claimed to be good at was making the next kernel cheap to add. It is
one `Case` -- sizes, work, grid, entry point -- plus the same verify-then-time
refactor `gemm` got, and it is the first row that exercises the other half of
the metric decision: bytes moved per second, because a kernel doing one `exp2`
and one divide per element it reads has no meaningful FLOP/s.

No `% of peak` for it. NVIDIA's HGX B200 page states the flops per GPU and
does not state the HBM bandwidth per GPU, so there is no sourced denominator
and the run says so in place of a ratio.

The CPU reference is a 128-entry table rather than a per-row `exp2` sweep:
every row is the same 128 values in a different order -- 11 is odd, so the
stride is a bijection mod 128 -- so the peak and the denominator are the same
for every row at any size, and each output is still compared against its own
expected value. That is what makes a half-million-row check affordable.
feitreim added a commit that referenced this pull request Jul 28, 2026
* gemm: let the cluster's TMEM allocator survive a second launch

`gemm_cg2` issued all three `cta_group::2` allocator instructions from
rank 0 alone, with the peer reading the leader's address over distributed
shared memory, and never relinquished the allocation permit at all. The
intrinsics all say the same thing about who issues them -- "one full warp
in each peer CTA" -- and the cost of ignoring it is invisible to a
one-shot run: a CTA that exits without relinquishing its permit, or
without taking its half of the pair's dealloc, leaves the SM's allocator
short, and the next CTA scheduled there waits in `tcgen05.alloc` for
columns that are never coming back.

So the first launch was always fine and the second one in the same
process hung forever. #40 is what found it, by being the first thing to
launch this kernel twice; `modal_app.py::examples` cannot see it, because
one launch is a strictly weaker claim than two.

Both CTAs now allocate, relinquish and deallocate, and each reads the
address out of its own staging word -- the collective writes one into
each, so the DSMEM read is gone with the bug it was covering for.

* examples: a bench harness that checks a size before it times it

`modal run modal_app.py::bench` (B200), separate from `examples` so the
correctness path stays a few seconds.

`gemm::check` grows a size parameter and a tail: `run` launches `[m, n, k]`,
compares every element of `C` against the CPU reference, and only then hands
the launch to a `then` callback. That order is the whole design -- the timing
hook is unreachable from a launch whose output was wrong, so there is no path
that reports throughput for a kernel that did not compute. `check` passes a
no-op and is otherwise what it was.

`bench.rs` owns the clock and the table. Timing is CUDA events either side of
the launch rather than wall clock around the driver call, which at the small
end of the sweep is the difference between measuring the kernel and measuring
the host. Five launches are thrown away before thirty timed ones; the headline
is the minimum, with the median and maximum printed beside it because a gap
between them is a finding rather than noise to hide.

An example states what it is bound by. GEMM is compute-bound and gets TFLOP/s;
a memory-bound kernel gets GB/s, because `2*M*N*K` for a normalization kernel
is a large-looking number that describes nothing. A `% of peak` column appears
only where the peak behind it is sourced -- 2250 TFLOP/s dense bf16 for one
B200, from NVIDIA's own HGX page and its "Dense is 1/2 sparse spec shown"
footnote -- and the run prints that provenance under the table. Everything not
in the table is in the skip list with the issue it waits on, so a missing row
never reads as "slow".

The CPU reference is now 35 dot products rather than `m*n*k` of them: `a_value`
repeats every 7 rows and `b_value` every 5 columns, so at 8192^3 the naive form
is minutes of host time for the same 35 numbers. Every element is still
compared against its own expected value.

Sizes that do not divide the 256x128x64 tiling are rejected rather than
launched, since the kernel bounds-checks none of its walk.

* bench: softmax, the memory-bound row the harness was shaped for

#41 promoted softmax to running while this branch was in flight, so the skip
list was wrong: it is not aspirational any more, and the first thing the
harness claimed to be good at was making the next kernel cheap to add. It is
one `Case` -- sizes, work, grid, entry point -- plus the same verify-then-time
refactor `gemm` got, and it is the first row that exercises the other half of
the metric decision: bytes moved per second, because a kernel doing one `exp2`
and one divide per element it reads has no meaningful FLOP/s.

No `% of peak` for it. NVIDIA's HGX B200 page states the flops per GPU and
does not state the HBM bandwidth per GPU, so there is no sourced denominator
and the run says so in place of a ratio.

The CPU reference is a 128-entry table rather than a per-row `exp2` sweep:
every row is the same 128 values in a different order -- 11 is odd, so the
stride is a bijection mod 128 -- so the peak and the denominator are the same
for every row at any size, and each output is still compared against its own
expected value. That is what makes a half-million-row check affordable.
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.

TMA store path

1 participant