M3-023M3: Deep Learning FoundationsNormalization TechniquesMedium
⚡Flashcard Drill➔Mastery:
Why BatchNorm Uses Running Statistics During Inference
📐 Mathematical Definition
⚡ One-Sentence Core Answer
Inference often runs on single samples (batch size = 1) where batch variance is zero, and predictions must be deterministic and independent of other co-batched inputs.
📌 Key Takeaways
- •Single sample availability: online inference frequently evaluates , where sample variance is undefined / zero
- •Determinism requirement: the output for sample must never depend on what other unrelated samples were batched with it
- •Running statistics: computes exponential moving averages of training batch means and variances:
📐 Mathematical Derivations
Mechanisms and Failure Modes:
- Training Mode: For mini-batch :
, .
Simultaneously updates running statistics via Exponential Moving Average (EMA) with momentum :
, .
- Inference Mode (`model.eval()`):
Freezes batch statistics and uses the global running estimates: .
- Why current batch statistics fail at inference: If an inference server receives , , causing division by zero. Furthermore, if a fraudulent transaction is batched with 3 normal transactions, its prediction would change depending on who it was batched with, violating system determinism and leaking batch information.
- Training Mode: For mini-batch :
, .
Simultaneously updates running statistics via Exponential Moving Average (EMA) with momentum :
, .
- Inference Mode (`model.eval()`):
Freezes batch statistics and uses the global running estimates: .
- Why current batch statistics fail at inference: If an inference server receives , , causing division by zero. Furthermore, if a fraudulent transaction is batched with 3 normal transactions, its prediction would change depending on who it was batched with, violating system determinism and leaking batch information.
🏭 Production Trade-offs
Weight folding optimization: During inference, because are constants, BatchNorm can be mathematically folded into the preceding Conv2D layer: , , reducing inference latency to zero additional FLOPs.
⚠️ Common Interview Pitfalls
- ✕Forgetting to call
model.eval(), which causes the model to compute running stats and normalize using test batch statistics - ✕Fine-tuning on small datasets without updating or freezing running statistics appropriately, causing distribution collapse
🎯 Interviewer Follow-up Inquiries
- ?How does folding BatchNorm into Conv2D weights eliminate normalization latency during production inference?
- ?What causes training and inference performance discrepancy when fine-tuning a pretrained model with frozen BatchNorm?
⚡
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.
中文速览与面试要点
解释 BatchNorm 在推理时为什么用 running 统计
推理时无 batch(或 batch=1),且需确定性输出;running 统计是训练期 batch 统计的滑动平均。
核心要点
- 两个原因:① 推理时可能没有 batch ——线上推理常是单样本或小 batch(batch=1 时 batch 方差为 0,无法归一化);② 确定性要求 ——推理结果不应依赖'同批处理的其他样本'(否则同一输入在不同 batch 组合下输出不同,不可复现、且引入信息泄漏)。 running 统计的构造 :训练时每个 batch 计算 μ_B、σ²_B,并用滑动平均更新全局估计:μ_run←m·μ_run+(1−m)·μ_B(m 通常 0.9–0.99,等价于对最近约 1/(1−m) 个 batch 的指数加权平均);σ² 同理。推理时用 μ_run、σ²_run 归一化, 不再更新 。 为什么这样合理 :训练结束后 μ_run 近似了'整个训练集的平均统计量',故推理时用它是无偏且确定的;这与'用训练集统计量做标准化'的直觉一致。 常见 bug :① 忘记 model.eval() ——推理时仍用 batch 统计,导致结果依赖 batch 组成、且随 batch 大小变化;② running 统计未收敛 ——训练步数太少(或 momentum 太小)时 μ_run 仍偏离真实分布,推理性能差;③ 微调时冻结 BN 统计 ——若微调数据分布与预训练不同,应更新 running 统计(或改用 GN/LN),否则归一化失配。
- 实践要点:① 微调 BN 的策略 ——(a) 数据分布相似、batch 大 → 正常更新 running 统计;(b) 数据分布不同或 batch 小 → 冻结 BN 统计 (只训练 γ、β)或改用 GN/LN;这是迁移学习中的常见决策点。② 与 SyncBN ——多卡训练时若各卡 batch 小,可用 SyncBN(跨卡同步统计量,等效于大 batch);代价是通信开销。③ BN 与 dropout 的冲突 ——dropout 改变激活方差,而 BN 的 running 统计是在有 dropout 时估计的,推理时 dropout 关闭导致方差偏移(见'BN 与 dropout'题)。④ BN 的初始化 ——γ=1、β=0(恒等);running_mean=0、running_var=1(初始假设标准正态)。⑤ 诊断方法 ——对比训练与推理模式下的输出(同一输入),若差异大说明 running 统计有问题;也可打印 μ_run 与训练集真实均值对比。⑥ 替代方案 ——若 batch 太小或推理需确定性,用 LN/GN(它们训练推理一致,无此问题);这也是 Transformer 用 LN 的原因之一。
- train/eval 行为不一致是常见 bug 源
- LN/GN 无此问题
常见陷阱
- 推理时未切换到 eval 模式(BN 用 batch 统计)
- 微调时盲目冻结/更新 BN 统计而不检查分布差异