Skip to content

Generalize the global layout beyond PanelMap (and run an example) - #39

Merged
feitreim merged 3 commits into
mainfrom
issue-8-global-layout
Jul 27, 2026
Merged

feitreim merged 3 commits into
mainfrom
issue-8-global-layout

Conversation

@feitreim

@feitreim feitreim commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

PanelMap built exactly one descriptor shape: bf16, rank 3, packed, box derived
from the SharedTile. GlobalLayout<E, RANK> keeps the derivation and drops
everything else.

Design

pub struct GlobalLayout<E: Element, const RANK: usize> {
    base: u64,
    extents: [usize; RANK],
    strides: [u64; RANK],   // byte strides, [0] == E::BYTES
    _marker: PhantomData<E>,
}
  • packed(base, extents) and strided(base, extents, element_strides) — the
    second is a leading dimension wider than its rows, which the GEMM does not
    need but a sliced tensor does. Both unsafe; the layout does not borrow the
    buffer. Dimension 0 is the contiguous one, the driver's order, which is also
    the order tma_load_2d gives its coordinates in.
  • tensor_map::<T: TileBox<Element = E>>(&stream) -> Result<TensorMap, _> is
    safe, because the layout's constructor already took the promise.
  • The box-from-tile derivation survives and got stronger. A new TileBox
    trait, implemented once for SharedTile<E, R, C, S>, hands the map
    BOX_COLS = SUBTILE_COLS, BOX_ROWS = R, the swizzle mode (from
    S::ATOM_BYTES, so the atom width and the driver enum cannot be stated
    apart) and, through Element, the data type. tensor_map states no shape
    field of its own. The Element = E bound means a layout paired with a tile
    of the wrong element does not typecheck — something the old builder, with
    bf16 hardcoded on both sides, could not say.
  • PanelMap is a type alias for TensorMap; encode_bf16_panels is now
    five lines over GlobalLayout::<Bf16, 3>::packed(...).tensor_map::<Tile>().
    Every existing call site is byte-identical and unchanged.
  • Still #[cfg(feature = "host")] in full.

strides is [u64; RANK] rather than [u64; RANK - 1] (what the driver
takes) and tensor_map passes self.strides[1..].as_ptr(). That is the
deliberate dodge: RANK - 1 as an array length needs generic_const_exprs.

On the per-dimension compile-time/runtime marker

The issue asks for one. I did not build it, and I don't think it should be
built yet.
Every extent at every call site in this repo — the device tests'
rows/planes, the GEMM's M/N/K — is a runtime value, so a marker would
be type machinery with no instantiation exercising the compile-time arm. What it
would buy is constant folding in address arithmetic that happens inside the TMA
engine, not in emitted code: the extents are written into a 128-byte descriptor
once on the host and the kernel never sees them. And the natural implementation
computes array lengths from the markers, which is generic_const_exprs.

The rank is a const generic, because it decides the arity of the arrays the
driver call takes — that is what a const generic is for here.

This is also #23's lesson applied: base_ldtm_shapes! made the set of
expressible tiles a closed library decision as a side effect of a const-generic
design nobody had a use case for. Runtime extents can gain a marker later
without breaking a caller; a marker per dimension cannot be removed.

A host launcher became possible, and gemm runs

examples/README.md said the absence of a launcher was #8. It is now
gemm::check, and it produces the first numerical result this library has ever
had:

kernel          status                                 threads        shared
gemm            runs                                       128        73792 B

pass  gemm              512x256x256 exact

[512, 256] · [256, 256]ᵀ on a B200, every element compared to a CPU reference
with ==. Operands are integers in [-3, 3] and [-2, 2], so every product
and every partial sum is exact in bf16 and in fp32 — a mismatch is a wrong
coordinate, a wrong stride or a wrong operand half, never a rounding artifact.
The two operands' maps differ only in their extents; neither states a box.

Getting there cost one real bug, and it is the best argument in this PR for
running examples rather than compiling them.
The kernel compiled, and hung.
Both CTAs' TMA loads have to complete on the leader's stage barrier, and
gemm.rs mapped that address by hand in a GAP block asking for
Semaphore::at_rank. But a plain cp.async.bulk.tensor completes on a barrier
in the issuing CTA's own shared memory, so the peer's 24 KiB never reached
the count the leader had charged for 48 KiB. The fix is
tma_load_2d_multicast_cg2 with the CTA's own bit as the whole mask, onto
Semaphore::multicast_alias: nothing is replicated, and the multicast form's
barrier operand is .shared::cluster, which is the only way one CTA may name
another's barrier. Both primitives were already in the library. README §8 said
this kernel "cannot use the multicast load"; that is now corrected in place,
with the more useful statement — what a cluster kernel needs from multicast is
the address space, not the delivery. The GAP block is deleted.

Second thing the run needed: 72 KiB of dynamic shared memory is past the 48 KiB
a block gets by default, and cuda-oxide issues
CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES only from its prepared-launch
path. Hence #[launch_contract(...)] on gemm_cg2 — the envelope is restated
as literals because the attribute takes literals, with a const _: () = assert!(...) keeping it in step with THREADS/SHARED_BYTES.

What I verified

Check Result
modal run modal_app.py::build pass — clippy (lib+host, device-tests, examples, all --all-targets), 53 host tests, cargo oxide build --arch sm_100a for both kernel crates
modal run modal_app.py (B200) 14 of 14 device cases pass, including the new 2d tensor map
modal run modal_app.py::examples (B200) pass gemm 512x256x256 exact
cargo fmt --check clean in all three crates

Every row above was re-run after rebasing onto #37 (95aa969). (The hang cost
one container; I stopped it rather than let it ride to the 30-minute timeout.)

Rebase notes: device-tests conflicted with #35's swizzle_probe::<R, C>
refactor and #37's reduction shuffles case, so the 2-D case was rewritten to
match the file's new discipline — an inline tma_2d_probe::<R, C> beside
swizzle_probe, and a check_tma_2d::<R, C> taking a launch closure like its
neighbours. examples/README.md conflicted on the status table; #37's shortened
blocked-on lists are kept verbatim (softmax is #9 and nothing else), with
only gemm's row changed to runs.

What the host tests can and cannot reach

cuTensorMapEncodeTiled fills 128 opaque bytes and needs a driver, so the
encode call itself is unreachable off a GPU and nothing can read a descriptor
back. What is testable is everything fed into it, and that is now a private
descriptor_shape::<T>() returning the globalDim/boxDim arrays plus a
check_driver_requirements pass. Seven tests cover: packed strides as the
products below each dimension; strided spacing rows by a pitch and panicking
on a gap along dimension 0; the box being one subtile of the tile it is paired
with, and not widening when the tile does; rank 2 dropping the plane
coordinate; the exact arrays encode_bf16_panels used to write by hand; and
each driver rule (16-byte base, 16-byte strides, extent ≥ box, box ≤ 256)
naming the field it is about instead of surfacing as CUDA_ERROR_INVALID_VALUE.

And on silicon

device-tests gains one case, 2d tensor map: the same swizzle round trip as
swizzle round trip, through tma_load_2d, against a rank-2 layout whose row
stride is 96 bf16 columns for a 64-column tile. The padding is a bit pattern
decode_cell rejects, so a descriptor that walks rows by the wrong stride
reports padding at a position rather than a plausible neighbour. It passes,
which is what makes "rank 2 works" and "non-packed strides work" hardware facts
rather than arithmetic that agrees with itself.

Examples

  • gemm.rs: header compiles → runs; #[launch_contract]; the at_leader
    GAP block deleted; the maps built from GlobalLayout; check + a CPU
    reference at the end of the file.
  • main.rs: prints the status table, then runs every kernel that has a
    launcher and exits non-zero on a wrong number. Off a GPU it degrades to the
    table it always printed, so ::build is unaffected.
  • Cargo.toml: kittens with features = ["host"].
  • README.md: status table (gemm → runs), the run command, the
    no-launcher paragraph replaced by the result and the bug, the Generalize the global layout beyond PanelMap #8 entry
    closed, and §8 (multicast) corrected.
  • modal_app.py: an examples B200 function, and clippy over the examples
    crate in build.

What #8 does not close

GlobalLayout is bf16-only, because Element is implemented only for Bf16 —
#2 owns that, and it is why layernorm's fp32 parameter vectors are still not
describable. The element is now one TensorMapElement impl away rather than a
hardcode in a builder, which is the whole of the change #2 will need on this
side. Rank 1 is expressible and untried; nothing here wants one yet.

Closes #8

feitreim added 3 commits July 27, 2026 18:54
PanelMap built exactly one descriptor shape -- bf16, rank 3, packed, box
derived from the tile. GlobalLayout keeps the derivation and drops
everything else: base, extents and byte strides at any rank 1..=5, packed
or with an explicit leading dimension, with the box, swizzle mode and
data type read off the SharedTile the map is paired with through the new
TileBox trait. A layout paired with a tile of the wrong element does not
typecheck, which the old builder could not say.

Only the rank is a const generic. Every extent at every call site is a
runtime value, and a per-dimension compile-time marker would need array
lengths computed from the markers -- generic_const_exprs.

encode_bf16_panels stays, as a five-line constructor over the new type,
so the hardware-validated device tests keep their one path unchanged.
The 3-D panel map is the only descriptor shape silicon has ever checked
here. This runs the same swizzle round trip through tma_load_2d against
a GlobalLayout whose row stride is wider than its row -- the rank and
the stride a GEMM operand actually has. The padding is a bit pattern no
cell can take, so a wrong stride reports padding at a position rather
than a plausible neighbour.
GlobalLayout makes the GEMM's 2-D operands describable, so the examples
crate gets the launcher its README explained the absence of. gemm::check
runs [512,256]x[256,256]T on a B200 and compares every element against a
CPU reference with ==, not a tolerance: the operands are small integers,
so every product and every partial sum is exact in bf16 and fp32 alike.
Result: 512x256x256 exact.

Two things the run found that compiling never could:

- The kernel hung. Both CTAs' TMA loads complete on the leader's stage
  barrier, and the kernel mapped that address by hand -- but a plain
  cp.async.bulk.tensor completes on a barrier in the *issuing* CTA's
  shared memory, so the peer's 24 KiB never reached the leader's charge
  of 48 KiB. The fix is tma_load_2d_multicast_cg2 with the CTA's own bit
  as the whole mask onto Semaphore::multicast_alias: no replication,
  .shared::cluster barrier operand. That deletes the at_leader GAP
  block, and corrects README §8, which said this kernel could not use
  the multicast load.

- 72 KiB of dynamic shared memory needs the MAX_DYNAMIC_SHARED_SIZE_BYTES
  opt-in, which only cuda-oxide's prepared-launch path issues -- hence
  #[launch_contract] on the kernel.

modal_app.py gains an ::examples function and clippy over the examples
crate; README's status table, its #8 entry and its multicast item are
updated.
@feitreim
feitreim force-pushed the issue-8-global-layout branch from c6dd5eb to 3e12802 Compare July 27, 2026 23:00
@feitreim
feitreim merged commit 21247fd into main Jul 27, 2026
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.

Generalize the global layout beyond PanelMap

1 participant