234. 忽略 padding 的 token 级 KL 蒸馏
在知识蒸馏中,较小的 student 模型学习匹配 teacher 的 next-token 分布。由于 batch 会进行 padding,padding 位置不能计入计算,否则短序列会被稀释。
编写 distill_kl(student, teacher, mask, T),其中 student 和 teacher 的 shape 为 (b, s, V),mask 的 shape 为 (b, s),真实 token 为 1,padding 为 0,T > 0 为温度。
- 在最后一个维度上计算 p = softmax(teacher / T) 和 log q = log_softmax(student / T)。
- 每个 token 的 loss = T ** 2 * sum_v p * (log p - log q)。遵循 0 * log 0 = 0 的约定。
- 返回仅针对真实 token 的每个 token loss 的平均值,结果为 float。如果 mask 中没有真实 token,则返回 0.0。
def distill_kl(student, teacher, mask, T)示例 1
when student equals teacher, the loss is 0.0.
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
提示 1
This is a KL divergence per token, scaled by T squared, then averaged only over positions where the mask is 1.
提示 2
Divide both logit arrays by T, take stable log-softmax over the vocab axis, compute sum of p * (log p - log q) per token, multiply by T ** 2, and take the mask-weighted average.
提示 3
Get log p from a stable log-softmax (subtract the max, then subtract the log of the summed exps) and set p = np.exp(logp), so 0 * log 0 never shows up as nan. Return 0.0 early when mask.sum() == 0.
常见错误
- 有 bug 的版本对所有位置使用了 .mean(),这导致 padding 在分子上增加了零,但在分母中仍被计入,从而缩小了带有 padding 的 batch 的 loss。
理解思路
在蒸馏中,student 学习的是复制 teacher 在整个 vocabulary 上的概率分布,而不仅仅是其最高概率的答案。两者之间的差距通过每个 token 的 KL 散度来衡量。Padding 位置不是真实的 token,因此必须在求和与计数中同时排除。Worked example with T = 1: 在一个真实 token 处,teacher 给出的 p = [0.5, 0.5],student 给出的 q = [0.8, 0.2]。KL = 0.5 * ln(0.5 / 0.8) + 0.5 * ln(0.5 / 0.2) = -0.2350 + 0.4581 = 0.2231。如果第二个位置是 padding (mask 为 0),则结果是 0.2231 / 1,而不是对 2 取平均。
p = softmax(teacher / T), log q = log_softmax(student / T), per-token loss = T^2 * sum of p * (log p - log q), with 0 * log 0 = 0; final loss = sum over masked-in tokens / number of real tokens, or 0 if there are none
T^2 因子使梯度大小在不同温度下保持稳定。该技术用于将大型 LLM 压缩为更小的模型。