Compute drives language-model quality: scaling laws show predictable loss drops with more FLOPs
Single-thread Dennard scaling (1980–2000s) ended; parallel GPU scaling grew $>1000\times$ in 10 years
Number representation: $\sim 16\times$
Complex matrix instructions: $\sim 12.5\times$
Process shrinks & sparsity: $\sim 2.5\times$ and $\sim 2\times$
Target hardware today: NVIDIA Blackwell (B200/B300, SM100 family); Ampere & Hopper appear only as history
Goal: make GPU performance predictable by connecting algorithms directly to hardware bottlenecks.
CPU vs. GPU: Latency vs. Throughput
CPUs optimize latency: finish a few complex, branch-heavy threads as fast as possible
GPUs optimize throughput: run thousands of lightweight threads in parallel and hide memory stalls by switching work
GPU Anatomy: SMs & the Memory Hierarchy
Closer = faster & smaller: registers, TMEM, and SMEM/L1 sit inside each SM; L2 is on die; HBM sits off die
On-chip SRAM is $\sim 100\times$ more expensive per byte but $\sim 8\times$ faster than off-die DRAM (HBM)
Memory Level (Ampere ref.)
Latency (cycles)
Shared memory (ld / st)
23 / 19
L1 cache
33
L2 cache
200
Global memory (HBM)
290
Historical Ampere cycle counts illustrate the order-of-magnitude gap between on-SM SRAM and off-chip HBM.
The Memory Wall & Specialized Matmul Hardware
Memory wall: compute scaled $60{,}000\times$ while DRAM bandwidth scaled only $100\times$ — feeding the compute units is the hard part
Tensor Cores (introduced in Volta) are dedicated matrix-multiply units: matmuls are $>10\times$ faster than scalar floating-point ops
Consequence: fast ML algorithms cast work as dense matmuls and ruthlessly minimize HBM movement and non-matmul ops.
CUDA Execution Model: Grids, Blocks, Warps & Threads
Thread: smallest execution unit; executes the kernel code with its own registers and coordinates (threadIdx, blockIdx)
Warp: 32 consecutively numbered threads scheduled together under SIMT (Single Instruction, Multiple Threads)
Block (CTA): group of threads placed together on one SM with shared memory; a Grid launches many independent blocks
Worked Example: Vector Add in CUDA
__global__ void vec_add(const float *a, const float *b, float *c, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
c[idx] = a[idx] + b[idx];
}
}
// Launch for n = 1,000,000 elements with 256 threads per block (8 warps):
int block_size = 256;
int grid_size = (n + block_size - 1) / block_size; // 3,907 blocks
vec_add<<<grid_size, block_size>>>(a, b, c, n);
Global index: thread 5 in block 3 computes
idx = 3 * 256 + 5 = 773
Tail guard: $3{,}907 \times 256 = 1{,}000{,}192$ threads launch; the final 192 skip work via if (idx < n)
Hardware mapping: B300's 148 SMs pull blocks dynamically from the 3,907-block grid until done
Every CUDA kernel scales seamlessly to more SMs because blocks execute independently in any order.
Warps: Latency Hiding & Control Divergence
Latency hiding: a warp stalled on memory costs nothing if another resident warp on the SM is ready to issue
Control divergence (compute, not memory): if threads inside one warp take different branches, the warp executes both paths serially
CUDA Memory Model & Synchronization
Scope hierarchy:
Per-thread: fast registers (spills go to slow local memory in HBM)
Per-block: fast on-SM shared memory
Per-grid: slow off-chip global memory
Within a block: __syncthreads() is a fast hardware barrier so threads safely share SMEM data
Across blocks: no cheap global barrier — blocks may not even run simultaneously, so cross-block exchange goes through HBM (often a new kernel launch)
Later (Part 3): Hopper/Blackwell add mbarrier for async block handoffs and clusters for neighbor-SM sharing.
Occupancy: Limits & Worked Example on B300
Occupancy = active warps resident on an SM divided by the SM's maximum warp capacity
Resident blocks per SM are capped by the tightest of three per-SM budgets:
$$\text{blocks/SM} = \min\!\left(\left\lfloor\frac{\text{SMEM}_{\text{SM}}}{\text{SMEM}_{\text{block}}}\right\rfloor,\;\left\lfloor\frac{\text{Regs}_{\text{SM}}}{\text{Regs}_{\text{thread}}\cdot T_{\text{block}}}\right\rfloor,\;\left\lfloor\frac{W_{\max}}{T_{\text{block}}/32}\right\rfloor\right)$$
Worked example — B300 (148 SMs, up to 227 KB SMEM/block, 65,536 × 32-bit regs/SM):
Launch blocks of $T_{\text{block}} = 256$ threads (8 warps) using 128 registers/thread ($32{,}768$ regs/block):
• With 96 KB SMEM/block: $\min(\lfloor 227/96\rfloor,\, \lfloor 65{,}536/32{,}768\rfloor) = \min(2, 2) = \mathbf{2\text{ blocks/SM}}$ (16 warps/SM, 296 blocks across GPU).
• With 160 KB SMEM/block: $\lfloor 227/160\rfloor = \mathbf{1\text{ block/SM}}$ (8 warps/SM, 148 blocks across GPU).
Why max occupancy is NOT the goal for Tensor Core kernels: large GEMM & attention tiles intentionally run few, large warps/blocks so each block gets maximum SMEM, registers, and TMEM for data reuse
Memory-bound elementwise kernels want high occupancy to hide HBM latency; Tensor Core kernels hide latency inside big async tiles.
Recomputation discards $s_1, s_2$ and recomputes them on-chip during backward: 5/8 the HBM traffic
Trades abundant compute for scarce HBM bandwidth and capacity — essential in FlashAttention's backward pass
Lever 4: Memory Coalescing & DRAM Burst Mode
DRAM burst mode: each row-buffer read delivers an entire contiguous burst section ($\ge 128$ bytes in practice)
Coalescing: when all 32 threads in a warp load contiguous addresses within one burst, hardware serves them in a single transaction
Shared Memory Bank Conflicts & Swizzling
Shared memory is split into 32 banks, each 4 bytes wide; successive 4-byte words map round-robin to banks 0–31
If threads in a warp access different addresses in the same bank, hardware serializes those accesses
Fix 1 — Padding: allocate 33 columns instead of 32 so column elements shift by 1 bank per row (wastes some SMEM)
Fix 2 — Swizzling: XOR row & column bits so both rows and columns spread across distinct banks with zero wasted bytes
Hardware TMA swizzle modes on Hopper and Blackwell apply this exact layout automatically during tile loads.
Lever 5 (The Big One): Tiling Matrix Multiplication
Non-tiled matmul: every element of $A$ and $B$ is read $N$ times from global memory (and row reads are uncoalesced)
Tiled matmul: each element is read $N/T$ times from HBM and reused $T$ times in SMEM — a factor of $T$ reduction in global memory traffic
Tile loads into SMEM can also be arranged for full DRAM coalescing
Tile Quantization, Alignment & the Matrix Mystery
Tile quantization: when matrix dimensions do not divide tile size, boundary blocks do mostly wasted work
Burst alignment: unaligned leading dimensions break wide vectorized loads and force slower fallback kernels
Historical case study (nanoGPT): padding vocab size $50{,}257 \to 50{,}304$ (nearest multiple of 64) gave a $\sim 25\%$ speedup despite computing more dimensions!
Rule of thumb: pad matrix dimensions (vocab, hidden size, head count) to clean multiples of tile & burst widths.
Wave Quantization: A100 Baseline vs. Blackwell B300
Historical A100 (108 SMs) with $256\times 128$ tiles:
Persistent kernels (CUTLASS, DeepGEMM): launch 1 CTA per SM (148 on B300) and loop over output tiles via a scheduler, overlapping epilogue & next-tile prologue
Cluster Launch Control (CLC) on Blackwell: hardware tile fetcher allowing persistent kernels to pull work dynamically
Split-K / Stream-K: partitions leftover tail tiles along $K$ across SMs — reduces wave quantization, though does not eliminate it completely
Part 3: Why Synchronous Kernels Break Down on Blackwell
In classic CUDA kernels (Ampere era), the same threads both issue global-to-shared loads and execute math
On Hopper & Blackwell, Tensor Core throughput outpaced everything else so sharply that synchronous load-sync-compute loops starve the Tensor Cores
The modern architectural answer:
Asynchronous hardware engines for bulk memory copies (TMA) and matrix multiply (wgmma → tcgen05)
Warp specialization: separate warps own data movement, MMA, and epilogue/softmax
Next: unpack the five hardware building blocks that make this pipeline possible on Hopper and Blackwell.
TMA (Tensor Memory Accelerator) & mbarrier
TMA: one thread launches a bulk multidimensional tile copy; hardware handles address math, bounds, and swizzling
mbarrier: asynchronous barrier in SMEM; consumers wait on byte-completion count instead of stalling the whole CTA with __syncthreads()
Example: FlashAttention-3 loads $Q, K, V$ tiles via SM90_TMA_LOAD
Asynchronous Tensor Cores: Hopper wgmma (History)
Hopper (SM90) introduced wgmma: an asynchronous Tensor Core MMA issued by a warpgroup (4 warps = 128 threads)
Direct SMEM operands: reads at least one matrix tile straight from shared memory, cutting register-file traffic
Asynchronous issue: warpgroup launches wgmma and immediately overlaps other work (e.g., softmax) before waiting on the result
Why Blackwell moved beyond wgmma:
Accumulators still lived in the general register file → high register pressure
Required coordinating 128 threads just to issue one MMA
Hopper established async MMA; Blackwell fixes its register-file bottleneck with TMEM and single-thread tcgen05.
Warp Specialization: Producer & Consumer Roles
Instead of all warps doing identical work, a single CTA assigns dedicated producer (TMA load) and consumer (MMA / math) warps
A multi-stage SMEM ring buffer with full/empty mbarriers lets loads run several tiles ahead of math
Thread block cluster (introduced in Hopper, expanded in Blackwell): group of CTAs guaranteed to run concurrently on neighboring SMs
Distributed Shared Memory (DSMEM): CTAs in a cluster can read and write each other's shared memory directly without touching HBM
TMA multicast: fetches one tile from HBM and broadcasts it to every CTA in the cluster
Tiling taken one level higher: cuts redundant HBM reads across SMs sharing the same $A$ or $B$ tiles
Blackwell (SM100): tcgen05 & Tensor Memory (TMEM)
Single-thread MMA (tcgen05): a single thread (not a 128-thread warpgroup) issues asynchronous Tensor Core MMAs — all other warps stay free for other roles
Tensor Memory (TMEM): new explicitly allocated per-SM memory of 128 lanes × 512 columns of 32-bit cells
Why TMEM matters: moving MMA accumulators out of registers eliminates register-pressure bottlenecks for fused softmax, scaling, and epilogues
TMEM is explicitly allocated and accessed by warps only when moving finished tiles out to epilogue or softmax.
Blackwell 2-CTA Cooperative MMA (cta_group::2)
cta_group::2 ("2-CTA") MMA: two SMs in a Blackwell cluster cooperate on a single, larger MMA tile
Each SM stages only half the shared operand in its SMEM and exchanges over the hardware cluster link → halves each SM's operand traffic
Used directly in FlashAttention-4's SM100 forward kernel alongside tcgen05 and TMEM
Part 4: Why Standard Attention Is Memory-Bound
Attention computes three steps for $Q, K, V \in \mathbb{R}^{N\times d}$:
$$S = QK^T \in \mathbb{R}^{N\times N},\quad P = \text{softmax}(S),\quad O = PV \in \mathbb{R}^{N\times d}$$
Standard PyTorch materializes the $N\times N$ matrix $S$, applies mask, softmax, and dropout — writing & reading $O(N^2)$ intermediates to HBM at every step
Key paradox: FlashAttention-1 (Dao et al., 2022) performs more FLOPs (due to backward recomputation) yet runs dramatically faster by cutting HBM R/W nearly $10\times$
Historical GPT-2 Benchmark (Dao et al., 2022)
Metric
Standard
FlashAttention
GFLOPs
66.6
75.2
HBM R/W (GB)
40.3
4.4
Runtime (ms)
41.7
7.3
Two ideas unlock sub-quadratic HBM traffic for exact attention: tiling (with online softmax) and backward recomputation.
FlashAttention-1 & 2 (2022–2023): Tiling K, Q, V in SRAM
Idea: load tiles of $Q, K, V$ from HBM into SRAM, compute $S_{ij} = Q_i K_j^T$, fuse softmax, multiply by $V_j$, and accumulate $O_i$ — never writing $N\times N$ matrices to HBM
Backward pass: saves only $O$ and per-row softmax stats, then recomputes $S_{ij}, P_{ij}$ tile-by-tile in SRAM
The obstacle: softmax normalizes across an entire row of $N$ keys — how do we compute it tile by tile?
Online Softmax: Tiling Across the Sequence Dimension
Milakov & Gimelshein (2018): compute numerically safe softmax without knowing the global row maximum in advance.
Rescaling $d_{j-1}$ by $e^{m_{j-1}-m_j}$ forms a telescoping sum: exact at every step!
Why it generalizes to tiles: replace single element $x_j$ with a tile of scores $S^{(t)}$ — track running row max $m^{(t)}$ and running denominator $\ell^{(t)}$
Because $O = \sum_t P^{(t)} V^{(t)}$ is linear in the weights, we can rescale the running output accumulator $O^{(t-1)}$ by the exact same factor!
All three Part-2 ideas fused: tiling ($Q, K, V$), operator fusion ($QK^T$, $\exp$, $PV$ in SRAM), and recomputation (in backward)
FA1 (2022) → FA2 (2023): FA2 keeps unnormalized $\tilde{O}$ in the inner loop (dividing by $\ell$ once at the end), parallelizes over sequence length, and cuts non-matmul FLOPs
Next: how FlashAttention-3 (Hopper) and FlashAttention-4 (Blackwell) map this exact math onto the asynchronous hardware model.
Both new ideas in FA4 follow directly from the roofline: once matmuls get fast enough, non-matmul ops become the bottleneck.
1. Moving exp2 Off the SFU (B200 vs. B300)
On B200, Tensor Cores outrun the special-function unit (MUFU) → exp2 in softmax bottlenecks attention
FA4 emulates part of the exp2 calls using a polynomial on ordinary FMA units, splitting load across MUFU + FMA
On B300 (SM103), faster SFUs remove the MUFU bottleneck → FA4 switches back to hardware exp2
2. Conditional (Lazy) Rescaling
Standard online softmax rescales the running output $\tilde{O}$ every time row max $m$ increases
FA4 lets the running max lag by a threshold and rescales $\tilde{O}$ only when $m$ jumps past that threshold
Skips most correction work while keeping the final output mathematically exact via consistent denominator tracking
Modern 1M-context models (DeepSeek-V4.1-Flash, Kimi K3, MiniMax-M3) pair sparse/compressed attention with these exact Blackwell kernel primitives.
Batch-Invariant (Deterministic) Kernels
The problem: floating-point addition is non-associative ($(a+b)+c \ne a+(b+c)$)
Standard kernels change split-K factors, reduction orders, or tile shapes as batch size varies
Result: the same prompt gets different logits depending on what else sits in the batch!
Root cause (Thinking Machines, Sept 2025): traced batch nondeterminism to matmul, RMSNorm, and attention — not floating-point atomics
Fix — batch-invariant kernels: enforce a fixed reduction tree/order per output element regardless of batch size
Early overhead: tens of percent (~34% for SGLang's deterministic mode with CUDA graphs)
Recent research (Detent, self-reported): reduced to 1.04–1.17× latency
Why it matters in 2026: RL post-training (e.g., DeepSeek-V4.1-Flash, Nemotron 3.5) requires rollout and trainer logprobs to match
Performance optimizations like dynamic split-K silently alter numerical behavior unless reduction order is pinned.
Megakernels: Removing Launch Gaps at Small Batch
Megakernels collapse an entire decode step into one persistent kernel driven by an on-GPU task scheduler
Built either by compilers (Mirage MPK) or hand-written per model
When they win: gains are largest at batch 1 (where launch latency and inter-kernel wave drains dominate) and shrink as batch grows and matmuls fill all SMs
The Modern GPU Kernel DSL Landscape (2026)
Writing Blackwell kernels spans a spectrum from automatic graph compilers down to explicit warp-role hardware control.
Tool / Language
Abstraction Level
Key Strengths & Examples
CUDA C++ / CUTLASS
Lowest (C++ / PTX)
Full hardware control; persistent GEMM & CLC templates
CuTe DSL
Low-level Python DSL
Explicit layouts, TMA, tcgen05, TMEM; used to write FlashAttention-4
TileLang
Middle-level tile DSL
Tile-centric programming with explicit pipelining; used by DeepSeek's TileKernels
NVIDIA's tile-level programming model for Tensor Core GPUs
torch.compile
Graph compiler
Automatic pointwise & reduction fusion via TorchInductor
Rule of practice: start with torch.compile and Triton; drop to TileLang, CuTe DSL, or CUTLASS/CUDA only for hot bottlenecks.
Recap: Thinking Like a Blackwell GPU
The underlying principles never changed: cut HBM traffic, keep Tensor Cores saturated, and move non-matmul work off the critical path.
Hardware shapes algorithms: Tensor Core FLOPs outpaced HBM bandwidth ($60{,}000\times$ vs. $100\times$) and SFUs → data movement and non-matmul ops dominate
Core performance levers: low precision (MXFP8, MXFP4 vs. NVFP4), fusion & CUDA graphs, recomputation, coalescing, bank-conflict-free SMEM swizzling, tiling, and persistent/CLC scheduling
Blackwell's asynchronous execution: TMA + mbarrier, warp specialization, clusters/DSMEM, tcgen05, TMEM (128×512×32b), and 2-CTA MMAs overlap loads, matmuls, and softmax
Putting it together: FlashAttention 1→4, megakernels, batch-invariant kernels, and modern DSLs (CUDA, CUTLASS, CuTe DSL, TileLang, Triton/Gluon, cuTile) turn hardware awareness into real end-to-end speed
← → / space to move · A to reveal answers · F fullscreen