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 insightSample completions on-policy from the student, score those exact tokens under a larger same-tokenizer teacher , and optimize Jensen-Shannon divergence advantages: 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- 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
- 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") - 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()) - 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_reverseingrad runs watchshows 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
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.
Models & datasets
| Model | Duration | Est. cost |
|---|---|---|
Qwen3 4Bstudent ← 32B teacherqwen/qwen3-4b | ~16 min | ~$1.35 |
Qwen3 8Bstudent ← 32B teacherqwen/qwen3-8b | ~24 min | ~$2.10 |
| Dataset | Source | Size |
|---|---|---|
| No Robots Prompts | Hugging Face | 9,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 pureforward_klorreverse_kl: JSD stays bounded when the student assigns near-zero probability to a teacher token and avoids early mode collapse.