# Inside FlashInfer's SM100 GEMM *FlashInfer's block-scaled FP4 GEMM for Blackwell, taken apart in three parts: the tile and the instruction, the pipeline around it, and how a tactic is chosen.* ## Inside FlashInfer's SM100 GEMM, Part 1: The Tile and the Instruction *What one tcgen05.mma computes in FlashInfer's block-scaled FP4 GEMM, how the tiles nest from that instruction up to the whole matrix, and where the scale factors go* If you open FlashInfer's NVFP4 GEMM for Blackwell, `dense_blockscaled_gemm_sm100.py`, you find about 2,000 lines of CuTe DSL. It's the kernel that `flashinfer.mm_fp4(..., backend="cute-dsl")` runs on B200 and B300 GPUs, which makes it one of the kernels that sit under the FP4 linear layers of a serving engine. And yet, the actual math in it fits on one line: multiply two matrices of 4-bit numbers, each with its own little scale factors, and add up the products. Everything else in those 2,000 lines is about getting the data to the tensor cores at the right moment, in the right layout, and choosing how to cut the problem into pieces. Reading the kernel from top to bottom is hard, because the computation, the data movement and the synchronization are all interleaved, and almost every number in the code (128, 256, 4, 32, 512) comes from some hardware rule that the code doesn't explain. So, in this series, I want to take the kernel apart and look at each piece on its own, with one question in mind: what does this piece compute, and why is it shaped the way it is? This first part is about the computation itself. We will start with what the kernel computes, including the block scale factors, then look at the one tensor core instruction that does all the work, and then see how the kernel nests its tiles around that instruction, from a single instruction up to the whole output matrix. Along the way, we will look at the two layouts the instruction insists on: the swizzled layout of the operands in shared memory and the layout of the scale factors in tensor memory. Part 2 is about the pipeline that keeps the tensor cores busy (warps, barriers, stages and the persistent loop), and part 3 is about tactics, which is to say how FlashInfer picks the tile shape, the cluster shape and a few other options for a given matrix shape. Everything here refers to FlashInfer at commit `c0e62fa7b` and `nvidia-cutlass-dsl` 4.8.0, and I ran all the code and measurements on a B300 (compute capability 10.3, 148 SMs). I'll leave out everything about how FlashInfer compiles and caches the kernels, since none of it changes what the kernel computes. If some of the GPU terms below are new to you, my earlier articles on [the TMA](https://sleepy-capybara.vercel.app/tma-cute-dsl/) and on [the SM100 memory hierarchy](https://sleepy-capybara.vercel.app/sm100-memory-hierarchy/) introduce shared memory, clusters, mbarriers and tensor memory from scratch. I'll briefly recap what we need as we go. ### 1. What the Kernel Computes #### 1.1 Three Block-Scaled Formats Let's start with the numbers themselves. A 4-bit floating-point number, `e2m1` (1 sign bit, 2 exponent bits, 1 mantissa bit), can only represent 16 values: 0, 0.5, 1, 1.5, 2, 3, 4 and 6, and their negatives. That is obviously not enough range for the weights or activations of a neural network, so these formats are always "block scaled": a short block of consecutive elements along the K dimension (the dimension we sum over in a matrix multiplication) shares one scale factor, and every element in the block is stored relative to it. The kernel supports three such formats, which differ in the block size and in the type of the scale factor: - **NVFP4:** `e2m1` elements, blocks of 16, one `e4m3` scale factor (an 8-bit float) per block, plus one fp32 global scale for the whole tensor. - **MXFP4:** `e2m1` elements, blocks of 32, one `ue8m0` scale factor per block. `ue8m0` is an 8-bit exponent with no sign and no mantissa, so every scale factor is a power of two. - **MXFP8:** `e4m3` or `e5m2` elements (8-bit floats), blocks of 32, one `ue8m0` scale factor per block. In the kernel, these are not three code paths. The kernel only looks at the element type, the scale-factor type and the block size (`sf_vec_size`), and CuTe DSL picks the matching tensor core instruction from those types. We'll see that choice in section 2. For most of this series, I'll use NVFP4 as the example, since it's what `mm_fp4` uses by default, and since its global scale is a nice extra wrinkle. So, what does the kernel compute? If we write qA for the 4-bit values of A, sA for its block scale factors, and similarly for B, then for row i of A and row j of B (the kernel wants both A and B with K as the contiguous dimension, so the product is A times B transposed): C[i, j] = alpha x sum over blocks b of ( sA[i, b] x sB[j, b] x sum over k in b of qA[i, k] x qB[j, k] ) Here alpha is 1 / (gA x gB). NVFP4 multiplies each tensor by a global scale (gA for A, gB for B) before quantizing it, to stretch it into the range that an `e4m3` scale times an `e2m1` value can represent, and alpha undoes both stretches at the end. (I went through where alpha is applied, in fp32 in the epilogue right before the conversion to bf16, in [the memory-hierarchy article](https://sleepy-capybara.vercel.app/sm100-memory-hierarchy/). MXFP4 and MXFP8 have no global scale, so for them alpha is normally 1.) Notice where the block scales sit in that formula: inside the sum over K. Since a scale factor only covers 16 elements along K, two blocks of the same row can have different scales, so we can't pull them out of the sum and apply them at the end. Either we dequantize everything first, which would mean multiplying 4-bit values in a wider format and losing the point of FP4, or the tensor core applies the scales itself, block by block, while it accumulates. Blackwell's tensor cores do the latter, and that is what "block-scaled MMA" means. #### 1.2 The Same Computation in PyTorch To make this concrete, let's quantize two random matrices with FlashInfer, run the kernel, and then recompute the result in PyTorch from the raw bytes, without any help from FlashInfer. Here is the first half: ```python import torch from flashinfer import SfLayout, mm_fp4, nvfp4_quantize M, N, K = 256, 512, 1024 torch.manual_seed(0) a = torch.randn(M, K, device="cuda", dtype=torch.bfloat16) b = torch.randn(N, K, device="cuda", dtype=torch.bfloat16) ga = 448 * 6 / a.float().abs().max() # global scales, as in gb = 448 * 6 / b.float().abs().max() # FlashInfer's tests a4, a_sf = nvfp4_quantize(a, ga, sfLayout=SfLayout.layout_128x4) b4, b_sf = nvfp4_quantize(b, gb, sfLayout=SfLayout.layout_128x4) alpha = (1 / (ga * gb)).reshape(1) c = mm_fp4(a4, b4.T, a_sf, b_sf.T, alpha, torch.bfloat16, backend="cute-dsl") ``` `a4` is a 256 x 512 tensor of `uint8`, two 4-bit values per byte, and `a_sf` holds one byte per block of 16 elements, so 256 x 64 bytes. The interesting part is the scale-factor layout, `layout_128x4`, which is not a plain row-major matrix. We'll see in section 5 exactly why it looks the way it does. For now, here is how to undo it, together with the decoding of the 4-bit values: ```python E2M1 = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6]) def unpack_e2m1(packed): # (rows, K / 2) uint8 -> (rows, K) lo, hi = packed & 0xF, packed >> 4 # element 2i is the low nibble return E2M1[torch.stack((lo, hi), -1).long()].flatten(-2) def unswizzle_sf(sf, rows, k, vec=16): # 128x4 layout -> (rows, K / vec) kt = (k // vec + 3) // 4 # chunks along K, 4 scales each t = sf.reshape(-1, kt, 32, 4, 4) # (row tile, k tile, r%32, r//32, kb) t = t.permute(0, 3, 2, 1, 4).reshape(-1, kt * 4) return t[:rows, : k // vec] def dequant(packed, sf, rows, k): q = unpack_e2m1(packed.cpu().view(torch.uint8)) s = unswizzle_sf(sf.cpu().view(torch.float8_e4m3fn), rows, k) return q * s.float().repeat_interleave(16, dim=1) A = dequant(a4, a_sf, M, K) B = dequant(b4, b_sf, N, K) ref = alpha.cpu() * (A @ B.T) err = (c.cpu().float() - ref).abs().max() / ref.abs().max() print(f"largest error relative to max |C|: {err:.1e}") ``` This prints an error of 3.3e-3, which is about what we get from rounding the fp32 result to bf16 at the end (bf16 keeps 8 significant bits, so its relative rounding error is up to about 4e-3). So the kernel computes the formula above, and `unswizzle_sf` tells us something we'll need later: in the 128x4 layout, the scale factors are stored in chunks that cover 128 rows and 4 blocks of K, and inside a chunk, row r comes at position (r mod 32, r div 32). Keep that in mind until section 5. ### 2. The Instruction #### 2.1 One Thread, One Big Matrix Multiplication All of the math in the kernel is done by one instruction, `tcgen05.mma` with the `block_scale` modifier. If you have written tensor core code for older GPUs, this instruction will look strange in two ways. First, it is issued by a single thread. On Ampere, every thread of a warp held a few elements of the operands in its registers and the warp issued the `mma` together. On Hopper, a warpgroup of 128 threads issued `wgmma` together. On Blackwell, one thread issues the instruction, and the tensor cores then do the work asynchronously while that thread moves on. Second, none of the operands are in registers. The instruction reads A and B from shared memory, through two 64-bit descriptors that say where each tile starts and how it's laid out. It reads the scale factors of A and B from tensor memory (TMEM), the dedicated 256 KB memory that every SM100 SM has for its tensor cores. And it accumulates the result D, in fp32, in TMEM as well. So, one instruction computes D += (A x SFA) (B x SFB)^T for a whole tile at once. How big a tile? In CuTe DSL, the instruction shape is a property of the MMA "op" that the kernel builds, and the DSL checks it against the hardware rules when the op is created. For block-scaled MMAs, those rules (from `BlockScaledMmaOp` in `cute/nvgpu/tcgen05/mma.py`) are: - with one CTA (`cta_group::1`): M must be 128, and N can be any multiple of 8 from 8 to 256; - with a pair of CTAs (`cta_group::2`, which we'll come to in a moment): M is 128 or 256, and N is a multiple of 16 from 16 to 256; - K is fixed by the element type: 64 for FP4 and 32 for FP8. The K rule is easier to remember in bytes. FlashInfer computes it as `mma_inst_bits_k // a_dtype.width` with `mma_inst_bits_k = 256`, so one instruction always consumes 256 bits, 32 bytes, of every row of A and B. For FP4 that's 64 elements, for FP8 it's 32. The kernel builds the op with a helper from CuTe DSL, which chooses between three instruction kinds based on the types: `MmaMXF4NVF4Op` for FP4 with blocks of 16 (NVFP4), `MmaMXF4Op` for FP4 with blocks of 32 (MXFP4), and `MmaMXF8F6F4Op` for FP8 (MXFP8). That's the choice I mentioned in section 1.1. Everything else in the kernel is the same for all three formats. To get a feeling for the size, one 128 x 256 x 64 instruction does 128 x 256 x 64 = 2.1 million multiply-adds, or 4.2 million floating-point operations. In the NVFP4 case it also applies 128 x 4 scale factors of A and 256 x 4 of B, since K = 64 is four blocks of 16. #### 2.2 The CTA Pair Now, the pair. Blackwell can run one MMA instruction across two SMs: two CTAs of the same cluster (a group of CTAs that the hardware schedules together on nearby SMs) form a pair, and one thread in the first CTA of the pair, the leader, issues an instruction with M = 256. Each CTA keeps 128 rows of A in its own shared memory and gets 128 rows of the result in its own TMEM. And B is split as well: each CTA holds half of the N columns of B, and the tensor cores of both SMs read B from both shared memories. Figure 1 shows who holds what for a 256 x 256 tile. ![What each CTA of a pair holds for one 256 x 256 tile](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/figures/fig01_cta_pair.png) *Figure 1: One 256 x 256 tile computed by a CTA pair. Each CTA holds half of A and half of B, the leader issues the instruction, and each CTA's TMEM receives its own 128 rows of the result.* As shown in Figure 1, the pair computes a 256 x 256 tile while each CTA only stores half of A's rows and half of B's columns. We will see in section 6 why that matters so much: it halves the bytes each SM loads for B without halving the work. In FlashInfer's kernel, the pair is switched on by the tile shape alone. `use_2cta_instrs = mma_tiler_mn[0] == 256`: an M tile of 256 means the pair instruction, an M tile of 128 means one CTA. Because the pair lives inside a cluster, a 256-row tile also requires a cluster with at least two CTAs along M. #### 2.3 Accumulate or Overwrite One last detail about the instruction. TMEM isn't cleared between output tiles, so the first instruction of every tile has to overwrite D instead of adding to it. The instruction has a flag for that, which the kernel sets through the tiled MMA object, once per tile: ```python # excerpt from dense_blockscaled_gemm_sm100.py tiled_mma.set(tcgen05.Field.ACCUMULATE, False) # ... for _k_block in range(k_block_cnt): # ... for kphase_idx in cutlass.range(num_kphases, unroll_full=True): # ... cute.gemm( tiled_mma, tCtAcc, tCrA[kphase_coord], tCrB[kphase_coord], tCtAcc, ) # Enable accumulate on tCtAcc after first kphase tiled_mma.set(tcgen05.Field.ACCUMULATE, True) ``` `cute.gemm` with a tcgen05 tiled MMA becomes one instruction (`UTCOMMA` in the SASS, as we saw in the memory-hierarchy article), so the inner loop issues one instruction per "k-phase", and the outer loop walks over K. That brings us to the question of how the kernel organizes all those instructions. ### 3. Tiles All the Way Down A GEMM kernel always cuts the problem into tiles, but in this kernel there are several levels of tiles, and they all have different names in the code (`mma_inst_shape_mnk`, `mma_tiler`, `cta_tile_shape_mnk`, `cluster_shape_mn`). Here they are from the smallest to the largest, for the configuration that FlashInfer picks for a large square problem: a 256 x 256 MMA tile computed by a CTA pair in a 2 x 1 cluster. 1. **The instruction:** 256 x 256 x 64, as above. One leader thread issues it. 2. **The K tile, or stage:** 4 instructions along K make one K tile of 256 elements. This is the unit that the kernel loads into shared memory at a time, and the code calls it the `mma_tiler`: (256, 256, 256). The 4 is `mma_inst_tile_k`, and the instructions inside one K tile are the "k-phases" of the loop above. 3. **The CTA tile:** each CTA of the pair owns 128 rows of the output, so the CTA tile is 128 x 256 (`cta_tile_shape_mnk`). With one CTA per tile, the CTA tile and the MMA tile are the same. 4. **The cluster:** the 2 x 1 cluster is exactly one pair, so it covers 256 x 256 outputs. Larger clusters cover several MMA tiles, which share their loads through multicast, as we'll see in part 2. 5. **The grid:** the output matrix is covered by MMA tiles, 32 x 32 of them for an 8,192 x 8,192 output, and the persistent scheduler hands these tiles to the clusters one after another (also part 2). Figure 2 shows the first four levels. ![The levels of tiles in FlashInfer's SM100 GEMM](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/figures/fig02_tile_levels.png) *Figure 2: From the output matrix to one instruction. The output is cut into 256 x 256 MMA tiles; each is computed by a pair of CTAs that own 128 rows each; the K loop advances by K tiles of 256; and each K tile is four instructions of K = 64.* All of these shapes follow from the tactic, the tile and cluster shape the kernel is constructed with. Here is a short function that derives them the same way `_setup_attributes` does: ```python def tile_levels(tile_mn, cluster_mn, elem_bits=4, inst_per_k_tile=4): two_cta = tile_mn[0] == 256 inst = (*tile_mn, 256 // elem_bits) # one tcgen05.mma k_tile = (*tile_mn, inst[2] * inst_per_k_tile) # one stage cta = (tile_mn[0] // (2 if two_cta else 1), tile_mn[1], k_tile[2]) cluster = (cta[0] * cluster_mn[0], tile_mn[1] * cluster_mn[1]) return dict(inst=inst, k_tile=k_tile, cta=cta, cluster_out=cluster) for tile, cluster in [((256, 256), (2, 1)), ((128, 16), (1, 1)), ((256, 128), (2, 2))]: print(tile, cluster, tile_levels(tile, cluster)) ``` For the 256 x 256 tile, this gives an instruction of (256, 256, 64), a K tile of (256, 256, 256), a CTA tile of (128, 256, 256), and a cluster that covers 256 x 256 outputs. For a 128 x 16 tile, which FlashInfer uses for decoding with very few tokens (part 3), every level is (128, 16, ...) and the cluster is a single CTA. I checked all three against the values that the kernel itself computes while it compiles. Why is the K tile 256 elements? For FP4, 256 elements are 128 bytes per row, and 128 bytes is the width of the swizzled shared-memory layout that the instruction reads, which is our next topic. (FlashInfer also has a "deep-K" variant with 8 instructions per stage, a K tile of 512 and 256-byte rows. It's one of the tactics in part 3.) ### 4. The Operand Layout in Shared Memory #### 4.1 Why the Layout Matters The instruction reads A and B from shared memory without any help from the threads, so it can only read layouts it understands, and the descriptor describes which one it is. CuTe DSL picks the layout for us. When I printed the shared-memory layout of A for the 256 x 256 configuration, it came out as: ```text S<3,4,3> o 0 o ((128,64),1,4,5):((256,1),0,64,32768) ``` Let's read it from the right. The part after the `:` is a CuTe layout, shape on the left and strides on the right, in units of FP4 elements. `(128, 64)` with strides `(256, 1)` is one instruction's slice of A: 128 rows of 64 elements, where consecutive elements are next to each other and consecutive rows are 256 elements, 128 bytes, apart. Then `4` with stride `64` is the four k-phases of the K tile, each starting 64 elements (32 bytes) further along the same rows. And `5` with stride `32768` is five stages, each 32,768 elements or 16 KB. So, one stage of A is 128 rows of 128 bytes, and each instruction reads a 32-byte-wide column of it. The part on the left, `S<3,4,3>`, is the swizzle, and it is the reason this layout exists. #### 4.2 The 128-Byte Swizzle Shared memory is divided into 32 banks of 4 bytes, so a 128-byte row covers each bank exactly once. That is a problem for anyone who reads the same few bytes from many rows at once, which is exactly what a matrix multiplication does when it walks down a column: in an unswizzled layout, byte 0 of every row sits in bank 0, so reading the first 16 bytes of 8 rows means 8 accesses to the same 4 banks, one after another. The fix is to permute the 16-byte pieces of each row. In the 128-byte swizzle (CuTe calls it `K_SW128`), a row of 128 bytes is 8 pieces of 16 bytes, and in row r, piece p is stored at position p XOR (r mod 8). The pattern repeats every 8 rows, so the unit of the layout, the swizzle atom, is 8 rows of 128 bytes, 1 KB. That's what `S<3,4,3>` encodes: take the 3 address bits starting at bit 4 (which 16-byte piece), and XOR them with the 3 bits starting at bit 7 (which 128-byte row within the atom). The swizzle works on byte addresses, which is why the very same `S<3,4,3>` shows up for FP4, FP8 and bf16, whose atoms are 8 x 256, 8 x 128 and 8 x 64 elements, always 8 x 128 bytes. Here's the same thing in Python, together with a check of what it buys us: ```python def sw128(row, piece): # byte offset of 16-byte piece `piece` of `row` return row * 128 + (piece ^ (row % 8)) * 16 def bank_group(offset): # which 16-byte group of 4 banks return offset % 128 // 16 for piece in range(8): plain = {bank_group(r * 128 + piece * 16) for r in range(8)} swizzled = {bank_group(sw128(r, piece)) for r in range(8)} print(piece, len(plain), len(swizzled)) ``` For every piece, the unswizzled layout puts all 8 rows into the same bank group (it prints 1), and the swizzled layout spreads them over all 8 groups (it prints 8). Figure 3 shows the same thing as a picture. ![Plain and 128-byte swizzled layouts of an 8 x 128-byte block](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/figures/fig03_swizzle.png) *Figure 3: Eight rows of 128 bytes, cut into 16-byte pieces. Without swizzling (left), piece 0 of every row lands in the same banks. With the 128-byte swizzle (right), piece p of row r goes to position p XOR r, so the eight copies of piece 0 cover all banks.* As we can see in Figure 3, the swizzle turns a column of the tile into a diagonal. The TMA writes tiles in this layout directly when it loads them from global memory (the TMA descriptor has a swizzle mode for exactly this purpose), and the tensor core reads them back in the same layout, so no thread ever has to know about it. That's also the reason for the 128-byte K tile from section 3: a K tile of 256 FP4 elements is exactly one swizzle-atom row wide, so one stage of A is a stack of 1 KB swizzle atoms, 16 of them for 128 rows. ### 5. The Scale Factors #### 5.1 Where the Instruction Wants Them The scale factors are small (one byte per 16 elements, so 1/8 of the size of the FP4 data), but they have the most unusual path through the kernel. They come from global memory into shared memory with the TMA, like A and B, but the instruction doesn't read them from shared memory. It reads them from TMEM, so the kernel has to copy them from shared memory into TMEM first, with another tcgen05 instruction, `tcgen05.cp`, which is issued by the same thread that issues the MMAs. How do they have to be arranged in TMEM? TMEM is a 2D memory of 128 lanes and 512 columns of 32-bit cells. For the NVFP4 instruction with K = 64, the PTX documentation (the figure for "scale_vec::4X/block16") specifies that the four scale factors of row m (one per block of 16) go into the four bytes of one cell, in lane m mod 32 and column m div 32. So 128 rows of SFA take up 32 lanes and 4 columns per instruction, and since a K tile has 4 instructions, 16 columns per K tile. That is exactly what the kernel computes for `num_sfa_tmem_cols`: (128 / 32) x 4 = 16. #### 5.2 Why the 128x4 Layout Looks the Way It Does Now we can understand the strange global layout from section 1.2. In CuTe DSL, the layout of the scale factors in global memory is built from a fixed "basic chunk" (`BlockScaledBasicChunk` in `cutlass/utils/blockscaled_layout.py`): ```text shape ((32, 4), (16, 4)) stride ((16, 4), ( 0, 1)) ``` The first mode is the rows: 32 x 4 = 128 rows, where row r has offset (r mod 32) x 16 + (r div 32) x 4. The second mode is K: 16 elements share one scale factor (stride 0), and 4 blocks of 16 are consecutive bytes (stride 1). So one chunk covers 128 rows and 64 elements of K, and it is 512 bytes, with the scale factor of row r and block kb at byte (r mod 32) x 16 + (r div 32) x 4 + kb. Compare that with the TMEM rule: lane r mod 32, column r div 32, byte kb. If we view the 32 lanes of 4 columns as a 32 x 16-byte block, row r and block kb land at lane (r mod 32), byte (r div 32) x 4 + kb, which is the very same offset. In other words, a 512-byte chunk of the global layout is a byte-for-byte image of what the instruction wants to find in TMEM. Let's check that in Python: ```python def sf_byte(row, kb): # offset inside one 512-byte chunk of the layout return (row % 32) * 16 + (row // 32) * 4 + kb def tmem_cell(row, kb): # (lane, column, byte), from the PTX docs return row % 32, row // 32, kb same = all(sf_byte(r, kb) == lane * 16 + col * 4 + byte for r in range(128) for kb in range(4) for lane, col, byte in [tmem_cell(r, kb)]) print(same) ``` It prints `True`. Figure 4 shows the mapping for one example row. ![How a 512-byte chunk of scale factors maps onto TMEM](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/figures/fig04_sf_chunk.png) *Figure 4: One 512-byte chunk of scale factors covers 128 rows and 4 blocks of 16 along K. Viewed as 32 rows of 16 bytes, it is exactly the image of 32 TMEM lanes by 4 columns that one NVFP4 instruction reads. Row 37 is highlighted: lane 5, column 1.* So, the layout of the scale factors in global memory, which looked so odd in section 1.2, is chosen so that no part of the kernel ever has to rearrange them. The TMA copies chunks into shared memory as they are, and `tcgen05.cp` copies each chunk into TMEM as it is. The copy the kernel uses is `Cp4x32x128bOp`, which is PTX's `tcgen05.cp` with shape `.32x128b` (32 lanes of 128 bits, so 32 x 16 bytes, one chunk) and the multicast option `.warpx4`, which writes the same 32 lanes into all four lane quarters of TMEM. So the 32 lanes from section 5.1 exist four times, once in each quarter of TMEM. #### 5.3 SFB, and Why It Is Always 128 Wide The scale factors of B follow the same rules, with B's rows (the N dimension of the output) in place of A's rows. But there is a complication: the scale-factor chunk always covers 128 rows, and the N tile can be smaller (64, 32 or even 8) or not a multiple of 128 (192). So the kernel always loads SFB in tiles of `round_up(tile_n, 128)` rows, through a second tiled MMA object, `tiled_mma_sfb`, that is never used for math but only for this partitioning. For N tiles smaller than 128, several output tiles share one SFB tile, and the MMA reads its part through a shifted TMEM address. We will come back to that in part 3, since that's what makes the narrow N tiles of 8, 16 and 32 possible. In the CTA pair, both CTAs need the scale factors of all 256 columns of B, because each CTA computes all 256 columns for its own 128 rows. That's why the SFB copy is a multicast load to both CTAs, as Figure 1 showed, while A, B and SFA are each split between the two CTAs. ### 6. One K Tile, and How Big the Tile Should Be #### 6.1 Putting One K Tile Together We now have all the pieces of one iteration of the main loop. The MMA warp waits until a stage of shared memory has been filled, copies that stage's scale factors into TMEM, and issues four instructions, one per k-phase, each pointing at its own 32-byte column of A and B and its own TMEM columns of scale factors: ```python # excerpt from dense_blockscaled_gemm_sm100.py cute.copy( tiled_copy_s2t_sfa, tCsSFA_compact_s2t_staged, tCtSFA_compact_s2t, ) cute.copy( tiled_copy_s2t_sfb, tCsSFB_compact_s2t_staged, tCtSFB_compact_s2t, ) # tCtAcc += tCrA * tCrSFA * tCrB * tCrSFB num_kphases = cute.size(tCrA, mode=[2]) for kphase_idx in cutlass.range(num_kphases, unroll_full=True): # ... # Set SFA/SFB tensor to tiled_mma sf_kphase_coord = (None, None, kphase_idx) tiled_mma.set( tcgen05.Field.SFA, tCtSFA[sf_kphase_coord].iterator, ) tiled_mma.set( tcgen05.Field.SFB, tCtSFB_mma[sf_kphase_coord].iterator, ) # ... ``` The two `tiled_mma.set` calls are how the TMEM addresses of the scale factors get into the instruction: each k-phase points at its own 4 columns of SFA and its own columns of SFB. For a 256 x 256 tile, a K tile is then 4 instructions of 256 x 256 x 64. For an 8,192 x 8,192 x 8,192 GEMM, that's 128 instructions per output tile and 1,024 tiles, so 131,072 instructions, issued by the 74 leader threads of the 74 CTA pairs that fit on the B300's 148 SMs. In my measurement this took about 158 to 164 microseconds, so each pair finished one 256 x 256 x 64 instruction about every 90 nanoseconds. The waiting and the copying are what part 2 is about. But we can already answer one question with what we have: why does FlashInfer prefer the 256 x 256 tile for big problems? #### 6.2 FLOPs per Byte Every stage, each CTA has to receive its A, B, SFA and SFB bytes from L2 or HBM before its tensor cores can do the stage's work. So the more FLOPs a tile gets out of every byte it loads, the less bandwidth it needs to keep its tensor cores busy. Here's that ratio for a few tiles, computed the same way the kernel sizes its shared-memory stages: ```python def stage(tile_mn, k=256, sf_vec=16): # bytes and FLOPs per CTA per stage pair = 2 if tile_mn[0] == 256 else 1 rows, cols = tile_mn[0] // pair, tile_mn[1] a, b = rows * k // 2, cols // pair * k // 2 # FP4: two per byte sfa = rows * k // sf_vec sfb = -(-cols // 128) * 128 * k // sf_vec # SFB rounds N up to 128 flops = 2 * rows * cols * k return a + b + sfa + sfb, flops for tile in [(128, 64), (128, 128), (128, 256), (256, 128), (256, 256)]: nbytes, flops = stage(tile) print(tile, nbytes, round(flops / nbytes)) ``` This prints 28,672 bytes and 146 FLOPs per byte for 128 x 64, 36,864 and 228 for 128 x 128, 55,296 and 303 for 128 x 256, 28,672 and 293 for 256 x 128, and 38,912 and 431 for 256 x 256. Those byte counts are exactly the stage sizes that the kernel computed for these tiles. Notice what the pair does: a 256 x 128 tile does the same work per CTA as a 128 x 128 tile, but each CTA loads only half of B, so its ratio goes from 228 to 293. And the 256 x 256 tile is the best of all, since each CTA computes a 128 x 256 piece of output while loading 128 rows of A and only 128 columns of B. To see how much this matters, I ran the kernel with each of these tiles on an 8,192 x 8,192 x 8,192 problem, with a cold L2 cache and the same cluster for every tile (2 x 1 for 256-row tiles, a single CTA otherwise). Figure 5 shows the result. ![Throughput of the kernel for each MMA tile shape](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/figures/fig05_tiles.png) *Figure 5: PFLOP/s of FlashInfer's NVFP4 GEMM on a B300 for an 8,192-cubed problem, one bar per MMA tile, with the FLOPs per loaded byte of each tile below it. All outputs were bit-identical to FlashInfer's CUTLASS backend.* As we can see in Figure 5, the throughput follows the FLOPs per byte almost perfectly, from 3.3 PFLOP/s for 128 x 64 to 6.7 PFLOP/s for 256 x 256. There is one exception, 128 x 256, which has a higher ratio than 256 x 128 but is a bit slower. Its stages are 55 KB, and only 3 of them fit in shared memory, while the 256 x 128 tile gets 7 stages. That's a nice preview of part 2: the FLOPs per byte tell us how much loading a tile needs, but the number of stages decides whether the loading can stay far enough ahead. (The same ranking holds for GLM-5.3's gate and up projection with 8,192 tokens, 8,192 x 24,576 x 6,144, which I also measured: 3.2 PFLOP/s for 128 x 64 and 6.5 PFLOP/s for 256 x 256.) ### 7. Summary To summarize this first part, here is the computation of FlashInfer's SM100 block-scaled GEMM, from the bottom up: 1. **The math** is C = alpha x sum over blocks of (sA sB x sum of qA qB). The block scales sit inside the sum over K, which is why the tensor cores apply them. NVFP4, MXFP4 and MXFP8 differ only in the types and the block size, and CuTe DSL picks the matching instruction kind. 2. **The instruction** is `tcgen05.mma` with block scaling, issued by one thread. It reads A and B from shared memory, the scale factors from TMEM, and accumulates in TMEM. Its M is 128, or 256 for a CTA pair; its N is a multiple of 8 (16 for a pair) up to 256; and it consumes 32 bytes of K per row. 3. **The tiles** nest as instruction, K tile (4 instructions, 128 bytes of FP4 per row), CTA tile (half the rows for a pair), cluster and grid. 4. **The operands** sit in shared memory in the 128-byte swizzled layout, written that way by the TMA and read that way by the tensor cores, so that a column of the tile spreads over all banks. 5. **The scale factors** come in 512-byte chunks that are byte-for-byte images of 32 TMEM lanes by 4 columns, so the TMA and `tcgen05.cp` can move them without any rearranging. SFB is always loaded 128 rows wide. 6. **The tile shape** matters mostly through FLOPs per byte loaded, and the CTA pair is the trick that raises it, by splitting B between two SMs. In part 2, we'll look at everything this part skipped: how the kernel waits for a stage to be filled, how many stages it keeps, how the accumulator in TMEM is handed to the epilogue while the next tile is already being computed, and how clusters and the persistent loop decide which SM works on which tile. ### Sources - [FlashInfer's SM100 block-scaled GEMM (dense_blockscaled_gemm_sm100.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/dense_blockscaled_gemm_sm100.py) - [FlashInfer's shared helpers for it (dense_blockscaled_gemm_sm100_common.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/dense_blockscaled_gemm_sm100_common.py) - [PTX ISA: tcgen05.mma block scaling and scale-factor layouts](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#tcgen05-mma-scale-factor-a) - [PTX ISA: tcgen05.cp](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#tcgen05-instructions-tcgen05-cp) - [PTX ISA: swizzling modes](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#tensor-swizzling-modes) - [CUTLASS CuTe DSL (the blackwell_helpers and blockscaled_layout utilities)](https://github.com/NVIDIA/cutlass/tree/main/python/CuTeDSL) - [OCP Microscaling Formats (MX) specification](https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf) ## 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* In [part 1](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/), 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. ![Serial and pipelined execution of load, MMA and epilogue](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/figures/fig01_overlap.png) *Figure 1: Load, multiply and epilogue one after the other (left), and overlapped (right). In the overlapped version, the tensor cores only wait at the very beginning.* 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: ```python # 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. ![The ring of operand stages with their full and empty barriers](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/figures/fig02_ring.png) *Figure 2: Five stages of operands in shared memory. The TMA warp waits for a stage's empty barrier and refills the stage, and the TMA completes the full barrier when all bytes have landed. The MMA warp waits for full and issues its MMAs, and the tensor cores complete empty when they are done reading.* #### 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: ```python 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: ```python 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: ```python # 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: ```python # 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: ```python 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. ![Kernel time as a function of the number of operand stages](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/figures/fig03_stages.png) *Figure 3: Kernel time with the operand ring capped at 1 to the maximum number of stages, for a large GEMM (left) and a 16-token decoding step (right). Cold L2, B300.* 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: ```python # 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. ![The two overlapping accumulators in TMEM and the order of the epilogue](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/figures/fig04_overlap_accum.png) *Figure 4: The accumulators of two consecutive 256-wide tiles share TMEM columns 208 to 255. The epilogue reads the shared columns first (subtiles 7 and 6 of tile t, read backwards), then releases the accumulator, so the MMAs of tile t + 1 can start while subtiles 5 to 0 are still being read.* 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: ```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. ![Which output tiles the first two rounds of the persistent loop compute](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/figures/fig05_schedule.png) *Figure 5: The 32 x 32 tiles of an 8,192 x 8,192 output and the persistent schedule for 74 CTA pairs. The first round (dark) covers tile numbers 0 to 73 in M-major order, the second (light) 74 to 147. The last round is only partly full: 1,024 = 13 x 74 + 62.* 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: 1. **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. 2. **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. 3. **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. 4. **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. 5. **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)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/dense_blockscaled_gemm_sm100.py) - [FlashInfer's shared helpers for it (dense_blockscaled_gemm_sm100_common.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/dense_blockscaled_gemm_sm100_common.py) - [CUTLASS CuTe DSL (pipelines and the persistent tile scheduler)](https://github.com/NVIDIA/cutlass/tree/main/python/CuTeDSL) - [PTX ISA: mbarrier](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-mbarrier) - [PTX ISA: tcgen05.commit](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#tcgen-async-sync-operations-commit) - [CUDA Programming Guide: thread block clusters](https://docs.nvidia.com/cuda/cuda-programming-guide/index.html) - [Using TMA Load, Prefetch, and Multicast Load in CuTe DSL](https://sleepy-capybara.vercel.app/tma-cute-dsl/) - [The SM100 Memory Hierarchy, from HBM to Tensor Memory](https://sleepy-capybara.vercel.app/sm100-memory-hierarchy/) ## Inside FlashInfer's SM100 GEMM, Part 3: Choosing a Tactic *How mm_fp4 turns a matrix shape into a tile, a cluster and a few switches, why swapping A and B wins for small batches, how the narrow N tiles reach their scale factors, and how to time tactics without fooling yourself* In the first two parts of this series, we took FlashInfer's SM100 block-scaled GEMM apart: in [part 1](https://sleepy-capybara.vercel.app/sm100-gemm/1-tiles/) the instruction, the tiles and the scale factors, and in [part 2](https://sleepy-capybara.vercel.app/sm100-gemm/2-pipeline/) the warps, barriers, stages, accumulators and the persistent loop that keep the tensor cores busy. Along the way, we kept running into choices: 128 or 256 rows per tile, 64 or 256 columns, a cluster of 2 or of 8, the early or the late accumulator release. Most of those choices aren't fixed in the kernel. They are parameters of its constructor, and somebody has to pick them for every matrix shape the kernel is called with. FlashInfer calls one such set of choices a tactic. In this last part, we'll look at what a tactic contains, how much it matters which one you pick (quite a lot, as we'll see), and how `mm_fp4(..., backend="cute-dsl")` picks one, both with its autotuner and without it. The most interesting choices are for small batches, where the kernel swaps its two operands and uses very narrow tiles, so those get the most space. At the end, we'll look at how the autotuner times the tactics, since a wrong timing method picks the wrong tactic even when the candidate list is right. As before, the code is FlashInfer at `c0e62fa7b` with CuTe DSL 4.8.0, and the measurements are from a B300. All shapes are from GLM-5.3's dense layers, unsharded: the fused gate and up projection (N = 24,576, K = 6,144), the down projection (N = 6,144, K = 12,288) and the attention output projection (N = 6,144, K = 16,384), each with M from 1 to 8,192 tokens. I timed every kernel with CUPTI, from the start of the kernel to its end, with the L2 cache flushed before every launch (section 7 explains why), and every output was bit-identical to FlashInfer's CUTLASS backend. ### 1. What a Tactic Is #### 1.1 Six Fields In the `mm_fp4` runner for the CuTe DSL backend (`CuteDSLFp4GemmRunner` in `gemm_base.py`), a tactic is a tuple of six fields: ```python # (mma_tiler_mn, cluster_shape_mn, swap_ab, use_prefetch, kernel_type, extra) ((256, 256), (2, 1), False, False, "sm100", None) # large M ((128, 16), (1, 1), True, False, "sm100", None) # a few tokens ((128, 8), (1, 1), True, False, "sm100sk", 2) # split-K, two slices ``` The first two are the MMA tile and the cluster shape from parts 1 and 2. `swap_ab` exchanges the roles of A and B, which is the subject of section 4. `use_prefetch` makes the TMA warp issue L2 prefetches for the next few K tiles ahead of its loads. `kernel_type` is `"sm100"` for the kernel we have been reading, or `"sm100sk"` for a separate split-K kernel that FlashInfer also offers for small batches. The last field depends on the kernel type: for the split-K kernel, it's the number of K slices, and for the persistent kernel it's either `None` or 8, which selects the "deep-K" variant with 8 instructions per K tile instead of 4. One more knob, the L2 eviction policy of the TMA loads, isn't part of the tuple, because the runner derives it from the tactic and the shape (section 6). Everything else we saw in parts 1 and 2 (the number of stages, the number of accumulators, the epilogue subtile, the multicast masks) follows from these fields when the kernel is constructed. #### 1.2 Where the Candidates Come From The runner builds the list of candidates from two fixed lists in `kernels/utils.py`, 11 MMA tiles and 9 cluster shapes: ```python # excerpt from kernels/utils.py _SM100_MMA_TILER_MN_CANDIDATES = [ (128, 8), (128, 16), (128, 32), (128, 64), (256, 64), (128, 128), (256, 128), (128, 192), (256, 192), (128, 256), (256, 256), ] # ... _CLUSTER_SHAPE_MN_CANDIDATES = [ (1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (2, 4), (4, 1), (4, 2), (4, 4), ] ``` It takes every combination with both values of `swap_ab` and keeps the ones that the kernel's `can_implement` accepts. That check encodes the rules from parts 1 and 2: a 256-row tile needs at least two CTAs along M in the cluster, cluster dimensions are powers of two and at most 4, and the narrow tiles (N of 8, 16 or 32) have extra rules that we'll see in section 5. `use_prefetch` is only offered when it can plausibly help: when the grid fills between half and all of the SMs, or when K is at least 8,192. For M up to 32, the runner keeps only swapped tactics with a narrow tile. It then appends the deep-K variants of the narrow tiles and the split-K tactics. That still leaves a lot: between 120 and 258 valid persistent-kernel tactics for our 30 shapes, before the split-K and deep-K ones. Profiling all of them would take a while for every new shape, so the runner ranks them with a heuristic score and the autotuner only profiles the best 32 (`_MM_FP4_CUTE_DSL_MAX_TUNING_CONFIGS`). The same score picks the tactic when no autotuning has happened, which we'll come back to in section 8. ### 2. How Much the Choice Matters Before looking at how the choice is made, I wanted to know how much is at stake. So for each of our 30 shapes (3 layers times 10 token counts), I timed every tactic that the autotuner would profile, 918 kernels in total. Here's the spread between the best and the worst of them: - **Across all shapes,** the slowest profiled tactic took 1.6 times as long as the fastest, as a geometric mean, and 4.4 times as long in the worst case (GLM-5.3's gate and up projection with 32 tokens: 19.7 against 87.2 microseconds). - **The untuned choice,** which `mm_fp4` makes when no autotuning has happened, was 5% slower than the best tactic on average and 13% slower at most. So, the list of candidates already contains mostly reasonable tactics (it's ranked, after all), but picking the wrong one among them can still cost several times the runtime, and even the heuristic pick is 5% slower than the best on average. Let's look at what drives the differences, starting with the effect that the heuristic models most directly. ### 3. Tile and Wave Quantization #### 3.1 Two Kinds of Waste There are two ways a tile shape can waste work, and the heuristic score (`_score_block_scaled_tactic` in `kernels/utils.py`) measures both. The first is **tile quantization**. If the matrix dimension isn't a multiple of the tile, the last row or column of tiles is only partly filled, but the tensor cores compute it in full. With M = 300 and 128-row tiles, there are 3 tiles along M covering 384 rows, so 22% of the work is thrown away. The score calls the useful fraction `m_eff` (and `n_eff` for N). The second is **wave quantization**, which we met at the end of part 2. The persistent kernel runs one CTA per SM, and the tiles are dealt out in rounds. If the number of CTA tiles isn't a multiple of the number of SMs, the last round leaves some SMs idle. The score counts the rounds (`num_waves`) and divides by them. Put together, the core of the score is the useful work per round, normalized by the width of the tile: `m_eff * n_eff * sqrt(tile_n / 256) / (num_waves * tile_n)`, where the square root is a rough model of how wider tiles get more throughput per CTA. On top of that come a few corrections: a penalty for tiles wider than 128 when K is short (since the pipeline can't hide their latency), a 5% bonus for the CTA pair, small penalties for large clusters, and a 5% penalty for any tactic whose orientation disagrees with a simple rule, swap when M is at most 32 and don't swap otherwise (section 4). #### 3.2 A Worked Example Let's take one shape where this matters: GLM-5.3's down projection with 4,096 tokens, so M = 4,096, N = 6,144 and K = 12,288. Here is the wave arithmetic for the two tiles that came out on top: ```python import math def waves(m, n, tile, sms=148): ctas_m = math.ceil(m / tile[0]) * (2 if tile[0] == 256 else 1) ctas_n = math.ceil(n / tile[1]) ctas = ctas_m * ctas_n return ctas, ctas / sms, math.ceil(ctas / sms) for tile in [(256, 256), (256, 192)]: ctas, exact, rounds = waves(4096, 6144, tile) print(tile, ctas, f"{exact:.2f} waves -> {rounds} rounds,", f"{exact / rounds:.0%} of the SMs busy on average") ``` The 256 x 256 tile gives 768 CTAs, which is 5.19 waves of 148, so 6 rounds in which the SMs are busy 86% of the time. The 256 x 192 tile gives 1,024 CTAs, 6.92 waves, so 7 rounds that are 99% full. The narrower tile does a little less work per CTA, but it wastes almost nothing at the end. Which one is faster? In my measurement, 256 x 192 took 91.6 microseconds and 256 x 256 took 99.6, so the better-filled waves save 8% of the time. The heuristic score, though, prefers 256 x 256 here, by about 1%: its square-root throughput model credits the wider tile with 15% more throughput per CTA, which almost exactly cancels the extra round it needs. So the untuned path picks the slower tile, and this is a nice illustration of why FlashInfer profiles the top candidates instead of trusting the score. The score is a good way to rank a list, but it's a model, and at the margin the model is wrong. ### 4. Swapping A and B #### 4.1 The Problem with Small M Now let's look at decoding, where M, the number of tokens, is tiny: 1 to 32 tokens per step is typical for a serving engine at low concurrency. Here we run into the instruction's shape rules from part 1. The M dimension of `tcgen05.mma` is 128 or 256, never smaller. So with M = 1, the kernel computes a 128-row tile in which one row is real and 127 are padding. That is tile quantization at its most extreme, with an `m_eff` of 1/128. In terms of time, it isn't quite as bad as it sounds, since a decoding GEMM is limited by reading the weight matrix from HBM and not by the tensor cores. But the padding still costs: without swapping, N is the weight dimension, which is far above the 32 that the narrow tiles allow (section 5), so the smallest usable N tile is 64. The weight matrix B is then cut into 64-row slabs, and every slab is multiplied by a 128-row tile of A that is almost all zeros. The fix is a transposition identity. The kernel computes C = A B^T. If we transpose both sides, C^T = B A^T, which is the same kind of product with the roles of A and B exchanged. So we can give the kernel the weights as its A operand and the activations as its B operand, and it computes C^T. Now the large dimension, the 24,576 output features of the gate and up projection, is on the M side, where the instruction wants 128 rows, and the tokens are on the N side, where the instruction accepts as few as 8 columns. Figure 1 shows the two orientations. ![The MMA tile without and with swapping A and B, for a single token](https://sleepy-capybara.vercel.app/sm100-gemm/3-tactics/figures/fig01_swap.png) *Figure 1: For one token, the unswapped kernel (left) computes 128-row tiles with one useful row. Swapped (right), the weight matrix fills the 128 rows and the token occupies an 8-column tile, so almost nothing is padding.* #### 4.2 Swapping in Practice In code, the identity is one line of PyTorch: ```python import torch a = torch.randn(4, 64) # 4 tokens, K = 64 b = torch.randn(256, 64) # 256 output features c = a @ b.T # what we want: (4, 256) c_t = b @ a.T # what the swapped kernel computes: (256, 4) print(torch.allclose(c, c_t.T, atol=1e-5)) # the swapped result, written column-major, is c in row-major order col_major = torch.empty_strided((256, 4), (1, 256)) col_major.copy_(c_t) print(torch.equal(col_major.as_strided((4, 256), (256, 1)), c_t.T)) ``` The second check shows the other half of the trick. The kernel writes its (N, M)-shaped output in column-major order, which in memory is exactly the (M, N) row-major matrix the caller wants. So the runner doesn't need any transpose after the kernel. It passes the weights as A and the activations as B, swaps the two scale-factor tensors, and gives the kernel a column-major view of the output buffer: ```python # excerpt from gemm_base.py if swap_ab: kernel_m, kernel_n = n, m # ... kernel_a, kernel_b = b.T, a kernel_a_sf, kernel_b_sf = b_descale.T, a_descale ``` (Full disclosure: I wrote the changes that let `mm_fp4` swap for M that isn't a multiple of 8 and added the narrow tiles of the next section, so I'm not a neutral reporter here. All the numbers below are from this article's measurements.) How much does it buy? For M from 1 to 32, I timed the best non-swapped tactic (over five tiles of 64 to 256 columns and six cluster shapes) against the best swapped one. Figure 2 shows the result. ![Best swapped against best unswapped tactic for small batches](https://sleepy-capybara.vercel.app/sm100-gemm/3-tactics/figures/fig02_swap_gain.png) *Figure 2: Kernel time of the best unswapped tactic (gray) and the best swapped tactic with a narrow tile (pink), for GLM-5.3's three dense projections with 1 to 32 tokens.* As we can see in Figure 2, the swapped tactic wins every time, by a factor of 1.07 to 1.21. The gain is largest for one token and shrinks as M approaches 32, where the unswapped 64-column tiles waste less and the swapped tiles have to grow to 32 columns. Notice also how flat the swapped times are: the down projection takes 12.3 microseconds for one token and 13.3 for 32, since in both cases the kernel mostly reads the same 42 MB of weights and scale factors. For the gate and up projection, that's 85 MB in 19.2 microseconds, or 4.4 TB/s, a bit more than half of the B300's 7.7 TB/s peak memory bandwidth. ### 5. The Narrow Tiles #### 5.1 Scale Factors for Eight Tokens With the tokens on the N side, the N tile can be as small as the instruction allows: 8 columns for one CTA. That's what the tiles (128, 8), (128, 16) and (128, 32) are for. But they run into a problem we saw at the end of part 1: the scale factors of B (now the activations) always come in chunks of 128 rows, because that's the unit that `tcgen05.cp` copies into TMEM. A 16-wide tile only needs 16 of those 128 rows. The kernel's solution is to load the whole 128-row SFB chunk anyway and let several narrow tiles share it. In the mainloop, tile number i along N computes its offset into the chunk and points the MMA at the right part: ```python # excerpt from dense_blockscaled_gemm_sm100.py tok_off = ( mma_tile_coord_mnl[1] % self.sfb_sub_tiles_per_tile ) * self.cta_tile_shape_mnk[1] offset = cutlass.Int32(tok_off // 32) shifted_ptr = cute.recast_ptr( acc_tmem_ptr + self.num_accumulator_tmem_cols + self.num_sfa_tmem_cols + offset, dtype=self.sf_dtype, ) tCtSFB_mma = cute.make_tensor(shifted_ptr, tCtSFB_layout) sSFB_shifted = cute.make_tensor( sSFB.iterator + cutlass.Int32(tok_off % 32) * 16, sSFB.layout, ) ``` Remember from part 1 that row r of the chunk lives in TMEM lane r mod 32, column r div 32, and in shared memory at byte (r mod 32) x 16 + (r div 32) x 4. So a tile that starts at token `tok_off` has two things to adjust: its first row should land in TMEM lane 0, which the kernel arranges by starting the shared-memory source of the copy `tok_off mod 32` lines (16 bytes each) later; and its TMEM column moves by `tok_off div 32`, which shifts the MMA's SFB address. Since the shifted copy still reads a full 512-byte chunk, it can run up to 31 lines past the end of the real one, which is why narrow tiles reserve one extra chunk of shared memory for SFB (the 512 bytes we saw in part 2's stage count). #### 5.2 Why Only 32 Tokens That column shift turned out to be the catch. According to the kernel's comments, `tcgen05.mma` faults with a misaligned address when the SFB column shift is odd, so a tile that starts at token 32 (shift 1) or 96 (shift 3) crashes. (The 64-wide tile also shifts SFB, by two columns, which is fine.) So the kernel only allows narrow tiles while every tile starts in the first 32 tokens of the chunk, which means that the kernel's N, the number of tokens in the swapped orientation, has to be at most 32: ```python # excerpt from dense_blockscaled_gemm_sm100.py NARROW_TILE_MAX_N = 32 # ... return tile_n >= 64 or kernel_n <= cls.NARROW_TILE_MAX_N ``` Here is the arithmetic for all narrow tiles, which also shows why 32 is the limit: ```python def sfb_shift(tile_n, tile_index): tok_off = tile_index % (128 // tile_n) * tile_n return tok_off // 32, tok_off % 32 * 16 # (TMEM column, smem bytes) for tile_n in (8, 16, 32): tiles = [sfb_shift(tile_n, i) for i in range(128 // tile_n)] fits = [s for i, s in enumerate(tiles) if (i + 1) * tile_n <= 32] print(tile_n, "tokens <= 32:", fits, "first odd shift at tile", next(i for i, (c, _) in enumerate(tiles) if c % 2)) ``` For 8-wide tiles, the four tiles that cover tokens 0 to 31 all have column shift 0 and start 0, 128, 256 and 384 bytes into the chunk, and the first odd shift comes with tile 4, at token 32. For 16-wide tiles it's tiles 0 and 1, then tile 2 at token 32, and for 32-wide tiles only tile 0, with tile 1 again at token 32. So "at most 32 tokens" is exactly "never an odd column shift". Figure 3 shows the shared chunk. ![How narrow tiles share one 128-row chunk of SFB](https://sleepy-capybara.vercel.app/sm100-gemm/3-tactics/figures/fig03_narrow_sfb.png) *Figure 3: The 128 token rows of one SFB chunk, in TMEM columns of 32. 16-wide tiles 0 and 1 start in column 0 and only differ in their shared-memory offset; tile 2 would need a column shift of 1, which faults, so the kernel limits narrow tiles to 32 tokens.* `can_implement` also rejects narrow tiles in clusters with more than one CTA along N, so the SFB chunk of a narrow tile is never multicast. And it explains the stale-tactic check in the runner's `forward`: the autotuner's cache is bucketed by M, so a tactic tuned for 16 tokens could be replayed for 40, which would fault. The runner checks `narrow_tile_ok` before every launch and falls back to the untuned choice if it fails. One more thing I noticed while measuring: for M up to 32, the runner lists (256, 8) among the narrow tiles it allows, and `can_implement` accepts it, but the CTA-pair instruction requires N to be a multiple of 16 (part 1), so CuTe DSL rejects that tile when the kernel is built. None of the runner's ranked tactics for our shapes used it, but it's a candidate that can never run. #### 5.3 Which Narrow Tile? With three narrow tiles to choose from, which one should a given M use? A tile covers `tile_n` tokens, so with 16 tokens and 8-wide tiles, the kernel needs two tiles along N, and each of them reads the entire weight matrix. Whether that matters depends on the layer. For the gate and up projection, with 24,576 weight rows, there are already 192 weight tiles of 128 rows, more than the 148 SMs, and splitting the tokens over two tiles doubles the work for no gain: with 16 tokens, the 8-wide tile took 32.6 microseconds against 19.7 for the 16-wide one, about the cost of reading the weights twice. The down projection has only 6,144 weight rows, so 48 weight tiles, and most SMs are idle. Here, splitting the tokens over two tiles gives the idle SMs something to do: with 16 tokens, the 8-wide and 16-wide tiles took 12.3 and 12.5 microseconds, and with 32 tokens, two 16-wide tiles beat one 32-wide tile, 12.7 against 13.2. My guess is that the second read of the weights is mostly served by L2, since the CTAs that read the same weight tile run at the same time, but I haven't measured the L2 hit rates. Either way, the rule of thumb is to use the smallest narrow tile that covers all tokens when the weight tiles already fill the GPU, and that splitting the tokens is cheap when they don't. The autotuner finds both cases on its own. ### 6. More Switches: Split-K, Deep-K, Prefetch and L2 Hints The remaining options all target the same situation: a small grid that leaves SMs idle, or a weight matrix that has to stream through once. I'll go through them briefly, with what I measured for each. **Split-K.** When the output has very few tiles (say, 20 tiles of 128 weight rows for N = 2,560), most of the 148 SMs have nothing to do. A split-K kernel cuts K into 2 or 4 slices, computes them on different CTAs of a cluster, and adds the partial results at the end. FlashInfer's `_select_sm100_mm_fp4_splitk_tactic` documents when it measured this to help on B200 and GB300: mostly for 20 or fewer weight tiles. GLM-5.3's dense layers have at least 48 weight tiles, and in my sweep, split-K was never the fastest tactic for them. For the attention output projection with one token, the untuned choice picks two slices (because K = 16,384 is long), at 15.4 microseconds against 14.9 for the best persistent tactic. **Deep-K.** The variant with 8 instructions per K tile makes every TMA row fetch 256 bytes instead of 128, which according to FlashInfer's comments helps HBM efficiency for narrow tiles once there are enough weight tiles to fill the GPU. For our three shapes, I measured it against the normal 4 instructions per K tile with the same tile and cluster: it ranged from 1% faster to 7% slower, so mostly a wash or a small loss here. **Prefetch.** With `use_prefetch`, the TMA warp issues L2 prefetches (the `cute.prefetch` from the TMA article) for the K tiles it will load next, so that the actual loads find their data in L2. Comparing each prefetch tactic in the sweep with the same tile and cluster without prefetch, it ranged from a big win to a big loss. For the attention output projection with 256 tokens and a 128 x 128 tile in a 2 x 2 cluster, prefetch took the kernel from 22.5 to 18.2 microseconds. For the down projection with 4,096 tokens and a 128 x 192 tile, it made it slower, from 116.2 to 147.9. So it is a switch for the autotuner, not one to turn on by default. **L2 eviction hints.** The runner gives the TMA loads an L2 eviction policy based on the shape (`mm_fp4_l2_policy` in `gemm_mm_fp4_cute_dsl.py`). When there are at most two tiles of tokens, the weights are read at most twice, so they are loaded with `evict_first`, which, as the function's docstring explains, keeps them from pushing the small, much-reused activation tile out of L2. When there are more token tiles and no swap, both operands are re-read many times, and both get `evict_last`. Here is what that was worth in my measurements: with 16 tokens, `evict_first` on the weights took the swapped 128 x 16 kernel from 22.8 to 20.2 microseconds for the gate and up projection, and from 13.8 to 12.5 for the down projection; with 256 tokens and a 128 x 128 tile, from 32.0 to 26.7 and from 20.3 to 17.3. With 8,192 tokens, the docstring reports 0.1 to 10% from `evict_last` on B200 and GB300, but on the B300 with our shapes I saw no difference beyond the noise. So on this machine, the hints matter for the case of streaming the weights once past a small, hot activation tile. ### 7. Timing Tactics Without Fooling Yourself #### 7.1 Cold L2 All of this depends on timing each candidate correctly, and that turns out to be harder than it looks. The obvious way, launching a kernel many times in a row and dividing the total time, measures the kernel with a warm L2 cache: the second launch finds the operands of the first one in L2. On the B300, the L2 holds 126.5 MiB, and the weights of the gate and up projection (85 MB with their scale factors) fit entirely. So a warm measurement of a decoding step measures how fast the kernel reads from L2, while in a real model, the next layer's weights are almost never in L2 when its GEMM starts. Here's what that does to the choice. For the gate and up projection with 16 tokens, Figure 4 shows every tactic that the autotuner profiles, with its warm time against its cold time. ![Warm-L2 time against cold-L2 time for every profiled tactic](https://sleepy-capybara.vercel.app/sm100-gemm/3-tactics/figures/fig04_warm_cold.png) *Figure 4: Every profiled tactic for GLM-5.3's gate and up projection with 16 tokens, timed with a warm L2 (horizontal) and with the L2 flushed before each launch (vertical). The fastest warm tactic, split-K with two slices, is among the slowest cold.* As we can see in Figure 4, the tactic that is fastest with a warm L2 is split-K with two slices, at 14.2 microseconds, but with a cold L2 it takes 26.9, while the best cold tactic takes 19.5. My guess is that split-K helps when the operands come from L2, since then more CTAs can pull from it at once, but when they come from HBM, the bandwidth is the limit, and splitting K only adds the traffic of the partial results. Across all 30 shapes, picking by warm time cost 6% on average against the best cold tactic, and up to 38%. The big losses, 34 to 38%, were all the gate and up projection with at most 16 tokens, where the warm measurement always preferred split-K; for the other shapes, the warm pick was off by 3 to 10% or not at all. That's why the `mm_fp4` tuning config sets `use_cold_l2_cache=True`. Before every sample, the autotuner zeroes a buffer of twice the L2 size, which evicts everything, and then times one launch. #### 7.2 CUDA Graphs and Timers The other half of the config is `use_cuda_graph=True`: the autotuner captures the launch in a CUDA graph and replays the graph, so that the host-side launch overhead (Python, argument packing, the driver) doesn't end up in the measurement. That overhead is not small next to these kernels. For the down projection with 16 tokens, whose kernel takes 9.4 microseconds with a warm L2, I measured about 7 microseconds of host time per call of the runner's `forward` alone, and about 55 microseconds per call of the public `mm_fp4` function, so back-to-back eager calls would mostly measure the host. Even with a graph, though, the timer matters. The autotuner's default timer is a pair of CUDA events around the graph replay. On the B300, CUDA events themselves resolve 32 nanoseconds, but the span between the two events includes the graph launch, and I measured it to add about 4.5 microseconds to every sample of these kernels, for example 24.2 microseconds by events for a kernel that CUPTI times at 19.6. Since the offset is roughly the same for every tactic, it doesn't change the ranking much: picking by event time cost only 1% on average against picking by CUPTI time, and 8% at most. But it compresses the differences, which matters when two tactics are close. FlashInfer's autotuner can also use CUPTI (its measurement policy has a `"cupti"` timer), and that's what I used for every number in this series. ### 8. Without the Autotuner Autotuning takes time, so `mm_fp4` also has an untuned path, which is what runs when a shape was never tuned. It uses the same score as the ranking, but precomputes it once per (N, K) for a fixed set of M buckets, the powers of two from 1 to 32,768, and then looks up the bucket of each call, which takes about 0.2 microseconds on the host. For small M, it first asks the split-K selector from section 6, and falls back to the score otherwise. How good is it? From the sweep, the untuned choice was within 5% of the best tactic on average and 13% in the worst case, the attention output projection with 128 tokens, where the best tactic used a 1 x 4 cluster with prefetch and the untuned one a single CTA without. For decoding shapes, it always swaps and picks a narrow tile, and most of its losses elsewhere come from the cluster shape and prefetch, which the score can't see well, and from wave effects like the one in section 3.2. So the heuristic is a reasonable default, and the autotuner adds a few percent on top, mostly at medium and large M. ### 9. Summary of the Series To summarize this part: 1. **A tactic** is (tile, cluster, swap_ab, prefetch, kernel type, extra). The runner enumerates 11 tiles, 9 clusters, both orientations and both prefetch settings, filters them with `can_implement`, ranks them with a heuristic score, and profiles the best 32. 2. **The choice matters:** the slowest profiled tactic was 1.6 times slower than the fastest on average and up to 4.4 times. The untuned choice was 5% slower on average. 3. **Tile and wave quantization** drive most of the score. At the margin the score is wrong, as for the down projection with 4,096 tokens, where better-filled waves beat a wider tile by 8%. 4. **Swapping A and B** puts the weights on the instruction's 128-row M side and the tokens on the N side, where tiles of 8, 16 and 32 are possible. It was 1.07 to 1.21 times faster for 1 to 32 tokens. 5. **Narrow tiles** share a 128-row chunk of scale factors and reach their part through a shifted TMEM column and shared-memory offset; an odd column shift faults, which is why they are limited to 32 tokens. When the weight tiles fill the GPU, the best narrow tile is the smallest one that covers all tokens; when they don't, splitting the tokens over two tiles is cheap. 6. **The extra switches** (split-K, deep-K, prefetch, L2 hints) help in specific places; the L2 hint was worth up to 17% for small and medium batches. 7. **Timing** must use a cold L2 and a CUDA graph. With a warm L2, the weights of a decoding GEMM sit in L2, and the warm winner was up to 38% slower with a cold one. And to summarize the whole series: FlashInfer's SM100 block-scaled GEMM is built around one instruction, `tcgen05.mma` with block scaling, which a single thread issues for a whole 128- or 256-row tile, reading its operands from shared memory and its scale factors from TMEM (part 1). Everything else in the kernel exists to keep that instruction busy: a TMA warp, an MMA warp and four epilogue warps connected by rings of mbarriers, two accumulators in TMEM that even overlap for the widest tiles, and a persistent loop that deals out tiles to clusters (part 2). And since no single configuration is right for every shape, the kernel is a family of configurations, and the last piece of the puzzle is picking one well, which means modeling quantization, swapping the operands for small batches, and timing the candidates the way they will actually run. ### Sources - [FlashInfer's SM100 block-scaled GEMM (dense_blockscaled_gemm_sm100.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/dense_blockscaled_gemm_sm100.py) - [FlashInfer's mm_fp4 runner and tuning configs (gemm_base.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/gemm_base.py) - [FlashInfer's tactic candidates and heuristic score (kernels/utils.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/kernels/utils.py) - [FlashInfer's compile helper and L2 policy (gemm_mm_fp4_cute_dsl.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/gemm/gemm_mm_fp4_cute_dsl.py) - [FlashInfer's autotuner (autotuner.py)](https://github.com/flashinfer-ai/flashinfer/blob/c0e62fa7b18cbf051f729214984c235eb521a551/flashinfer/autotuner/autotuner.py) - [PTX ISA: tcgen05.mma block scaling](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#tcgen05-mma-scale-factor-b) - [GLM-5.3 model card and config](https://huggingface.co/zai-org/GLM-5.3)