Skip to content

Two fp32 a store where the layout pairs them, and the boundary intercept says so (#91) - #94

Merged
feitreim merged 1 commit into
mainfrom
vectorize-store-rows-91
Jul 28, 2026
Merged

feitreim merged 1 commit into
mainfrom
vectorize-store-rows-91

Conversation

@feitreim

Copy link
Copy Markdown
Owner

Closes #91.

The answer, in one line

store_rows now writes two fp32 per instruction where the layout says it may,
and the depth sweep's intercept falls 36–45% while its slope does not move
— which is the specific prediction #91 attached to this change, and what makes
this evidence rather than a throughput delta. 8192³ goes 1076.4 → 1223.4
TFLOP/s (+13.7%)
and 16384³ 1222.4 → 1291.7 (+5.7%), both end to end
through bench.rs' verify-then-time path.

1. What changed, and why it is on the layout

BaseLdtm::column(lane, value) = 2*(lane%4) + 16*(value/4) + [0,1,8,9][value%4]
puts a thread's four values of a 16-column block at two adjacent pairs. So
values 0 and 1 are one st.global.v2.f32, values 2 and 3 are another, and a
[128, 128] fp32 accumulator band drops from 512 scalar stores a lane to 256
paired ones. Not v4: the run breaks at the 1 → 8 step, and nothing here
forces it.

#91 asked for this to go through the trait, and it does:

// ColLayout
const CONTIGUOUS_VALUES: usize = 1;

The contract is both halves of what a vector access needs — that the addresses
are adjacent and that the first is aligned for the width:

run % CONTIGUOUS_VALUES == 0  ⟹  col_of(lane, run + i) == col_of(lane, run) + i
                                  for i < CONTIGUOUS_VALUES, and
                                  CONTIGUOUS_VALUES divides col_of(lane, run)
                                  and VALUES.

BaseLdtm claims 2. The default is 1, which is true of every map, so a
layout written later (#23 opened the shape set) gets scalar accesses until it
claims better rather than silently inheriting this arithmetic.
base_ldtm_pairs_every_other_value checks the claim as stated — every lane,
every value, four widths — rather than by re-deriving {0,1,8,9}, and a
post-monomorphization const { assert!(..) } in the mover catches a layout
whose run does not divide its values.

What the layout cannot know, and the mover checks. A vector access must be
aligned to its own width, and a cursor's base, stride and column origin are
runtime numbers. GlobalRows::runs_aligned tests the three terms that have to
agree — base, column origin, row stride — once per call, and picks between
two separately-unrolled loops, so neither path carries a branch. An odd leading
dimension gets scalar stores rather than a misaligned-address fault. That is
deliberately not a new safety contract: promising alignment would have made an
odd ldc silent UB in a mover whose whole point is that the stride arrives at
runtime.

load_rows gets the same treatment over the same addresses.

Both paths are in the emitted PTX, as intended — gemm_cg2 carries 4
st.global.v2.f32 and 4 st.global.b32, the rolled paired loop and its
fallback.

2. The intercept moved and the slope did not

#90's fit, re-derived by least squares on raw minimum milliseconds, over the
same three point selections §7 reports
so the comparison is like for like.
Before and after were measured in the same session pair on one B200.

Confidence in the fit first: fed #90's published milliseconds, my script
reproduces its table to the last digit — 1508.4 / 0.2948 ms / 29.5 µs / 28.8%,
residuals +40.0, −2.1, −50.0, +12.0, marginal costs 0.378, 0.503, 0.569.

points steady TFLOP/s fixed ms per tile µs share at K=8192
K = 8192, 32768 1481 → 1515 0.2778 → 0.1783 27.8 → 17.8 27.2% → 19.7%
K = 2048, 8192, 32768 1511 → 1519 0.3299 → 0.1845 33.0 → 18.4 32.3% → 20.4%
all four 1530 → 1527 0.3598 → 0.1981 36.0 → 19.8 35.3% → 21.9%

Intercept: −36% to −45%. Slope: −0.2% on the four-point fit (+2.3% and
+0.5% on the two thinner selections, in the direction and of the size selection
noise has). The boundary's share of the 8192³ launch goes from 27–35% to
20–22%.

My baseline session runs 2–6% under #90's published figures across all nine
cells, which is the cross-session drift #90 itself reported ("the other session
runs 2–4% under all nine figures"). That is why before and after were
re-measured here rather than comparing against the merged numbers.

The raw rows, all four verified before being timed:

K before ms after ms
512 0.4468 0.2623
2048 0.5416 0.3690
8192 1.0202 0.9041
32768 3.2475 3.0815

The four-point residuals shrink too, +42.1, +2.2, −58.1, +13.7 →
+19.2, −9.1, −13.9, +3.7, and with them the point-selection sensitivity that
was all of #90's stated uncertainty: the intercept now spans 0.178–0.198 ms
where it spanned 0.278–0.360. Removing a large fixed cost removed much of what
made the line a rough model. The convexity #90 attributed to crossing L2 is
still there — marginal cost per K block still rises, 0.445, 0.557, 0.567 µs.

3. Two corroborations with no fit in them at all

The size sweep falls in the order a fixed cost predicts. The shallower the
reduction, the larger a share the boundary was, so the gain shrinks
monotonically with depth:

shape before ms after ms before TFLOP/s after TFLOP/s gain
256x128x256 0.0238 0.0171 — — −28% time
512x256x256 0.0254 0.0176 — — −31% time
1024³ 0.0280 0.0219 76.6 98.0 +28%
2048³ 0.0470 0.0371 365.5 463.6 +27%
4096³ 0.1919 0.1534 716.3 895.9 +25%
8192³ 1.0214 0.8987 1076.4 1223.4 +14%
16384³ 7.1955 6.8098 1222.4 1291.7 +6%

8192³ repeats to 0.6% between the two sessions that measured it here (0.8987
and 0.9041). 16384³ is still the least reproducible row in the file, as #90
found; both trees were measured in the same session pair, and the +5.7% is a
single comparison, not a range.

The small-size floor moves with it. §7's item 3 established that the flat
~23 µs at the small end is one item boundary showing up undivided. It is
23.8 µs before and 17.1 µs after — a 6.7 µs drop against the ~10 µs the fit
says a tile's boundary lost. One cluster, one item, nothing amortized, no fit.

4. Why it is worth more than halving the instruction count

Under BaseLdtm a single scalar store has a warp's 32 lanes writing eight
rows of C, four four-byte words each at columns 0, 2, 4, 6 — 8 sectors
carrying 16 useful bytes each
— and the next value writes those same eight
sectors again. The pair store touches the same eight and fills them. So it
halves the instructions and doubles sector utilization, which is why the
effect is larger than "half as many stores" would buy.

5. Registers, reported and not treated as the result

ptxas -v, sm_100a:

kernel before after spill st/ld stack
gemm_cg2 40 167 0 / 0 528 → 528
flash_forward 123 168 0 / 0 1824 → 1824
global_rows_map 32 144 0 / 0 528 → 528
global_copy_probe_128_movers 44 168 0 / 0 528 → 528

Nothing spills and no frame grows, and 167 registers still admits 3 CTAs/SM
— 65536 registers an SM over 128 threads and 3 CTAs leaves 170. The clock
agrees residency did not drop: falling to 2 CTAs/SM would have shown up as a
slowdown, not +14%.

I guessed at the cause and the guess was wrong, so here is the measurement
instead.
The obvious suspect is the inline asm's clobber("memory") blocking
LLVM from sinking the LDTM drain into the store loop — #63's "register cost is
liveness". It is not that: a tree with both clobbers deleted gives byte-identical
counts
(167 / 168 / 144 / 168). So the rise comes from the asm store itself
and not from its memory ordering, and the clobber is kept because it is sound
and, now measured, free. What in the asm lowering costs the registers is not
established here, and I am not going to assert a mechanism I have not shown.

This is the fifth time here that the register column has ordered time backwards
(#47, #63, #67, #76). It is reported because the headroom is now thin — 167
against 170, where shared memory already caps residency at 3 — so the next
change to this epilogue should know both resources are at the limit.

6. The TMA route, priced and not built

TMEM → shared → TMA store (#9) is what softmax already does, and
tma_store_wait_read releases the shared buffer as soon as the engine has read
it, which is the mechanism an overlapping epilogue and #15's lcsf both need.
It replaces the scattered stores with one engine-driven transfer. It costs
shared memory this kernel does not have.

The residency census in device-tests measures that directly, in this PR's own
run: gemm envelope (cg2) is 3 CTAs/SM at 73792 B a CTA against 233472 B an
SM
. That is 221376 used and 4032 B a CTA of headroom. One warp's
[32, 128] fp32 band is 16384 B; the whole [128, 128] tile is 65536 B.
So a staging buffer takes residency to 2 CTAs/SM, or to 1 — MAX_CLUSTERS
222 → 148 or 74.

Against a steady state already at only 67% of dense peak, cutting concurrency by
a third to recover a term now worth 20–22% is a losing trade. It was already
close at 27–36%; this PR makes the prize smaller and leaves the price unchanged.

The one version that could pay reuses an existing ring slot — an ARing stage
is 16384 B, exactly one band — so the plan does not grow. But the slot must not
be refilled until the engine has read it, which serializes the next item's first
loads against the store unless the schedule changes with it. That makes it a
scheduling change entangled with #15 and #88, not an epilogue change.

It also needs plumbing that does not exist: TensorMapElement is implemented
for Bf16 only (no CU_TENSOR_MAP_DATA_TYPE_FLOAT32), there is no fp32
SharedTile swizzle — the atom arithmetic is written around 2-byte elements —
and stmatrix is b16, so getting fp32 registers into a swizzled shared tile is
plain indexed stores plus a fence.proxy.async.shared::cta. Roughly 250–400
lines across shared.rs, global.rs, ldst.rs, the epilogue and its host
launcher.

Verdict: worth its own issue, queued behind #15 and #89, and not to be
attempted before the shared-memory plan question is settled
— at today's plan
the arithmetic says it loses.

Scope

No kernel constant moved, and examples/src/gemm.rs is untouched — the
epilogue call site needed no change, which is the point of the pairing being a
property of the layout rather than of the call site.

  • src/reg.rs: ColLayout::CONTIGUOUS_VALUES (default 1), BaseLdtm claims 2,
    and base_ldtm_pairs_every_other_value.
  • src/global.rs: GlobalRows::runs_aligned, the store_pair/load_pair
    helpers, and store_rows/load_rows split into width-parameterized loops,
    plus three host tests.
  • examples/README.md §7: the tables and the argument above.

Verification

  • modal run modal_app.py::build — exit 0, all seven steps including
    RUSTDOCFLAGS=-D warnings cargo doc --features host and a real
    cargo oxide build --arch sm_100a of both crates.
  • modal run modal_app.py::examples — pass gemm 512x256x256 exact (4 tiles over 4 clusters), 4096x4096x256 exact (512 tiles over 222 clusters),
    pass softmax, pass layernorm. Run before any timing: a wrong store
    lands wrong numbers silently.
  • modal run modal_app.py::device_tests — 31 of 31 cases passed, including
    global rows map, which reads a band out of a pitched fp32 matrix at a
    non-zero, non-block-aligned origin.
  • modal run modal_app.py::bench --case gemm-depth and --case gemm, on this
    tree and on a clean d47a7f0 worktree, same session pair.
  • modal run modal_app.py::regcount on both trees, plus the no-clobber
    diagnostic tree above.
  • Locally: cargo fmt --check, cargo clippy --all-targets -D warnings,
    cargo test (78 passing, one new).

B200, driver 580.95.05, 148 SMs.

@feitreim
feitreim merged commit ec84abc into main Jul 28, 2026
2 checks passed
feitreim added a commit that referenced this pull request Jul 28, 2026
feitreim added a commit that referenced this pull request Jul 28, 2026
…are at 0.69 of it (#92) (#96)

* cuBLASLt beside the GEMM, in-process and checked first (#92)

* The measured ratio, both runs, and what cuBLASLt's 1791-1947 says about #90's derivation (#92)

* Re-measure both columns on one tree after #94: 0.69 where the ratio is stable, and cuBLASLt prices the target (#92)
feitreim added a commit that referenced this pull request Jul 28, 2026
…eventh (#98) (#101)

#94 §6 rejected a shared staging buffer for the GEMM epilogue because it costs
an occupancy step, and "cutting concurrency by a third to recover a fifth is a
losing trade." The arithmetic was right and the premise under it was never
measured: a third of the *residency* is not a third of the *throughput*.

Measured by growing `gemm_cg2`'s declared shared plan with bytes no code reads
or writes — 8192 to cross 3 -> 2, 49152 to cross 2 -> 1 — with `CTAS_PER_SM`
moved to match. Work, traversal, instruction mix and register count identical
either side; the only variable is residency. The dead allocation is an
experiment and does not land.

One CTA an SM is worth **14-16%**, not 33%. The cost is convex: the third CTA is
worth a seventh, the second 25-44%, and at 1 CTA/SM throughput is flat at
~590 TFLOP/s across 4096^3 to 16384^3 — so over half of what this kernel
achieves is overlap between CTAs.

Three rungs added to `tmem residency census` at the exact envelopes, because a
run where residency did not move measures nothing and the occupancy query is
pinned at 1 by `tcgen05.alloc` (#77). They count 3 / 2 / 1, and the census's own
verdict asserts it.

#15's straight route is back on the table but not green: it breaks even only if
`lcsf` hides ~70% of the item boundary.
feitreim added a commit that referenced this pull request Aug 6, 2026
…ints stop remembering it (#132) (#200)

* The drain a deferred job owes is `Job::finish`, and thirteen entry points stop remembering it (#132)

A job that defers its last item's store owed one drain after the item loop, and
the trait provided nowhere to put it: both deferred jobs invented a `pending`
field with a `u32::MAX` sentinel and a `finish()` the *entry point* had to call.
`gemm_ws` has nine entry points and so had nine chances to forget it, and
forgetting it is a whole output tile computed by nobody.

`Job::finish` is that place — empty default, so it costs nothing for a job that
does not defer, and called by both `run` and `run_stealing` after their loops.
It runs after the loop's last `inval` and before the caller's `dealloc_*`, which
is exactly where all thirteen hand-rolled calls already sat, so no launch's
instruction stream moves.

The call sites removed: `gemm_cg2_lcsf`'s `job.finish()`, the nine in
`gemm_ws`, and the three `job.ring.drain()` the `StoreRing` entry points carried
— the same shape of obligation, named by #132 as such.

Also written down in `pipeline.rs`, where #132 asks for it: a
warp-asynchronous item stream is out of scope for this trait, why it is a
decision rather than an omission, and what the decision costs — #90 and #94 put
the item boundary it buys at a fifth to a third of the launch. That argument
lived only in `experiments/src/gemm_ws.rs`, which is being restructured.

* The empty default is about a job that defers nothing, not about an empty cluster

* The drain a job owes is the hook's, and docs/library/pipeline.md says so too (#132)
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.

store_rows writes one f32 at a time, and the layout pairs every other value

1 participant