M4-049M4: Sequences & TransformersEfficient Attention & FlashAttentionMedium
⚡Flashcard Drill➔Mastery:

FlashAttention Backward Pass: Recomputing Softmax in SRAM Without Saving Intermediate Matrices

📐 Mathematical Definition
saved: {mi,ℓi,Oi};P=exp⁡(S−m)/ℓ recomputed on the fly\text{saved}:\ \{m_i,\ell_i,O_i\};\quad P=\exp(S-m)/\ell\ \text{recomputed on the fly}
⚡ One-Sentence Core Answer
The backward pass saves only forward normalizers (m,ℓm, \ell), recomputing the attention matrix on-the-fly in SRAM blocks to eliminate O(N2)O(N^2) activation memory completely.

📌 Key Takeaways

  • •
    Memory saving: standard backprop saves N×NN \times N attention matrix (O(N2)O(N^2)); FlashAttention saves only scalar vectors m,ℓ∈RNm, \ell \in \mathbb{R}^N (O(N)O(N))
  • •
    Backward recomputation: loads Qi,Kj,VjQ_i, K_j, V_j and cached (mi,ℓi)(m_i, \ell_i) into SRAM, reconstructing attention block PijP_{ij} in registers
  • •
    Gradient flow: computes dQ,dK,dVdQ, dK, dV locally in fast SRAM and streams accumulated gradients back to HBM

📐 Mathematical Derivations

Mathematical Formulations of FlashAttention Backward Pass:
In standard attention backprop, the gradient formulas require the full forward attention matrix P=softmax(QKT/d)P = \text{softmax}(Q K^T / \sqrt{d}):
dV=PTdOdV = P^T dO, dP=dOVT\quad dP = dO V^T, dS=P⊙(dP−rowsum(dP⊙P))\quad dS = P \odot (dP - \text{rowsum}(dP \odot P)), dQ=1ddSK\quad dQ = \frac{1}{\sqrt{d}} dS K, dK=1ddSTQ\quad dK = \frac{1}{\sqrt{d}} dS^T Q.
Storing P∈RB×H×N×NP \in \mathbb{R}^{B \times H \times N \times N} requires tens of gigabytes of VRAM for long contexts.
FlashAttention Recomputation Trick:
- Forward Storage: FlashAttention stores ONLY the output O∈RN×dO \in \mathbb{R}^{N \times d} and the log-sum-exp normalization vector Li=mi+log⁡(ℓi)∈RNL_i = m_i + \log(\ell_i) \in \mathbb{R}^N. Storage footprint is strictly $O(N)$.
- Backward Execution Loop:
1. Load blocks Qi,Kj,VjQ_i, K_j, V_j and dOidO_i into fast SRAM.
2. Recompute local attention block in SRAM using cached LiL_i: Pij=exp⁡(QiKjTd−Li)P_{ij} = \exp\left( \frac{Q_i K_j^T}{\sqrt{d}} - L_i \right).
3. Compute dVj+=PijTdOidV_j += P_{ij}^T dO_i directly in SRAM.
4. Compute dPij=dOiVjTd P_{ij} = dO_i V_j^T, and define Di=rowsum(dOi⊙Oi)D_i = \text{rowsum}(dO_i \odot O_i).
5. Form dSij=Pij⊙(dPij−Di)d S_{ij} = P_{ij} \odot (d P_{ij} - D_i).
6. Accumulate dQi+=1ddSijKjdQ_i += \frac{1}{\sqrt{d}} d S_{ij} K_j and dKj+=1ddSijTQidK_j += \frac{1}{\sqrt{d}} d S_{ij}^T Q_i.
All intermediate matrices Pij,dPij,dSijP_{ij}, d P_{ij}, d S_{ij} live exclusively in SRAM registers and are discarded immediately.

🏭 Production Trade-offs

FLOPs vs Bandwidth Trade-off: Recomputing PijP_{ij} in backward pass adds ≈15%\approx 15\% more arithmetic FLOPs, but eliminates hundreds of gigabytes of HBM read/write traffic, resulting in an overall 2.5−4×2.5-4\times faster backward pass.
⚠️ Common Interview Pitfalls
  • ✕
    Attempting to cache intermediate attention matrices during forward pass when using FlashAttention, defeating its memory advantages
  • ✕
    Assuming FlashAttention backward pass is slower due to recomputation; memory bandwidth savings far outweigh recompute FLOPs
🎯 Interviewer Follow-up Inquiries
  • ?
    Why is the vector Di=rowsum(dOi⊙Oi)D_i = \text{rowsum}(dO_i \odot O_i) mathematically equal to rowsum(dPi⊙Pi)\text{rowsum}(dP_i \odot P_i) in backpropagation?
  • ?
    How does FlashAttention's O(N)O(N) activation memory enable training with 10×10\times longer context windows?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔
📚

Associated Knowledge Base Guides & Mindmaps

Explore the comprehensive technical article, exam cards, and global architecture tree.

← PreviousM4-048: Online Softmax: Enabling Block-by-Block Incremental Attention Tiling📋Back to BankNext →M4-050: PagedAttention: Eliminating KV-Cache Memory Fragmentation via Virtual Memory Paging
中文速览与面试要点

解释 FlashAttention 的 backward 如何避免重算整块

保存每行的 (m, ℓ) 与输出 O,反向时用它们重算 S、P(不存 L×L 矩阵),显存 O(L)。

核心要点

  • 数学机理: 标准反向的问题 ——注意力反向需要 dP(softmax 输出 P 的梯度)与 dS;而 dP 的计算需要 P=softmax(S),故标准实现 保存 P(L×L) ,显存 O(L²)。 Flash 的做法 ——前向只保存每行的 两个标量 (m_i, ℓ_i)(running max 与 running sum)与输出 O(O(L·d));反向时 重新计算 P:P=exp(S−m)/ℓ,其中 S 由 Q/K 分块重算(S=QKᵀ,只需当前分块)。这样显存从 O(L²) 降到 O(L·d) (与序列长度线性)。 反向的分块累积 ——与在线 softmax 类似,反向也可分块进行:遍历 K/V 分块,计算 dQ、dK、dV 的贡献并累积(dQ 需在所有 K 块上累积、dK/dV 在 Q 块上累积);其中也需处理'重缩放'(因为 m、ℓ 在分块中变化)。 额外 FLOPs ——重算 S 需要一次额外的 QKᵀ 与 softmax(约等于前向的注意力计算),故反向的额外开销约 +33%(前向 1 + 重算 1 + 反向 1 ≈ 3 vs 原 2)。 关键收益 ——(a) 显存 O(L²)→O(L),使长序列训练可行;(b) HBM 读写大幅减少(不需读写 L×L 矩阵),故 反向也更快 (尽管 FLOPs 略增)。这是'用计算换显存,同时因减少 IO 而净提速'的经典案例。
  • 深度剖析与工程权衡:① 与梯度检查点的对比 ——Flash Attention 的反向重算可视为'注意力内部的梯度检查点'(保存少量统计量、重算中间结果);两者思想一致,但 Flash 的重算是 kernel 内部 的、更细粒度且避免了 HBM 往返。② 'IO 减少 > FLOPs 增加' ——这是 memory-bound 场景的核心规律;若某优化减少 IO 但增加 FLOPs,仍可能净提速(只要算力有冗余)。面试中能说出这一规律很有说服力。③ 与确定性 ——分块计算的浮点求和顺序与标准实现不同,故结果有微小差异;训练时通常可接受,但需注意'可复现性'要求(见 M3 可复现性题)。④ FlashAttention-2/3 的改进 ——FA2 优化了并行度与 warp 调度(减少非 matmul 的 FLOPs、改善 occupancy);FA3 针对 Hopper 架构用 TMA 与 warp-specialization 进一步提升。⑤ 与 KV cache 的交互 ——训练时 Flash 不存 P;但 推理 decode 时需读取 KV cache(已存),此时瓶颈是 KV 的读取带宽(见 Flash-Decoding 题)。⑥ 面试要点 ——被问'Flash 的反向怎么省显存',应给出' 只存 (m, ℓ, O) 三个 O(L) 量、反向重算 S 与 P、分块累积 ',并说明'额外 FLOPs ≈ +33% 但因减少 IO 而净提速';能联系到梯度检查点是加分。
  • 只保存 O(L) 的统计量,不保存 O(L²) 的 P 矩阵
  • 反向时重算 S 与 P(需要 Q/K/V 分块)
  • 用'分块重算 + 累积'避免物化

常见陷阱

  • 以为反向必须保存 P 矩阵
  • 忽略重算带来的额外 FLOPs(约 +33%)