On-Policy Distillation¶
Shrink a teacher into a student by correcting the student where it actually goes: the student samples, the teacher scores those exact tokens, and the student's distribution is pulled toward the teacher's. Works across tokenizers and with several teachers at once.
Offline vs on-policy¶
The usual way to distill is offline: the teacher generates a dataset, the student does SFT on it (or trains against the teacher's distributions on fixed data: off-policy distillation, a mode of pgs train). That trains the student on the teacher's trajectories, but at inference the student walks its own path, and every early deviation lands it in states the training data never covered.
On-policy distillation (OPD) flips the sampling. Every step the student samples completions with its current weights, the teacher scores exactly those tokens, and the loss is the reverse KL from the student to the teacher on the student's own states:
With the default loss, full_rkl, the step minimises the exact reverse KL over the shared vocabulary, averaged over the batch's completion tokens:
where \(y\) is the student's own completion, \(t\) runs over its tokens, \(N\) is the number of completion tokens in the batch, \(v\) runs over the vocabulary, and \(p_S\), \(p_T\) are the student's and the teacher's next-token distributions given the same prefix. With loss.length_norm: true the average is per sequence instead of per token.
Quickstart¶
Qwen3-1.7B into Qwen3-0.6B on GSM8K, non-thinking, on one A100 80GB:
# data/gsm8k_*.jsonl: one chat prompt per line, with the reference answer for dev accuracy
import itertools, json
from datasets import load_dataset
PROMPT = "{q}\nSolve the problem step by step, then give the final answer as a number on the last line, after 'Answer:'."
def rows(split, n):
for r in itertools.islice(load_dataset("openai/gsm8k", "main", split=split, streaming=True), n):
yield {"messages": [{"role": "user", "content": PROMPT.format(q=r["question"])}],
"answer": r["answer"].split("####")[-1].strip().replace(",", "")}
for name, split, n in [("gsm8k_train", "train", 3000), ("gsm8k_test200", "test", 200)]:
with open(f"data/{name}.jsonl", "w") as f:
f.writelines(json.dumps(r) + "\n" for r in rows(split, n))
pgs distill --config configs/distill_math.yaml
pgs distill --config configs/distill_math.yaml --train.learning_rate 1e-6 --logging.use_wandb true
Every option can be overridden on the command line, including those of a named teacher or source: --teachers.qwen3_1_7b.backend vllm, --sources.gsm8k.max_new_tokens 384.
A step¶
- The orchestrator draws
rollout.batch_promptsprompts from the sources (byweight) and renders each with the student's chat template and with its teacher's. - The rollout engine samples
rollout.group_sizecompletions per prompt atrollout.temperature, and records each sampled token's log-probability under the policy that sampled it. - Each completion is cut at the first stop token (kept: stopping is supervised too), aligned with its teacher's view of the same text, and scored by that teacher.
- The student scores its own completions (the only forward with gradient); each teacher's loss is summed over its samples and normalized by the batch's completion tokens. Logits are projected a slice of rows at a time, so
[tokens, vocabulary]is never materialized. - Clipped AdamW step on fp32 master weights (bf16 autocast); the new weights go to the rollout engine.
Rollout backends¶
rollout.backend |
What samples | Notes |
|---|---|---|
hf (default) |
the trainer's own model.generate |
No extra dependency. Slow: padded batches, no paged KV cache. |
vllm |
an in-process vLLM engine on the student's GPU | Sleeps while the trainer trains (its weights and KV cache are released), wakes for the next batch; new weights are loaded into it in place after every step. Needs the vllm extra. |
vllm_server |
a separate vllm serve process on the same GPU |
Experimental. Weights go over CUDA IPC through vLLM's native weight-transfer endpoints; generation runs concurrently with training (rollout.max_staleness: 1). Also needs ray installed (vLLM 0.26's IPC module imports it). |
sglang |
an in-process sglang.Engine on the student's GPU |
Sleeps while the trainer trains (weights, KV cache and CUDA graphs released); new weights arrive as bucketed bf16 CUDA IPC handles after every step, and the radix cache is flushed with them. SGLang in its own environment. |
sglang_server |
an SGLang server on the student's GPU, or one at rollout.url |
Weights by CUDA IPC (rollout.weight_sync: tensor), NCCL from the trainer (distributed, a server on another GPU or node) or a checkpoint on a shared file system (disk). |
vLLM or SGLang. Both sample the student's completions with their own log-probs and receive its weights after every step; the losses and metrics do not change. vLLM is the default and the measured path below; SGLang is the alternative when it is faster for the model and batch (its radix cache shares long common prefixes such as the turns of agent traces), or to sample on another node. Two differences matter for distillation: with max_staleness: 1 a weight update waits for SGLang's requests in flight (no rollout spans two versions), and for sampling_mix entries with top-k / top-p SGLang returns the renormalised log-probs only from 0.5.12 on. The support table, the options (rollout.sglang_args, rollout.weight_sync, rollout.weight_bucket_mb), the installation and the GPU checks are in the RL guide, Rollout engines.
rollout.gpu_memory_utilization is the engine's share of the GPU (weights and KV cache; SGLang's mem_fraction_static); with vllm and sglang it only holds that memory while it generates.
Staleness and asynchrony¶
rollout.max_staleness is how many optimizer steps a batch may lag behind the weights it trains:
0(default): batch k is generated with the weights of step k, strictly on-policy. The orchestrator thread still samples and renders the next prompts while the trainer trains.1: batch k+1 is generated (and scored by the teacher) while the trainer trains on batch k. The divergence losses need no correction for this: the student's distribution is computed with the current weights, only the visited states come from a one-step-old policy. The policy-gradient losses (sampled_rkl,xtok) weight each token by the importance ratio to the rollout policy's log-probabilities, and zero it outside[loss.is_low, loss.is_high].
With vllm and max_staleness: 1 the engine stays awake (its memory is held during training) and its kernels share the trainer's CUDA stream, so what overlaps is mostly host work: vLLM's scheduling and the trainer's Python. On a second stream the in-process engine raced with the trainer's kernels (illegal memory accesses that disappear with CUDA_LAUNCH_BLOCKING=1), so it is kept on one. With vllm_server and sglang_server the rollouts run in another process, and the teacher scoring on a stream of its own. The in-process sglang engine decodes in its own scheduler process too; its weight pushes run on the default stream.
A batch older than max_staleness when it reaches the trainer is dropped and counted (dropped_samples); the orchestrator only starts a batch once the weights it may use are published, so this does not happen in normal operation. staleness is logged every step.
Teachers and losses¶
A teacher is hf (in-process, frozen bf16, full distribution) or vllm (a vLLM server run prefill-only: prompt_logprobs=k returns the teacher's top-k log-probabilities and the actual token's at every completion position). A vLLM teacher is a separate server, launched on the student's GPU with teachers.<name>.gpu_memory_utilization or reached at url, because vLLM allows one sleep-mode engine per process and that one is the rollout engine. Each teacher has one loss, picked automatically unless teachers.<name>.loss is set:
| Loss | Needs | What it minimizes | Default for |
|---|---|---|---|
full_rkl |
hf teacher, shared vocabulary | exact reverse KL over the shared vocabulary at every completion token | hf teacher, shared vocabulary |
rs_kd |
hf teacher, shared vocabulary | forward KL to tokens drawn from the teacher's distribution, importance-weighted (Random Sampling KD, arXiv 2503.16870): unbiased, loss.rs_rounds ids per token |
— |
topk_kl |
shared vocabulary | KL between coarse distributions: the teacher's top-k plus the realized token, and one tail bucket holding the rest of each side's mass (loss.beta: 1 reverse, 0 forward) |
vllm teacher, shared vocabulary |
sampled_rkl |
shared vocabulary | REINFORCE on the per-token reward \(\log p_T(y) - \log p_S(y)\) (the sampled reverse KL), with an importance ratio to the rollout policy | — |
xtok |
any tokenizers | REINFORCE on text chunks: reward \(\log p_T(c) - \log p_S(c)\) for chunk \(c\); optional top-k KL where a chunk is one token on each side | teacher with another tokenizer |
Asking for a shared-vocabulary loss with a teacher whose tokenizer differs is an error at startup, before any weights load.
A shared vocabulary means the teacher's vocabulary is a prefix of the student's and both tokenize a set of probe texts identically (Qwen3-0.6B and Qwen3-1.7B; or a ChatML student extending Llama 3's vocabulary with <|im_end|>, distilled from a Llama-3-template teacher). Prompts are rendered with each model's own template, and the student's end-of-turn token is scored against the teacher's (teachers.<name>.eos_map, automatic in the common cases), so the teacher also supervises when to stop.
Across tokenizers¶
When the tokenizers differ, the completion's text is re-tokenized by the teacher and both token sequences are cut into chunks at the byte offsets where both end a token:
A chunk is the same text on both sides, so its total log-probability is comparable: the reward of chunk \(c\) is \(A_c = \log p_T(c) - \log p_S(c)\) (the sum of each side's token log-probabilities in the chunk), and the rewards of a completion add up to its log-likelihood ratio between the two models. Details that matter:
- The student's byte offsets come from the sampled token ids (each token's bytes), never from re-encoding the decoded text: a sampled sequence is often not the tokenizer's canonical encoding of its own text.
- The student's end-of-turn token pairs with the teacher's as the last chunk.
- Whitespace-only chunks carry no loss (
loss.mask_whitespace): tokenizers disagree most on whitespace runs, and supervising them hurt code models badly in published work. - Bytes after the last complete UTF-8 character (a completion cut inside an emoji) and special tokens inside a completion are left out.
loss.xtok_spread: chunkgives every token of a chunk the chunk's advantage;proportionalgives each token \(t\) the share \(\log p_S(t) / \log p_S(c)\) of it.loss.xtok_dense_weight > 0adds a top-k KL at chunks of exactly one token on each side, over the teacher's top-k tokens mapped to student tokens that spell the same bytes (a tail bucket holds the rest).
Several teachers¶
Each source names its teacher; every step mixes the sources by weight and each sample is scored by its own teacher with its own loss (one teacher per sample, no ensemble averaging):
teachers:
math: {model: Qwen/Qwen3-1.7B} # full_rkl
chat: {model: HuggingFaceTB/SmolLM2-360M-Instruct} # another tokenizer: xtok
sources:
gsm8k: {path: data/gsm8k_train.jsonl, teacher: math, weight: 0.5}
chat: {path: data/chat_train.jsonl, teacher: chat, weight: 0.5}
Metrics are reported per teacher (kl/<teacher>, k1/<teacher>, tokens/<teacher>) and dev metrics per source (eval/dev_kl/<source>). An hf teacher that does not fit next to the others can wait on CPU between scoring calls (offload: true) or live on another GPU (device: cuda:1).
Privileged context (on-policy self-distillation)¶
A messages source can give the teacher information the student does not see: privileged_field names a row field
(a resolved fact, a tool result, a short hint), and privileged_template ({content}, {privileged}) places it. With
privileged_role: user (default) the template rewrites the last user turn; with privileged_role: system it rewrites the
system turn (or adds one), so the teacher reads the note as an instruction to itself rather than as the user's words.
With the student's own checkpoint as teacher this is on-policy self-distillation with privileged information (OPSD,
arXiv:2602.04942): the student is pulled towards what it would say if it knew. It works best when the privileged text is
something the student could look up or decide in one step; a full reference solution tends to teach the teacher's
compressed style instead.
sources:
help:
path: help_rows.jsonl # each row: messages, hint
privileged_field: hint
privileged_role: system
privileged_template: "{content}\n\n{privileged}"
Kinds of privileged context¶
The teacher's turn need not carry new facts. What the student lacks may be attention: it misreads a constraint, forgets
a fact stated in the system prompt, or answers the question it expected instead of the one asked. A teacher that is the
student itself, with the input made easier to read, then marks the tokens where the student goes wrong. Templates have
four placeholders: {content} (the turn being rewritten), {privileged} (the row's field), {question} (the last user
turn's text) and {system} (the system turn's text, empty without one).
| Kind | Row field | Template | Role |
|---|---|---|---|
| the question read twice (RE2, arXiv:2309.06275) | none | {content}\n\nRead the question again: {question} |
user |
| a restated constraint | constraint |
{content}\n\nRemember: {privileged} |
user |
| system facts repeated next to the question | none | {system}\n\n{content} |
user |
| a fact card | facts |
{content}\n\nFacts you can rely on:\n{privileged} |
system |
| a trigger-free rewording (the same request without the words that mislead) | reworded |
{privileged} |
user |
| a hint or the reference answer | hint |
{content}\n\nHint: {privileged} |
user or system |
privileged_views puts several kinds in one source. A view with a field applies to the rows where that field is
non-empty (0 counts, an empty string does not); a view without one applies to every row. Each rollout draws one
applicable view by weight; held-out rows get one fixed view each, so dev metrics are comparable between evaluations.
Rows no view applies to are ordinary rows (the teacher sees what the student sees). Steps log the share of each view as
privileged/<name> (privileged/none: rows without a view). privileged_template_field names a row field holding that
row's own template (same placeholders), used instead of the view's where non-empty, for data generated with
per-row instructions; it is checked against every view that may apply to the row when the source loads.
teachers:
self: {model: runs/sft/final} # the student's own starting checkpoint, frozen
sources:
constraints:
path: if_rows.jsonl # rows: messages, and optionally constraint, facts, reworded
teacher: self
privileged_views:
- {name: re2, template: "{content}\n\nRead the question again: {question}", weight: 1}
- {name: constraint, field: constraint, template: "{content}\n\nRemember: {privileged}", weight: 2}
- {name: facts, field: facts, role: system, template: "{content}\n\nFacts you can rely on:\n{privileged}"}
- {name: reworded, field: reworded, template: "{privileged}"}
Removing a trigger: the teacher without the tools¶
A view may also change the tool schemas the teacher's prompt lists, while the student keeps the row's own:
tools: drop (the teacher sees no tools; the view applies to rows that have tools) or tools_field: <row field> (the
teacher's own list, OpenAI schemas or their JSON string, e.g. a subset or a corrected list; it applies where the row
fills the field, like field, and [] means no tools). A view that changes the tools needs no template. This is
context-ablation self-distillation: when unrelated tools attached to an ordinary request make the model refuse ("I
have no tool for that, so I can't"), the same frozen model rendered without them answers, and the student, which
sees the tools, is pulled towards that answer.
teachers:
self: {model: runs/sft/final}
sources:
tool_noise:
path: requests_with_unrelated_tools.jsonl # rows: messages, tools (unrelated to the request), act_hint?
teacher: self
privileged_views:
- {name: no_tools, tools: drop, weight: 2}
- {name: act_hint, field: act_hint, template: "{content}\n\n{privileged}"} # e.g. "Answer directly."
The trained turn must stay one the student could give with the tools in view (an answer, not a call to a tool only
the teacher sees), so drop or replace tools only on rows where the right behaviour does not need them. Off-policy
teacher views (distill.teachers.<name> in pgs train) take the same tools: drop / tools_field.
To measure which kind carries signal, put each view in its own source over the same file (eval/dev_kl/<source> and
eval/dev_acc/<source> then split by kind), or compare kl/<teacher> at step 0 between configs: a view whose teacher
agrees with the student everywhere (step-0 KL near 0) teaches nothing. The privileged text must never reach the
student: check a few rendered teacher prompts against the student's before a long run. With the frozen starting
checkpoint as teacher, the target does not move with the student; nothing in this library measures yet how far the
student follows before the gap closes (watch kl/<teacher> fall and the held-out accuracy of the task).
Measured¶
Student Qwen3-0.6B, non-thinking, on GSM8K train prompts; one A100 80GB (vLLM 0.26, torch 2.11, cu129). Every run: 64 prompts per step, 512 new tokens, temperature 1, 60 steps, learning rate 3e-6 (5 warmup steps, cosine), configs/distill_math.yaml with the changes listed. Dev metrics on 200 GSM8K test questions: dev_kl is the on-policy sampled reverse-KL estimate per student token (on the teacher's own tokens for xtok, whitespace chunks excluded), accuracy is greedy with the last number after "Answer:". Greedy accuracy of the models alone on the same questions: Qwen3-0.6B 64.5%, Qwen3-1.7B 79.0%, Qwen3.5-0.8B 52.0%, SmolLM2-360M-Instruct 10.0%.
| Run | Rollout | Teacher → loss | Rollout tok/s (median) | s / step (median) | dev_kl, step 0 → 60 | GSM8K %, step 0 / 20 / 40 / 60 |
|---|---|---|---|---|---|---|
| reference | hf |
Qwen3-1.7B hf → full_rkl |
638 | 27.9 | 0.542 → 0.256 | 61.5 / 62.5 / 64.0 / 61.5 |
| default | vllm |
Qwen3-1.7B hf → full_rkl |
7,503 | 5.6 | 0.538 → 0.248 | 63.0 / 64.0 / 61.0 / 59.5 |
| vLLM teacher | vllm |
Qwen3-1.7B vllm (top-8) → topk_kl |
7,898 | 6.9 | 0.538 → 0.253 | 63.0 / 66.0 / 67.0 / 64.0 |
| sampled | vllm |
Qwen3-1.7B hf → sampled_rkl |
7,529 | 5.4 | 0.538 → 0.282 | 63.0 / 67.5 / 62.5 / 59.5 |
| cross-tokenizer | vllm |
Qwen3.5-0.8B hf → xtok |
8,557 | 5.7 | 0.446 → 0.204 | 63.0 / 58.0 / 48.5 / 53.5 |
| xtok, same vocabulary | vllm |
Qwen3-1.7B hf → xtok |
7,448 | 5.4 | 0.509 → 0.242 | 63.0 / 67.5 / 64.0 / 64.5 |
| two teachers | vllm |
GSM8K: Qwen3-1.7B full_rkl; chat: SmolLM2-360M xtok |
8,420 | 5.9 | GSM8K 0.538 → 0.277, chat 0.779 → 0.423 | 63.0 / 64.5 / 70.0 / 64.0 |
| async, in-process | vllm, max_staleness: 1 |
Qwen3-1.7B hf → full_rkl |
4,550 (while training) | 4.4 | 0.538 → 0.253 | 62.5 / 62.0 / 63.0 / 62.5 |
| async server | vllm_server, max_staleness: 1 |
Qwen3-1.7B hf → full_rkl |
4,345 (while training) | 4.7 | 0.524 → 0.260 | 61.0 / 65.5 / 66.0 / 61.5 |
What the numbers say:
- Rollouts dominate with
hf. The same run takes 27.9 s per step with the trainer'sgenerateand 5.6 s with the in-process vLLM engine (rollouts ~12× faster, steps ~5×); the KL curves match. In the vLLM step (medians), rollout is 2.15 s, the hf teacher 0.75 s, training 1.88 s, the weight update 0.14 s and sleep/wake 0.67 s; a vLLM teacher takes 1.9 s (prefill with top-k log-probs, returned as JSON). - Every loss reduces the on-policy KL by about half in 60 steps.
full_rklandtopk_kl(8 teacher tokens plus a tail bucket) track each other; the sampled estimators (sampled_rkl,xtok) are noisier. - Accuracy follows the teacher, within noise. With 200 questions one standard error is ~3.4 points: runs toward Qwen3-1.7B peak 3–7 points above the start around steps 20–40, and end within noise of it. A longer run at learning rate 1e-6 (150 steps) has the same shape: 63.0 → 67.0 at step 50 → 60.5 at step 150, while its dev KL plateaus at 0.26 from step 50 on. Watch
eval/dev_accand keep the best checkpoint. Toward Qwen3.5-0.8B, which is worse than the student at GSM8K, the student drifts toward the teacher's 52%, as it should: distillation transfers the teacher's behaviour, not accuracy. - Across tokenizers, xtok behaves like the same-vocabulary losses. Forced on the same-vocabulary teacher it matches
sampled_rkl; aligning a batch of 64 completions costs ~0.05 s. - Asynchrony saves 15–20% on one GPU. Generating the next batch while the trainer trains, 60 steps take 280 s (in-process engine) or 300 s (server) instead of 354 s; the two contend for the GPU (training 1.9 → 2.7–3.0 s, rollout 2.2 → 3.6–3.7 s), and the in-process engine also skips its per-step sleep/wake. Every batch was exactly one version old; none was dropped. The dev KL curves match the synchronous run's.
- Weight sync is exact. After an update, the rollout engine's log-probabilities of fixed probe sequences match the trainer's within bf16 noise (mean |Δ| 0.049 in-process, 0.056 over CUDA IPC, against 0.041 before any change and 1.56 after perturbing the trainer's weights without an update); Qwen3.5 (checkpoint names differ from the loaded model's) matches too (0.022).
Qwen3.5-4B → Qwen3.5-0.8B, and where a step's time goes¶
configs/distill_qwen35.yaml: full_rkl from an hf teacher, 64 prompts × 512 new tokens per step, on-policy (max_staleness: 0). In 100 steps (11 minutes, five evaluations included) GSM8K accuracy goes 53.0 → 55.5 → 59.5 → 62.0 → 62.5% (steps 0/25/50/75/100; the teacher scores 87.5%) and dev KL 0.344 → 0.245. A step takes 5.5 s, down from 8.4 s before these changes (the same batch; timings are means over steps 3–8):
| Phase (s) | before | after | what changed |
|---|---|---|---|
| rollout (vLLM, 64 × ~375 tokens) | 2.58 | 2.46 | — (decode-bound: see below) |
| vLLM sleep/wake | 1.07 | 0 | rollout.sleep: false, gpu_memory_utilization: 0.1: the engine stays resident |
| weight sync | 0.23 | 0.03 | no weights to re-map after a sleep |
| teacher scoring | 1.92 | 1.46 | no output-head pass the loss does not use; Liger kernels |
| student forward/backward + optimizer | 2.57 | 1.67 | fused full_rkl (below); Liger kernels |
The fused full_rkl (opd/fused_rkl.py, used automatically for plain linear output heads and a shared vocabulary without end-of-turn remapping) computes both models' logits in fp32 straight from bf16 GEMMs, then makes two streaming passes over them in Triton: one for both log-sum-exps, the KL and its statistics, one for the analytic gradient q·(log q − log p + 1 − KL − S). Autograd through the definition, which the generic path uses, takes about a dozen elementwise passes over the [tokens, 248k] logits and recasts the output head's weight for every slice. The fused path is also more exact: against fp64 on the same inputs its loss is within 4e-6 and its gradients within 1.3% (norm), where the autocast path's are 9e-6 and 2.9%.
The fused path covers every head logits.output_head produces: a logit scale (Cohere, Granite, Falcon-H1) and Gemma 2's final-logit softcap are applied inside the kernels, with the softcap's derivative computed as \(4\,\sigma(2x)\,\sigma(-2x)\) (no cancellation where the logits saturate). On real hidden states against fp64: Gemma-2-2B-it ← Gemma-2-2B (softcap 30, 256k vocabulary) loss error 2.6e-4 vs 4.8e-3 for the generic path, gradients 5–12× closer, 79 vs 197 ms; Granite-3.3-2B ← 8B (logit scales 1/8 and 1/16) 3.6e-5 vs 7.5e-5, 46 vs 61 ms.
Rollout time is set by decoding: 512 steps for the longest completion, about 5 ms each at 64 sequences (Qwen3.5's linear-attention layers read and write a recurrent state per sequence at every step). Larger batches decode more tokens per second: 128 prompts per step give 13.5k rollout tokens/s instead of 9.7k, and 4.9k trained tokens/s instead of 4.3k, at half the optimizer steps per token.
Packed scoring: train.packing¶
A step samples rollout.group_size completions per prompt, and by default scores each as a row of its own: the teacher and the student both forward the prompt once per completion, and every row is padded to the longest of its micro-batch. train.packing lays a scoring micro-batch out as one row instead (palingenesis.opd.packing, on the packed forward of palingenesis.tree_packing that RL's train.packing uses):
train.packing |
A micro-batch is | Forwarded tokens |
|---|---|---|
padded (default) |
right-padded rows, train.score_micro_seqs per forward |
rows × the longest row |
varlen |
one row, the sequences end to end | the sum of their lengths (no padding) |
tree |
one row, the sequences' prefix trie | each prompt once + its completions |
rollout:
group_size: 8
train:
packing: tree
# packing_tokens: 32768 # packed tokens per micro-batch (0 = score_micro_seqs x the longest sequence)
# packing_gather_tokens: 262144 # tree: K/V rows the attention gathers per layer (0 = 8 x the token budget)
What tree shares, and how:
- The student's forward and backward, and every hf teacher's forward. Softmax attention reads each segment's root-to-segment path in one variable-length flash call; Gated DeltaNet layers (Qwen3.5) run once per tree level, each segment from its parent's state. Gradients reach a shared prompt token from every completion below it.
- Each model packs its own tokens. A teacher that reads another prompt than the student (privileged context, a view without the tools, another tokenizer for
xtok) shares its own prompt among the group's completions; nothing assumes the two prompts are alike. - Several teachers. Samples are routed to their teacher as before; each teacher's samples form their own rows, and a prompt's completions stay together.
- Agent traces. A trace is one trie: the trunk is forwarded once under every regenerated turn and onset branch, and the recorded-turn positions are read from the same pass. Several traces share a row. This replaces the chunk-wise pass of
seco_tree(one no-grad forward of the trunk, then a recomputation chunk by chunk) with one forward and one backward that hold the whole row's activations: use it for traces that fittrain.packing_tokens(defaulttree_chunk_size + tree_branch_tokens), and keeppaddedfor traces far longer than that (a sequence longer than the budget is still forwarded whole). - Only what pays. A tree level costs the recurrent layers a kernel call and the attention a gathered path, whatever it saves. A row becomes a tree when its shared runs together save more than its levels cost (
tree_packing.TREE_MIN_SAVEDforwarded tokens per level); the few tokens completions happen to start alike are copied, not shared, and a row that would not gain is laid out flat (varlen).
The losses do not change: full_rkl (the fused head kernel included), topk_kl, sampled_rkl, rs_kd and xtok read the hidden states of the completion positions gathered from the row, in the order the padded path yields them. On float64 models (tiny Qwen3 and Qwen3.5, tests/test_opd_packing.py) the teacher's hidden states, every loss statistic and dev_kl equal the padded path's to 1e-10 and the student's gradients to 1e-6 (relative), with privileged and tool views, two teachers, and traces with onset branches. Two things depend on how sequences are grouped into micro-batches, and so differ between modes without being wrong: loss.token_weighting: entropy keeps the highest-entropy tokens of each micro-batch, and rs_kd draws its samples micro-batch by micro-batch.
What it does not cover:
- vLLM teachers score on their server as before, one prefill-only request per completion; the server's own prefix cache serves what it serves for such requests (vLLM recomputes the prefill of a request that asks for
prompt_logprobs, see a vLLM teacher for agent traces).train.packingthen applies to the student only. - Rollouts are the engine's (vLLM / SGLang prefix caching:
rollout.prefix_caching). - Models need softmax attention configured for sdpa and, for recurrent layers, transformers' Gated DeltaNet; sliding-window attention, attention softcapping and other recurrent layers (Mamba) are refused at startup with the reason.
varlenon agent traces is refused (it would forward every turn's context again).
Memory: a packed micro-batch holds train.packing_tokens tokens of activations, by default what a padded micro-batch holds at most (score_micro_seqs × the longest sequence), so more completions fit a forward. If it does not fit, lower train.packing_tokens; model.gradient_checkpointing works with packed rows.
Measured (scripts/gpu_checks/opd_tree.sh: one A100, vLLM rollout, Qwen3.5-0.8B student, Qwen3.5-2B hf teacher, full_rkl, prompts of about 630 tokens and completions of about 160, one sampled batch timed in each mode). The pre-registered target was a step at least 25% faster at group size 8 with the same dev KL, and the mode is not recommended below 10%.
| Group size | tree step time vs padded |
varlen step time vs padded |
|---|---|---|
| 4 | -28% | -7% |
| 8 | -33% (target: at least 25%, met) | -6% |
| 16 | -40% | -10% |
At group size 8 tree cuts the teacher's time by 64% and the student's by 54%; the rest of the step (the rollout, the output-head work) is the same in every mode. varlen shares nothing between a prompt's completions, so it gains only the padding it removes. Equality with the padded path on the real models (the teacher's log-probs and top-k, the loss statistics, dev_kl and the student's gradients, judged against the noise between two padded layouts) passes for both varlen and tree with full_rkl. The topk_kl equality has not been measured on a GPU: the check's second trainer in the same process could not load the student, because the first trainer's vLLM engine had registered its own Qwen3.5 config class with transformers (fixed: pgs restores transformers' classes after each engine start; not rerun on a GPU yet). Absolute step times, peak memory and the dev-KL difference are in the check's speed lines. The gain grows with the group size and with the prompt's share of the tokens; with short prompts next to long completions it is smaller.
Why the step gains less than the backbones do: packing shortens the two backbones' passes, by the share of forwarded tokens it removes (a 300-token prompt under eight 300-token completions: 2700 tokens instead of 4800). The rollout and the output-head work of the loss (one projection per completion token, per model) are the same in every mode, so the step gains less than the backbones do, and little when prompts are short next to the completions.
Sparse teacher targets and token selection¶
Same setup (Qwen3.5-4B → 0.8B, 100 steps, one seed each; one standard error on 200 questions is ~3.4 points):
| Run | GSM8K %, step 0 / 25 / 50 / 75 / 100 | dev_kl, step 100 | s / step |
|---|---|---|---|
full_rkl (baseline) |
53.0 / 55.5 / 59.5 / 62.0 / 62.5 | 0.243 | 5.5 |
token_weighting: sure, \(\alpha = 1\) |
53.0 / 55.0 / 62.5 / 61.0 / 62.0 | 0.245 | 5.5 |
token_weighting: entropy, keep 20% |
53.0 / 62.5 / 63.0 / 59.0 / 64.0 | 0.249 | 5.7 |
rs_kd, 50 draws |
53.0 / 53.5 / 59.0 / 58.5 / 56.5 | 0.284 | 7.0 |
- Token selection matches the baseline, within noise. SuRe (arXiv 2608.25643) up-weights tokens the student found unlikely;
entropytrains on only the 20% of tokens where the student is most uncertain (the forking tokens of arXiv 2506.01939, an RL result applied here to distillation). Training on a fifth of the tokens loses nothing measurable here, and neither beats the baseline by more than the noise. - Random Sampling KD is unbiased but noisier than top-k on-policy. On a real batch, against the exact full forward-KL gradient: rs_kd with 50 draws is 13° off (25° with 12), top-12 with a tail bucket 2.6°, top-50 0.6°, and even renormalized top-12 (the paper's Top-K baseline) 4.4°. The paper (arXiv 2503.16870) reports the opposite ordering (top-12 58°, its method 4°) on pretraining text, where the teacher's distribution is broad; at the states an on-policy student visits the teacher is confident (4.3 distinct ids in 50 draws), so a top-k captures nearly all the mass and sampling only adds variance. rs_kd optimizes forward KL, which is mode-covering: completions grew to ~455 tokens (vs ~380) and accuracy trailed. It is also slower here (the teacher projects and samples the full vocabulary per token). Use it where sparse targets are the point — caching a teacher's targets offline, a teacher on another device — not in place of
full_rklon one GPU.
Also run, 5 steps each: an hf teacher with offload: true (moving Qwen3-1.7B on and off the GPU adds 1.4 s per step) and a vLLM teacher (Qwen3.5-0.8B) for xtok with the dense term. Runs are in the palingenesis-validation wandb project, named opd2-*.
Agent traces: distill every turn of recorded trajectories¶
Recorded agent conversations (system, user, then assistant turns with reasoning and tool calls, interleaved with tool outputs) are on-policy distillation data without any environment: at every assistant turn the student regenerates the turn from the recorded context, tool outputs included, and the teacher scores what it wrote. One trace gives one training context per assistant turn.
model:
student: Qwen/Qwen3.5-0.8B
chat_template_kwargs: {enable_thinking: true} # the traces reason between tool calls
teachers:
big: {model: Qwen/Qwen3.5-4B}
small: {model: Qwen/Qwen3.5-2B}
sources:
agent:
format: agent_traces
path: data/agent_traces.parquet # rows: messages, tools, and any other columns
branches_per_trace: 8 # turns regenerated per sampled trace (0 = all)
max_context: 32768
max_new_tokens: 2048
teacher: small # topics not listed below
topic_field: domain
topic_teachers:
big: [Code_Agent, Search_Agent-en]
rollout: {backend: vllm, prefix_caching: true, max_model_len: 36864}
loss: {trace_kd_weight: 0.5} # also distill the recorded turns (off-policy)
Thinking and non-thinking traces, and plain prompts, in one run. Each source can set its own
chat_template_kwargs over the model's, so thinking traces and non-thinking traces go in two sources of the same run.
messages sources can join an agent_traces run: each prompt becomes a one-turn trace (the student writes the
answer, its teacher scores it, as in plain OPD). Use this to anchor single-turn skills while distilling agent traces:
sources:
agent: {format: agent_traces, path: data/traces.jsonl, teacher: agentic, weight: 0.5}
agent_think: {format: agent_traces, path: data/traces_think.jsonl, teacher: agentic, weight: 0.2,
chat_template_kwargs: {enable_thinking: true}}
tool_calls: {format: messages, path: data/calls.jsonl, teacher: tools, weight: 0.3,
chat_template_kwargs: {enable_thinking: false}}
In an agent_traces run, every row of a source renders with that source's arguments. A messages row whose own
chat_template_kwargs disagree with its source's is an error: split such rows into two sources. mcqa sources, and
messages sources with sampling_mix or privileged context, need a plain OPD run.
configs/distill_agent_traces.yaml is the full example (openbmb/UltraData-SFT-Agent-2609: code, search, office and tool-use agents; contexts of 5k–120k tokens, 2–95 assistant turns per trace).
Each context is the student's own rendering. Contexts are rendered with the student's chat template exactly as at inference, tools included, and the student generates from those token ids; the teacher (same tokenizer) scores the same ids. Set the template options the traces were made with: with Qwen3.5 small models, enable_thinking: true (their template defaults to non-thinking, which would render every recorded turn's reasoning as a history the model never sees at inference).
Every model reads a trace once. Inside one agentic loop, chat templates keep the earlier turns' reasoning (Qwen3.5 and MiniMax-M2.x after the last user query, GLM-5.x always unless clear_thinking), so turn k's context is a prefix of turn k+1's: the trace is one trunk with the turns hanging off it. Where a template rewrites the history (reasoning dropped once a new user message arrives), a turn leaves the trunk at its longest common prefix with it and carries the rest of its context. Then:
| reads | instead of | |
|---|---|---|
| student rollouts | the trace prefilled once (vLLM prefix caching; Qwen3.5 hybrids included) | every turn's whole context |
| teacher | the trace once, then every turn from its position (palingenesis.seco_tree) |
every turn's whole context |
| student training | the same tree, backward included; exact gradients through the shared context, activation memory of one chunk | every turn's whole context, forward and backward |
On an 8-turn, 30k-token trace, prefix caching alone turns 3.2 s of prefill into 0.5 s. The tree's gradients are tested equal to training every turn as its own sequence (Qwen3.5 hybrid and pure attention, turns batched or not), and it runs the regenerated turns of a trace as one batched forward, each from its own position.
Recorded turns come free. The trace holds the recorded assistant turns too, and the teacher reads them in the pass it makes anyway: trace_kd_weight adds distillation on them (off-policy, the full distribution, reported as kd_kl/<teacher>), costing only the output-head projections.
Routing teachers by topic. With topic_field and topic_teachers, each row goes to the teacher of its topic (one shuffled dataset, many topics, a teacher per group of topics); kl/<teacher> and, at evaluation, eval/dev_kl_full/<source>/<topic> follow each group. It works for messages sources too.
Budget. A step lasts as long as its longest regenerated turn: max_new_tokens bounds it. A truncated turn is still a valid sample (every token of it is a state the student reached); recorded agent turns are mostly short (median 130–340 tokens, p95 0.6–1.5k, office agents writing files up to 5k).
The student's own episodes: training where it starts to repeat itself¶
A student distilled from teacher traces is trained only on states the teacher reached. Its own failure states, the context after its own wrong command or several thousand tokens into a turn that keeps restating the same doubt, never appear in that data, and that is where small distilled students loop (2512.12895; self-conditioning on one's own errors, 2509.09677). Patching the forms one can name (an exact repeated call, a repeated sentence) moves the failure to the forms one did not name: sub-word runs, counting enumerations, near-paraphrases.
Recorded traces need not come from a teacher. Run the student in its environment, record its episodes (successes and
failures, tools included), and give them to an agent_traces source: every regenerated turn then starts from a state
the student reached itself, and the teacher's distribution says what to do there (DAgger, 1011.0686; for LLM agents
2605.12913). Two options aim that compute at the states that matter:
sources:
own:
format: agent_traces
path: data/student_episodes.jsonl # the student's own episodes on training tasks (never the eval tasks)
branches_per_trace: 2 # ordinary turns, as for any trace
onset_branches: 2 # plus up to 2 turns regenerated from where a recorded turn started repeating
onset_kd_tokens: 32 # recorded-turn distillation keeps 32 tokens of each repetitive run
max_context: 65536
max_new_tokens: 4096
teacher_traces: {format: agent_traces, path: data/teacher_traces.jsonl, weight: 1.0} # keep the skill source
loss: {trace_kd_weight: 0.5}
Where a turn starts repeating itself. opd.traces.repetition_runs scans the recorded assistant turns, token ids
only: a token is a repeat when the onset_ngram tokens ending at it were already written by the assistant (this turn
or an earlier one; tool outputs and prompts do not count, so quoting an observation is not a repeat), n-grams written
by more than onset_common of the earlier turns are scaffolding (call markup, habitual openers) and never count, and a
run starts where onset_threshold of the last onset_window tokens are repeats. No phrase, call syntax or format is
named, so exact loops, sub-word runs, enumerations, near-paraphrases that reuse their phrases and turns that copy
earlier turns all qualify. Legitimate copies (a path written again, a code block rewritten) qualify too; that costs
compute only: the teacher agrees with a good copy and its KL there is small. On a set of repetitive but healthy
search-agent traces, the defaults (6, 32, .75, .5) put 3% of assistant tokens inside runs.
onset_branches. Up to this many extra regenerated turns per trace start at the earliest runs, mid-turn: the
student continues from the token before the repetition and the teacher scores its continuation (reported as
kl_onset/<teacher>, and eval/dev_kl_onset/<source> on held-out traces). The earliest runs, because a teacher
reading a long loop starts agreeing with it (TIDE, 2608.09836): the corrective signal sits at the onset. With either
option on, the trunk may be the whole trace, so the last turn (where an episode cut at the token budget runs on) is
scanned and distilled too. The scan sees what the template renders: a template that drops earlier reasoning after a
new user message hides that reasoning from the scan as from the model.
onset_kd_tokens. With trace_kd_weight, recorded-turn distillation keeps this many tokens of each run and drops
the rest: thousands of loop tokens on which the teacher agrees would otherwise dilute the per-token mean. Turns that
deliberate without repeating themselves are distilled whole.
Nothing in the target is a rule: no stop string, no banned phrase, no length cap. The scan only chooses where the student is trained; what it learns there is the teacher's distribution. Screen the teacher on the same prefixes first: from the student's onset states it should continue differently from the student (a teacher that loops from there teaches the loop). Mix the teacher-trace source back in, so the run keeps what the student learned from it.
Failed tool calls and where the teacher stops being reliable¶
Two more options for the student's own episodes, both off by default.
sources:
own:
format: agent_traces
path: data/student_episodes.jsonl
branches_per_trace: 2
# failed tool calls: what the harness answered, read from the data
error_patterns: ["^Error:", "command not found", "No such file or directory"]
error_invalid_calls: true # a call to an undeclared tool, or arguments that are not a JSON object
error_weight: 2.0 # loss weight of a failed turn's tokens
first_error_weight: 3.0 # the first failed turn of a failed episode
success_field: solved # row field: falsy or <= 0 = the episode failed
error_branches: 2 # plus up to 2 turns regenerated at failed turns, the first one first
# teacher-reliability cutoff
cutoff_logp: -2.0 # stop supervising where the statistic falls below -2
cutoff_window: 0 # 0: STRIDE's sum of per-turn means from the first turn; W: mean of the last W
cutoff_tokens: 150 # each turn's mean over its first 150 tokens (0 = all)
cutoff_weight: 0.0 # turns after the cutoff: dropped (or down-weighted, e.g. 0.25)
Failed turns. A turn whose tool call failed is a state the student caused and must learn to avoid, and where its episode starts to drift. SAGE-OPD (2606.19659) gives such deterministic failures (malformed actions, failed tool calls) full weight while down-weighting other turns, and STRIDE (2609.14636) finds the teacher's endorsement of a student trajectory drops at its first wrong action, not gradually with the turn index. Failures are read from the data, never from the rendered text, so any harness and chat template qualify:
error_patterns: regular expressions (re.search) on the observations that answer the turn, i.e. the messages after it up to the next assistant turn whose role is inerror_roles(default[tool]; adduserfor harnesses that answer a malformed turn with a user message). Choose patterns that mean "the call did not run as intended" (an edit that matched nothing, an unknown command); a test run that fails is information, not a failed call.error_field: a per-message key that marks an error when truthy, on the assistant turn or on its observations (for episodes that record one).error_invalid_calls: a call to a tool the trace does not declare, or with arguments that never parsed to a JSON object.
error_weight scales every token of a failed turn, regenerated or recorded; first_error_weight replaces it for
the first failed turn of an episode that failed (success_field; empty = every episode), a cheap stand-in for the
first wrong action. The loss stays a weighted mean: the per-token weights are renormalized over the batch, as in
SAGE-OPD's normalization, so the loss scale does not move with the share of failed turns. With
branches_per_trace small, a random choice of turns rarely lands on the failed ones: error_branches adds
regenerated turns there. Reported as error_branches and error_token_share (the share of regenerated tokens on
failed turns) per step, kl_error/<teacher> (the KL on those turns) and eval/dev_kl_error/<source>.
The teacher-reliability cutoff. Deep into a drifted episode the teacher reads a history it would never have
written, and its targets there are least reliable (teacher perplexity on student tokens grows with the turn index,
Guided-OPD 2606.15912). STRIDE stops a rollout once the running sum of per-turn mean teacher log-probs of the
student's tokens falls below \(\lambda\) (\(-1\) to \(-3\) on τ²-bench), keeping the turn that crossed it, and finds the informative
part of a turn in its first ~150 tokens. Here, per recorded turn \(k\) inside the trunk, \(l_k\) is the teacher's mean
log-prob of the turn's recorded tokens (its first cutoff_tokens); the statistic is the sum \(l_1 + \dots + l_k\)
(cutoff_window: 0, STRIDE's; it grows with the number of turns, so on long episodes it acts partly as a turn
budget) or the mean of the last cutoff_window values (a per-token scale, independent of the episode's length; e.g.
cutoff_window: 3, cutoff_logp: -1.5). At the first turn where it falls below cutoff_logp, the turns after it,
recorded and regenerated (their context holds it), get cutoff_weight: 0 drops them. The teacher computes these
log-probs in the pass it makes anyway; turns are chosen before the teacher reads the trace, so the regenerated turns
it then drops have cost a rollout. Screen \(\lambda\) on the teacher's log-probs over a sample of episodes first (the
teacher_turn_logp metric reports their mean). Reported per step as cut_trace_share (traces cut),
cut_token_share (recorded-turn tokens after the cutoff), cut_branch_share (regenerated turns after it) and
teacher_turn_logp (mean per-turn teacher log-prob of the recorded turns: it should rise as the student improves,
STRIDE's progress signal). Training only: evaluation scores every held-out turn the same way in every configuration.
A vLLM teacher for agent traces¶
An hf teacher reads each trace once in bf16 next to the student. A teacher too large for that (a 27B in bf16 is
~54 GB) can run as a vLLM server instead, quantized (vllm_args: ["--quantization", "fp8"], weight-only on GPUs
without fp8 compute), and the student trains on topk_kl against its top-k:
teachers:
big:
model: Qwen/Qwen3.5-27B
backend: vllm
gpu_memory_utilization: 0.45
vllm_args: ["--quantization", "fp8"]
loss: {top_k: 16, trace_kd_weight: 0.5}
rollout: {backend: vllm, prefix_caching: true, max_model_len: 69632} # also the teacher server's context
Each regenerated turn is one prefill-only request (its context and completion; prompt_logprobs gives the top-k and
the student token's log-prob at every position), and the trunk one more when recorded turns are distilled or the
cutoff is on. The cost differs from an hf teacher's in two ways. vLLM computes prompt log-probs without its prefix
cache, so every regenerated turn costs a full prefill of its context (an hf teacher reads the shared context once
per trace): keep branches_per_trace small on long traces. And the response carries top_k entries for every
position of the context, not only the completion's, so its size grows with context × top_k. The targets are sparse
(the teacher's top-k plus the student's token, the rest in one tail bucket), so kl/<teacher> is the coarse KL.
The path is tested against a mock server on CPU (its loss equals topk_kl turn by turn); the sizes above are
illustrative, so check the teacher server's and the trainer's memory together on a short run first.
Multiple-choice pools¶
format: mcqa sources train on multiple-choice pools in a benchmark's exact prompt format (configs/distill_opd.yaml carries ITALIC's verbatim templates), with the reference shots, random pool shots and zero-shot mixed per prompt, and greedy letter accuracy as the dev metric.
Dedup your pool against the target benchmark
Training pools are often drawn from the same corpora a benchmark was curated
from. palingenesis.opd.pool hashes every question (normalized: lowercased,
accent-stripped, alphanumeric-only) so you can reject anything that appears
in the benchmark before it enters the pool.
The teacher's accuracy is a hard ceiling for pure KL, and half of a mediocre teacher's supervision pulls the student toward wrong answers. Score the pool with the teacher first and filter:
Every row comes back annotated with teacher_answer and teacher_correct (one batched forward per row, the answer read from the option-letter logits).
Custom sources¶
A source is any object with sample() (messages, max_new_tokens, meta), evaluate(engine) and batch_stats(rollouts); pass it as OPDTrainer(config, source=...). The engine a source evaluates with offers greedy_generate(messages_list, max_new_tokens) and dev_kl(messages_list, max_new_tokens). The built-in sources in palingenesis.opd.sources are short templates.
What to watch¶
| Metric | Meaning |
|---|---|
k1/<teacher> |
sampled reverse-KL estimate per student token, \(\sum (\log p_S - \log p_T) / \text{tokens}\): the same scale for every loss |
kl/<teacher> |
the loss's own KL (exact for full_rkl, coarse for topk_kl) |
eval/dev_kl/<source> |
k1 on held-out prompts, sampled on-policy: the quantity being trained, out of sample |
eval/dev_kl_full/<source> |
exact per-token reverse KL (full_rkl teachers) |
eval/dev_acc/<source> |
greedy accuracy (messages rows with an answer, mcqa letters) |
kl_onset/<teacher>, kl_error/<teacher>, eval/dev_kl_onset/<source>, eval/dev_kl_error/<source> |
agent traces: the KL on regenerated turns that start at a repetition onset, or regenerate a turn whose tool call failed |
error_branches, error_token_share |
agent traces with failed-turn detection: regenerated turns at failed turns, and their share of regenerated tokens |
cut_trace_share, cut_token_share, cut_branch_share, teacher_turn_logp |
agent traces with the teacher cutoff: traces cut, recorded tokens and regenerated turns after the cutoff, the teacher's mean per-turn log-prob of the recorded turns |
residual_mass/<teacher> |
student mass on tokens the teacher cannot see; stays ≈ 0 |
is_dropped/<teacher>, abs_log_ratio/<teacher> |
policy-gradient losses: tokens outside the importance-ratio range, and the mean trainer/rollout log-prob gap |
dense_kl/<teacher>, dense_fraction/<teacher> |
xtok dense term: its KL per supervised position, and the share of tokens that have one |
rollout_tok_s, time/rollout, time/teacher, time/train, time/sync |
where a step's time goes |
staleness, dropped_samples |
how far behind the trained batch was |
Accuracy gains typically saturate before the KL stops falling. Keep train.save_steps small when checkpoint selection matters.
To read what the student samples, logging.dump_trajectories: N writes every Nth batch's completions (text, finish reason, the sampler's and the teacher's log-probs, the sampled KL per completion; logging.dump_groups samples prompts) to <output_dir>/rollouts/, and pgs rollouts --dir <output_dir> reports finish reasons, loops, and the completions furthest from the teacher (Observability).
Checkpoints and resume¶
Every train.save_steps steps the trainer writes output_dir/step_N: the student in Hugging Face format (loadable and servable as is) plus trainer_state.pt with the optimizer, the policy version and the random states. final is the model only. To continue an interrupted run, rerun the same command with --train.resume_from auto (the newest complete checkpoint in output_dir; a fresh start if there is none) or a checkpoint path. The student reloads from the checkpoint, the rollout engine syncs to it before its first rollout, the learning-rate schedule and wandb run continue where they were. Prompts continue from the sampler's saved state; the few drawn ahead of training when the checkpoint was written are skipped, not repeated.
Memory¶
With rollout.sleep: false the vLLM engine keeps its gpu_memory_utilization share while the trainer trains, which saves the wake-up each step (about 1 s for Qwen3.5-0.8B) when it fits: models with little KV cache per token (hybrid linear-attention models, small models) need only a small share.
Student (fp32 master weights + bf16 autocast, AdamW) and frozen bf16 hf teachers share the GPU; the vllm rollout engine takes rollout.gpu_memory_utilization of it only while it generates. If it does not fit: lower train.score_micro_seqs (gradient accumulation keeps the math identical; with train.packing varlen / tree, train.packing_tokens), enable model.gradient_checkpointing, move a teacher to another GPU (device), or offload it between uses (offload). vLLM's sleep mode is not compatible with PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True.