数学与经典机器学习
RS 面试里的数学不是考试题,而是"你能不能用数学把 LLM 训练里的现象讲清楚":为什么交叉熵就是 MLE、为什么 RLHF 的 KL 是反向的、GRPO 为什么用 k3 估计 KL、Adam 的 bias correction 是怎么来的、LoRA 为什么能 work。这一章把这些"底层语言"一次补齐。
建议顺序。第一遍按 §3 信息论 → §2 概率 → §4 优化 → §5 经典 ML → §1 线性代数的顺序读 ★ 概念(这几个和 LLM 面试最相关),每读完一节就做 §6 里对应的练习;第二遍打开"速记模式"只看一句话和英文回答,出声练习。
和其他模块的关系。§2 的 importance sampling 和 §3 的 KL 是 06 Post-training 与 RL(PPO ratio、KL 惩罚、GRPO)的直接前置;§4 的优化器和学习率调度会在 05 预训练 里以"大模型超参"的形式再出现;§1 的矩阵求导和 FLOPs 会在 03 反向传播 和 04 参数量/FLOPs 估算 中用到;§5 的指标和统计会在 13 评估 深入。
| 节 | 优先级 | 面试里最常见的形式 |
|---|---|---|
| §1 线性代数 | ☆ | SVD/低秩与 LoRA、矩阵求导、Jacobian 形状、matmul FLOPs |
| §2 概率统计 | ★ | Bayes 题、MLE↔CE、MAP↔正则、importance sampling、重参数化 |
| §3 信息论 | ★ | KL 非负/不对称、forward vs reverse KL、k1/k2/k3、perplexity |
| §4 优化 | ★ | Adam 全公式 + bias correction、AdamW、warmup/cosine/WSD、clipping、batch size |
| §5 经典 ML | ☆ | 偏差–方差、L1 vs L2、逻辑回归梯度、AUC/校准、PCA、k-means |
| §6 练习 | ★ | 16 道带完整解答的推导/编程/概率题 |
§1 · LINEAR ALGEBRA线性代数:把矩阵看成"变换"
面试里线性代数很少单独考,但它是所有推导的语言:矩阵求导决定你能不能手推反向传播;SVD 决定你能不能讲清 LoRA 和低秩;条件数和谱范数决定你能不能解释"为什么训练不稳";matmul FLOPs 是所有算力估算的起点。目标不是背定理,而是每个概念都能给出"几何直觉 + 一个 ML 里的用处"。
矩阵乘法 = 线性映射的复合,以及 2mnk FLOPs
矩阵 \(A\in\mathbb{R}^{m\times n}\) 是一个从 \(\mathbb{R}^n\) 到 \(\mathbb{R}^m\) 的线性映射;\(AB\) 就是"先做 \(B\) 再做 \(A\)"。一个 \((m\times k)\cdot(k\times n)\) 的矩阵乘法要 \(2mkn\) 次浮点运算。
A matrix is a linear map; matrix multiplication is composition of maps, and an (m×k)(k×n) matmul costs about 2mkn FLOPs.
四种看 \(y=Ax\) 的方式(面试时能切换视角很加分):
- 行视角:\(y_i = a_i^\top x\),每个输出是 \(A\) 的一行与 \(x\) 的点积 —— 这就是"打分"(attention 里 \(QK^\top\) 的每个元素是一个 query 和一个 key 的点积)。
- 列视角:\(y = \sum_j x_j\, A_{:,j}\),输出是 \(A\) 的列的线性组合 —— 所以 \(Ax\) 只能落在 \(A\) 的列空间里。attention 的输出 \(\text{softmax}(\cdot)V\) 就是 value 行向量的凸组合。
- 变换视角:\(A\) 把空间做旋转/拉伸/投影。SVD 告诉你任何矩阵 = 旋转 · 沿坐标轴拉伸 · 旋转。
- 外积视角:\(AB = \sum_k A_{:,k} B_{k,:}\),矩阵乘法是 \(k\) 个秩 1 矩阵之和 —— 这是理解低秩(LoRA \(BA\))的关键。
FLOPs 计算。\(C = AB\),\(A\in\mathbb{R}^{m\times k}, B\in\mathbb{R}^{k\times n}\)。\(C\) 有 \(mn\) 个元素,每个是长度 \(k\) 的点积:\(k\) 次乘法 + \(k-1\) 次加法 ≈ \(2k\)。所以总共 \(\approx 2mkn\) FLOPs(一次 multiply-add 记作 2 FLOPs)。
| 场景 | 形状 | FLOPs |
|---|---|---|
| 线性层前向,batch 里 \(T\) 个 token | \((T\times d_{in})(d_{in}\times d_{out})\) | \(2Td_{in}d_{out}\) = 2 × token 数 × 参数量 |
| 线性层反向(对输入 + 对权重各一次 matmul) | 两个同规模 matmul | \(4Td_{in}d_{out}\) |
| 前向 + 反向 | \(6 \times\) token 数 \(\times\) 参数量 → 这就是 6ND 的来源(见 m04) | |
| attention 分数 \(QK^\top\)(单头) | \((T\times d_h)(d_h\times T)\) | \(2T^2 d_h\):对序列长度是平方 |
为什么矩阵乘法的顺序会影响计算量
矩阵乘法满足结合律但不同括号的代价不同。\(A\in\mathbb{R}^{n\times d}, B\in\mathbb{R}^{d\times n}, x\in\mathbb{R}^{n}\):
- \((AB)x\):先算 \(AB\) 要 \(2n^2d\),再乘 \(x\) 要 \(2n^2\)。
- \(A(Bx)\):\(Bx\) 要 \(2nd\),再 \(A(\cdot)\) 要 \(2nd\),总共 \(4nd\)。
当 \(n\gg d\) 时差了 \(n/2\) 倍。这正是 linear attention 的核心技巧:\((\phi(Q)\phi(K)^\top)V\) 是 \(O(T^2d)\),改成 \(\phi(Q)(\phi(K)^\top V)\) 就是 \(O(Td^2)\)。LoRA 推理时也应该算 \(B(Ax)\) 而不是先合成 \(BA\)(除非要 merge 进权重)。
I think of a matrix as a linear map, so a product AB is just applying B and then A. For cost, an m-by-k times k-by-n matmul has mn outputs, each a length-k dot product, so it's about 2mkn FLOPs. That's where the rule of thumb comes from that a forward pass costs about 2 FLOPs per parameter per token, and forward plus backward about 6. And because matmuls do O(n³) work on O(n²) data, big matmuls are compute-bound while matrix-vector products, like batch-one decoding, are memory-bound.
- Why is the backward pass roughly twice the cost of the forward pass for a linear layer?
思路
前向 \(Y = XW\)。反向要算两个梯度:\(\partial L/\partial X = G W^\top\)(传给前一层)和 \(\partial L/\partial W = X^\top G\)(更新参数),每个都是和前向同规模的 matmul,所以 ≈ 2 倍。第一层的 \(\partial L/\partial X\) 理论上可以省掉,但量级不变。 - How would you compute the FLOPs of one transformer forward pass on a sequence of T tokens?
思路
参数相关的 matmul:\(2\cdot T\cdot N_{\text{non-emb}}\);再加 attention 的 \(QK^\top\) 和 \(AV\):每层 \(2\cdot 2T^2 d\)(所有头合计)。当 \(T \ll 6d\) 左右时参数项主导。细节见 m04 §5。
秩、零空间、特征值
秩 = 列空间的维度 = 映射"真正保留"的方向数;零空间 = 被压成 0 的方向;特征向量 = 只被拉伸不被转向的方向,特征值 = 拉伸倍数。
Rank is the dimension of the output space a matrix can reach; the null space is what it kills; eigenvectors are directions the map only scales.
- 秩–零化度定理:\(A\in\mathbb{R}^{m\times n}\),\(\text{rank}(A) + \dim\text{null}(A) = n\)。输入的 \(n\) 维要么被保留(进列空间),要么被消灭(进零空间)。
- 秩的上界:\(\text{rank}(AB)\le\min(\text{rank}A,\text{rank}B)\)。所以 \(B\in\mathbb{R}^{d\times r}, A\in\mathbb{R}^{r\times d}\) 的乘积 \(BA\) 秩最多是 \(r\) —— LoRA 的更新 \(\Delta W = BA\) 天然是低秩的。
- Attention 的低秩瓶颈:单头 \(QK^\top = XW_QW_K^\top X^\top\),\(W_QW_K^\top\) 是 \(d\times d\) 但秩 \(\le d_h\)。这是"多头"的一个动机,也是"low-rank bottleneck"论文讨论的点。
- 特征分解:\(Av = \lambda v\)。可对角化时 \(A = V\Lambda V^{-1}\),于是 \(A^t = V\Lambda^tV^{-1}\):重复作用一个矩阵,长期行为由最大 \(|\lambda|\) 决定。这就是 RNN 梯度消失/爆炸(反复乘同一个 Jacobian)以及 power iteration 的原理。
- 对称矩阵(\(A=A^\top\)):谱定理保证特征值全是实数、特征向量可以选成正交:\(A = Q\Lambda Q^\top\)。协方差矩阵、Hessian 都是对称的。
- 迹和行列式:\(\text{tr}A = \sum\lambda_i\),\(\det A = \prod\lambda_i\)。\(\det\) 是体积缩放倍数(normalizing flow 的 log-det Jacobian 就是这个)。
Rank tells you how many independent directions survive the map, and the null space is everything that gets sent to zero; they add up to the input dimension. A product BA can never have rank larger than the inner dimension, which is exactly why a LoRA update is low-rank by construction. Eigenvectors are the directions a matrix only stretches, so if you apply the same matrix many times, the largest eigenvalue dominates — that's the core of vanishing and exploding gradients in RNNs.
- What's the rank of the attention score matrix QKᵀ for a single head?
思路
\(Q,K\in\mathbb{R}^{T\times d_h}\),所以 \(\text{rank}(QK^\top)\le d_h\)。当 \(T > d_h\) 时这个 \(T\times T\) 矩阵是低秩的(softmax 之后不再严格低秩,因为是非线性,但仍受限)。 - How does power iteration find the top eigenvector, and where is it used in deep learning?
思路
反复做 \(v\leftarrow Av/\|Av\|\),与 \(\lambda_2/\lambda_1\) 成几何速率收敛到最大特征向量。用途:spectral normalization(GAN 里每步一次 power iteration 估计 \(\sigma_{\max}(W)\)),估计 Hessian 最大特征值(edge of stability 研究,用 Hessian-vector product),PageRank。
SVD、Eckart–Young 与 LoRA 直觉
任何矩阵 \(M = U\Sigma V^\top\) = 旋转 · 拉伸 · 旋转;保留前 \(k\) 个奇异值得到的是所有秩 \(k\) 矩阵里离 \(M\) 最近的(Eckart–Young)。LoRA 假设微调的增量 \(\Delta W\) 大部分能量集中在少数奇异方向上。
SVD writes any matrix as rotate–scale–rotate, and truncating it gives the best rank-k approximation; LoRA bets that fine-tuning updates are approximately low-rank.
定义。\(M\in\mathbb{R}^{m\times n}\),\(M = U\Sigma V^\top = \sum_{i=1}^{r}\sigma_i u_i v_i^\top\),其中 \(U, V\) 的列正交,\(\sigma_1\ge\sigma_2\ge\dots\ge\sigma_r>0\),\(r=\text{rank}(M)\)。
- 几何:\(V^\top\) 把输入旋转到"主轴"坐标,\(\Sigma\) 沿每个轴拉伸 \(\sigma_i\) 倍,\(U\) 再旋转到输出空间。单位球被映射成椭球,半轴长就是奇异值。
- 与特征分解的关系:\(M^\top M = V\Sigma^2V^\top\),\(MM^\top = U\Sigma^2U^\top\)。所以奇异值是 \(M^\top M\) 特征值的平方根。PCA 就是对中心化数据矩阵做 SVD(§5)。
- Eckart–Young–Mirsky 定理:\(M_k = \sum_{i\le k}\sigma_iu_iv_i^\top\) 满足 \(\|M-M_k\|_F = \sqrt{\sum_{i>k}\sigma_i^2}\),\(\|M-M_k\|_2=\sigma_{k+1}\),并且对任意秩 \(\le k\) 的 \(B\) 都有 \(\|M-B\|\ge\|M-M_k\|\)(两种范数都成立)。
- 伪逆:\(M^+ = V\Sigma^{+}U^\top\)(非零 \(\sigma\) 取倒数)。最小二乘的最小范数解是 \(w = X^+y\)。
LoRA 的直觉(Hu et al. 2021)
冻结预训练权重 \(W_0\in\mathbb{R}^{d\times k}\),只训练 \(\Delta W = BA\),\(B\in\mathbb{R}^{d\times r}, A\in\mathbb{R}^{r\times k}\),\(r\ll\min(d,k)\)。参数从 \(dk\) 降到 \(r(d+k)\)。初始化 \(B=0\)(所以一开始 \(\Delta W=0\),模型等于原模型),\(A\) 随机;输出乘以 \(\alpha/r\) 缩放,使得换 \(r\) 时不用重新调学习率。
- 为什么能 work:论文的假设是微调时权重的变化有低"内在秩"(intrinsic rank)——预训练模型已经有了大部分能力,下游适配只需要在少数方向上调整。Eckart–Young 告诉我们:如果 \(\Delta W\) 的奇异值衰减很快,秩 \(r\) 近似的损失就很小。
- 部署:推理前可以把 \(BA\) merge 进 \(W_0\),没有额外延迟;也可以不 merge,一个 base model 同时服务多个 adapter。
- 局限:需要学很多新知识的任务(例如大量继续预训练)秩可能不够;有工作比较 LoRA 和全参微调的遗忘/学习权衡。
代码:验证 Eckart–Young 与范数恒等式(numpy,已运行)
import numpy as np
rng = np.random.default_rng(0)
M = rng.normal(size=(30, 20))
U, s, Vt = np.linalg.svd(M, full_matrices=False) # M = U diag(s) Vᵀ,s 降序
k = 5
Mk = (U[:, :k] * s[:k]) @ Vt[:k] # 截断 SVD = 最优 rank-k 近似
# Eckart–Young:Frobenius 误差 = sqrt(剩余奇异值平方和),谱范数误差 = s[k]
assert np.isclose(np.linalg.norm(M - Mk, 'fro'), np.sqrt((s[k:]**2).sum()))
assert np.isclose(np.linalg.norm(M - Mk, 2), s[k])
P = rng.normal(size=(30, k)); Q = np.linalg.lstsq(P, M, rcond=None)[0] # 任意别的 rank-k
assert np.linalg.norm(M - P @ Q, 'fro') > np.linalg.norm(M - Mk, 'fro')
assert np.isclose(np.linalg.norm(M, 2), s[0]) # 谱范数 = σ_max
assert np.isclose(np.linalg.norm(M, 'fro')**2, (s**2).sum()) # ||M||_F² = Σσ²
assert np.isclose(np.linalg.cond(M), s[0] / s[-1]) # 条件数
print("rank-5 relative error:", round(np.linalg.norm(M - Mk) / np.linalg.norm(M), 3),
" params:", 30 * 20, "->", k * (30 + 20))
输出:
rank-5 relative error: 0.676 params: 600 -> 250
随机高斯矩阵的奇异值衰减很慢,所以 rank-5 误差很大(0.676);真实的权重增量通常衰减快得多,这正是 LoRA 依赖的性质。
SVD factorizes any matrix into a rotation, an axis-aligned scaling by the singular values, and another rotation. Eckart–Young says that keeping the top k singular triplets gives the best rank-k approximation in both Frobenius and spectral norm, with error equal to the discarded singular values. LoRA relies on this kind of structure: it freezes the pretrained weight and learns a low-rank update BA, betting that the fine-tuning delta has fast-decaying singular values. B is initialized to zero so training starts exactly from the base model, and the update can be merged into the weights for zero inference overhead.
- How many trainable parameters does LoRA with rank 16 add to a 4096×4096 projection?
思路
\(r(d+k) = 16\times 8192 = 131{,}072\),相比全量 \(4096^2\approx 16.8\)M,约 0.78%。 - Why initialize B to zero rather than A?
思路
两种都能让 \(\Delta W=0\)。约定是 \(B=0\)、\(A\) 随机:此时 \(\partial L/\partial B = G\,(Ax)^\top\) 非零,\(B\) 立刻开始学习;\(A\) 的梯度含 \(B^\top\),第一步为零,之后才动。关键是不能两个都为零。 - How would you check whether a fine-tuning delta is really low-rank?
思路
拿全参微调前后的 \(\Delta W = W_{ft}-W_0\),做 SVD,画奇异值谱或累计能量 \(\sum_{i\le k}\sigma_i^2/\sum\sigma_i^2\);比较同样 Frobenius 范数的随机矩阵的谱作为基线。也可以直接对比不同 \(r\) 的 LoRA 下游表现。
正定 / 半正定矩阵(PSD)
\(A\succeq 0\) ⇔ 对所有 \(x\) 有 \(x^\top Ax\ge 0\) ⇔ 对称且特征值全 \(\ge 0\) ⇔ 可以写成 \(A=B^\top B\)。协方差、Gram/kernel 矩阵、凸函数的 Hessian、Fisher 信息都是 PSD。
A PSD matrix defines a non-negative quadratic form; covariances, kernel matrices, Fisher matrices and Hessians of convex functions are all PSD.
- 为什么协方差是 PSD:\(x^\top\Sigma x = x^\top\mathbb{E}[(z-\mu)(z-\mu)^\top]x = \mathbb{E}[(x^\top(z-\mu))^2]\ge 0\)。方差不可能为负。
- 二次型几何:\(x^\top Ax = c\) 是椭球,主轴是特征向量,半轴长 \(\propto 1/\sqrt{\lambda_i}\)。Hessian 正定 ⇒ 局部是"碗",有严格局部极小;有负特征值 ⇒ 鞍点。
- Cholesky:正定矩阵 \(A=LL^\top\)。从 \(\mathcal{N}(\mu,\Sigma)\) 采样就是 \(x = \mu + L\varepsilon\),\(\varepsilon\sim\mathcal{N}(0,I)\)(重参数化,§2)。
- 数值上:\(X^\top X\) 理论上 PSD,但浮点误差可能让最小特征值略负;常见修补是加 \(\epsilon I\)(ridge / jitter),这同时也改善条件数。
A symmetric matrix is positive semidefinite if xᵀAx is non-negative for every x, equivalently all eigenvalues are non-negative, or it can be written as BᵀB. Covariance matrices are PSD because xᵀΣx is just the variance of a projection. In optimization, a PSD Hessian means the function is locally convex, and a negative eigenvalue means you're at a saddle direction.
范数、谱范数与条件数:数值稳定性的语言
Frobenius 范数 \(\|A\|_F=\sqrt{\sum\sigma_i^2}\) 衡量"总能量",谱范数 \(\|A\|_2=\sigma_{\max}\) 衡量"最多把向量拉长几倍";条件数 \(\kappa=\sigma_{\max}/\sigma_{\min}\) 衡量问题有多"病态",它决定 GD 的收敛速度和数值误差的放大倍数。
Frobenius norm is total energy, spectral norm is the maximum stretch, and the condition number is the ratio of largest to smallest singular value — it controls both numerical error amplification and gradient-descent speed.
| 范数 | 定义 | ML 里在哪出现 |
|---|---|---|
| 向量 \(L_2\) | \(\sqrt{\sum x_i^2}\) | weight decay、梯度裁剪(global grad norm) |
| 向量 \(L_1\) | \(\sum|x_i|\) | Lasso 稀疏(§5) |
| 向量 \(L_\infty\) | \(\max|x_i|\) | 对抗扰动约束;Adam 更新接近 sign → 与 \(L_\infty\) 几何相关 |
| Frobenius | \(\sqrt{\sum_{ij}A_{ij}^2}=\sqrt{\text{tr}(A^\top A)}\) | 把矩阵当长向量;L2 正则;LoRA 近似误差 |
| 谱范数 | \(\max_{\|x\|=1}\|Ax\| = \sigma_{\max}\) | Lipschitz 常数;spectral norm(GAN);Muon 的几何(谱范数下的最速下降) |
| 核范数 | \(\sum\sigma_i\) | 秩的凸松弛(矩阵补全) |
为什么谱范数和稳定性有关:深层网络 \(f = f_L\circ\dots\circ f_1\),Lipschitz 常数 \(\le\prod_l \|W_l\|_2\cdot\text{Lip}(\sigma)\)。每层谱范数略大于 1 ⇒ 前向激活/反向梯度指数爆炸;略小于 1 ⇒ 指数消失。初始化方案(Xavier/Kaiming,m03)本质是在控制每层的"增益"≈1。
条件数的两种含义:
- 数值误差放大:解 \(Ax=b\),\(b\) 的相对误差最多被放大 \(\kappa(A)\) 倍。正规方程 \(X^\top Xw=X^\top y\) 的条件数是 \(\kappa(X)^2\)(下方代码验证),所以实践中用 QR/SVD(
lstsq)而不是显式构造 \(X^\top X\) 求逆。 - 优化速度:对 \(\mu\)-强凸、\(L\)-光滑函数,GD 用 \(\eta=1/L\) 每步误差缩小 \((1-1/\kappa)\),\(\kappa=L/\mu\);需要 \(O(\kappa\log(1/\epsilon))\) 步。动量把它改善到 \(O(\sqrt\kappa\log(1/\epsilon))\)(§4)。预条件器(Adam、Shampoo)的目标就是减小有效条件数。
np.linalg.inv(X.T @ X) @ X.T @ y 写最小二乘。面试官会追问"为什么不用 solve / lstsq":显式求逆更慢且数值更差,条件数被平方。The spectral norm is the largest singular value — the most a matrix can stretch a vector — so it's the Lipschitz constant of a linear layer, and a product of layer norms bounds how signals and gradients grow with depth. The condition number, the ratio of largest to smallest singular value, tells you how ill-posed a problem is: it amplifies numerical error, and for gradient descent it sets the convergence rate, roughly kappa log one over epsilon iterations. That's the motivation for preconditioning methods like Adam or Shampoo, and also why we solve least squares with QR or SVD instead of inverting XᵀX, which squares the condition number.
- Why does adding λI (ridge) help numerically?
思路
\(X^\top X+\lambda I\) 的特征值是 \(\sigma_i^2+\lambda\),条件数变成 \((\sigma_{\max}^2+\lambda)/(\sigma_{\min}^2+\lambda)\),被限制住了;同时保证可逆。统计上等价于高斯先验(§2 MAP)。
矩阵求导速查与 Jacobian 形状
记住四个公式:\(\nabla_x x^\top Ax=(A+A^\top)x\);\(\nabla_x\|Ax-b\|^2=2A^\top(Ax-b)\);\(\partial\,\text{tr}(XB)/\partial X=B^\top\);线性层 \(Y=XW^\top\) 的梯度 \(\partial L/\partial W=G^\top X\)、\(\partial L/\partial X=GW\)。核心技巧:标量对矩阵的梯度和该矩阵同形状,用形状对齐来检查。
The gradient of a scalar with respect to a matrix has the same shape as that matrix, so most matrix-calculus results can be derived — and checked — by making the shapes line up.
约定
本页用"分母布局":标量 \(L\) 对 \(x\in\mathbb{R}^n\) 的梯度 \(\nabla_x L\in\mathbb{R}^n\),对 \(W\in\mathbb{R}^{m\times n}\) 的梯度也是 \(m\times n\)。向量函数 \(f:\mathbb{R}^n\to\mathbb{R}^m\) 的 Jacobian \(J\in\mathbb{R}^{m\times n}\),\(J_{ij}=\partial f_i/\partial x_j\)。
推导方法:微分法(最可靠)
写出 \(dL\),整理成 \(dL = \text{tr}(G^\top dX)\) 的形式,则 \(\partial L/\partial X = G\)。用到:\(d(AXB)=A\,dX\,B\),\(\text{tr}(ABC)=\text{tr}(CAB)\),\(a=\text{tr}(a)\)(标量)。
- \(L = x^\top Ax\):\(dL = dx^\top Ax + x^\top A\,dx = x^\top(A^\top + A)dx\) ⇒ \(\nabla_x L = (A+A^\top)x\),对称时 \(=2Ax\)。
- \(L=\|Ax-b\|^2 = r^\top r\),\(r = Ax-b\):\(dL = 2r^\top dr = 2r^\top A\,dx\) ⇒ \(\nabla_x L = 2A^\top(Ax-b)\)。令它为零得正规方程 \(A^\top Ax = A^\top b\)。
- \(L=\text{tr}(XB)\):\(dL = \text{tr}(dX\,B) = \text{tr}(B\,dX)\) ⇒ \(\partial L/\partial X = B^\top\)。
- \(L=\log\det X\):\(dL = \text{tr}(X^{-1}dX)\) ⇒ \(\partial L/\partial X = X^{-\top}\)(高斯 MLE 求协方差时用)。
- 线性层:\(Y = XW^\top\)(\(X\in\mathbb{R}^{B\times d_{in}}\),\(W\in\mathbb{R}^{d_{out}\times d_{in}}\),PyTorch 约定),上游梯度 \(G = \partial L/\partial Y\in\mathbb{R}^{B\times d_{out}}\)。\(dL = \text{tr}(G^\top dY) = \text{tr}(G^\top X\,dW^\top) = \text{tr}(dW\, X^\top G) = \text{tr}\big((G^\top X)^\top dW\big)\)(第三步用 \(\text{tr}(M)=\text{tr}(M^\top)\),第四步用循环性),所以 \(\partial L/\partial W = G^\top X\)(\(d_{out}\times d_{in}\),✓ 与 \(W\) 同形状);同理 \(dL=\text{tr}(G^\top dX\,W^\top)=\text{tr}\big((GW)^\top dX\big)\) ⇒ \(\partial L/\partial X = GW\)(\(B\times d_{in}\) ✓)。
形状检查法(面试现场救命)
如果忘了公式:\(\partial L/\partial W\) 必须是 \(d_{out}\times d_{in}\),手里有 \(G\)(\(B\times d_{out}\))和 \(X\)(\(B\times d_{in}\)),要消掉 batch 维 \(B\),唯一的拼法就是 \(G^\top X\)。90% 的情况下形状唯一确定答案。
Jacobian 形状与 VJP
| 函数 | Jacobian 形状 | 说明 |
|---|---|---|
| \(f:\mathbb{R}^n\to\mathbb{R}\)(loss) | \(1\times n\)(梯度是它的转置) | 反向模式一次 pass 就得到全部 |
| \(f:\mathbb{R}^n\to\mathbb{R}^m\) | \(m\times n\) | elementwise 激活:对角矩阵 |
| softmax \(\mathbb{R}^K\to\mathbb{R}^K\) | \(\text{diag}(p)-pp^\top\) | m03 详细推导 |
| \(Y=XW^\top\) 对 \(W\) | \((B d_{out})\times(d_{out}d_{in})\) | 巨大且稀疏——实际从不显式构造 |
反向传播从不构造完整 Jacobian,而是计算 vector–Jacobian product \(v^\top J\)(VJP):拿着上游梯度 \(v\) 一层层往回乘。对标量 loss,reverse mode 的成本 ≈ 常数倍前向;forward mode(JVP)每次只得到一个方向导数,要 \(n\) 次才能得到完整梯度 —— 这就是深度学习用反向模式的原因(m03 §1)。
代码:用有限差分验证全部公式(numpy,已运行)
import numpy as np
rng = np.random.default_rng(0)
def num_grad(f, X, eps=1e-6):
G = np.zeros_like(X)
for i in np.ndindex(X.shape):
E = np.zeros_like(X); E[i] = eps
G[i] = (f(X + E) - f(X - E)) / (2 * eps)
return G
n, d = 6, 4
A = rng.normal(size=(d, d)); x = rng.normal(size=d)
M = rng.normal(size=(n, d)); b = rng.normal(size=n)
B = rng.normal(size=(d, n)); W = rng.normal(size=(n, d))
S = A @ A.T + d * np.eye(d) # 对称正定
assert np.allclose(num_grad(lambda v: v @ A @ v, x), (A + A.T) @ x, atol=1e-6) # ∇ xᵀAx
assert np.allclose(num_grad(lambda v: np.sum((M @ v - b)**2), x), 2 * M.T @ (M @ x - b), atol=1e-5) # ∇||Mx-b||²
assert np.allclose(num_grad(lambda Z: np.trace(Z @ B), W), B.T, atol=1e-6) # ∂tr(ZB)/∂Z = Bᵀ
assert np.allclose(num_grad(lambda Z: np.log(np.linalg.det(Z)), S), np.linalg.inv(S).T, atol=1e-5) # ∂log det
# 线性层 Y = X Wᵀ,L = sum(G ⊙ Y):∂L/∂W = Gᵀ X,∂L/∂X = G W
Xb = rng.normal(size=(3, d)); Wl = rng.normal(size=(5, d)); G = rng.normal(size=(3, 5))
assert np.allclose(num_grad(lambda Z: np.sum(G * (Xb @ Z.T)), Wl), G.T @ Xb, atol=1e-6)
assert np.allclose(num_grad(lambda Z: np.sum(G * (Z @ Wl.T)), Xb), G @ Wl, atol=1e-6)
print("all matrix-calculus identities verified")
输出:all matrix-calculus identities verified
My go-to approach is the differential: write dL, massage it into trace of G-transpose dX, and then G is the gradient. For a linear layer Y equals X W-transpose with upstream gradient G, that gives dL/dW equals G-transpose X and dL/dX equals G W. I always sanity-check with shapes — the gradient must have the same shape as the parameter, and usually there's only one way to multiply the available matrices to get that shape. In practice backprop never forms full Jacobians; it computes vector-Jacobian products layer by layer.
- What's the gradient of the batch-mean MSE loss for linear regression?
思路
\(L = \frac1n\|Xw-y\|^2\) ⇒ \(\nabla_w L = \frac2n X^\top(Xw-y)\)。很多人会漏掉 \(1/n\) 或 2,形状 \(d\) ✓。 - Why is reverse mode preferred over forward mode for training neural nets?
思路
loss 是标量(输出维度 1),参数维度 \(n\) 巨大。反向模式成本 ∝ 输出维度(一次 VJP 拿到所有偏导),前向模式成本 ∝ 输入维度(需要 \(n\) 次 JVP)。代价是反向模式要存中间激活(显存)。
§2 · PROBABILITY & STATISTICS概率统计:从 Bayes 到重参数化
这一节是整章最重要的部分之一。LLM 本身就是一个条件概率分布 \(p_\theta(x_t\mid x_{<t})\);训练是 MLE;RL 里的 policy gradient、PPO ratio、off-policy 修正都是 Monte Carlo 和 importance sampling;VAE/扩散用重参数化;采样用 Gumbel-max。面试官经常用"一道概率题热身"来看你的基本功,所以 Bayes 和期望题要能快速、清晰地解出来。
Bayes 定理与"疾病检测"题
\(P(H\mid E) = \dfrac{P(E\mid H)P(H)}{P(E)}\):后验 ∝ 似然 × 先验。患病率 1%、敏感度 99%、假阳性率 5% 时,一次阳性后真正患病的概率只有 \(1/6\approx 16.7\%\),因为健康人基数大,假阳性数量压倒真阳性。
Posterior is likelihood times prior, normalized; with a 1% base rate even a 99%-sensitive test with 5% false positives gives only about a 17% chance of disease after one positive.
标准解法(面试时一定写出分母的全概率展开):
$$P(D\mid +) = \frac{P(+\mid D)P(D)}{P(+\mid D)P(D) + P(+\mid \neg D)P(\neg D)} = \frac{0.99\times0.01}{0.99\times 0.01+0.05\times0.99} = \frac{0.01}{0.01+0.05}=\frac16.$$频数法(更直观,适合口头解释):想象 10000 人。100 人患病,其中 99 人阳性;9900 人健康,其中 495 人阳性。阳性共 594 人,真患病 99 人,\(99/594 = 1/6\)。
第二次独立检测仍阳性:把 \(1/6\) 当新先验再算一次,得到 ≈ 79.8%。也可以用赔率形式:后验赔率 = 先验赔率 × 似然比。似然比 \(=0.99/0.05=19.8\),先验赔率 \(1:99\) → 一次阳性后 \(19.8:99 = 1:5\)(即 1/6)→ 两次后赔率 \(19.8^2:99\approx 3.96:1\),概率 \(3.96/4.96\approx 0.798\)。
代码(已运行)
from fractions import Fraction as F
def posterior(prior, sens, fpr):
"""P(D | +) = P(+|D)P(D) / [P(+|D)P(D) + P(+|¬D)P(¬D)]"""
return sens * prior / (sens * prior + fpr * (1 - prior))
prior, sens, fpr = F(1, 100), F(99, 100), F(5, 100) # 患病率 1%,敏感度 99%,假阳性率 5%
p1 = posterior(prior, sens, fpr)
p2 = posterior(p1, sens, fpr) # 第二次独立阳性:把上一次的后验当先验
print("P(D|+) =", p1, "≈", round(float(p1), 4)) # 1/6 ≈ 0.1667
print("P(D|++) ≈", round(float(p2), 4)) # ≈ 0.7984
assert p1 == F(1, 6) and abs(float(p2) - 0.7984) < 1e-4
P(D|+) = 1/6 ≈ 0.1667
P(D|++) ≈ 0.7984
I'd apply Bayes' rule and expand the denominator with the law of total probability. Out of 10,000 people, 100 are sick and 99 of them test positive, while 5% of the 9,900 healthy people — about 495 — also test positive. So among 594 positives only 99 are actually sick, which is one in six. The intuition is that the low base rate means false positives from the large healthy population swamp the true positives. A second independent positive multiplies the odds by the likelihood ratio again, bringing it to roughly 80%.
- What if the two tests are not independent given disease status?
思路
那就不能简单把似然比相乘,需要 \(P(++\mid D)\) 和 \(P(++\mid\neg D)\) 的联合分布。比如同一种系统性误差导致的假阳性会重复出现,第二次检测提供的信息就少很多。类比:用同一个 LLM judge 评两次,错误高度相关,不能当作两次独立证据。 - How does this relate to precision and recall?
思路
敏感度 = recall = \(P(+\mid D)\);\(P(D\mid +)\) = precision。precision 依赖于正例比例(prevalence),recall 不依赖。所以同一个分类器换一个基率不同的数据集,precision 会变。
期望、方差、协方差,以及全期望 / 全方差公式
期望永远是线性的(不需要独立);方差 \(\text{Var}(aX+bY)=a^2\text{Var}X+b^2\text{Var}Y+2ab\,\text{Cov}(X,Y)\);全期望 \(\mathbb{E}[X]=\mathbb{E}[\mathbb{E}[X\mid Y]]\);全方差 \(\text{Var}X = \mathbb{E}[\text{Var}(X\mid Y)] + \text{Var}(\mathbb{E}[X\mid Y])\)。\(n\) 个 i.i.d. 样本均值的方差是 \(\sigma^2/n\)。
Expectation is always linear; variance of a sum adds covariances; the tower rule and the law of total variance split uncertainty into within-group and between-group parts.
必背规则
- \(\mathbb{E}[aX+bY+c]=a\mathbb{E}X+b\mathbb{E}Y+c\)(任意相关性都成立——指示变量技巧的基础)。
- \(\text{Var}X = \mathbb{E}[X^2]-(\mathbb{E}X)^2\);\(\text{Var}(aX+c)=a^2\text{Var}X\)。
- \(\text{Cov}(X,Y)=\mathbb{E}[XY]-\mathbb{E}X\mathbb{E}Y\);独立 ⇒ 协方差为 0(反之不成立:\(X\sim\mathcal{N}(0,1), Y=X^2\) 不相关但不独立)。
- 独立时 \(\mathbb{E}[XY]=\mathbb{E}X\,\mathbb{E}Y\),\(\text{Var}(X+Y)=\text{Var}X+\text{Var}Y\)。
- 样本均值 \(\bar X_n\):\(\mathbb{E}\bar X_n=\mu\),\(\text{Var}\bar X_n=\sigma^2/n\),标准误 \(\sigma/\sqrt n\)。误差只按 \(1/\sqrt n\) 下降:要把评估误差减半需要 4 倍样本(m13 的 eval 置信区间)。
- 向量形式:\(\text{Cov}(Ax) = A\,\text{Cov}(x)A^\top\)。
全期望 / 全方差
\(\mathbb{E}[X] = \mathbb{E}_Y[\mathbb{E}[X\mid Y]]\)("先在每组内平均,再按组的概率平均")。全方差:
$$\text{Var}(X) = \underbrace{\mathbb{E}[\text{Var}(X\mid Y)]}_{\text{组内方差}} + \underbrace{\text{Var}(\mathbb{E}[X\mid Y])}_{\text{组间方差}}.$$证明:\(\mathbb{E}[\text{Var}(X\mid Y)] = \mathbb{E}[\mathbb{E}[X^2\mid Y]] - \mathbb{E}[(\mathbb{E}[X\mid Y])^2] = \mathbb{E}[X^2]-\mathbb{E}[(\mathbb{E}[X\mid Y])^2]\);\(\text{Var}(\mathbb{E}[X\mid Y]) = \mathbb{E}[(\mathbb{E}[X\mid Y])^2] - (\mathbb{E}X)^2\)。相加得 \(\mathbb{E}[X^2]-(\mathbb{E}X)^2\)。∎
- 评估方差分解:benchmark 分数的方差 = 题目抽样带来的方差 + 每道题上模型采样的方差(m13)。全方差公式告诉你多采样几次 response 只能降低第一项里的一部分。
- RL baseline:policy gradient 估计量的方差可以按"状态"条件分解;用 \(V(s)\) 做 baseline 减掉的是组间那部分(m06)。GRPO 的组内归一化也可以从这个角度理解。
- 指示变量技巧:随机排列的不动点个数期望 = \(\sum_i P(\pi(i)=i) = n\cdot\frac1n = 1\),完全不需要考虑相关性。
Linearity of expectation holds regardless of dependence, which is why indicator-variable tricks are so powerful. Variance of a sum picks up covariance terms, and for i.i.d. samples the variance of the mean is sigma squared over n, so the standard error only shrinks like one over root n. The law of total variance splits variance into the expected within-group variance plus the variance of the group means — I find that useful for thinking about eval noise, for example separating question-sampling variance from model-sampling variance.
- You evaluate on 500 questions and get 70%. What's the standard error?
思路
\(\sqrt{p(1-p)/n} = \sqrt{0.7\cdot0.3/500}\approx 0.0205\),即约 ±2%(95% CI 约 ±4%)。所以两个模型差 2 个点在 500 题上通常不显著(若是配对比较可以更敏感,见 m13)。 - Expected number of distinct values when rolling a die 6 times?
思路
指示变量:每个面至少出现一次的概率 \(1-(5/6)^6\)。期望 \(=6(1-(5/6)^6)\approx 3.99\)。
常用分布:Bernoulli、Categorical、Gaussian、多元高斯
二分类输出 = Bernoulli(sigmoid 参数化),LM 的下一个 token = Categorical(softmax 参数化),回归噪声 / VAE 隐变量 / 扩散噪声 = Gaussian。高斯有三个关键性质:线性变换后仍是高斯、条件分布和边缘分布仍是高斯、给定均值方差时熵最大。
Bernoulli for binary outputs, categorical for next-token prediction, Gaussians for noise and latents — Gaussians stay Gaussian under linear maps, marginalization and conditioning.
| 分布 | pmf / pdf | 均值 | 方差 | ML 中 |
|---|---|---|---|---|
| Bernoulli(\(p\)) | \(p^x(1-p)^{1-x}\) | \(p\) | \(p(1-p)\) | 逻辑回归、BCE、reward model 的偏好概率 |
| Binomial(\(n,p\)) | \(\binom nk p^k(1-p)^{n-k}\) | \(np\) | \(np(1-p)\) | pass@k、准确率的抽样分布 |
| Categorical(\(\pi\)) | \(\prod_k\pi_k^{[x=k]}\) | — | — | LM 输出、分类 |
| Geometric(\(p\)) | \((1-p)^{k-1}p\) | \(1/p\) | \((1-p)/p^2\) | "重复直到成功"的次数 |
| Gaussian \(\mathcal{N}(\mu,\sigma^2)\) | \(\frac{1}{\sqrt{2\pi\sigma^2}}e^{-(x-\mu)^2/2\sigma^2}\) | \(\mu\) | \(\sigma^2\) | MSE 损失、初始化、扩散 |
| Laplace(\(\mu,b\)) | \(\frac1{2b}e^{-|x-\mu|/b}\) | \(\mu\) | \(2b^2\) | L1 损失 / L1 正则的先验 |
| Beta(\(a,b\)) | \(\propto x^{a-1}(1-x)^{b-1}\) | \(\frac a{a+b}\) | — | Bernoulli 的共轭先验;Thompson sampling |
多元高斯(MVN)
$$\mathcal{N}(x;\mu,\Sigma) = (2\pi)^{-k/2}|\Sigma|^{-1/2}\exp\!\Big(-\tfrac12(x-\mu)^\top\Sigma^{-1}(x-\mu)\Big)$$- 线性变换:\(x\sim\mathcal{N}(\mu,\Sigma)\) ⇒ \(Ax+b\sim\mathcal{N}(A\mu+b, A\Sigma A^\top)\)。所以 \(x=\mu+L\varepsilon\)(\(LL^\top=\Sigma\))就能采样。
- 独立高斯之和:\(\mathcal{N}(\mu_1,\sigma_1^2)+\mathcal{N}(\mu_2,\sigma_2^2)=\mathcal{N}(\mu_1+\mu_2,\sigma_1^2+\sigma_2^2)\)。DDPM 能一步写出 \(q(x_t\mid x_0)\) 就靠这个(m12)。
- 条件分布:分块 \(\begin{pmatrix}x_a\\x_b\end{pmatrix}\),\(x_a\mid x_b\sim\mathcal{N}(\mu_a+\Sigma_{ab}\Sigma_{bb}^{-1}(x_b-\mu_b),\ \Sigma_{aa}-\Sigma_{ab}\Sigma_{bb}^{-1}\Sigma_{ba})\)(Gaussian process 回归的公式)。
- 最大熵:给定均值和方差的所有连续分布中,高斯熵最大——"除了二阶矩我什么都不假设"。
- 高维直觉:\(\mathcal{N}(0,I_d)\) 的样本范数集中在 \(\sqrt d\) 附近("肥皂泡"),两个独立高斯向量几乎正交(点积 \(\sim\mathcal{N}(0,d)\),归一化后 \(\sim 1/\sqrt d\))。这就是 attention 里除以 \(\sqrt{d}\) 的动机(m04)。
The workhorses are Bernoulli for binary labels, categorical for next-token prediction, and Gaussians. Gaussians are special because they're closed under linear transformations, marginalization and conditioning, and they're the maximum-entropy distribution for a given mean and covariance. A useful high-dimensional fact is that the dot product of two independent standard Gaussian vectors in d dimensions has variance d, which is exactly why attention scores are divided by root d.
大数定律、中心极限定理与集中不等式
LLN:样本均值 → 真期望;CLT:\(\sqrt n(\bar X_n-\mu)\to\mathcal{N}(0,\sigma^2)\),所以样本均值近似正态、误差 \(\approx\sigma/\sqrt n\)。这是所有置信区间、Monte Carlo 误差分析、"梯度噪声随 batch size 减小"的基础。
The CLT says the sample mean is approximately normal with standard deviation sigma over root n, which underlies confidence intervals, Monte Carlo error bars and minibatch gradient noise.
- CLT 条件:i.i.d. 且方差有限。方差无限(重尾,例如 importance weight 发散时)CLT 失效,样本均值会被极少数巨大值主导——这正是 IS 方差爆炸时估计"看起来对但时不时乱跳"的原因。
- Minibatch 梯度:\(g_B = \frac1B\sum_{i\in B}\nabla\ell_i\),协方差 \(\approx\Sigma/B\)。batch 翻倍噪声标准差降为 \(1/\sqrt2\)。这联系到 §4 的线性缩放规则和 critical batch size。
- Hoeffding:\(X_i\in[a,b]\) 独立,\(P(|\bar X-\mu|\ge t)\le 2\exp(-2nt^2/(b-a)^2)\)。非渐近、对有界变量成立。例如要以 95% 置信把准确率估计误差控制在 ±1%:\(n\ge \ln(2/0.05)/(2\cdot0.01^2)\approx 18{,}445\)(比 CLT 给出的 \(\approx 9{,}604\) 保守)。
- Markov / Chebyshev:\(P(X\ge a)\le\mathbb{E}X/a\)(\(X\ge0\));\(P(|X-\mu|\ge k\sigma)\le1/k^2\)。
The law of large numbers says the sample mean converges to the expectation, and the central limit theorem says its fluctuations are approximately Gaussian with standard deviation sigma over root n, as long as the variance is finite. That's why eval error bars shrink like one over root n and why minibatch gradient noise scales like one over the batch size in variance. When the variance is infinite — say, exploding importance weights — the CLT breaks down and estimates get dominated by rare huge samples.
最大似然估计(MLE):交叉熵 = 类别分布的负对数似然
MLE:\(\hat\theta=\arg\max_\theta\sum_i\log p_\theta(x_i)\)。高斯噪声下的 MLE = 最小化 MSE;类别分布下的 MLE = 最小化交叉熵;LM 预训练就是对每个 token 做 categorical MLE。MLE 也等价于最小化 \(\text{KL}(p_{\text{data}}\,\|\,p_\theta)\)(forward KL)。
Maximum likelihood with Gaussian noise gives MSE, with a categorical model gives cross-entropy, and in general it's equivalent to minimizing the forward KL from the data distribution to the model.
三个必推的例子
(1) Bernoulli:\(n\) 次抛硬币 \(k\) 次正面。\(\ell(p) = k\log p + (n-k)\log(1-p)\),\(\ell'(p) = k/p - (n-k)/(1-p) = 0\) ⇒ \(\hat p = k/n\)。
(2) Gaussian:\(x_i\sim\mathcal{N}(\mu,\sigma^2)\)。
$$\ell(\mu,\sigma^2) = -\frac n2\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_i(x_i-\mu)^2.$$\(\partial_\mu\ell=\frac1{\sigma^2}\sum(x_i-\mu)=0\) ⇒ \(\hat\mu=\bar x\)。\(\partial_{\sigma^2}\ell = -\frac{n}{2\sigma^2}+\frac{1}{2\sigma^4}\sum(x_i-\mu)^2=0\) ⇒ \(\hat\sigma^2=\frac1n\sum(x_i-\bar x)^2\)。注意它是有偏的:\(\mathbb{E}\hat\sigma^2 = \frac{n-1}{n}\sigma^2\)(因为用 \(\bar x\) 代替了 \(\mu\),"用掉了一个自由度"),无偏版本除以 \(n-1\)(Bessel 修正)。
回归:若 \(y = f_\theta(x)+\varepsilon\),\(\varepsilon\sim\mathcal{N}(0,\sigma^2)\),则 \(-\log p(y\mid x) = \frac{(y-f_\theta(x))^2}{2\sigma^2}+\text{const}\)。所以 MSE = 高斯似然下的 MLE。同理 L1 损失 = Laplace 噪声下的 MLE(对离群点更鲁棒,因为 Laplace 尾部更重)。
(3) Categorical / 交叉熵:模型输出 \(p_\theta(\cdot\mid x) = \text{softmax}(z)\),标签 \(y\)。负对数似然 \(-\log p_\theta(y\mid x) = -\sum_k [y=k]\log p_k = H(\text{onehot}(y), p_\theta)\),正好是 one-hot 分布和模型分布的交叉熵。LM 预训练:
$$\mathcal{L}(\theta) = -\frac{1}{T}\sum_{t=1}^{T}\log p_\theta(x_t\mid x_{<t}),$$就是对每个位置做 categorical MLE(链式法则把序列概率分解成条件概率之积)。
MLE ⇔ forward KL
$$\text{KL}(p_{\text{data}}\|p_\theta) = \mathbb{E}_{p_{\text{data}}}[\log p_{\text{data}}] - \mathbb{E}_{p_{\text{data}}}[\log p_\theta].$$第一项与 \(\theta\) 无关,所以最小化 KL ⇔ 最大化 \(\mathbb{E}_{p_{\text{data}}}\log p_\theta\),而后者的经验版本就是平均对数似然。这一点在 §3 讨论 forward vs reverse KL 时非常关键:SFT/预训练 = forward KL = mode-covering。
MLE 的性质
- 一致性(样本→∞ 时收敛到真参数,若模型正确设定);渐近正态,方差达到 Cramér–Rao 下界 \(I(\theta)^{-1}/n\)(\(I\) 是 Fisher 信息,§4 natural gradient 会用到)。
- 小样本会过拟合(例如没见过的词概率为 0 ⇒ 测试 log-lik = \(-\infty\)),需要先验/平滑 ⇒ MAP。
代码:Bernoulli MLE / MAP 与高斯方差偏差(已运行)
import numpy as np
rng = np.random.default_rng(0)
# Bernoulli:MLE = k/n;Beta(2,2) 先验的 MAP = (k+1)/(n+2)("加一平滑")
n, k = 10, 9
grid = np.linspace(1e-4, 1 - 1e-4, 100001)
loglik = k * np.log(grid) + (n - k) * np.log(1 - grid)
logpost = loglik + np.log(grid) + np.log(1 - grid) # + log Beta(2,2) 密度(差常数)
assert abs(grid[loglik.argmax()] - k / n) < 1e-3
assert abs(grid[logpost.argmax()] - (k + 1) / (n + 2)) < 1e-3
# Gaussian:方差的 MLE 有偏,E[σ²_MLE] = (n-1)/n · σ²
X = rng.normal(0, 2, size=(200_000, 5)) # σ² = 4, n = 5
v_mle = X.var(axis=1, ddof=0).mean() # 除以 n
v_unb = X.var(axis=1, ddof=1).mean() # 除以 n-1(Bessel 修正)
print(f"E[var_MLE] ≈ {v_mle:.3f} (theory 3.2), E[var_unbiased] ≈ {v_unb:.3f} (theory 4)")
assert abs(v_mle - 3.2) < 0.03 and abs(v_unb - 4) < 0.04
E[var_MLE] ≈ 3.207 (theory 3.2), E[var_unbiased] ≈ 4.009 (theory 4)
Maximum likelihood picks the parameters that make the observed data most probable. With Gaussian noise, the negative log-likelihood is just squared error up to constants, so least squares is MLE; with a categorical model, the negative log-likelihood of the label is exactly cross-entropy with a one-hot target — and language-model pretraining is just that, applied to every next token. More abstractly, maximizing expected log-likelihood is the same as minimizing the forward KL from the data distribution to the model, which is why MLE is mode-covering. One caveat is that MLE can be biased — the Gaussian variance estimate divides by n instead of n minus one.
- Why is the MLE of the variance biased, intuitively?
思路
\(\bar x\) 是对这批样本"量身定做"的中心,使 \(\sum(x_i-c)^2\) 最小,所以 \(\sum(x_i-\bar x)^2\le\sum(x_i-\mu)^2\),系统性偏小。精确地:\(\mathbb{E}\sum(x_i-\bar x)^2 = (n-1)\sigma^2\)。 - If MLE minimizes forward KL, what does that imply about LM samples?
思路
forward KL 对"数据有、模型没有"的地方惩罚无穷大,所以模型倾向于把概率质量铺开覆盖所有数据模式,包括低质量的长尾,导致采样时会生成数据中不常见/不合理的组合。这是为什么需要 temperature < 1、top-p 等截断解码,以及 RLHF(reverse KL 风格,偏 mode-seeking)能让输出更"尖锐"。 - What is the Fisher information and how does it relate to MLE variance?
思路
\(I(\theta) = \mathbb{E}[\nabla\log p\,\nabla\log p^\top] = -\mathbb{E}[\nabla^2\log p]\)(正则条件下)。MLE 渐近协方差 \(I(\theta)^{-1}/n\):曲率越大(似然越尖),参数估计越准。Bernoulli:\(I(p)=1/(p(1-p))\),所以 \(\text{Var}\hat p\approx p(1-p)/n\),和直接算的一致。
MAP:L2 正则 = 高斯先验,L1 正则 = Laplace 先验
MAP:\(\arg\max_\theta[\log p(D\mid\theta)+\log p(\theta)]\)。高斯先验 \(\theta\sim\mathcal{N}(0,\tau^2I)\) 给出 \(+\frac{1}{2\tau^2}\|\theta\|^2\)(L2 / weight decay);Laplace 先验给出 \(+\frac1b\|\theta\|_1\)(L1 / Lasso,产生稀疏解)。正则化强度 = 先验有多"紧"。
MAP adds a log-prior to the log-likelihood; a Gaussian prior gives L2 regularization and a Laplace prior gives L1, with the regularization strength inversely related to the prior's width.
推导:后验 \(p(\theta\mid D)\propto p(D\mid\theta)p(\theta)\),取负对数:
$$-\log p(\theta\mid D) = -\log p(D\mid\theta) - \log p(\theta) + \text{const}.$$- \(p(\theta)=\prod_j\mathcal{N}(\theta_j;0,\tau^2)\) ⇒ \(-\log p(\theta) = \frac{1}{2\tau^2}\|\theta\|_2^2+\text{const}\)。若数据项是 \(\frac1{2\sigma^2}\sum(y_i-x_i^\top\theta)^2\),则 \(\lambda = \sigma^2/\tau^2\):先验越窄(\(\tau\) 小)正则越强。
- \(p(\theta)=\prod_j\frac1{2b}e^{-|\theta_j|/b}\) ⇒ \(-\log p(\theta)=\frac1b\|\theta\|_1+\text{const}\)。
- Bernoulli + Beta 先验:Beta(\(a,b\)) 先验下 MAP \(=\frac{k+a-1}{n+a+b-2}\)。Beta(2,2) ⇒ \(\frac{k+1}{n+2}\)(Laplace 平滑 / "加一平滑"),解决了 \(k=0\) 时概率为 0 的问题。
MAP vs 完整贝叶斯:MAP 只取后验的众数(一个点),不表示不确定性;完整贝叶斯对后验积分做预测 \(p(y\mid x,D)=\int p(y\mid x,\theta)p(\theta\mid D)d\theta\)。深度学习里实际上全是点估计;ensemble、MC dropout 是对后验的粗略近似。
注意:MAP 不是重参数化不变的(换个参数化,密度的众数会移动),而 MLE 是。
MAP estimation maximizes the log-likelihood plus a log-prior. If the prior on the weights is a zero-mean Gaussian, the log-prior is a squared L2 norm, so ridge or L2 regularization is MAP with a Gaussian prior, and the strength is the noise variance over the prior variance. A Laplace prior gives an L1 penalty, which is what produces sparse solutions in the Lasso. And a Beta(2,2) prior on a Bernoulli parameter gives add-one smoothing.
估计量的偏差与方差
\(\text{MSE}(\hat\theta) = \text{Bias}^2 + \text{Var}\)。无偏不一定最好:有时引入一点偏差可以大幅降低方差(James–Stein、ridge、k2 KL 估计、GAE 的 \(\lambda<1\)、PPO 的 clipping)。
Mean squared error decomposes into bias squared plus variance, and trading a little bias for much less variance is a recurring theme — from ridge regression to GAE and the k2 KL estimator.
\(\mathbb{E}[(\hat\theta-\theta)^2] = \mathbb{E}[(\hat\theta-\mathbb{E}\hat\theta)^2] + (\mathbb{E}\hat\theta-\theta)^2\)(交叉项期望为 0)。
| 场景 | 低偏差高方差 | 高偏差低方差 |
|---|---|---|
| RL 回报估计 | Monte Carlo return | TD(0) bootstrapping;GAE 的 \(\lambda\) 在两者间插值 |
| KL 估计 | k1 = \(-\log r\) | k2 = \(\frac12(\log r)^2\);k3 两者兼得(§3) |
| Policy gradient | REINFORCE | actor-critic 用学到的 critic |
| 模型 | 高容量模型 | 强正则模型(§5 偏差–方差分解) |
还有一致性(\(n\to\infty\) 时收敛到真值):self-normalized IS 有偏但一致;MLE 方差估计有偏但一致。
The mean squared error of an estimator splits into bias squared plus variance, so an unbiased estimator isn't automatically the best one. In RL this shows up everywhere: Monte Carlo returns are unbiased but noisy, bootstrapped TD targets are biased but low-variance, and GAE's lambda interpolates between them.
Monte Carlo 估计
\(\mathbb{E}_{p}[f(x)]\approx\frac1N\sum_{i=1}^N f(x_i)\),\(x_i\sim p\)。无偏,误差 \(\text{std}(f)/\sqrt N\),与维度无关。RL 的 policy gradient、LLM eval 的采样平均、ELBO 估计全是 Monte Carlo。
Monte Carlo replaces an expectation with a sample average — unbiased, with error decaying as one over root N regardless of dimension.
- 为什么"与维度无关"很重要:数值积分(网格)需要的点数随维度指数增长;MC 的误差只取决于 \(f\) 的方差。这就是高维积分(对所有可能的 token 序列求期望)只能用 MC 的原因。
- 方差缩减技巧:(1) 控制变量(control variate):用 \(f - c(g - \mathbb{E}g)\),\(g\) 与 \(f\) 相关、期望已知。RL 的 baseline 就是控制变量;k3 KL 估计也是(§3)。(2) 对偶变量(antithetic):成对使用 \(\varepsilon\) 和 \(-\varepsilon\)(进化策略里常用)。(3) 重要性采样(下一个概念)。(4) 分层采样。
- score-function 估计(REINFORCE / log-derivative trick):\(\nabla_\theta\mathbb{E}_{p_\theta}[f(x)] = \mathbb{E}_{p_\theta}[f(x)\nabla_\theta\log p_\theta(x)]\)。推导:\(\nabla\int p_\theta f = \int f\nabla p_\theta = \int f p_\theta\nabla\log p_\theta\)。不需要 \(f\) 可微(reward 可以是"答案对不对"),代价是高方差。完整推导见 m06。
Monte Carlo estimation approximates an expectation by averaging f over samples from p. It's unbiased and its error shrinks like the standard deviation of f over root N, independent of dimension, which is why it's the only practical option over sequence spaces. Most of the craft is variance reduction: baselines in policy gradient are control variates, and importance sampling lets you reuse samples from a different distribution.
重要性采样(Importance Sampling):推导、方差爆炸、自归一化、PPO ratio
想求 \(\mathbb{E}_p[f]\) 但只能从 \(q\) 采样:\(\mathbb{E}_p[f]=\mathbb{E}_q\big[\frac{p(x)}{q(x)}f(x)\big]\)。无偏,但当 \(q\) 和 \(p\) 差得远时权重 \(p/q\) 的方差会爆炸(甚至无穷大)。PPO 的 ratio \(\pi_\theta/\pi_{\text{old}}\) 就是 IS 权重,clipping 和 KL 约束本质上是在防止权重方差爆炸。
Importance sampling reweights samples from q by p over q to estimate expectations under p; it's unbiased but the variance blows up when q is far from p — which is exactly what PPO's ratio clipping guards against.
推导(一行)
$$\mathbb{E}_{p}[f(x)] = \int p(x)f(x)\,dx = \int q(x)\frac{p(x)}{q(x)}f(x)\,dx = \mathbb{E}_{q}\big[w(x)f(x)\big],\quad w=\frac pq.$$要求 \(q(x)>0\) 在所有 \(p(x)f(x)\ne0\) 的地方成立(支撑集覆盖)。估计量 \(\hat\mu = \frac1N\sum w(x_i)f(x_i)\),\(x_i\sim q\)。
方差
$$\text{Var}_q[wf] = \mathbb{E}_q[w^2f^2]-\mu^2 = \int\frac{p(x)^2f(x)^2}{q(x)}dx - \mu^2.$$- 当 \(q\) 在 \(p\) 有质量的地方很小时,\(p^2/q\) 很大 ⇒ 方差巨大。例:\(p=\mathcal{N}(0,1)\),\(q=\mathcal{N}(0,s^2)\),\(f=x^2\)。\(\int p^2f^2/q\) 中被积函数 \(\propto x^4\exp(-x^2(1-\frac{1}{2s^2}))\),当 \(s\le 1/\sqrt2\) 时指数项不衰减 ⇒ 方差无穷大。提议分布比目标"窄"是危险的,宁可宽一点。
- 最优提议:\(q^*(x)\propto|f(x)|p(x)\)(\(f\ge0\) 时方差为 0),但需要知道归一化常数,实际不可行;它告诉我们 \(q\) 应该把样本放在 \(|f|p\) 大的地方。
- 有效样本量(ESS):\(\text{ESS}=\frac{(\sum w_i)^2}{\sum w_i^2}\in[1,N]\)。ESS/N 很小说明少数样本主导了估计。
- 序列上权重是乘积:\(\prod_t\frac{p(a_t\mid s_t)}{q(a_t\mid s_t)}\),方差随长度指数增长——这就是为什么长序列 off-policy RL 很难,以及为什么 PPO 用 per-token ratio(一种近似,忽略状态分布的变化)。
自归一化 IS(SNIS)
如果只知道未归一化的 \(\tilde p = Zp\):\(\hat\mu_{\text{SN}} = \frac{\sum_i \tilde w_i f(x_i)}{\sum_i\tilde w_i}\),\(\tilde w_i=\tilde p(x_i)/q(x_i)\)。\(Z\) 在分子分母中抵消。有偏(比值的期望 ≠ 期望的比值)但一致,且常常方差更小。实现时在 log 空间计算权重并减去最大值防止溢出。
与 RL / LLM 的联系
- PPO:目标 \(\mathbb{E}_{a\sim\pi_{\text{old}}}\big[\frac{\pi_\theta(a\mid s)}{\pi_{\text{old}}(a\mid s)}A(s,a)\big]\)——用旧策略的样本估计新策略的 surrogate 目标,正是 IS。clip 到 \([1-\epsilon,1+\epsilon]\) 限制了权重,等价于"别让 \(\pi_\theta\) 离 \(\pi_{\text{old}}\) 太远,否则 IS 估计不可信"。
- off-policy / 异步 RL:rollout 由稍旧的策略(甚至推理引擎里数值略不同的同一策略)生成,需要 IS 修正(例如 truncated IS)来纠偏,详见 m06 §7。
- KL 估计:用 \(\pi_\theta\) 的样本估计 \(\text{KL}(\pi_\theta\|\pi_{\text{ref}})\) 时用到 ratio \(r=\pi_{\text{ref}}/\pi_\theta\)(§3 k1/k2/k3)。
代码:IS 方差随提议分布宽度的变化 + SNIS(已运行)
import numpy as np
rng = np.random.default_rng(0)
def npdf(x, mu, s):
return np.exp(-(x - mu)**2 / (2 * s**2)) / np.sqrt(2 * np.pi * s**2)
# 目标 E_p[x²],p = N(0,1),真值 1。提议 q = N(0, s²),权重 w = p/q
n, reps = 1000, 2000
print(" q_sigma | mean of est | std of est | ESS/n")
for s in [0.5, 0.8, 1.0, 1.5, 3.0]:
ests, ess = [], []
for _ in range(reps):
x = rng.normal(0, s, n)
w = npdf(x, 0, 1) / npdf(x, 0, s)
ests.append(np.mean(w * x**2))
ess.append(w.sum()**2 / (w**2).sum() / n) # effective sample size
print(f" {s:3.1f} | {np.mean(ests):6.3f} | {np.std(ests):7.3f} | {np.mean(ess):.3f}")
# 理论:E_q[(w f)²] = ∫ p² f² / q 在 s ≤ 1/√2 时发散 → s = 0.5 时估计量方差是无穷大
# Self-normalized IS:只需要未归一化的 log p̃ - log q
x = rng.normal(0, 1.5, 100_000)
logw = (-0.5 * x**2) - (-0.5 * (x / 1.5)**2)
w = np.exp(logw - logw.max()) # 减 max 防溢出,归一化时抵消
snis = np.sum(w * x**2) / np.sum(w)
print(f"SNIS estimate {snis:.4f}")
assert abs(snis - 1) < 0.03
q_sigma | mean of est | std of est | ESS/n
0.5 | 1.017 | 3.968 | 0.231
0.8 | 1.000 | 0.114 | 0.844
1.0 | 1.000 | 0.045 | 1.000
1.5 | 0.999 | 0.022 | 0.832
3.0 | 1.001 | 0.029 | 0.459
SNIS estimate 1.0013
读表:\(s=1\) 时 \(q=p\),权重恒为 1。\(s=0.5\)(比目标窄)时平均值看起来还"差不多",但估计的标准差是 \(s=1.5\) 时的约 180 倍,并且理论方差是无穷大——跑更多次会偶尔看到巨大的离群值。\(s=1.5\) 反而比 \(s=1\) 方差更小,因为 \(f=x^2\) 的贡献来自尾部,宽一点的 \(q\) 更接近最优提议 \(\propto x^2p(x)\)。
Importance sampling rewrites an expectation under p as an expectation under q of the weight p over q times f, so you can reuse samples from a different distribution, and it's unbiased as long as q covers p's support. The catch is variance: it depends on the integral of p squared f squared over q, which blows up — even becomes infinite — when q is thinner than p in important regions, and for sequences the weights are products so variance grows exponentially with length. PPO is a good example: the probability ratio is an importance weight from the old policy to the new one, and clipping it is essentially a way to keep that estimator trustworthy. When you only know p up to a constant, self-normalized IS divides by the sum of weights, which is biased but consistent.
- Why does PPO use per-token ratios instead of the full sequence ratio?
思路
完整轨迹的 IS 权重是 \(\prod_t\pi_\theta/\pi_{\text{old}}\),方差随长度指数增长,长回答(几千 token)完全不可用。PPO 的 surrogate 用每步的 ratio 乘该步的 advantage,这是在"新旧策略状态分布近似相同"假设下的一阶近似(TRPO 论文中的 surrogate 推导),只要策略变化小(trust region),误差是二阶的。 - How would you diagnose that your importance weights are degenerate?
思路
看 ESS/N、权重的最大值/分位数、log-ratio 的分布;在 PPO 里监控 clip fraction 和近似 KL。如果 clip fraction 很高或 KL 很大,说明策略漂移过快(学习率太大或 epoch 太多)。 - Give the optimal proposal and explain why it's impractical.
思路
\(q^*\propto|f|p\);对 \(f\ge0\),\(w f = \mu\) 恒定,方差为 0。但归一化常数恰好是我们要算的 \(\mu\),所以是循环的。实践意义是 \(q\) 应该在 \(|f|p\) 大的地方放更多样本。
拒绝采样(Rejection Sampling)
找 \(M\) 使 \(p(x)\le Mq(x)\);从 \(q\) 抽 \(x\),以概率 \(\frac{p(x)}{Mq(x)}\) 接受。接受的样本精确服从 \(p\),接受率 \(=1/M\)。LLM 里的"rejection sampling fine-tuning"(采样多个回答、只保留通过验证器的)借用了这个名字,思想是"按条件过滤得到目标分布"。
Rejection sampling draws from a proposal q and accepts with probability p over Mq, giving exact samples from p with acceptance rate one over M.
正确性证明:\(P(x\in dx,\ \text{accept}) = q(x)dx\cdot\frac{p(x)}{Mq(x)} = \frac{p(x)}{M}dx\)。对 \(x\) 积分得接受率 \(1/M\)。条件于接受:\(p(x)dx\)。∎
- 高维的灾难:\(M\) 往往随维度指数增长,接受率趋于 0。
- LLM 中的"rejection sampling":对 prompt 采样 \(k\) 个回答,用 reward model / 验证器保留最好的或正确的,再做 SFT(如 Llama 2 的 RS 阶段、STaR、RFT)。若把"正确"看作条件,被保留的样本服从 \(p_\theta(y\mid x, \text{correct})\propto p_\theta(y\mid x)\mathbb 1[\text{correct}]\)——这正是拒绝采样(\(M=1\),接受概率是指示函数)。
- Speculative decoding 的接受规则 \(\min(1, p/q)\) + 残差重采样是一种"修正版拒绝采样",保证输出分布精确等于目标模型(m08)。
代码:从 Beta(2,5) 拒绝采样(已运行)
import numpy as np
from math import gamma
rng = np.random.default_rng(0)
def beta_pdf(x, a, b):
return gamma(a + b) / (gamma(a) * gamma(b)) * x**(a - 1) * (1 - x)**(b - 1)
# 目标 p = Beta(2,5),提议 q = U(0,1),M = max p/q = p(众数 0.2)
M = beta_pdf(0.2, 2, 5)
x = rng.random(400_000) # x ~ q
u = rng.random(400_000)
accepted = x[u < beta_pdf(x, 2, 5) / M] # 以概率 p(x)/(M q(x)) 接受
rate = len(accepted) / len(x)
print(f"accept rate {rate:.4f} (theory 1/M = {1/M:.4f}); mean {accepted.mean():.4f} (theory {2/7:.4f})")
assert abs(rate - 1 / M) < 3e-3 and abs(accepted.mean() - 2 / 7) < 3e-3
accept rate 0.4070 (theory 1/M = 0.4069); mean 0.2860 (theory 0.2857)
In rejection sampling you pick a proposal q and a constant M with p less than or equal to M q everywhere, sample from q, and accept with probability p over M q. Accepted samples are exactly distributed as p and the acceptance rate is one over M, which collapses in high dimensions. In LLM training, "rejection sampling" usually means sampling several responses and keeping the ones a verifier accepts, which samples from the model conditioned on being correct.
Gumbel-max 技巧
\(\arg\max_k(z_k+g_k)\),\(g_k\overset{iid}\sim\text{Gumbel}(0,1)=-\log(-\log U)\),服从 \(\text{softmax}(z)\)。把"采样"变成"加噪声后取 argmax"。Gumbel-softmax 把 argmax 换成带温度的 softmax,得到可微的近似。
Adding independent Gumbel noise to logits and taking the argmax gives an exact sample from the softmax distribution.
证明思路:Gumbel CDF \(F(g)=\exp(-e^{-g})\),所以 \(g=-\log(-\log U)\) 即 \(e^{-g} = -\log U\sim\text{Exp}(1)\)。令 \(E_k = e^{-(z_k+g_k)}\),则 \(E_k\sim\text{Exponential}(\text{rate}=e^{z_k})\)(因为 \(-\log U\sim\text{Exp}(1)\),再乘 \(e^{-z_k}\))。\(\arg\max(z_k+g_k) = \arg\min E_k\),而独立指数分布中第 \(k\) 个最小的概率是 \(\frac{e^{z_k}}{\sum_j e^{z_j}}\)。∎
- 用处:(1) 并行/批量采样实现(某些推理框架用"logits + Gumbel 噪声再 argmax"实现采样);(2) Gumbel-top-k:取前 \(k\) 大即得到无放回采样 \(k\) 个;(3) Gumbel-softmax / Concrete:\(\text{softmax}((z+g)/\tau)\),\(\tau\to0\) 趋于 one-hot,用于离散隐变量的近似重参数化(有偏)。
代码(已运行)
import numpy as np
rng = np.random.default_rng(0)
logits = np.array([1.0, 0.0, -1.0, 2.0])
G = -np.log(-np.log(rng.random((500_000, 4)))) # Gumbel(0,1) 噪声
samples = (logits + G).argmax(axis=1) # Gumbel-max trick
freq = np.bincount(samples, minlength=4) / len(samples)
softmax = np.exp(logits - logits.max()); softmax /= softmax.sum()
print("empirical", freq.round(3), " softmax", softmax.round(3))
assert np.allclose(freq, softmax, atol=3e-3)
empirical [0.237 0.087 0.032 0.643] softmax [0.237 0.087 0.032 0.644]
The Gumbel-max trick says that if you add i.i.d. Gumbel noise to the logits and take the argmax, the result is an exact sample from the softmax. One clean proof is that exp of minus logit-plus-noise is exponential with rate e to the logit, and the minimum of independent exponentials picks index k with probability proportional to its rate. Taking the top-k instead gives sampling without replacement, and replacing argmax with a tempered softmax gives the Gumbel-softmax relaxation.
重参数化技巧 vs score-function 梯度
要算 \(\nabla_\phi\mathbb{E}_{z\sim q_\phi}[f(z)]\):若能写 \(z=g_\phi(\varepsilon)\),\(\varepsilon\sim p(\varepsilon)\)(如 \(z=\mu+\sigma\varepsilon\)),则梯度 \(=\mathbb{E}_\varepsilon[\nabla_\phi f(g_\phi(\varepsilon))]\),可以直接反向传播,方差通常远小于 score-function(REINFORCE)估计。要求 \(f\) 对 \(z\) 可微、\(z\) 连续。LLM 的离散 token 无法重参数化,所以 RLHF 用 score-function 梯度。
The reparameterization trick moves the randomness into a parameter-free noise variable so gradients flow through the sample; it's much lower variance than the score-function estimator but needs a differentiable f and continuous latent — which is why discrete-token RL uses REINFORCE-style gradients instead.
| 重参数化(pathwise) | score function(REINFORCE) | |
|---|---|---|
| 公式 | \(\mathbb{E}_\varepsilon[\nabla_\phi f(g_\phi(\varepsilon))]\) | \(\mathbb{E}_{q_\phi}[f(z)\nabla_\phi\log q_\phi(z)]\) |
| 要求 | \(f\) 可微,\(z\) 可写成可微变换 | 只需能算 \(\log q_\phi\) 的梯度;\(f\) 可以是黑盒 |
| 方差 | 通常低 | 通常高,需要 baseline |
| 典型应用 | VAE、扩散的训练噪声、SAC 的策略 | RLHF/RLVR、离散隐变量、不可微 reward |
VAE 里:\(z=\mu_\phi(x)+\sigma_\phi(x)\odot\varepsilon\),ELBO 的重建项对 \(\phi\) 的梯度可以直接反传(m12)。
代码:两种估计量的方差对比(已运行)
import numpy as np
rng = np.random.default_rng(0)
# 目标:d/dμ E_{x~N(μ,1)}[x²] = d/dμ (μ² + 1) = 2μ
mu, n = 1.5, 100_000
eps = rng.normal(size=n)
x = mu + eps # 重参数化 x = μ + ε
g_reparam = 2 * x # ∂/∂μ f(μ+ε) = f'(x)
g_score = x**2 * (x - mu) # f(x) ∇_μ log N(x; μ, 1) (REINFORCE)
print(f"reparam: mean {g_reparam.mean():.3f}, per-sample std {g_reparam.std():.2f}")
print(f"score : mean {g_score.mean():.3f}, per-sample std {g_score.std():.2f} (true {2*mu})")
assert abs(g_reparam.mean() - 3) < 0.03 and abs(g_score.mean() - 3) < 0.1
assert g_reparam.std() < g_score.std()
reparam: mean 2.998, per-sample std 2.00
score : mean 2.991, per-sample std 7.21 (true 3.0)
同一个梯度,score-function 估计的单样本标准差是重参数化的 3.6 倍;在高维、复杂的 \(f\) 上差距通常更大。
torch.multinomial 的输出没有梯度;straight-through 或 Gumbel-softmax 是有偏的近似。To differentiate an expectation with respect to the parameters of the sampling distribution, the reparameterization trick writes the sample as a deterministic function of the parameters and some fixed noise — like mu plus sigma times epsilon — so gradients flow through the sample directly. That usually has far lower variance than the score-function or REINFORCE estimator, which multiplies f by the gradient of the log-density. The trade-off is that reparameterization needs a differentiable f and a continuous variable, so for discrete tokens and black-box rewards, like in RLHF, we fall back on score-function gradients with baselines.
- Why can't we reparameterize next-token sampling in an LLM?
思路
token 是离散的,任何把 \(\varepsilon\) 映射到 token 的函数都是分段常数,对 logits 的导数几乎处处为 0。Gumbel-max 把随机性移到了噪声上,但 argmax 不可微;Gumbel-softmax 可微但有偏,并且下游需要连续输入(embedding 的软混合),与真实离散生成不一致。
§3 · INFORMATION THEORY信息论:熵、交叉熵、KL
LLM 面试里信息论问得非常多,因为它直接对应训练目标和对齐目标:预训练 loss 是交叉熵;perplexity 是它的指数;RLHF / GRPO 里的 KL 惩罚有"方向"和"估计量"两个维度的选择;蒸馏用 KL;VAE 的 ELBO 里有 KL。这一节最高频的三个问题是:KL 为什么非负、forward vs reverse KL 的区别、k1/k2/k3 估计量。
熵与交叉熵
熵 \(H(p)=-\sum p\log p\) 是用最优编码描述 \(p\) 的样本所需的平均比特数(不确定性);交叉熵 \(H(p,q)=-\sum p\log q\) 是"真实分布是 \(p\) 却按 \(q\) 设计编码"时的平均码长。\(H(p,q)=H(p)+\text{KL}(p\|q)\ge H(p)\)。
Entropy is the average code length under the optimal code for p; cross-entropy is the average code length when you use a code designed for q, and the gap is exactly the KL divergence.
- 单位:\(\log_2\) → bits;\(\ln\) → nats。PyTorch 的 cross_entropy 用自然对数(nats)。1 nat = \(1/\ln 2\approx1.443\) bits。
- 范围:离散分布 \(0\le H(p)\le\log K\);均匀分布最大,one-hot 为 0。词表 \(K=32000\) 时最大熵 \(\ln 32000\approx 10.37\) nats——随机初始化的 LM 初始 loss 应该接近这个值,这是一个很好的 sanity check(m01 排错清单)。
- "惊讶度"视角:\(-\log p(x)\) 是观察到 \(x\) 时的"惊讶度"(surprisal),熵是期望惊讶度。
- 联合熵与条件熵:\(H(X,Y)=H(X)+H(Y\mid X)\)(链式法则)。LM 的序列交叉熵按 token 分解就是这个链式法则。
- 为什么交叉熵是分类的好损失:(1) 它是 MLE(§2);(2) 和 softmax 组合后梯度是简洁的 \(p-y\)(m03);(3) 它是 proper scoring rule:期望损失在预测 = 真实分布时唯一最小,所以鼓励校准的概率。
- LM 的 entropy:RL 训练中常监控策略的 token 级熵;熵快速下降(entropy collapse)意味着探索减少,是 GRPO 类训练的常见问题(m06)。
Entropy measures uncertainty — it's the expected surprisal, or the average number of bits you need with the best possible code for p. Cross-entropy is the average code length if the data come from p but you use a code optimized for q, and it equals the entropy plus the KL divergence, so it's minimized exactly when q equals p. That's why cross-entropy is a proper scoring rule and why it's the natural training loss for language models. A handy sanity check: a randomly initialized LM should start near log of the vocabulary size, about 10.4 nats for a 32k vocab.
- Your model's initial loss is 25 with a 32k vocabulary. What's wrong?
思路
应接近 \(\ln 32000\approx10.4\)。远高于此说明初始 logits 尺度太大(初始化/输出层没缩放,softmax 过于尖锐且是错的),或者 loss 计算有 bug(把 probs 当 logits、没有平均、mask 错误)。
KL 散度:定义、非负性(Jensen)、不对称性
\(\text{KL}(p\|q)=\mathbb{E}_p\big[\log\frac{p}{q}\big]\ge0\),等号当且仅当 \(p=q\);证明用 Jensen 不等式(\(\log\) 是凹函数)。KL 不对称、不满足三角不等式,不是距离。
KL divergence is the expected log-ratio under p; it's non-negative by Jensen's inequality, zero only when the distributions match, and asymmetric, so it's not a metric.
非负性证明(必须能白板写出)
Jensen:对凹函数 \(\varphi\),\(\mathbb{E}[\varphi(X)]\le\varphi(\mathbb{E}[X])\)。取 \(\varphi=\log\),\(X = q(x)/p(x)\),\(x\sim p\):
$$-\text{KL}(p\|q) = \mathbb{E}_p\Big[\log\frac{q(x)}{p(x)}\Big]\le\log\mathbb{E}_p\Big[\frac{q(x)}{p(x)}\Big] = \log\sum_{x:p(x)>0}q(x)\le\log 1 = 0.$$等号要求 \(q/p\) 在 \(p\) 的支撑上为常数(Jensen 取等),再结合总和为 1 ⇒ \(p=q\)。∎
另一种证明(更初等,也是 k3 估计量的来源):利用 \(\log t\le t-1\)(切线不等式):\(-\text{KL} = \mathbb{E}_p[\log\frac qp]\le\mathbb{E}_p[\frac qp-1] = \sum q - 1\le 0\)。
不对称性
例:\(\text{KL}(\mathcal{N}(0,1)\|\mathcal{N}(1,2^2))\approx0.443\),反过来 \(\approx1.307\)(下面代码算出)。另一个极端:若某处 \(p>0\) 而 \(q=0\),\(\text{KL}(p\|q)=\infty\),但 \(\text{KL}(q\|p)\) 可以有限。这个"零点行为"就是 forward/reverse KL 性质不同的根源(下一个概念)。
高斯 KL 闭式(VAE、策略蒸馏常用)
$$\text{KL}\big(\mathcal{N}(\mu_1,\sigma_1^2)\,\|\,\mathcal{N}(\mu_2,\sigma_2^2)\big) = \log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12.$$推导见 练习 6.4。VAE 中 \(\text{KL}(\mathcal{N}(\mu,\sigma^2)\|\mathcal{N}(0,1)) = \frac12(\mu^2+\sigma^2-1-\log\sigma^2)\)。多元:\(\frac12\big[\text{tr}(\Sigma_2^{-1}\Sigma_1)+(\mu_2-\mu_1)^\top\Sigma_2^{-1}(\mu_2-\mu_1)-k+\ln\frac{\det\Sigma_2}{\det\Sigma_1}\big]\)。
其他性质
- KL 对 \((p,q)\) 联合凸。
- 数据处理不等式:对 \(p, q\) 施加同一个变换(信道),KL 不增。
- Pinsker:\(\text{TV}(p,q)\le\sqrt{\frac12\text{KL}(p\|q)}\),所以 KL 小 ⇒ 分布在总变差意义上接近(TRPO 的理论用到)。
- 对称化版本:JS 散度 \(\text{JS}=\frac12\text{KL}(p\|m)+\frac12\text{KL}(q\|m)\),\(m=\frac{p+q}2\),有界(\(\le\log 2\)),原始 GAN 最优判别器下的目标(m12)。
代码:高斯 KL 闭式 vs Monte Carlo(已运行)
import numpy as np
rng = np.random.default_rng(0)
def kl_gauss(mu1, s1, mu2, s2):
"""KL( N(mu1, s1²) || N(mu2, s2²) )"""
return np.log(s2 / s1) + (s1**2 + (mu1 - mu2)**2) / (2 * s2**2) - 0.5
def kl_mvn(m1, S1, m2, S2):
"""KL( N(m1,S1) || N(m2,S2) ) = ½[tr(S2⁻¹S1) + (m2-m1)ᵀS2⁻¹(m2-m1) - k + ln(det S2 / det S1)]"""
k, S2i, d = len(m1), np.linalg.inv(S2), m2 - m1
return 0.5 * (np.trace(S2i @ S1) + d @ S2i @ d - k + np.log(np.linalg.det(S2) / np.linalg.det(S1)))
def logpdf(x, mu, s):
return -0.5 * np.log(2 * np.pi * s**2) - (x - mu)**2 / (2 * s**2)
x = rng.normal(1.0, 2.0, size=2_000_000) # x ~ p = N(1, 2²)
mc = np.mean(logpdf(x, 1.0, 2.0) - logpdf(x, -0.5, 1.0)) # E_p[log p - log q]
print(f"closed form {kl_gauss(1.0, 2.0, -0.5, 1.0):.4f} Monte Carlo {mc:.4f}")
assert abs(mc - kl_gauss(1.0, 2.0, -0.5, 1.0)) < 1e-2
assert np.isclose(kl_mvn(np.array([1.0]), np.array([[4.0]]), np.array([-0.5]), np.array([[1.0]])),
kl_gauss(1.0, 2.0, -0.5, 1.0))
print(f"asymmetry: KL(N(0,1)||N(1,2²)) = {kl_gauss(0,1,1,2):.4f}, KL(N(1,2²)||N(0,1)) = {kl_gauss(1,2,0,1):.4f}")
closed form 1.9319 Monte Carlo 1.9340
asymmetry: KL(N(0,1)||N(1,2²)) = 0.4431, KL(N(1,2²)||N(0,1)) = 1.3069
F.kl_div(input, target) 期望 input 是 log-probs,计算的是 \(\text{KL}(\text{target}\|\text{input})\)——参数顺序和数学记号相反,非常容易用反。KL of p from q is the expectation under p of log p over q. It's non-negative by Jensen's inequality: since log is concave, the expected log of q over p is at most the log of its expectation, which is the log of at most one, so zero. Equality needs q over p to be constant, which means the distributions are equal. It's asymmetric — if q puts zero mass where p has mass, KL of p from q is infinite but the reverse can be finite — and that asymmetry is what makes forward and reverse KL behave so differently.
- Is KL divergence a metric? What would you use if you need one?
思路
不是:不对称、不满足三角不等式。需要度量可以用总变差 TV、Hellinger 距离、\(\sqrt{\text{JS}}\)(是度量)、Wasserstein 距离。 - Show KL is invariant to reparameterization of x.
思路
\(y=g(x)\) 可逆,\(p_Y(y)=p_X(x)|dx/dy|\),\(q_Y\) 同理,Jacobian 因子在比值 \(p_Y/q_Y\) 中抵消,期望不变。熵则不是不变的(微分熵会加上 \(\mathbb{E}\log|\det J|\))。
Forward KL vs Reverse KL:mode-covering vs mode-seeking
用模型 \(q_\theta\) 拟合目标 \(p\):forward KL \(\text{KL}(p\|q_\theta)\) 在 \(p>0, q\approx0\) 处惩罚巨大 ⇒ \(q\) 必须覆盖 \(p\) 的所有模式(mode-covering,"宁滥勿缺");reverse KL \(\text{KL}(q_\theta\|p)\) 在 \(q>0, p\approx0\) 处惩罚巨大 ⇒ \(q\) 只放在 \(p\) 高的地方,可以只抓一个模式(mode-seeking,"宁缺勿滥")。SFT / 预训练 / 蒸馏 = forward KL;RLHF 的 KL 惩罚、变分推断 = reverse KL。
Forward KL from data to model is mode-covering — the model must put mass everywhere the data does — while reverse KL is mode-seeking; maximum-likelihood SFT minimizes forward KL, while the RLHF objective and variational inference minimize reverse KL.
为什么
Forward:\(\text{KL}(p\|q)=\mathbb{E}_{x\sim p}[\log p(x)-\log q(x)]\)。期望在 \(p\) 下取,只要 \(p(x)>0\) 而 \(q(x)\to0\),\(-\log q(x)\to\infty\)。所以 \(q\) 被"逼着"在 \(p\) 的每个模式上都放质量;而 \(q\) 在 \(p\approx0\) 的地方放质量几乎不受罚(那里权重 \(p\approx 0\))。用单峰 \(q\) 拟合双峰 \(p\) 时,结果是一个夹在中间、很宽的分布,可能在两个峰之间的"低谷"处放大量质量。
Reverse:\(\text{KL}(q\|p)=\mathbb{E}_{x\sim q}[\log q(x)-\log p(x)]\)。期望在 \(q\) 下取,只要 \(q(x)>0\) 而 \(p(x)\to0\),代价 \(\to\infty\);而"没覆盖到 \(p\) 的某个模式"不受罚。所以 \(q\) 会躲在一个模式里,宽度跟那个模式差不多,并且低估方差。
数值实验(下方代码):\(p = \frac12\mathcal{N}(-3,0.5^2)+\frac12\mathcal{N}(3,0.5^2)\),用单个高斯拟合:
- forward KL 最优:\(\mu=0,\sigma\approx3.05\)——正好是矩匹配(\(\sigma^2 = 9+0.25\))。对指数族 \(q\),最小化 forward KL ⇔ 匹配充分统计量的期望。
- reverse KL 最优:\(\mu=\pm3,\sigma=0.5\)——锁定一个峰,KL \(=\log 2\)(另一半质量被完全忽略的代价)。
在 LLM 中的对应(高频考点)
| 场景 | 目标 | 方向 | 行为 |
|---|---|---|---|
| 预训练 / SFT(MLE) | \(\min_\theta\text{KL}(p_{\text{data}}\|\pi_\theta)\) | forward | 覆盖所有数据模式;采样会出现"平均化"、长尾低质量内容 |
| 标准(word-level)知识蒸馏 | \(\text{KL}(p_{\text{teacher}}\|q_{\text{student}})\) | forward | 小学生模型被迫覆盖教师的全部分布,容量不足时会把质量放到教师认为不可能的地方 |
| On-policy / reverse-KL 蒸馏(如 MiniLLM、GKD 的一些设置) | \(\text{KL}(q_{\text{student}}\|p_{\text{teacher}})\) | reverse | 学生只学教师的主要模式,生成质量更高但多样性下降 |
| RLHF 目标 | \(\max\mathbb{E}_{\pi}[r]-\beta\,\text{KL}(\pi_\theta\|\pi_{\text{ref}})\) | reverse | 样本来自 \(\pi_\theta\);最优解 \(\pi^*\propto\pi_{\text{ref}}e^{r/\beta}\)(m06);倾向 mode-seeking,多样性下降 |
| 变分推断 / VAE 的 ELBO | \(\text{KL}(q_\phi(z\mid x)\|p(z\mid x))\) | reverse | 近似后验低估不确定性 |
代码:双峰目标上的 forward vs reverse KL 拟合(已运行)
import numpy as np
# 目标 p:双峰混合 0.5 N(-3,0.5^2)+0.5 N(3,0.5^2);用单个高斯 q=N(mu, s^2) 拟合
xs = np.linspace(-10, 10, 8001); dx = xs[1] - xs[0]
def npdf(x, mu, s): return np.exp(-(x - mu)**2 / (2 * s**2)) / np.sqrt(2 * np.pi * s**2)
p = 0.5 * npdf(xs, -3, 0.5) + 0.5 * npdf(xs, 3, 0.5)
def kl(a, b): # 数值积分 ∫ a log(a/b)
m = a > 1e-300
return np.sum(a[m] * (np.log(a[m]) - np.log(np.maximum(b[m], 1e-300)))) * dx
best_f, best_r = None, None
for mu in np.linspace(-4, 4, 161):
for s in np.linspace(0.2, 5, 97):
q = npdf(xs, mu, s)
f = kl(p, q); r = kl(q, p)
if best_f is None or f < best_f[0]: best_f = (f, mu, s)
if best_r is None or r < best_r[0]: best_r = (r, mu, s)
print("forward KL(p||q) best: KL=%.3f mu=%.2f sigma=%.2f" % best_f)
print("reverse KL(q||p) best: KL=%.3f mu=%.2f sigma=%.2f" % best_r)
# 前向:矩匹配 mu≈0, sigma≈sqrt(9+0.25)≈3.04 (mode-covering)
assert abs(best_f[1]) < 0.1 and abs(best_f[2] - np.sqrt(9.25)) < 0.1
# 反向:锁定一个峰 mu≈±3, sigma≈0.5(mode-seeking)
assert abs(abs(best_r[1]) - 3) < 0.1 and abs(best_r[2] - 0.5) < 0.1
forward KL(p||q) best: KL=1.112 mu=0.00 sigma=3.05
reverse KL(q||p) best: KL=0.693 mu=-3.00 sigma=0.50
The key question is which distribution the expectation is taken under. Forward KL, data to model, is an expectation under the data, so the model is heavily penalized wherever data has mass but the model doesn't — it becomes mode-covering and, if it's not expressive enough, spreads mass between modes. Reverse KL, model to target, is an expectation under the model, so it's penalized for putting mass where the target has none, and it's happy to lock onto a single mode — mode-seeking. Maximum-likelihood pretraining and SFT minimize forward KL, while the KL penalty in RLHF is reverse KL, since it's estimated on the policy's own samples, and that fits the observation that RLHF reduces output diversity.
- Why is the RLHF KL penalty computed as reverse KL rather than forward KL?
思路
(1) 实用:我们手里只有当前策略的样本,reverse KL \(\mathbb{E}_{\pi_\theta}[\log\pi_\theta-\log\pi_{\text{ref}}]\) 可以直接用 on-policy 样本估计;forward KL 需要 \(\pi_{\text{ref}}\) 的样本。(2) 理论:KL 正则化的 reward 最大化有闭式最优解 \(\pi^*\propto\pi_{\text{ref}}\exp(r/\beta)\),这是 DPO 推导的起点(m06)。(3) 它可以被理解为把 reward 改成 \(r-\beta\log(\pi_\theta/\pi_{\text{ref}})\) 的熵正则 RL。 - In distillation, when would you prefer reverse KL?
思路
当学生容量远小于教师、而我们更在意生成质量(不出错)而非覆盖全部分布时;配合学生自己生成的 on-policy 样本,还能缓解 exposure bias。代价是多样性下降和可能的 mode collapse。 - For an exponential-family q, what does minimizing forward KL do?
思路
令梯度为零得 \(\mathbb{E}_q[T(x)] = \mathbb{E}_p[T(x)]\):矩匹配。对高斯就是匹配均值和协方差——上面实验中 \(\sigma^2 = 9.25\) 正是混合分布的方差。
KL 估计量 k1 / k2 / k3(以及 GRPO 为什么用 k3)
样本 \(x\sim q\),\(r = p(x)/q(x)\),估计 \(\text{KL}(q\|p)\):k1 \(=-\log r\)(无偏、方差大、可为负);k2 \(=\frac12(\log r)^2\)(有偏、低方差、非负);k3 \(=(r-1)-\log r\)(无偏、非负、低方差)。GRPO 把 k3 作为 loss 项直接加在目标里(\(q=\pi_\theta, p=\pi_{\text{ref}}\)),因为它逐样本非负、方差小。
With samples from q and ratio r = p/q, k1 = −log r is unbiased but noisy, k2 = ½(log r)² is biased but low-variance, and k3 = (r − 1) − log r is unbiased, always non-negative and low-variance — which is why GRPO uses it as a per-token KL penalty.
来源:John Schulman 的博文 Approximating KL Divergence (2020)。在 LLM 里,完整 KL 需要对整个词表、所有可能序列求和,不可行,只能用采样到的 token 上的 log-ratio 来估计。
三个估计量
- k1 = \(-\log r = \log q(x)-\log p(x)\):\(\mathbb{E}_q[k1]=\text{KL}(q\|p)\),无偏。但单个样本可以为负(约一半样本 \(q<p\)),方差大。
- k2 = \(\frac12(\log r)^2\):非负;当 \(p\approx q\) 时,它的期望和 KL 在二阶上一致(两者都 ≈ \(\frac12\mathbb{E}[(\log r)^2]\),都近似 \(\frac12\) Fisher 信息二次型),所以偏差很小;分布差得远时偏差变大。
- k3 = \((r-1)-\log r\):思路是 控制变量。\(\mathbb{E}_q[r-1] = \sum q\cdot\frac pq - 1 = 0\),所以给 k1 加上 \(\lambda(r-1)\) 不改变期望。取 \(\lambda=1\):由 \(\log r\le r-1\)(\(\log\) 的切线不等式),每个样本都 \(\ge0\)。几何上它是 \(\log\) 在 \(r=1\) 处的切线与 \(\log r\) 之间的距离(Bregman 散度)。
实验(Schulman 博文的设置:\(q=\mathcal{N}(0,1), p=\mathcal{N}(1,1)\),真值 0.5)
k1: bias/true = -0.002 std/true = 2.00 min = -4.232
k2: bias/true = +0.250 std/true = 1.73 min = +0.000
k3: bias/true = +0.001 std/true = 1.70 min = +0.000
k1 无偏但有负值、标准差最大;k2 偏高 25%;k3 无偏、非负、标准差最小——与原博文的结论一致。
在 RLHF/GRPO 中怎么用
- PPO-RLHF(InstructGPT 风格):把 per-token 的 k1(\(\log\pi_\theta-\log\pi_{\text{ref}}\))放进 reward:\(r_t = r_{\text{RM}}\cdot\mathbb 1[t=T]-\beta\,(\log\pi_\theta(a_t)-\log\pi_{\text{ref}}(a_t))\),再通过 advantage 进入 policy gradient。
- GRPO(DeepSeekMath):不放进 reward,而是把 k3 形式 \(\frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1\) 作为 loss 项 直接加在每个 token 上,让 advantage 只由组内归一化的 reward 决定(m06 §7)。选择 k3 的直接理由:逐 token 非负、无偏(作为 KL 值的估计)、方差小。
上面的"无偏"指的是 KL 数值 的估计。但把 \(k_n\) 当成 loss 对 \(\theta\) 求导时(样本 \(x\sim\pi_\theta\) 视为常数,只对 \(\log\pi_\theta(x)\) 求导),期望梯度是另一回事。设 \(q=\pi_\theta\),\(p=\pi_{\text{ref}}\):
- k1 作 loss:\(\nabla k1 = \nabla\log\pi_\theta(x)\),期望 \(=\mathbb{E}_{\pi_\theta}[\nabla\log\pi_\theta]=0\)。期望梯度为零——直接把 k1 加进 loss(而不是放进 reward)在期望意义上什么都不做,只增加噪声。
- k2 作 loss:\(\nabla k2 = -\log r\cdot\nabla\log\pi_\theta = (\log\pi_\theta-\log\pi_{\text{ref}})\nabla\log\pi_\theta\),期望恰好是 \(\nabla\text{KL}(\pi_\theta\|\pi_{\text{ref}})\)(on-policy 时与"k1 放进 reward"等价)。
- k3 作 loss:\(\nabla k3=(1-r)\nabla\log\pi_\theta\),期望 \(=-\sum_x\pi_{\text{ref}}(x)\nabla\log\pi_\theta(x) = \nabla\text{KL}(\pi_{\text{ref}}\|\pi_\theta)\)——是 forward KL 的梯度!在 \(\pi_\theta\approx\pi_{\text{ref}}\) 时两者一阶相同,所以可以看作 reverse KL 梯度的一阶近似。
下面的代码在一个 6 类 softmax 策略上精确验证了这三条。这一点在 2025 年的若干分析里被讨论过,例如 Liu et al. 2025, "Rethinking KL Regularization in RLHF"(认为 k2-as-loss 与 k1-in-reward 在 on-policy 下梯度等价,k3-as-loss 是一阶有偏近似)和 Zhang et al. 2025, "On the Design of KL-Regularized Policy Gradient Algorithms for LLM Reasoning"(还讨论了 off-policy 时 KL 项需要的重要性权重修正)。面试里能说出"估计值无偏 ≠ 梯度正确"会非常加分。
代码:k1/k2/k3 的偏差与方差(已运行)
import numpy as np
rng = np.random.default_rng(0)
def logpdf(x, mu, s=1.0):
return -0.5 * np.log(2 * np.pi * s**2) - (x - mu)**2 / (2 * s**2)
# 估计 KL(q || p),样本 x ~ q。q = N(0,1), p = N(1,1),真值 = 0.5
q_mu, p_mu, true = 0.0, 1.0, 0.5
x = rng.normal(q_mu, 1.0, size=1_000_000)
logr = logpdf(x, p_mu) - logpdf(x, q_mu) # log r, r = p(x)/q(x)
r = np.exp(logr)
est = {"k1": -logr, # 无偏,方差大,可以为负
"k2": 0.5 * logr**2, # 有偏(q≈p 时偏差小),非负
"k3": (r - 1) - logr} # 无偏 + 非负 + 方差小
for name, k in est.items():
print(f"{name}: bias/true = {(k.mean() - true) / true:+.3f} std/true = {k.std() / true:.2f} min = {k.min():+.3f}")
assert abs(est["k1"].mean() - true) < 5e-3 and abs(est["k3"].mean() - true) < 1e-2
assert est["k3"].min() >= 0 > est["k1"].min()
代码:把 k1/k2/k3 当作 loss 时的期望梯度(已运行)
import numpy as np
rng = np.random.default_rng(1)
K = 6
theta = rng.normal(size=K) # 当前策略 logits
ref = rng.normal(size=K) # 参考策略 logits
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
p, q = softmax(theta), softmax(ref) # p = π_θ, q = π_ref
def expected_grad(per_sample_grad):
"""精确期望 E_{x~π_θ}[ ∇_θ loss(x) ],对离散支撑求和(相当于无限多样本)"""
return sum(p[x] * per_sample_grad(x) for x in range(K))
dlogp = lambda x: np.eye(K)[x] - p # ∇_θ log softmax(θ)_x
r = lambda x: q[x] / p[x] # r = π_ref / π_θ
# 把 kn 当 loss、对 log π_θ(x) 求导(样本 x 视为常数,不对采样求导)
g_k1 = expected_grad(lambda x: dlogp(x)) # ∇(-log r) = ∇log p
g_k2 = expected_grad(lambda x: -np.log(r(x)) * dlogp(x)) # ∇½(log r)² = -log r · ∇log p
g_k3 = expected_grad(lambda x: (1 - r(x)) * dlogp(x)) # ∇(r-1-log r) = (1-r)∇log p
def num_grad(f, z, eps=1e-6):
return np.array([(f(z + eps * e) - f(z - eps * e)) / (2 * eps) for e in np.eye(K)])
rev_kl = lambda z: np.sum(softmax(z) * (np.log(softmax(z)) - np.log(q))) # KL(π_θ || π_ref)
fwd_kl = lambda z: np.sum(q * (np.log(q) - np.log(softmax(z)))) # KL(π_ref || π_θ)
print("k1-as-loss expected grad:", np.round(g_k1, 6)) # ≡ 0
print("k2 vs ∇reverse KL :", np.allclose(g_k2, num_grad(rev_kl, theta), atol=1e-6))
print("k3 vs ∇reverse KL :", np.allclose(g_k3, num_grad(rev_kl, theta), atol=1e-6))
print("k3 vs ∇forward KL :", np.allclose(g_k3, num_grad(fwd_kl, theta), atol=1e-6))
assert np.allclose(g_k1, 0)
assert np.allclose(g_k2, num_grad(rev_kl, theta), atol=1e-6)
assert np.allclose(g_k3, num_grad(fwd_kl, theta), atol=1e-6)
assert not np.allclose(g_k3, num_grad(rev_kl, theta), atol=1e-3)
k1-as-loss expected grad: [ 0. 0. -0. 0. 0. 0.]
k2 vs ∇reverse KL : True
k3 vs ∇reverse KL : False
k3 vs ∇forward KL : True
exp,必要时 clamp,防止溢出。Since we can't sum over the whole sequence space, we estimate KL from sampled tokens. With samples from q and r equal to p over q, k1 is minus log r: unbiased but high variance and often negative. k2 is half log r squared: always non-negative and low variance, but biased when the distributions are far apart. k3 adds the control variate r minus one, which has zero mean under q, giving r minus one minus log r — unbiased, non-negative by the tangent-line inequality for log, and low variance. GRPO uses that k3 form as a per-token penalty in the loss. One subtlety I'd mention is that unbiased as an estimate of the KL value doesn't mean the gradient is right: differentiating k3 as a loss on-policy actually gives the gradient of the forward KL, which only matches the reverse-KL gradient to first order near the reference.
- Why does GRPO put the KL in the loss instead of in the reward like PPO-RLHF?
思路
GRPO 的 advantage 是组内归一化的结果级 reward(没有 critic、没有 per-token reward)。如果把 per-token KL 混进 reward,会干扰组内归一化,并且需要逐 token 的回报计算。把 KL 作为单独的 loss 项更简单,advantage 保持"纯任务信号"。代价是上面讨论的梯度偏差问题;也有不少后续工作(如 DAPO)直接去掉了 KL 项(m06)。 - Show that k2's expectation matches KL to second order.
思路
令 \(\delta = \log r\),小。\(\text{KL}(q\|p)=\mathbb{E}_q[-\delta]\)。又 \(\mathbb{E}_q[r]=1\) ⇒ \(\mathbb{E}_q[e^\delta]=1\) ⇒ \(\mathbb{E}[\delta]+\frac12\mathbb{E}[\delta^2]+O(\delta^3)=0\) ⇒ \(\mathbb{E}[-\delta]=\frac12\mathbb{E}[\delta^2]+O(\delta^3)\) = \(\mathbb{E}[k2]+O(\delta^3)\)。同样 k3 \(=e^\delta-1-\delta=\frac12\delta^2+O(\delta^3)\),逐样本也接近 k2。
互信息(Mutual Information)
\(I(X;Y)=\text{KL}(p(x,y)\|p(x)p(y)) = H(X)-H(X\mid Y)\ge0\):知道 \(Y\) 之后 \(X\) 的不确定性减少多少。为 0 当且仅当独立。对比学习的 InfoNCE 是互信息的一个下界。
Mutual information is the KL between the joint and the product of marginals — how much knowing one variable reduces uncertainty about the other.
- \(I(X;Y)=H(X)+H(Y)-H(X,Y)\),对称。
- InfoNCE(CLIP、SimCLR、CPC):在 \(N\) 个候选中识别正样本的交叉熵损失 \(\mathcal{L}\),满足 \(I(X;Y)\ge\log N-\mathcal{L}\)。所以这个下界最多是 \(\log N\)——这也是对比学习喜欢大 batch 的一个理论解释。
- 数据处理不等式:\(X\to Y\to Z\) 构成马尔可夫链 ⇒ \(I(X;Z)\le I(X;Y)\)。处理不能凭空增加信息(information bottleneck 视角)。
- 可解释性中的 probing 本质上在问"表示 \(h\) 中有多少关于属性 \(y\) 的(可线性解码的)信息"(m11)。
Mutual information is the KL divergence between the joint distribution and the product of the marginals, equivalently the reduction in entropy of X once you know Y. It's zero exactly when they're independent. Contrastive losses like InfoNCE give a lower bound on it, bounded by log of the number of negatives, which is one argument for large batches in contrastive learning.
Perplexity 与 bits-per-byte
\(\text{PPL}=\exp\big(-\frac1T\sum_t\log p(x_t\mid x_{<t})\big)=e^{\text{平均 CE(nats)}}\),可理解为"模型平均在多少个等可能的 token 中犹豫"。PPL 依赖 tokenizer,不同词表的模型不能直接比;bits-per-byte(BPB)把总 NLL 除以原始文本的字节数,与 tokenizer 无关。
Perplexity is the exponential of the average per-token cross-entropy — an effective branching factor — but it depends on the tokenizer, so bits-per-byte normalizes total log-loss by raw bytes for fair comparison across vocabularies.
- 例:平均 loss 2.0 nats/token ⇒ PPL \(=e^2\approx7.39\)。loss 从 2.0 降到 1.9,PPL 从 7.39 降到 6.69——loss 的小改进在 PPL 上更显眼。
- BPB:\(\text{BPB}=\frac{\sum_t -\log_2 p(x_t\mid x_{<t})}{\#\text{bytes}} = \frac{\text{loss}_{\text{nats/token}}}{\ln 2}\cdot\frac{\#\text{tokens}}{\#\text{bytes}}\)。例:loss 2.0 nats/token,平均每 token 4 字节 ⇒ BPB \(=2.0/0.693/4\approx0.72\)。
- 为什么 PPL 依赖 tokenizer:词表越大,每个 token 承载更多文本,每 token 的 loss 更高但 token 数更少。总 NLL(整段文本的 \(-\log p\))理论上才是可比较的量,按字节归一化即 BPB。
- 压缩视角:LM 的 NLL 就是用算术编码压缩文本的码长,所以"语言建模即压缩"。
- 局限:PPL 和下游能力(推理、指令遵循)相关但不等价;对 RLHF 后的模型 PPL 会变差(分布变尖锐)但质量更好(m05、m13)。
Perplexity is just the exponential of the average per-token negative log-likelihood, so it's like the effective number of choices the model is hesitating between at each step. The big caveat is that it's per token, so models with different tokenizers aren't comparable; bits-per-byte fixes that by dividing the total negative log-likelihood, in bits, by the number of raw bytes. I'd also keep in mind that perplexity tracks pretraining quality but doesn't capture things like instruction following — an RLHF'd model can have worse perplexity and still be much more useful.
§4 · OPTIMIZATION优化:从 GD 到 Adam、AdamW、学习率调度和 Muon
优化器是 RS 面试里出现频率最高的"数学 + 实践"交叉话题:Adam 的完整更新规则和 bias correction 推导几乎必考;AdamW 和 L2 的区别、warmup 为什么需要、batch size 和学习率的关系是经典追问。这一节从二次函数上的 GD 出发(一切直觉的来源),一路讲到二阶方法和 2024–2025 年的新优化器。
梯度下降、凸性、光滑性与步长
若 \(f\) 是 \(L\)-光滑的(梯度 Lipschitz,Hessian 特征值 \(\le L\)),GD 用 \(\eta\le 1/L\) 保证每步下降;在二次函数上 \(\eta>2/L\) 必然发散。强凸时收敛速度由条件数 \(\kappa=L/\mu\) 决定:每步误差乘以约 \((1-1/\kappa)\)。
For an L-smooth function, gradient descent with step size up to 1/L is guaranteed to decrease the loss, steps above 2/L diverge on quadratics, and the convergence rate is governed by the condition number L over mu.
定义
- 凸:\(f(y)\ge f(x)+\nabla f(x)^\top(y-x)\)(函数在切线上方);二阶:\(\nabla^2f\succeq0\)。凸函数的局部极小就是全局极小。
- \(\mu\)-强凸:\(f(y)\ge f(x)+\nabla f(x)^\top(y-x)+\frac\mu2\|y-x\|^2\);\(\nabla^2 f\succeq\mu I\)。
- \(L\)-光滑:\(\|\nabla f(x)-\nabla f(y)\|\le L\|x-y\|\) ⇒ \(f(y)\le f(x)+\nabla f(x)^\top(y-x)+\frac L2\|y-x\|^2\)(二次上界)。
下降引理(为什么 \(\eta=1/L\))
把 \(y=x-\eta\nabla f(x)\) 代入二次上界:
$$f(x-\eta\nabla f)\le f(x)-\eta\|\nabla f\|^2+\frac{L\eta^2}{2}\|\nabla f\|^2 = f(x)-\eta\Big(1-\frac{L\eta}{2}\Big)\|\nabla f\|^2.$$只要 \(\eta<2/L\) 就下降;\(\eta=1/L\) 时下降量最大 \(\frac1{2L}\|\nabla f\|^2\)。
二次函数上的精确分析
\(f=\frac12x^\top Ax\),\(x_{t+1}=(I-\eta A)x_t\)。沿特征方向 \(i\):\(x^{(i)}_{t+1}=(1-\eta\lambda_i)x^{(i)}_t\)。
- 收敛 ⇔ 所有 \(|1-\eta\lambda_i|<1\) ⇔ \(\eta<2/\lambda_{\max}=2/L\)。
- \(\eta=1/L\) 时最慢方向的收缩因子 \(1-\mu/L = 1-1/\kappa\);最优固定步长 \(\eta=2/(L+\mu)\) 给出 \(\frac{\kappa-1}{\kappa+1}\)。
- 代码验证:\(\kappa=100\)、\(\eta=1/L\) 时 200 步后误差 \(=0.99^{200}\approx0.134\);\(\eta=2.1/L\) 时爆炸到 \(10^8\)。
非凸情形
深度学习是非凸的,理论只能保证收敛到驻点:\(\min_t\|\nabla f(x_t)\|^2\le\frac{2L(f(x_0)-f^*)}{T}\)(对下降引理求和)。实践中高维鞍点比坏的局部极小更常见,而 SGD 噪声有助于逃离鞍点。
代码:步长阈值与动量加速(已运行)
import numpy as np
A = np.diag([1.0, 100.0]); L, mu = 100.0, 1.0 # f(x) = ½ xᵀAx,κ = L/μ = 100
def gd(eta, steps=200):
x = np.array([1.0, 1.0])
for _ in range(steps):
x = x - eta * A @ x
return np.linalg.norm(x)
print("GD η=1.9/L :", gd(1.9 / L)) # 收敛(慢方向卡住)
print("GD η=2.1/L :", gd(2.1 / L)) # 发散:|1 - ηL| > 1
print("GD η=1/L :", gd(1 / L), " theory (1-1/κ)^200 =", (1 - 1 / 100)**200)
# Heavy-ball(Polyak)最优参数:速率 ≈ (√κ-1)/(√κ+1) = 9/11
k = L / mu
eta = 4 / (np.sqrt(L) + np.sqrt(mu))**2
beta = ((np.sqrt(k) - 1) / (np.sqrt(k) + 1))**2
x, v = np.array([1.0, 1.0]), np.zeros(2)
for _ in range(200):
v = beta * v - eta * A @ x
x = x + v
print("heavy-ball :", np.linalg.norm(x))
assert gd(2.1 / L) > 1e3 and np.linalg.norm(x) < 1e-6 < gd(1 / L)
GD η=1.9/L : 0.02156758289826935
GD η=2.1/L : 189905276.46046528
GD η=1/L : 0.13397967485796206 theory (1-1/κ)^200 = 0.13397967485796172
heavy-ball : 1.3617360499738978e-15
If the loss is L-smooth — its curvature is bounded by L — then plugging the gradient step into the quadratic upper bound shows a step size of 1/L guarantees decrease, and on a quadratic anything above 2/L diverges along the top eigendirection. The rate is set by the condition number: the step size is limited by the sharpest direction while progress is limited by the flattest one, so each step only shrinks the error by about one minus one over kappa. That mismatch is the whole motivation for momentum and preconditioned methods like Adam.
- Your loss diverges in the first few hundred steps. Through this lens, what's happening and what do you do?
思路
初始阶段的局部曲率(sharpness)可能很大,\(\eta>2/\lambda_{\max}\);Adam 早期的二阶矩估计也不可靠。对策:warmup(让曲率先下降、统计量先稳定)、降低峰值 lr、梯度裁剪、检查初始化(m03)。
SGD 与梯度噪声
SGD 用 minibatch 梯度 \(g_B\) 代替全梯度:无偏,协方差 \(\approx\Sigma/B\)。噪声既是代价(需要更小的 lr、收敛到"噪声球"),也被认为是一种隐式正则(偏好平坦极小)。有效噪声尺度大致 \(\propto\eta/B\)。
SGD uses an unbiased minibatch gradient whose noise covariance shrinks like one over the batch size; the effective noise scale is roughly learning rate over batch size.
- 为什么用 SGD:一个 batch 的计算成本是全数据的 \(B/N\),但梯度方向已经足够好;早期训练时,"多走几步噪声大的步"比"走一步精确的步"高效得多。
- 固定 lr 不会精确收敛:在极小值附近梯度均值→0 但噪声不为 0,参数在一个半径 \(\propto\sqrt{\eta\,\text{tr}\Sigma/B}\) 的区域内抖动。这就是需要 lr decay 的根本原因:衰减阶段 loss 会明显下降(WSD 调度的 decay 段 loss 骤降就是这个现象)。
- SDE 视角:小 lr 下 SGD 近似 \(d\theta=-\nabla f\,dt+\sqrt{\eta\Sigma/B}\,dW\)。噪声"温度"\(\propto\eta/B\),这给出了线性缩放规则的一个理论动机。
- Epoch、shuffle:LLM 预训练通常每个 token 只看约一遍(单 epoch),所以"泛化"和"优化"几乎是同一件事——训练 loss ≈ 测试 loss。
SGD replaces the full gradient with a minibatch estimate, which is unbiased with noise covariance scaling like one over the batch size. With a constant learning rate it never settles exactly; it bounces around the minimum in a ball whose size grows with learning rate over batch size, which is why decaying the learning rate produces that sharp drop in loss at the end of training. The noise is also often argued to act as an implicit regularizer toward flatter minima.
动量与 Nesterov
动量 \(v\leftarrow\beta v+g,\ \theta\leftarrow\theta-\eta v\) 对梯度做指数平均:一致方向上累积加速(有效步长 \(\eta/(1-\beta)\)),来回震荡的方向上相互抵消。在病态二次函数上把迭代次数从 \(O(\kappa)\) 降到 \(O(\sqrt\kappa)\)。Nesterov 在"预估的下一位置"求梯度,理论上对凸函数是最优加速。
Momentum averages gradients so consistent directions accelerate and oscillating directions cancel, improving the dependence on the condition number from kappa to root kappa.
Heavy-ball(Polyak):\(v_{t+1}=\beta v_t-\eta\nabla f(\theta_t)\),\(\theta_{t+1}=\theta_t+v_{t+1}\)。
Nesterov:\(v_{t+1}=\beta v_t-\eta\nabla f(\theta_t+\beta v_t)\),\(\theta_{t+1}=\theta_t+v_{t+1}\)。先按动量"冲"一步再看梯度,起到纠偏作用。
- 有效学习率:梯度恒定时 \(v\to g/(1-\beta)\),\(\beta=0.9\) 时放大 10 倍。PyTorch 的 SGD momentum 写法是 \(v\leftarrow\beta v+g\);Adam 的一阶矩写法是 \(m\leftarrow\beta m+(1-\beta)g\)(EMA,不放大)——两种约定差一个 \(1/(1-\beta)\) 因子,调 lr 时要注意。
- 二次函数上的加速:最优参数 \(\eta=\frac{4}{(\sqrt L+\sqrt\mu)^2}\),\(\beta=\big(\frac{\sqrt\kappa-1}{\sqrt\kappa+1}\big)^2\) 时收敛速率 \(\approx\frac{\sqrt\kappa-1}{\sqrt\kappa+1}\)。\(\kappa=100\):GD 每步 0.99,heavy-ball 每步约 0.818。代码中 200 步后 GD 误差 0.134,heavy-ball \(10^{-15}\)。
- 物理直觉:一个有质量、有摩擦(\(1-\beta\))的小球在 loss 曲面上滚动。
Momentum keeps an exponential average of past gradients and steps along that. Along directions where gradients consistently agree it builds up speed, roughly multiplying the step by one over one minus beta, and along directions where they oscillate — like across a narrow valley — the contributions cancel. On an ill-conditioned quadratic that improves the iteration count from order kappa to order root kappa. Nesterov evaluates the gradient at the look-ahead point, which gives the optimal accelerated rate for smooth convex problems.
AdaGrad 与 RMSProp:逐坐标自适应学习率
AdaGrad 用历史梯度平方和 \(G=\sum g^2\) 缩放:\(\theta\leftarrow\theta-\eta g/\sqrt{G+\epsilon}\),稀疏特征获得更大步长,但 \(G\) 单调增长使学习率趋于 0。RMSProp 改用 EMA \(v\leftarrow\beta v+(1-\beta)g^2\),"忘掉"久远的梯度。Adam = RMSProp + 动量 + bias correction。
AdaGrad divides by the root of the accumulated squared gradients, so rarely-updated coordinates get larger steps but the learning rate decays to zero; RMSProp uses an exponential moving average instead, and Adam adds momentum and bias correction on top.
- 为什么除以 \(\sqrt{v}\):一个粗略的"对角预条件"——梯度一直很大的坐标(陡)步长小,梯度小的坐标(平)步长大,近似地把各方向的曲率拉平(尽管 \(\sqrt{\mathbb{E}g^2}\) 并不是真正的曲率,它和对角 Fisher 的平方根相关)。
- 尺度不变性:把某个坐标的梯度整体乘以 \(c\),\(g/\sqrt v\) 不变。所以自适应方法对不同层、不同参数量级不太敏感——这对 Transformer(embedding、LayerNorm 增益、attention 投影的梯度尺度差异巨大)非常重要,这也是"Transformer 用 SGD 很难训"的常见解释之一。
AdaGrad scales each coordinate's step by one over the root of its accumulated squared gradients, which is great for sparse features but makes the step size decay to zero. RMSProp fixes that with an exponential moving average. The key property is per-coordinate scale invariance, which matters a lot in transformers where different parameter groups have wildly different gradient scales.
Adam:完整更新规则与 bias correction 推导
\(m_t=\beta_1m_{t-1}+(1-\beta_1)g_t\),\(v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2\),\(\hat m_t=m_t/(1-\beta_1^t)\),\(\hat v_t=v_t/(1-\beta_2^t)\),\(\theta_t=\theta_{t-1}-\eta\,\hat m_t/(\sqrt{\hat v_t}+\epsilon)\)。因为 \(m_0=v_0=0\),早期的 EMA 被拉向 0,\(\mathbb{E}[m_t]=(1-\beta_1^t)\mathbb{E}[g]\),除以 \(1-\beta_1^t\) 就消除了这个偏差。
Adam keeps EMAs of the gradient and squared gradient, divides each by one minus beta to the t to undo the zero-initialization bias, and steps by m-hat over root v-hat plus epsilon.
原论文:Kingma & Ba 2014。默认 \(\beta_1=0.9,\beta_2=0.999,\epsilon=10^{-8}\);LLM 预训练常用 \(\beta_2=0.95\)(更快适应梯度尺度变化,减少 loss spike,见 m05)。
Bias correction 推导
展开递推(\(m_0=0\)):
$$m_t=(1-\beta_1)\sum_{i=1}^{t}\beta_1^{t-i}g_i.$$假设梯度平稳,\(\mathbb{E}[g_i]=\mathbb{E}[g]\):
$$\mathbb{E}[m_t]=\mathbb{E}[g]\,(1-\beta_1)\sum_{i=1}^{t}\beta_1^{t-i}=\mathbb{E}[g]\,(1-\beta_1)\frac{1-\beta_1^t}{1-\beta_1}=(1-\beta_1^t)\,\mathbb{E}[g].$$所以 \(\hat m_t = m_t/(1-\beta_1^t)\) 是无偏的(在平稳假设下)。同理 \(\mathbb{E}[v_t]=(1-\beta_2^t)\mathbb{E}[g^2]\)(非平稳时多一个小误差项,原论文讨论了)。
为什么对 \(v\) 的修正更重要:\(\beta_2=0.999\) 时 \(1-\beta_2^t\) 在 \(t=1\) 是 0.001,\(t=100\) 时约 0.095——不修正的话 \(v\) 被严重低估 ⇒ \(\sqrt v\) 太小 ⇒ 早期步长被放大数倍(\(\beta_1=0.9,\beta_2=0.999\) 时最多约 6.6 倍,见练习 6.3),训练一开始就可能崩。修正后第一步 \(\hat m_1=g_1\),\(\hat v_1=g_1^2\),步长 \(=\eta\cdot g_1/|g_1| = \eta\,\text{sign}(g_1)\)。
Adam 更新的几个性质
- 步长有界:\(|\Delta\theta|\lesssim\eta\)(大致),与梯度尺度无关。lr 直接控制"每步参数改变多少"——这让 lr 成了可以跨模型迁移的量(与 μP 相关,m05)。
- 接近 sign 下降:当 \(\beta_1,\beta_2\) 让 \(\hat m\approx g\)、\(\hat v\approx g^2\) 时更新约为 \(\eta\,\text{sign}(g)\);Lion 把这一点做到了极致。
- 显存:每个参数额外存 \(m, v\) 两个 fp32 状态,这就是混合精度 Adam 的 "16 bytes/param"(2 bf16 权重 + 2 bf16 梯度 + 4 fp32 master + 4 m + 4 v,m09)。
- \(\epsilon\):防止除零;在梯度很小的参数上 \(\epsilon\) 起作用使更新退化为 SGD 式。大模型训练里 \(\epsilon\) 太大会削弱自适应性,太小在 bf16/低精度下有数值问题,常见取 \(10^{-8}\) 左右(部分工作讨论过 \(\epsilon\) 与 loss spike 的关系)。
代码:从零实现 AdamW 并验证 bias correction(numpy,已运行)
import numpy as np
class AdamW:
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
self.params = params # list of np.ndarray,原地更新
self.lr, (self.b1, self.b2), self.eps, self.wd = lr, betas, eps, weight_decay
self.m = [np.zeros_like(p) for p in params] # 一阶矩(动量)
self.v = [np.zeros_like(p) for p in params] # 二阶矩(梯度平方的 EMA)
self.t = 0
def step(self, grads):
self.t += 1
for p, g, m, v in zip(self.params, grads, self.m, self.v):
if self.wd: # decoupled weight decay:不经过 m, v
p -= self.lr * self.wd * p
m[:] = self.b1 * m + (1 - self.b1) * g
v[:] = self.b2 * v + (1 - self.b2) * g * g
m_hat = m / (1 - self.b1 ** self.t) # bias correction
v_hat = v / (1 - self.b2 ** self.t)
p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
# (1) 常数梯度:未修正的 m_1 = 0.1·g(被拉向 0),修正后 m_hat == g
g = np.array([2.0, -3.0])
p = np.zeros(2); opt = AdamW([p], lr=0.1)
opt.step([g])
assert np.allclose(opt.m[0], 0.1 * g)
assert np.allclose(p, -0.1 * np.sign(g), atol=1e-6) # 第一步 ≈ lr·sign(g):与梯度尺度无关
for _ in range(9):
opt.step([g])
assert np.allclose(opt.m[0] / (1 - 0.9 ** opt.t), g)
# (2) 随机梯度下验证 E[m_t] = (1 - β1^t)·E[g]
rng = np.random.default_rng(0)
b1, T, R = 0.9, 5, 200_000
gs = 1.0 + rng.normal(size=(R, T)) # E[g] = 1
m = np.zeros(R)
for t in range(T):
m = b1 * m + (1 - b1) * gs[:, t]
print(f"E[m_5] ≈ {m.mean():.4f}, theory 1-0.9^5 = {1 - b1**T:.4f}")
assert abs(m.mean() - (1 - b1 ** T)) < 5e-3
# (3) 病态二次函数上收敛
A = np.diag([1.0, 10.0]); x = np.array([3.0, -2.0])
opt = AdamW([x], lr=0.05)
for _ in range(2000):
opt.step([A @ x])
assert np.linalg.norm(x) < 1e-2
print("converged:", x)
E[m_5] ≈ 0.4099, theory 1-0.9^5 = 0.4095
converged: [ 8.77700223e-46 -8.54201821e-46]
Adam keeps an exponential moving average of the gradient, m, and of the squared gradient, v, then steps by m over root v plus epsilon. Because both start at zero, early averages are biased toward zero: unrolling the recursion, the expectation of m_t is one minus beta-one to the t times the expected gradient. Dividing by that factor removes the bias. It matters most for v with beta-two near one — without correction v is tiny early on, so the first steps would be huge. After correction the very first update is just the learning rate times the sign of the gradient, and in general the step size is roughly bounded by the learning rate, independent of the gradient's scale.
- Why do LLM pretraining runs often use β₂ = 0.95 instead of 0.999?
思路
\(\beta_2=0.999\) 的有效窗口约 1000 步,梯度尺度突然变大时(某些罕见 token、数据分布切换),\(v\) 反应太慢,\(m/\sqrt v\) 会突然变得很大 ⇒ 更新过大 ⇒ loss spike。0.95(窗口约 20 步)适应得更快,更稳定。代价是 \(v\) 估计更嘈杂。 - How much optimizer memory does Adam need for a 7B model in fp32 states?
思路
\(m, v\) 各 4 bytes × 7B = 56 GB;加上 fp32 master weights 28 GB,共 84 GB 仅优化器相关状态。这就是 ZeRO 分片、8-bit Adam、Adafactor(分解二阶矩)的动机。 - What does Adam's update look like in the limit of β₁ = β₂ = 0?
思路
\(m=g, v=g^2\),更新 \(=\eta\,g/(|g|+\epsilon)\approx\eta\,\text{sign}(g)\):signSGD。这说明 Adam 有很强的 "sign descent" 成分。
AdamW vs Adam + L2:解耦权重衰减
Adam + L2:把 \(\lambda\theta\) 加进梯度,它会被 \(\sqrt{\hat v}\) 除掉——梯度大的参数衰减得少,正则效果被扭曲。AdamW:在自适应更新之外单独做 \(\theta\leftarrow\theta-\eta\lambda\theta\),所有参数按同一比例衰减。对 SGD 两者等价,对 Adam 不等价。
With Adam, adding an L2 term to the gradient gets rescaled by the adaptive denominator, so heavily-updated weights are barely regularized; AdamW decouples the decay and shrinks every weight by the same factor, which is equivalent to L2 only for plain SGD.
论文:Loshchilov & Hutter, "Decoupled Weight Decay Regularization"。
| 更新 | |
|---|---|
| SGD + L2 | \(\theta\leftarrow\theta-\eta(g+\lambda\theta) = (1-\eta\lambda)\theta-\eta g\) —— 和 weight decay 完全相同 |
| Adam + L2 | \(g'=g+\lambda\theta\),然后 \(\theta\leftarrow\theta-\eta\,\hat m(g')/(\sqrt{\hat v(g')}+\epsilon)\):衰减项被逐坐标缩放 |
| AdamW | \(\theta\leftarrow\theta-\eta\big(\hat m/(\sqrt{\hat v}+\epsilon)+\lambda\theta\big)\):衰减与自适应缩放无关 |
- 为什么 Adam+L2 不好:对于历史梯度大(\(v\) 大)的参数,L2 项被除以大的 \(\sqrt v\),几乎不衰减;而恰恰是这些参数最需要正则。AdamW 让正则强度与梯度统计解耦,实践中泛化更好、lr 和 wd 两个超参也更独立。
- PyTorch 实现:
torch.optim.AdamW的衰减是 \(\theta\leftarrow\theta(1-\eta\lambda)\),乘了 lr。所以 lr 调度会同时调度 weight decay;改变峰值 lr 时实际衰减强度也变了。LLM 常见 \(\lambda=0.1\)。 - 哪些参数不衰减:通常 bias、LayerNorm/RMSNorm 的增益、(有时)embedding 不做 weight decay——把归一化增益往 0 拉没有意义,还会损害表达。
- weight decay 在 LLM 里的作用:单 epoch 预训练中它不太是"防过拟合",更多是控制参数范数、与归一化层配合影响"有效学习率",以及影响训练末期的 loss(有工作讨论过 AdamW 的平衡态参数范数与 \(\sqrt{\eta/\lambda}\) 相关)。
torch.optim.Adam(weight_decay=0.1) 等于 AdamW——它是 Adam + L2(耦合版本)。(2) 对所有参数(包括 norm 增益和 bias)做 weight decay。For plain SGD, L2 regularization and weight decay are identical. With Adam they're not: if you add lambda theta to the gradient, it gets divided by the adaptive root-v term, so parameters with large historical gradients are barely regularized. AdamW decouples it — it applies the adaptive update from the loss gradient, and separately shrinks every weight by eta times lambda. That generally generalizes better and makes learning rate and weight decay easier to tune independently. In practice we also exclude biases and normalization gains from decay. And note that in PyTorch, torch.optim.Adam with weight_decay is the coupled L2 version, not AdamW.
- Why don't we apply weight decay to LayerNorm gains?
思路
增益 \(\gamma\) 的"自然值"是 1,衰减把它往 0 拉,等于在每层压缩输出尺度,与归一化的目的冲突;参数量也极少,对正则几乎没贡献。bias 同理。
学习率调度:warmup、cosine、linear、WSD
Warmup(几百到几千步线性升温)避免早期大更新导致发散——此时 Adam 的二阶矩估计不准、损失面曲率大、残差流尺度还不稳定;之后衰减(cosine / linear)让 SGD 噪声逐渐减小以收敛到更低的 loss。WSD(warmup–stable–decay)在大部分时间保持常数 lr,最后 10–20% 快速衰减,可以从任意 stable 阶段的 checkpoint 分叉出去做衰减,适合不确定总训练量和 scaling law 研究。
Warmup prevents early instability when curvature is high and Adam's statistics are unreliable; decay reduces gradient noise for the final drop in loss; WSD keeps a constant rate and decays only at the end, so you can branch off any checkpoint without fixing the total budget in advance.
为什么需要 warmup(能给出多个理由)
- Adam 二阶矩:前几步 \(\hat v\) 基于极少样本,噪声大;某些坐标 \(\hat v\) 偶然很小 ⇒ 更新过大。RAdam 论文把 warmup 解释为降低自适应学习率的早期方差。
- 曲率/sharpness:初始化附近 Hessian 最大特征值可能很大,大 lr 超过 \(2/\lambda_{\max}\) 就会发散;小 lr 训练一段后曲率下降("progressive sharpening"的反面,早期常见 sharpness reduction),此时才能承受大 lr。
- Post-LN Transformer:输出层附近梯度大,不 warmup 很难训(Pre-LN 缓解了这一点但大模型仍普遍使用 warmup,m04)。
- 大 batch:Goyal et al. 2017(ImageNet 一小时)用 gradual warmup 配合线性缩放规则,避免大 lr 在开始时破坏网络。
常见调度公式
- linear warmup:\(\eta_t=\eta_{\max}\cdot t/T_w\)。
- cosine:\(\eta_t=\eta_{\min}+\frac12(\eta_{\max}-\eta_{\min})(1+\cos(\pi\frac{t-T_w}{T-T_w}))\),常取 \(\eta_{\min}=0.1\eta_{\max}\)(Chinchilla 发现 cosine 周期应与总训练步数匹配,周期过长会损失性能)。
- linear decay:直线衰减到 \(\eta_{\min}\)(或 0),近年有工作报告 linear-to-zero 不比 cosine 差。
- WSD:warmup → 常数 \(\eta_{\max}\) → 在最后一段快速衰减(线性、cosine 或 \(1-\sqrt{\cdot}\) 等形状)。由 MiniCPM(Hu et al. 2024) 推广;Hägele et al. 2024 系统比较了它与 cosine,发现带冷却的常数 lr 可以匹配 cosine,并能显著降低做 scaling law 实验的成本(一条 stable 轨迹 + 多个短 decay 分支 = 多个训练长度)。
- inverse sqrt:\(\propto1/\sqrt t\)(原始 Transformer),现在大模型较少用。
代码:三种调度(已运行)
import math
def lr_at(step, max_lr, total, warmup, kind="cosine", min_ratio=0.1, decay_frac=0.2):
"""warmup 线性升温,然后 cosine / linear / WSD 衰减到 min_ratio·max_lr"""
if step < warmup:
return max_lr * (step + 1) / warmup
lo = min_ratio * max_lr
if kind == "cosine":
prog = (step - warmup) / max(1, total - warmup)
return lo + 0.5 * (max_lr - lo) * (1 + math.cos(math.pi * prog))
if kind == "linear":
prog = (step - warmup) / max(1, total - warmup)
return max_lr - (max_lr - lo) * prog
if kind == "wsd": # warmup-stable-decay
decay_start = int(total * (1 - decay_frac))
if step < decay_start:
return max_lr # stable:常数 lr,可随时分叉出去做 decay
prog = (step - decay_start) / max(1, total - decay_start)
return max_lr - (max_lr - lo) * prog
raise ValueError(kind)
T, W = 10_000, 500
for kind in ["cosine", "linear", "wsd"]:
xs = [lr_at(s, 3e-4, T, W, kind) for s in (0, W - 1, 5000, 8000, 9000, T - 1)]
print(f"{kind:6s}", " ".join(f"{x:.2e}" for x in xs))
assert abs(lr_at(W - 1, 3e-4, T, W) - 3e-4) < 1e-12
assert abs(lr_at(T, 3e-4, T, W) - 3e-5) < 1e-12
assert lr_at(7999, 3e-4, T, W, "wsd") == 3e-4
cosine 6.00e-07 3.00e-04 1.76e-04 5.85e-05 3.73e-05 3.00e-05
linear 6.00e-07 3.00e-04 1.72e-04 8.68e-05 5.84e-05 3.00e-05
wsd 6.00e-07 3.00e-04 3.00e-04 3.00e-04 1.65e-04 3.01e-05
列依次是 step 0、warmup 结束、5000、8000、9000、最后一步。WSD 在 8000 步前保持峰值,最后 20% 线性衰减。
scheduler.step(),调度被拉伸/压缩。(3) cosine 周期设得比实际训练长得多(例如计划训练 1T token 但只训了 300B 就停),模型从未经历 decay,评估结果偏差。Warmup ramps the learning rate up over the first few hundred or thousand steps because early on the curvature can be high and Adam's second-moment estimates are based on very few samples, so a full-size step can blow up training. After the peak we decay, because with a constant rate SGD noise keeps you bouncing around; decaying shrinks that noise and gives the characteristic drop in loss. Cosine to about ten percent of the peak is the classic choice, but warmup-stable-decay is popular now: hold the rate constant and decay only in the last ten to twenty percent. The big practical win is that you don't have to fix the training length in advance — you can branch a short decay off any checkpoint, which makes scaling-law sweeps much cheaper.
- With WSD, why does the loss drop sharply during the decay phase?
思路
stable 阶段参数在"河谷"中沿谷底方向前进,但在横向(高曲率方向)因为大 lr 的噪声而高位震荡;decay 时噪声减小,参数沉到谷底,loss 迅速下降。这与"river valley"损失面的解释一致。 - How would you choose warmup length?
思路
经验上几百到几千步(或总步数的 ~0.5–2%);batch 越大、lr 越高、模型越深通常需要更长。诊断:看早期 loss 是否 spike、grad norm 是否爆炸,做小规模扫描。warmup 过长主要浪费一些步数,过短会导致不稳定,所以倾向于宁长勿短。
梯度裁剪
按全局范数裁剪:若 \(\|g\|>c\),\(g\leftarrow g\cdot c/\|g\|\)。保持方向、限制步长,防止偶发的巨大梯度(坏 batch、loss spike)毁掉训练。LLM 常用 \(c=1.0\)。按值裁剪(逐元素 clamp)会改变方向,较少用。
Global-norm clipping rescales the whole gradient when its norm exceeds a threshold, preserving direction while bounding the step — standard practice in LLM training with a threshold around 1.0.
- 全局范数:所有参数的梯度拼起来算一个 \(L_2\) 范数(PyTorch
clip_grad_norm_)。分布式训练中需要跨设备 all-reduce 平方和(FSDP 有专门的实现)。 - 调用位置:
loss.backward()→ (混合精度时先scaler.unscale_)→clip_grad_norm_→optimizer.step()。 - 与 Adam 的交互:Adam 本身对梯度尺度不敏感,但裁剪仍有用:一个巨大的梯度会污染 \(m\) 和 \(v\)(尤其 \(v\) 会长期偏大,使之后的有效 lr 降低)。
- 监控:grad norm 曲线是最重要的训练健康指标之一。频繁触发裁剪说明 lr 太高或有不稳定性(m05 训练稳定性)。
Gradient clipping by global norm computes one L2 norm over all parameters' gradients, and if it exceeds a threshold — typically 1.0 for LLMs — rescales the whole gradient to that norm. It keeps the direction but bounds the step size, so an occasional bad batch can't wreck the run or pollute Adam's moment estimates. If clipping fires constantly, that's a signal the learning rate is too high or something is unstable.
Batch size 与学习率:线性缩放、平方根缩放、critical batch size
SGD 的经验规则:batch 扩大 \(k\) 倍,lr 也扩大 \(k\) 倍(linear scaling,Goyal et al. 2017);Adam 类优化器更接近 \(\sqrt k\) 缩放。但这只在 batch 小于 critical batch size 时有效:超过它之后,增大 batch 几乎不再减少所需步数,只是浪费计算。McCandlish et al. 2018 用梯度噪声尺度 \(B_{\text{noise}}=\text{tr}(\Sigma)/\|G\|^2\) 来预测它。
Below the critical batch size, doubling the batch lets you roughly double the learning rate and halve the steps; above it, returns diminish sharply — and the gradient noise scale predicts where that transition is.
- 线性缩放的推理:\(k\) 个小 batch 各走一步 ≈ 一个大 batch 走一步,前提是这 \(k\) 步中梯度变化不大(小 lr 时成立)。SDE 视角下保持 \(\eta/B\) 不变即保持噪声温度不变。
- Critical batch size(McCandlish et al. 2018, "An Empirical Model of Large-Batch Training"):当 batch 远小于噪声尺度时,梯度主要是噪声,加倍 batch ≈ 加倍进度;远大于噪声尺度时,梯度已经很准,再加 batch 没用。权衡曲线:\(\big(\frac{S}{S_{\min}}-1\big)\big(\frac{E}{E_{\min}}-1\big)=1\)(\(S\)=步数,\(E\)=样本数)。
- 随训练变化:loss 越低,梯度信号越弱、噪声越相对显著,噪声尺度越大 ⇒ critical batch size 随训练增大。这是 batch size warmup / ramp(训练中逐步增大 batch,GPT-3 等使用过)的理论依据。
- 大模型的实际:常用 batch 数百万 token;Kaplan et al. 2020 给出了 critical batch 随 loss 的幂律关系。更大的 batch 能更好地利用数据并行,但超过 critical batch 就是在用计算换时间。
The rule of thumb for SGD is linear scaling: multiply the batch by k and multiply the learning rate by k, with warmup, because k small steps roughly equal one big step when the gradient doesn't change much; for Adam, square-root scaling is often closer. But it only holds up to the critical batch size. McCandlish and colleagues showed that the gradient noise scale — trace of the gradient covariance over the squared norm of the mean gradient — predicts it: below it, bigger batches buy almost linear speedups in steps; above it, you're just burning compute. The noise scale grows as loss falls, which motivates ramping the batch size up during training.
- You doubled the batch size and the loss-vs-tokens curve got worse. Why?
思路
(1) 没有相应调 lr(步数减半而每步不变大);(2) 已经超过 critical batch size,每个 token 的效率下降;(3) warmup 按步数定义,现在 warmup 覆盖的 token 数翻倍但步数没变(或相反)。比较时应以 token/计算量为横轴并重新调 lr。
二阶方法:Newton、Fisher、natural gradient → K-FAC / Shampoo
Newton 法 \(\Delta\theta=-H^{-1}g\) 用曲率重新缩放每个方向,对二次函数一步到位,但 \(d\times d\) 的 Hessian 存不下也求不了逆。Natural gradient 用 Fisher 信息 \(F\) 代替 \(H\):\(\Delta\theta=-F^{-1}g\),是在 KL 度量下的最速下降。K-FAC、Shampoo 用 Kronecker 分解近似每层的 \(F\) 或梯度二阶矩,让"矩阵预条件"可行。
Newton's method preconditions by the inverse Hessian; natural gradient uses the inverse Fisher, i.e. steepest descent in KL geometry; K-FAC and Shampoo make this tractable with per-layer Kronecker-factored approximations.
- Newton:对二阶泰勒展开 \(f(\theta+\Delta)\approx f+g^\top\Delta+\frac12\Delta^\top H\Delta\) 求最小 ⇒ \(\Delta=-H^{-1}g\)。仿射不变、二次收敛,但 \(O(d^2)\) 存储、\(O(d^3)\) 求逆;非凸时 \(H\) 不定,Newton 会朝鞍点/极大值走。
- Fisher 信息:\(F=\mathbb{E}_{x, y\sim p_\theta}[\nabla\log p_\theta(y\mid x)\nabla\log p_\theta(y\mid x)^\top]\),总是 PSD。对 log-loss,在模型良好拟合时 \(F\) ≈ Gauss–Newton 矩阵 ≈ Hessian。"empirical Fisher"(用真实标签 \(y\) 而不是模型采样)是另一个东西,近似性较差。
- Natural gradient:求解 \(\min_\Delta g^\top\Delta\) s.t. \(\text{KL}(p_\theta\|p_{\theta+\Delta})\le\epsilon\)。KL 的二阶展开是 \(\frac12\Delta^\top F\Delta\) ⇒ \(\Delta\propto-F^{-1}g\)。它对参数化不变——只关心分布怎么变。TRPO 就是 policy 上的 natural gradient + 线搜索(m06)。
- K-FAC(Martens & Grosse 2015):对线性层 \(W\),梯度 \(=\delta a^\top\),近似 \(F_W\approx\mathbb{E}[aa^\top]\otimes\mathbb{E}[\delta\delta^\top]\),于是 \(F^{-1}\) 只需对两个小矩阵求逆:\(\Delta W = -\,G^{-1}\nabla_W L\,A^{-1}\)(\(A=\mathbb{E}[aa^\top]\),\(G=\mathbb{E}[\delta\delta^\top]\))。
- Shampoo(Gupta et al. 2018):对矩阵参数维护 \(L=\sum GG^\top\),\(R=\sum G^\top G\),更新 \(L^{-1/4}GR^{-1/4}\)。在 AlgoPerf 等基准中表现强。SOAP(Vyas et al. 2024)在 Shampoo 预条件器的特征基里运行 Adam,更稳定、超参更少。
Newton's method rescales the gradient by the inverse Hessian, so every direction gets a step matched to its curvature — but for billions of parameters you can't store or invert that. Natural gradient replaces the Hessian with the Fisher information, which you can derive as steepest descent under a KL trust region, and it's invariant to how you parameterize the model; TRPO is natural gradient applied to policies. Practical methods approximate the per-layer Fisher or gradient covariance with Kronecker factors: K-FAC uses activation and backprop-signal covariances, and Shampoo uses left and right gradient statistics with inverse fourth roots. You can see Adam as the diagonal end of this spectrum.
新优化器速览:Lion、Shampoo/SOAP、Muon
Lion:只用动量的符号更新,省一个状态、更新幅度恒定。Muon:对 2D 权重矩阵,把动量矩阵做近似正交化(Newton–Schulz 迭代,得到 \(\approx UV^\top\)),让更新在所有奇异方向上幅度相等;embedding、输出层和标量参数仍用 AdamW。Kimi/Moonshot 的工作报告在大规模 LLM 上相对 AdamW 有约 2 倍的计算效率。
Lion takes the sign of an interpolated momentum; Muon orthogonalizes the momentum of each 2D weight matrix with a Newton–Schulz iteration so every singular direction moves equally, keeping AdamW for embeddings, the output head and scalars.
Lion(Chen et al. 2023, "Symbolic Discovery of Optimization Algorithms")
\(c_t=\beta_1m_{t-1}+(1-\beta_1)g_t\);\(\theta\leftarrow\theta-\eta(\text{sign}(c_t)+\lambda\theta)\);\(m_t=\beta_2m_{t-1}+(1-\beta_2)g_t\)(默认 \(\beta_1=0.9,\beta_2=0.99\))。通过程序搜索发现。每个坐标更新幅度都是 \(\eta\),所以 lr 通常要比 AdamW 小 3–10 倍、weight decay 相应放大。只存一个动量,省显存。
Muon(Keller Jordan et al., 2024 博文)
- 做法:对每个 2D 隐藏层权重,先算 SGD-momentum(默认 Nesterov 风格)的更新矩阵 \(M\),再用 5 步 Newton–Schulz 迭代把它近似替换为最近的半正交矩阵 \(UV^\top\)(\(M=U\Sigma V^\top\))。迭代在 bf16 中进行,输入先除以 Frobenius 范数使奇异值 \(\le 1\);每步对每个奇异值作用多项式 \(p(\sigma)=a\sigma+b\sigma^3+c\sigma^5\),系数 \((3.4445,-4.7750,2.0315)\) 被调成能快速把 \([0,1]\) 中的奇异值推到 1 附近(不精确等于 1,大约落在 0.7–1.2,实践中足够)。
- 为什么:梯度/动量矩阵往往是"低秩主导"的——少数奇异方向占据了几乎全部能量;正交化让那些很少被更新的方向也获得同样幅度的更新。理论上它是谱范数约束下的最速下降,也等价于 Shampoo 去掉预条件累积后的形式。
- 范围:只用于隐藏层的 2D 矩阵(卷积核展平成 2D);embedding、LM head、增益和 bias 用 AdamW。博文建议 Q、K、V 分别正交化而不是作为一个融合矩阵。
- 规模化:Liu et al. 2025, "Muon is Scalable for LLM Training"(Moonshot AI)加入 weight decay 并调整每个参数矩阵的更新尺度,使其能与 AdamW 的超参匹配;用它训练了 3B 激活 / 16B 总参数的 MoE 模型 Moonlight(5.7T token),scaling law 实验显示相对 AdamW 约 2× 计算效率。
代码:Newton–Schulz 正交化(numpy,已运行)
import numpy as np
rng = np.random.default_rng(0)
def newton_schulz5(G, steps=5, eps=1e-7):
"""Muon 的近似正交化:返回 ≈ U Vᵀ(G = U S Vᵀ)。系数来自 Keller Jordan (2024)。"""
a, b, c = 3.4445, -4.7750, 2.0315
X = G / (np.linalg.norm(G) + eps) # Frobenius 归一化 ⇒ 所有奇异值 ≤ 1
transpose = X.shape[0] > X.shape[1]
if transpose:
X = X.T # 让 X Xᵀ 是较小的方阵
for _ in range(steps):
A = X @ X.T
X = a * X + (b * A + c * A @ A) @ X # 每个奇异值 σ ↦ aσ + bσ³ + cσ⁵
return X.T if transpose else X
G = rng.normal(size=(64, 32)) @ np.diag(np.logspace(0, -2, 32)) # 条件数 ~100 的"梯度"
O = newton_schulz5(G)
U, s, Vt = np.linalg.svd(G, full_matrices=False)
sv = np.linalg.svd(O, compute_uv=False)
print(f"input singular values: [{s.min():.4f}, {s.max():.3f}]")
print(f"output singular values: [{sv.min():.3f}, {sv.max():.3f}]")
print(f"cosine(O, U Vᵀ) = {np.sum(O * (U @ Vt)) / np.linalg.norm(O) / np.linalg.norm(U @ Vt):.3f}")
assert sv.max() < 1.3 and sv.min() > 0.3 # 不是精确正交,但奇异值被"拉平"到 1 附近
input singular values: [0.0601, 7.515]
output singular values: [0.686, 1.202]
cosine(O, U Vᵀ) = 0.983
输入奇异值横跨两个数量级,5 步后全部落在 [0.69, 1.20],方向与精确 \(UV^\top\) 的余弦相似度 0.98。
Muon is an optimizer for the 2D weight matrices of hidden layers. It computes a momentum update and then approximately orthogonalizes it with a few Newton–Schulz iterations, effectively replacing the update with UVᵀ from its SVD, so all singular directions move by the same amount instead of a few dominant directions taking over. You can view it as steepest descent under the spectral norm, or as Shampoo without accumulation. Embeddings, the output head and scalar parameters still use AdamW. Moonshot showed it scales to large MoE models once you add weight decay and match update scales, reporting roughly twice AdamW's compute efficiency.
§5 · CLASSICAL ML经典机器学习:偏差–方差、正则化、线性模型、指标
RS 面试很少考 SVM 的对偶推导,但几类问题经常出现:偏差–方差分解(推导 + 和现代 double descent 的关系)、L1 vs L2 为什么一个稀疏一个不稀疏、手推逻辑回归梯度、ROC-AUC vs PR-AUC、模型校准。还有一些"写 20 行 numpy"的题(k-means、PCA、逻辑回归),在 m14 也会再练一次。
偏差–方差分解(推导)
对平方损失,\(\mathbb{E}_{D,\varepsilon}[(y-\hat f_D(x))^2] = \underbrace{(\bar f(x)-f(x))^2}_{\text{bias}^2}+\underbrace{\mathbb{E}_D[(\hat f_D(x)-\bar f(x))^2]}_{\text{variance}}+\underbrace{\sigma^2}_{\text{noise}}\),\(\bar f=\mathbb{E}_D[\hat f_D]\)。模型太简单 → 偏差大(欠拟合),太复杂 → 方差大(过拟合)。现代过参数化模型(double descent)表明"复杂度 ↑ 方差必然 ↑"并不总是成立。
Expected squared error at a point splits into squared bias of the average model, variance across training sets, and irreducible noise — though overparameterized models show the classic U-curve isn't the whole story.
推导
设 \(y=f(x)+\varepsilon\),\(\mathbb{E}\varepsilon=0\),\(\text{Var}\,\varepsilon=\sigma^2\),\(\varepsilon\) 与训练集 \(D\) 独立。固定 \(x\),记 \(\hat f=\hat f_D(x)\),\(\bar f=\mathbb{E}_D\hat f\)。
$$\begin{aligned} \mathbb{E}[(y-\hat f)^2] &= \mathbb{E}[(f+\varepsilon-\hat f)^2] = \mathbb{E}[(f-\hat f)^2] + 2\,\mathbb{E}[\varepsilon]\,\mathbb{E}[f-\hat f] + \mathbb{E}[\varepsilon^2]\\ &= \mathbb{E}[(f-\hat f)^2]+\sigma^2. \end{aligned}$$再把 \(f-\hat f = (f-\bar f)+(\bar f-\hat f)\) 展开:
$$\mathbb{E}[(f-\hat f)^2] = (f-\bar f)^2 + 2(f-\bar f)\underbrace{\mathbb{E}[\bar f-\hat f]}_{=0} + \mathbb{E}[(\bar f-\hat f)^2] = \text{bias}^2+\text{var}.$$两次都用了同一个技巧:"加减均值,交叉项期望为零"。∎
实验验证(多项式回归,20 个训练点)
deg=1: bias²=0.152 var=0.033 noise=0.090 sum=0.275 test MSE=0.276
deg=3: bias²=0.003 var=0.024 noise=0.090 sum=0.117 test MSE=0.118
deg=7: bias²=0.002 var=3.354 noise=0.090 sum=3.446 test MSE=3.440
1 次多项式偏差主导;3 次最佳;7 次偏差很小但方差爆炸。三项之和与独立测量的测试 MSE 吻合。
和现代深度学习的关系
- Double descent(Belkin et al. 2019;Nakkiran et al. 2019 的 "Deep Double Descent"):测试误差随模型大小先降、在"刚好能插值训练集"的阈值附近升高、之后再次下降。阈值处模型被迫用很"扭曲"的函数拟合噪声(方差峰值);远超阈值后,在众多插值解中,优化算法的隐式偏好(例如最小范数)选到了平滑的解。
- Nakkiran et al. 还观察到 epoch-wise double descent 和"更多数据反而变差"的区间。
- LLM 预训练:单 epoch、数据远多于"可记忆"的量,处于几乎没有过拟合的区间,"更大模型 + 更多数据"单调变好(scaling law)。偏差–方差的语言更多出现在微调(小数据、多 epoch)和 RL 估计量中。
代码(已运行)
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x)
x0 = np.linspace(0.05, 0.95, 50); sigma = 0.3 # 测试点 & 噪声标准差
for deg in [1, 3, 7]:
preds = []
for _ in range(500): # 500 个独立训练集,每个 20 个点
xt = rng.random(20); yt = f(xt) + sigma * rng.normal(size=20)
preds.append(np.polyval(np.polyfit(xt, yt, deg), x0))
P = np.array(preds) # (500, 50)
bias2 = ((P.mean(0) - f(x0))**2).mean()
var = P.var(0).mean()
ynew = f(x0) + sigma * rng.normal(size=P.shape) # 新的测试噪声
mse = ((P - ynew)**2).mean()
print(f"deg={deg}: bias²={bias2:.3f} var={var:.3f} noise={sigma**2:.3f} "
f"sum={bias2 + var + sigma**2:.3f} test MSE={mse:.3f}")
assert abs(mse - (bias2 + var + sigma**2)) < 0.05 * mse + 0.01
Fix a test point and average over training sets and label noise. Adding and subtracting the true function, the noise term separates out because it's independent of the training set, and then adding and subtracting the average prediction splits the rest into squared bias — how far the average model is from the truth — and variance — how much the prediction fluctuates across training sets. Simple models have high bias, flexible models high variance. The modern caveat is double descent: past the interpolation threshold, test error can go down again because the optimizer's implicit bias picks smooth interpolating solutions, which is part of why huge overparameterized networks generalize.
- How do ensembling and bagging affect bias and variance?
思路
平均 \(M\) 个模型:偏差不变(平均的期望还是 \(\bar f\)),方差变为 \(\rho\sigma^2+\frac{1-\rho}{M}\sigma^2\)(\(\rho\) 为模型间相关系数)。所以 bagging/随机森林通过去相关降方差;boosting 主要降偏差。 - Where does the bias-variance trade-off show up in RL for LLMs?
思路
advantage 估计(MC vs critic vs GAE λ)、KL 估计量(k1/k2/k3)、组大小(GRPO 组内 baseline:组越大 baseline 越准)、PPO clipping(引入偏差换稳定)。
正则化:L1 vs L2 的几何、dropout、early stopping、数据增强
L2 把权重均匀缩小但几乎不会恰好为 0;L1 产生稀疏解,因为 L1 球在坐标轴上有"尖角",损失等高线最先碰到的往往是尖角(某些坐标 = 0);从梯度看,L1 的"拉力"在 0 附近不消失(恒为 \(\lambda\)),而 L2 的拉力 \(\lambda w\) 随 \(w\to0\) 消失。
L1 gives sparse solutions because its constraint ball has corners on the axes and its pull toward zero doesn't fade near zero, whereas L2's pull is proportional to the weight, so it shrinks but rarely zeroes.
三种解释 L1 稀疏性
- 几何:约束形式 \(\min L(w)\) s.t. \(\|w\|_1\le t\)。L1 球是菱形(高维是 cross-polytope),顶点在坐标轴上;椭圆等高线与菱形的第一个接触点大概率是顶点或低维棱 ⇒ 部分坐标为 0。L2 球是圆,接触点一般不在坐标轴上。
- 次梯度:一维 \(\min_w\frac12(w-a)^2+\lambda|w|\) 的解是 soft-thresholding:\(w^*=\text{sign}(a)\max(|a|-\lambda,0)\)。\(|a|\le\lambda\) 时恰好为 0。而 \(\frac12(w-a)^2+\frac\lambda2w^2\) 的解是 \(w^*=a/(1+\lambda)\),只缩放,永不为 0。
- 贝叶斯:Laplace 先验在 0 处有尖峰,高斯先验在 0 处是平的(§2 MAP)。
其他正则化
- Dropout:训练时以概率 \(p\) 置零激活并把剩下的除以 \(1-p\)(inverted dropout,保持期望),测试时不做任何事。解释:隐式集成指数多个子网络;防止神经元共适应。LLM 大规模预训练通常不用 dropout(单 epoch,没有过拟合问题,dropout 只会降低有效容量和吞吐),微调时有时会用(m03)。
- Early stopping:在验证集 loss 最低时停止。对线性模型 + GD,早停近似等价于 L2 正则(\(t\) 步 GD ≈ \(\lambda\approx1/(\eta t)\) 的 ridge)。
- 数据增强:编码不变性先验(图像翻转、裁剪;文本回译、同义改写)。
- Label smoothing:目标从 one-hot 变成 \((1-\epsilon)\) 和 \(\epsilon/K\),防止 logits 无限增大、改善校准(m03)。
- 隐式正则:SGD 噪声、小 batch、早停、参数共享、架构本身(卷积的平移等变)。
Three ways to see why L1 gives sparsity. Geometrically, the L1 ball has corners on the axes, so the loss contours usually touch it at a corner where some coordinates are zero. Analytically, the one-dimensional L1 problem is solved by soft-thresholding — anything with magnitude below lambda becomes exactly zero — while L2 just rescales by one over one plus lambda. And from a Bayesian view, the Laplace prior has a sharp peak at zero while the Gaussian is flat there. L2 shrinks weights smoothly and is what weight decay implements. For deep nets we also rely on dropout, early stopping and augmentation — though large-scale LLM pretraining usually skips dropout since it's single-epoch and not overfitting.
- Why is dropout rescaled by 1/(1−p) during training?
思路
保持每个激活的期望不变:\(\mathbb{E}[\text{mask}\cdot x/(1-p)]=x\)。这样测试时直接使用完整网络、无需缩放(inverted dropout)。若训练时不缩放,就必须在测试时乘以 \(1-p\)。 - When might you prefer elastic net?
思路
特征高度相关时,Lasso 会随机选其中一个并丢弃其余,不稳定;加上 L2 项(elastic net)会让相关特征共享权重,同时保留稀疏性。
交叉验证与数据划分
训练集拟合参数,验证集选超参/早停,测试集只在最后用一次。k-fold CV 在小数据上更稳健地估计泛化误差。最大的风险是泄漏:任何从测试集"偷看"的信息(预处理统计量、重复样本、时间顺序、benchmark 污染)都会让估计过于乐观。
Train for parameters, validation for hyperparameters, test once at the end; k-fold CV gives a more stable estimate on small data, and leakage is the main way these estimates go wrong.
- k-fold:分 \(k\) 份,轮流做验证,平均。常用 \(k=5\) 或 10。分层(stratified)保持类别比例;分组(group k-fold)保证同一用户/文档不跨 fold;时间序列用前向滚动验证。
- 常见泄漏:在全数据上做标准化/特征选择后再切分;近重复样本跨训练/测试;用测试集调超参("在测试集上做研究生下降");LLM 的 benchmark 题出现在预训练语料中(m13 污染检测)。
- LLM 时代:模型太大,不做 k-fold;但"held-out、时间切分、去重、私有测试集"的思想完全一样。
The training set fits parameters, the validation set picks hyperparameters and stopping points, and the test set should be touched once. With small data, k-fold cross-validation averages over k splits for a more stable estimate, using stratified or grouped folds when needed. The main failure mode is leakage — fitting preprocessing on all the data, near-duplicates across splits, or, for LLMs, benchmark contamination in the pretraining corpus.
线性回归:闭式解、梯度、几何、ridge
\(\min_w\|Xw-y\|^2\) 的梯度 \(2X^\top(Xw-y)\),令其为零得正规方程 \(X^\top Xw=X^\top y\),\(\hat w=(X^\top X)^{-1}X^\top y\)。几何上 \(X\hat w\) 是 \(y\) 在 \(X\) 列空间上的正交投影,残差与所有特征正交。Ridge:\(\hat w=(X^\top X+\lambda I)^{-1}X^\top y\),总是可逆。
Least squares has gradient 2Xᵀ(Xw − y); setting it to zero gives the normal equations, and geometrically the fit is the orthogonal projection of y onto the column space of X. Ridge adds λI, which makes the system always invertible.
- 概率解释:高斯噪声下的 MLE(§2);ridge = 高斯先验下的 MAP。
- 投影矩阵:\(P = X(X^\top X)^{-1}X^\top\),\(P^2=P\),\(P^\top=P\)。残差 \(r=(I-P)y\),\(X^\top r=0\)(这就是正规方程本身)。
- 复杂度:形成 \(X^\top X\) 是 \(O(nd^2)\),求解 \(O(d^3)\)。\(d\) 大时用 GD/SGD 或共轭梯度。
- 数值:用
np.linalg.solve或lstsq(QR/SVD)而不是inv;\(\kappa(X^\top X)=\kappa(X)^2\)(§1)。 - \(d > n\):\(X^\top X\) 奇异,有无穷多解;最小范数解是 \(X^+y\),从 \(w_0=0\) 开始的 GD 恰好收敛到它(隐式正则的经典例子,与 double descent 相关)。
- GD 步长:平均损失 \(\frac1n\|Xw-y\|^2\) 的光滑常数是 \(L=\frac2n\lambda_{\max}(X^\top X)\),用 \(\eta=1/L\)。
代码:闭式 / lstsq / GD / ridge 一致性(已运行)
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 5
X = rng.normal(size=(n, d)); w_true = rng.normal(size=d)
y = X @ w_true + 0.1 * rng.normal(size=n)
w_normal = np.linalg.solve(X.T @ X, X.T @ y) # 正规方程:用 solve,不要 inv
w_lstsq = np.linalg.lstsq(X, y, rcond=None)[0] # SVD/QR:更稳(不平方条件数)
# 梯度下降:L(w) = ||Xw - y||²/n,∇L = 2Xᵀ(Xw - y)/n,smoothness 常数 = 2·λmax(XᵀX/n)
Lsm = 2 * np.linalg.eigvalsh(X.T @ X / n).max()
w = np.zeros(d)
for _ in range(3000):
w -= (1 / Lsm) * 2 * X.T @ (X @ w - y) / n
assert np.allclose(w_normal, w_lstsq) and np.allclose(w, w_normal, atol=1e-6)
lam = 0.5 # ridge:(XᵀX + λI)⁻¹Xᵀy
w_ridge = np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)
assert np.linalg.norm(w_ridge) < np.linalg.norm(w_normal)
print("cond(X) =", round(np.linalg.cond(X), 3), " cond(XᵀX) =", round(np.linalg.cond(X.T @ X), 3))
assert np.isclose(np.linalg.cond(X.T @ X), np.linalg.cond(X)**2)
cond(X) = 1.289 cond(XᵀX) = 1.662
Least squares minimizes the squared residual norm; the gradient is two X-transpose times the residual, and setting it to zero gives the normal equations. Geometrically, the fitted values are the orthogonal projection of y onto the column space of X, so the residual is orthogonal to every feature. Numerically I'd use a QR or SVD-based solver rather than inverting XᵀX, since that squares the condition number. Ridge adds lambda times the identity, which always makes it invertible and corresponds to a Gaussian prior. And when there are more features than samples, gradient descent from zero converges to the minimum-norm solution — a nice example of implicit regularization.
逻辑回归:推导梯度 \(X^\top(\sigma(Xw)-y)\)
\(p=\sigma(w^\top x)\),损失是 BCE(Bernoulli NLL)\(\ell=-[y\log p+(1-y)\log(1-p)]\)。利用 \(\sigma'=\sigma(1-\sigma)\),梯度化简为 \(\nabla_w\ell=(p-y)x\),批量形式 \(\frac1nX^\top(\sigma(Xw)-y)\)。损失是凸的(Hessian \(X^\top SX\succeq0\)),但线性可分时 MLE 不存在(\(\|w\|\to\infty\)),需要正则。
Logistic regression's gradient simplifies to (p − y)x per example, or Xᵀ(σ(Xw) − y) over a batch; the loss is convex, but on separable data the weights diverge without regularization.
推导
\(z=w^\top x\),\(p=\sigma(z)=\frac1{1+e^{-z}}\)。先求 \(\sigma'(z)=\frac{e^{-z}}{(1+e^{-z})^2}=\sigma(z)(1-\sigma(z))\)。
$$\frac{\partial\ell}{\partial z} = -\Big[\frac{y}{p}-\frac{1-y}{1-p}\Big]\frac{\partial p}{\partial z} = -\Big[\frac{y}{p}-\frac{1-y}{1-p}\Big]p(1-p) = -[y(1-p)-(1-y)p] = p-y.$$链式法则 \(\partial z/\partial w=x\) ⇒ \(\nabla_w\ell=(p-y)x\)。对 \(n\) 个样本取平均:\(\nabla_w\mathcal{L}=\frac1nX^\top(\sigma(Xw)-y)\)。
更简洁的写法:\(\ell = \log(1+e^{z})-yz\)(代入 \(\log p=-\log(1+e^{-z})\)、\(\log(1-p)=-z-\log(1+e^{-z})\) 化简)。\(\partial\ell/\partial z=\sigma(z)-y\),一步到位,而且 np.logaddexp(0, z) 正好是 \(\log(1+e^z)\) 的数值稳定实现。
Hessian 与凸性
\(\nabla^2\mathcal{L}=\frac1nX^\top SX\),\(S=\text{diag}(p_i(1-p_i))\succeq0\) ⇒ 凸。Newton 法在这里就是 IRLS(迭代重加权最小二乘)。
与 softmax 回归 / LLM 的联系
\(K\) 类:\(p=\text{softmax}(Wx)\),交叉熵对 logits 的梯度是 \(p-y\)(one-hot),对 \(W\) 是 \((p-y)x^\top\)。这和 LM head 的梯度形式完全一样;sigmoid 是 \(K=2\) 的特例(\(\sigma(z)=\text{softmax}([z,0])_1\))。Bradley–Terry reward model 的损失 \(-\log\sigma(r_w-r_l)\) 也是逻辑回归(m06)。
可分数据的问题
若存在 \(w\) 完美分开数据,把 \(w\) 放大 \(c\) 倍会让所有 \(p\) 更接近 0/1,loss 单调下降趋于 0 ⇒ 没有有限的最优解,GD 中 \(\|w\|\) 发散(方向收敛到最大间隔方向——又一个隐式正则的例子,Soudry et al. 2018)。
代码:numpy 逻辑回归 + 梯度检查(已运行)
import numpy as np
def sigmoid(z):
# 数值稳定:正负两支分开算,避免 exp 溢出
out = np.empty_like(z, dtype=float)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
ez = np.exp(z[~pos])
out[~pos] = ez / (1.0 + ez)
return out
def loss_and_grad(w, b, X, y, lam=0.0):
"""平均 BCE + (lam/2)||w||²。X:(n,d) y:(n,) ∈ {0,1}"""
n = X.shape[0]
z = X @ w + b # (n,) logits
# BCE = log(1+e^z) - y·z,用 logaddexp(0,z) 稳定计算 log(1+e^z)
loss = np.mean(np.logaddexp(0.0, z) - y * z) + 0.5 * lam * (w @ w)
r = sigmoid(z) - y # (n,) 残差 p - y
gw = X.T @ r / n + lam * w # (d,) = Xᵀ(σ(Xw)-y)/n
gb = r.mean()
return loss, gw, gb
def train(X, y, lr=0.5, steps=2000, lam=1e-3):
w, b = np.zeros(X.shape[1]), 0.0
for _ in range(steps):
loss, gw, gb = loss_and_grad(w, b, X, y, lam)
w -= lr * gw
b -= lr * gb
return w, b, loss
rng = np.random.default_rng(0)
n, d = 1000, 5
w_true = rng.normal(size=d)
X = rng.normal(size=(n, d))
y = (rng.random(n) < sigmoid(X @ w_true + 0.5)).astype(float)
# (1) 有限差分梯度检查 —— 面试写完梯度一定要说"我会做 gradient check"
w0, b0, eps = rng.normal(size=d), 0.3, 1e-6
_, gw, _ = loss_and_grad(w0, b0, X, y, 1e-2)
num = np.array([(loss_and_grad(w0 + eps * e, b0, X, y, 1e-2)[0]
- loss_and_grad(w0 - eps * e, b0, X, y, 1e-2)[0]) / (2 * eps) for e in np.eye(d)])
assert np.allclose(num, gw, atol=1e-7)
# (2) 训练并和"知道真参数的 oracle"比较
w, b, loss = train(X, y)
acc = np.mean((sigmoid(X @ w + b) > 0.5) == y)
oracle = np.mean(((X @ w_true + 0.5) > 0) == y)
cos = w @ w_true / np.linalg.norm(w) / np.linalg.norm(w_true)
print(f"loss {loss:.4f} acc {acc:.3f} oracle acc {oracle:.3f} cos(w, w_true) {cos:.3f}")
assert acc > oracle - 0.02 and cos > 0.95
loss 0.6067 acc 0.674 oracle acc 0.666 cos(w, w_true) 0.993
准确率只有 67% 是因为标签本身是从 \(\sigma(Xw_{\text{true}})\) 随机采样的(知道真参数的 oracle 也只有 66.6%);判断学得好不好要看参数方向(余弦 0.993)。
np.log(sigmoid(z)):\(z\) 很负时 sigmoid 下溢为 0,log 得 \(-\infty\)。用 logaddexp 或 PyTorch 的 BCEWithLogitsLoss(接收 logits)。(2) 梯度忘了除以 \(n\),导致 lr 依赖 batch size。(3) 用 MSE 训练逻辑回归:非凸且 sigmoid 饱和时梯度消失。Logistic regression models the probability as sigmoid of w-dot-x and minimizes binary cross-entropy, which is the Bernoulli negative log-likelihood. Using sigma prime equals sigma times one minus sigma, the derivative with respect to the logit collapses to p minus y, so the gradient is p minus y times x, or Xᵀ(σ(Xw) − y) over n for a batch. The Hessian is XᵀSX with S diagonal and non-negative, so it's convex. In code I'd compute the loss from logits as log(1 + e^z) − yz using logaddexp for stability. The same p-minus-y form shows up for softmax cross-entropy, which is exactly the gradient at an LM head.
- Why not train logistic regression with MSE?
思路
MSE 对 \(w\) 非凸;梯度 \(=(p-y)p(1-p)x\),当预测错得很离谱时(\(p\approx0\) 而 \(y=1\))\(p(1-p)\approx0\),梯度消失,学不动。BCE 的梯度 \((p-y)x\) 恰好消去了这个因子。 - What happens on linearly separable data?
思路
MLE 不存在,\(\|w\|\to\infty\),概率趋于 0/1、过度自信。加 L2 正则或早停;GD 的方向会收敛到最大间隔(hard-margin SVM)方向。
Softmax 回归(多项逻辑回归)
\(p=\text{softmax}(Wx+b)\),损失 \(-\log p_y\),梯度 \(\nabla_W=(p-e_y)x^\top\)。softmax 对 logits 加常数不变(冗余参数),所以实现时先减去最大值保证数值稳定。
Softmax regression generalizes logistic regression to K classes; the gradient is (p − one_hot(y)) xᵀ, and subtracting the max logit before exponentiating keeps it numerically stable.
- \(\text{softmax}(z+c\mathbf 1)=\text{softmax}(z)\),所以 \(K\) 组参数中有一组是冗余的(\(K=2\) 时退化为 sigmoid)。
- \(-\log p_y = -z_y+\log\sum_k e^{z_k}\);用 log-sum-exp 技巧:\(\text{LSE}(z)=m+\log\sum e^{z_k-m}\),\(m=\max z\)。
- 完整的 softmax Jacobian 和 CE 梯度推导在 m03 §2。
Softmax regression is the multiclass version of logistic regression: logits are a linear function of the input, probabilities come from a softmax, and the loss is the negative log-probability of the correct class. The gradient with respect to the logits is the predicted distribution minus the one-hot label. Since softmax is invariant to adding a constant, I subtract the max logit before exponentiating to avoid overflow.
分类指标:P/R/F1、ROC-AUC vs PR-AUC、校准与 ECE
Precision = TP/(TP+FP)(预测为正的里面有多少对),Recall = TP/(TP+FN)(真正的正例找回多少)。ROC-AUC = 随机正例得分高于随机负例的概率,对类别比例不敏感;类别极不平衡时 PR-AUC 更能反映正类上的表现。校准:预测 80% 置信的样本里应该有 80% 正确;ECE 衡量偏离程度。
Precision is the fraction of predicted positives that are right, recall the fraction of actual positives found; ROC-AUC is the probability a random positive outranks a random negative and ignores class balance, so PR-AUC is more informative for rare positives; calibration asks whether confidence matches accuracy.
| 指标 | 公式 | 注意 |
|---|---|---|
| Accuracy | (TP+TN)/N | 不平衡时误导(99% 负例,全猜负就 99%) |
| Precision | TP/(TP+FP) | 依赖正例比例(§2 Bayes) |
| Recall / TPR | TP/(TP+FN) | = 敏感度 |
| FPR | FP/(FP+TN) | ROC 横轴 |
| F1 | \(2PR/(P+R)\) | 调和平均,被较小者主导 |
| ROC-AUC | TPR vs FPR 曲线下面积 | = \(P(s_+>s_-)\),与 Mann–Whitney U 统计量等价 |
| PR-AUC / AP | Precision vs Recall 曲线下面积 | 随机分类器的基线 = 正例比例(而 ROC 基线永远 0.5) |
ROC-AUC vs PR-AUC
ROC 的两个坐标 TPR、FPR 都是在各自类别内部归一化的,所以不随类别比例变化。当负例极多时,FPR 从 0.001 涨到 0.01 在 ROC 图上几乎看不出,但可能意味着假阳性数量涨 10 倍、precision 暴跌——PR 曲线能看到。正例稀少且关心正类(检测、检索、安全 flag)用 PR-AUC。
校准(Calibration)
- 可靠性图:把预测置信度分桶,画每桶的平均置信度 vs 实际准确率;完美校准是对角线。
- ECE \(=\sum_b\frac{|B_b|}{n}|\text{acc}(B_b)-\text{conf}(B_b)|\)。简单但依赖分桶方式。
- 修正:temperature scaling(在验证集上学一个标量 \(T\),\(\text{softmax}(z/T)\),不改变 argmax/准确率)、Platt scaling、isotonic regression。
- LLM:预训练模型的 token 概率通常校准得不错(因为 CE 是 proper scoring rule);RLHF 后往往过度自信(GPT-4 技术报告中展示过 post-training 损害校准的现象)。用 LLM 做判断/打分时要注意这一点。
代码:秩公式 AUC(处理并列)+ ECE(已运行)
import numpy as np
rng = np.random.default_rng(0)
def roc_auc(y, s):
"""AUC = P(s_pos > s_neg) + ½P(相等)。秩公式(Mann–Whitney U),O(n log n)"""
order = np.argsort(s, kind="mergesort"); ss = s[order]
ranks = np.empty(len(s)); i = 0
while i < len(s): # 并列取平均秩
j = i
while j + 1 < len(s) and ss[j + 1] == ss[i]:
j += 1
ranks[order[i:j + 1]] = (i + j) / 2 + 1
i = j + 1
n1 = y.sum(); n0 = len(y) - n1
return (ranks[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)
def auc_bruteforce(y, s): # O(n1·n0) 定义式,用来对拍
pos, neg = s[y == 1], s[y == 0]
return np.mean((pos[:, None] > neg[None, :]) + 0.5 * (pos[:, None] == neg[None, :]))
def ece(conf, correct, bins=10):
edges = np.linspace(0, 1, bins + 1); e = 0.0
for lo, hi in zip(edges[:-1], edges[1:]):
m = (conf > lo) & (conf <= hi)
if m.any():
e += m.mean() * abs(correct[m].mean() - conf[m].mean())
return e
y = (rng.random(500) < 0.3).astype(int)
s = np.round(y * 0.8 + rng.normal(size=500), 1) # round 制造并列
assert np.isclose(roc_auc(y, s), auc_bruteforce(y, s))
print("AUC =", round(roc_auc(y, s), 4))
conf = rng.random(100_000); correct = (rng.random(100_000) < conf).astype(float)
print("ECE calibrated =", round(ece(conf, correct), 4),
" ECE overconfident =", round(ece(np.clip(conf * 1.3, 0, 1), correct), 4))
AUC = 0.7222
ECE calibrated = 0.0024 ECE overconfident = 0.1141
Precision asks, of everything I flagged, how much was right; recall asks, of everything that was actually positive, how much I found. ROC-AUC is the probability that a random positive gets a higher score than a random negative, and since both axes are normalized within each class it's insensitive to class imbalance — which is exactly why it can look great when positives are rare. In that regime I'd look at precision-recall curves, where a random classifier's baseline is the positive rate. Calibration is a separate question: whether 80% confidence means 80% accuracy. ECE measures that, and temperature scaling on a validation set is the standard fix since it doesn't change the ranking.
- How would you compute AUC in O(n log n)?
思路
按得分排序,计算正例的秩和 \(R_+\)(并列取平均秩),\(\text{AUC}=\frac{R_+-n_+(n_++1)/2}{n_+n_-}\)。上面代码实现并与 \(O(n_+n_-)\) 定义式对拍。 - Does temperature scaling change accuracy?
思路
不改变:除以正数 \(T\) 不改变 logits 的排序,argmax 不变;只改变置信度(概率的"尖锐程度")。
kNN、决策树与 boosting、SVM(简要)
kNN:无训练、按最近邻投票,受维度灾难影响。决策树:按信息增益/基尼不纯度贪心切分;随机森林(bagging + 特征随机)降方差,梯度提升(每棵树拟合当前损失的负梯度)降偏差,在表格数据上仍然常常最强。SVM:最大化间隔,等价于 hinge loss + L2;核技巧把内积换成核函数。
kNN is lazy nearest-neighbor voting; trees split greedily on impurity, random forests reduce variance and gradient boosting reduces bias; SVMs maximize the margin, which is hinge loss plus L2, and kernels replace inner products.
- kNN:\(k\) 小 → 低偏差高方差;\(k\) 大 → 反之。高维时所有点的距离趋于相近(距离集中),最近邻失去意义。现代对应:embedding 检索(RAG、kNN-LM),用近似最近邻(ANN,如 HNSW、IVF/PQ)。
- 决策树:信息增益 = 切分前熵 − 切分后加权熵;基尼 \(1-\sum p_k^2\)。容易过拟合 → 剪枝、限深。
- Boosting:AdaBoost 重加权错分样本;梯度提升 \(F_{m}=F_{m-1}+\nu h_m\),\(h_m\) 拟合 \(-\partial L/\partial F\)("函数空间里的梯度下降")。XGBoost/LightGBM 是工业标准。
- SVM:硬间隔 \(\min\frac12\|w\|^2\) s.t. \(y_i(w^\top x_i+b)\ge1\);几何间隔 \(=1/\|w\|\),所以最小化 \(\|w\|\) 就是最大化间隔。软间隔 ⇔ \(\min\frac\lambda2\|w\|^2+\frac1n\sum\max(0,1-y_if(x_i))\)(hinge loss)。对偶问题只依赖内积 \(x_i^\top x_j\),替换为核 \(k(x_i,x_j)\)(RBF 等)即在隐式高维特征空间中做线性分类;解只依赖于支持向量。
- Hinge vs logistic:两者都是 0-1 损失的凸上界;hinge 在间隔足够大后损失恰为 0(稀疏解、不给概率),logistic 永远有梯度并给出概率。
Briefly: kNN predicts by voting among nearest neighbors and suffers in high dimensions as distances concentrate. Trees split greedily on impurity; random forests reduce variance by averaging decorrelated trees, while gradient boosting fits each new tree to the negative gradient of the loss — it's still the go-to for tabular data. SVMs maximize the margin, which is equivalent to hinge loss plus L2 regularization, and since the dual only involves inner products, kernels let you work in an implicit feature space.
k-means
交替两步:(1) 每个点分配给最近的中心;(2) 中心更新为所属点的均值。每一步都不增加目标 \(\sum_i\|x_i-c_{z_i}\|^2\),所以必然收敛,但只到局部最优——用 k-means++ 初始化和多次重启。它是"硬分配 + 等方差球形"版本的 GMM-EM。
K-means alternates assigning points to the nearest centroid and recomputing centroids as means; each step can only lower the objective so it converges, but only to a local optimum — hence k-means++ and restarts.
- 为什么收敛:分配步固定中心,选最近中心使每项最小;更新步固定分配,均值是平方距离和的最小化者。目标单调不增、分配方式有限 ⇒ 有限步收敛。
- 复杂度:每次迭代 \(O(nkd)\)。向量化距离:\(\|x-c\|^2=\|x\|^2-2x^\top c+\|c\|^2\)。
- k-means++:依次选中心,每个新中心以 \(\propto D(x)^2\)(到最近已选中心的距离平方)的概率选取;期望 \(O(\log k)\) 近似比。
- 选 \(k\):elbow 法、silhouette、下游任务。
- 局限:假设簇是凸的、大小相近的球;对尺度和离群点敏感。
- LLM 中:VQ-VAE 的码本更新、数据去重/聚类采样、语义去重(SemDeDup)、产品量化(PQ)检索。
K-means alternates two steps: assign each point to its nearest centroid, then move each centroid to the mean of its points. Each step can only decrease the within-cluster sum of squares and there are finitely many assignments, so it converges — but only to a local optimum, so I'd use k-means++ initialization and several restarts. It can be seen as the hard-assignment, equal-spherical-covariance limit of EM for Gaussian mixtures.
PCA
PCA 找方差最大的正交方向:中心化数据 \(X_c=U\Sigma V^\top\),主成分是 \(V\) 的列,第 \(i\) 个方向的方差 \(=\sigma_i^2/(n-1)\)。等价表述:最小化投影后的重建误差(Eckart–Young)。必须先中心化。
PCA finds orthogonal directions of maximum variance — the right singular vectors of the centered data matrix — which is equivalent to the best low-rank reconstruction in squared error.
推导(最大方差视角)
找单位向量 \(u\) 最大化投影方差 \(u^\top Su\),\(S=\frac1{n-1}X_c^\top X_c\)。拉格朗日:\(u^\top Su-\lambda(u^\top u-1)\),求导 ⇒ \(Su=\lambda u\):\(u\) 是 \(S\) 的特征向量,方差 \(=u^\top Su=\lambda\),取最大特征值。后续主成分在与前面正交的子空间里重复。由 SVD,\(S=V\frac{\Sigma^2}{n-1}V^\top\),所以直接对 \(X_c\) 做 SVD 即可(比显式构造 \(S\) 数值更稳)。
- 解释方差比:\(\lambda_i/\sum_j\lambda_j\)。
- 重建视角:投影到前 \(k\) 个主成分的重建误差 = 剩余特征值之和,是所有 \(k\) 维线性子空间中最小的。
- 局限:只捕捉线性结构;对特征尺度敏感(常先标准化);方差大 ≠ 有用。
- 在 LLM 研究里:可视化表示/激活、分析 embedding 各向异性、找"表示里的主方向"(例如激活差的 PCA 来得到 steering 方向,m11);也是"线性 autoencoder 的最优解张成主子空间"这一结果的来源。
代码:k-means 与 PCA(numpy,已运行)
import numpy as np
rng = np.random.default_rng(0)
def kmeans(X, k, iters=100, seed=0):
r = np.random.default_rng(seed)
C = X[r.choice(len(X), k, replace=False)] # 随机挑 k 个点做初始中心
for _ in range(iters):
# (n,k) 平方距离 = ||x||² - 2x·c + ||c||²,完全向量化
d2 = (X**2).sum(1, keepdims=True) - 2 * X @ C.T + (C**2).sum(1)
labels = d2.argmin(1) # assignment step
newC = np.array([X[labels == j].mean(0) if np.any(labels == j) else C[j]
for j in range(k)]) # update step(空簇保留旧中心)
if np.allclose(newC, C):
break
C = newC
inertia = ((X - C[labels])**2).sum()
return C, labels, inertia
def pca(X, k):
Xc = X - X.mean(0) # 一定先中心化
U, S, Vt = np.linalg.svd(Xc, full_matrices=False) # Xc = U S Vᵀ
var = S**2 / (len(X) - 1) # = 协方差矩阵的特征值
return Vt[:k], Xc @ Vt[:k].T, var[:k] / var.sum() # 主方向, 投影, 解释方差比
centers = np.array([[0, 0], [5, 5], [0, 6]])
X = np.vstack([c + rng.normal(scale=0.6, size=(200, 2)) for c in centers])
C, labels, inertia = min((kmeans(X, 3, seed=s) for s in range(5)), key=lambda t: t[2]) # 多次重启
print("k-means centers:\n", np.round(C[np.lexsort(C.T[::-1])], 2))
assert np.allclose(np.sort(C, 0), np.sort(centers, 0), atol=0.2)
dirn = np.array([1.0, 2.0]) / np.sqrt(5) # 数据沿 (1,2)/√5 拉长
Z = rng.normal(size=(2000, 1)) * 3 * dirn + rng.normal(size=(2000, 2)) * 0.3
comps, proj, ratio = pca(Z, 1)
print("PC1 =", np.round(comps[0], 3), " explained ratio =", np.round(ratio, 3))
assert abs(abs(comps[0] @ dirn) - 1) < 1e-3
evals, evecs = np.linalg.eigh(np.cov(Z.T)) # 与协方差特征分解一致
assert abs(abs(evecs[:, -1] @ comps[0]) - 1) < 1e-8
k-means centers:
[[-0.06 0.01]
[-0.04 5.99]
[ 4.97 5.01]]
PC1 = [0.446 0.895] explained ratio = [0.99]
U 而不是 Vt 作为主方向(形状 \(n\times k\) vs \(k\times d\),看形状就知道)。(3) 不同量纲的特征直接做 PCA。PCA looks for orthogonal directions that capture the most variance. Maximizing uᵀSu subject to unit norm gives an eigenvalue problem, so the principal components are the top eigenvectors of the covariance, and the variance along each is its eigenvalue. In practice I center the data and take the SVD — the right singular vectors are the components and the squared singular values over n minus one are the variances. Equivalently, it's the best k-dimensional linear reconstruction in squared error, by Eckart–Young.
EM 与高斯混合模型(简要)
有隐变量 \(z\) 时直接最大化 \(\log\sum_zp(x,z)\) 很难。EM 交替:E 步计算后验 \(q(z)=p(z\mid x,\theta^{\text{old}})\)(GMM 中是每个点属于每个分量的"责任");M 步最大化 \(\mathbb{E}_q[\log p(x,z\mid\theta)]\)(GMM 中是加权均值/协方差/权重)。每步不降低似然,因为它在优化 ELBO 这个下界。
EM alternates computing the posterior over latent variables and maximizing the expected complete-data log-likelihood; it monotonically increases the likelihood because it's coordinate ascent on the ELBO.
ELBO 视角:对任意 \(q\),
$$\log p(x\mid\theta) = \underbrace{\mathbb{E}_q\Big[\log\frac{p(x,z\mid\theta)}{q(z)}\Big]}_{\text{ELBO}(q,\theta)} + \text{KL}\big(q(z)\,\|\,p(z\mid x,\theta)\big).$$E 步令 \(q=p(z\mid x,\theta)\) 使 KL = 0、ELBO = log-likelihood;M 步在 \(q\) 固定下提高 ELBO ⇒ 似然不降。VAE 是同一个 ELBO,但 \(q\) 用神经网络摊销(amortized)、用梯度同时优化两者(m12)。
GMM:E 步 \(\gamma_{ik}=\frac{\pi_k\mathcal{N}(x_i;\mu_k,\Sigma_k)}{\sum_j\pi_j\mathcal{N}(x_i;\mu_j,\Sigma_j)}\);M 步 \(N_k=\sum_i\gamma_{ik}\),\(\mu_k=\frac1{N_k}\sum_i\gamma_{ik}x_i\),\(\Sigma_k=\frac1{N_k}\sum_i\gamma_{ik}(x_i-\mu_k)(x_i-\mu_k)^\top\),\(\pi_k=N_k/n\)。当 \(\Sigma_k=\sigma^2I\)、\(\sigma\to0\) 时责任变成硬分配 ⇒ k-means。
EM handles latent-variable models by alternating two steps: the E-step computes the posterior over the latent variables under the current parameters — for a Gaussian mixture, each component's responsibility for each point — and the M-step re-estimates parameters by maximizing the expected complete-data log-likelihood, which for GMMs is just responsibility-weighted means and covariances. It never decreases the likelihood because it's coordinate ascent on the evidence lower bound, the same ELBO that VAEs optimize with amortized inference.
§6 · EXERCISES练习(16 题,全部带完整解答)
建议做法:先盖住答案,在纸上推导或在空白文件里写代码(关掉 AI 补全),限时;然后对照答案,并用英文把思路讲一遍。所有代码都在本地用 numpy 运行通过(输出贴在答案里)。难度:★ 基础、★★ 面试常规、★★★ 有区分度。
| # | 题目 | 类型 | 对应概念 |
|---|---|---|---|
| 6.1 | 推导逻辑回归梯度 | 推导 | 逻辑回归 |
| 6.2 | numpy 训练逻辑回归 | 代码 | 逻辑回归 |
| 6.3 | Adam bias correction | 推导 + 代码 | Adam |
| 6.4 | 高斯 KL 闭式 | 推导 | KL |
| 6.5 | forward/reverse KL 双峰实验 | 代码 | forward vs reverse |
| 6.6 | 重要性采样方差 | 推导 + 代码 | IS |
| 6.7 | k-means 与 PCA | 代码 | k-means, PCA |
| 6.8 | Bernoulli MLE 与 MAP | 推导 | MLE, MAP |
| 6.9 | 最小二乘梯度与正规方程 | 推导 | 线性回归 |
| 6.10 | 疾病检测 Bayes | 概率 | Bayes |
| 6.11 | 抛硬币直到 HH 的期望次数 | 概率 | 期望 |
| 6.12 | 折断木棍成三角形 | 概率 | — |
| 6.13 | 证明 k3 非负且无偏 | 推导 | k1/k2/k3 |
| 6.14 | 证明 Gumbel-max | 推导 | Gumbel |
| 6.15 | soft-thresholding(L1 为什么稀疏) | 推导 | 正则化 |
| 6.16 | GD 在二次函数上的最大步长 | 推导 | GD |
设 \(p_i=\sigma(w^\top x_i)\),\(\mathcal{L}(w)=-\frac1n\sum_i[y_i\log p_i+(1-y_i)\log(1-p_i)]+\frac\lambda2\|w\|^2\)。推导 \(\nabla_w\mathcal{L}\) 并写成矩阵形式;证明 \(\mathcal{L}\) 是凸的。
提示
参考答案
单样本 \(\ell=\log(1+e^{z})-yz\)(因为 \(\log p=z-\log(1+e^z)\),\(\log(1-p)=-\log(1+e^z)\),代入得 \(-[yz-y\log(1+e^z)-(1-y)\log(1+e^z)]=\log(1+e^z)-yz\))。
\(\frac{d\ell}{dz}=\frac{e^z}{1+e^z}-y=\sigma(z)-y\),\(\frac{\partial z}{\partial w}=x\)。所以
$$\nabla_w\mathcal{L}=\frac1n\sum_i(p_i-y_i)x_i+\lambda w=\frac1nX^\top(\sigma(Xw)-y)+\lambda w.$$Hessian:\(\frac{d^2\ell}{dz^2}=\sigma(z)(1-\sigma(z))\ge0\),所以 \(\nabla^2\mathcal{L}=\frac1nX^\top SX+\lambda I\),\(S=\text{diag}(p_i(1-p_i))\)。对任意 \(v\):\(v^\top X^\top SXv=\sum_iS_{ii}(x_i^\top v)^2\ge0\),加上 \(\lambda I\) 后(\(\lambda>0\))严格凸,唯一最优解存在。
English: "The derivative with respect to the logit collapses to p minus y, so the gradient is Xᵀ(σ(Xw) − y) over n plus lambda w, and the Hessian XᵀSX/n + λI is positive definite."
用 numpy 从零实现带 L2 的逻辑回归:数值稳定的 loss、梯度、全批量 GD 训练,以及有限差分梯度检查。在合成数据上验证学到的方向接近真参数。
提示
np.logaddexp(0, z) - y*z;sigmoid 正负分开写避免溢出;梯度检查用中心差分 \((f(w+\epsilon e_i)-f(w-\epsilon e_i))/2\epsilon\)。参考答案
完整代码与输出见 逻辑回归 概念块中的 "numpy 逻辑回归 + 梯度检查"。要点:(1) 形状:X:(n,d)、w:(d,)、r = sigmoid(Xw+b) - y 形状 (n,)、gw = X.T @ r / n;(2) 梯度检查误差 < 1e-7;(3) 不要只看准确率——标签本身有噪声时用"和真参数的余弦相似度"或与 oracle 的准确率比较。
复杂度:每步 \(O(nd)\)。追问"如何扩展到大数据"→ minibatch SGD;"如何多类"→ softmax 回归,梯度 \((P-Y)^\top X/n\)。
(a) 证明在梯度平稳 \(\mathbb{E}[g_t]=\mu\) 时,\(\mathbb{E}[m_t]=(1-\beta_1^t)\mu\)。(b) \(\beta_2=0.999\),若不做修正,第 1 步和第 10 步 \(v_t\) 被低估了多少倍?对步长有什么影响?(c) 写出 AdamW 的一步更新代码。
提示
参考答案
(a) \(m_t=(1-\beta_1)\sum_{i=1}^t\beta_1^{t-i}g_i\),取期望 \(=(1-\beta_1)\mu\sum_{j=0}^{t-1}\beta_1^j=(1-\beta_1)\mu\frac{1-\beta_1^t}{1-\beta_1}=(1-\beta_1^t)\mu\)。
(b) \(t=1\):\(1-0.999=0.001\),\(v\) 被低估 1000 倍,\(\sqrt v\) 低估约 31.6 倍;\(m\) 被低估 10 倍(\(\beta_1=0.9\))。未修正的步长 \(\frac{m}{\sqrt v}\approx\frac{0.1g}{0.0316|g|}\approx3.16\,\text{sign}(g)\),约为修正后的 3.16 倍。\(t=10\):\(1-0.999^{10}\approx0.00995\),\(\sqrt{\cdot}\approx0.0998\);\(1-0.9^{10}\approx0.651\);步长放大 \(0.651/0.0998\approx6.5\) 倍。也就是说不修正时早期步长被放大数倍:放大因子 \(\frac{1-\beta_1^t}{\sqrt{1-\beta_2^t}}\) 在 \(t\approx12\) 时最大(约 6.6 倍),之后缓慢回落,要到上千步才接近 1——正好是训练最脆弱的阶段,容易导致早期不稳定。
(c) 代码见 Adam 概念块(含三个断言:常数梯度下 \(m_1=0.1g\)、第一步位移 \(=\text{lr}\cdot\text{sign}(g)\)、随机梯度下 \(\mathbb{E}[m_5]\approx1-0.9^5\))。
推导 \(\text{KL}(\mathcal{N}(\mu_1,\sigma_1^2)\,\|\,\mathcal{N}(\mu_2,\sigma_2^2))\) 的闭式,并化简出 VAE 中 \(\text{KL}(\mathcal{N}(\mu,\sigma^2)\|\mathcal{N}(0,1))\)。
提示
参考答案
\(\log p(x)-\log q(x)=\log\frac{\sigma_2}{\sigma_1}-\frac{(x-\mu_1)^2}{2\sigma_1^2}+\frac{(x-\mu_2)^2}{2\sigma_2^2}\)。
在 \(x\sim p\) 下取期望:第二项 \(=-\frac{\sigma_1^2}{2\sigma_1^2}=-\frac12\)。第三项:\(x-\mu_2=(x-\mu_1)+(\mu_1-\mu_2)\),\(\mathbb{E}[(x-\mu_2)^2]=\sigma_1^2+(\mu_1-\mu_2)^2\)(交叉项期望为 0)。所以
$$\text{KL}=\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12.$$代入 \(\mu_2=0,\sigma_2=1\):\(-\log\sigma+\frac{\sigma^2+\mu^2}{2}-\frac12=\frac12(\mu^2+\sigma^2-1-\log\sigma^2)\)。检查:\(\mu=0,\sigma=1\) 时为 0 ✓;对 \(\sigma\) 求导 \(\sigma-1/\sigma=0\) ⇒ \(\sigma=1\) 是最小点 ✓。
数值验证(闭式 1.9319 vs Monte Carlo 1.9340)见 KL 概念块的代码。
目标 \(p=\frac12\mathcal{N}(-3,0.5^2)+\frac12\mathcal{N}(3,0.5^2)\)。用单个高斯 \(q=\mathcal{N}(\mu,\sigma^2)\) 分别最小化 \(\text{KL}(p\|q)\) 和 \(\text{KL}(q\|p)\)。先预测答案,再用 numpy 网格搜索验证。reverse KL 最优值为什么约等于 \(\log2\)?
提示
参考答案
预测:forward → 矩匹配:\(\mu=0\),\(\sigma^2=\text{Var}_p=0.25+9=9.25\),\(\sigma\approx3.04\)。reverse → 锁定一个峰:\(\mu=\pm3,\sigma=0.5\)。此时在 \(q\) 的支撑上 \(p\approx\frac12q\),所以 \(\text{KL}(q\|p)=\mathbb{E}_q[\log\frac{q}{q/2}]=\log2\approx0.693\)。
代码与输出见 forward vs reverse KL 概念块:网格搜索得到 forward \((\mu,\sigma)=(0.00,3.05)\)、reverse \((-3.00,0.50)\)、KL \(=0.693\)。
English takeaway: "Forward KL matches moments and smears mass between the modes; reverse KL picks one mode and pays exactly log 2 for ignoring the other half of the mass."
用 \(q=\mathcal{N}(0,s^2)\) 的样本以重要性采样估计 \(\mathbb{E}_{p}[x^2]\),\(p=\mathcal{N}(0,1)\)。(a) 写出估计量并证明无偏。(b) 求使估计量方差有限的 \(s\) 的范围。(c) 写模拟代码,比较不同 \(s\) 的经验标准差和 ESS。
提示
参考答案
(a) \(\hat\mu=\frac1N\sum w(x_i)x_i^2\),\(w=p/q\);\(\mathbb{E}_q[wx^2]=\int q\frac pq x^2=\mathbb{E}_p[x^2]=1\)。
(b) \(\frac{p(x)^2}{q(x)}=\frac{\frac1{2\pi}e^{-x^2}}{\frac1{\sqrt{2\pi}s}e^{-x^2/2s^2}}=\frac{s}{\sqrt{2\pi}}\exp\!\Big(-x^2\big(1-\tfrac1{2s^2}\big)\Big)\)。乘 \(x^4\) 后可积 ⇔ \(1-\frac{1}{2s^2}>0\) ⇔ \(s>\frac1{\sqrt2}\approx0.707\)。\(s\le0.707\) 时方差无穷大。(进一步,二阶矩 \(=\frac{s}{\sqrt{2\pi}}\int x^4e^{-ax^2}dx=\frac{s}{\sqrt{2\pi}}\cdot\frac{3\sqrt\pi}{4a^{5/2}}\),\(a=1-\frac1{2s^2}\);\(s=1\) 时 \(a=\frac12\),二阶矩 \(=3\),方差 \(=2\),与直接从 \(p\) 采样一致 ✓。)
(c) 代码与输出见 重要性采样 概念块。\(s=0.5\) 时估计标准差 ≈ 3.97(且理论上无穷),\(s=1.5\) 时只有 0.022——比 \(s=1\)(直接采样,0.045)还小,因为宽提议更接近最优 \(q^*\propto x^2p(x)\)。
用 numpy 实现 (a) 向量化的 k-means(不允许对样本写 Python 循环),处理空簇,多次重启选最小 inertia;(b) 基于 SVD 的 PCA,返回主方向、投影和解释方差比,并与协方差特征分解对比。
提示
Vt[:k]。参考答案
代码与输出见 PCA 概念块。验证:三簇数据恢复出的中心与真实中心误差 < 0.2;沿 \((1,2)/\sqrt5\) 拉长的数据第一主方向与真方向的 \(|\cos|>0.999\),并与 np.linalg.eigh(np.cov(Z.T)) 的最大特征向量一致(符号可能相反——特征向量符号不唯一,比较时取绝对值)。
追问:k-means 复杂度 \(O(nkdT)\);PCA 用 SVD 是 \(O(nd\min(n,d))\),大数据可用随机化 SVD。
抛硬币 10 次,9 次正面。(a) 求 \(p\) 的 MLE;(b) 用 Beta(2,2) 先验求 MAP;(c) 求后验均值;(d) 用 Fisher 信息给出 MLE 的近似标准误。
提示
参考答案
(a) \(\ell(p)=9\log p+\log(1-p)\),\(\ell'=9/p-1/(1-p)=0\) ⇒ \(\hat p=0.9\)。
(b) 后验 \(\propto p^{9}(1-p)\cdot p(1-p)=p^{10}(1-p)^2\),即 Beta(11,3),众数 \(\frac{10}{12}\approx0.833\) \(=\frac{k+1}{n+2}\)。
(c) 后验均值 \(\frac{11}{14}\approx0.786\)。
(d) \(I(p)=\frac{1}{p(1-p)}\)(单次),标准误 \(\approx\sqrt{\hat p(1-\hat p)/n}=\sqrt{0.09/10}\approx0.095\)。小样本下正态近似很粗糙(\(\hat p\pm2\text{SE}\) 会超过 1),这也是先验/Wilson 区间有用的原因。
代码验证(网格搜索 MLE / MAP)见 MLE 概念块。
推导 \(L(w)=\|Xw-y\|^2+\lambda\|w\|^2\) 的梯度和闭式解;说明为什么 \(\lambda>0\) 时一定可逆;给出 GD 收敛的最大步长。
提示
参考答案
\(\nabla L=2X^\top(Xw-y)+2\lambda w=0\) ⇒ \((X^\top X+\lambda I)w=X^\top y\) ⇒ \(\hat w=(X^\top X+\lambda I)^{-1}X^\top y\)。\(X^\top X\succeq0\),特征值 \(\sigma_i^2\ge0\);加 \(\lambda I\) 后特征值 \(\sigma_i^2+\lambda\ge\lambda>0\),正定 ⇒ 可逆。
Hessian \(H=2(X^\top X+\lambda I)\),\(L_{\text{smooth}}=2(\sigma_{\max}^2+\lambda)\),GD 收敛要求 \(\eta<2/L_{\text{smooth}}=1/(\sigma_{\max}^2+\lambda)\)。代码见 线性回归 概念块(闭式、lstsq、GD 三者一致)。
某病患病率 1%。检测敏感度 99%,假阳性率 5%。(a) 一次阳性后患病概率?(b) 两次独立阳性?(c) 一次阳性、一次阴性?
提示
参考答案
(a) \(\frac{0.0099}{0.0099+0.0495}=\frac16\approx16.7\%\)。(b) 赔率 \(\frac1{99}\times19.8^2=3.96\) ⇒ \(3.96/4.96\approx79.8\%\)。(c) 赔率 \(\frac1{99}\times19.8\times\frac{0.01}{0.95}\approx0.0021\) ⇒ 约 0.21%(一次阴性的证据很强,因为敏感度高)。
from fractions import Fraction as F
def posterior(prior, sens, fpr):
"""P(D | +) = P(+|D)P(D) / [P(+|D)P(D) + P(+|¬D)P(¬D)]"""
return sens * prior / (sens * prior + fpr * (1 - prior))
prior, sens, fpr = F(1, 100), F(99, 100), F(5, 100) # 患病率 1%,敏感度 99%,假阳性率 5%
p1 = posterior(prior, sens, fpr)
p2 = posterior(p1, sens, fpr) # 第二次独立阳性:把上一次的后验当先验
print("P(D|+) =", p1, "≈", round(float(p1), 4)) # 1/6 ≈ 0.1667
print("P(D|++) ≈", round(float(p2), 4)) # ≈ 0.7984
assert p1 == F(1, 6) and abs(float(p2) - 0.7984) < 1e-4
P(D|+) = 1/6 ≈ 0.1667
P(D|++) ≈ 0.7984
公平硬币,期望抛多少次第一次出现连续两个正面(HH)?HT 呢?为什么不一样?
提示
参考答案
HH:设 \(E_0\) 为从头开始的期望,\(E_1\) 为最后一次是 H 时还需的期望。
$$E_0=1+\tfrac12E_1+\tfrac12E_0,\qquad E_1=1+\tfrac12\cdot0+\tfrac12E_0.$$第一式得 \(E_0=2+E_1\),代入第二式:\(E_1=1+\frac12(2+E_1)\) ⇒ \(E_1=4\),\(E_0=6\)。
HT:\(E_0=1+\frac12E_1+\frac12E_0\),\(E_1=1+\frac12\cdot0+\frac12E_1\)(在 H 之后抛出 H 仍处于"最后一次是 H"的状态)⇒ \(E_1=2\),\(E_0=4\)。
为什么不同:HH 失败(抛出 T)会让你回到起点;HT 的失败(再抛出 H)仍保留了进展。也可以用"模式自重叠"解释:HH 与自身有重叠(后缀 H = 前缀 H),期望 \(=2^1+2^2=6\);HT 无自重叠,期望 \(=2^2=4\)(Conway 公式)。
import random
random.seed(0)
def tosses_until(pattern):
window, n = "", 0
while not window.endswith(pattern):
window = (window + random.choice("HT"))[-len(pattern):]
n += 1
return n
R = 200_000
e_hh = sum(tosses_until("HH") for _ in range(R)) / R
e_ht = sum(tosses_until("HT") for _ in range(R)) / R
print(f"E[HH] ≈ {e_hh:.3f} (theory 6), E[HT] ≈ {e_ht:.3f} (theory 4)")
assert abs(e_hh - 6) < 0.08 and abs(e_ht - 4) < 0.05
E[HH] ≈ 5.985 (theory 6), E[HT] ≈ 3.994 (theory 4)
在单位长度木棍上独立均匀随机选两个点折断成三段。三段能组成三角形的概率是多少?
提示
参考答案
设切点 \(u,v\sim U(0,1)\),不妨 \(u<v\)(占正方形的一半,面积 1/2)。三段:\(u,\ v-u,\ 1-v\)。条件:\(u<\frac12\)、\(v>\frac12\)、\(v-u<\frac12\)。在 \(u<v\) 的三角形中,这三个条件围成一个顶点为 \((0,\frac12),(\frac12,\frac12),(\frac12,1)\) 的小三角形,面积 \(\frac18\)。概率 \(=\frac{1/8}{1/2}=\frac14\)。
import numpy as np
rng = np.random.default_rng(0)
u = rng.random((1_000_000, 2))
a, b = u.min(1), u.max(1) # 两个切点排序
x, y, z = a, b - a, 1 - b # 三段长度
p = np.mean((x < .5) & (y < .5) & (z < .5)) # 三角形 ⇔ 每段都 < 1/2
print("P(triangle) ≈", p) # 理论 1/4
assert abs(p - 0.25) < 3e-3
P(triangle) ≈ 0.24969
English: "A triangle exists iff every piece is shorter than one half; in the unit square of cut points that region has area one quarter."
设 \(x\sim q\),\(r=p(x)/q(x)\)。(a) 证明 \(k3=(r-1)-\log r\) 是 \(\text{KL}(q\|p)\) 的无偏估计且逐样本非负。(b) 在什么情况下 \(\mathbb{E}_q[r]\ne1\),从而 k3 变成有偏?(c) 把 k3 当作 loss(\(q=\pi_\theta\),只对 \(\log\pi_\theta(x)\) 求导)时,期望梯度是什么?
提示
参考答案
(a) \(\mathbb{E}_q[r-1]=\sum_{x:q(x)>0}p(x)-1=0\)(当 \(q\) 覆盖 \(p\) 的支撑时),所以 \(\mathbb{E}[k3]=\mathbb{E}[-\log r]=\text{KL}(q\|p)\)。非负:函数 \(h(t)=t-1-\log t\) 满足 \(h(1)=0\),\(h'(t)=1-1/t\),在 \(t=1\) 取最小值 0,所以 \(h\ge0\)。
(b) 若 \(p\) 在某些 \(q=0\) 的地方有质量(\(q\) 不覆盖 \(p\)),\(\mathbb{E}_q[r]=\sum_{q>0}p<1\),k3 的期望比 KL 小 \(1-\sum_{q>0}p\)。例如采样时用了 top-p 截断,但 ratio 用的是未截断的概率。
(c) \(\nabla_\theta k3=\nabla r-\nabla\log r=-r\nabla\log\pi_\theta+\nabla\log\pi_\theta=(1-r)\nabla\log\pi_\theta\)。期望 \(\sum_x\pi_\theta(1-\frac{\pi_{\text{ref}}}{\pi_\theta})\nabla\log\pi_\theta=\underbrace{\sum\pi_\theta\nabla\log\pi_\theta}_{=0}-\sum\pi_{\text{ref}}\nabla\log\pi_\theta=\nabla_\theta\text{KL}(\pi_{\text{ref}}\|\pi_\theta)\):forward KL 的梯度,而不是 reverse。数值验证见 k1/k2/k3 概念块。
证明:若 \(g_k\overset{iid}\sim\text{Gumbel}(0,1)\),则 \(P(\arg\max_k(z_k+g_k)=i)=\frac{e^{z_i}}{\sum_je^{z_j}}\)。
提示
参考答案
Gumbel 采样 \(g=-\log(-\log U)\),所以 \(e^{-g}=-\log U\sim\text{Exp}(1)\)。于是 \(E_k=e^{-z_k}e^{-g_k}\) 是 Exp(1) 乘以 \(e^{-z_k}\),即 \(E_k\sim\text{Exp}(\lambda_k)\),\(\lambda_k=e^{z_k}\)。
\(\arg\max_k(z_k+g_k)=\arg\min_kE_k\)(\(e^{-t}\) 单调递减)。对独立指数变量:
$$P(E_i=\min)=\int_0^\infty\lambda_ie^{-\lambda_it}\prod_{j\ne i}e^{-\lambda_jt}\,dt=\lambda_i\int_0^\infty e^{-(\sum_j\lambda_j)t}dt=\frac{\lambda_i}{\sum_j\lambda_j}=\frac{e^{z_i}}{\sum_je^{z_j}}.\quad\blacksquare$$数值验证见 Gumbel-max 概念块(经验频率与 softmax 误差 < 0.003)。
求解 \(\min_w\frac12(w-a)^2+\lambda|w|\)(\(\lambda>0\)),并与 \(\min_w\frac12(w-a)^2+\frac\lambda2w^2\) 对比,解释 L1 为什么产生稀疏解。
提示
参考答案
\(w>0\):导数 \(w-a+\lambda=0\) ⇒ \(w=a-\lambda\),需 \(a>\lambda\)。\(w<0\):\(w=a+\lambda\),需 \(a<-\lambda\)。\(w=0\) 是最优 ⇔ \(0\in -a+\lambda[-1,1]\) ⇔ \(|a|\le\lambda\)。合起来:
$$w^*=\text{sign}(a)\max(|a|-\lambda,\,0)\quad\text{(soft-thresholding)}.$$L2 版本:\(w-a+\lambda w=0\) ⇒ \(w^*=\frac{a}{1+\lambda}\),除非 \(a=0\) 否则永不为 0。
解释:L1 的"拉力"(次梯度)在 0 附近恒为 \(\lambda\),只要数据项的拉力 \(|a|\) 不足以克服它,参数就被钉在 0;L2 的拉力 \(\lambda w\) 在 0 附近趋于 0,只能缩小。这也是 Lasso 的坐标下降 / ISTA(proximal gradient)每步做 soft-thresholding 的原因。
\(f(x)=\frac12x^\top Ax\),\(A=\text{diag}(1,100)\)。(a) GD 收敛的最大固定步长是多少?(b) \(\eta=1/L\) 时 200 步后误差缩小多少?(c) 最优固定步长和对应的收敛速率?(d) 说明 heavy-ball 动量的改进。
提示
参考答案
(a) 需要 \(|1-100\eta|<1\) 且 \(|1-\eta|<1\) ⇒ \(\eta<0.02=2/L\)。
(b) \(\eta=0.01\):大特征方向一步归零;小特征方向每步乘 \(0.99\),200 步后 \(0.99^{200}\approx0.134\)。
(c) 最优 \(\eta=\frac{2}{L+\mu}=\frac{2}{101}\),两个方向的收缩因子绝对值相等 \(=\frac{\kappa-1}{\kappa+1}=\frac{99}{101}\approx0.980\)。
(d) heavy-ball 最优参数下速率 \(\approx\frac{\sqrt\kappa-1}{\sqrt\kappa+1}=\frac{9}{11}\approx0.818\);达到 \(10^{-6}\) 精度需要约 \(\ln10^6/\ln(11/9)\approx69\) 步,而 GD(最优步长)约需 \(\ln10^6/\ln(101/99)\approx691\) 步。代码验证见 GD 概念块。
§ · CHEAT SHEET一页速查
面试前一晚看这一页。每一行都应该能在 30 秒内口头展开。
线性代数
| 内容 | 公式 / 结论 |
|---|---|
| matmul FLOPs | \((m\times k)(k\times n)\):\(2mkn\);前向 2N/token,前向+反向 6N/token |
| 秩 | \(\text{rank}(AB)\le\min(\text{rank}A,\text{rank}B)\);rank + nullity = n |
| SVD / Eckart–Young | \(M=U\Sigma V^\top\);\(\|M-M_k\|_F=\sqrt{\sum_{i>k}\sigma_i^2}\),\(\|M-M_k\|_2=\sigma_{k+1}\) |
| LoRA | \(W_0+\frac\alpha rBA\),\(B=0\) 初始化;参数 \(r(d+k)\) |
| 范数 | \(\|A\|_F^2=\sum\sigma_i^2=\text{tr}(A^\top A)\);\(\|A\|_2=\sigma_{\max}\);\(\kappa=\sigma_{\max}/\sigma_{\min}\);\(\kappa(X^\top X)=\kappa(X)^2\) |
| 矩阵求导 | \(\nabla x^\top Ax=(A+A^\top)x\);\(\nabla\|Ax-b\|^2=2A^\top(Ax-b)\);\(\partial\text{tr}(XB)/\partial X=B^\top\);\(\partial\log\det X/\partial X=X^{-\top}\) |
| 线性层 | \(Y=XW^\top\):\(\partial L/\partial W=G^\top X\),\(\partial L/\partial X=GW\) |
概率统计
| 内容 | 公式 / 结论 |
|---|---|
| Bayes 检测 | 1% / 99% / 5% ⇒ \(P(D\mid+)=1/6\);两次阳性 ≈ 0.80;赔率 × 似然比 |
| 方差 | \(\text{Var}(aX+bY)=a^2\text{Var}X+b^2\text{Var}Y+2ab\text{Cov}\);\(\text{Var}\bar X=\sigma^2/n\) |
| 全方差 | \(\text{Var}X=\mathbb{E}[\text{Var}(X\mid Y)]+\text{Var}(\mathbb{E}[X\mid Y])\) |
| 准确率标准误 | \(\sqrt{p(1-p)/n}\);500 题 70% ⇒ ±2% |
| MLE | Bernoulli \(k/n\);Gaussian \(\bar x\)、\(\frac1n\sum(x-\bar x)^2\)(有偏,\(\times\frac{n}{n-1}\) 修正);MSE = 高斯 NLL;CE = 类别 NLL;MLE ⇔ min forward KL |
| MAP | L2 ⇔ 高斯先验(\(\lambda=\sigma^2/\tau^2\));L1 ⇔ Laplace;Beta(2,2) ⇒ \(\frac{k+1}{n+2}\) |
| Importance sampling | \(\mathbb{E}_p f=\mathbb{E}_q[\frac pqf]\);方差 \(\int p^2f^2/q-\mu^2\);ESS \(=(\sum w)^2/\sum w^2\);q 要比 p 宽;PPO ratio = IS 权重 |
| 拒绝采样 | 接受概率 \(p/(Mq)\),接受率 \(1/M\) |
| Gumbel-max | \(\arg\max(z+g)\sim\text{softmax}(z)\),\(g=-\log(-\log U)\) |
| 重参数化 | \(z=\mu+\sigma\varepsilon\);低方差但需可微、连续;离散 token → score function |
| Score function | \(\nabla\mathbb{E}_{p_\theta}f=\mathbb{E}[f\nabla\log p_\theta]\) |
信息论
| 内容 | 公式 / 结论 |
|---|---|
| 熵 / 交叉熵 | \(H(p,q)=H(p)+\text{KL}(p\|q)\);均匀分布熵 \(\log K\);32k 词表初始 loss ≈ 10.4 nats |
| KL ≥ 0 | Jensen:\(\mathbb{E}_p\log\frac qp\le\log\mathbb{E}_p\frac qp\le0\);或 \(\log t\le t-1\) |
| 高斯 KL | \(\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12\);VAE:\(\frac12(\mu^2+\sigma^2-1-\log\sigma^2)\) |
| Forward vs reverse | \(\text{KL}(p\|q)\):mode-covering(SFT、MLE、标准蒸馏);\(\text{KL}(q\|p)\):mode-seeking(RLHF 惩罚、VI)。"期望在谁下面,谁是裁判" |
| k1/k2/k3 | \(x\sim q\),\(r=p/q\):\(-\log r\)(无偏、高方差、可负);\(\frac12(\log r)^2\)(有偏、低方差);\((r-1)-\log r\)(无偏、非负、低方差,GRPO) |
| 作为 loss 的梯度 | k1:期望 0;k2:\(\nabla\text{KL}(\pi_\theta\|\pi_{\text{ref}})\);k3:\(\nabla\text{KL}(\pi_{\text{ref}}\|\pi_\theta)\)(一阶近似) |
| PPL / BPB | PPL \(=e^{\text{CE}}\);BPB \(=\frac{\text{CE}_{\text{nats/tok}}}{\ln2}\cdot\frac{\text{tokens}}{\text{bytes}}\),与 tokenizer 无关 |
优化
| 内容 | 公式 / 结论 |
|---|---|
| GD 步长 | \(\eta\le1/L\) 保证下降;二次函数 \(\eta>2/L\) 发散;速率 \(1-1/\kappa\);momentum \(\to\frac{\sqrt\kappa-1}{\sqrt\kappa+1}\) |
| Adam | \(m=\beta_1m+(1-\beta_1)g\);\(v=\beta_2v+(1-\beta_2)g^2\);\(\hat m=m/(1-\beta_1^t)\);\(\hat v=v/(1-\beta_2^t)\);\(\theta\mathrel{-}=\eta\hat m/(\sqrt{\hat v}+\epsilon)\) |
| bias correction | \(\mathbb{E}m_t=(1-\beta_1^t)\mathbb{E}g\);第一步 = \(\eta\,\text{sign}(g)\) |
| AdamW | \(\theta\mathrel{-}=\eta\lambda\theta\) 与自适应更新解耦;Adam+L2 会被 \(\sqrt v\) 缩放;norm/bias 不衰减;LLM:\(\beta_2=0.95\),wd=0.1,clip=1.0 |
| 调度 | warmup(二阶矩不准、曲率大)→ cosine 到 10% / linear / WSD(常数 + 末段 10–20% 衰减,可分叉) |
| Batch | SGD 线性缩放、Adam 约 √ 缩放;critical batch \(\approx\text{tr}\Sigma/\|G\|^2\),随训练增大 |
| 二阶 | Newton \(H^{-1}g\);natural gradient \(F^{-1}g\)(KL 信赖域);K-FAC \(G^{-1}\nabla WA^{-1}\);Shampoo \(L^{-1/4}GR^{-1/4}\) |
| 新优化器 | Lion:sign 更新,lr 小 3–10×;Muon:2D 权重的动量做 Newton–Schulz 正交化 \(\approx UV^\top\),其他参数 AdamW |
经典 ML
| 内容 | 公式 / 结论 |
|---|---|
| 偏差–方差 | \(\text{MSE}=\text{bias}^2+\text{var}+\sigma^2\);两次"加减均值";double descent |
| L1 vs L2 | soft-threshold \(\text{sign}(a)\max(|a|-\lambda,0)\) vs \(a/(1+\lambda)\) |
| 线性回归 | \((X^\top X+\lambda I)^{-1}X^\top y\);投影;用 solve/lstsq |
| 逻辑回归 | \(\nabla=\frac1nX^\top(\sigma(Xw)-y)\);loss \(=\log(1+e^z)-yz\);Hessian \(X^\top SX\) |
| 指标 | P = TP/(TP+FP);R = TP/(TP+FN);AUC = \(P(s_+>s_-)\);稀有正例用 PR-AUC;ECE;temperature scaling 不改 argmax |
| PCA | 中心化 → SVD → Vt[:k];方差 \(\sigma_i^2/(n-1)\) |
| k-means / EM | 交替分配/更新,单调收敛到局部最优;EM = ELBO 上的坐标上升 |
| 概率谜题 | HH 期望 6,HT 期望 4;木棍三角形 1/4;随机排列不动点期望 1 |
§ · TOP QUESTIONS高频面试题清单
按出现频率排序(基于常见 RS/ML 面试题型的经验归纳)。每题链接到能回答它的概念块。练习方法:读题 → 不看答案用英文讲 1 分钟 → 点链接对照。
- Why is KL divergence non-negative? Prove it. → KL
- What's the difference between forward and reverse KL? Which one does SFT minimize, and which does RLHF use? → Forward vs reverse KL
- Write out the Adam update. Why is bias correction needed? Derive it. → Adam
- What's the difference between Adam with L2 regularization and AdamW? → AdamW
- Why do we need learning-rate warmup? → LR schedules
- Show that cross-entropy loss is maximum likelihood. Why MSE for regression? → MLE
- How does L2 regularization relate to a Gaussian prior? Why does L1 give sparsity? → MAP, Regularization
- Explain importance sampling. When does it fail? How does it relate to PPO? → Importance sampling
- How do you estimate KL from samples? Why does GRPO use the k3 estimator? → k1/k2/k3
- Derive the gradient of logistic regression. → Logistic regression
- Derive the bias–variance decomposition. How does double descent fit in? → Bias–variance
- A test is 99% sensitive with 5% false positives; prevalence 1%. P(disease | positive)? → Bayes
- Expected number of coin flips to get two heads in a row? → 练习 6.11
- What is perplexity? Why can't you compare it across tokenizers? → Perplexity
- Explain SVD and why LoRA works. → SVD & LoRA
- What is the reparameterization trick, and why can't we use it for LLM token sampling? → Reparameterization
- How should the learning rate change when you increase the batch size? What's the critical batch size? → Batch size
- Gradient of xᵀAx / ‖Ax − b‖² / a linear layer's weight? → Matrix calculus
- What is the condition number and why does it matter for optimization? → Norms & conditioning, GD
- When would you use PR-AUC instead of ROC-AUC? What is calibration? → Metrics
- Why does momentum help? → Momentum
- Explain natural gradient. How does it relate to TRPO? → Second-order methods
- What is Muon and how does it differ from Adam? → New optimizers
- Implement PCA / k-means in numpy. → PCA, k-means
- Why is gradient clipping by norm used in LLM training? → Clipping
- Explain the Gumbel-max trick. → Gumbel-max
- How many FLOPs does a matrix multiply take? Where does 6ND come from? → Matmul FLOPs
- What is mutual information? How does InfoNCE relate to it? → MI
§ · RECALL自测卡片
先自己说出答案(最好用英文出声),再点开对照并打分。