Skip to content

An fp32 band reaches a shared staging tile, because a scatter is not an stmatrix (#174) - #183

Merged
feitreim merged 4 commits into
mainfrom
feat/issue-174-fp32-staging
Aug 4, 2026
Merged

feitreim merged 4 commits into
mainfrom
feat/issue-174-fp32-staging

Conversation

@feitreim

@feitreim feitreim commented Aug 4, 2026 •

Copy link
Copy Markdown
Owner

Closes #174.

What was missing

global::store_shared_rows and global::accumulate_shared_rows are generic
over their element and would take a SharedTile<F32, …> happily. Nothing could
fill one: ldst::store_tile and store_tile_x4 bound
E: Element<Unpacked = [f32; 2]> because they are stmatrix, which moves b16
matrices and nothing else. So an fp32 accumulator band reached memory only
through store_rows' per-value global stores — the shape #116 measured at
20.43 µs/tile against the staged route's 6.68 — and every kernel with an fp32
C paid it.

What this adds

  • ldst::scatter_tile — global::store_rows' loop with a
    SwizzledChunks::element where the GlobalRows::at was. Generic in the
    element and the layout, where store_tile is BaseLdtm-only:
    store_tile's addressing is an ldmatrix shape, while a scatter only ever
    asks the layout which (row, column) a value is.
  • SwizzledChunks::element — the shared-side twin of GlobalRows::at. A
    column splits into the chunk that holds it and the byte offset inside it; the
    swizzle stays at's and is not repeated.
  • Element::write_pair_shared — two adjacent values in one shared access,
    which is where a scatter's instruction count goes. st.shared.v2.f32 at fp32;
    at bf16 not a vector instruction at all, since two adjacent bf16 are one
    32-bit word, so the pair is one pack and one store and halves the cvt
    count too.

The alignment is structural rather than tested, which is the difference from
store_rows: a chunk is 16-byte aligned, a pair starts at a multiple of
ColLayout::CONTIGUOUS_VALUES by that constant's own contract, and
2 * E::BYTES divides 16 at both element widths. So the rung is a const and
neither path carries a branch.

An fp32 epilogue is now the same two calls a bf16 one is: scatter_tile, then
store_shared_rows or accumulate_shared_rows.

What holds it

Host: every_column_owns_its_own_bytes_of_the_chunk_holding_it (the element
split is a partition of the tile's bytes, over every base phase, at fp32 and
bf16, single and stacked subtiles) and
a_warps_scatter_covers_the_band_exactly_once, walked at the pair stride so it
also asserts that a pair is one aligned access inside one chunk.

tests/gaps.rs: an_fp32_band_reaches_a_staging_tile, whose unbounded E and
free L are the claim — narrowing either is the gap reopening.

B200 (gpu-ci), 50 of 50 cases: scatter drain / scatter drain wide at
32 and 128 fp32 columns, against register drain / register drain wide — the
same rectangle written the old way, through one host check, so a difference
between the two routes is the staging tile's alone.

Measurements

The route works and costs registers, not a frame

oxide-train's gemm_tcgen05_f32_optimized converted to the staged drain, on a
B200 (ptxas, and CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES for the frame):

registers .local frame
register drain (today) 120 512 B
staged, scalar scatter 94 0
staged, pair rung 96 0

That 512 B was a band that does not fit (the category #181 established), not a
rolled walk: store_rows held a whole [32, 64] fp32 band, and the accumulating
mode held C's band beside it. Staging removes both — a pass narrows to
[16, 64], and the fold becomes accumulate_shared_rows', which holds no band.

The probes, at 32 and at 128 columns

regcount on a93dc0d, device-tests' four fp32 probes — the same [64, C]
rectangle by the two routes, with the identity fill unrolled (fa70e35) so the
rows no longer share the probe's own .local depot:

kernel columns regs stack
register_drain 32 44 0
scatter_drain 32 40 0
register_drain_wide 128 122 0
scatter_drain_wide 128 56 0

At 128 columns the staged route is 66 registers cheaper — 122 against 56 —
and at 32 it is 4 cheaper. That is the claim in its cleanest form: the register
cost of an fp32 drain is the band's width, and a staging tile is what lets the
band stop being the whole pass. The gap widens with the band exactly as it
should, and it is the same mechanism that takes the downstream kernel's 512 B
frame to zero.

For scale, the bf16 staged probes at the same widths read 32 and 34, since
stmatrix moves a whole [16, 16] block where a scatter moves a pair.

The milliseconds did not follow, and the reason bounds the route

Three baseline runs against three converted runs, same harness, cuBLASLt in the
same process on the same stream. The bf16 arms are unchanged code and are the
noise floor: they move ±3% run to run, and 4096³ is the shape where the harness
is tightest.

shape arm baseline (ms) staged (ms)
4096³ f32 store 0.108 / 0.107 / 0.108 0.100 / 0.103 / 0.102
4096³ f32 accumulate 0.145 / 0.145 / 0.146 0.168 / 0.168 / 0.167
8192³ f32 store 0.635 / 0.670 / 0.643 0.623 / 0.711 / 0.624
8192³ f32 accumulate 0.758 / 0.814 / 0.755 0.844 / 0.980 / 0.901
16384³ f32 store 5.455 / 6.058 / 5.828 5.840 / 5.829 / 6.150
16384³ f32 accumulate 6.348 / 7.065 / 6.471 6.241 / 6.413 / 6.835

Against cuBLASLt at 16384³: f32 store 0.905 / 0.849 / 0.850 → 0.839 / 0.888 /
0.802, f32 accumulate 0.778 / 0.728 / 0.766 → 0.785 / 0.807 / 0.722. So: store
~5% faster at 4096³ and a wash above it; accumulate 15% slower at 4096³ and
8192³, reproducibly.

The cause is the tile's height, not the route. Four bytes an element buys
half the rows in the same shared bytes, so an fp32 band takes eight passes where
the bf16 band takes four, and a pass is a serial
scatter → ld.shared → global → bar.warp.sync chain. Twice the passes is
twice that exposed latency, and the accumulating variant puts an ld.global on
it as well. #116's −19% for bf16 was measured with a tile wide enough to
amortize the pass; that kernel's operand rings leave 18 344 B for four warps,
which at fp32 is not enough for one.

The pair rung was added in response to this — it halves the shared stores a band
costs — and moved nothing, which is what says the cost is the pass count rather
than the instruction count.

So the downstream conversion is not shipped. This PR is the route and the
evidence; the epilogue that can afford a [32, 64] fp32 staging tile is the one
to re-measure it on. GAPS.md §2.6 and docs/library/ldst.md carry both halves.

…an stmatrix (#174)

`store_shared_rows` and `accumulate_shared_rows` were already generic over
their element and would take a `SharedTile<F32, ...>`; nothing could fill one.
`ldst::store_tile` and `store_tile_x4` bound `Element<Unpacked = [f32; 2]>`
because they are `stmatrix`, which moves b16 matrices and nothing else — so an
fp32 accumulator band reached memory only through `store_rows`' per-value
global stores, the shape #116 measured at 20.43 us/tile against the staged
route's 6.68.

`ldst::scatter_tile` is that missing fill, and it is deliberately not a new
instruction: a store into shared memory at any element is an ordinary
`st.shared`, so this is `global::store_rows`' own loop with a
`SwizzledChunks::element` where the `GlobalRows::at` was. It is generic in the
layout as well as the element, where `store_tile` is `BaseLdtm`-only, because
nothing about a scatter is an `ldmatrix` shape.

`SwizzledChunks::element` is the shared-side twin of `GlobalRows::at`: a column
splits into the chunk holding it and the byte offset inside that chunk, and the
swizzle stays `at`'s. Two host tests carry the addressing —
`every_column_owns_its_own_bytes_of_the_chunk_holding_it` and
`a_warps_scatter_covers_the_band_exactly_once`.

`device-tests` gains `scatter drain` and `scatter drain wide` against
`register drain` and `register drain wide`: the same rectangle at 32 and at 128
fp32 columns, written through the staging tile and straight out of the
registers. One host check holds all four, so a difference between them is the
staging tile's alone -- and the pair is the register-pressure A/B `regcount`
reads as well as the correctness one.
@feitreim feitreim added the gpu-ci Run the B200 device-test tier on this PR (costs GPU minutes) label Aug 4, 2026
…n every regcount row

Every one of the four fp32 probes and both bf16 ones read 272 stack bytes and
identical .local traffic, because the identity fill was a rolled walk over a
RegTile -- ferro #166's depot, the fill's and not the drain's. Unrolling it the
way every mover in the library is unrolled leaves the drains comparable to each
other, which is the whole reason the scatter and register rows are a pair.
…struction count was going

The first cut issued one st.shared per value: a [16, 64] fp32 band is 64 a
thread against the eight stmatrix the same band costs at bf16, and that gap is
the whole risk in trading a global scatter for a shared one. Element gains
write_pair_shared and scatter_tile a pair rung over ColLayout's
CONTIGUOUS_VALUES, halving it -- st.shared.v2.f32 at fp32, and at bf16 not a
vector instruction at all, since two adjacent bf16 are one 32-bit word and the
pair is one pack and one store.

The alignment is structural rather than tested, which is the difference from
store_rows: a chunk is 16-byte aligned, a pair starts at a multiple of
CONTIGUOUS_VALUES by that constant's contract, and 2 * E::BYTES divides 16 at
both element widths. So the rung is a const and neither path carries a branch.
The band-coverage test now walks at the pair stride and asserts both claims the
rung rests on.
oxide-train's fp32 GEMM converted to the staged drain goes from 120 registers
and a 512 B .local frame to 96 and none -- the frame was a band that did not
fit, and staging removes it twice over, since a pass narrows and the fold moves
into accumulate_shared_rows. Against three baseline runs on a B200 the store arm
is ~5% faster at 4096 cubed and a wash above it, and the accumulate arm is 15%
slower at 4096 and 8192 cubed.

The cause is the tile's height and it bounds when this route is right: four
bytes an element buys half the rows in the same shared bytes, so an fp32 band is
eight passes where bf16 is four, and a pass is a serial scatter, ld.shared,
global, bar.warp.sync chain. #116's -19% was measured with a tile wide enough to
amortize the pass; that kernel's operand rings do not leave one. The conversion
was not shipped.
@feitreim

feitreim commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

The downstream conversion that was measured, and not shipped

Kept here rather than as an oxide-train PR: it is a data point, and the
measurements above say it is a loss on that kernel. Anyone re-measuring the
staged fp32 drain on an epilogue with more shared memory to spend starts from
this.

gpu/gemm/src/optimized.rs, against oxide-train a02f5ef. Correctness passed
on a B200 in both forms (scalar scatter and pair rung), and the ptxas pin would
have ratcheted gemm_tcgen05_f32_optimized from 120 / 512 B to 96 / 0.

The one design note worth carrying forward: the two staging tiles are the same
4096 bytes a warp
read at different shapes — [32, 64] at bf16, [16, 64] at
fp32 — so the shared plan does not know which epilogue it is serving and
SHARED_BYTES stays one number. That is also exactly why it loses: half the
rows is twice the passes.

diff --git a/gpu/gemm/src/optimized.rs b/gpu/gemm/src/optimized.rs
index 2f55f8b..1861e37 100644
--- a/gpu/gemm/src/optimized.rs
+++ b/gpu/gemm/src/optimized.rs
@@ -54,24 +54,31 @@
 //! a time and paid more than the whole rest of the kernel for it: 1113.8
 //! TFLOP/s storing against 536.2 accumulating, at 4096³ on a B200.
 //!
-//! An **fp32** `C` cannot take that route at all — `stmatrix` moves b16
-//! matrices, so nothing can fill an fp32 staging tile — and drains through
-//! [`store_rows`] a value at a time instead. That is a ferro-kittens gap rather
-//! than a choice here; GAPS.md §2.6 carries it.
+//! An **fp32** `C` takes the same route since ferro #174, by a different
+//! filling instruction: `stmatrix` moves b16 matrices, so an fp32 band reaches
+//! its staging tile through [`scatter_tile`]'s per-value `st.shared` instead.
+//! Everything after that is shared — same drain movers, same access ladder,
+//! same 16-byte stores — so the two epilogues differ in one call.
+//!
+//! The two staging tiles are **the same 4096 bytes a warp**, read at different
+//! shapes: `[32, STAGE_N]` at bf16 and `[16, STAGE_N]` at fp32, four bytes an
+//! element buying half the rows. So the shared plan does not know which
+//! epilogue it is serving, [`SHARED_BYTES`] is one number, and the fp32 drain
+//! takes two row halves per column group where the bf16 one takes a whole band.
+//! Both are [`STAGE_N`] columns a pass and both are one
+//! `tcgen05.ld.16x256b.x8` per 16 rows of it, which is what keeps this a
+//! comparison of the *store* half.
 
 use cuda_device::tcgen05::tcgen05_fence_before_thread_sync;
 use cuda_device::tma::TmaDescriptor;
 use cuda_device::{DisjointSlice, cluster, cluster_launch, kernel, thread, warp};
 use cuda_host::cuda_module;
 
-use kittens::global::{
-    GlobalRows, accumulate_shared_rows, load_rows, store_rows, store_shared_rows,
-};
-use kittens::ldst::store_tile_x4;
+use kittens::global::{GlobalRows, accumulate_shared_rows, store_shared_rows};
+use kittens::ldst::{scatter_tile, store_tile_x4};
 use kittens::mma::{MmaShape, commit_multicast_cg2, mma_walk_cg2};
 use kittens::pipeline::{self, Job};
 use kittens::plan::SharedPlan;
-use kittens::reg::Add;
 use kittens::shared::{Bf16, F32, SharedTile, SharedTileRing, Swizzle128B};
 use kittens::sync::{Semaphore, SemaphoreRing};
 use kittens::tmem::{TmemTile, alloc_cluster, dealloc_cluster};
@@ -117,8 +124,17 @@ type Ring = SharedTileRing<Bf16, BLOCK_M, BLOCK_K, Swizzle128B, STAGES>;
 type StageTile = SharedTile<Bf16, 32, STAGE_N, Swizzle128B>;
 type StageRun = SharedTileRing<Bf16, 32, STAGE_N, Swizzle128B, WARPS>;
 type Band = RegTile<32, STAGE_N, BaseLdtm>;
+/// The same staging bytes at fp32 — half the rows, because an element is twice
+/// as wide. A pass is [`STAGE_N`] columns either way.
+type WideStage = SharedTile<F32, 16, STAGE_N, Swizzle128B>;
+type WideBand = RegTile<16, STAGE_N, BaseLdtm>;
 type Accumulator = TmemTile<BLOCK_M, BLOCK_N>;
 
+const _: () = assert!(
+    StageTile::BYTES == WideStage::BYTES,
+    "one staging run serves both epilogues, so the two tiles are the same bytes"
+);
+
 const _: () = assert!(HALF_N == BLOCK_M, "one stage type serves both operands");
 const _: () = assert!(
     Stage::BYTES == MnStage::BYTES,
@@ -174,9 +190,9 @@ const fn staged(at: SharedPlan) -> (StageRun, SharedPlan) {
 /// Dynamic shared memory both entry points declare. It has to stay at or under
 /// the 116 736 B an SM's 233 472 leaves a CTA at [`CTAS_PER_SM`].
 ///
-/// The fp32 epilogue never touches the staging run and declares it anyway,
-/// which costs nothing: tensor memory already pins residency at two, so those
-/// 16 424 B buy the bf16 drain its shape and take nothing from the other.
+/// Both epilogues stage through the same 16 424 B, which is why there is one
+/// number here rather than one per entry point: an fp32 tile of the same bytes
+/// is half the rows, not twice the footprint.
 pub const SHARED_BYTES: usize = staged(shared(SharedPlan::sizing()).plan).1.bytes();
 
 const _: () = {
@@ -248,14 +264,20 @@ impl Drain for Packed {
     }
 }
 
-/// fp32 `C`, straight out of the registers.
+/// fp32 `C`, through the same staging tile read at fp32 (ferro #174).
 ///
-/// No staging tile, and not for want of asking: [`store_shared_rows`] is
-/// generic over its element and would take an fp32 tile, but `stmatrix` moves
-/// b16 matrices and nothing in ferro-kittens can *fill* one (GAPS.md §2.6). So
-/// this is the scattered per-value drain the bf16 path stopped using — one
-/// `st.global.v2.f32` per pair of columns against the other's contiguous 16
-/// bytes — and it is why the fp32 rows of the benchmark trail the bf16 ones.
+/// [`Packed`]'s drain with two things changed and nothing else: the band
+/// reaches shared memory through [`scatter_tile`]'s per-value `st.shared`
+/// rather than an `stmatrix`, and it goes 16 rows at a time rather than 32,
+/// because four bytes an element is half the rows in the same 4096. The global
+/// half is identical — the same mover, the same access ladder, the same
+/// contiguous 16-byte stores.
+///
+/// What that replaces is the register drain, where `store_rows` wrote one
+/// `st.global.v2.f32` per pair of columns across eight discontiguous runs a
+/// warp, and the accumulating mode held a second whole band beside the first to
+/// do it. The fold is now [`accumulate_shared_rows`]', which reads `C` at the
+/// width it writes it and holds no band at all.
 #[derive(Clone, Copy)]
 struct Wide {
     c: GlobalRows<F32>,
@@ -264,20 +286,39 @@ struct Wide {
 
 impl Drain for Wide {
     #[inline(always)]
-    unsafe fn drain(self, accumulator: Accumulator, _stage: StageTile, row: u32, column: u32) {
+    unsafe fn drain(self, accumulator: Accumulator, stage: StageTile, row: u32, column: u32) {
         unsafe {
-            let (lane, band_row) = (lane(), 32 * warp_id());
+            // The run's bytes, read at this epilogue's element — the same
+            // reinterpretation `MnStage::from_raw` makes of an operand stage.
+            let stage = WideStage::from_raw(stage.base());
+            let (lane, chunks) = (lane(), stage.chunk_writer());
+            let band_row = 32 * warp_id();
             let mut at = 0u32;
             while at < BLOCK_N as u32 {
-                let mut band: Band = accumulator.tile_x8(band_row, at);
-                if self.fold {
-                    // The fold's addresses are the store's, so `C` comes back
-                    // at the width it goes out at, and the sum is held in fp32
-                    // — the accumulator's own precision, with nothing rounded
-                    // on the way through.
-                    band.bin_map_assign::<Add>(load_rows(self.c, row, column + at, lane));
+                let mut half = 0u32;
+                while half < 32 {
+                    let band: WideBand = accumulator.tile_x8(band_row + half, at);
+                    scatter_tile(chunks, 0, 0, lane, band);
+                    if self.fold {
+                        accumulate_shared_rows::<F32, 16, STAGE_N, Swizzle128B, 32>(
+                            self.c,
+                            row + half,
+                            column + at,
+                            lane,
+                            stage,
+                        );
+                    } else {
+                        store_shared_rows::<F32, 16, STAGE_N, Swizzle128B, 32>(
+                            self.c,
+                            row + half,
+                            column + at,
+                            lane,
+                            stage,
+                        );
+                    }
+                    warp::sync_mask(u32::MAX);
+                    half += 16;
                 }
-                store_rows(self.c, row, column + at, lane, band);
                 at += STAGE_N as u32;
             }
         }

@feitreim
feitreim merged commit 51f57c5 into main Aug 4, 2026
4 of 6 checks passed
@feitreim
feitreim deleted the feat/issue-174-fp32-staging branch August 4, 2026 04:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu-ci Run the B200 device-test tier on this PR (costs GPU minutes)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An fp32 band cannot reach a shared staging tile, so an fp32 epilogue is stuck on the pre-#116 drain

1 participant