Stanford CS336: Language Modeling from Scratch Lecture 5 – GPUs

Hardware Fundamentals, Performance Optimization & FlashAttention
Blackwell Edition (SM100 / B200 & B300)

Why GPUs? Compute Scaling & Lecture Roadmap

  • 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
1. GPU & CUDA Fundamentals SMs, warps, memory model, occupancy 2. Making Workloads Fast Roofline, FP8/FP4, fusion, tiling, waves 3. Asynchronous Blackwell Model TMA, warp roles, clusters, tcgen05, TMEM 4. FlashAttention 1–4 & Practice Online softmax, determinism, DSLs

Goal: make GPU performance predictable by connecting algorithms directly to hardware bottlenecks.

CPU vs. GPU: Latency vs. Throughput

CPU (Latency-Optimized) Control ALU ALU ALU ALU Large Caches DRAM GPU (Throughput-Optimized) Many Compute Units High-Bandwidth Memory (HBM) Thread Execution GPU: Hide stalls across threads W1 W2 W3 W4 CPU: Minimize single-thread latency T1 Computing Waiting on memory Die area trade-off: CPUs spend silicon on branch prediction & large caches; GPUs spend it on arithmetic throughput.

GPU Anatomy: SMs & the Memory Hierarchy

Blackwell GPU (148 SMs) Streaming Multiprocessors (SMs) On-Die L2 Cache Shared across all SMs HBM (Global Memory) Off-die DRAM stacks next to GPU Host CPU RAM (PCIe / NVLink) Inside One SM 4 Warp Schedulers Register File (65,536 × 32b) CUDA Cores FP32 / INT / SFU Tensor Cores Matrix MMA Tensor Memory (TMEM) Blackwell SM100 accumulators Shared Memory / L1 Cache Up to 227 KB/block on B300 + TMA hardware copy engine
  • 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 cache33
L2 cache200
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

20-Year Scaling Gap (Log Scale) Year (1996 → 2023+) Normalized Scaling (log) HW FLOPs: 60,000× (3.0×/2yr) DRAM BW: 100× (1.6×/2yr) Interconnect: 30× (1.4×/2yr)
Matmul vs. Non-Matmul FLOPs (Log) GPU Generation (K80 → P100 → V100 → A100 → H100+) Peak TFLOP/s (log) Tensor Core Matmul Non-Matmul FP Ops >10×

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

Grid (1 Kernel Launch) Block (0,0) Block (1,0) Block i Block ... Blocks (CTAs) are scheduled independently onto SMs e.g. 256 threads/block Block i (on 1 SM) Warp 0 (threads 0–31) Warp 1 (threads 32–63) ⋮ Warp 7 (threads 224–255) Shares 1 SMEM allocation 8 warps = 256 threads Warp (32 Threads, SIMT) 1 Warp Scheduler → 1 Instruction T0 T1 T2 T3 … T31 Same instruction, private registers idx = blockIdx.x*blockDim.x + threadIdx.x

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
1D Mapping: Blocks → Array Indices Block 00–255 Block 1256–511 … Block 3906999,936–1,000,191 Valid elements: 0 … 999,999 guarded Adjacent threads (idx, idx+1) access adjacent floats.

Every CUDA kernel scales seamlessly to more SMs because blocks execute independently in any order.

Warps: Latency Hiding & Control Divergence

Zero-Cost Warp Switching (1 Scheduler) Warp 0 LD stalled on HBM (~290 cyc) FMA Warp 1 FMA waiting on load ST Warp 2 FMA FMA Time → (SM stays busy every cycle) All resident warps keep state in registers: switch costs 0 cycles.
Control Divergence Within a Warp if (tid < 4) { A; B; } else { X; Y; } Z; T0..3 A B masked off Z T4..31 masked off X Y Z Both paths execute serially! Branches are cheap only when all 32 threads in a warp take the same path.

CUDA Memory Model & Synchronization

GPU Grid Block (0,0) Shared Memory Registers Registers Thread 0 Thread 1 __syncthreads() Block (1,0) Shared Memory Registers Registers Thread 0 Thread 1 __syncthreads() Global Memory (HBM) — R/W Per Grid Constant Memory — Read-Only Per Grid Host
  • 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

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).

Memory-bound elementwise kernels want high occupancy to hide HBM latency; Tensor Core kernels hide latency inside big async tiles.

Part 2: The Roofline Model

Arithmetic / Operational Intensity (FLOPs / Byte, log) Throughput (FLOP/s, log) Peak Tensor Core FLOP/s Registers Shared Memory BW HBM Bandwidth Roof Memory-Bound Compute-Bound Elementwise / Decode Large Dense GEMM
  • Achievable throughput: $$\text{FLOP/s} \le \min\!\big(\text{Peak FLOP/s},\; \text{Intensity}\times\text{BW}\big)$$
  • Central question: how do we avoid being memory-bound?
  • Five core levers:
    1. Low-precision math
    2. Operator fusion
    3. Recomputation
    4. Memory coalescing & bank layout
    5. Tiling (plus wave scheduling)

Every optimization in Part 2 either moves fewer bytes from HBM or raises compute done per byte fetched.

Lever 1: Low Precision & Mixed-Precision Tensor Cores

  • Fewer bits = fewer bytes moved: worked example on elementwise $\text{ReLU}(x) = \max(0, x)$ over length $n$
    • 1 read + 1 write, 1 comparison FLOP per element
    • FP32 (4 B): 8 B/FLOP ($0.125$ FLOP/B)
    • FP16/BF16 (2 B): 4 B/FLOP ($0.25$ FLOP/B) — 2× intensity
  • Precision sensitivity in practice:
    • Low precision (FP16/BF16/FP8/FP4): matmuls, most pointwise ops
    • Higher precision (FP32): reductions (sum, softmax, norm) to avoid rounding drift
    • Higher range (FP32/BF16): exp, log, pow, loss functions
Mixed-Precision Tensor Core Low-bit A Low-bit B × + more products FP32 Accumulator (TMEM on SM100) FP32 Fast low-bit multiply + high-precision sum

Hardware Tensor Cores double or quadruple throughput as input width shrinks, while FP32 accumulation guards numerical stability.

Floating-Point Formats: FP16, BF16, FP8 & MXFP8

Bit Layouts: Range (Exp) vs. Precision (Mantissa) Sign Exponent Mantissa FP16 1 5 exp 10 mantissa BF16 1 8 exp (FP32 range) 7 mantissa E4M3 1 4 exp 3 mant E5M2 1 5 exp 2 m Per-Tensor FP8 1 shared FP32 scale MXFP8 (Blackwell) 32 vals + E8M0 32 vals + E8M0 32 vals + E8M0 32 vals + E8M0 Fine-grained E8M0 scales let MXFP8 use E4M3 (more mantissa).
  • MXFP8 on Blackwell:
    • Stores data in E4M3 (more mantissa) because block scales handle dynamic range
    • 1 E8M0 scale factor per 32 values along the inner reduction axis
  • Training implication — transposes are nontrivial!
    • Forward (FPROP) needs rowwise-scaled activations & weights
    • Backward (DGRAD, WGRAD) needs transposed tensors → must transpose & re-quantize along the new reduction axis
    • Norms, softmax, master weights stay in BF16/FP32

4-Bit Microscaling on Blackwell: MXFP4 vs. NVFP4

FP4 (E2M1): Only 16 Representable Values −6 −4 −3 −2 ±0 2 3 4 6 ±{0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0} MXFP4 (OCP Standard) Block of 32 FP4 values 1 E8M0 NVFP4 (NVIDIA Blackwell) 16 FP4 vals E4M3 16 FP4 vals E4M3 + Second-Level Per-Tensor FP32 Scale
PropertyMXFP4 (OCP)NVFP4 (Blackwell)
Block size32 values16 values
Block scaleE8M0 (power of 2)E4M3 (mantissa bits)
Tensor scaleNoneFP32 per-tensor
  • Why NVFP4 preserves more accuracy at 4 bits: smaller blocks isolate outliers better, and E4M3 scales avoid power-of-two rounding loss
  • 2026 production use: Kimi K3 trains MoE experts with MXFP4 QAT; DeepSeek-V4.1-Flash stores global KV cache in FP4 (890 B/tok)

Do not conflate the two: 16-element blocks with E4M3 scales define NVFP4, not MXFP4.

Lever 2: Operator Fusion & Kernel Launch Overhead

Naive: 5 Kernels HBM sin(x) pow2 cos(x) pow2 add 5 launches + 5 HBM round-trips Fused: 1 Kernel HBM sin(x) ↓ pow2 cos(x) ↓ pow2 ↓ add 1 launch + 1 read + 1 write
  • Example: $\sin^2 x + \cos^2 x$ naively launches 5 CUDA kernels, shipping intermediates back and forth to HBM
  • Operator fusion keeps intermediates in registers and does one HBM read and write
    • Compilers like torch.compile (TorchInductor) fuse pointwise chains automatically
  • Kernel launch overhead: CPU-side launch latency leaves GPUs idle between tiny kernels
    • CUDA Graphs capture a sequence of launches and replay them in one call, bridging fusion and megakernels

Shipping data from warehouse (HBM) to factory (SM) once per chain eliminates both bandwidth waste and launch gaps.

Lever 3: Recomputation (Activation Checkpointing)

Standard (Save Activations) x sigmoid s1 sigmoid s2 sigmoid out Backwardgraph dx reads s1, s2, dout Fwd: 1 read, 3 writes Bwd: 3 reads, 1 write Total: 8 HBM accesses Recompute in Backward x sigmoid sigmoid sigmoid out Recompute+ Backward dx reads x, dout only Fwd: 1 read, 1 write Bwd: 2 reads, 1 write Total: 5 HBM accesses (5/8)
  • Backprop normally stores intermediate activations in HBM for the backward pass
  • For memory-bound ops (like 3 stacked sigmoids), saving & reloading costs 8 HBM accesses
  • 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

Coalesced Loads (1 DRAM Burst Request) T0T1T2T3 0 1 2 3 4 5 6 7 8 9 10 11 Burst section 0 Burst section 1 Burst section 2 Uncoalesced: Strided Loads (4 Bursts Wasted) M[0,0] ← T0 M[1,0] ← T1 M[2,0] ← T2 M[3,0] ← T3 In real GPUs, each burst section is ≥128 bytes. Row-Major Matrix Access Not Coalesced T0 → T1 → Threads move along rows: stride = width between T0, T1 Coalesced T0 T1 ↓ Threads move down cols: adjacent addresses per step

Shared Memory Bank Conflicts & Swizzling

32 Shared Memory Banks (4 Bytes Wide Each) Bank 0 Bank 1 Bank 2 Bank 3 … Banks 4–30 … Bank 31 Conflict-Free (1 Cycle) Stride-1 row read: T0→B0, T1→B1, …, T31→B31 32 banks served in parallel 32-Way Bank Conflict Column read of 32-col tile: T0..T31 all hit Bank 0! Serialized into 32 accesses Swizzled Layout: Bank = col ⊕ row Row 0: B0 B1 B2 B3 Row 1: B1 B0 B3 B2 Row 2: B2 B3 B0 B1 No col conflict!
  • 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

Matrix $A$ ($N\times N$) $T\times T$ × Matrix $B$ ($N\times N$) $T\times T$ = Matrix $C$ ($N\times N$) Output Phase Loop 1. Load $A, B$ tiles → SMEM 2. Sync 3. Accumulate partial sums 4. Next tile Each block owns one $T\times T$ output tile of $C$ and marches across $N/T$ phases along $K$.

Tile Quantization, Alignment & the Matrix Mystery

Tile Quantization (128×128 Tiles) 256 × 256: 4 tiles (100%) 256 × 257: 6 tiles (2 wasted) Burst Alignment Aligned: 1 clean burst/tile Unaligned: spans extra bursts
  • 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) — 256×128 Tiles 1792 98 tiles → 1 full wave 1793 Wave 1: 108 tiles Wave 2: 12 tiles (96 SMs idle) Blackwell B200/B300 (148 SMs, cc 10.3) 1793 120 tiles → still 1 wave! 2048 128 tiles → 1 wave 2049 Wave 1: 148 tiles Wave 2: 5 tiles (143 SMs idle!) Periodic throughput cliffs whenever tile count crosses a multiple of SM count
  • Historical A100 (108 SMs) with $256\times 128$ tiles:
    • $N=1792$: $(1792/256)\times(1792/128) = 7\times 14 = 98$ tiles (1 wave)
    • $N=1793$: $8\times 15 = 120$ tiles → spills into 2 waves!
  • H100 SXM (132 SMs) & B200/B300 (148 SMs): both 98 and 120 fit in a single wave
  • On B200/B300 (148 SMs), the cliff moves to $>148$ tiles:
    • $N=2048 \to 8\times 16 = 128$ tiles (1 wave)
    • $N=2049 \to 9\times 17 = 153$ tiles (2 waves; 143 SMs idle in tail)

Mitigating Wave Quantization: Persistent Kernels & Stream-K

Persistent Kernel + Cluster Launch Control (CLC) Tile Work Queue Tile 0 Tile 1 CLC next tile … Tile M−1 SM 0 (1 persistent CTA) SM 1 (1 persistent CTA) ⋮ SM 147 (1 persistent CTA) Split-K / Stream-K: Divide Tail Work Tail Output Tile Split along K K0 K1 K2 SM a computes partial K0 SM b computes partial K1 SM c computes partial K2 → sum Evenly spreads leftover tiles across all SMs.

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
Classic Synchronous CTA (All Warps Same Role) Load Tile 0 sync MMA Tile 0 sync Load Tile 1 Tensor Cores sit idle during loads & barriers Async + Warp-Specialized CTA (Blackwell) Load TMA 0 TMA 1 TMA 2 TMA 3 MMA MMA 0 MMA 1 MMA 2 Other Softmax 0 Softmax 1 Data copy, Tensor Cores & softmax run concurrently!

Next: unpack the five hardware building blocks that make this pipeline possible on Hopper and Blackwell.

TMA (Tensor Memory Accelerator) & mbarrier

Before TMA (SIMT Thread Loads) HBM Tile SMEM Tile 128+ threads compute addresses & issue loads TMA (Hopper SM90 & Blackwell SM100) 1 Threadissues 1 op TMA Copy Engine • Hardware address calc • Bounds & padding • Auto SMEM swizzle • Bulk GMEM ↔ SMEM SMEM Tile(bank-conflict free) mbarriersignals bytes done HBM Tile Coalescing still governs DRAM underneath, but software no longer hand-codes per-thread loads.

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 wgmma Dataflow Warpgroup 4 warps (128 threads) SMEM Tiles A, B operands Async Tensor Core MMA Runs while warpgroup does softmax Accumulator in Registers (bottleneck)

Hopper established async MMA; Blackwell fixes its register-file bottleneck with TMEM and single-thread tcgen05.

Warp Specialization: Producer & Consumer Roles

Producer Warp(s) • Few registers needed • Loops over tiles • Wait empty mbarrier • Issue TMA load • Signals full mbarrier SMEM Ring Buffer (Pipeline Stages) Stage 0 (ready → consumer) Stage 1 (TMA filling) Stage 2 (empty → producer) Stage 3 (empty → producer) TMA fill empty full release Consumer Warp(s) • Reallocate extra registers here • Wait full mbarrier • Run Tensor Core MMAs • Signal empty mbarrier • Softmax / epilogue
  • 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
  • Example: FlashAttention-3's Hopper mainloop uses 1 producer warp + 1 to 3 MMA warpgroups

Thread Block Clusters, Distributed SMEM & Multicast

HBM: 1 Read of Shared Tile TMA Hardware Multicast Thread Block Cluster (Co-Resident on Neighboring SMs) SM 0 / CTA 0 SMEM 0 Tile C(0,0) SM 1 / CTA 1 SMEM 1 Tile C(0,1) SM 2 / CTA 2 SMEM 2 Tile C(0,2) Distributed Shared Memory (SM-to-SM direct access)
  • 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)

Hopper SM90 (History) 128 threads issue wgmma Tensor Cores Register File MMA Accumulators + Softmax + Epilogue (severe register pressure) Blackwell SM100 (Current) 1 Thread issues tcgen05 5th-Gen Tensor Cores Tensor Memory (TMEM) 128 lanes × 512 cols × 32b Dedicated MMA accumulators Register File Freed! Dedicated to softmax & epilogue
  • 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)

2-SM Cluster Executing One Cooperative tcgen05 (cta_group::2) MMA SM 0 (CTA 0 — Leader Issues MMA) SMEM 0 Top half of A + Left B Tensor Core 0 Reads SMEM 0 & SMEM 1 TMEM 0: Top Half of Larger Output Tile Only loads 1/2 the B operand bytes per SM! Cluster Link SM 1 (CTA 1 — Partner SM) SMEM 1 Bot half of A + Right B Tensor Core 1 Reads SMEM 1 & SMEM 0 TMEM 1: Bottom Half of Larger Output Tile Only loads 1/2 the B operand bytes per SM!

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)

MetricStandardFlashAttention
GFLOPs66.675.2
HBM R/W (GB)40.34.4
Runtime (ms)41.77.3
GPT-2 Time Breakdown (Historical Baseline) Matmul Dropout (HBM) Softmax (HBM) Mask (HBM) Matmul PyTorch Fused Kernel FlashAttention

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

Memory Hierarchy (A100 Baseline) SRAM 19 TB/s (20 MB) GPU HBM 1.5 TB/s (40 GB) CPU DRAM: 12.8 GB/s (>1 TB) Same steep SRAM/HBM gap holds on Blackwell. Tiled Attention: Keep $N\times N$ Scores Inside SRAM Q K&supT; V On-Chip SRAM (No HBM Write of $S, P$) 1. $S = Q_i K_j^T$2. Online $\exp$ 3. Accum $O_i$$+ P_{ij} V_j$ Output $O$ written to HBM

Online Softmax: Tiling Across the Sequence Dimension

Milakov & Gimelshein (2018): compute numerically safe softmax without knowing the global row maximum in advance.

Standard Safe Softmax (3 Passes)

$$y_i = \frac{e^{x_i - m_V}}{\sum_{j=1}^{V} e^{x_j - m_V}},\quad m_V = \max_k x_k$$

  1. Pass 1: $m_V = \max_{1\le k \le V} x_k$
  2. Pass 2: $d_V = \sum_{j=1}^{V} e^{x_j - m_V}$
  3. Pass 3: $y_i = e^{x_i - m_V} / d_V$

Requires reading the whole row before computing any exponential.

Online Softmax (2 Passes → Tileable!)
  1. Init $m_0 = -\infty,\; d_0 = 0$
  2. For $j = 1 \dots V$: $$m_j = \max(m_{j-1},\, x_j)$$ $$d_j = d_{j-1}\cdot e^{m_{j-1} - m_j} + e^{x_j - m_j}$$
  3. Finally: $y_i = e^{x_i - m_V} / d_V$

Rescaling $d_{j-1}$ by $e^{m_{j-1}-m_j}$ forms a telescoping sum: exact at every step!

FlashAttention Forward Pass: Tiled Accumulation & Rescaling

$Q_i$ HBM → SRAM $(K^{(1)})^T$ $(K^{(2)})^T$ $S^{(1)} = Q_i(K^{(1)})^T$ $m^{(1)} = \text{max}(S^{(1)})$ $\tilde{P}^{(1)} = e^{S^{(1)}-m^{(1)}}$ $\ell^{(1)} = \sum \tilde{P}^{(1)}$ $S^{(2)} = Q_i(K^{(2)})^T$ $m^{(2)} = \max(m^{(1)}, S^{(2)})$ $\tilde{P}^{(2)} = e^{S^{(2)}-m^{(2)}}$ $\ell^{(2)} = \alpha\ell^{(1)} + \sum \tilde{P}^{(2)}$ $V^{(1)}$ $V^{(2)}$ · = Running Output Accumulator (SRAM/TMEM) Let $\alpha = e^{m^{(1)} - m^{(2)}}$ (rescaling factor) $\tilde{O}^{(1)} = \tilde{P}^{(1)} V^{(1)}$ $\tilde{O}^{(2)} = \alpha \tilde{O}^{(1)} + \tilde{P}^{(2)} V^{(2)}$ Final epilogue: $O_i = \tilde{O}^{(T)} / \ell^{(T)}$

Next: how FlashAttention-3 (Hopper) and FlashAttention-4 (Blackwell) map this exact math onto the asynchronous hardware model.

FlashAttention-3 (Hopper, 2024): Asynchronous Attention

FA3 Hopper Mainloop: Warp Specialization + Softmax/MMA Overlap Time → (Steady-State K/V Tile Pipeline) 1 Producer Warp TMA K1, V1 TMA K2, V2 TMA K3, V3 TMA K4, V4 TMA K5, V5 Consumer WG 0(4 warps, 128 thr) wgmma QK1 Softmax 1 wgmma P1V1 wgmma QK3 Softmax 3 Consumer WG 1(1–3 MMA WGs) wgmma QK2 Softmax 2 wgmma P2V2 wgmma QK4 Softmax ∥ wgmma

FlashAttention-4 (Blackwell, 2025–26): Dedicated Warp Roles

FA4 SM100 Forward Kernel (Written in CuTe DSL) Load Warp TMA loads $Q, K, V$ SMEM Swizzled ring MMA Warp (1 Thread!) tcgen05 + cta_group::2 (2-CTA) Issues $QK^T$ & $PV$ into TMEM TMEM $S_0, S_1, O_0, O_1$ Epilogue Final $O \to$ HBM 2 Softmax Warpgroups (Ping-Pong) Softmax WG 0Works on $Q$ Tile 0 Softmax WG 1Works on $Q$ Tile 1 Correction Warps Rescale running accumulator $O$ in TMEM (only when threshold crossed!)
  • Fine-grained warp specialization: 5 distinct roles — load warp (TMA), MMA warp (tcgen05/2-CTA), two ping-pong softmax warpgroups on two $Q$ tiles, correction warps, and epilogue
  • Because accumulators live in TMEM and only 1 thread launches MMAs, softmax and correction warps run with abundant registers and minimal stalls

FlashAttention-4 Innovations: exp2 & Conditional Rescaling

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

Performance optimizations like dynamic split-K silently alter numerical behavior unless reduction order is pinned.

Megakernels: Removing Launch Gaps at Small Batch

Standard Decode Step (Many Discrete Kernels) RMSNorm gap QKV Proj gap Attention gap O Proj gap MLP / MoE Launch overhead + tail drains + HBM barriers Megakernel (1 Persistent Kernel + On-GPU Task Scheduler) Norm QKV Proj Attention O Proj MLP / MoE Zero launch gaps! SMs pull ready ops dynamically Persistent CTAs stay resident across the entire layer / decode step using an on-GPU dependency queue.

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 / LanguageAbstraction LevelKey Strengths & Examples
CUDA C++ / CUTLASSLowest (C++ / PTX)Full hardware control; persistent GEMM & CLC templates
CuTe DSLLow-level Python DSLExplicit layouts, TMA, tcgen05, TMEM; used to write FlashAttention-4
TileLangMiddle-level tile DSLTile-centric programming with explicit pipelining; used by DeepSeek's TileKernels
Triton (+ Gluon)High-level block DSLProductive Python kernels; Gluon dialect exposes lower-level layouts & async ops
NVIDIA cuTileTile-based modelNVIDIA's tile-level programming model for Tensor Core GPUs
torch.compileGraph compilerAutomatic 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.