M3-051M3: Deep Learning FoundationsRegularization & Training TricksHard
⚡Flashcard Drill➔Mastery:

Stochastic Weight Averaging (SWA) and Weight Ensembling (Model Soups)

📐 Mathematical Definition
θSWA=1k∑i=1kθi;y^=1k∑i=1kfi(x) (ensemble)\theta_{\text{SWA}}=\frac1k\sum_{i=1}^{k}\theta_i;\qquad \hat y=\frac1k\sum_{i=1}^{k}f_i(x)\ (\text{ensemble})
⚡ One-Sentence Core Answer
SWA averages checkpoint weights along a cyclical/constant learning rate trajectory to discover flatter minima; Model Soups blend weights of multiple fine-tuned models with zero extra inference cost.

📌 Key Takeaways

  • •
    SWA mechanism: θSWA=1K∑k=1Kθk\theta_{\text{SWA}} = \frac{1}{K} \sum_{k=1}^K \theta_k sampled during late-stage training at high/cyclical LR
  • •
    Geometry of SWA: points on the boundary of a wide loss valley average into the flat interior, boosting test generalization
  • •
    Model Soups: linearly interpolates fine-tuned weights sharing the same pre-trained initialization without ensemble inference latency

📐 Mathematical Derivations

Mathematical Formulation (Izmailov et al., UAI 2018; Wortsman et al., ICML 2022):
① Stochastic Weight Averaging (SWA):
Standard SGD with learning rate decay converges to a point near the periphery of a flat loss basin. SWA maintains a cyclical or constant high learning rate schedule η\eta in late epochs, causing parameter trajectories to explore the basin boundaries. Checkpoint weights are collected every cc epochs:
θSWA(k)=kθSWA(k−1)+θkk+1\theta_{\text{SWA}}^{(k)} = \frac{k \theta_{\text{SWA}}^{(k-1)} + \theta_k}{k + 1}.
Because loss surfaces are locally convex, the geometric mean of boundary points lies deep inside the flat interior, achieving substantially lower test error and high robustness to covariate shift.
② Model Soups:
When fine-tuning the same pre-trained checkpoint with diverse hyperparameters (learning rate, augmentation, seeds), models remain in the same linear basin. Blending weights directly θsoup=∑i=1Mwiθi\theta_{\text{soup}} = \sum_{i=1}^M w_i \theta_i (where ∑wi=1\sum w_i = 1) matches or outperforms traditional multi-model output ensembling while incurring zero additional inference memory or latency overhead.

🏭 Production Trade-offs

Post-processing requirement: After computing θSWA\theta_{\text{SWA}}, the running mean and variance of all BatchNorm layers must be updated by passing training data through the model in a forward pass (torch.optim.swa_utils.update_bn). LayerNorm models do not require this calibration step.
⚠️ Common Interview Pitfalls
  • ✕
    Averaging weights of models trained from completely different random initializations; they occupy distinct loss basins, causing complete prediction collapse
  • ✕
    Evaluating SWA on BatchNorm architectures without updating running statistics, producing terrible benchmark scores
🎯 Interviewer Follow-up Inquiries
  • ?
    Why does linear weight interpolation fail between two models trained from different random initializations?
  • ?
    How does Greedy Model Soups decide which fine-tuned checkpoints to include in the average?
⚡
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-050: The Role of Exponential Moving Average (EMA) of Weights in Training📋Back to BankNext →M3-052: Label Smoothing: Role, Mathematical Mechanism, and Hidden Costs
中文速览与面试要点

什么是参数平均(SWA)与模型融合?

SWA 对轨迹上多点做等权平均,偏向平坦解;模型融合(checkpoint averaging / 集成)平均多个模型的预测或权重。

核心要点

  • 数学机理: SWA(Izmailov 等 2018) 的做法是在训练后期 周期性 地把 lr 拉高(如循环或固定高 lr),使参数在不同时间落在损失盆地内 不同但相近 的位置,然后对这些点做 等权平均 。理论依据:若这些点都在同一平坦盆地内,则它们的平均仍在盆地内且 更接近盆地中心 (平坦解),而平坦解的泛化通常更好;反之若各点落在不同盆地,平均点会落在'盆地之间的高损失脊'上,性能崩塌。 模型融合 有两个层次: (a) 权重平均 (需同盆地、且通常需重新估计 BN 统计——因为平均后的权重对应新的激活分布,BN 的 running mean/var 必须重新跑一遍数据); (b) 预测集成 ——保留多个模型分别推理再平均输出,不要求同盆地、效果最稳,但推理成本 ×k。 checkpoint averaging 是 SWA 的实用变体:对训练最后几个 epoch 的 checkpoint 做平均。
  • 深度剖析与工程权衡:① 为什么需要重估 BN ——BN 的 running statistics 依赖于当前权重的激活分布;权重平均后分布改变,若不重估,推理时归一化失配、性能显著下降。SWA 论文明确指出需'BN update pass'(用训练数据跑一遍前向更新统计)。② SWA vs EMA ——EMA 是'时间加权、单条轨迹',SWA 是'等权、周期性多采样点';EMA 更简单通用,SWA 在需要显式找平坦解时更有效。两者可叠加。③ 在 LLM 中的现实 ——权重平均在 LLM 中较少用(不同 checkpoint 常落在不同盆地,且成本高); 预测集成 在 LLM 中用于提升质量(如 self-consistency 采样多个答案投票),但那是解码层面的集成而非权重层面。④ 融合的实用价值 ——模型融合(ensemble)是竞赛提升精度的可靠手段(通常提升 1~3%),代价是推理成本;生产环境更常用 知识蒸馏 把集成压缩回单模型。⑤ 与 LoRA 的交互 ——多个 LoRA 适配器可通过权重平均合并(task arithmetic / model soup),但需注意不同任务的适配器可能落在不同盆地,平均可能失效。⑥ 面试要点 ——被问'能否把两个模型权重平均',正确回答:'只有当它们在同一损失盆地内才有效;否则应在预测层集成',并提到 BN 重估这一必要步骤。
  • SWA 需周期性高 lr 使采样点分散
  • 权重平均要求模型在同一'损失盆地'(否则有害)
  • 预测集成(ensemble)总比权重平均更稳但更贵

常见陷阱

  • 无条件平均两个独立训练的模型权重(不同盆地→崩塌)
  • 权重平均后不重估 BN 统计