Refactor `DistillationTrainer` and promote it to the stable API
Every major recent release ships on-policy logit distillation (Qwen3.x, DeepSeek-V4, GLM-5, Nemotron 3). We have 5 experimental trainers for it and 0 stable.
experimental.DistillationTrainer is the best candidate: small core, but a lot of bolt-on axes. The plan is to refactor it in place until it is GRPO-shaped — distillation is GRPO with the policy-gradient loss swapped for a teacher-KL loss — then promote it. Doing it gradually rather than as one big rewrite, so each step stays reviewable.
End state: single-teacher, always on-policy, prompt-only datasets, one chunked generalized-JSD loss (beta selects forward/reverse/JSD), living in trl/trainer/ with a deprecation shim left in trl/experimental/.
Ground rules: one concern per PR; replacements land as add-unwired → switch → delete; the objective stays pinned by a test throughout. Each item below is exactly one PR, stacked on the previous. Only three PRs change behaviour values (14, 35, 38) and they say so in the title. Alignment with GRPO is the north star across code, config, tests and docs: new tests are written GRPO-shaped (no bespoke helpers), and the full test-file rewrite to match test_grpo_trainer.py is item 47.
Re-derived (2026-07-21): items 14+ were re-ordered after finding that prompt-only training NaNs until num_items_in_batch is fixed (a prompt-only dataset has 0 dataset-completion tokens → num_items = 0 → loss sum/0). So the num_items fix moves to item 14 (front of Phase 3), and the collator→_tokenize_prompts swap moves into Phase 6 (generation). Full rationale in distillation_prs/PLAN_REMAINING.md.
Re-derived again (2026-07-23): Phases 5+ were re-ordered strictly bottom-up (state before consumer) after finding a forward-reference hazard — GRPO's generation methods consume config fields (min_p, generation_kwargs, …) and ctor attrs (_dist, _tokenizer, model_kwarg_keys, _last_loaded_step) that the old order added later. Those are now added add-only in Phase 5 before the generation adoption in Phase 6. Two features are dropped from scope entirely: cast_lm_head_to_fp32 and continuous batching — they never enter the config, ctor, or _generate_single_turn (which also removes the biggest source of forward-references). Net item count 60 → 57.
Phase 0 — Safety net
- [x] 01 — Pin the objective:
generalized_jsd_lossvs a reference impl + parity withGKDTrainer#6450 - [x] 02 — Pin on-policy and off-policy training end to end #6451
- [x] 03 — Document the
num_items_in_batchbug (xfail test) #6452
Phase 1 — Extract server + sparse, move IW-OPD out
Takes compute_loss from 7 dispatch paths to 1.
- [x] 04 — Move IW-OPD to
experimental/iw_opd/(frozenIWOPDTrainersnapshot) + repoint its paper-index entry. It is a teacher-guided policy-gradient method (teacher and PPO-style clipping), so it fits neither the stable full-vocab trainer nor GRPO (no teacher) — a dedicated snapshot, not a re-home on GRPO. #6453 - [x] 05 — Add
experimental/server_distillation/(ServerDistillationTrainersubclass carrying the server + sparse top-k path) and remove those paths from the base #6454 - [x] 06 — Remove the local sparse top-1 path from the base #6455
- [x] 07 — Remove top-k support selection from
generalized_jsd_loss#6456 - [x] 08 — Teacher validation: tokenizer-match → vocab-size check #6457
Phase 2 — Remove on/off-policy mixing
- [x] 09 — Deprecate
lmbda#6458 - [x] 10 — Move the GKD paper reproduction (
lmbda=0.5) toGKDTrainer#6459 - [x] 11 — Remove
lmbdaand the off-policy branch (always on-policy) #6460
Phase 3 — Dataset contract → prompt-only
- [x] 12 — Accept a
promptcolumn alongsidemessages#6461 - [x] 13 — Deprecate
messages-style datasets #6474 - [x] 14 — Fix
num_items_in_batchin the buffer path ⚠️ changes loss values (un-xfails items 03 + 12; ~15-line throwaway, superseded natively at item 28) #6478 - [x] 15 — Switch tests, docs and example to prompt-only #6479
- [x] 16 — Remove
messagessupport,max_length,max_prompt_length#6480 - [x] 17 — Pin signature columns to
["prompt", "image", "images"]#6481
Phase 4 — Tensor layout → GRPO keys
- [x] 18 — Emit
completion_maskalongsidelabels#6482 - [x] 19 — Loss consumes
completion_mask#6484 - [x] 20 — Emit
prompt_ids/prompt_mask/completion_ids#6487 - [x] 21 — Switch all consumers to the new keys (reconstruct
input_idsfromprompt_ids+completion_ids,logits_to_keep, region-shapedcompletion_mask; update item 18's shape test), drop the old ones #6497 - [x] 21b — ⚠️ Freeze
ServerDistillationTraineras a self-contained snapshot before the 22/28/33 deletions (it depends on_jsd_divergence/_reduce_divergence_loss/_compute_prompt_length+ the old layout); re-point at 55 (H7) #6508 - [x] 22 — Delete
_compute_prompt_length(server-only after 21; frozen at 21b)._build_sequence_batch/_get_completion_lengthsare still used by the buffer, so they move to item 28 #6509
Phase 5 — Generation-supporting state (config + ctor, add-only, before generation)
Everything GRPO's generation methods read is added here first, add-only — nothing consumes it yet, so nothing breaks. This is the re-derivation fix (H8): state before consumer.
- [x] 23 — Add
_tokenize_prompts(unwired; only needsprocessing_class, which already exists — no forward-refs) #6510 - [x] 24 — Config: add the shared generation fields add-only (
min_p,repetition_penalty,generation_kwargs,cache_implementation,chat_template_kwargs,pad_to_multiple_of,shuffle_dataset,ds3_gather_for_generation); aligntop_p0.95→1.0 (⚠️ mild generation-behaviour change) and vLLM defaults (vllm_server_port8001→8000,vllm_model_impl). NOT added (out of scope):cast_lm_head_to_fp32, continuous batching;steps_per_generationdeferred — without importance-sampling correction it would allow stale-policy training; kept GRPO-shaped (usegradient_accumulation_stepsin its place) so re-adding is a mechanical swap.max_completion_lengthstays 512 #6511 - [x] 25 — Ctor: add the generation-supporting state add-only (
self.min_p/repetition_penalty/top_k/chat_template_kwargs/pad_to_multiple_of/shuffle_dataset;self._dist,self._tokenizer,self.model_kwarg_keys,set_seed,add_model_tags); minimal rename_last_vllm_sync_step→_last_loaded_step(kept the throwaway buffer gate'svllm_sync_frequencymodulo — dies with the buffer at 28) #6512
Phase 6 — Generation stack → GRPO (state from Phase 5 now exists)
- [x] 26 — Add
_generate_single_turn(unwired) — vLLM +model.generate+ EOS truncation. No continuous-batching branch, nonum_generationsgrouping (n=1); returnscompletion_idsonly (loss uses the teacher distribution, not sampled logprobs) #6513 - [x] 27 — Add
_generate+_generate_and_score_completions(unwired; nativenum_items). Divergences: no logprobs (26 returnscompletion_idsonly); no rewards/advantages/rollout_func/tools (the "score" half is deleted → generate + batch-assembly); keep the GRPO method name for consistency #6521 - [x] 28 — The generation cutover (atomic — merges the old "samplers" + "switch"; the buffer dataloader and GRPO samplers are mutually exclusive). Rewrite
_get_train_sampler/get_train_dataloader/_get_eval_sampler/get_eval_dataloaderto GRPO's form (slot-in point: usegradient_accumulation_stepswhere GRPO usessteps_per_generation); switch_prepare_inputs;identitycollator + dropdata_collator; delete the buffer (_RepeatBatchDataLoader/_fill_buffer/…/_build_sequence_batch/_get_completion_lengths); removenum_generations(sampler + buffer both die here) + rewrite__post_init__derivation; drop the orphanedself.vllm_sync_frequencyctor line; nativenum_items; brings eval generation. Tests: deletetest_repeat_batch_dataloader_*/_RepeatBatchDataLoaderimport +test_num_items_in_batch_*, reworktest_generated_batch_emits_*#6522 - [x] 29 — Align the
generation_kwargsdict with GRPO (transformers path; gap found in re-audit): addbos_token_id/eos_token_id/min_p/repetition_penalty/cache_implementation, mergeargs.generation_kwargs,GenerationConfig(..., disable_compile=True)— makes the item-24 config fields take effect onmodel.generate#6523 - [x] 30 — Align the vLLM ctor block with GRPO (TP factor in
max_num_seqs— slot-in point:gradient_accumulation_stepsin place of GRPO'ssteps_per_generation; passrepetition_penalty/min_p/generation_kwargs,profiling_context) #6524
Phase 7 — Loss → chunked JSD
- [x] 31 — Add
_get_last_hidden_state(unwired; usesmodel_kwarg_keysfrom item 25) #6525 - [x] 32 — Add
_chunk+_chunked_divergence_loss+ unit tests (unwired) — the one deliberate bespoke-test exception (loss custody) #6526 - [x] 33 — Wire
compute_lossto the chunked path, assert equality, delete the old loss. Tests (same PR): deleteTestGeneralizedJSDLoss/TestGeneralizedJSDLossIsPinned+ the_reduce_divergence_lossrecording closure #6530 - [x] 34 — Keep + heavy-clean the Liger path (reversing the earlier "delete" plan). The fused JSD stays an opt-in fast path — SFT offers both chunked and Liger, and the path is verified working here. Converge the two loss paths so they share the
_get_last_hidden_stateextraction and differ only in the final loss call; delete the bespoke_liger_student_forward/_get_liger_zero3_lm_head_gather_ctx(+ itstraining_step/prediction_stepwrapping) and thehasattr/getattrprobing; use the sharedmaybe_gather_lm_head_ctxfor ZeRO-3. No raise; theuse_liger_kernelconfig field stays. Test: keep + cleantest_distillation_trainer_with_ligeras a Liger-vs-chunked agreement check #6537 - [ ] 35 — ❌ cancelled — temperature is kept and applied in the loss (threaded through the chunked path at #6530), matching the documented config contract; not made sampling-only. The earlier "matches GKD/frontier" rationale was dropped (GKD in fact divides by temperature; the KD temperature is a deliberate knob here)
Phase 8 — Config finish, constructor cleanup, remaining alignment
All generation/loss-independent, so it comes after the functional swap.
- [ ] 36 — ❌ cancelled —
teacher_model_name_or_path/teacher_model_revisionare the conventional CLI teacher config (read by the example script + futuretrl distillation, mirroringmodel_name_or_path/model_revision; consistent with GKD/GOLD), not dead. Keep all three; docstring house-style cleanup folded into item 39 - [ ] 37 — ❌ cancelled (folded into 36's cancellation)
- [x] 38 —
disable_dropoutdefault →False⚠️ behaviour change #6604 - [x] 39 — Config finish:
remove_unused_columns = Falseas a field (B10); docstring house-style sweep (or None→*optional*,strunion inmodel_init_kwargs,> [!NOTE]block); field grouping/ordering + section comments to match GRPO (learning_ratefirst,# Parameters that control …, three vLLM groups, drop stray# W&B);betacaveat inmetadata["help"](B8); simplify__post_init__(~~B7~~ ✅ done) #6605 - [x] 39b — Config cosmetic parity (NOT deferred — cosmetic diff-chasing is a core goal): field order to match
grpo_config.py, the three vLLM sub-groups (general/server/colocate),# Parameters that control …section comments,> [!NOTE]overridden-defaults block, import grouping. No behaviour change - [x] 40 — Constructor cleanup — split (the signature-changing parts are coupled to the server ctor, which forwards
model=None/compute_metrics/preprocess_logitsto the basesuper().__init__):- [x] 40a safe internal cleanups (drop dead inline
json.loads, guard Liger withis_liger_kernel_available(), directpad_token is None) — no API change · commita4ba0a27#6606 - [x] 40b signature/API: drop
compute_metrics/preprocess_logits_for_metrics, makemodelrequired — updatesServerDistillationTrainer.__init__in the same PR #6609 - [x] 40c GRPO-parity adds:
quantization_config+ QLoRA bf16 cast, PEFTenable_input_require_grads/ ZeRO-3 reentrant. (imports consolidation → item 46) #6610
- [x] 40a safe internal cleanups (drop dead inline
- [x] 41 — Make
advantagesoptional in the sharedprint_prompt_completions_sample(touches GRPO/RLOO) #6611 - [x] 42 — Use the shared printer, delete the private copy #6612
- [x] 43 — Adopt GRPO's
log(+ align metric keys:clipped_ratio, terminated-length metrics,num_tokens,step_time;_textual_logs→_logs); logging fields (droplog_completions_steps; addlog_multimodal/log_unique_prompts/log_completions_hub_repo) #6613 - [x] 44 — Adopt GRPO's
training_step/prediction_step/_save_checkpoint#6614 - [x] 45 — VLM support — done, superseded by item 59 (#6650); shipped as a post-promotion PR rather than pre-promotion
- [x] Liger softcap/scale guard — reject
use_liger_kernelwhen a student/teacher config setslogit_scale/final_logit_softcapping(the Liger kernel can't apply them, so it would silently optimize a different objective than the chunked path). Deep-review (2026-08-02) correctness find #6629 - [x] 46 — Convention/cosmetic sweep: rewrite trainer class docstring to GRPO format, remove
# ────box-divider comments, drop in-code "GRPO" name-drops, align@profiling_decoratorset #6630
Phase 9 — Test + doc rewrite to mirror GRPO
- [x] 47 — Rewrite the test file to mirror
test_grpo_trainer.py(drop_make_args/_make_local_trainer/recording-closure/setup_methods, inline construction,previous_trainable_params, CPU + slow classes); ADD the missing GRPO categories (PEFT, eval, iterable-dataset,trust_remote_code, config sweeps, VLM class, vLLM-skipped), assertion-style cleanup; keep the justified distillation-only tests — v1 is text-only, no VLM test class #6634 - [x] 48 — Rewrite
distillation_trainer.mdto mirrorgrpo_trainer.mdstructure (badge, Logged metrics section, prompt-only) #6639
Phase 10 — Promotion
- [x] 49 — Move to
trl/trainer/+ register (both blocks in both__init__) + experimental shim (atomic) #6640 - [x] 50 — Telemetry allowlist: Experimental → Stable #6641
- [x] 51 — CLI:
trl distillation(scripts/distillation.py+ command +test_cli) #6642 - [x] 52 — Move tests to
tests/(..testing_utils→.testing_utils, retarget imports) #6647 - [x] 53 — Docs:
_toctree,distillation_trainer.md(de-namespace, drop[!NOTE], badge),paper_index,index,clis,example_overview#6643 - [x] 54 — Update
examples/scripts/distillation.py#6644
Phase 11 — After promotion
IW-OPD's re-home is already done (#6453, as a frozen experimental/iw_opd/ snapshot rather than on GRPO).
- [x] 55 — Re-point
ServerDistillationTrainerat the stable base #6645 - [ ] 56 — ~~(optional) Liger fused JSD as an opt-in fast path~~ obsolete — Liger is kept and cleaned in v1 (item 34), so there is no post-promotion Liger follow-up
- [ ] 57 — (optional) Wire the MoE aux loss, or drop
router_aux_loss_coef - [ ] 58 — (follow-up) gather the teacher
lm_headunder pure FSDP (maybe_gather_lm_head_ctxis ZeRO-3-only) — shared chunked/Liger limitation, not a regression - [x] 59 — VLM support (was item 45):
AutoProcessorleft-truncate/pad,_is_vlm, image extraction + dataset-column injection,forward_kwargs/num_images/num_tiles/token-type threading,TestDistillationTrainerVLM. GRPO-verbatim mirror. #6650 — open, mergeable, reviews addressed
Deep review (2026-08-02) — follow-ups surfaced
Full audit in distillation_prs/DEEP_REVIEW_2026-08-02.md. Validation trifecta passed (converges; ~7× less peak memory than full-logit; server coherent). Loss verified correct on the default path.
- [x] Liger softcap/scale guard — the one real correctness gap (see item above) #6629
- [x] Log the student
entropymetric — the chunked path computesentropy_sum; now surfaced instead of discarded #6633 - [x] Consistency sweep folded into item 46 (#6630):
get_config_model_id, derivedoutput_dir. Deferred to a follow-on (was a rename/guard collision, now unblocked since 46 sits on the guard):use_liger_loss→use_liger_kernel,__init__block re-ordering to match GRPO - [x] Config drift: rebuild the
> [!NOTE]overridden-defaults block, 3or None→*optional*fields,remove_unused_columns: bool | None, restore verbatim vLLM help, add theparallelism_configcp/sp__post_init__guard #6632 - [ ]
log_completions_hub_repo(deferred from item 43) - [ ] Product decisions to make: split
temperature(generation vs loss softmax); GKD/DistillationTrainer overlap roadmap story;cast_lm_head_to_fp32;router_aux_loss_coef(MoE student)
Post-promotion follow-ons (status 2026-08-12)
The core refactor (items 01–55) has fully landed on main: trl.DistillationTrainer is stable, GRPO-shaped, chunked-JSD, vLLM-capable, with the experimental shim in place. Remaining open threads:
- [ ] VLM support — #6650 (item 59). Open, mergeable, reviews addressed. Next to merge.
- [ ] What's New announcement — README +
index.mdpromotion blurb. #6653 (open, stacked on 59-vlm; re-base tomainonce #6650 lands). - [ ] Tool calling —
max_tool_calling_iterations,_tool_call_loop,tool_maskloss masking; async/environments/logprobs deferred. Implemented on60-toolsbut #6652 was closed (confidential files were committed; history cleaned). Re-open as a fresh PR stacked59-vlm → tools. - [ ] Cross-trainer VLM gaps (shared with GRPO/RLOO — fix everywhere in one sweep, not here):
- images embedded in message content (no
image/imagescolumn) are used for generation but dropped from the training forward → placeholder tokens withoutpixel_values - mixed-modality batches pass
None/[]image entries into the processor _generatedeepcopys prompts now carrying injected PIL images (clones bitmaps each step)
- images embedded in message content (no
- [ ] Strengthen
test_train_vlmto assertpixel_valuesactually reach the forward (distillation-local; guards the image-injection fix)
Friendly note, not urgent: mirroring GRPO's path, tool support seems like it'd be expected on the promoted trainer, but it's absent from the plan. Just putting it on the radar in case it slipped through
right, thanks, adding it to the plan!