Pidoku

Warp Specialization and Software Pipelining

Module 25 Lesson 25.b 1h 20m Difficulty 5/5

Prerequisites 25.a, 4.c, 6.c


Before you start: words you need#

WordPlain meaning
Software pipeliningRewriting a loop so that iteration i’s loads are issued while iteration i − 1’s maths runs, so the two overlap instead of taking turns.
StageOne slot in a ring of shared-memory buffers. With 4 stages, up to 4 tiles can be loading or waiting at once.
Prologue / steady state / drainThe start of a pipelined loop (fill the ring), the middle (one load in, one compute out per step), and the end (finish the last stages with no new loads).
Warp specializationGiving different warps of one CTA different jobs — one warp only loads, one only issues MMAs, others only run the epilogue — instead of every warp doing everything.
Producer / consumerThe role that fills a buffer (the load warp) and the role that empties it (the MMA warp, or the epilogue).
Register reallocationsetmaxnreg: at run time, producer warpgroups hand registers back and math warpgroups take them.
Ping-pongTwo math warpgroups that take turns: while one runs its MMAs, the other runs its epilogue or softmax.
EpilogueThe code after the mainloop that turns the accumulator into the output: scale, add bias, activation, convert, store.

1. What is it?#

Two techniques, used together in every fast Hopper and Blackwell kernel:

  • Software pipelining overlaps data movement with compute across loop iterations, using a ring of shared-memory stages (25.a showed why a Blackwell GEMM needs about 7 of them).
  • Warp specialization splits the CTA’s warps into roles, each running its own simple loop and talking to the others only through mbarriers. It makes the overlap reliable: the load warp never waits behind a slow MMA instruction, and the epilogue of one tile runs while the next tile’s mainloop is already going.
flowchart LR
  P["Producer warp<br/>TMA loads"] -->|"full[s]"| R["Shared-memory ring<br/>stages 0..S-1"]
  R -->|"operands"| M["MMA warp<br/>tcgen05.mma"]
  M -->|"empty[s]"| P
  M -->|"acc_full[b]"| A["TMEM accumulators<br/>2 buffers"]
  A --> E["Epilogue warpgroups<br/>load, convert, store"]
  E -->|"acc_empty[b]"| M
  S["Scheduler warp<br/>which tile next"] -.-> P
  S -.-> M
  S -.-> E
  class P,M,E compute
  class R,A memory
  class S queue

That diagram is, almost word for word, the structure of CUTLASS’s SM100 GEMM kernel, whose warp roles are named MMA, Sched, MainloopLoad, EpilogueLoad and Epilogue.


2. Why does it exist?#

Pipelining exists because HBM latency (hundreds of nanoseconds) is several times longer than one tensor-core step (about 140 ns on B200 for a 128 × 128 × 64 BF16 step). Without overlap, the tensor core is idle most of the time. Section 7’s model puts a single-stage loop at 16 % busy.

Warp specialization exists because “every warp does everything” scales badly on Hopper and Blackwell:

  • The asynchronous units are issued by one thread (TMA, tcgen05.mma). Having 256 threads execute a loop in which only lane 0 does the real work wastes issue slots.
  • A single instruction stream must order its own instructions. If the warp issues a load and then must wait for an MMA before it can issue the next load, the load stalls behind the MMA. Two warps with separate instruction streams do not block each other.
  • Registers are uneven. Math warpgroups need over 200 registers per thread (accumulators, softmax state); a load warp needs a few dozen. Without specialisation every warp is sized for the worst case, which limits occupancy.
  • Epilogues are long. Converting and storing a 128 × 256 tile takes about as long as several mainloop steps. Overlapping it with the next tile’s mainloop is a direct win when K is small, which is common in inference (decode GEMMs, MoE experts).

FlashAttention-3 (2024) was the paper that made this mainstream for attention: it reports 1.5–2.0× over FlashAttention-2 on H100, largely from warp specialisation and ping-pong (13.l).


3. Simple analogy#

A one-person food truck: the cook takes an order, shops for ingredients, cooks, plates and serves, one customer at a time. Every step waits for the previous one.

A restaurant line: a runner keeps the shelves stocked (producer), a line cook cooks from the shelves (MMA warp), a plater finishes dishes (epilogue), and a host decides which table is next (scheduler). Each has one job and a small set of signals (“shelf 3 is stocked”, “shelf 3 is empty”, “dish ready”). The cook is never shopping, so the stove is never idle.

Ping-pong is two line cooks sharing one stove: while one is at the stove, the other is plating.


4. Tiny example: a 4-stage ring, step by step#

Four stages, K split into 10 steps. “L” = load issued, “C” = compute, numbers are K-steps.

time →        t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   t10  t11  t12
producer      L0   L1   L2   L3   .    L4   L5   L6   L7   L8   L9
              (fills 4 stages)    (waits for empty[0])
MMA warp                     C0   C1   C2   C3   C4   C5   C6   C7   C8   C9
                             ↑ first data lands after the load latency

Prologue: the producer issues four loads without waiting. Steady state: every time the MMA warp finishes step i, the tensor core signals empty[i % 4], and the producer immediately reuses that stage for step i + 4. Drain: no loads after L9; the MMA warp finishes C6–C9.

The parity rule from 25.a makes this work with only 2 × 4 barriers. Stage s is used on rounds 0, 1, 2, …; round r waits on parity r mod 2. The producer starts by waiting on the empty barriers with parity 1, which an untouched barrier reports as already complete, so the first four loads go straight through.

In Gluon, the two loops look like this (from Triton’s 08-warp-specialization.py, shortened):

Python
@gluon.jit
def load_partition(p):                       # 1 warp, 24 registers
    state = Counter.create(1, num_stages)    # start on the "already empty" parity
    for k in range(0, K, BLOCK_K):
        mbarrier.wait(p.empty.index(state.index), state.phase)
        bar = p.ready.index(state.index)
        mbarrier.expect(bar, p.a_desc.block_type.nbytes + p.b_desc.block_type.nbytes)
        tma.async_load(p.a_desc, [off_m, k], bar, p.a_bufs.index(state.index))
        tma.async_load(p.b_desc, [k, off_n], bar, p.b_bufs.index(state.index))
        state = state.next()                 # index = (index+1) % S, flip phase on wrap

@gluon.jit
def mma_partition(p):                        # 1 warp, 24 registers
    state = Counter.create(0, num_stages)
    use_acc = False
    for k in range(0, K, BLOCK_K):
        mbarrier.wait(p.ready.index(state.index), state.phase)
        tcgen05_mma(p.a_bufs.index(state.index), p.b_bufs.index(state.index),
                    p.acc, use_acc=use_acc)
        tcgen05_commit(p.empty.index(state.index))   # tensor core frees the stage
        state = state.next()
        use_acc = True
    tcgen05_commit(p.acc_ready)

# in the kernel body: default partition = epilogue (4 warps), then the workers
gl.warp_specialize([
    (epilogue_partition, (p,)),
    (load_partition, (p,)),
    (mma_partition, (p,)),
], [1, 1], [24, 24])        # worker warps, worker register budgets

The tutorial’s own benchmark on a B200 (8192 × 8192, FP16) reaches 1,180–1,320 TFLOP/s against cuBLAS’s 1,300–1,430 for K from 1,024 to 16,384, with this structure plus a persistent grouped tile scheduler — the authors’ figures, on their GPU.


5. Technical explanation#

Pipelining without specialisation (Ampere style)#

On Ampere, the same warps load (with cp.async) and compute (with mma.sync). The loop is unrolled so that each iteration issues the load for step i + S − 1, waits until the copy for step i has landed (cp.async.wait_group S−2), and computes step i. Triton’s num_stages=3 does exactly this for you (6.e). It works well when the compute is issued by the same threads anyway, which is why Triton could do it automatically for years.

Specialised roles on Hopper#

CUTLASS’s Hopper GEMMs come in two warp-specialised schedules:

ScheduleWarpgroupsHow they share workGood for
KernelTmaWarpSpecializedCooperative1 producer + 2 consumersboth consumers work on the same tile (each takes half of M)large tiles, long K
KernelTmaWarpSpecializedPingpong1 producer + 2 consumerseach consumer owns a different tile; they alternate mainloop and epiloguesmall or medium K, heavy epilogues

Both use register reallocation: in CUTLASS’s ping-pong kernel the producer warpgroup calls warpgroup_reg_dealloc<40> (24 under heavy pressure) and the math warpgroups warpgroup_reg_alloc<232> (240). Those are setmaxnreg.dec and setmaxnreg.inc underneath. The SM’s 64 K registers per partition are fixed; reallocation only moves them between warpgroups.

Ping-pong, in attention and GEMM#

On Hopper, each consumer warpgroup runs MMA, then non-MMA work (epilogue in a GEMM, softmax in attention). With two consumers and a named barrier between them, their MMA phases are forced to alternate:

warpgroup 1:  [ MMA tile a ][ epilogue a ][ MMA tile c ][ epilogue c ]
warpgroup 2:                [ MMA tile b ][ epilogue b ][ MMA tile d ]
tensor core:  [   busy     ][   busy     ][   busy     ][   busy     ]

FlashAttention-3 uses this between the two warpgroups (softmax of one overlapping matmul of the other), and also overlaps within a warpgroup: it issues the next QKᵀ wgmma before computing the current softmax, and waits on it later.

Blackwell: fewer, simpler roles#

On Blackwell, tcgen05.mma is issued by one thread and accumulates into TMEM, so the MMA role becomes one warp, and the accumulator no longer occupies the epilogue’s registers. Ping-pong is replaced by double-buffered TMEM accumulators: the MMA warp writes accumulator 1 while the epilogue drains accumulator 0, synchronised by acc_full[b] / acc_empty[b] barriers. A typical CUTLASS or Gluon Blackwell GEMM uses:

warp 0          MMA (one elected lane issues tcgen05.mma)
warp 1          scheduler (persistent tile order; CLC on Blackwell, 25.j)
warp 2          TMA loads for A and B
warp 3          TMA loads for the epilogue's C/bias (if needed)
warps 4-7       epilogue warpgroup: tcgen05.ld, convert, fuse, TMA store

FlashAttention-4 extends the idea to attention with separate softmax and correction warpgroups (the correction one rescales the output accumulator off the critical path, 13.l).

What the compilers now do for you#

  • Triton (3.x) has automatic warp specialisation for Hopper and Blackwell matmul-like loops (tl.range(..., warp_specialize=True) and the num_stages / num_warps knobs), plus Gluon (25.d) for hand-written partitions with gl.warp_specialize.
  • CuTe DSL offers pipeline.PipelineTmaUmma (producer TMA, consumer tcgen05.mma) and pipeline.PipelineUmmaAsync (MMA → epilogue) objects, which hide the parity bookkeeping, and cutlass.range(..., prefetch_stages=N) to generate the prologue.
  • TileLang added automatic producer–consumer warp specialisation and T.Pipelined(..., num_stages=N) (March 2026 release notes).
  • Pallas Mosaic GPU has emit_pipeline_warp_specialized and set_max_registers; the JAX Blackwell matmul tutorial reports utilisation rising from about 45 % to about 72 % when warp specialisation is added.

6. Under the hood: a ring, its barriers and the parity bookkeeping#

For S stages there are 2S mbarriers plus 2 per accumulator buffer:

full[s]       init count 1   producer: arrive.expect_tx(bytes); TMA completes the bytes
empty[s]      init count 1   arrived by tcgen05.commit (or by consumer threads on Hopper)
acc_full[b]   init count 1   tcgen05.commit after the last K step of a tile
acc_empty[b]  init count E   arrived by each of the E epilogue warps (or threads) when done reading

producer state:   (index = 0, phase = 1)     # first wait on empty passes immediately
consumer state:   (index = 0, phase = 0)
next():           index += 1; if index == S: index = 0; phase ^= 1

Why the producer starts at phase 1: a freshly initialised barrier is “in phase 0, not complete”. try_wait.parity with parity 1 asks “has the phase before the current one completed?”, and the hardware treats that as true. This is a convention, not magic; CUTLASS’s PipelineState and Gluon’s tutorial Counter encode it the same way.

Persistence changes the counting. In a persistent kernel (25.e, 25.j) the ring is not reset between tiles: the producer just keeps going into the next tile’s K-steps, so the state counters run across all tiles a CTA processes. Mixing per-tile resets with a persistent ring is a classic hang.

Who arrives on empty differs by architecture:

  • Hopper: the consumer warpgroup arrives after wgmma.wait_group says the MMAs reading that stage have finished (often one stage behind, to keep one MMA batch in flight).
  • Blackwell: tcgen05.commit arrives when the tensor core is done, with no thread waiting at all.

7. Performance implications: a timing model#

This model runs one SM through 8 output tiles of 64 K-steps each, with B200-like numbers: 700 ns per TMA load, 140 ns per MMA step, 900 ns per epilogue. “Serial” means the same warps do the epilogue and then start the next tile; “overlapped” means separate epilogue warps and two accumulator buffers.

Go
// pipeline.go — a timing model of one SM running a GEMM mainloop with an
// S-stage shared-memory ring, with and without an overlapped epilogue.
package main

import "fmt"

const (
	loadNs  = 700.0 // HBM -> shared latency for one stage (TMA)
	mmaNs   = 140.0 // tensor-core time for one K-step (B200, 128x128x64 BF16)
	epiNs   = 900.0 // epilogue: TMEM -> registers -> convert -> TMA store
	kSteps  = 64    // K = 4096 in steps of 64
	tilesSM = 8     // output tiles this SM processes (persistent kernel)
)

// run returns the time to finish all tiles and the fraction of it the tensor core was busy.
func run(stages int, overlapEpilogue bool) (float64, float64) {
	n := tilesSM * kSteps
	loadDone := make([]float64, n)
	mmaDone := make([]float64, n)
	var lastMMA, epiFree, finish float64
	for i := 0; i < n; i++ {
		// The producer may refill stage i%stages once the MMA that used it (step i-stages) finished.
		issue := 0.0
		if i >= stages {
			issue = mmaDone[i-stages]
		}
		// Without overlap, the next tile's loads wait for the previous epilogue to finish.
		if !overlapEpilogue && i%kSteps == 0 && i > 0 {
			issue = max(issue, epiFree)
		}
		loadDone[i] = issue + loadNs
		start := max(loadDone[i], lastMMA)
		if !overlapEpilogue && i%kSteps == 0 && i > 0 {
			start = max(start, epiFree) // one warpgroup does mainloop and epilogue in turn
		}
		mmaDone[i] = start + mmaNs
		lastMMA = mmaDone[i]
		if i%kSteps == kSteps-1 { // tile finished: run its epilogue
			epiStart := max(lastMMA, epiFree)
			epiFree = epiStart + epiNs
			finish = epiFree
		}
	}
	busy := float64(n) * mmaNs
	return finish, busy / finish
}

func main() {
	fmt.Println("stages  epilogue     time (us)  tensor-core busy")
	for _, s := range []int{1, 2, 4, 7} {
		t, u := run(s, false)
		fmt.Printf("%6d  serial     %10.1f  %15.0f%%\n", s, t/1000, u*100)
	}
	for _, s := range []int{4, 7} {
		t, u := run(s, true)
		fmt.Printf("%6d  overlapped %10.1f  %15.0f%%\n", s, t/1000, u*100)
	}
}
stages  epilogue     time (us)  tensor-core busy
     1  serial          437.3               16%
     2  serial          223.4               32%
     4  serial          118.1               61%
     7  serial           84.5               85%
     4  overlapped      108.8               66%
     7  overlapped       73.3               98%

What it shows:

  • Stages are the first-order effect. Busy time grows almost linearly until there are enough stages to cover the latency (here ⌈700 / 140⌉ + 1 = 6–7).
  • Overlapping the epilogue is the second. With enough stages, the serial epilogue still costs about 13 points; overlapping it recovers them. The shorter K is, the bigger this share: with 8 K-steps instead of 64, the epilogue is as long as the mainloop.
  • Too few stages cannot be rescued by overlap (4 stages: 61 % → 66 %).

Real kernels lose a few more points to L2 misses, instruction issue and wave quantisation (25.e), but the ordering is right, and it is what profilers show: in Nsight Compute, a starved pipeline shows as tensor pipe utilisation well below 100 % with warps stalled on mbarrier waits (“long scoreboard” or “barrier” stalls).


8. Production implications#

  • Read the kernel name. CUTLASS and cuBLAS kernel names include the schedule (warpspecialized, cooperative, pingpong, 1sm / 2sm). If a production profile shows a non-specialised kernel on H100 or B200 for a hot GEMM, that is a lead.
  • Small-K, small-M inference GEMMs favour ping-pong or overlapped epilogues. Decode GEMMs and MoE expert GEMMs have short mainloops, so the epilogue is a big fraction. This is one reason inference-specific libraries (DeepGEMM, FlashInfer, TensorRT-LLM’s kernels) pick different schedules from training-oriented ones.
  • Warp-specialised kernels are harder to debug. A wrong parity shows as a hang (the GPU stops responding until the watchdog or the job timeout fires). Engines run new kernels under a test harness with timeouts before enabling them (25.l).
  • Shared-memory budgets are tight. Adding a fused epilogue that needs a staging buffer can cost a pipeline stage. A “fusion” that removes a pipeline stage can be slower than no fusion; measure.

9. Common mistakes#

  1. Producer and consumer starting on the same parity. One side deadlocks on the very first wait.
  2. Resetting the pipeline state per tile in a persistent kernel. The ring’s barriers keep their phase across tiles; the counters must too.
  3. Arrival counts that do not match the number of arrivers (for example acc_empty initialised with 1 but arrived by 4 epilogue warps, or the other way round).
  4. Giving the producer too many registers. Without setmaxnreg, math warps spill, and spills to local memory erase the gain from specialisation.
  5. Too many stages. More stages than the latency needs only steal shared memory from tile size or the epilogue.
  6. Doing real work in the producer warp. Address arithmetic or dequantisation in the load warp (instead of in TMA or a dedicated transform warpgroup) puts it back on the critical path.
  7. Measuring one problem size. Pipeline depth that is right for K = 8192 is wrong for K = 512.

10. Hands-on exercise#

  1. Run the Go model with kSteps = 8 (a short-K decode GEMM). How much does the overlapped epilogue gain now? At what epiNs does even 7 stages + overlap fall below 80 %?
  2. On a Hopper or Blackwell GPU, run Triton’s python/tutorials/gluon/08-warp-specialization.py. Change num_buffers from 2 to 4 and record TFLOP/s across K. Compare with the Go model’s shape.
  3. In CUTLASS (C++), build the Hopper example examples/49_hopper_gemm_with_collective_builder with KernelTmaWarpSpecializedCooperative and then KernelTmaWarpSpecializedPingpong for M = N = 4096, K ∈ {256, 4096}. Which wins at each K, and why?
  4. Profile one of them with ncu --set full. Find the stall reasons of the producer warp and of the math warps, and explain them.

11. Interview questions#

  1. Why does a fast Hopper or Blackwell GEMM split its warps into producer, MMA and epilogue roles instead of having every warp do everything?
  2. Explain the full/empty barrier ring. Why does the producer start waiting on parity 1?
  3. What does setmaxnreg do, and why is it essential for warp specialisation?
  4. Compare CUTLASS’s cooperative and ping-pong schedules. When does each win?
  5. On Blackwell, what replaces ping-pong, and why does TMEM make that possible?
  6. How many pipeline stages does a kernel need? Derive it from latency and per-step compute time.
  7. A warp-specialised kernel hangs on one GPU in a hundred runs. What do you check first?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in