End-to-end knowledge distillation demo with a mock teacher (large MLP) and student (small MLP) on a synthetic 2D 3-class dataset.
train_knowledge_distillation() in train_kd.py follows Section 2 of Distilling the Knowledge in a Neural Network, with the paper's notation (v: teacher logits, z: student logits):
- Soft loss:
T^2 * CwhereC = -sum(p * log q),p = softmax(v / T),q = softmax(z / T)(Eq. 1). Teacher is frozen and both useT = 3.0. TheT^2factor compensates for the1/T^2shrinking of soft-target gradients (Eqs. 2–4). - Hard loss: standard cross-entropy of
zatT = 1against true labels. - Combined loss:
(1 - alpha) * soft + alpha * hardwithalpha = 0.1.
$ uv sync
$ uv run python train_kd.pymake_synthetic_data() generates 3 Gaussian blobs in 2D, one per class:
X:(3000, 2),torch.float32— 2D coordinates, centers at[-2, 0],[2, 0],[0, 2.5]with std 1.y:(3000,),torch.int64— class labels 0/1/2, 1000 samples each.
- Geoffrey Hinton, Oriol Vinyals, Jeff Dean. Distilling the Knowledge in a Neural Network. arXiv:1503.02531, 2015. arXiv

