Distillation2024

GKD

On-Policy Distillation of Language Models (GKD) Agarwal et al. (Google DeepMind) arXiv

The student writes its own answer and learns what the teacher would predict next at each step.

Why it mattered

Classic distillation fine-tunes a small student on static completions generated by a big teacher — but at inference time, the student conditions on its own earlier tokens and immediately drifts off distribution. GKD fixes exposure bias by sampling rollouts from the student and minimizing Jensen-Shannon divergence (JSD) against the teacher.

Core insight

Sample completions y∼πS(⋅∣x)y \sim \pi_S(\cdot \mid x) on-policy from the student, score those exact tokens under a larger same-tokenizer teacher πT\pi_T, and optimize Jensen-Shannon divergence advantages: DJS(πT  ∥  πS)=12DKL(πT  ∥  M)+12DKL(πS  ∥  M),M=12(πT+πS)D_{\text{JS}}(\pi_T \;\|\; \pi_S) = \tfrac{1}{2} D_{\text{KL}}(\pi_T \;\|\; M) + \tfrac{1}{2} D_{\text{KL}}(\pi_S \;\|\; M), \quad M = \tfrac{1}{2}(\pi_T + \pi_S) balancing mode-covering (forward KL) and mode-seeking (reverse KL) behavior.

OnPolicyDistiller(..., mode='jsd') supports TrainerTeacher, SnapshotTeacher, and OpenAITeacher (for a remote 32B vLLM/SGLang teacher) in 26 lines, while DistillRecipe offers managed on-policy top-kk KL when a 14B teacher fits on the same GPU.

When to use

Use GKD when distilling a large same-tokenizer teacher (e.g. 14B/32B) into a fast 1.7B/4B student and offline SFT distillation suffers from exposure bias on multi-step generations. If your student and teacher have different tokenizers, use sequence-level SFT distillation on teacher completions instead.

Step-by-step walkthrough

  1. 01

    Connect a same-tokenizer teacher via OpenAITeacher

    Point OpenAITeacher at any OpenAI-compatible vLLM or SGLang server hosting Qwen/Qwen3-32B (or use SnapshotTeacher on a decoupled qwen/qwen3-14b sampler). Connecting an OpenAI-compatible teacher or decoupled sampler keeps teacher weights off the student's training GPU.

    OpenAITeacher("http://teacher-host:8000/v1", model="Qwen/Qwen3-32B")
  2. 02

    Create OnPolicyDistiller with mode='jsd'

    Select mode='jsd' so per-token advantages balance forward and reverse KL without exploding when student probabilities are small. Using JSD balances mode-covering and mode-seeking gradients on the student's own sampled prefixes.

    OnPolicyDistiller(trainer, teacher, mode="jsd", loss=losses.ImportanceSampling())
  3. 03

    Step on unlabeled prompt batches and monitor KL

    Use optim.AdamW(lr='auto', objective='distill') and push distill_kl_reverse / loss to grad runs watch via trainer.log_metrics(). Tracking distill_kl_reverse in grad runs watch shows exactly when the student stops absorbing teacher signal.

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

Implementation

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

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

with (
    OpenAITeacher(
        os.environ["TEACHER_BASE_URL"],
        model="Qwen/Qwen3-32B",
        api_key=os.environ.get("TEACHER_API_KEY"),
    ) as teacher,
    client.trainers.create(
        "qwen/qwen3-4b",
        name="gkd-4b-jsd",
        max_cost_usd=5.0,
        adapter=adapters.LoRA(rank=32, merge_on_export=True),
    ) as trainer,
):
    distiller = OnPolicyDistiller(
        trainer, teacher, mode="jsd", 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"),
        )
        trainer.log_metrics(
            res.optim_step.step,
            {"kl_reverse": res.metrics["distill_kl_reverse"], "loss": res.metrics["loss"]},
        )

    artifact = trainer.export(name="gkd-4b-from-32b").result().artifact
    print(artifact.ref)

Benchmarks

Reported results from the original paper compared against its baseline.

XSum Summarization ROUGE-2T5-XL student distilled from T5-XXL (GKD vs. SeqKD)
+2.1 pts
Sequence-level KD21.8 pts
On-policy GKD (JSD)23.9 pts
GSM8K Accuracy (Distilled Student)Gemma-2B student (On-policy GKD vs. Supervised KD)
+5.8 pts
Supervised KD35.4%
On-policy GKD41.2%

Models & datasets

ModelDurationEst. cost
Qwen3 4Bstudent ← 32B teacherqwen/qwen3-4b
~16 min~$1.35
Qwen3 8Bstudent ← 32B teacherqwen/qwen3-8b
~24 min~$2.10
DatasetSourceSize
No Robots PromptsHugging Face9,500 diverse prompts

Practical gotchas

  • OpenAITeacher scores echo log-probs at temperature=1.0, so sample the student at temperature=1.0 and top_p=1.0 for exact alignment.
  • Student and teacher MUST share the exact same tokenizer (e.g. qwen/qwen3-4b student with Qwen/Qwen3-14B or Qwen/Qwen3-32B teacher).
  • Start with mode='jsd' before trying pure forward_kl or reverse_kl: JSD stays bounded when the student assigns near-zero probability to a teacher token and avoids early mode collapse.

grad primitives