Distillation2024

MiniLLM

MiniLLM: Knowledge Distillation with Reverse KL Gu et al. (Microsoft Research) arXiv

MiniLLM uses reverse KL to discourage answers the student favors much more than its teacher does.

Why it mattered

A 4B student simply does not have enough capacity to match every mode of a larger teacher's distribution. Standard forward KL punishes the student for missing any teacher mode, forcing it to spread thin probability everywhere and hallucinate. MiniLLM flips the direction to reverse KL with a variance-reducing baseline so the student focuses cleanly on high-probability teacher responses.

Core insight

Sample y∼πS(⋅∣x)y \sim \pi_S(\cdot \mid x), score exact token log-probs under the teacher πT\pi_T, and apply per-token reverse-KL policy-gradient advantages with batch-mean baseline centering: At=(log⁡πT(yt∣x,y<t)−log⁡πS(yt∣x,y<t))−bA_t = \left(\log \pi_T(y_t \mid x, y_{<t}) - \log \pi_S(y_t \mid x, y_{<t})\right) - b

OnPolicyDistiller(..., mode='reverse_kl', center_baseline=True) paired with SnapshotTeacher on a decoupled SamplingClient implements MiniLLM's exact reverse-KL policy gradient in 25 lines — with no custom teacher server required.

When to use

Use MiniLLM's reverse-KL distillation when distilling into a compact student (0.6B to 4B) that lacks capacity to cover every teacher mode, so mode-covering forward KL causes hallucinations and mushy outputs. When you have larger student capacity and want broader diversity, prefer GKD with JSD.

Step-by-step walkthrough

  1. 01

    Open a decoupled sample-only teacher session

    Use client.trainers.open_sampler('qwen/qwen3-14b') to score student tokens via SnapshotTeacher without allocating optimizer or gradient buffers for the teacher. Opening a sample-only teacher session scores student trajectories without reserving teacher optimizer memory.

    sampler = client.trainers.open_sampler("qwen/qwen3-14b", max_cost_usd=3.0); teacher = SnapshotTeacher(sampler.snapshot())
  2. 02

    Configure reverse KL with variance-reducing baseline

    Set mode='reverse_kl' and center_baseline=True to subtract the weighted batch-mean KL advantage, stabilizing policy gradients just like MiniLLM's single-step control variate. Enabling center_baseline=True subtracts the batch-mean advantage so reverse-KL policy gradients stay low-variance.

    OnPolicyDistiller(student, teacher, mode="reverse_kl", center_baseline=True)
  3. 03

    Update student with calibrated distill LR

    Run distiller.step() with optim.AdamW(lr='auto', objective='distill') and export the mode-seeking 4B adapter. Calibrated objective='distill' AdamW keeps adapter updates proportional to token-level KL scale.

    distiller.step(prompts, sample={"max_tokens": 256, "temperature": 1.0}, optim=optim.AdamW(lr="auto", objective="distill"))

Implementation

train.py
from datasets import load_dataset
from grad import Grad, OnPolicyDistiller, SnapshotTeacher, adapters, losses, optim

client = Grad()
prompts = [
    r["messages"][0]["content"]
    for r in load_dataset("HuggingFaceH4/no_robots", split="train[:1024]")
]

with (
    client.trainers.open_sampler("qwen/qwen3-14b", name="minillm-teacher", max_cost_usd=3.0) as teacher_sampler,
    teacher_sampler.snapshot() as teacher_snap,
    client.trainers.create(
        "qwen/qwen3-4b",
        name="minillm-4b",
        max_cost_usd=4.0,
        adapter=adapters.LoRA(rank=32, merge_on_export=True),
    ) as student,
):
    distiller = OnPolicyDistiller(
        student,
        SnapshotTeacher(teacher_snap),
        mode="reverse_kl",
        center_baseline=True,
        loss=losses.ImportanceSampling(),
    )
    for start in range(0, len(prompts), 32):
        res = distiller.step(
            prompts[start : start + 32],
            sample={"max_tokens": 256, "temperature": 1.0},
            optim=optim.AdamW(lr="auto", objective="distill"),
        )
        student.log_metrics(
            res.optim_step.step,
            {"kl_reverse": res.metrics["distill_kl_reverse"], "baseline": res.metrics["distill_baseline"]},
        )
    artifact = student.export(name="minillm-4b").result().artifact
    print(artifact.ref)

Benchmarks

Reported results from the original paper compared against its baseline.

DollyEval ROUGE-LOPT-1.3B student from OPT-13B teacher (MiniLLM vs. KD)
+2.6 pts
Standard Forward KD25%
MiniLLM (Reverse KL)27.6%
SelfInst ROUGE-LLLaMA-7B student from LLaMA-13B teacher (MiniLLM vs. KD)
+3.6 pts
Standard Forward KD18.2%
MiniLLM (Reverse KL)21.8%

Models & datasets

ModelDurationEst. cost
Qwen3 4B← Qwen3 14Bqwen/qwen3-4b
~14 min~$1.30
Qwen3 1.7B← Qwen3 14Bqwen/qwen3-1.7b
~9 min~$0.85
Qwen3 8B← Qwen3 14Bqwen/qwen3-8b
~20 min~$1.95
DatasetSourceSize
No Robots PromptsHugging Face9,500 prompts

Practical gotchas

  • Reverse KL can narrow response diversity if run too long — enable center_baseline=True and stop once held-out reverse KL flattens.
  • Always match tokenizers between student and teacher (e.g., qwen/qwen3-1.7b or qwen/qwen3-4b with qwen/qwen3-14b).
  • Evaluate generation diversity (distinct-2 or pass@k) alongside ROUGE-L: reverse KL aggressively prunes low-probability modes and will over-sharpen if run too many epochs.

grad primitives