Inside FlashInfer's SM100 GEMM, Part 2: Keeping the Tensor Cores Busy
How FlashInfer's block-scaled FP4 GEMM splits its warps into roles, passes stages and accumulators between them with mbarriers, loops persistently over output tiles, and shares loads inside a cluster
Series: Part 1 · Part 2 · Part 3
In part 1, we looked at the computation of FlashInfer's SM100 block-scaled GEMM: one tcgen05.mma instruction, issued by one thread, multiplies a tile of FP4 values from shared memory, applies the scale factors from tensor memory (TMEM) and accumulates into TMEM. A 256 x 256 output tile of an 8,192-deep matrix product takes 128 of those instructions, and we saw that the tile shape mostly matters through how many FLOPs it gets out of every byte it loads.
What we skipped is everything around the instruction. Before the MMA warp can issue the four instructions of a K tile, the operands of that K tile have to be in shared memory, and when the MMA warp is done with them, the shared memory has to be refilled with the next K tile. When all 128 instructions of a tile are done, the accumulator in TMEM has to be read out, scaled, converted to bf16 and stored, and the next tile can't start overwriting the accumulator before that has happened. And somebody has to decide which SM computes which tile.
In this part, we'll go through how the kernel organizes all of this. The short version is that it runs three things at the same time, loading, multiplying and storing, on different warps, and that it connects them with two ring buffers of mbarriers. Then we'll look at the persistent loop over tiles and at clusters, and I'll show measurements of how much each of these pieces is worth on a B300. As in part 1, everything refers to FlashInfer at c0e62fa7b and CuTe DSL 4.8.0, and every measured output was bit-identical to FlashInfer's CUTLASS backend.
1. Three Engines and Six Warps
1.1 Why Everything Is Asynchronous
On an SM100 GPU, the three steps of a GEMM run on three different pieces of hardware. The TMA unit copies tiles from global memory into shared memory. The tensor cores multiply. And the CUDA cores, the SM's ordinary arithmetic units, do the epilogue: they read the accumulator from TMEM into registers, multiply by the global scale, convert to bf16 and write the result back out, again with the TMA's help. Each of these units is asynchronous: a thread starts a TMA copy or an MMA, and the hardware works on it while the thread continues.
If the kernel did these steps one after the other for every K tile, each unit would sit idle while the others work. What we want instead is the picture on the right of Figure 1: while the tensor cores multiply K tile i, the TMA is already loading K tile i + 1 and i + 2, and while the epilogue stores tile t, the tensor cores are already working on tile t + 1.
The way to get there is to give each unit its own warp, which only issues work to that unit and waits for the others when it has to. This is called warp specialization.
1.2 The Six Warps
FlashInfer's kernel uses six warps, 192 threads per CTA, and one CTA per SM (the kernel asks for all the shared memory, so no second CTA would fit anyway). The roles are fixed in the constructor:
# excerpt from dense_blockscaled_gemm_sm100.py
self.epilog_warp_id = (
0,
1,
2,
3,
)
self.mma_warp_id = 4
self.tma_warp_id = 5
- Warp 5, the TMA warp, issues the TMA loads of A, B, SFA and SFB for every K tile, one elected thread per copy.
- Warp 4, the MMA warp, copies the scale factors from shared memory into TMEM and issues the MMA instructions, both from a single thread.
- Warps 0 to 3, the epilogue warps, read the accumulator out of TMEM. It takes four warps because of a TMEM rule from the memory-hierarchy article: each warp can only access its own quarter of TMEM's 128 lanes, and since the accumulator's 128 rows are the lanes, four warps together cover the tile.
The first epilogue warp also allocates TMEM at the start: all 512 columns, with is_two_cta=True when the CTAs work in pairs, since the two CTAs of a pair have to allocate together. The allocation instruction writes the TMEM address into a word of shared memory, and the MMA warp and the epilogue warps read it from there after a named barrier for their 160 threads. The TMA warp never touches TMEM, so it doesn't take part.
Each warp then runs its own loop over the same sequence of output tiles, and the three loops have to stay in step. That's what the mbarriers are for.
2. The Operand Ring
2.1 Stages and Two Barriers per Stage
The shared memory for the operands is organized as a ring of stages. A stage holds one K tile: A, B, SFA and SFB, 38 KB per CTA for the 256 x 256 tile, as we computed in part 1. The TMA warp fills the stages in order, wrapping around at the end, and the MMA warp consumes them in the same order.
Every stage has two mbarriers. An mbarrier is an 8-byte object in shared memory that counts arrivals: it's initialized with an expected number of arrivals, and when that many have arrived, it completes its current phase and starts the next one. A thread can wait on an mbarrier until a given phase has completed. The two barriers of a stage are:
- full: completes when all bytes of the stage have arrived. The TMA warp announces how many bytes to expect (77,824 for the 256 x 256 tile, the bytes of both CTAs of the pair, since all the pair's copies complete on the leader's barrier), and each TMA copy counts its bytes off as they land. The MMA warp waits on it.
- empty: completes when the tensor cores are done reading the stage. The MMA warp arrives on it, and the TMA warp waits on it before it overwrites the stage.
In the kernel, the pair of barriers and the logic around them is CuTe DSL's PipelineTmaUmma (UMMA is CUTLASS's name for the tcgen05 MMA). Figure 2 shows the ring for five stages.
2.2 The Phase Bit
There is one subtlety. Since the ring wraps around, stage 0 is filled for K tile 0, then again for K tile 5, then for K tile 10, and so on. When the MMA warp waits for "stage 0 is full", it has to say which time it means, or it would happily consume the K tile 0 data a second time. An mbarrier solves this with a phase bit: every time the barrier completes, its phase flips between 0 and 1, and a wait names the phase it is waiting for. So each side of the ring keeps a small state of (stage index, phase), and flips its phase whenever its index wraps around. In CuTe DSL, that's PipelineState, and the TMA warp's state starts with phase 1 while the MMA warp's starts with phase 0, which means that on the first lap, the producer finds every stage already "empty".
Here's the whole mechanism in plain Python, with a random interleaving of the two warps standing in for the hardware:
import random
class Barrier: # an mbarrier: an arrival count and a phase bit
def __init__(self, count):
self.count, self.pending, self.phase = count, count, 0
def arrive(self):
self.pending -= 1
if self.pending == 0: # the last arrival completes the phase
self.pending, self.phase = self.count, self.phase ^ 1
def done(self, phase): # has the phase with this parity completed?
return self.phase != phase
class State: # (stage index, phase) for one side of the ring
def __init__(self, stages, phase):
self.stages, self.index, self.phase = stages, 0, phase
def advance(self):
self.index += 1
if self.index == self.stages:
self.index, self.phase = 0, self.phase ^ 1
And the two loops, one step at a time:
def simulate(k_tiles=12, stages=5, seed=0):
rng = random.Random(seed)
full = [Barrier(1) for _ in range(stages)]
empty = [Barrier(1) for _ in range(stages)]
tma, mma = State(stages, phase=1), State(stages, phase=0)
slot, loaded, used = [None] * stages, 0, []
while len(used) < k_tiles:
if rng.random() < 0.5 and loaded < k_tiles: # the TMA warp
if empty[tma.index].done(tma.phase):
assert slot[tma.index] is None # never overwrite
slot[tma.index] = loaded
loaded += 1
full[tma.index].arrive() # the TMA's bytes landed
tma.advance()
elif full[mma.index].done(mma.phase): # the MMA warp
used.append(slot[mma.index])
slot[mma.index] = None
empty[mma.index].arrive() # the tensor cores are done
mma.advance()
return used
print(all(simulate(seed=s) == list(range(12)) for s in range(100)))
For 100 random interleavings, the MMA side consumes K tiles 0 to 11 in order, and the TMA side never overwrites a stage that hasn't been consumed, so this prints True. If you change the TMA warp's starting phase to 0, the very first wait never succeeds and the loop hangs, which is a good way to convince yourself why the two sides start out of phase.
2.3 Who Arrives on Which Barrier
In the simulation, the arrivals are ordinary function calls. In the kernel, they're done by the hardware, and that's where it gets interesting.
The full barrier is completed by the TMA itself: the TMA warp first arrives once and announces the expected bytes (producer_acquire does both, with arrive_and_expect_tx), and then every TMA copy that lands decrements the byte count. The barrier completes when the count reaches zero. That way, the MMA warp doesn't need to know how many copies there were or which CTA issued them.
The empty barrier is completed by the tensor cores. The MMA warp can't simply arrive on it after issuing the four MMAs of a stage, because the instructions are asynchronous and might still be reading shared memory at that point. Instead, consumer_release becomes a tcgen05.commit, which asks the tensor cores to arrive on the barrier once all MMAs issued so far have finished. In the 2-CTA case, the commit is multicast to both CTAs of the pair, since both CTAs' stages were read.
Here are the two halves in the kernel. The TMA warp's loop, cut down:
# excerpt from dense_blockscaled_gemm_sm100.py
for k_block in cutlass.range(0, k_block_cnt, 1, unroll=1):
# Conditionally wait for AB buffer empty
ab_pipeline.producer_acquire(
ab_producer_state, peek_ab_empty_status
)
# TMA load A/B/SFA/SFB
cute.copy(
tma_atom_a,
tAgA_slice[(None, ab_producer_state.count)],
tAsA[(None, ab_producer_state.index)],
tma_bar_ptr=ab_pipeline.producer_get_barrier(ab_producer_state),
mcast_mask=a_full_mcast_mask,
cache_policy=a_cache_policy,
)
# ... the same for B, SFA and SFB
# Peek (try_wait) AB buffer empty for k_block = prefetch_k_block_cnt + k_block + 1
ab_producer_state.advance()
peek_ab_empty_status = cutlass.Boolean(1)
if ab_producer_state.count < k_block_cnt:
peek_ab_empty_status = ab_pipeline.producer_try_acquire(
ab_producer_state
)
and the MMA warp's, which we saw in part 1:
# excerpt from dense_blockscaled_gemm_sm100.py
for _k_block in range(k_block_cnt):
if is_leader_cta:
# Conditionally wait for AB buffer full
ab_pipeline.consumer_wait(
ab_consumer_state, peek_ab_full_status
)
# ... copy SFA/SFB into TMEM, issue 4 MMAs
# Async arrive AB buffer empty
ab_pipeline.consumer_release(ab_consumer_state)
Notice the "peek" in both loops. Right after advancing to the next stage, each warp already does a non-blocking try_wait on the next barrier and keeps the result. If the barrier had already completed, the next iteration skips the blocking wait altogether. It's a small optimization, but this loop runs once per K tile on the critical path, so the saved cycles add up.
2.4 How Many Stages?
The deeper the ring, the further ahead the TMA warp can run, and the more latency it can hide. The kernel simply uses as many stages as fit into shared memory. _compute_stages reserves 1 KB for the barriers and two output buffers for the epilogue, gives the rest to as many operand stages as fit, and then hands whatever is left over to more output buffers. Here's the same arithmetic:
SMEM = 232448 # bytes of shared memory one CTA can use on sm_100
def stages(stage_bytes, c_stage_bytes, reserved=1024):
ab = (SMEM - reserved - 2 * c_stage_bytes) // stage_bytes
left = SMEM - reserved - 2 * c_stage_bytes - ab * stage_bytes
return ab, 2 + left // c_stage_bytes
print(stages(38912, 8192)) # 256 x 256 tile
print(stages(22528, 4096, reserved=1024 + 512)) # 128 x 16 tile
For the 256 x 256 tile, this gives 5 operand stages and 4 output buffers, and for the 128 x 16 tile that FlashInfer uses for decoding (its stages are only 22 KB, and narrow tiles reserve 512 bytes more for the scale factors, as we'll see in part 3), 9 stages and 6 output buffers. Both are exactly what the kernel computes.
Is it worth having that many? To find out, I capped the number of stages without changing anything else (by overriding _compute_stages in a subclass of the kernel), for two cases: the 256 x 256 tile on an 8,192-cubed problem, and the 128 x 16 tile on a decoding step with 16 tokens for GLM-5.3's gate and up projection (N = 24,576, K = 6,144). Figure 3 shows the result.
As we can see in Figure 3, a ring with a single stage is 2.6 to 3 times slower, since the TMA and the tensor cores then simply take turns. For the large GEMM, every additional stage helps, from 474 microseconds with one stage to 160 with five, and the kernel is still gaining at the point where shared memory runs out. The decoding step behaves differently: it improves quickly up to about six stages and then flattens out at about 19.8 microseconds. That's because this step is limited by how fast the 85 MB of FP4 weights and their scale factors can be read from HBM, and once enough loads are in flight to keep HBM busy, more stages don't add anything. (This is Little's law again, from the TMA article: bytes in flight = bandwidth x latency.)
3. The Accumulator Handoff
3.1 A Second Ring, in TMEM
The same producer-consumer idea connects the MMA warp with the epilogue warps, with the accumulator in TMEM in place of the shared-memory stages. When the MMA warp has issued the last instruction of a tile, it commits on the accumulator's "full" barrier, and the epilogue warps wait for it. When the epilogue warps have read the accumulator out, they arrive on its "empty" barrier, and the MMA warp waits for that before it starts the next tile in the same TMEM columns. This is CuTe DSL's PipelineUmmaAsync.
With only one accumulator, the tensor cores would sit idle while the epilogue reads it out. So, if the tile is narrow enough, the kernel keeps two accumulators in TMEM and alternates between them: for N tiles up to 192, two accumulators of N columns fit into TMEM's 512 columns next to the scale factors. _compute_stages sets num_acc_stage = 1 if mma_tiler_mnk[1] == 256 else 2.
3.2 Two Accumulators That Overlap
The 256-wide tile is the problem case, since two accumulators of 256 columns take all 512 columns and leave none for the scale factors, which need 48 (16 for SFA and 32 for SFB). The kernel's answer, which I described in detail in the memory-hierarchy article, is to let the two accumulators overlap: the second one starts at column 256 - 48 = 208 instead of 256, so the accumulators of consecutive tiles share 48 columns.
That only works if the epilogue reads the shared columns first. The epilogue reads the accumulator in subtiles of 32 columns, and for the accumulator in columns 0 to 255 it walks backwards (from column 255 down), for the one in columns 208 to 463 forwards. After the first two subtiles, which cover the 48 shared columns, it releases the accumulator early, which lets the MMA warp start the next tile while the epilogue reads the remaining 192 columns:
# excerpt from dense_blockscaled_gemm_sm100.py
if cutlass.const_expr(self.overlapping_accum):
if subtile_idx == self.iter_acc_early_release_in_epilogue:
# Fence for TMEM load
cute.arch.fence_view_async_tmem_load()
with cute.arch.elect_one():
acc_pipeline.consumer_release(acc_consumer_state)
acc_consumer_state.advance()
iter_acc_early_release_in_epilogue is 48 // 32 = 1, so the release happens as soon as subtile 1 has been loaded into registers. Figure 4 shows the TMEM columns and the order in which the epilogue reads them.
How much does the early release buy? To measure it, I moved the release to the last subtile, which turns the overlapping accumulators into what amounts to a single accumulator (the next tile can only start when the whole tile has been read), and ran both versions alternately five times each. For the 8,192-cubed problem, the early release takes the kernel from 162.9 to 157.7 microseconds, 3.3% faster. For GLM-5.3's gate and up projection with 8,192 tokens, it's 397.5 against 375.1 microseconds, 6.0% faster. That's roughly the time the tensor cores would otherwise spend waiting for the epilogue, once per tile.
3.3 The Epilogue in Brief
I went through the epilogue instruction by instruction in the memory-hierarchy article, so here is only the outline. For each 32-column subtile, each of the 128 epilogue threads loads 32 fp32 values of its row from TMEM, multiplies them by alpha (the NVFP4 global scale) in fp32, converts them to bf16 and writes them to one of the output buffers in shared memory; then one thread issues a TMA store of the subtile to global memory. The output buffers form a third ring, which only needs the TMA's bulk-store bookkeeping (PipelineTmaStore) instead of barriers: before the epilogue reuses a buffer, it waits until at most a few stores are still in flight.
4. The Persistent Loop
4.1 One CTA per SM, Many Tiles per CTA
So far, I've written "the next tile" without saying where it comes from. In a classic GEMM kernel, you launch one CTA per output tile, and the hardware schedules the CTAs onto SMs. FlashInfer's kernel is persistent instead: it launches only as many CTAs as can run at the same time, one per SM, and each of them loops over many output tiles. That's what lets the overlapped accumulators work at all, since the next tile has to be computed by the same CTA, while its epilogue is still busy with the previous one. It also saves the setup of every CTA (barrier initialization, TMEM allocation, descriptor prefetches) for all but the first tile.
How many CTAs? The host asks the driver how many clusters of the requested size can be resident at once (get_max_active_clusters), and the grid is that many clusters, or fewer if the problem has fewer tiles. On the B300, with one CTA per SM, that's 148 single CTAs, or 74 clusters of two.
4.2 Which Tiles a Cluster Gets
The scheduler, CuTe DSL's StaticPersistentTileScheduler, is simple. It numbers the work units, one per cluster's worth of output tiles, in M-major order (down the columns of the output first), and cluster c takes units c, c + G, c + 2G, and so on, where G is the number of clusters in the grid. Since each cluster computes its tile with all its CTAs, the CTA inside the cluster adds its own coordinate to get its own part. In Python:
def schedule(units_m, units_n, clusters):
work = {c: [] for c in range(clusters)}
for c in range(clusters):
unit = c # every cluster starts at its own index
while unit < units_m * units_n:
work[c].append((unit % units_m, unit // units_m)) # M first
unit += clusters # then strides by the grid size
return work
work = schedule(32, 32, 74) # 8192 x 8192 in 256 x 256 tiles, 74 pairs
print(len(work[0]), len(work[73]), work[0][:3])
For the 8,192 x 8,192 output with 256 x 256 tiles and 74 CTA pairs, there are 1,024 tiles, so clusters 0 to 61 get 14 tiles each and clusters 62 to 73 get 13. Cluster 0 computes tiles (0, 0), (10, 2) and (20, 4) first: since 74 isn't a multiple of 32, consecutive tiles of one cluster jump around the matrix. Figure 5 shows the first two rounds.
As shown in Figure 5, the clusters of one round compute a band of a little over two columns of tiles, so they all read the same few column blocks of B and every row block of A at the same time, which is good for L2 reuse. The last round has only 62 tiles for 74 pairs, so 12 pairs, 16% of the GPU, sit idle for one tile at the end. This "wave quantization" is one of the things the tactic heuristic in part 3 tries to minimize.
Two small things complete the picture. The scheduler counts how many tiles each CTA has executed (num_tiles_executed), and the epilogue uses that count to keep cycling through its output buffers across tiles. And the kernel supports programmatic dependent launch (PDL): it calls griddepcontrol_wait before it touches global memory and griddepcontrol_launch_dependents at the very end, so that when mm_fp4 launches with PDL enabled (its default), the next kernel can start its own setup while this one finishes.
5. Clusters and Multicast
5.1 What a Cluster Shares
In part 1, the cluster was just the container of the CTA pair. A larger cluster lets the CTAs share loads. Picture a 2 x 2 cluster of 256 x 256 tiles, that is, two CTA pairs side by side along N. Both pairs compute the same 256 rows of the output, so they need the same A tile, and they need different B tiles. Without a cluster, each pair would load that A tile from L2 on its own. With the cluster, each CTA loads half of its A slice and multicasts it, which means that the TMA writes the data into the shared memory of every CTA in the same cluster row, at the same offset, with one read from L2. The same goes for B along M when the cluster has more than one pair along M. (For the TMA mechanics of multicast, see the TMA article.)
In the kernel, this is all in the multicast masks and the arrival counts. Every TMA copy carries a mask of the CTAs it writes to (a_full_mcast_mask, computed by create_tma_multicast_mask from the cluster layout), and since a CTA's stage now contains data that other CTAs loaded, the stage is only free when every CTA that reads it is done. That's why the empty barrier expects num_mcast_ctas_a + num_mcast_ctas_b - 1 arrivals, and why tcgen05.commit is multicast to the same CTAs.
5.2 Bigger Clusters Are Not Free
So shouldn't the kernel always use the largest cluster? Each step up halves the L2 reads for one operand. But a cluster has to fit entirely into one GPC (a group of SMs that share some hardware), and the SMs of the B300 don't divide evenly into large clusters. When I asked the driver how many clusters fit at once, I got 148 single CTAs, 74 clusters of 2, 33 clusters of 4 (132 SMs), 15 clusters of 8 (120 SMs) and 7 clusters of 16 (112 SMs). So, a cluster of 16 leaves a quarter of the GPU idle.
Here's what that does to the 8,192-cubed problem with the 256 x 256 tile:
- 2 x 1 (one pair, 148 SMs): 158.1 microseconds.
- 2 x 2 (2 pairs, 132 SMs): 172.9.
- 4 x 1 (2 pairs, 132 SMs): 173.9.
- 4 x 2 and 2 x 4 (4 pairs, 120 SMs): 185.1 and 189.0.
- 4 x 4 (8 pairs, 112 SMs): 196.1.
The cluster of two is the fastest, and the larger clusters lose about as much time as the share of SMs they leave idle: the clusters of 4 run on 11% fewer SMs and take 9 to 10% longer, and the cluster of 16 runs on 24% fewer SMs and takes 24% longer. My reading is that for this compute-bound problem, L2 bandwidth isn't what limits the kernel (A and B are read from L2 many times either way, since each 256-row block of A is needed by all 32 column tiles), so the saved L2 reads can't make up for the lost SMs. I'd expect multicast to pay off where loading is the bottleneck, which is more likely with small tiles or small problems, and that's why the cluster shape is one of the knobs the autotuner searches over in part 3. (I also measured the 128 x 256 single-CTA tile with all nine cluster shapes: the best was 2 x 1 at 192.0 microseconds, and 4 x 4 was the slowest at 274.3.)
There is a practical lesson in those numbers, too. The number of clusters per wave is something the kernel gets from the driver at compile time, and FlashInfer has a fallback for when the driver query fails: it then assumes as many clusters as SMs, for every cluster size. I hit that fallback in a fresh Python process, when I called the query before anything had created a CUDA context: it returned 148 for every cluster size, with a warning. A kernel compiled with that value would launch more clusters than can be resident at once. All kernels in this article were compiled with the real values, but it's worth knowing that the grid size depends on this query.
6. Summary
To summarize, here is how FlashInfer's SM100 GEMM keeps the tensor cores busy:
- Warp specialization. Six warps per CTA: one issues TMA loads, one issues the scale-factor copies and the MMAs, and four read out the accumulator, since each warp can only reach a quarter of TMEM's lanes.
- The operand ring. Shared memory holds as many K tiles (stages) as fit, 5 for the 256 x 256 tile and 9 for the 128 x 16 tile. Each stage has a full barrier completed by the TMA's byte count and an empty barrier completed by
tcgen05.commit, and a phase bit tells the laps of the ring apart. One stage instead of five made the large GEMM three times slower. - The accumulator ring. Two accumulators in TMEM, or for 256-wide tiles two overlapping ones with an early release after the shared 48 columns, which was worth 3 to 6% at large sizes.
- The persistent loop. One CTA per SM (or one cluster per two SMs), each looping over tiles in M-major order with a stride of the grid size. The last partial round is the wave quantization that part 3 cares about.
- Clusters. Multicast saves L2 reads, but clusters must fit into a GPC, so on a B300 a cluster of 4 uses 132 SMs and a cluster of 16 only 112. For a large compute-bound GEMM, the cluster of two was the fastest.
In part 3, we'll put all these knobs together into what FlashInfer calls a tactic, and look at how mm_fp4 picks one for a given matrix shape: tile and wave quantization, swapping A and B for small batches, the narrow N tiles, split-K, and the right way to time all of it.
Sources
- FlashInfer's SM100 block-scaled GEMM (dense_blockscaled_gemm_sm100.py)
- FlashInfer's shared helpers for it (dense_blockscaled_gemm_sm100_common.py)
- CUTLASS CuTe DSL (pipelines and the persistent tile scheduler)
- PTX ISA: mbarrier
- PTX ISA: tcgen05.commit
- CUDA Programming Guide: thread block clusters
- Using TMA Load, Prefetch, and Multicast Load in CuTe DSL
- The SM100 Memory Hierarchy, from HBM to Tensor Memory