Token-level distillation KL that ignores padding

MediumLosses

In knowledge distillation a small student model learns to match a teacher's next-token distribution. Batches are padded, and padded positions must not count, or short sequences get diluted.

Write distill_kl(student, teacher, mask, T) where student and teacher are logits of shape (b, s, V), mask is (b, s) with 1 for real tokens and 0 for padding, and T > 0 is a temperature.
- p = softmax(teacher / T) and log q = log_softmax(student / T) over the last axis.
- Per-token loss = T ** 2 * sum_v p * (log p - log q). Use the convention 0 * log 0 = 0.
- Return the mean of the per-token loss over real tokens only, as a float. If the mask has no real tokens, return 0.0.

Signaturedef distill_kl(student, teacher, mask, T)

Example

when student equals teacher, the loss is 0.0.

Understand the idea

In distillation the student learns to copy the teacher's whole probability spread over the vocabulary, not just its top answer. The gap is measured with KL divergence at each token. Padding positions are not real tokens, so they must be left out of both the sum and the count. Worked example with T = 1: at one real token the teacher gives p = [0.5, 0.5] and the 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. If the second position is padding (mask 0), the answer is 0.2231 / 1, not an average over 2. Rule: 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. The T^2 factor keeps gradient size steady across temperatures. Used to compress large LLMs into smaller ones.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: identical is zerodistill_kl(_S, _S, _m, 2.0)
  • Sample 2: padded batch T=1distill_kl(_S, _Tl, _m, 1.0)
  • Test 3: padded batch T=2distill_kl(_S, _Tl, _m, 2.0)
  • Test 4: all paddingdistill_kl(_S, _Tl, np.zeros((2, 4)), 1.0)
  • Test 5: no paddingdistill_kl(_S, _Tl, np.ones((2, 4)), 3.0)