Skip to content

feat(cuda-device): derive the m16n8k16 accumulator fragment layout - #474

Merged
nihalpasham merged 3 commits into
NVIDIA:mainfrom
honeyspoon:up/mma-fragment-layout
Jul 27, 2026
Merged

nihalpasham merged 3 commits into
NVIDIA:mainfrom
honeyspoon:up/mma-fragment-layout

Conversation

@honeyspoon

Copy link
Copy Markdown
Contributor

wmma::mma_m16n8k16_f32_f16 takes and returns [f32; 4], and those four values are not four adjacent elements of the output tile — each lane holds a scattered quarter of a 16x8 tile. The intrinsic's own docs give the mapping as index arithmetic the caller must reproduce, and its safety section warns that a different array order computes a different matrix operation.

That failure is silent: it produces a wrong product rather than an error. This derives the mapping once so call sites do not each re-derive it.

The layout is a mixed-radix numeral

Substituting the PTX row/col formulas into the row-major offset and regrouping:

offset = (group + 8*(j>>1))*8 + 2*tig + (j&1)
       = (j&1)*1 + tig*2 + group*8 + (j>>1)*64

digit    range   place   source
j & 1      2       1     fragment index, low bit
tig        4       2     lane % 4
group      8       8     lane / 4
j >> 1     2      64     fragment index, high bit

Place values are the running product of the lower ranges (1, 2, 8, 64), span 128. So the numeral is uniquely decodable, (lane, j) -> offset is injective, and since domain and codomain both have 128 points it is a bijection — the warp's fragments tile the output exactly, no overlap and no gap.

What makes this awkward to write by hand is that the fragment index is split across two non-adjacent digit positions, at places 1 and 64, interleaved with the lane digits. That is why j 0 and 1 differ by one column while j 0 and 2 differ by eight rows.

API

All const fn, no unsafe, no new dependencies.

Function Purpose
acc_coords(lane, j) position in the 16x8 tile
acc_offset(lane, j) row-major offset, in numeral form
acc_matrix_offset(..., tile_row, tile_col, row_stride) strided destination a GEMM epilogue writes; None on overflow
acc_decode(offset) the inverse

acc_decode is exported deliberately: a caller with an existing hand-rolled layout can round-trip it in a test and catch a disagreement cheaply, rather than discovering it as wrong numerics.

Verified against hardware, not only against its own tests

A bijection onto the wrong positions would pass every unit test here. So the check that matters ran real mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 on sm_86 (RTX A2000, CUDA 13.3), gathering A and B from the PTX ISA layouts, scattering the result with acc_coords, and comparing against a host matmul. Inputs are asymmetric and non-repeating so a transposed or half-swapped layout could not coincidentally match:

LAYOUT CORRECT  (0/128 mismatched, worst abs diff 0.00000)

That also validates the A and B fragment layouts indirectly — a wrong gather would have produced a wrong product.

Tests

Bijection via an ownership map (fails on both overlap and gaps), agreement between the numeral and row/col forms, decode as a true inverse over all 128 points, the two-position split of the fragment index, disjointness preserved under strided placement, and overflow rejection. 6 tests, fmt --check clean, zero warnings.

Scope

The C/D accumulator only. A and B are different numerals and would each need the same treatment. Only sm_86 was available to test on; the formulas come from the PTX ISA rather than from hardware probing, and the layout is part of the instruction's ISA contract, so I would not expect divergence — but it is untested elsewhere.

`wmma::mma_m16n8k16_f32_f16` takes and returns `[f32; 4]`, and those four
values are not four adjacent elements of the output tile: each lane holds a
scattered quarter of a 16x8 tile. The intrinsic's own docs state the mapping as
index arithmetic the caller must reproduce exactly, and the safety section
notes that a different array order computes a different matrix operation.
Getting it wrong does not fail - it silently computes a wrong product. This
derives the mapping once so call sites do not each re-derive it.

The layout is a mixed-radix numeral. Substituting the PTX row/col formulas into
the row-major offset and regrouping:

    offset = (group + 8*(j>>1))*8 + 2*tig + (j&1)
           = (j&1)*1 + tig*2 + group*8 + (j>>1)*64

    digit    range   place   source
    j & 1      2       1     fragment index, low bit
    tig        4       2     lane % 4
    group      8       8     lane / 4
    j >> 1     2      64     fragment index, high bit

Place values are the running product of the lower ranges (1, 2, 8, 64), span
128, so the numeral is uniquely decodable and (lane, j) -> offset is injective.
Domain and codomain both have 128 points, so it is a bijection: the warp's
fragments tile the output exactly, no overlap and no gap.

What makes this awkward by hand is that the fragment index is split across two
non-adjacent digit positions, at places 1 and 64, interleaved with the lane
digits - which is why j 0 and 1 differ by one column while j 0 and 2 differ by
eight rows.

Provides `acc_coords`, `acc_offset`, `acc_matrix_offset` for the strided
destination a GEMM epilogue writes, and `acc_decode` as the inverse, exported
so a caller can round-trip an existing hand-rolled layout in a test and catch a
disagreement cheaply. All `const fn`, no unsafe.

Verified against hardware, not only against its own unit tests: real
`mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32` on sm_86 with A and B
gathered from the PTX ISA layouts and the result scattered by `acc_coords`,
compared to a host matmul with asymmetric inputs so a transposed or half-swapped
layout could not coincidentally match. 128 of 128 elements, worst absolute
difference 0. A bijection onto the wrong positions would pass the unit tests; it
would not pass that.

Tests cover the bijection via an ownership map, agreement between the numeral
and row/col forms, decode as a true inverse over all 128 points, the
two-position split of the fragment index, disjointness under strided placement,
and overflow rejection.

Scope: the C/D accumulator only. A and B are different numerals and would each
need the same treatment, though the hardware check exercises them indirectly.

Signed-off-by: abder <[email protected]>
@nihalpasham nihalpasham added enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) labels Jul 27, 2026
…lice

The module docs linked to crate::thread::DisjointBlock and
crate::thread::DisjointTiling, which do not exist; cargo doc -D warnings
rejects the broken intra-doc links. The real analogous type is
crate::disjoint::DisjointSlice, so the analogy sentence now credits it
with the no-overlap half of the guarantee (DisjointSlice enforces
disjointness, not coverage) and notes the digits come from the numeral
structure rather than thread indexing.

Signed-off-by: nihalpasham <[email protected]>
…8 shapes

The fragment mapping mma_frag derives for m16n8k16 f16 is shared by
every m16n8 accumulator shape that hands each lane four 32-bit
registers. The in-repo docs for mma_m16n8k16_f32_bf16,
mma_m16n8k8_f32_tf32, and mma_m16n8k32_s32_s8 state the identical C/D
layout, so link them from the module docs and say the helpers apply to
those accumulators unchanged.

Signed-off-by: nihalpasham <[email protected]>
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks, nice way to pin this layout,

  • coordinate algebra checks out against the PTX ISA table and our own wmma docs.

I pushed two doc commits:

  • the disjointness analogy now points at the type that actually exists (crate::disjoint::DisjointSlice; the old intra-doc links are exactly why the docs check on this PR is red),
  • plus a note that the same C/D mapping covers all four-register m16n8 accumulator shapes. cargo doc -D warnings and the unit tests pass locally.

Merging.

@nihalpasham
nihalpasham merged commit 5c428ed into NVIDIA:main Jul 27, 2026
33 checks passed
nihalpasham added a commit to honeyspoon/cuda-oxide that referenced this pull request Jul 28, 2026
…he rebase

The predication commit was written against a pre-NVIDIA#474 version of the
module docs and its context hunks reverted two maintainer passages:
the paragraph stating the accumulator mapping also applies to the
bf16/tf32/s8 `m16n8` shapes, and the `crate::disjoint::DisjointSlice`
cross-reference. The replacement text also linked
`crate::thread::DisjointBlock` and `crate::thread::DisjointTiling`,
which do not exist, breaking rustdoc under -D warnings. Restore the
current main text; the additive predication section and its tests are
untouched.
nihalpasham added a commit that referenced this pull request Jul 28, 2026
…ent (#511)

* feat(mma_frag): predicate accumulator registers against a logical extent

Follows #474, which derived the layout. A tile shape rarely divides the
problem, and the accumulator makes the mismatch awkward: each lane's four
values are scattered across the tile, so clipping is not a contiguous prefix.
Two lanes disagree about the same register index.

At M = 9 against the 16-row tile, j 0 and 1 land on row `group` and are always
inside; j 2 and 3 land on row `group + 8` and are inside only for group 0. So
lanes 0..3 keep four registers and every other lane keeps two, which is
4*4 + 28*2 = 72 = 9 * 8 - the whole logical tile and nothing more.

The predicate is per register, so it is returned as a 4-bit mask: a kernel
tests one mask instead of recomputing bounds per store, and the warp stays
convergent because every lane evaluates the same shape.
`acc_mask_is_uniform` reports whether a lane is all-in or all-out, which is
what decides whether an epilogue can take one unpredicated path.

Masking cannot introduce a race: it removes registers from a bijection, so the
surviving stores stay pairwise disjoint. Asserted rather than argued, by
claiming each element and failing on a double claim.

Verified against hardware with the destination prefilled with a sentinel, which
is what distinguishes 'computed the right values' from 'suppressed the wrong
stores':

    valid rows written: 72 (expect 72)
    wrong values      : 0
    padding clobbered : 0

Tests sweep every extent from 0x0 to 16x8 and assert the valid count equals
rows * cols, so a wrong predicate surfaces as a wrong total rather than as
missing output. Column clipping is covered separately because it behaves
differently: columns come from `tig`, so a narrow extent removes whole lanes
rather than registers.

Signed-off-by: abder <[email protected]>

* docs(cuda-device): restore the mma_frag module-doc text reverted by the rebase

The predication commit was written against a pre-#474 version of the
module docs and its context hunks reverted two maintainer passages:
the paragraph stating the accumulator mapping also applies to the
bf16/tf32/s8 `m16n8` shapes, and the `crate::disjoint::DisjointSlice`
cross-reference. The replacement text also linked
`crate::thread::DisjointBlock` and `crate::thread::DisjointTiling`,
which do not exist, breaking rustdoc under -D warnings. Restore the
current main text; the additive predication section and its tests are
untouched.

* docs(cuda-device): correct the convergence claim in the predication notes

Predication does not by itself keep a warp convergent: the mask is
computed from straight-line expressions, but its value differs across
lanes, so stores guarded on mask bits can still diverge exactly as any
bounds check would. Say what the mask actually buys - fewer tests per
store and a uniform fast path when `acc_mask_is_uniform` holds for
every lane - instead of overclaiming convergence.

---------

Signed-off-by: abder <[email protected]>
Co-authored-by: Nihal Pasham <[email protected]>
@honeyspoon
honeyspoon deleted the up/mma-fragment-layout branch July 28, 2026 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants