M3-002M3: Deep Learning FoundationsBackprop & AutodiffEasy
⚡Flashcard Drill➔Mastery:

Intermediate Quantities Retained for Backpropagation and Memory Optimization

📐 Mathematical Definition
checkpoint: recompute activations in backward\text{checkpoint}:\ \text{recompute activations in backward}
⚡ One-Sentence Core Answer
Backprop must save intermediate activations whose values appear in local derivative formulas; save memory via activation checkpointing, in-place operations, and fused kernels.

📌 Key Takeaways

  • •
    Saved tensors: linear layers save input activations xx (since ∂L∂W=δ⋅xT\frac{\partial \mathcal{L}}{\partial W} = \delta \cdot x^T); activations like ReLU save boolean masks
  • •
    Activation Checkpointing: discards intermediate activations and recomputes them during backward pass, reducing memory from O(L)O(L) to O(L)O(\sqrt{L})
  • •
    Fused Kernels: FlashAttention fuses attention score calculation to compute softmax on-chip (SRAM) without materializing O(N2)O(N^2) matrices in HBM

📐 Mathematical Derivations

Derivation of saved quantities: For a standard linear layer y=Wx+by = W x + b, the gradient with respect to weights is ∂L∂W=(∂L∂y)xT=δ⋅xT\frac{\partial \mathcal{L}}{\partial W} = \left(\frac{\partial \mathcal{L}}{\partial y}\right) x^T = \delta \cdot x^T. Thus, forward activation xx must be saved in GPU VRAM until the backward step.
For activation functions:
- ReLU(x)=max⁡(0,x)\text{ReLU}(x) = \max(0, x): ∂y∂x=1x>0\frac{\partial y}{\partial x} = \mathbf{1}_{x > 0}. Requires saving a 1-bit boolean mask instead of full 32-bit floats.
- Sigmoid(x)=σ(x)\text{Sigmoid}(x) = \sigma(x): σ′(x)=σ(x)(1−σ(x))\sigma'(x) = \sigma(x)(1 - \sigma(x)). Can save either input xx or output yy. Saving output yy is faster.
Activation Checkpointing (Rematerialization): Partition an LL-layer network into kk segments. Save only the boundary activations (requiring O(k)O(k) memory). During backward pass, recompute the forward pass within each segment on-the-fly (adding ∼20−30%\sim 20-30\% FLOPs overhead while cutting activation memory from O(L)O(L) to O(L)O(\sqrt{L}) for k=Lk=\sqrt{L}).

🏭 Production Trade-offs

Engineering trade-offs: Activation memory dominates model weight memory when sequence length NN or batch size BB is large. In modern LLM training, FlashAttention (tiling and online softmax) and Selective Activation Checkpointing (saving cheap layers, recomputing expensive attention/MLP activations) are standard.
⚠️ Common Interview Pitfalls
  • ✕
    Storing unnecessary intermediate tensors in global variables during training, preventing PyTorch garbage collection
  • ✕
    Applying activation checkpointing to computationally expensive layers that are memory-cheap, creating severe compute waste
🎯 Interviewer Follow-up Inquiries
  • ?
    Why does FlashAttention avoid saving the full N×NN \times N attention matrix while still computing exact gradients?
  • ?
    What is the mathematical threshold where activation memory exceeds model parameter memory in Transformer training?
⚡
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.

← PreviousM3-001: Computational Graphs and Two Automatic Differentiation Modes: Forward vs Reverse📋Back to BankNext →M3-003: Gradient Accumulation: Mathematical Equivalence and Implementation
中文速览与面试要点

反向传播需要保存哪些中间量?如何省显存

需保存激活值与局部梯度;可用梯度检查点、混合精度、分片(FSDP)降低显存。

核心要点

  • 保存内容:反向传播需要 (a) 前向的中间激活 (用于计算局部雅可比,如 attention 的 softmax 输出、激活函数输出);(b) 局部导数所需的额外量 (如 BatchNorm 的均值方差、dropout 的 mask);(c) 参数本身(若参数被覆盖则需保留副本)。 显存分布 (Adam + FP32 主权重 + FP16 计算,混合精度):参数 2B、梯度 2B、FP32 主权重 4B、Adam 的 m 与 v 各 4B → 优化器状态与主权重合计 16B/参数 (远超参数本身);而 激活 与 batch×序列长度成正比(长序列时成为主要瓶颈)。 四类省显存手段 :① 梯度检查点 ——只保存少数'检查点'的激活,反向时重算中间激活,显存从 O(n) 降到 O(√n),代价约 30% 额外计算;② 混合精度 ——激活用 FP16/BF16(减半);③ 分片 ——FSDP/ZeRO 把优化器状态、梯度、参数分片到多卡;④ 激活卸载(offloading) ——把激活换出到 CPU 内存(用 PCIe 带宽换显存)。
  • 实践要点:① 检查点的时间-内存权衡 ——√n 的来源是'分块检查点':把 L 层分成 √L 块、每块存一个检查点,反向时逐块重算;时间代价约为 1 次额外前向(30% 左右)。② 哪些层值得检查 ——激活大的层(attention、大 FFN)收益最大;小层(LayerNorm)不值得。③ 与混合精度的叠加 ——两者独立可叠加;但注意 FP16 激活下重算需保持数值一致(框架自动处理)。④ 优化器状态的优化 —— 8-bit Adam (bitsandbytes)把 m、v 量化为 8-bit,显存从 8B 降到 2B/参数; Adafactor 用分解近似二阶矩(只存行/列统计),显存从 O(n) 降到 O(√n)。⑤ 长序列的特殊问题 ——激活 ∝ batch×seq×hidden×layers,长上下文时激活常超过参数与优化器状态;此时应优先用检查点 + FlashAttention(不物化 L×L 矩阵)。⑥ 诊断 ——用 torch.cuda.max_memory_allocated() 与显存剖析工具确认瓶颈在激活还是优化器状态,再决定优化方向(这是省显存的第一步)。
  • 检查点用计算换内存(约 √n 内存)
  • FSDP/ZeRO 分片优化器状态与梯度

常见陷阱

  • 盲目开检查点而不诊断瓶颈(可能优化错方向)
  • 忽略优化器状态占 16B/参数这一事实