M4-049M4: Sequences & TransformersEfficient Attention & FlashAttentionMedium
⚡Flashcard Drill➔Mastery:
FlashAttention Backward Pass: Recomputing Softmax in SRAM Without Saving Intermediate Matrices
📐 Mathematical Definition
⚡ One-Sentence Core Answer
The backward pass saves only forward normalizers (), recomputing the attention matrix on-the-fly in SRAM blocks to eliminate activation memory completely.
📌 Key Takeaways
- •Memory saving: standard backprop saves attention matrix (); FlashAttention saves only scalar vectors ()
- •Backward recomputation: loads and cached into SRAM, reconstructing attention block in registers
- •Gradient flow: computes 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 :
, , , , .
Storing requires tens of gigabytes of VRAM for long contexts.
FlashAttention Recomputation Trick:
- Forward Storage: FlashAttention stores ONLY the output and the log-sum-exp normalization vector . Storage footprint is strictly $O(N)$.
- Backward Execution Loop:
1. Load blocks and into fast SRAM.
2. Recompute local attention block in SRAM using cached : .
3. Compute directly in SRAM.
4. Compute , and define .
5. Form .
6. Accumulate and .
All intermediate matrices live exclusively in SRAM registers and are discarded immediately.
In standard attention backprop, the gradient formulas require the full forward attention matrix :
, , , , .
Storing requires tens of gigabytes of VRAM for long contexts.
FlashAttention Recomputation Trick:
- Forward Storage: FlashAttention stores ONLY the output and the log-sum-exp normalization vector . Storage footprint is strictly $O(N)$.
- Backward Execution Loop:
1. Load blocks and into fast SRAM.
2. Recompute local attention block in SRAM using cached : .
3. Compute directly in SRAM.
4. Compute , and define .
5. Form .
6. Accumulate and .
All intermediate matrices live exclusively in SRAM registers and are discarded immediately.
🏭 Production Trade-offs
FLOPs vs Bandwidth Trade-off: Recomputing in backward pass adds more arithmetic FLOPs, but eliminates hundreds of gigabytes of HBM read/write traffic, resulting in an overall 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 mathematically equal to in backpropagation?
- ?How does FlashAttention's activation memory enable training with 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.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
解释 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%)