Lecture 7 · Attention and MoE Kernels: FlashAttention, Context Parallelism, SonicMoE

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 07。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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 from code/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:

  1. 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.
  2. Count its bytes. Estimate the HBM traffic and arithmetic intensity of both versions, and the role of the SRAM size and the L2 cache.
  3. Parallelize the sequence. Describe ring attention, Ulysses and KV-parallel decode; state when each overlaps or fits; balance causal work across ranks.
  4. 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

SectionIdeaCode in code/lecture07/
§2.1–2.3online softmax: the exact block mergeflash.py, 01_online_softmax.py
§2.4–2.6tiled forward, recomputing backward; saved memory and FLOPsflash.py, 02_flash_attention.py
§2.7bytes, intensity, SRAM, L2: the H100 rooflineattn_io.py, 03_hbm_traffic.py
§3ring attention, Ulysses, KV-parallel decode, causal balancecontext_parallel.py, 04_context_parallel.py
§3.4when ring attention overlaps; what CP buys in memory05_cp_overlap_model.py
§4MoE granularity, tiles, token rounding, saved buffers06_moe_kernels.py

0.4 Notation

SymbolMeaning
LL, ddsequence length; head dimension
Q,K,V∈RL×dQ, K, V \in \mathbb{R}^{L \times d}one head’s queries, keys, values
S=QK⊤/dS = QK^\top/\sqrt d, P=softmax(S)P = \text{softmax}(S), O=PVO = PVscores, probabilities, output
mi,ℓi,uim_i, \ell_i, u_ionline-softmax state of query row ii: running max, mass, weighted sum
LSEi=mi+log⁡ℓi\text{LSE}_i = m_i + \log \ell_ithe log-sum-exp saved per row
Br,BcB_r, B_cquery-tile and key-tile heights
MMon-chip SRAM per streaming multiprocessor (elements)
pp, c=L/pc = L/pCP group size; tokens per rank
nq,nkvn_q, n_{kv}query heads; KV heads
T,k,E,fT, k, E, ftokens, 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 L2L^2 term of attention is arithmetic that FlashAttention does not remove. Today’s lecture is about the first problem and its consequences:

  • FlashAttention removes the L×LL \times L 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 S=QK⊤/dS = QK^\top/\sqrt d, P=softmax(S)P = \text{softmax}(S), O=PVO = PV. The inputs and output are L×dL \times d, but SS and PP are L×LL \times L: quadratic storage. At L=32,768L = 32{,}768 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 SS; softmax reads SS and writes PP; PV reads PP. Each boundary writes and re-reads an L×LL \times L tensor, and softmax does little arithmetic per byte moved. Demo 03 counts it: 4Ld+4L24Ld + 4L^2 elements for 2L2d2L^2d FLOPs (causal), an arithmetic intensity of d/4=32d/4 = 32 FLOP/B for d=128d = 128 in bf16, whatever LL 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 L=16,384L = 16{,}384.

2.2 A block average needs its weight

The fix is to never form a whole row of PP: process the keys in blocks and combine. The slides’ toy shows why combining is subtle. One query sees two key blocks, with unnormalized weights ese^{s}:

  • block A: weights 1, 1 on values 0, 2 → total weight zA=2z_A = 2, local output oA=1o_A = 1;
  • block B: weight 6 on value 4 → zB=6z_B = 6, oB=4o_B = 4.

Averaging the local outputs gives (1+4)/2=2.5(1 + 4)/2 = 2.5. The right answer weights each block by its mass: (zAoA+zBoB)/(zA+zB)=(2+24)/8=3.25(z_A o_A + z_B o_B)/(z_A + z_B) = (2 + 24)/8 = 3.25, 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 sjs_j, keep

m=max⁡jsj,ℓ=∑jesj−m,u=∑jesj−mvj.m = \max_j s_j, \qquad \ell = \sum_j e^{s_j - m}, \qquad u = \sum_j e^{s_j - m} v_j .

Two blocks aa, bb merge exactly, with m=max⁡(ma,mb)m = \max(m_a, m_b):

ℓ=ema−mℓa+emb−mℓb,u=ema−mua+emb−mub,o=u/ℓ.\ell = e^{m_a - m}\ell_a + e^{m_b - m}\ell_b, \qquad u = e^{m_a - m}u_a + e^{m_b - m}u_b, \qquad o = u/\ell .

The state per query is two scalars and one dd-vector, independent of the context length: 520 B in fp32 at d=128d = 128, against 524 kB for a materialized bf16 row of SS and PP 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 ese^{s} 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):

  1. For each block of BrB_r query rows (outer loop, one thread block on the GPU), initialize (m,ℓ,u)(m, \ell, u).
  2. For each block of BcB_c keys and values (inner loop): load the Kj,VjK_j, V_j tile into SRAM, compute the Br×BcB_r \times B_c score tile, update (m,ℓ,u)(m, \ell, u) on-chip, and discard the tile.
  3. Write only the final Oi=u/ℓO_i = u/\ell and the row statistic LSEi=m+log⁡ℓ\text{LSE}_i = m + \log\ell to HBM.

SS and PP 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 PP (and frameworks often also save SS or the mask): O(L2)O(L^2) memory per head. FlashAttention saves only QQ, KK, VV, OO and one LSE per row, and in backward recomputes each score tile and recovers the probabilities exactly, with no new softmax:

Pij=exp⁡(Sij−LSEi).P_{ij} = \exp(S_{ij} - \text{LSE}_i).

Then, tile by tile (flash.flash_backward):

dVj+=P⊤dOi,dP=dOiVj⊤,dS=P∘(dP−Di),dQi+=dS Kj/d,dKj+=dS⊤Qi/d,dV_j \mathrel{+}= P^\top dO_i,\quad dP = dO_i V_j^\top,\quad dS = P \circ (dP - D_i),\quad dQ_i \mathrel{+}= dS\,K_j/\sqrt d,\quad dK_j \mathrel{+}= dS^\top Q_i/\sqrt d,

with Di=rowsum(dOi∘Oi)D_i = \text{rowsum}(dO_i \circ O_i), 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, d=64d = 64, fp32, causal):

Lmaterialized attention savesPyTorch’s CPU flash kernel savesratio
51211.8 MB4.21 MB3×
1,02440.9 MB8.42 MB5×
2,048151 MB16.8 MB9×
4,096579 MB33.7 MB17×

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 LL, the fused one 2×. Saved attention memory goes from O(L2+Ld)O(L^2 + Ld) to O(Ld)O(Ld) 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 2L2d2L^2d per head to recompute SS: 10L2d10L^2d instead of 8L2d8L^2d.

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, d=64d = 64, one thread:

LmaterializedPyTorch fused flash kernelour Python-loop tiles
1,02426.5 ms15.5 ms21.6 ms
2,04890.0 ms49.8 ms80.2 ms
4,096354 ms174 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: QQ is read once and OO written once (2Ld2Ld), plus one LSE per row (LL). Every query block re-reads the K/V blocks it needs, (L/Br)⋅2Ld(L/B_r) \cdot 2Ld, halved with a causal mask. Bigger query tiles mean fewer re-reads. On-chip, a thread block holds QiQ_i, KjK_j, VjV_j, the output accumulator (B×dB \times d each) and the score tile (B×BB \times B). With 228 KB of shared memory per SM (114K bf16 elements) and d=128d = 128, the largest square tile is B=160B = 160.

That gives the FlashAttention paper’s Θ(L2d2/M)\Theta(L^2 d^2 / M) HBM accesses, against materialized attention’s Θ(Ld+L2)\Theta(Ld + L^2). Per head, d=128d = 128, bf16, causal:

Lmaterialized: bytes (FLOP/B)flash, every K/V tile from HBMflash, K/V re-reads via L2materialized → flash time
4,096138 MB (31)29.4 MB (146)4.20 MB (1,022)41.3 µs → 8.77 / 4.34 µs
16,3842.16 GB (32)440 MB (156)16.8 MB (4,088)646 µs → 131 / 69.5 µs
131,072138 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 L=32,768L = 32{,}768 (64 heads), materialized attention would keep 256 GiB of SS and PP for backward. FlashAttention keeps 516 MiB of O and LSE and recomputes SS 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.

BottleneckMain idea
FA2too few workers, too much synchronizationsplit query rows across thread blocks and warps (the loop order above); reduce non-matmul work
FA3data movement and softmax leave gaps between matmulsoverlap 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 pp GPUs, L/pL/p each. Two cases need it. In training at long context, activations scale with B⋅LB \cdot L and BB 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 pp-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 QrQ_r 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 (p−1)(p - 1) K/V blocks: 788 kB here.

3.3 When does the transfer hide?

One ring round with local length c=L/pc = L/p and model width D=nqdD = n_q d:

tcompute≈4c2DFeff,tcomm≈α+2c nkv d bBWeff.t_{\text{compute}} \approx \frac{4c^2 D}{F_{\text{eff}}}, \qquad t_{\text{comm}} \approx \alpha + \frac{2c\, n_{kv}\, d\, b}{BW_{\text{eff}}}.

Compute grows as c2c^2, communication as cc, so long local chunks make overlap easy. The scaling limit, in the slides’ words: at fixed LL, doubling pp quarters compute per round but only halves its payload. Demo 05 solves for the shortest chunk that still hides the transfer (FeffF_{\text{eff}} = 50% of BF16 peak):

attentionNVLinkInfiniBand
Llama-3-70B, GQA (8 KV heads), full block pair209 tokens1.27 K
same, causal block pair (half the work)3592.51 K
same model with MHA (64 KV heads)1.11 K9.90 K

GQA makes ring attention easy to overlap: the K/V payload is nkv/nq=1/8n_{kv}/n_q = 1/8 of what MHA would send. At L=131,072L = 131{,}072 over InfiniBand, the ring stays fully overlapped up to p=64p = 64, a 2,048-token chunk. At p=128p = 128 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 2p2p chunks and give rank rr chunks rr and 2p−1−r2p - 1 - r (zigzag sharding, 之字形切分). Global positions stay unchanged, so the mask is still correct. Measured with ring attention at L=4,096L = 4{,}096 (4 ranks, 512 × 512 tiles):

shardingtiles computed per rankcompute per rankstep time
contiguous3, 7, 11, 1520.0 – 59.8 ms62.1 ms
zigzag9, 9, 9, 940.4 – 45.7 ms49.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 (L/pL/p tokens, all heads) into head-sharded ones (all LL tokens, n/pn/p 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, pp cannot exceed nkvn_{kv} unless K/V heads are replicated. For Llama-3-70B at 128k tokens (bf16, per rank, per layer):

CP ranksring: K/V passed onUlysses: q, k, v, o AllToAll
8470 MB528 MB
16503 MB315 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:

MethodConstraint to check
Ringenough local compute to overlap each transfer (§3.3)
Ulysseshead divisibility, especially few KV heads under GQA
AllGather K, Vevery 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:

  1. broadcast the query;
  2. each rank scans its local KV shard and produces a partial (m,ℓ,u)(m, \ell, u) per head;
  3. combine the small summaries with the online-softmax merge.

Demo 04 checks it exactly against full attention. Each rank sends (2+d)(2 + d) 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 (TT tokens, kk experts per token, EE experts, expert width ff):

  • Finer experts: halve ff, double kk. Activated FFN FLOPs ∝ TkDfTkDf stay fixed, but the expanded Tk×DTk \times D buffers, holding each token’s activation once per selected expert, double.
  • Sparser routing: increase EE at fixed kk. The average tokens per expert, Mˉ=Tk/E\bar M = Tk/E, fall, and small expert batches leave partly filled GEMM tiles.

Demo 06 measures both with a seeded router (TT = 16,384, DD = 2,048, 128-row tiles):

configurationexpanded buffertokens per experttile padding
top-2, f = 4,096 (E = 128)134 MB25624.2%
top-16, f = 512 (E = 128)1.07 GB2,0483.1%
top-8, E = 32—4,0961.3%
top-8, E = 2,048—64100%

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:

X→gather + up/gateH→SwiGLUA→downYe→weighted combineO.X \xrightarrow{\text{gather + up/gate}} H \xrightarrow{\text{SwiGLU}} A \xrightarrow{\text{down}} Y_e \xrightarrow{\text{weighted combine}} O .

XX is the input, HH the gate and up pre-activations, AA the SwiGLU output, YeY_e the expert outputs. A straightforward implementation materializes the gathered expert-major copy of the inputs, XeX_e, and keeps all of these for backward. SonicMoE’s choices, from the slides:

  • fuse the input gathering into the matrix-multiply loads, so XeX_e is never materialized;
  • keep XX, HH and the routing metadata, and reorder the backward pass to use them;
  • release AA and YeY_e 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, DD = 7,168, bf16):

layersave everythingsave X, H onlysaving
coarse: top-2, f = 8,1921.39 GB654 MB2.1×
DeepSeek-V3: top-8, f = 2,0482.80 GB654 MB4.3×
fine: top-16, f = 1,0244.68 GB654 MB7.2×

The gathered inputs and expert outputs (Tk×DTk \times D 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 (TT = 16,384, EE = 128, top-8):

routerpadding before → afterassignments changedrouter probability mass moved
uniform6.5% → 02.3% (1,429 dropped, 1,557 added)1.4%
skewed7.1% → 05.9%1.6%

Padding disappears, but some tokens now have fewer than kk 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-kk routing on model quality. SonicMoE’s kernel optimizations also work with unchanged routing.


5. Summary

  1. Materialized attention is HBM-bound. It writes and re-reads L×LL \times L intermediates at ~d/4d/4 FLOP/B (32 at d=128d = 128), far below the H100’s 295. At 32k tokens one head’s scores are 2 GiB.
  2. Online softmax keeps (m,ℓ,u)(m, \ell, u) per query, merges blocks exactly and stably, and is associative up to rounding. Everything else in this lecture is built on it.
  3. 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).
  4. FA2 and FA3 turn removed bytes into utilization: better work partitioning, then asynchronous overlap and FP8 on Hopper.
  5. 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.
  6. MoE kernels. Granularity grows the Tk×DTk \times D 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 ese^{s} without subtracting the maximum.
  • Calling FlashAttention approximate. It is exact attention; only the rounding differs.
  • Expecting FlashAttention to remove the L2L^2 arithmetic. It removes the L2L^2 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 p>nkvp > n_{kv} 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

  1. 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 (m,ℓ,u)(m, \ell, u), merge them, and check against the full softmax.
Answer

A: mA=ln⁡3m_A = \ln 3, ℓA=e−ln⁡3+1=4/3\ell_A = e^{-\ln 3} + 1 = 4/3, uA=(1/3)⋅1+1⋅5=16/3u_A = (1/3)\cdot 1 + 1 \cdot 5 = 16/3. B: mB=ln⁡4m_B = \ln 4, ℓB=1\ell_B = 1, uB=2u_B = 2. Merge with m=ln⁡4m = \ln 4: ℓ=(3/4)(4/3)+1=2\ell = (3/4)(4/3) + 1 = 2, u=(3/4)(16/3)+2=6u = (3/4)(16/3) + 2 = 6, o=3o = 3. Full softmax: weights 1,3,41, 3, 4 (sum 8), o=(1+15+8)/8=3o = (1 + 15 + 8)/8 = 3. ✓

  1. Materialized traffic. For one head with L=8192L = 8192, d=128d = 128 in bf16, how many bytes does materialized attention’s forward move, and what is its intensity (full mask)?
Answer

(4Ld+4L2)×2=(4.19M+268M)×2≈545(4Ld + 4L^2) \times 2 = (4.19\text{M} + 268\text{M}) \times 2 \approx 545 MB. FLOPs 4L2d=34.44L^2d = 34.4 GFLOP; intensity ≈ 63 FLOP/B, about d/2d/2 for a full mask, d/4d/4 causal. Either way, below the H100 knee.

  1. Why recompute? In a training step, FlashAttention’s backward does 10L2d10L^2d instead of 8L2d8L^2d FLOPs. Explain why that is usually a win on an H100.
Answer

The alternative is to save PP (L2L^2 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 SS 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.

  1. Tile size. With 228 KB of SRAM and d=64d = 64 in bf16, what is the largest square tile by the rule (4d+B)B≤M(4d + B)B \le M? How does FlashAttention’s K/V re-read traffic compare with d=128d = 128‘s 160-row tile?
Answer

M=114,000M = 114{,}000: (256+B)B≤114,000(256 + B)B \le 114{,}000 gives B≈224B \approx 224 (multiple of 16). Re-read traffic per head is (L/B)⋅2Ld(L/B) \cdot 2Ld. With dd halved and BB 1.4× larger, it is 2×1.4=2.8×2 \times 1.4 = 2.8\times lower than at d=128d = 128; the intensity, however, also halves with dd.

  1. Ring overlap. A model has D=4096D = 4096, 32 query heads and 8 KV heads (d=128d = 128). At 400 TFLOP/s effective and 50 GB/s per GPU (α ≈ 0), what local chunk length hides a ring step’s transfer?
Answer

4c2D/F=2c nkvdb/BW⇒c=nkvdbF/(2D BW)=8⋅128⋅2⋅400e12/(2⋅4096⋅50e9)=2,0004c^2D/F = 2c\,n_{kv} d b/BW \Rightarrow c = n_{kv} d b F/(2D\,BW) = 8 \cdot 128 \cdot 2 \cdot 400\text{e}12/(2 \cdot 4096 \cdot 50\text{e}9) = 2{,}000 tokens (double for causal block pairs).

  1. 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 rr holds positions 4r..4r+34r..4r+3, so pairs =∑(pos+1)= \sum (\text{pos}+1) = 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.

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

pp must divide both 48 and 8: p∈{1,2,4,8}p \in \{1, 2, 4, 8\}. At p=16p = 16 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.

  1. MoE buffers. For TT = 8,192 tokens, DD = 4,096, top-8 experts of width 1,536 in bf16, how big are the gathered inputs XeX_e and the expert outputs YeY_e, and what does keeping only XX and HH save, relative to keeping X,Xe,H,A,YeX, X_e, H, A, Y_e?
Answer

Xe=Ye=TkD⋅2=8192⋅8⋅4096⋅2=537X_e = Y_e = Tk D \cdot 2 = 8192 \cdot 8 \cdot 4096 \cdot 2 = 537 MB each. X=67X = 67 MB, H=Tk⋅2f⋅2=403H = Tk \cdot 2f \cdot 2 = 403 MB, A=201A = 201 MB. Everything: 67 + 537 + 403 + 201 + 537 = 1.74 GB; X+HX + H = 470 MB, 3.7× less.

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.py does;
  • 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 attentionFlashAttention / 感知访存的注意力
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 Jacobiansoftmax 雅可比矩阵
warp specialization / asynchronous copy / ping-pongwarp 特化 / 异步拷贝 / 乒乓调度
context parallelism (CP)上下文并行
ring attention / neighbour exchange环形注意力 / 邻居交换
DeepSpeed-Ulysses / head shardingUlysses 序列并行 / 按头切分
causal load balance / zigzag sharding因果负载均衡 / 之字形切分
KV-parallel decode / partial summaryKV 并行解码 / 部分摘要
expert granularity / routing sparsity专家粒度 / 路由稀疏度
grouped GEMM / tile padding / wave分组矩阵乘 / 分块填充 / 波次
expert-major layout / gather / scatter按专家排列 / 收集 / 分散
epilogue / fusion收尾阶段 / 融合
token roundingtoken 取整(按分块对齐)
← 返回课程目录