Buckets:
Distillation Trainer
Overview
The Distillation Trainer implements on-policy knowledge distillation as described in On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes by Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Knowledge distillation (KD) is widely used for compressing a teacher model to reduce its inference cost and memory footprint, by training a smaller student model. However, current KD methods for auto-regressive sequence models suffer from distribution mismatch between output sequences seen during training and those generated by the student during inference. To address this issue, we introduce Generalized Knowledge Distillation (GKD). Instead of solely relying on a fixed set of output sequences, GKD trains the student on its self-generated output sequences by leveraging feedback from the teacher on such sequences. Unlike supervised KD approaches, GKD also offers the flexibility to employ alternative loss functions between the student and teacher, which can be useful when the student lacks the expressivity to mimic the teacher's distribution.
The DistillationTrainer trains a smaller student model to match a teacher's next-token distribution on the student's own on-policy generations, extending the ideas from the GKDTrainer. A generation buffer decouples the training microbatch size from the generation batch size, letting vLLM batch many prompts in a single call across gradient accumulation steps.
The Distillation Trainer is currently part of the
trl.experimentalnamespace. APIs may change without notice while the feature is iterated on.
Quick start
from datasets import load_dataset
from trl.experimental.distillation import DistillationConfig, DistillationTrainer
# 1. Load dataset and format as a prompt-only column
dataset = load_dataset("openai/gsm8k", "main", split="train")
dataset = dataset.map(
lambda x: {"prompt": [{"role": "user", "content": x["question"]}]},
remove_columns=dataset.column_names,
)
# 2. Configure distillation
config = DistillationConfig(
output_dir="results/distill-qwen-gsm8k",
num_train_epochs=1,
bf16=True,
save_strategy="no",
# Distillation
beta=1.0, # reverse KL
# Teacher
teacher_model_init_kwargs={"dtype": "bfloat16"},
)
# 3. Train
trainer = DistillationTrainer(
model="Qwen/Qwen2.5-1.5B-Instruct",
teacher_model="Qwen/Qwen2.5-7B-Instruct",
args=config,
train_dataset=dataset,
)
trainer.train()
trainer.save_model()
Usage tips
The experimental.distillation.DistillationTrainer trains the student fully on-policy: the student generates its own completions and learns to match the teacher's next-token distribution on them. The key parameter is set via experimental.distillation.DistillationConfig:
beta: controls the interpolation in the Generalized Jensen-Shannon Divergence. Whenbeta=0.0the loss approximates forward KL divergence, whilebeta=1.0approximates reverse KL divergence. Values in between interpolate.
On-policy generation
Fully on-policy training generally outperforms off-policy distillation because the student learns from its own mistakes rather than imitating trajectories it may never produce. The generation buffer keeps this efficient: prompts across gradient accumulation steps are batched into a single vLLM call.
Expected dataset type
The dataset should be formatted as a conversational prompt-only dataset. The student generates its own completions on-policy, so only the prompt is needed:
{"prompt": [{"role": "user", "content": "What color is the sky?"}]}
Example script
Use examples/scripts/distillation.py to launch distillation training from the command line. The script supports full training and LoRA via the standard ModelConfig flags.
# Full training:
python examples/scripts/distillation.py \
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
--teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
--dataset_name trl-lib/ultrafeedback-prompt \
--learning_rate 2e-5 \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 8 \
--output_dir distilled-model \
--num_train_epochs 1
# LoRA:
python examples/scripts/distillation.py \
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
--teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
--dataset_name trl-lib/ultrafeedback-prompt \
--learning_rate 2e-4 \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 8 \
--output_dir distilled-model \
--num_train_epochs 1 \
--use_peft \
--lora_r 64 \
--lora_alpha 16
DistillationTrainer[[trl.experimental.distillation.DistillationTrainer]]
Trainer for knowledge distillation from a teacher model to a student model.
Supports:
Generalized JSD loss (forward KL, reverse KL, or interpolated JSD via
beta)On-policy distillation: the student generates completions, the teacher scores them
Local teacher model
Student on-policy generation via vLLM or model.generate()
Liger kernel for memory-efficient fused JSD loss
resume_from_checkpoint (
strorbool, optional) -- If astr, local path to a saved checkpoint as saved by a previous instance ofTrainer. If abooland equalsTrue, load the last checkpoint in args.output_dir as saved by a previous instance ofTrainer. If present, training will resume from the model/optimizer/scheduler states loaded here.trial (
optuna.Trialordict[str, Any], optional) -- The trial run or the hyperparameter dictionary for hyperparameter search.ignore_keys_for_eval (
list[str], optional) -- A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.~trainer_utils.TrainOutputObject containing the global step count, training loss, and metrics.
Main training entry point.
Will save the model, so you can reload it using from_pretrained().
Will only save from the main process.
- commit_message (
str, optional, defaults to"End of training") -- Message to commit while pushing. - blocking (
bool, optional, defaults toTrue) -- Whether the function should return only when thegit pushhas finished. - token (
str, optional, defaults toNone) -- Token with write permission to overwrite Trainer's original args. - revision (
str, optional) -- The git revision to commit from. Defaults to the head of the "main" branch. - kwargs (
dict[str, Any], optional) -- Additional keyword arguments passed along to~Trainer.create_model_card.The URL of the repository where the model was pushed ifblocking=False, or aFutureobject tracking the progress of the commit ifblocking=True.
Upload self.model and self.processing_class to the 🤗 model hub on the repo self.args.hub_model_id.
DistillationConfig[[trl.experimental.distillation.DistillationConfig]]
"}, {"name": "batch_eval_metrics", "val": ": bool = False"}, {"name": "save_only_model", "val": ": bool = False"}, {"name": "save_strategy", "val": ": transformers.trainer_utils.SaveStrategy | str = 'steps'"}, {"name": "save_steps", "val": ": float = 500"}, {"name": "save_on_each_node", "val": ": bool = False"}, {"name": "save_total_limit", "val": ": int | None = None"}, {"name": "enable_jit_checkpoint", "val": ": bool = False"}, {"name": "push_to_hub", "val": ": bool = False"}, {"name": "hub_token", "val": ": str | None = None"}, {"name": "hub_private_repo", "val": ": bool | None = None"}, {"name": "hub_model_id", "val": ": str | None = None"}, {"name": "hub_strategy", "val": ": transformers.trainer_utils.HubStrategy | str = 'every_save'"}, {"name": "hub_always_push", "val": ": bool = False"}, {"name": "hub_revision", "val": ": str | None = None"}, {"name": "load_best_model_at_end", "val": ": bool = False"}, {"name": "metric_for_best_model", "val": ": str | None = None"}, {"name": "greater_is_better", "val": ": bool | None = None"}, {"name": "ignore_data_skip", "val": ": bool = False"}, {"name": "restore_callback_states_from_checkpoint", "val": ": bool = False"}, {"name": "full_determinism", "val": ": bool = False"}, {"name": "seed", "val": ": int = 42"}, {"name": "data_seed", "val": ": int | None = None"}, {"name": "use_cpu", "val": ": bool = False"}, {"name": "accelerator_config", "val": ": dict | str | None = None"}, {"name": "parallelism_config", "val": ": accelerate.parallelism_config.ParallelismConfig | None = None"}, {"name": "dataloader_drop_last", "val": ": bool = False"}, {"name": "dataloader_num_workers", "val": ": int = 0"}, {"name": "dataloader_pin_memory", "val": ": bool = True"}, {"name": "dataloader_persistent_workers", "val": ": bool = False"}, {"name": "dataloader_prefetch_factor", "val": ": int | None = None"}, {"name": "remove_unused_columns", "val": ": bool = True"}, {"name": "label_names", "val": ": list[str] | None = None"}, {"name": "train_sampling_strategy", "val": ": str = 'random'"}, {"name": "length_column_name", "val": ": str = 'length'"}, {"name": "ddp_find_unused_parameters", "val": ": bool | None = None"}, {"name": "ddp_bucket_cap_mb", "val": ": int | None = None"}, {"name": "ddp_broadcast_buffers", "val": ": bool | None = None"}, {"name": "ddp_static_graph", "val": ": bool | None = None"}, {"name": "ddp_backend", "val": ": str | None = None"}, {"name": "ddp_timeout", "val": ": int = 1800"}, {"name": "fsdp", "val": ": str | None = None"}, {"name": "fsdp_config", "val": ": dict[str, typing.Any] | str | None = None"}, {"name": "deepspeed", "val": ": dict | str | None = None"}, {"name": "debug", "val": ": str | list[transformers.debug_utils.DebugOption] = ''"}, {"name": "skip_memory_metrics", "val": ": bool = True"}, {"name": "do_train", "val": ": bool = False"}, {"name": "do_eval", "val": ": bool = False"}, {"name": "do_predict", "val": ": bool = False"}, {"name": "resume_from_checkpoint", "val": ": str | None = None"}, {"name": "warmup_ratio", "val": ": float | None = None"}, {"name": "logging_dir", "val": ": str | None = None"}, {"name": "local_rank", "val": ": int = -1"}, {"name": "model_init_kwargs", "val": ": dict[str, typing.Any] | str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "temperature", "val": ": float = 1.0"}, {"name": "beta", "val": ": float = 1.0"}, {"name": "max_completion_length", "val": ": int = 512"}, {"name": "disable_dropout", "val": ": bool = True"}, {"name": "teacher_model_name_or_path", "val": ": str | None = None"}, {"name": "teacher_model_revision", "val": ": str | None = None"}, {"name": "teacher_model_init_kwargs", "val": ": dict[str, typing.Any] | str | None = None"}, {"name": "num_generations", "val": ": int = 1"}, {"name": "generation_batch_size", "val": ": int | None = None"}, {"name": "top_p", "val": ": float = 1.0"}, {"name": "top_k", "val": ": int = 0"}, {"name": "min_p", "val": ": float | None = None"}, {"name": "generation_kwargs", "val": ": dict | None = None"}, {"name": "chat_template_kwargs", "val": ": dict | None = None"}, {"name": "repetition_penalty", "val": ": float = 1.0"}, {"name": "cache_implementation", "val": ": str | None = None"}, {"name": "pad_to_multiple_of", "val": ": int | None = None"}, {"name": "shuffle_dataset", "val": ": bool | None = True"}, {"name": "ds3_gather_for_generation", "val": ": bool = True"}, {"name": "use_vllm", "val": ": bool = False"}, {"name": "vllm_mode", "val": ": str = 'colocate'"}, {"name": "vllm_server_base_url", "val": ": str | None = None"}, {"name": "vllm_server_host", "val": ": str = '0.0.0.0'"}, {"name": "vllm_server_port", "val": ": int = 8000"}, {"name": "vllm_server_timeout", "val": ": float = 240.0"}, {"name": "vllm_group_port", "val": ": int = 51216"}, {"name": "vllm_gpu_memory_utilization", "val": ": float = 0.3"}, {"name": "vllm_tensor_parallel_size", "val": ": int = 1"}, {"name": "vllm_max_model_length", "val": ": int | None = None"}, {"name": "vllm_model_impl", "val": ": str = 'vllm'"}, {"name": "vllm_structured_outputs_regex", "val": ": str | None = None"}, {"name": "vllm_sync_frequency", "val": ": int = 1"}, {"name": "vllm_enable_sleep_mode", "val": ": bool = False"}, {"name": "log_completions", "val": ": bool = False"}, {"name": "log_completions_steps", "val": ": int = 100"}, {"name": "num_completions_to_print", "val": ": int | None = None"}]}> Parameters that control the model
- model_init_kwargs (
dict[str, Any], optional) -- Keyword arguments forAutoModelForCausalLM.from_pretrained, used when themodelargument of the trainer is provided as a string. - trust_remote_code (
bool, optional, defaults toFalse) -- Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to from_pretrained and from_pretrained, for both the student and teacher.
Parameters that control the distillation
- temperature (
float, optional, defaults to1.0) -- Temperature for sampling during generation and for computing the distillation loss. Higher values produce softer probability distributions. - beta (
float, optional, defaults to1.0) -- Interpolation coefficient for the Generalized Jensen-Shannon Divergence loss. When0.0, the loss is the forward KL divergence. When1.0, the loss is the reverse KL divergence. When0.5, it is the standard JSD. - max_completion_length (
int, optional, defaults to512) -- Maximum number of tokens to generate per completion during on-policy generation. - disable_dropout (
bool, optional, defaults toTrue) -- Whether to disable dropout in the student model during training.
Parameters that control the teacher model
teacher_model_name_or_path (
strorNone, optional) -- Model name or path for the teacher model. Used when the teacher is loaded locally.teacher_model_revision (
strorNone, optional) -- Model revision of the teacher model (e.g., branch name, tag, or commit hash).teacher_model_init_kwargs (
dict[str, Any]orNone, optional) -- Keyword arguments passed toAutoModelForCausalLM.from_pretrainedwhen instantiating the teacher model from a string. Parameters that control on-policy generationnum_generations (
int, optional, defaults to1) -- Number of completions to generate per prompt during on-policy generation.generation_batch_size (
intorNone, optional) -- Number of unique prompts per worker per optimizer step. IfNone, computed from(per_device_train_batch_size * gradient_accumulation_steps) // num_generations.top_p (
float, optional, defaults to1.0) -- Top-p (nucleus) sampling parameter for on-policy generation.top_k (
int, optional, defaults to0) -- Top-k sampling parameter for on-policy generation.0disables top-k filtering.min_p (
float, optional) -- Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between0.0and1.0. Typical values are in the0.01-0.2range.generation_kwargs (
dict[str, Any], optional) -- Additional keyword arguments to pass to GenerationConfig (if using transformers) orSamplingParams(if using vLLM) when sampling completions. This can be used to further customize the generation behavior, such as settingsuppress_tokens,num_beams, etc. If it contains keys that conflict with the other generation parameters (likemin_p,top_p, etc.), they will override them.chat_template_kwargs (
dict[str, Any], optional) -- Additional keyword arguments to pass to theapply_chat_templatefunction when generating completions.repetition_penalty (
float, optional, defaults to1.0) -- Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values >1.0encourage the model to use new tokens, while values <1.0encourage the model to repeat tokens.cache_implementation (
str, optional) -- Implementation of the cache method for faster generation whenuse_vllmis set toFalse.pad_to_multiple_of (
int, optional) -- If set, the prompts ids and completions ids will be padded to a multiple of this value.shuffle_dataset (
bool, optional, defaults toTrue) -- Whether to shuffle the training dataset.ds3_gather_for_generation (
bool, optional, defaults toTrue) -- This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation.
Parameters that control vLLM for student generation
- use_vllm (
bool, optional, defaults toFalse) -- Whether to use vLLM for generating on-policy completions from the student model. - vllm_mode (
str, optional, defaults to"colocate") -- Mode for student vLLM integration. Either"server"or"colocate". - vllm_server_base_url (
strorNone, optional) -- Base URL for the student vLLM server. If provided,vllm_server_hostandvllm_server_portare ignored. - vllm_server_host (
str, optional, defaults to"0.0.0.0") -- Host of the student vLLM server. - vllm_server_port (
int, optional, defaults to8000) -- Port of the student vLLM server. - vllm_server_timeout (
float, optional, defaults to240.0) -- Timeout for connecting to the student vLLM server. - vllm_group_port (
int, optional, defaults to51216) -- Port for the vLLM weight-update group (NCCL communicator). - vllm_gpu_memory_utilization (
float, optional, defaults to0.3) -- GPU memory utilization for the colocated student vLLM engine. - vllm_tensor_parallel_size (
int, optional, defaults to1) -- Tensor parallel size for the colocated student vLLM engine. - vllm_max_model_length (
intorNone, optional) -- Maximum model sequence length for the colocated vLLM engine. - vllm_model_impl (
str, optional, defaults to"vllm") -- Model implementation backend for vLLM. Use"vllm"or"transformers". - vllm_structured_outputs_regex (
strorNone, optional) -- Regex pattern for vLLM structured outputs. - vllm_sync_frequency (
int, optional, defaults to1) -- Frequency (in training steps) to synchronize student model weights to the vLLM engine. - vllm_enable_sleep_mode (
bool, optional, defaults toFalse) -- Enable vLLM sleep mode to offload student weights during the optimizer step.
Parameters that control logging
- log_completions (
bool, optional, defaults toFalse) -- Whether to log a sample of (prompt, completion) pairs everylog_completions_stepssteps. Ifrichis installed, it prints the sample. Ifwandband/ortrackiologging is enabled, it logs it towandband/ortrackio. - log_completions_steps (
int, optional, defaults to100) -- Number of steps between logging completions. Only used iflog_completionsisTrue. - num_completions_to_print (
intorNone, optional) -- Number of completions to print. IfNone, all completions are logged.
Configuration class for the DistillationTrainer.
Extends TrainingArguments with parameters specific to knowledge distillation. This config is independent of SFTConfig — all necessary fields are declared here.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
Xet Storage Details
- Size:
- 20.9 kB
- Xet hash:
- fdcd67e083d3efe5e26f3064c71c0e0ee0e3df47345b42657c4c1d24425e335c
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.