trl icon indicating copy to clipboard operation
trl copied to clipboard

Refactor `DistillationTrainer` and promote it to the stable API

Open qgallouedec opened this issue 4 months ago • 2 comments

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_loss vs a reference impl + parity with GKDTrainer #6450
  • [x] 02 — Pin on-policy and off-policy training end to end #6451
  • [x] 03 — Document the num_items_in_batch bug (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/ (frozen IWOPDTrainer snapshot) + 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/ (ServerDistillationTrainer subclass 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) to GKDTrainer #6459
  • [x] 11 — Remove lmbda and the off-policy branch (always on-policy) #6460

Phase 3 — Dataset contract → prompt-only

  • [x] 12 — Accept a prompt column alongside messages #6461
  • [x] 13 — Deprecate messages-style datasets #6474
  • [x] 14 — Fix num_items_in_batch in 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 messages support, 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_mask alongside labels #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_ids from prompt_ids+completion_ids, logits_to_keep, region-shaped completion_mask; update item 18's shape test), drop the old ones #6497
  • [x] 21b — ⚠️ Freeze ServerDistillationTrainer as 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_lengths are 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 needs processing_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); align top_p 0.95→1.0 (⚠️ mild generation-behaviour change) and vLLM defaults (vllm_server_port 8001→8000, vllm_model_impl). NOT added (out of scope): cast_lm_head_to_fp32, continuous batching; steps_per_generation deferred — without importance-sampling correction it would allow stale-policy training; kept GRPO-shaped (use gradient_accumulation_steps in its place) so re-adding is a mechanical swap. max_completion_length stays 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's vllm_sync_frequency modulo — 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, no num_generations grouping (n=1); returns completion_ids only (loss uses the teacher distribution, not sampled logprobs) #6513
  • [x] 27 — Add _generate + _generate_and_score_completions (unwired; native num_items). Divergences: no logprobs (26 returns completion_ids only); 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_dataloader to GRPO's form (slot-in point: use gradient_accumulation_steps where GRPO uses steps_per_generation); switch _prepare_inputs; identity collator + drop data_collator; delete the buffer (_RepeatBatchDataLoader/_fill_buffer/…/_build_sequence_batch/_get_completion_lengths); remove num_generations (sampler + buffer both die here) + rewrite __post_init__ derivation; drop the orphaned self.vllm_sync_frequency ctor line; native num_items; brings eval generation. Tests: delete test_repeat_batch_dataloader_*/_RepeatBatchDataLoader import + test_num_items_in_batch_*, rework test_generated_batch_emits_* #6522
  • [x] 29 — Align the generation_kwargs dict with GRPO (transformers path; gap found in re-audit): add bos_token_id/eos_token_id/min_p/repetition_penalty/cache_implementation, merge args.generation_kwargs, GenerationConfig(..., disable_compile=True) — makes the item-24 config fields take effect on model.generate #6523
  • [x] 30 — Align the vLLM ctor block with GRPO (TP factor in max_num_seqs — slot-in point: gradient_accumulation_steps in place of GRPO's steps_per_generation; pass repetition_penalty/min_p/generation_kwargs, profiling_context) #6524

Phase 7 — Loss → chunked JSD

  • [x] 31 — Add _get_last_hidden_state (unwired; uses model_kwarg_keys from 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_loss to the chunked path, assert equality, delete the old loss. Tests (same PR): delete TestGeneralizedJSDLoss/TestGeneralizedJSDLossIsPinned + the _reduce_divergence_loss recording 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_state extraction and differ only in the final loss call; delete the bespoke _liger_student_forward / _get_liger_zero3_lm_head_gather_ctx (+ its training_step/prediction_step wrapping) and the hasattr/getattr probing; use the shared maybe_gather_lm_head_ctx for ZeRO-3. No raise; the use_liger_kernel config field stays. Test: keep + clean test_distillation_trainer_with_liger as 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_revision are the conventional CLI teacher config (read by the example script + future trl distillation, mirroring model_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_dropout default → False ⚠️ behaviour change #6604
  • [x] 39 — Config finish: remove_unused_columns = False as a field (B10); docstring house-style sweep ( or None→*optional*, str union in model_init_kwargs, > [!NOTE] block); field grouping/ordering + section comments to match GRPO (learning_rate first, # Parameters that control …, three vLLM groups, drop stray # W&B); beta caveat in metadata["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_logits to the base super().__init__):
    • [x] 40a safe internal cleanups (drop dead inline json.loads, guard Liger with is_liger_kernel_available(), direct pad_token is None) — no API change · commit a4ba0a27 #6606
    • [x] 40b signature/API: drop compute_metrics/preprocess_logits_for_metrics, make model required — updates ServerDistillationTrainer.__init__ in the same PR #6609
    • [x] 40c GRPO-parity adds: quantization_config + QLoRA bf16 cast, PEFT enable_input_require_grads / ZeRO-3 reentrant. (imports consolidation → item 46) #6610
  • [x] 41 — Make advantages optional in the shared print_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 (drop log_completions_steps; add log_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_kernel when a student/teacher config sets logit_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_decorator set #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.md to mirror grpo_trainer.md structure (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 ServerDistillationTrainer at 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_head under pure FSDP (maybe_gather_lm_head_ctx is ZeRO-3-only) — shared chunked/Liger limitation, not a regression
  • [x] 59 — VLM support (was item 45): AutoProcessor left-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 entropy metric — the chunked path computes entropy_sum; now surfaced instead of discarded #6633
  • [x] Consistency sweep folded into item 46 (#6630): get_config_model_id, derived output_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, 3 or None→*optional* fields, remove_unused_columns: bool | None, restore verbatim vLLM help, add the parallelism_config cp/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.md promotion blurb. #6653 (open, stacked on 59-vlm; re-base to main once #6650 lands).
  • [ ] Tool calling — max_tool_calling_iterations, _tool_call_loop, tool_mask loss masking; async/environments/logprobs deferred. Implemented on 60-tools but #6652 was closed (confidential files were committed; history cleaned). Re-open as a fresh PR stacked 59-vlm → tools.
  • [ ] Cross-trainer VLM gaps (shared with GRPO/RLOO — fix everywhere in one sweep, not here):
    • images embedded in message content (no image/images column) are used for generation but dropped from the training forward → placeholder tokens without pixel_values
    • mixed-modality batches pass None/[] image entries into the processor
    • _generate deepcopys prompts now carrying injected PIL images (clones bitmaps each step)
  • [ ] Strengthen test_train_vlm to assert pixel_values actually reach the forward (distillation-local; guards the image-injection fix)

qgallouedec avatar Jul 20 '26 00:07 qgallouedec

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

Strongich avatar Jul 20 '26 16:07 Strongich

right, thanks, adding it to the plan!

qgallouedec avatar Jul 20 '26 16:07 qgallouedec