Skip to content
Skip to lesson
Back to Topics
LearnTraining, Fine-Tuning & AlignmentKnowledge Distillation for LLMs
HardFine-Tuning & Training14 min read

Knowledge Distillation for LLMs

Distill a 70B teacher into a fast 7B student using softened token probabilities, filtered reasoning traces, and student-sampled supervision, while avoiding tokenizer mismatches and silent tail errors.

On this page

A 70B reasoning model solves 94% of your technical QA benchmarks, but takes 180 milliseconds per response and blows through your serving budget. A 7B model answers in 42 milliseconds at less than half the cost, yet fine-tuning it on ground-truth answer strings alone leaves a sharp accuracy gap on tricky edge cases.

closes that gap by training a compact student directly from the behavior of a stronger teacher. With white-box access, the student matches softened next- probabilities or intermediate hidden states. With black-box text-only access, it fine-tunes on verified teacher answers and reasoning traces.

Soft labels and dark knowledge

Hinton et al. showed that a teacher's full probability distribution carries far more supervision than a one-hot target.[1] Consider a four-token vocabulary for a cache-retention prompt: 7d, 3d, 30d, and never. A hard label puts 1.00 on 7d and 0.00 everywhere else, telling the student which token wins while erasing how close the runners-up were.

The teacher's non-target probabilities preserve that similarity structure. Giving 3d far more mass than 30d or never teaches the student that shorter TTL windows lie much closer to 7d than disabling caching altogether. Hinton et al. called this relative structure dark knowledge.

Three aligned probability distributions compare a hard one-hot target with teacher softmax probabilities at T=1 and T=4 from logits [4.0, 2.0, 1.0, 0.7] over 7d, 3d, 30d, and never. Raising temperature to T=4 preserves the exact ranking while narrowing the top gap (7d minus 3d) from 1.000 to 0.708 to 0.156 and lifting informative probability mass onto secondary candidates.
Raising temperature flattens the teacher's peak while preserving the rank order across alternatives (7d > 3d > 30d > never), making near-miss probabilities visible to the student.

Dividing raw by a T>1T > 1 before softmax lifts those runner-up probabilities without altering rank order. When ground-truth labels are also present, training blends soft distillation loss with standard T=1T = 1 task cross-entropy:

L=α⋅Ldistill+(1−α)⋅Ltask\mathcal{L} = \alpha \cdot \mathcal{L}_{\text{distill}} + (1 - \alpha) \cdot \mathcal{L}_{\text{task}}

At scale, next-token distillation pays off sharply. In the Gemma 2 technical report, a 2B student trained for 500B tokens via logit distillation from a 7B teacher reached 67.7 on their three-benchmark average, compared with 60.3 trained from scratch on the same token budget.[2]

Logit distillation and temperature scaling

In white-box causal language models, logit distillation minimizes between the frozen teacher's and student's softened next-token distributions at every supervised prefix position:

qi=exp⁡(zt,i/T)∑jexp⁡(zt,j/T),pi=exp⁡(zs,i/T)∑jexp⁡(zs,j/T),LKL=T2∑iqilog⁡qipiq_i = \frac{\exp(z_{t,i} / T)}{\sum_j \exp(z_{t,j} / T)}, \qquad p_i = \frac{\exp(z_{s,i} / T)}{\sum_j \exp(z_{s,j} / T)}, \qquad \mathcal{L}_{\text{KL}} = T^2 \sum_i q_i \log \frac{q_i}{p_i}

Why multiply by T2T^2? Differentiating the unscaled soft cross-entropy −∑iqilog⁡pi-\sum_i q_i \log p_i with respect to student logit zs,iz_{s,i} yields 1T(pi−qi)\frac{1}{T}(p_i - q_i). Because large TT also shrinks (pi−qi)(p_i - q_i) roughly as 1/T1/T, the unscaled gradient decays like 1/T21/T^2, drowning out the distillation term relative to the T=1T = 1 hard loss.[1] Multiplying by T2T^2 restores the gradient to T(pi−qi)T(p_i - q_i), which converges to centered-logit MSE matching as T→∞T \to \infty.

Verify both temperature softening and T2T^2 gradient preservation directly in PyTorch:

temperature-gradient-check.py
import torch
import torch.nn.functional as F

teacher = torch.tensor([4.0, 2.0, 1.0, 0.7], dtype=torch.float64)
base_student = torch.tensor([1.0, 0.4, 0.1, -0.2], dtype=torch.float64)
high_temp_limit = ((base_student - base_student.mean()) - (teacher - teacher.mean())) / len(teacher)

for T in (1.0, 4.0, 40.0, 400.0):
    student = base_student.clone().requires_grad_()
    q_log = F.log_softmax(teacher / T, dim=0)
    p_log = F.log_softmax(student / T, dim=0)
    loss = F.kl_div(p_log, q_log, log_target=True, reduction="sum")
    (raw_grad,) = torch.autograd.grad(loss, student)
    scaled_grad = (T ** 2) * raw_grad
    gap = (scaled_grad - high_temp_limit).norm()
    top_gap = float(q_log.exp()[0] - q_log.exp()[1])
    print(f"T={T:5g} | top_gap={top_gap:.3f} | raw_norm={raw_grad.norm():.6f} | scaled_norm={scaled_grad.norm():.6f} | dist_to_limit={gap:.6f}")
Temperature softening and gradient check
T=    1 | top_gap=0.708 | raw_norm=0.434065 | scaled_norm=0.434065 | dist_to_limit=0.156800
T=    4 | top_gap=0.156 | raw_norm=0.030553 | scaled_norm=0.488844 | dist_to_limit=0.080567
T=   40 | top_gap=0.013 | raw_norm=0.000272 | scaled_norm=0.435812 | dist_to_limit=0.008958
T=  400 | top_gap=0.001 | raw_norm=0.000003 | scaled_norm=0.429383 | dist_to_limit=0.000901

Causal alignment and vocabulary identity

Two silent alignment bugs ruin autoregressive logit distillation:

  1. One-step label shift: Logits at prefix position tt predict the hard token at t+1t + 1. Shift hard labels left (labels[1:]), while keeping teacher and student logits aligned at the same position tt (logits[:-1]).
  2. Exact token-to-ID mapping: Equal vocab_size is insufficient. If token ID 17 means return in the teacher and <pad> in the student, KL training runs without errors while driving the student toward gibberish.
Four prefix positions t0 through t3 align teacher and student 4-logit vectors vertically for KL distillation over shared token IDs (0=7d, 1=3d, 2=30d, 3=never). Below, original labels [0, 0, 1, -100] shift left by one step to pair t0 with 0 (7d), t1 with 1 (3d), and t2 with -100 (masked out of both KL and cross-entropy loss), while t3 has no next label.
Teacher and student logits align at the same prefix position t, while hard labels shift left by one step. Positions whose next label is -100 are masked out of both the KL and cross-entropy losses.

Forward versus reverse KL

Because KL divergence is asymmetric, choosing which distribution sits on the left dictates how a capacity-limited student allocates probability mass:

DKL(Pteacher∥Pstudent)=∑xPteacher(x)log⁡Pteacher(x)Pstudent(x)D_{\mathrm{KL}}(P_{\text{teacher}} \parallel P_{\text{student}}) = \sum_{x} P_{\text{teacher}}(x) \log \frac{P_{\text{teacher}}(x)}{P_{\text{student}}(x)} DKL(Pstudent∥Pteacher)=∑xPstudent(x)log⁡Pstudent(x)Pteacher(x)D_{\mathrm{KL}}(P_{\text{student}} \parallel P_{\text{teacher}}) = \sum_{x} P_{\text{student}}(x) \log \frac{P_{\text{student}}(x)}{P_{\text{teacher}}(x)}
  • Forward KL (mode-covering): Putting Ps(x)→0P_s(x) \to 0 anywhere Pt(x)>0P_t(x) > 0 drives the penalty to +∞+\infty. A smaller student stretches mass across all teacher modes, sometimes spilling probability into low-quality valleys between them.
  • Reverse KL (mode-seeking): Putting Ps(x)>0P_s(x) > 0 where Pt(x)→0P_t(x) \to 0 blows up the loss, whereas dropping an entire teacher mode pays only a finite cost (covering one of two equal 0.5 modes gives log⁡2≈0.693\log 2 \approx 0.693). The student concentrates sharply on high-probability teacher modes, boosting precision at the cost of diversity.

Neither direction wins everywhere. MiniLLM optimizes sequence-level reverse KL via policy gradients with teacher-mixed sampling and length normalization to prevent repetition collapse.[3] Generalized Knowledge Distillation (GKD) decouples divergence from sampling and finds generalized Jensen-Shannon divergence beats both KL directions on smaller translation students, while forward KL wins its headline GSM8K run.[4]

By the chain rule of KL divergence, a full-sequence KL decomposes into next-token KL terms weighted by prefixes drawn from the left distribution. Watch both the chain-rule identity and the asymmetry on tail leaks:

Two scenarios compare teacher probabilities (0.58, 0.40, 0.02) against student distributions for 7d, 3d, and never on a shared 0 to 0.60 axis. In Scenario A (student never = 0.10, +0.08 extra mass), forward KL is 0.051 and reverse KL is 0.084. In Scenario B (student never = 0.25, +0.23 extra mass), forward KL climbs to 0.218 while reverse KL jumps to 0.436, roughly twice as steep.
As the student shifts mass onto the teacher's low-probability token (never), reverse KL climbs roughly twice as fast as forward KL (0.436 vs 0.218).
kl-direction-and-sequence-chain.py
import math

def kl(left: list[float], right: list[float]) -> float:
    total = 0.0
    for p, q in zip(left, right):
        if p == 0.0:
            continue
        if q == 0.0:
            return math.inf
        total += p * math.log(p / q)
    return total

# 1. Tail leak asymmetry on (7d, 3d, never)
teacher = [0.58, 0.40, 0.02]
for name, student in [("mild_leak", [0.54, 0.36, 0.10]), ("heavy_leak", [0.40, 0.35, 0.25])]:
    print(f"{name:10s} | forward KL={kl(teacher, student):.3f} | reverse KL={kl(student, teacher):.3f}")
print(f"drop mode  | forward KL={kl([0.5, 0.5], [1.0, 0.0])}   | reverse KL={kl([1.0, 0.0], [0.5, 0.5]):.3f}")

# 2. Sequence KL chain rule weights prefixes by the left distribution
t1, s1 = [0.8, 0.2], [0.5, 0.5]
t2, s2 = [[0.9, 0.1], [0.2, 0.8]], [[0.5, 0.5], [0.4, 0.6]]
t_joint = [t1[i] * t2[i][j] for i in range(2) for j in range(2)]
s_joint = [s1[i] * s2[i][j] for i in range(2) for j in range(2)]
fwd_chain = kl(t1, s1) + sum(t1[i] * kl(t2[i], s2[i]) for i in range(2))
rev_chain = kl(s1, t1) + sum(s1[i] * kl(s2[i], t2[i]) for i in range(2))
print(f"seq forward: joint={kl(t_joint, s_joint):.6f} == teacher-weighted={fwd_chain:.6f}")
print(f"seq reverse: joint={kl(s_joint, t_joint):.6f} == student-weighted={rev_chain:.6f}")
Output
mild_leak  | forward KL=0.051 | reverse KL=0.084
heavy_leak | forward KL=0.218 | reverse KL=0.436
drop mode  | forward KL=inf   | reverse KL=0.693
seq forward: joint=0.505499 == teacher-weighted=0.505499
seq reverse: joint=0.530881 == student-weighted=0.530881

Response distillation and synthetic reasoning traces

When the teacher is behind an API or uses a different tokenizer, response distillation (sequence-level KD) fine-tunes the student on verified (prompt, response) completions generated by the teacher. It decouples teacher inference from student GPU memory, works across model families, and transfers multi-step reasoning traces that far outpace short final-answer labels.

RecipeTeacher signalKey takeaway
Alpaca 7B[5]52K Self-Instruct pairsPopularized synthetic SFT distillation (non-commercial license)
Orca 13B[6]Step-by-step explanation tracesRich rationales outperform terse answer imitation
phi-1.5[7]Synthetic textbook prose + filtered codeHigh-signal synthetic corpora rival much larger web datasets
Distilling Step-by-Step[8]Rationales + task labelsMulti-task supervision cuts labeled data requirements
DeepSeek-R1-Distill[9]~800K curated reasoning + general tracesFine-tuned Qwen/Llama students (32B Qwen hit 72.6% AIME 2024 pass@1 and 94.3% MATH-500)

Standard SFT treats every teacher token as ground truth, so unfiltered errors become training targets. Use a Seed-Expand-Filter pipeline: author 100 to 500 seed prompts, split seed families before expansion so paraphrases never cross train/eval boundaries, deduplicate prompts before paying for teacher generation, and filter outputs with programmatic verifiers (unit tests, math checkers, schema checks):

build-clean-distillation-set.py
def normalize(text: str) -> str:
    return " ".join(text.lower().replace("?", "").split())

held_out_eval = {
    normalize("Explain how FlashAttention tiles SRAM"),
    normalize("Derive the softmax Jacobian"),
}

candidates = [
    ("What is 17 * 24?", "408", "408"),
    ("  what is 17 * 24?  ", "408", "408"),
    ("What is 2**10 - 24?", "1024", "1000"),
    ("Explain how FlashAttention tiles SRAM?", "Tiles Q, K, V...", "Tiles Q, K, V..."),
]

seen, kept, dropped = set(), [], []
for prompt, teacher_out, expected in candidates:
Output
kept training rows: [{'prompt': 'What is 17 * 24?', 'response': '408'}]
filtered out:       [('what is 17 * 24?', 'duplicate'), ('What is 2**10 - 24?', 'wrong_teacher_output'), ('Explain how FlashAttention tiles SRAM?', 'eval_contamination')]

Feature alignment and student-sampled supervision

Feature distillation

With white-box access, feature distillation aligns selected student hidden states to corresponding detached teacher layers using a learned linear projection glg_l that bridges hidden-dimension differences:

Lfeature=∑l∥fm(l)teacher−gl ⁣(flstudent)∥2\mathcal{L}_{\text{feature}} = \sum_l \left\| f_{m(l)}^{\text{teacher}} - g_l\!\left(f_l^{\text{student}}\right) \right\|^2

Here m(l)m(l) pairs student layer ll with a teacher layer (depths need not match), and padding tokens are masked before averaging. Because layer pairing and activation storage add real complexity, benchmark feature matching against plain logit KD on held-out tasks before adopting it.

Closing exposure bias with student-generated prefixes

Training strictly on fixed teacher completions suffers from exposure bias: at inference time the student conditions on its own earlier tokens, so a single off-track token shifts it into prefixes absent from the offline dataset.

fixes this by sampling live completions from the student and scoring those exact student-generated prefixes with the teacher. In GKD, a mixing fraction λ\lambda blends fixed teacher prefixes with live student generations, and either forward KL, reverse KL, or generalized Jensen-Shannon divergence applies on top.[4] Gemma 2's post-training similarly combines synthetic teacher responses with distillation on the student's own distribution.[2] Remember that the sampling source (fixed dataset vs live student samples) is orthogonal to the divergence (forward vs reverse KL).

A branching prefix tree starts from the shared prompt "How long is this disabled key restorable? Answer:". The teacher trajectory visits "...7" and "...7 days". Live student sampling visits the shared prefix "...7" but branches onto "...30" and "...30 days", creating 2 new teacher-scored prefixes and 4 distinct scored prefixes in total.
When the student branches onto tokens absent from fixed teacher data, student-sampled collection scores those visited prefixes directly with the teacher.
MethodTeacher signalMain advantageMain constraint
Response KDVerified text tracesTokenizer-independent; works with API teachersUnfiltered teacher errors become SFT targets
Logit KDSoftened token probabilitiesTransfers full runner-up rankingRequires identical token-to-ID vocabulary
Feature KDIntermediate hidden statesSupervises internal representationsExtra layer mapping, projections, and memory
Student-sampled KD (OPD)Teacher logits on student prefixesCloses exposure bias directlyRequires online student sampling + teacher scoring

Production trainers such as Hugging Face TRL's DistillationTrainer and experimental GKDTrainer implement live student sampling and chunked full-vocabulary generalized Jensen-Shannon losses to avoid materializing giant [batch, seq, vocab] tensors (note that chunked trainers reading lm_head.weight directly need modules_to_save=["lm_head"] rather than LoRA on lm_head).[10][11]

Practical PyTorch training loop and logit caching

A bug-free PyTorch logit KD loop requires three invariants:

  1. Freeze the teacher: Set teacher.requires_grad_(False) and teacher.eval(), and run teacher forward passes under torch.no_grad().
  2. Mask prompt and padding tokens explicitly: F.cross_entropy supports ignore_index=-100, whereas F.kl_div does not.[12][13] Index both branches with valid = shifted_labels != -100.
  3. Flatten valid tokens before batchmean: F.kl_div(..., reduction="batchmean") divides by the leading dimension only.[13] Flattening to [num_valid_tokens, vocab] yields a true per-token mean; leaving [batch, seq, vocab] sums across sequence length instead.
tiny-kd-training-step.py
class TinyLM(nn.Module):
    def __init__(self, vocab_size: int, hidden_size: int):
        super().__init__()
        self.embed = nn.Embedding(vocab_size, hidden_size)
        self.lm_head = nn.Linear(hidden_size, vocab_size)

    def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.lm_head(self.embed(input_ids))

def kd_loss(student_logits, teacher_logits, labels, vocab_s, vocab_t, temperature=3.0, alpha=0.7):
    if vocab_s != vocab_t:
        raise ValueError("Logit KD requires identical token-to-ID mappings.")
    shifted_labels = labels[:, 1:]
    valid = shifted_labels != -100
    if not valid.any():
        raise ValueError("No supervised next-token positions; skip this batch.")

    s_flat = student_logits[:, :-1, :][valid].float()
    t_flat = teacher_logits[:, :-1, :].detach()[valid].float()
    y_flat = shifted_labels[valid]

    soft = F.kl_div(
        F.log_softmax(s_flat / temperature, dim=-1),
        F.log_softmax(t_flat / temperature, dim=-1),
        log_target=True,
        reduction="batchmean",
    ) * (temperature ** 2)
    hard = F.cross_entropy(s_flat, y_flat)
    return alpha * soft + (1.0 - alpha) * hard

torch.manual_seed(0)
torch.set_num_threads(1)

vocab = tuple(f"t{i}" for i in range(12))
teacher = TinyLM(12, 16).eval()
teacher.requires_grad_(False)
student = TinyLM(12, 6).train()
optimizer = torch.optim.AdamW(student.parameters(), lr=0.05)

input_ids = torch.tensor([[1, 2, 3, 4, 5], [1, 3, 5, 7, 9]])
labels = input_ids.clone()
labels[:, :2] = -100   # mask prompt tokens
labels[1, -1] = -100   # mask trailing padding token

with torch.no_grad():
    teacher_logits = teacher(input_ids)
teacher_before = teacher.lm_head.weight.clone()

loss_before = kd_loss(student(input_ids), teacher_logits, labels, vocab, vocab)
optimizer.zero_grad()
loss_before.backward()
optimizer.step()
loss_after = kd_loss(student(input_ids), teacher_logits, labels, vocab, vocab)

perturbed = teacher_logits.clone()
perturbed[:, :-1, :][labels[:, 1:] == -100] = 1000.0
loss_perturbed = kd_loss(student(input_ids), perturbed, labels, vocab, vocab)

print(f"loss before -> after : {float(loss_before):.4f} -> {float(loss_after):.4f}")
print(f"teacher frozen       : {bool(torch.equal(teacher.lm_head.weight, teacher_before))}")
print(f"ignored-mask delta   : {abs(float(loss_after - loss_perturbed)):.6f}")
Output
loss before -> after : 1.1329 -> 0.9520
teacher frozen       : True
ignored-mask delta   : 0.000000

Offline top-k logit caching and the tail illusion

Caching dense bf16 teacher logits over 50M tokens and a 32K vocabulary consumes 2,980.2 GiB, whereas caching (k=64) values plus int32 token IDs takes 17.9 GiB (166.7x smaller). Never renormalize only the top-kk tokens to sum to 1, however: if the teacher puts [0.60, 0.30, 0.10] and the student puts [0.30, 0.15, 0.55], both renormalized top-2 distributions become [2/3, 1/3], reporting 0.000 KL while hiding a 0.453 full-vocabulary error where the student dumps 55% mass onto tail junk! Keep an explicit residual tail bucket (1 - sum(top_k)) whenever caching top-kk logits.

QuantityFormulaValue
Dense bf16 logit cache (50M tok, 32K vocab)50M×32,000×2 B/23050\text{M} \times 32{,}000 \times 2\text{ B} / 2^{30}2,980.2 GiB
Top-64 cache (bf16 value + int32 ID)50M×64×(2+4) B/23050\text{M} \times 64 \times (2 + 4)\text{ B} / 2^{30}17.9 GiB (166.7x smaller)
Full-vocabulary forward KL∑iqiln⁡(qi/pi)\sum_i q_i \ln(q_i / p_i) on [0.60, 0.30, 0.10] vs. [0.30, 0.15, 0.55]0.453
Renormalized top-2 KL (no tail bucket)Both rescale to [2/3, 1/3]0.000 (hides 55% tail error)

Capacity limits, evaluation, and failure modes

Distillation cannot bypass student parameter capacity, shorter context windows, or missing prompt coverage. Benchmark four checkpoints under identical decoding budgets: the base student, hard-label SFT, the distilled student, and the teacher. Check licensing as well, since teacher API terms and open weights often restrict commercial distillation.[5]

Ship a distilled student only when it clears every target threshold simultaneously: accuracy, critical error rate, latency, and serving cost.

Four release thresholds evaluate a 7B distilled student: checked accuracy 0.92 clears the 0.90 floor (PASS), critical error rate 0.04 breaches the 0.02 ceiling (FAIL), latency 42 ms clears the 60 ms limit (PASS), and monthly serving cost 18,000 dollars clears the 20,000 dollar cap (PASS). Because every threshold must pass simultaneously, the critical error rate holds back deployment.
The 7B student is 4.3x faster (42 ms vs. 180 ms), stays under its $20k monthly serving budget ($18k), and clears 90% accuracy (92%), yet its 4% critical error rate exceeds the 2% ceiling, holding back deployment until the failure slice is fixed.
SymptomLikely causeFix
Higher TT stops helping held-out scoresOver-softening blurs informative peaksTune TT and α\alpha on held-out tasks, not training KL
Student predicts current tokenMissing one-token shift on hard labelsPair logits at tt with hard labels at t+1t + 1
KL drops cleanly, outputs are gibberishTeacher/student token-to-ID mismatchVerify exact vocabulary equality or use response KD
Student repeats teacher hallucinationsUnfiltered SFT errors or excessive α\alphaFilter traces with verifiers and lower α\alpha
Small student fails hard reasoning slicesCapacity gap or exposure biasIncrease student size, narrow scope, or add OPD
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.At temperature 3, one token has student probability 0.25 and detached teacher probability 0.65. What are the unscaled and T^2-scaled student-logit gradients?
2.A causal sequence is [BOS, Q1, Q2, A1, A2, PAD] (indices 0-5), with only A1 and A2 supervised. Which logit positions compare, and which label indices supply hard targets?
3.A teacher puts [0.7, 0.3] on tokens A and B; the student puts [1.0, 0.0]. What are forward KL(teacher||student) and reverse KL(student||teacher)?
4.Teacher probabilities [0.4, 0.4, 0.2] and student probabilities [0.1, 0.1, 0.8] are renormalized over the top two tokens. What do truncated KL and full KL show?
5.A student emits a prefix absent from fixed teacher data. Which update directly fixes this exposure-bias gap?

5 questions remaining.

References

Distilling the Knowledge in a Neural Network.

Hinton, G., Vinyals, O., & Dean, J. · 2015

https://arxiv.org/abs/1503.02531

Gemma 2: Improving Open Language Models at a Practical Size

Gemma Team, Google DeepMind · 2024

https://storage.googleapis.com/deepmind-media/gemma/gemma-2-report.pdf

MiniLLM: Knowledge Distillation of Large Language Models

Gu, Y., et al. · 2024

https://arxiv.org/abs/2306.08543

On-policy Distillation of Language Models: Learning from Self-Generated Mistakes

Agarwal, R., et al. · 2024

https://arxiv.org/abs/2306.13649

Stanford Alpaca: An Instruction-following LLaMA Model.

Taori, R., et al. · 2023 · GitHub

https://github.com/tatsu-lab/stanford_alpaca

Orca: Progressive Learning from Complex Explanation Traces of GPT-4.

Mukherjee, S., et al. · 2023

https://arxiv.org/abs/2306.02707

Textbooks Are All You Need II: phi-1.5 technical report.

Li, Y., et al. · 2023

https://arxiv.org/abs/2309.05463

Distilling Step-by-Step! Outperforming Larger Language Models with Less Training Data.

Hsieh, C., et al. · 2023

https://arxiv.org/abs/2305.02301

DeepSeek-R1: Original January 2025 Report (v1)

DeepSeek-AI · 2025

https://arxiv.org/html/2501.12948v1

TRL Distillation Trainer

Hugging Face TRL Contributors · 2026

https://huggingface.co/docs/trl/distillation_trainer

TRL Generalized Knowledge Distillation Trainer

Hugging Face TRL Contributors · 2026

https://huggingface.co/docs/trl/gkd_trainer

CrossEntropyLoss

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.CrossEntropyLoss.html

torch.nn.functional.kl_div

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.kl_div.html

PyTorch 2.14: AdamW

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.optim.AdamW.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.