KBench / agent /ref /ptx.md
ZMC2019's picture
agent/: Ada/Lovelace and Blackwell coverage, verified by compilation
7202032 verified
|
Raw
History Blame Contribute Delete
10.7 kB

PTX quick reference

Every instruction below was assembled with nvcc -arch=sm_90a on CUDA 12.8 — the toolchain in the task containers. Nothing here is from memory. Where something does not work, that is recorded too.

You reach for PTX when the compiler will not emit what you need: a specific cache policy, an async copy you want issued at a precise point, an MMA shape the C++ API does not expose, or a warpgroup instruction. For everything else, write CUDA C++ and read the SASS.

Inline asm syntax

asm volatile("instr.mod %0, [%1];" : "=f"(dst) : "l"(ptr) : "memory");
//            ^template              ^outputs   ^inputs     ^clobbers
constraint binds to
"f" / "d" .f32 / .f64 register
"r" / "l" .u32 / .u64 register — shared-memory addresses are "r" (32-bit), global are "l"
"h" .u16 (fp8 pairs, bf16 halves)
"=f" output, "+f" read-modify-write

volatile stops the compiler sinking or duplicating the instruction; add "memory" when it orders other accesses. Convert a shared pointer with __cvta_generic_to_shared(ptr) before passing it as "r".

Loads and stores — cache control

instruction effect
ld.global.nc.f32 read-only/__ldg path, uses the texture cache
ld.global.L2::128B.f32 prefetch a 128B L2 sector
ld.global.L1::no_allocate.f32 streaming: do not pollute L1
st.global.cs.f32 evict-first store — for data nobody reads again
ld.global.v4.f32 {a,b,c,d} one 128-bit transaction; the single most reliable bandwidth win

Vectorize first. A .v4.f32 (or .v4.b32 for two bf16x2) load moves 16B per instruction, quartering the instruction count and hitting the ideal 4 sectors/request that ncu reports.

Async copy (Ampere+) — cp.async

cp.async.ca.shared.global [%smem], [%gmem], 16;   // through L1
cp.async.cg.shared.global [%smem], [%gmem], 16;   // bypass L1, for streamed tiles
cp.async.commit_group;
cp.async.wait_group 1;                            // let 1 group stay in flight

Sizes are 4, 8 or 16 bytes; 16 is the one worth using. This is what double buffering is built from: issue group N+1, then wait_group 1 and compute on group N.

TMA (Hopper) — bulk tensor copy

cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes
    [%smem], [%tmap, {%x, %y}], [%mbar];
cp.reduce.async.bulk.tensor.2d.global.shared::cta.add.tile.bulk_group
    [%tmap, {%x, %y}], [%smem];      // accumulate a tile straight back to global

One thread issues the copy for the whole tile; the descriptor (%tmap) is built on the host with cuTensorMapEncodeTiled (see cuda-cpp.md). TMA does the address arithmetic, the bounds checking and the swizzle in hardware — this is why Hopper kernels spend so few instructions on addressing.

Barriers

instruction use
mbarrier.init.shared.b64 [%bar], %count initialise, once, by one thread
mbarrier.arrive.expect_tx.shared::cta.b64 arrival that also declares the incoming TMA byte count
mbarrier.try_wait.parity.shared::cta.b64 phase-flipping wait; the loop-friendly form
fence.proxy.async.shared::cta order async-proxy writes (TMA/wgmma) against generic ones
barrier.cluster.arrive / .wait Hopper cluster-wide sync

fence.proxy.async is the one people forget: TMA writes shared memory through a different proxy than ordinary stores, so without the fence your MMA can read a tile that is not there yet.

Tensor cores

Per-warp (mma.sync) — portable back to Ampere:

mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32  {d0..d3}, {a0..a3}, {b0,b1}, {c0..c3};
mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32  {d0..d3}, {a0..a3}, {b0,b1}, {c0..c3};

Warpgroup (wgmma, Hopper) — issued by 128 threads, operands read straight from shared memory via a 64-bit descriptor:

wgmma.fence.sync.aligned;
wgmma.mma_async.sync.aligned.m64nNk16.f32.bf16.bf16 {d...}, %desc_a, %desc_b, 1,1,1,0,0;
wgmma.commit_group.sync.aligned;
wgmma.wait_group.sync.aligned 0;

Accumulator size, measuredm64nNk16.f32 needs exactly N/2 f32 registers per thread:

shape acc regs/thread
m64n8k16 4
m64n16k16 8
m64n64k16 32
m64n128k16 64
m64n256k16 128

Getting this wrong is a compile error (Argument vector size mismatch), not a silent bug — but it also tells you the register budget up front: an m64n256k16 accumulator alone is 128 registers, half the architectural maximum, which is why big-N warpgroup tiles force warp specialisation.

Feeding the MMA:

ldmatrix.sync.aligned.m8n8.x4.shared.b16        {r0..r3}, [%smem];
ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16  {r0..r3}, [%smem];   // transposed, free
stmatrix.sync.aligned.m8n8.x4.shared.b16        [%smem], {r0..r3};

ldmatrix loads a fragment in exactly the layout the MMA wants. .trans transposes for free — never transpose in registers by hand.

Warp-level

instruction note
shfl.sync.bfly.b32 butterfly reduction: log2(32) = 5 steps
redux.sync.add.u32 whole-warp integer reduction in one instruction (sm_80+)
elect.sync pick one leader lane — cheaper than laneid == 0
vote.sync.ballot.b32 predicate mask across the warp

Warp specialisation (Hopper)

setmaxnreg.dec.sync.aligned.u32 24;    // producer warps: give registers back
setmaxnreg.inc.sync.aligned.u32 232;   // consumer warps: take them

This is the mechanism behind producer/consumer kernels: DMA warps need almost no registers, MMA warps need a great many, and the register file is redistributed at runtime rather than sized for the worst case.

Scheduling and math

instruction note
griddepcontrol.wait / .launch_dependents programmatic dependent launch — overlap the tail of one kernel with the head of the next
nanosleep.u32 N back off inside a spin loop; without it, spinning starves the warps you are waiting on
ex2.approx.f32 the softmax primitive — compute exp(x) as ex2(x * 1.4427); far cheaper than exp
rcp.approx.f32, rsqrt.approx.f32, tanh.approx.f32 fast paths for normalisation and gelu
cvt.rn.satfinite.e4m3x2.f32 pack two floats into fp8x2 with saturation, one instruction
cvt.rn.bf16x2.f32 pack two floats into bf16x2

Atomics

red.global.add.f32 [%p], %v;             // fire-and-forget: no return value, no latency to hide
atom.global.add.v2.f32 {%d0,%d1}, [%p], {%v0,%v1};   // vector atomic

Use red whenever you discard the old value — atom makes the warp wait for a result you never read.

Architecture matrix — what assembles where

Compiled against CUDA 12.8 for each target. yes means it assembles, which is a lower bound on availability, not a statement about speed: only sm_90 hardware was available to run on here.

instruction sm_89 Ada sm_90a Hopper sm_100a Blackwell DC sm_120a Blackwell RTX
cp.async.cg yes yes yes yes
cp.async.bulk.tensor (TMA, 2d and 5d) yes yes yes
mbarrier.init yes yes yes yes
mbarrier.arrive.expect_tx yes yes yes
barrier.cluster yes yes yes
fence.proxy.async yes yes yes
mma.sync m16n8k16 bf16 yes yes yes yes
mma.sync m16n8k32 fp8 e4m3 yes yes yes yes
ldmatrix.x4 yes yes yes yes
stmatrix.x4 yes yes yes
wgmma.mma_async yes
tcgen05.* (mma / alloc / ld / fence) yes
cvt e4m3x2 (fp8) yes yes yes yes
cvt e2m1x2 (fp4) yes yes
cvt e2m3x2 / e3m2x2 (fp6) yes yes
cvt.rz ue8m0x2 (MX block scale) yes yes
setmaxnreg yes yes yes
griddepcontrol (PDL) yes yes yes
redux.sync.add yes yes yes yes
elect.sync yes yes yes

Three consequences worth internalising:

wgmma is Hopper-only. It does not assemble for Blackwell. A warpgroup GEMM written for sm_90a will not compile for sm_100a — Blackwell replaces it with tcgen05, which uses a separate tensor memory space rather than accumulating in registers. Portable code needs both paths, or falls back to mma.sync, which assembles everywhere from Ada up.

tcgen05 is datacenter-only. It assembles for sm_100a (B100/B200) but not sm_120a (RTX 50-series / RTX PRO). Consumer Blackwell tops out at mma.sync + TMA — do not assume "Blackwell" implies 5th-gen tensor cores. Its accumulator lives in tensor memory, a dedicated on-chip lanes × columns store (128 rows × 512 columns of 32-bit cells per CTA on sm_100a, per PTX ISA §9.7.16.1), allocated with tcgen05.alloc and read back with tcgen05.ld — not in registers. So the register-budget arithmetic that sizes a Hopper wgmma tile does not transfer. Note the Blackwell tuning guide does not cover tcgen05; PTX ISA §9.7.16 is the reference.

Ada (sm_89) is an Ampere-class programming model with fp8 arithmetic. It has the fp8 mma.sync, but no TMA, no clusters, no stmatrix, no setmaxnreg, no elect.sync, no transaction barriers. Every Hopper structural technique — TMA choreography, warp specialisation with register reallocation, cluster-wide barriers — is unavailable. On Ada the wins come from cp.async double buffering, ldmatrix + mma.sync, vectorised access, and fp8.

Narrow-precision syntax traps (measured)

  • e2m1x2 (fp4) packs into 8 bits, and PTX has no 8-bit inline-asm constraint. You must declare the register inside the asm block: { .reg .b8 t; cvt.rn.satfinite.e2m1x2.f32 t, %1, %2; cvt.u16.u8 %0, t; }
  • ue8m0x2 accepts .rz only. .rn fails with "Illegal rounding modifier".
  • Getting these wrong reports as "Arguments mismatch", which reads like the instruction is missing when it is actually present. Check the destination register type before concluding an instruction is unavailable on your target.

Run python3 tools/check_toolchain.py [arch] to regenerate this table for your own machine and toolkit.

Verifying what you wrote

nvcc -arch=sm_90a -cubin -o /dev/null probe.cu     # does it assemble?
cuobjdump -sass kernel.cubin | grep -E "HMMA|QGMMA|LDL|STL"

LDL/STL in the SASS means registers spilled. Zero HMMA/QGMMA where you expected tensor cores means the MMA never issued — the commonest cause of a "why is my kernel at 5% of peak".