Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 6 (Sep 16, 2026), slides
lecture6.pdf(20 slides), Attention and MoE Kernels: FlashAttention, Context Parallelism, and SonicMoE. It also uses the context-parallelism backup slides of the parallelism lecture (Fall 2026 Lecture 5, slides 100–107). Recommended readings (course schedule): T. Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022); T. Dao, FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (2023); W. Guo et al., SonicMoE: Accelerating MoE with IO and Tile-aware Optimizations (ICLR 2026, arXiv:2512.14080). Other sources: J. Shah et al., FlashAttention-3 (2024); M. Milakov and N. Gimelshein, Online normalizer calculation for softmax (2018); H. Liu, M. Zaharia, P. Abbeel, Ring Attention with Blockwise Transformers for Near-Infinite Context (2023); S. A. Jacobs et al., DeepSpeed Ulysses (2023); the NVIDIA Megatron-Core context-parallelism documentation; N. Bhatia et al., Helix Parallelism (2025), as cited on the slides. Every number labelled measured comes fromcode/lecture07/on the author’s laptop; computed / model numbers come from the same code. Numbers labelled reported are quoted from the papers. Code:code/lecture07/:flash.py(online softmax, tiled forward and backward),attn_io.py(byte and FLOP accounting),context_parallel.py(ring attention, Ulysses, KV-parallel decode across real processes), and six demos. Reading time: ~2 hours for the prose; ~20 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain FlashAttention from first principles. Explain why materialized attention is HBM-bound, how online softmax lets attention be computed tile by tile, and why the backward pass recomputes instead of saving.
- Count its bytes. Estimate the HBM traffic and arithmetic intensity of both versions, and the role of the SRAM size and the L2 cache.
- Parallelize the sequence. Describe ring attention, Ulysses and KV-parallel decode; state when each overlaps or fits; balance causal work across ranks.
- Reason about MoE kernels. Explain how expert granularity and sparsity affect buffers and GEMM tiles, which activations a fused MoE kernel can stop saving, and why token rounding changes the computation while the other optimizations do not.
0.2 Prerequisites and scope
- Prerequisites: Lecture 2 (roofline, the attention L² crossover), Lecture 3 (tiles, waves, fusion), Lecture 4 (MoE routing), Lectures 5–6 (collectives, TP/SP, activation memory).
- Scope: the two kernels the slides study (FlashAttention, SonicMoE’s MoE layer) and the parallelism built on blockwise attention (context parallelism). Everything is checked numerically against reference computations, CP across real processes, and modelled on H100 numbers.
- Not in scope today: writing GPU kernels in CUDA/Triton/TileLang (Assignment 1 practices Triton), sparse attention kernels (Lecture 4’s DSA/NSA), and serving-time attention kernels such as paged attention (Lecture 22).
0.3 Section → code map
| Section | Idea | Code in code/lecture07/ |
|---|---|---|
| §2.1–2.3 | online softmax: the exact block merge | flash.py, 01_online_softmax.py |
| §2.4–2.6 | tiled forward, recomputing backward; saved memory and FLOPs | flash.py, 02_flash_attention.py |
| §2.7 | bytes, intensity, SRAM, L2: the H100 roofline | attn_io.py, 03_hbm_traffic.py |
| §3 | ring attention, Ulysses, KV-parallel decode, causal balance | context_parallel.py, 04_context_parallel.py |
| §3.4 | when ring attention overlaps; what CP buys in memory | 05_cp_overlap_model.py |
| §4 | MoE granularity, tiles, token rounding, saved buffers | 06_moe_kernels.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| , | sequence length; head dimension |
| one head’s queries, keys, values | |
| , , | scores, probabilities, output |
| online-softmax state of query row : running max, mass, weighted sum | |
| the log-sum-exp saved per row | |
| query-tile and key-tile heights | |
| on-chip SRAM per streaming multiprocessor (elements) | |
| , | CP group size; tokens per rank |
| query heads; KV heads | |
| tokens, experts per token, experts, expert hidden width |
1. Where we are
Lecture 6 ended with a number. For Llama-3-70B at 8k tokens, the attention scores dominate a layer’s activations: 3.56 GB per layer even with TP = 8, against 285 MB once they are recomputed. Lecture 4 added a second problem: at long context, the term of attention is arithmetic that FlashAttention does not remove. Today’s lecture is about the first problem and its consequences:
- FlashAttention removes the intermediates from memory: from HBM traffic in the forward pass, and from saved activations for the backward pass. The FLOPs stay as they are.
- Context parallelism (上下文并行) shards the one dimension no other parallelism shards completely, the sequence. Its efficient forms are built directly on FlashAttention’s blockwise structure.
- MoE kernels (SonicMoE) apply the same thinking (IO, tiles, what to save) to the other expensive layer of a modern model.
2. FlashAttention
2.1 Why materialized attention is expensive
One head computes , , . The inputs and output are , but and are : quadratic storage. At one bf16 score matrix is 2 GiB per head, so 64 heads need 128 GiB for one layer’s scores alone (demo 01 reproduces the slide’s numbers).
Materialized attention passes both intermediates through HBM. QKᵀ writes ; softmax reads and writes ; PV reads . Each boundary writes and re-reads an tensor, and softmax does little arithmetic per byte moved. Demo 03 counts it: elements for FLOPs (causal), an arithmetic intensity of FLOP/B for in bf16, whatever is. The H100’s knee is 295 FLOP/B (Lecture 2), so materialized attention is HBM-bound at every length, at 646 µs per head at .
2.2 A block average needs its weight
The fix is to never form a whole row of : process the keys in blocks and combine. The slides’ toy shows why combining is subtle. One query sees two key blocks, with unnormalized weights :
- block A: weights 1, 1 on values 0, 2 → total weight , local output ;
- block B: weight 6 on value 4 → , .
Averaging the local outputs gives . The right answer weights each block by its mass: , which is exactly the softmax over all three keys (demo 01 Part A). A block must carry its mass along with its output.
2.3 Online softmax: a small, stable summary
For a block of scores , keep
Two blocks , merge exactly, with :
The state per query is two scalars and one -vector, independent of the context length: 520 B in fp32 at , against 524 kB for a materialized bf16 row of and at 128k tokens (demo 01 Part D). This is the online softmax (在线 softmax) of Milakov and Gimelshein, FlashAttention’s Algorithm 1. Three properties make it the workhorse of this lecture:
- Stability. Subtracting the running maximum keeps every exponential ≤ 1. With scores near 1000, the unshifted overflows to infinity and the result is NaN; the online version is within 1.7e-8 of fp64 (demo 01 Part B).
- Exactness. The rescaling preserves every previously processed key. The result equals the full softmax, up to rounding.
- Associativity. The merge is associative up to rounding. Block sizes from 1 to 4,096 keys, in order or shuffled, agree with the full softmax to 1.9e-15 in fp64 (4.4e-6 in fp32, demo 01 Part C). FlashAttention can therefore choose its tiles freely, ring attention can receive K/V blocks in any rotation, and KV-parallel decode can merge shards in any order.
2.4 The forward pass: stream tiles through on-chip memory
FlashAttention’s forward pass, in FlashAttention-2’s loop order (flash.flash_forward):
- For each block of query rows (outer loop, one thread block on the GPU), initialize .
- For each block of keys and values (inner loop): load the tile into SRAM, compute the score tile, update on-chip, and discard the tile.
- Write only the final and the row statistic to HBM.
and never exist in HBM. With a causal mask, tiles entirely above the diagonal are skipped. Demo 02 checks the implementation against autograd of materialized attention over three tile shapes, causal and not: the outputs agree to 8.9e-15 in fp64 and 4.3e-6 in fp32. Same attention, up to floating-point rounding.
2.5 The backward pass trades arithmetic for memory
To back-propagate through softmax, materialized attention saves (and frameworks often also save or the mask): memory per head. FlashAttention saves only , , , and one LSE per row, and in backward recomputes each score tile and recovers the probabilities exactly, with no new softmax:
Then, tile by tile (flash.flash_backward):
with , the softmax Jacobian’s correction term. Demo 02 checks dQ, dK and dV to ~1e-15 (fp64). What it buys, measured with autograd’s saved-tensor hooks (1 × 8 heads, , fp32, causal):
| L | materialized attention saves | PyTorch’s CPU flash kernel saves | ratio |
|---|---|---|---|
| 512 | 11.8 MB | 4.21 MB | 3× |
| 1,024 | 40.9 MB | 8.42 MB | 5× |
| 2,048 | 151 MB | 16.8 MB | 9× |
| 4,096 | 579 MB | 33.7 MB | 17× |
PyTorch’s scaled_dot_product_attention on CPU runs a flash-attention kernel, and it saves exactly FlashAttention’s set: Q, K, V, O, LSE. The materialized version grows 4× per doubling of , the fused one 2×. Saved attention memory goes from to per head.
The price is FLOPs. Counted by PyTorch’s FLOP counter for one 1,024-token, 4-head layer:
- Forward: unchanged without a mask (1.07 GFLOP). With a causal mask the tiled version does fewer FLOPs, because it skips the masked tiles (570 MFLOP), while materialized attention computes the masked half anyway.
- Backward: adds per head to recompute : instead of .
For a full attention mask, a training step costs 1.17× the FLOPs. For a causal mask it costs 0.62×, because the skipped tiles outweigh the recomputation. As the slide puts it, recomputation adds FLOPs, so its time cost depends on the bottleneck.
2.6 What a laptop shows, and what it does not
Measured on this CPU, forward + backward, causal, 8 heads, , one thread:
| L | materialized | PyTorch fused flash kernel | our Python-loop tiles |
|---|---|---|---|
| 1,024 | 26.5 ms | 15.5 ms | 21.6 ms |
| 2,048 | 90.0 ms | 49.8 ms | 80.2 ms |
| 4,096 | 354 ms | 174 ms (2.0×) | — |
The fused kernel is about 2× faster. Our Python tiles, the same algorithm with causal tiles skipped, run at about the materialized version’s speed. A CPU’s automatic caches blur the split between slow memory and fast, programmer-managed SRAM that FlashAttention exploits on a GPU, so on a laptop tiling mostly buys memory. The speed-up on a GPU comes from that HBM-vs-SRAM gap, and from fusing the whole loop into one kernel. The next section models it.
2.7 Bytes on the H100: tiles, SRAM and L2 (demo 03)
FlashAttention’s traffic, per head: is read once and written once (), plus one LSE per row (). Every query block re-reads the K/V blocks it needs, , halved with a causal mask. Bigger query tiles mean fewer re-reads. On-chip, a thread block holds , , , the output accumulator ( each) and the score tile (). With 228 KB of shared memory per SM (114K bf16 elements) and , the largest square tile is .
That gives the FlashAttention paper’s HBM accesses, against materialized attention’s . Per head, , bf16, causal:
| L | materialized: bytes (FLOP/B) | flash, every K/V tile from HBM | flash, K/V re-reads via L2 | materialized → flash time |
|---|---|---|---|---|
| 4,096 | 138 MB (31) | 29.4 MB (146) | 4.20 MB (1,022) | 41.3 µs → 8.77 / 4.34 µs |
| 16,384 | 2.16 GB (32) | 440 MB (156) | 16.8 MB (4,088) | 646 µs → 131 / 69.5 µs |
| 131,072 | 138 GB (32) | 27.6 GB (159) | 134 MB* (32,704) | 41.1 ms → 8.23 / 4.45 ms |
(*One head’s K and V at 128k, 67 MB, exceed the 50 MB L2.)
The two flash columns bound reality. If every K/V tile came from HBM, FlashAttention would still be below the knee (156 FLOP/B), but 4.9× faster than materialized attention, with the same FLOPs. If the re-reads of a head’s K and V hit L2, which holds them at 16k (8 MB per head), HBM sees Q, K, V and O once, and the kernel is compute-bound: 9.3× faster. Real kernels sit between, and the speed-up is the bytes. Traffic falls as 1/tile size (4.30 GB with 16 × 16 tiles, 440 MB with 160 × 160), but SRAM caps the tile: 256 × 256 no longer fits in 228 KB.
For a whole Llama-3-70B attention layer at (64 heads), materialized attention would keep 256 GiB of and for backward. FlashAttention keeps 516 MiB of O and LSE and recomputes for 16.7% more FLOPs (causal): arithmetic traded for memory and bytes.
2.8 FlashAttention-2 and -3: closing the utilization gap
Removing the bytes leaves a different bottleneck: keeping the Tensor Cores busy.
| Bottleneck | Main idea | |
|---|---|---|
| FA2 | too few workers, too much synchronization | split query rows across thread blocks and warps (the loop order above); reduce non-matmul work |
| FA3 | data movement and softmax leave gaps between matmuls | overlap asynchronous copies, matmuls and softmax on Hopper (warp specialization, ping-pong between warp groups); an FP8 path, with quantization error |
Reported figures: FlashAttention-2 reaches 50–73% of the A100’s theoretical peak FLOP/s, and FlashAttention-3 up to 740 TFLOP/s in FP16 on H100 (75% utilization) and close to 1.2 PFLOP/s in FP8. These are the papers’ numbers, not ours. The order of the story is the course’s method in miniature. First fix the dominant term (bytes: FA1). Then the utilization of the next resource (parallelism and synchronization: FA2). Then the overlap of everything with everything (FA3).
3. Context parallelism
3.1 Splitting one sequence across GPUs
When one sequence is too large for one GPU, split its tokens across GPUs, each. Two cases need it. In training at long context, activations scale with and cannot go below 1. In serving, one long request’s KV cache can exceed a GPU. Most of the model shards trivially along the sequence: norms, MLPs and projections are token-wise. Attention does not, because each query needs keys and values from positions held by other ranks (those allowed by the mask). Two more facts from the slides:
- CP alone replicates the weights. Like DP, training must combine their gradients across the CP group; in practice CP ranks join the DP group for the gradient reduction.
- Sequence activations shrink about -fold, plus exchange buffers.
For Llama-3-70B the 80-layer stack’s activations are 365 GB per GPU at 128k tokens, even with TP = 8 + SP and selective recomputation. CP = 8 brings that to 45.6 GB. At 1M tokens: 2.92 TB, and 91.3 GB with CP = 32 (demo 05 Part C).
3.2 Ring attention: keep queries local, rotate K/V
Ring attention (环形注意力, Liu et al. 2023) keeps each rank’s in place and passes the K/V blocks around a ring. With 4 GPUs there is one local round and three neighbour exchanges. In each round a rank sends its current K/V block to the next rank, receives the next block from the previous rank, computes the partial result of its queries against the block it holds, and merges it into its output with online softmax. context_parallel.ring_attention does this with real isend/irecv calls. Positions travel with the K/V blocks so that the causal mask uses global positions.
Across 4 processes (256 tokens, 8 heads), ring attention matches full attention to 1.6e-15 (fp64) with a full mask, and with causal contiguous and causal zigzag sharding (demo 04 Part A). Each rank passes on K/V blocks: 788 kB here.
3.3 When does the transfer hide?
One ring round with local length and model width :
Compute grows as , communication as , so long local chunks make overlap easy. The scaling limit, in the slides’ words: at fixed , doubling quarters compute per round but only halves its payload. Demo 05 solves for the shortest chunk that still hides the transfer ( = 50% of BF16 peak):
| attention | NVLink | InfiniBand |
|---|---|---|
| Llama-3-70B, GQA (8 KV heads), full block pair | 209 tokens | 1.27 K |
| same, causal block pair (half the work) | 359 | 2.51 K |
| same model with MHA (64 KV heads) | 1.11 K | 9.90 K |
GQA makes ring attention easy to overlap: the K/V payload is of what MHA would send. At over InfiniBand, the ring stays fully overlapped up to , a 2,048-token chunk. At the transfer (86.9 µs per round) exceeds the compute (69.5 µs).
3.4 Causal masks need balanced placement
With a causal mask, a rank holding the last tokens has the most work: its queries see every earlier key. The slides’ 8-token example on 4 GPUs gives each GPU 2 contiguous tokens, for 3, 7, 11 and 15 query–key pairs. Pairing an early and a late chunk instead, as Megatron-Core CP does, gives 9, 9, 9, 9. Split the sequence into chunks and give rank chunks and (zigzag sharding, 之字形切分). Global positions stay unchanged, so the mask is still correct. Measured with ring attention at (4 ranks, 512 × 512 tiles):
| sharding | tiles computed per rank | compute per rank | step time |
|---|---|---|---|
| contiguous | 3, 7, 11, 15 | 20.0 – 59.8 ms | 62.1 ms |
| zigzag | 9, 9, 9, 9 | 40.4 – 45.7 ms | 49.8 ms |
With contiguous shards everyone waits for the last rank. Zigzag is 1.25× faster here; the ideal is 15/9 = 1.67×, but on one laptop four busy ranks compete for the same CPU. One implementation detail decides whether this works at all. The balance only pays if fully masked tiles are skipped: a zigzag K/V block always contains an early chunk, so skipping only whole blocks skips nothing. The first version of the code did exactly that, and zigzag came out slower than contiguous (README, “plan vs reality”).
3.5 Ulysses: trade sequence shards for head shards
DeepSpeed-Ulysses takes the other route. An AllToAll converts the sequence-sharded Q, K, V ( tokens, all heads) into head-sharded ones (all tokens, heads). Each rank then runs ordinary full-sequence attention, FlashAttention included, on its heads, and a second AllToAll restores token ownership. There are two layout exchanges in forward and two in backward. On 4 processes, Ulysses matches full attention exactly (demo 04).
The constraint is head divisibility. With GQA’s few KV heads, cannot exceed unless K/V heads are replicated. For Llama-3-70B at 128k tokens (bf16, per rank, per layer):
| CP ranks | ring: K/V passed on | Ulysses: q, k, v, o AllToAll |
|---|---|---|
| 8 | 470 MB | 528 MB |
| 16 | 503 MB | 315 MB, with the 8 KV heads replicated 2× |
An AllGather of K/V moves the same bytes as the ring, but leaves every rank holding all 537 MB of K/V: simpler local attention, but infeasible at extreme length. The slides’ summary:
| Method | Constraint to check |
|---|---|
| Ring | enough local compute to overlap each transfer (§3.3) |
| Ulysses | head divisibility, especially few KV heads under GQA |
| AllGather K, V | every rank needs the full gathered K/V |
Production systems combine them, for example Ulysses inside a node and a ring across nodes. Terminology varies by framework; recall from Lecture 6 that Megatron’s SP shards only selected activations within TP, while CP also partitions attention across the sequence.
3.6 Decode: keep the KV cache sharded
In decode there is one query per request, and the long context is the KV cache. KV-parallel decode (the idea behind the Helix work the slides cite) keeps the cache sharded along the sequence:
- broadcast the query;
- each rank scans its local KV shard and produces a partial per head;
- combine the small summaries with the online-softmax merge.
Demo 04 checks it exactly against full attention. Each rank sends numbers per head, 6.53 kB here, instead of a cache shard. The benefit is more KV capacity and more aggregate HBM bandwidth, which is what decode is bound by (Lecture 3). The cost is communication and synchronization on every decode step, on the critical path, where Lecture 5 showed α-dominated collectives hurt most. This is why systems often pick smaller CP groups for decode than for prefill.
4. MoE kernels: the SonicMoE case study
4.1 Granularity and sparsity move costs into buffers and tiles
Two design trends in MoE models change what the kernel sees ( tokens, experts per token, experts, expert width ):
- Finer experts: halve , double . Activated FFN FLOPs ∝ stay fixed, but the expanded buffers, holding each token’s activation once per selected expert, double.
- Sparser routing: increase at fixed . The average tokens per expert, , fall, and small expert batches leave partly filled GEMM tiles.
Demo 06 measures both with a seeded router ( = 16,384, = 2,048, 128-row tiles):
| configuration | expanded buffer | tokens per expert | tile padding |
|---|---|---|---|
| top-2, f = 4,096 (E = 128) | 134 MB | 256 | 24.2% |
| top-16, f = 512 (E = 128) | 1.07 GB | 2,048 | 3.1% |
| top-8, E = 32 | — | 4,096 | 1.3% |
| top-8, E = 2,048 | — | 64 | 100% |
At 64 tokens per expert, every expert’s 128-row tile is half empty: the grouped GEMM does twice the work. A grouped GEMM (分组矩阵乘) runs several experts’ matmuls in one launch, each with its own weights and row count. It removes per-expert launch overhead: measured on this CPU, torch._grouped_mm is 1.23× faster than a Python loop over 64 experts. But it cannot remove padding inside each expert’s tiles. Padding every expert to the busiest one, the simplest batched alternative, computes 8.8% extra rows here.
4.2 Saved activations vs temporary buffers
An MoE layer’s forward produces a chain of tensors:
is the input, the gate and up pre-activations, the SwiGLU output, the expert outputs. A straightforward implementation materializes the gathered expert-major copy of the inputs, , and keeps all of these for backward. SonicMoE’s choices, from the slides:
- fuse the input gathering into the matrix-multiply loads, so is never materialized;
- keep , and the routing metadata, and reorder the backward pass to use them;
- release and after their forward use, and recompute SwiGLU in backward (the GEMMs are not recomputed).
Demo 06 computes what that saves per layer and per GPU (8,192 tokens, = 7,168, bf16):
| layer | save everything | save X, H only | saving |
|---|---|---|---|
| coarse: top-2, f = 8,192 | 1.39 GB | 654 MB | 2.1× |
| DeepSeek-V3: top-8, f = 2,048 | 2.80 GB | 654 MB | 4.3× |
| fine: top-16, f = 1,024 | 4.68 GB | 654 MB | 7.2× |
The gathered inputs and expert outputs ( each) are exactly the buffers that grow with granularity. Not saving them makes fine-grained MoE affordable in activation memory, the same trade as FlashAttention’s: recompute the cheap part, keep the small part.
4.3 Overlapping grouped GEMM with IO
A GEMM tile ends with an epilogue (收尾阶段): activation functions, reductions, stores. In a naive kernel the Tensor Cores idle during it. SonicMoE overlaps one tile’s epilogue and IO with another tile’s matmul, the “ping-pong” schedule of FlashAttention-3 on Hopper: two groups of warps alternate between matmul and finish/IO. It is the same lesson as FA3: once the bytes are minimized, the next win is overlap.
4.4 Token rounding changes the computation
Token rounding (token 取整) attacks the padding of §4.1 at its source. It rounds each expert’s token count to a multiple of the tile height, up or down, guided by the router scores. Rounding up adds the highest-scoring tokens that were not yet routed to that expert; rounding down drops its lowest-scoring assignments. Demo 06 implements a “nearest multiple” version ( = 16,384, = 128, top-8):
| router | padding before → after | assignments changed | router probability mass moved |
|---|---|---|---|
| uniform | 6.5% → 0 | 2.3% (1,429 dropped, 1,557 added) | 1.4% |
| skewed | 7.1% → 0 | 5.9% | 1.6% |
Padding disappears, but some tokens now have fewer than experts and some more. The slides draw the line clearly. Fusion, online-softmax rescaling and backward reordering preserve results up to floating-point rounding; token rounding changes routing, so it changes the computation. It therefore needs what any modelling change needs: a comparison against unchanged top- routing on model quality. SonicMoE’s kernel optimizations also work with unchanged routing.
5. Summary
- Materialized attention is HBM-bound. It writes and re-reads intermediates at ~ FLOP/B (32 at ), far below the H100’s 295. At 32k tokens one head’s scores are 2 GiB.
- Online softmax keeps per query, merges blocks exactly and stably, and is associative up to rounding. Everything else in this lecture is built on it.
- FlashAttention streams K/V tiles through SRAM, writes only O and LSE, and recomputes P from LSE in backward. Measured: the same results to 1e-15, 17× less saved memory at 4k. FLOPs are unchanged forward, +25% backward (fewer overall with causal tile skipping). HBM traffic falls with tile size, capped by SRAM; with L2-resident K/V the kernel becomes compute-bound (9.3× faster in the model at 16k).
- FA2 and FA3 turn removed bytes into utilization: better work partitioning, then asynchronous overlap and FP8 on Hopper.
- Context parallelism shards the sequence. Ring attention overlaps K/V transfers once local chunks exceed ~200 tokens (NVLink) or ~1.3k (InfiniBand) for GQA. Ulysses needs divisible heads. KV-parallel decode merges tiny summaries every step. Causal masks need zigzag placement and tile-level skipping.
- MoE kernels. Granularity grows the buffers, and sparsity empties GEMM tiles. SonicMoE keeps only X and H (4.3× less for a DeepSeek-V3-shaped layer), overlaps epilogues with matmuls, and optionally rounds token counts to tiles: the one change that alters the computation.
6. Common pitfalls
- Averaging block outputs without their masses, or forgetting to rescale the old state when the maximum changes.
- Computing without subtracting the maximum.
- Calling FlashAttention approximate. It is exact attention; only the rounding differs.
- Expecting FlashAttention to remove the arithmetic. It removes the bytes; long context still needs sparse attention, hybrids (Lecture 4) or CP.
- Judging a kernel by a CPU timing. The HBM-vs-SRAM gap is a GPU property; on a laptop, measure memory.
- Contiguous causal shards in CP, or zigzag shards without tile-level skipping.
- Choosing Ulysses with without planning K/V replication.
- Assuming KV-parallel decode is free. It adds a collective to every token.
- Treating token rounding like a kernel optimization. It changes routing; evaluate quality.
7. Exercises
- Merge by hand. One query sees block A with scores (0, ln 3) and values (1, 5), and block B with score ln 4 and value 2. Compute each block’s , merge them, and check against the full softmax.
Answer
A: , , . B: , , . Merge with : , , . Full softmax: weights (sum 8), . ✓
- Materialized traffic. For one head with , in bf16, how many bytes does materialized attention’s forward move, and what is its intensity (full mask)?
Answer
MB. FLOPs GFLOP; intensity ≈ 63 FLOP/B, about for a full mask, causal. Either way, below the H100 knee.
- Why recompute? In a training step, FlashAttention’s backward does instead of FLOPs. Explain why that is usually a win on an H100.
Answer
The alternative is to save ( elements per head) and read it back. That is quadratic memory, which may not fit at all (256 GiB per Llama-3-70B layer at 32k), and quadratic HBM traffic at low intensity. Recomputing from Q and K tiles already in SRAM costs 25% more backward FLOPs at high intensity. When the step is bandwidth- or capacity-bound, that arithmetic is nearly free.
- Tile size. With 228 KB of SRAM and in bf16, what is the largest square tile by the rule ? How does FlashAttention’s K/V re-read traffic compare with ‘s 160-row tile?
Answer
: gives (multiple of 16). Re-read traffic per head is . With halved and 1.4× larger, it is lower than at ; the intensity, however, also halves with .
- Ring overlap. A model has , 32 query heads and 8 KV heads (). At 400 TFLOP/s effective and 50 GB/s per GPU (α ≈ 0), what local chunk length hides a ring step’s transfer?
Answer
tokens (double for causal block pairs).
- Causal balance. With 16 tokens on 4 ranks (4 per rank), compute the causal query–key pairs per rank for contiguous and zigzag sharding (8 chunks of 2).
Answer
Contiguous: rank holds positions , so pairs = 10, 26, 42, 58. Zigzag: rank 0 holds {0, 1, 14, 15}: 1+2+15+16 = 34; rank 1 {2, 3, 12, 13}: 3+4+13+14 = 34; ranks 2 and 3 are also 34. Balanced; total 136 = 16·17/2.
- Ulysses and GQA. A model has 48 query heads and 8 KV heads. Which CP sizes can Ulysses use without replicating K/V heads?
Answer
must divide both 48 and 8: . At the query heads would still split (3 per rank), but 8 KV heads cannot be split 16 ways, so each KV head would have to be replicated twice: under GQA the binding constraint is the KV heads.
- MoE buffers. For = 8,192 tokens, = 4,096, top-8 experts of width 1,536 in bf16, how big are the gathered inputs and the expert outputs , and what does keeping only and save, relative to keeping ?
Answer
MB each. MB, MB, MB. Everything: 67 + 537 + 403 + 201 + 537 = 1.74 GB; = 470 MB, 3.7× less.
8. The related assignment (concepts only)
Fall 2026’s Assignment 1 (performance engineering) asks for Triton kernels, profiling and MFU, and attention is the canonical example. The concepts this lecture equips you with:
- deciding a kernel’s bottleneck from its bytes and FLOPs before writing it (§2.1, §2.7);
- the online-softmax state and why the merge must rescale;
- choosing tiles under an SRAM budget, and reasoning about what is re-read and from where;
- validating a fused kernel against a reference: same output and gradients within a dtype-appropriate tolerance, as
02_flash_attention.pydoes; - measuring memory as well as time: saved-for-backward bytes are a first-class result.
No solutions or starter-code reproductions are given; the demo code here is independent of the assignment.
9. Research directions
- Attention kernels for new hardware and formats. FP8 and FP4 attention trade accuracy for throughput (FA3 reports lower error than a baseline FP8 attention). Where are the accuracy cliffs for long-context models?
- Sparse and hybrid attention kernels. DSA’s indexer and NSA’s selection (Lecture 4) need FlashAttention-quality kernels with gather; their tile efficiency is an open engineering problem.
- CP for decode. KV-parallel decode adds a collective per token. Can it be overlapped with the next layer, or with speculative decoding’s multiple queries?
- Load balance beyond causal masks. Document masks, packed sequences and sliding windows make the work per rank irregular. Balanced sharding for arbitrary masks is unsolved in general.
- When does token rounding hurt quality? SonicMoE makes routing tile-aware. Measuring the quality cost across router types and skews, and designing routers that are tile-friendly by construction, is open.
10. Further reading
- T. Dao, D. Fu, S. Ermon, A. Rudra, C. Ré, FlashAttention (NeurIPS 2022, arXiv:2205.14135); T. Dao, FlashAttention-2 (arXiv:2307.08691); J. Shah et al., FlashAttention-3 (arXiv:2407.08608).
- M. Milakov, N. Gimelshein, Online normalizer calculation for softmax (arXiv:1805.02867); M. Rabe, C. Staats, Self-attention Does Not Need O(n²) Memory (arXiv:2112.05682).
- H. Liu, M. Zaharia, P. Abbeel, Ring Attention with Blockwise Transformers for Near-Infinite Context (arXiv:2310.01889).
- S. A. Jacobs et al., DeepSpeed Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models (arXiv:2309.14509).
- NVIDIA Megatron-Core documentation: context parallelism (load-balanced causal sharding).
- W. Guo et al., SonicMoE: Accelerating MoE with IO and Tile-aware Optimizations (ICLR 2026, arXiv:2512.14080).
11. Next lecture
Lecture 8 · A Training Framework End to End: NeMo AutoModel. Lectures 5–7 built the pieces: collectives, DP/FSDP, EP, TP/SP, PP, FlashAttention, CP, grouped GEMMs. A training framework packages them behind a configuration. It provides model definitions, a parallelism plan applied in a fixed order (PP stages, then CP, then EP, then checkpointing, then FSDP), checkpoints that survive a change of layout, and an optimization loop driven by profiles. NVIDIA’s AutoModel case study takes a DeepSeek-V4-style MoE from 3.8% to 12% MFU, step by measured step. We build a miniature framework on the CPU that does the same things in small.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| FlashAttention / IO-aware attention | FlashAttention / 感知访存的注意力 |
| materialized attention / score matrix / probability matrix | 物化注意力 / 分数矩阵 / 概率矩阵 |
| online softmax / running maximum / mass | 在线 softmax / 运行最大值 / 质量(归一化和) |
| log-sum-exp (LSE) | 对数和指数 |
| numerical stability / overflow | 数值稳定性 / 上溢 |
| tile / tiling / tile size | 块 / 分块 / 块大小 |
| SRAM / shared memory / registers | 片上静态存储 / 共享内存 / 寄存器 |
| HBM traffic / L2 cache | 显存流量 / 二级缓存 |
| recomputation / saved activations | 重计算 / 保存的激活 |
| softmax Jacobian | softmax 雅可比矩阵 |
| warp specialization / asynchronous copy / ping-pong | warp 特化 / 异步拷贝 / 乒乓调度 |
| context parallelism (CP) | 上下文并行 |
| ring attention / neighbour exchange | 环形注意力 / 邻居交换 |
| DeepSpeed-Ulysses / head sharding | Ulysses 序列并行 / 按头切分 |
| causal load balance / zigzag sharding | 因果负载均衡 / 之字形切分 |
| KV-parallel decode / partial summary | KV 并行解码 / 部分摘要 |
| expert granularity / routing sparsity | 专家粒度 / 路由稀疏度 |
| grouped GEMM / tile padding / wave | 分组矩阵乘 / 分块填充 / 波次 |
| expert-major layout / gather / scatter | 按专家排列 / 收集 / 分散 |
| epilogue / fusion | 收尾阶段 / 融合 |
| token rounding | token 取整(按分块对齐) |