TRL documentation
Distillation Trainer
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.
The abstract from the paper is the following:
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. It generates the student’s completions on-policy (optionally vLLM-powered) and matches the teacher over its full next-token distribution with a memory-efficient chunked Jensen-Shannon divergence loss, so the teacher’s dense distribution is never materialized in full.
This trainer was contributed by Carlos Miguel Patiño.
For an async counterpart that decouples generation from training and scores against a teacher served over HTTP instead of a local forward pass, see AsyncDistillationTrainer.
Quick start
This example demonstrates how to train a model using the distillation method. We distill a Qwen 2.5 0.5B Instruct model from a Qwen 2.5 1.5B Instruct teacher on the prompts from the UltraFeedback prompt dataset. You can view the data in the dataset here:
Below is the script to train the model.
# train_distillation.py
from datasets import load_dataset
from trl import DistillationTrainer
dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train")
trainer = DistillationTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
teacher_model="Qwen/Qwen2.5-1.5B-Instruct",
train_dataset=dataset,
)
trainer.train()Execute the script using the following command:
torchrun --nproc_per_node 8 train_distillation.py
Looking deeper into the distillation method
On-policy knowledge distillation trains a student to reproduce a teacher’s next-token distribution on completions the student generates itself, rather than on a fixed set of teacher outputs. Learning from its own generations lets the student correct its own mistakes, which generally outperforms off-policy distillation. This section breaks down how it works in practice, covering the two key steps: generating completions and computing the loss.
Generating completions
At each training step, the student generates a batch of completions for the sampled prompts.
Computing the loss
The loss is the generalized Jensen-Shannon divergence (JSD) between the student distribution and the teacher distribution over the generated completion tokens, interpolated by beta and defined as:
where is the -mixture of the two distributions. The endpoints reduce to the pure divergences: beta=0.0 gives the forward KL and beta=1.0 the reverse KL .
In practice, the projection to vocabulary logits and the divergence are computed in chunks, so peak activation memory does not scale with the full vocabulary × sequence-length logits tensor. See Reducing Memory Usage.
Expected dataset type
The dataset should be a prompt-only dataset, in either standard or conversational format. The student generates its own completions on-policy, so only the prompt is needed:
{"prompt": [{"role": "user", "content": "What color is the sky?"}]}Logged metrics
While training and evaluating, we record the following metrics:
num_tokens: The total number of tokens processed so far, including both prompts and completions. When using tools, only non-tool tokens are counted.step_time: The average time (in seconds) taken per training step (including generation).completions/mean_length: The average length of generated completions. When using tools, only non-tool tokens are counted.completions/min_length: The minimum length of generated completions. When using tools, only non-tool tokens are counted.completions/max_length: The maximum length of generated completions. When using tools, only non-tool tokens are counted.completions/mean_terminated_length: The average length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.completions/min_terminated_length: The minimum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.completions/max_terminated_length: The maximum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.completions/clipped_ratio: The ratio of truncated (clipped) completions.tools/call_frequency: The average number of tool calls per completion in the generation batch. Logged only whentoolsare provided.tools/failure_frequency: The fraction of tool calls that failed (the tool was not found, raised an exception, or the call type is unsupported). It is0.0when no tool was called. Logged only whentoolsare provided.rewards/{EnvironmentClass}/mean: The average value returned by the environment’sget_rewardover the rollouts bound to that environment class. Logged only when anenvironment_factorydefinesget_reward, and never used in the loss.rewards/{EnvironmentClass}/std: The standard deviation of the value returned byget_reward, over the same rollouts.entropy: Average entropy of token predictions across generated completions (in nats).teacher/<id>/jsd: The mean per-token divergence against teacher<id>, or NaN when no example was routed to it. Logged only when several teachers are passed.teacher/<id>/token_frac: The fraction of completion tokens scored by teacher<id>. Logged only when several teachers are passed.
Customization
Speed up training with vLLM-powered generation
Generation is often the main bottleneck when training with on-policy methods. To accelerate generation, you can use vLLM, a high-throughput, low-latency inference engine for LLMs. To enable it, first install the package with
pip install trl[vllm]
We support two ways of using vLLM during training: colocate mode and server mode.
Option 1: Colocate mode
In this mode, vLLM runs inside the trainer process and shares GPU memory with the training model. This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode.
from trl import DistillationConfig
training_args = DistillationConfig(
...,
use_vllm=True, # vllm_mode="colocate" by default
)Option 2: Server mode
In this mode, vLLM runs in a separate process (and using separate GPUs) and communicates with the trainer via HTTP. This is ideal if you have dedicated GPUs for inference.
Start the vLLM server:
VLLM_SERVER_DEV_MODE=1 vllm serve <model_name> --gpu-memory-utilization 0.9 \ --weight-transfer-config '{"backend": "nccl"}' \ --logprobs-mode processed_logprobs \ --max-logprobs -1Enable server mode in your training script:
from trl import DistillationConfig training_args = DistillationConfig( ..., use_vllm=True, vllm_mode="server", )
Make sure that the server is using different GPUs than the trainer, otherwise you may run into NCCL errors. You can specify the GPUs to use with the
CUDA_VISIBLE_DEVICESenvironment variable.
Depending on the model size and the overall GPU memory requirements for training, you may need to adjust the
vllm_gpu_memory_utilizationparameter in DistillationConfig to avoid underutilization or out-of-memory errors.
For more information, see Speeding up training with vLLM.
Train adapters with PEFT
We support tight integration with the 🤗 PEFT library, letting you train adapters and share them on the Hub rather than training the whole student.
from datasets import load_dataset
from trl import DistillationTrainer
from peft import LoraConfig
dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train")
trainer = DistillationTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
teacher_model="Qwen/Qwen2.5-1.5B-Instruct",
train_dataset=dataset,
peft_config=LoraConfig(),
)
trainer.train()The distillation loss reads
lm_head.weightdirectly and runs the student backbone without going throughPeftModel.forward(). Adapters onlm_head(viatarget_modules) and prompt-learning methods (PromptTuning, PrefixTuning, P-Tuning) are therefore rejected, since they would be silently ignored. To train the head, usemodules_to_save=["lm_head"]instead.
Multiple teachers
To distill several frozen domain experts (e.g. a math expert and a code expert) into a single student, as in MOPD, pass a dictionary mapping teacher IDs to teachers instead of a single teacher. Each example selects its teacher through a teacher_id column, and its completion is scored by that teacher only. Every teacher must share the student’s vocabulary, and is prepared like a single teacher, so DeepSpeed ZeRO-3 shards (and optionally offloads) each of them. FSDP is not supported with a teacher mapping.
from datasets import Dataset
from trl import DistillationConfig, DistillationTrainer
dataset = Dataset.from_dict(
{
"prompt": [
[{"role": "user", "content": "What is the derivative of x^2?"}],
[{"role": "user", "content": "Write a function that reverses a string."}],
],
"teacher_id": ["math", "code"],
}
)
trainer = DistillationTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
teacher_model={
"math": "Qwen/Qwen2.5-Math-1.5B-Instruct",
"code": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
},
args=DistillationConfig(output_dir="mopd-student", teacher_model_init_kwargs={"code": {"dtype": "bfloat16"}}),
train_dataset=dataset,
)
trainer.train()Agent Training
DistillationTrainer supports agent training: the student calls tools during generation and is distilled on the resulting trajectory. Tool-result tokens are masked out of the loss, so the student is only trained on the tokens it generated itself.
Tools
The tools argument expects a list of Python functions that define the tools available to the agent:
from trl import DistillationTrainer
trainer = DistillationTrainer(
tools=[tool1, tool2],
...,
)Each tool must be a standard Python function with type-hinted arguments and return types, along with a Google-style docstring describing its purpose, arguments, and return value. For more details, see the Passing tools guide.
The tool call loop requires the chat template to be prefix-preserving (appending a tool message must not change how earlier messages are rendered). For known model families (e.g. Qwen3, DeepSeek-V3), TRL automatically swaps in a patched training template when tools are enabled. See Chat Templates for the full list.
Use max_tool_calling_iterations in the DistillationConfig to cap the number of tool-calling turns. By default there is no limit, and generation stops when the student produces a response turn with no tool calls, when the completion (all turns and tool results) reaches max_completion_length tokens, or when the full sequence reaches the model’s maximum length (vllm_max_model_length with vllm_mode="colocate", the model’s max_position_embeddings otherwise).
Example:
from trl import DistillationTrainer
def multiply(a: int, b: int) -> int:
"""
Multiplies two integers.
Args:
a: The first integer.
b: The second integer.
Returns:
The product of the two integers.
"""
return a * b
trainer = DistillationTrainer(
tools=[multiply],
...,
)Async tools are not supported yet — pass synchronous functions.
Environments
You can also provide tools through environment_factory. In this mode, DistillationTrainer creates one environment instance per rollout and exposes the environment’s public methods as tools. The student runs a multi-turn episode against its own instance, the teacher scores every token the student generated with the whole episode (tool results included) as context, and the tool-result tokens are masked out of the loss.
environment_factoryrequirestransformers>=5.2.0.
The trainer keeps one environment instance per rollout in the generation batch, so
per_device_train_batch_size × gradient_accumulation_steps × num_processesinstances exist at once across processes (more ifper_device_eval_batch_sizeis larger), reused between batches. If each instance opens a session on a remote environment server (as with OpenEnv), that server must accept that many concurrent sessions. See Server concurrency.
Per rollout, the trainer samples one row of the train_dataset, uses its "prompt" column as the prompt, and passes the row’s other columns to reset() as keyword arguments, so the environment reads the task from the dataset.
from datasets import Dataset
from trl import DistillationConfig, DistillationTrainer
# Each row carries the prompt and the task data (here, the counter target to reach).
targets = [i % 6 + 1 for i in range(64)]
dataset = Dataset.from_dict(
{
"prompt": [[{"role": "user", "content": f"Increment the counter to {t}."}] for t in targets],
"target": targets,
}
)
class IncrementEnv:
# Reserved methods
def reset(self, target, **kwargs) -> str | None: # required; the row's `target` column arrives as a keyword argument
self.counter = 0
self.target = target
return None # a returned string is appended to the last user message
def get_reward(self) -> float: # optional: logged, never used in the loss
return float(self.counter == self.target)
# Public methods (exposed as tools)
def increment(self, step: int) -> int:
"""
Increment the internal counter.
Args:
step: Value to add to the counter.
Returns:
The updated counter value.
"""
self.counter += step
return self.counter
trainer = DistillationTrainer(
model="Qwen/Qwen3-0.6B",
teacher_model="Qwen/Qwen3-4B",
args=DistillationConfig(max_tool_calling_iterations=4, chat_template_kwargs={"enable_thinking": False}),
train_dataset=dataset,
environment_factory=IncrementEnv,
)
trainer.train()The counter task is solved in one tool call, so it only shows the API. For a task where the later turns matter, see the distillation_data_analysis_env example and its comparison of whole episodes against the first turn.
An environment class has two reserved methods: reset and get_reward. Unlike any other public methods, these are not exposed to the model as tools.
reset(required) is called when the rollout starts. It can return eitherNoneor a string. In distillation, when it returns a string, that string is appended to the last user message.get_reward(optional) takes no argument and returns afloat. Distillation has no reward, so it is called once per completed rollout only to log the episode’s score asrewards/{EnvironmentClass}/mean, which is handy to follow task success while the loss goes down. It also lets an environment release per-episode resources. It runs on every rollout, so an expensiveget_reward(for example one that runs a test suite) adds to the time of every step.
With tools,
max_completion_lengthis the budget for the whole episode: every model turn plus every tool result. Tool results are masked out of the loss but still count toward it, and they can take most of it, for example when tools return tables or tracebacks, as in thedistillation_data_analysis_envexample. Size it for the episode rather than for a single answer. A tool result that would overflow the budget is dropped and the episode ends there.
To mix several environments in one run, pass a dictionary mapping environment names to factories and add an environment column to the dataset, as for GRPOTrainer: each rollout only sees the tools of its own environment, and the environment field is not forwarded to reset, nor is the teacher_id field with multiple teachers. Instances are reused across steps (reset between episodes), so an expensive __init__ is paid once. The distillation_data_analysis_env example distills a data-analysis agent in OpenEnv’s data-analysis environment.
Async environment methods (tools or
get_reward) are not supported yet, and thetrain_datasetis required: the environment cannot own the data as with GRPOTrainer.
Multimodal Tool Responses
Tools can return images alongside text by returning a list of content blocks. This is useful for VLM agent training where the tool provides visual feedback (e.g., screenshots, plots, camera captures).
from PIL import Image
def take_screenshot() -> list:
"""
Takes a screenshot of the current screen.
Returns:
The screenshot image with a description.
"""
img = Image.open("screenshot.png")
return [{"type": "image", "image": img}, {"type": "text", "text": "Here is the screenshot."}]The returned images are automatically injected into the conversation and passed to the VLM for subsequent generation turns.
Training Vision Language Models
DistillationTrainer supports distilling Vision-Language Models (VLMs) on multimodal datasets containing both text and images. Pass a VLM as both the student and the teacher, and provide a prompt-only dataset with either an image column (single image per sample) or an images column (list of images per sample). For more information on the expected dataset structure, see the Dataset Format — Vision datasets section.
Tested with:
- Gemma 3 — e.g.,
google/gemma-3-4b-it - LLaVA-NeXT — e.g.,
llava-hf/llava-v1.6-mistral-7b-hf - Qwen2-VL — e.g.,
Qwen/Qwen2-VL-2B-Instruct - Qwen2.5-VL — e.g.,
Qwen/Qwen2.5-VL-3B-Instruct
Compatibility with all VLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes.
Command line interface
Use the trl distillation CLI to launch distillation training from the command line. It supports full training and LoRA via the standard ModelConfig flags.
# Full training:
trl distillation \
--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:
trl distillation \
--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 16DistillationTrainer
class trl.DistillationTrainer
< source >( model: str | PreTrainedModel | PeftModelteacher_model: str | transformers.modeling_utils.PreTrainedModel | dict[str, str | transformers.modeling_utils.PreTrainedModel] | None = Noneargs: trl.trainer.distillation_config.DistillationConfig | None = Nonetrain_dataset: datasets.arrow_dataset.Dataset | None = Noneeval_dataset: datasets.arrow_dataset.Dataset | dict[str, datasets.arrow_dataset.Dataset] | None = Noneprocessing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | transformers.processing_utils.ProcessorMixin | None = Nonecallbacks: list[transformers.trainer_callback.TrainerCallback] | None = Noneoptimizers: tuple[typing.Optional[torch.optim.Optimizer], typing.Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None)quantization_config: BitsAndBytesConfig | None = Nonepeft_config: PeftConfig | None = Nonetools: list[collections.abc.Callable] | None = Noneenvironment_factory: collections.abc.Callable[[], trl.trainer.distillation_trainer._SupportsReset] | dict[str, collections.abc.Callable[[], trl.trainer.distillation_trainer._SupportsReset]] | None = None )
Parameters
- model (
stror PreTrainedModel or PeftModel) — Model to be trained. Can be either:- A string, being the model id of a pretrained model hosted inside a model repo on huggingface.co, or a
path to a directory containing model weights saved using
save_pretrained, e.g.,
'./my_model_directory/'. The model is loaded using<ModelArchitecture>.from_pretrained(where<ModelArchitecture>is derived from the model config) with the keyword arguments inargs.model_init_kwargs. Ifdtypeis not specified inargs.model_init_kwargs, it defaults tofloat32. This differs from from_pretrained, where (since Transformers v5) the dtype is inferred from the model config. - A PreTrainedModel object. Only causal language models are supported.
- A PeftModel object. Only causal language models are supported.
- A string, being the model id of a pretrained model hosted inside a model repo on huggingface.co, or a
path to a directory containing model weights saved using
save_pretrained, e.g.,
- teacher_model (
str, PreTrainedModel ordict[str, str | PreTrainedModel], optional) — Teacher model whose next-token distribution the student is trained to match. Can be a model id / path (loaded likemodel, usingargs.teacher_model_init_kwargs), an instantiated PreTrainedModel, or a mapping from teacher ID to either of those, in which case theteacher_idcolumn of each row selects its teacher. Every teacher must share the student’s vocabulary. May be omitted by subclasses that supply the teacher another way (e.g. a remote server). - args (DistillationConfig, optional) —
Configuration for this trainer. If
None, a default configuration is used. - train_dataset (Dataset or IterableDataset) —
Dataset to use for training. It must include a column
"prompt". Any additional columns in the dataset is ignored. The format of the samples can be either:- Standard: Each sample contains plain text.
- Conversational: Each sample contains structured messages (e.g., role and content).
When
train_datasetis an IterableDataset (e.g. a streaming dataset),max_stepsmust be set in the training arguments, since its length cannot be inferred and the total number of training steps is required to bound the training loop and configure the learning rate scheduler. - eval_dataset (Dataset, IterableDataset, DatasetDict, IterableDatasetDict or
dict[str, Dataset | IterableDataset]) — Dataset to use for evaluation. It must meet the same requirements astrain_dataset. - processing_class (PreTrainedTokenizerBase, ProcessorMixin, optional) —
Processing class used to process the data. The padding side must be set to “left”. If
None, the processing class is loaded from the model’s name with from_pretrained. A padding token,tokenizer.pad_token, must be set. If the processing class has not set a padding token,tokenizer.eos_tokenwill be used as the default. - callbacks (list of TrainerCallback, optional) —
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
in here.
If you want to remove one of the default callbacks used, use the remove_callback method.
- optimizers (
tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None], optional, defaults to(None, None)) — A tuple containing the optimizer and the scheduler to use. Will default to an instance ofAdamWon your model and a scheduler given by get_linear_schedule_with_warmup controlled byargs. - quantization_config (BitsAndBytesConfig, optional) —
Quantization configuration used when loading the model from a model identifier. Combine with
peft_configfor QLoRA training. Ignored if the model is already instantiated. - peft_config (PeftConfig, optional) —
PEFT configuration used to wrap the model. If
None, the model is not wrapped. - tools (list of
Callable, optional) — A list of callable tool functions that the model can invoke during generation. Each tool should be a standard Python function with properly type-hinted arguments and return values, and a Google-style docstring describing its purpose, arguments, and return value. For more details, see: https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function’s name, type hints, and docstring to determine how to call it. Ensure that the model’s chat template supports tool use and that it has been fine-tuned for tool calling. - environment_factory (
EnvironmentFactoryordict[str, EnvironmentFactory], optional) — A callable that creates and returns an environment instance, or a dictionary mapping environment names to such callables. The environment class should define methods that can be invoked as tools during generation. Each method should comply with the same requirements as thetoolsdescribed above. The environment must also implement a callableresetmethod that can be used to reset state between generations. Theresetmethod should return eitherNoneor a string: when it returns a string, that string is appended to the last user message before generation. Tool-result tokens are excluded from the loss, but they count towardmax_completion_length, which is the budget for the whole episode. If the environment defines aget_rewardmethod taking no argument and returning afloat, it is called once per rollout and only logged, never used in the loss, so an expensiveget_rewardadds to the time of every step.With a single callable, every example uses the same environment, with one instance per rollout so their interactions stay isolated. With a dictionary, each example must carry an
environmentfield selecting its environment by name, and only that environment’s tools are exposed in its prompt — letting a single run mix tasks (e.g. a coding environment and a game). This feature is experimental and may change or be removed at any time without prior notice.
Trainer for knowledge distillation. The student is trained on-policy — it generates the completions itself — to
match the teacher’s next-token distribution under a generalized Jensen-Shannon divergence (interpolating forward
KL, reverse KL, and JSD via beta), as introduced in On-Policy Distillation of Language
Models.
Example:
>>> from trl import DistillationTrainer
>>> from datasets import load_dataset
>>> dataset = load_dataset("trl-lib/tldr", split="train")
>>> trainer = DistillationTrainer(
... model="Qwen/Qwen2.5-0.5B-Instruct",
... teacher_model="Qwen/Qwen2.5-1.5B-Instruct",
... train_dataset=dataset,
... )
>>> trainer.train()train
< source >( resume_from_checkpoint: str | bool | None = Nonetrial: optuna.Trial | dict[str, Any] | None = Noneignore_keys_for_eval: list[str] | None = None ) → ~trainer_utils.TrainOutput
Parameters
- 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.
Returns
~trainer_utils.TrainOutput
Object 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.
push_to_hub
< source >( commit_message: str | None = 'End of training'blocking: bool = Truetoken: str | None = Nonerevision: str | None = Noneprivate: bool | None = None**kwargs )
Parameters
- 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. - private (
bool, optional) — Whether to make the repo private when it is created. Defaults toargs.hub_private_repo. Has no effect if the repo already exists. - kwargs (
dict[str, Any], optional) — Additional keyword arguments passed along to~Trainer.create_model_card.
Upload self.model and self.processing_class to the 🤗 model hub on the repo self.args.hub_model_id.
DistillationConfig
class trl.DistillationConfig
< source >( output_dir: str | None = Noneper_device_train_batch_size: int = 8num_train_epochs: float = 3.0max_steps: int = -1learning_rate: float = 1e-06lr_scheduler_type: transformers.trainer_utils.SchedulerType | str = 'linear'lr_scheduler_kwargs: dict | str | None = Nonewarmup_steps: float = 0optim: transformers.training_args.OptimizerNames | str = 'adamw_torch_fused'optim_args: str | None = Noneweight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08optim_target_modules: None | str | list[str] = Nonegradient_accumulation_steps: int = 1average_tokens_across_devices: bool = Truemax_grad_norm: float = 1.0label_smoothing_factor: float = 0.0bf16: bool | None = Nonefp16: bool = Falsebf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: bool | None = Noneactivation_checkpointing: bool | None = Noneactivation_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonegradient_checkpointing: bool | None = Nonegradient_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonetorch_compile: bool = Falsetorch_compile_backend: str | None = Nonetorch_compile_mode: str | None = Noneuse_liger_kernel: bool = Falseliger_kernel_config: dict[str, bool] | None = Noneuse_cache: bool = Falseneftune_noise_alpha: float | None = Nonetorch_empty_cache_steps: int | None = Noneauto_find_batch_size: bool = Falselogging_strategy: transformers.trainer_utils.IntervalStrategy | str = 'steps'logging_steps: float = 10logging_first_step: bool = Falselog_on_each_node: bool = Truelogging_nan_inf_filter: bool = Trueinclude_num_input_tokens_seen: str | bool = 'no'log_level: str = 'passive'log_level_replica: str = 'warning'disable_tqdm: bool | None = Nonereport_to: None | str | list[str] = 'none'run_name: str | None = Noneproject: str = 'huggingface'trackio_space_id: str | None = Nonetrackio_bucket_id: str | None = Nonetrackio_static_space_id: typing.Union[str, NoneType, typing.Literal[False]] = Noneeval_strategy: transformers.trainer_utils.IntervalStrategy | str = 'no'eval_steps: float | None = Noneeval_delay: float = 0per_device_eval_batch_size: int = 8prediction_loss_only: bool = Falseeval_on_start: bool = Falseeval_do_concat_batches: bool = Trueeval_use_gather_object: bool = Falseeval_accumulation_steps: int | None = Noneinclude_for_metrics: list[str] = <factory>batch_eval_metrics: bool = Falsesave_only_model: bool = Falsesave_strategy: transformers.trainer_utils.SaveStrategy | str = 'steps'save_steps: float = 500save_on_each_node: bool = Falsesave_total_limit: int | None = Noneenable_jit_checkpoint: bool = Falsepush_to_hub: bool = Falsehub_token: str | None = Nonehub_private_repo: bool | None = Nonehub_model_id: str | None = Nonehub_strategy: transformers.trainer_utils.HubStrategy | str = 'every_save'hub_always_push: bool = Falsehub_revision: str | None = Noneload_best_model_at_end: bool = Falsemetric_for_best_model: str | None = Nonegreater_is_better: bool | None = Noneignore_data_skip: bool = Falserestore_callback_states_from_checkpoint: bool = Falsefull_determinism: bool = Falseseed: int = 42data_seed: int | None = Noneuse_cpu: bool = Falseaccelerator_config: dict | str | None = Noneparallelism_config: accelerate.parallelism_config.ParallelismConfig | None = Nonedataloader_drop_last: bool = Falsedataloader_num_workers: int = 0dataloader_pin_memory: bool = Truedataloader_persistent_workers: bool = Falsedataloader_prefetch_factor: int | None = Nonedataloader_multiprocessing_context: str | None = Nonedataloader_in_order: bool = Trueremove_unused_columns: bool | None = Falselabel_names: list[str] | None = Nonetrain_sampling_strategy: str = 'random'length_column_name: str = 'length'ddp_find_unused_parameters: bool | None = Noneddp_bucket_cap_mb: int | None = Noneddp_broadcast_buffers: bool | None = Noneddp_static_graph: bool | None = Noneddp_backend: str | None = Noneddp_timeout: int = 1800fsdp: str | None = Nonefsdp_config: dict[str, typing.Any] | str | None = Nonedeepspeed: dict | str | None = Nonedebug: str | list[transformers.debug_utils.DebugOption] = ''skip_memory_metrics: bool = Truedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseresume_from_checkpoint: str | None = Nonelocal_rank: int = -1model_init_kwargs: dict[str, typing.Any] | str | None = Nonetrust_remote_code: bool = Falseteacher_model_name_or_path: dict[str, str] | str | None = Noneteacher_model_revision: str | None = Noneteacher_model_init_kwargs: dict[str, typing.Any] | str | None = Nonedisable_dropout: bool = Falsemax_completion_length: int | None = 512ds3_gather_for_generation: bool = Trueshuffle_dataset: bool | None = Truepad_to_multiple_of: int | str | None = 'auto'temperature: float = 1.0top_p: float = 1.0top_k: int = 0min_p: float | None = Nonegeneration_kwargs: dict | str | None = Nonechat_template_kwargs: dict | str | None = Nonerepetition_penalty: float = 1.0cache_implementation: str | None = Noneuse_vllm: bool = Falsevllm_mode: str = 'colocate'vllm_model_impl: str = 'vllm'vllm_enable_sleep_mode: bool = Falsevllm_structured_outputs_regex: str | None = Nonevllm_server_base_url: str | None = Nonevllm_server_host: str = '0.0.0.0'vllm_server_port: int = 8000vllm_server_timeout: float = 240.0vllm_group_port: int = 51216vllm_gpu_memory_utilization: float = 0.3vllm_max_model_length: int | None = Nonevllm_tensor_parallel_size: int = 1beta: float = 1.0max_tool_calling_iterations: int | None = Nonelog_completions: bool = Falsenum_completions_to_print: int | None = Nonelog_unique_prompts: bool = False )
Parameters that control the model and the teacher model
- model_init_kwargs (
strordict[str, Any], optional) — Keyword arguments forAutoModelForCausalLM.from_pretrained, used when themodelargument of the trainer is provided as a string. Therevisionvalue is also used when loading the processing class. - 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. - teacher_model_name_or_path (
strordict[str, str], optional) — Model name or path for the teacher model. Used when the teacher is loaded locally. A mapping from teacher ID to model name or path uses several teachers, where theteacher_idcolumn of each row selects its teacher. - teacher_model_revision (
str, optional) — Model revision of the teacher model (e.g., branch name, tag, or commit hash). - teacher_model_init_kwargs (
strordict[str, Any], optional) — Keyword arguments passed toAutoModelForCausalLM.from_pretrainedwhen instantiating the teacher model from a string. Whenteacher_model_name_or_pathis a mapping, provide a mapping from teacher ID to loading kwargs instead, e.g.{"math": {"dtype": "bfloat16"}, "code": {"revision": "main"}}. Omitted teachers use the default loading kwargs. - disable_dropout (
bool, optional, defaults toFalse) — Whether to disable dropout in the student model during training.
Parameters that control the data preprocessing
- remove_unused_columns (
bool, optional, defaults toFalse) — Whether to remove dataset columns other than"prompt","image","images","teacher_id", and"environment". - max_completion_length (
intorNone, optional, defaults to512) — Maximum number of tokens to generate per completion during on-policy generation. Withtoolsorenvironment_factory, it caps the whole multi-turn completion after the prompt (all model turns plus tool results). - 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. - shuffle_dataset (
bool, optional, defaults toTrue) — Whether to shuffle the training dataset. - pad_to_multiple_of (
intorstr, optional, defaults to"auto") — If set, the prompts ids and completions ids will be padded to a multiple of this value."auto"pads to a multiple of 128 on Neuron (AWS Trainium), which compiles once per input shape, and does not pad elsewhere.
Parameters that control generation
- temperature (
float, optional, defaults to1.0) — Temperature for sampling during generation and for computing the distillation loss. Higher values produce softer probability distributions. - 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.
Parameters that control generation acceleration powered by vLLM
- 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_model_impl (
str, optional, defaults to"vllm") — Model implementation backend for vLLM. Use"vllm"or"transformers". - vllm_enable_sleep_mode (
bool, optional, defaults toFalse) — Enable vLLM sleep mode to offload student weights during the optimizer step. - vllm_structured_outputs_regex (
str, optional) — Regex pattern for vLLM structured outputs.
Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
- vllm_server_base_url (
str, 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).
Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
- vllm_gpu_memory_utilization (
float, optional, defaults to0.3) — GPU memory utilization for the colocated student vLLM engine. - vllm_max_model_length (
int, optional) — Maximum model sequence length for the colocated vLLM engine. - vllm_tensor_parallel_size (
int, optional, defaults to1) — Tensor parallel size for the colocated student vLLM engine.
Parameters that control the training
- 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. Unlike GRPO’sbeta(a KL-penalty coefficient against a reference model), here it selects the divergence itself; there is no reference-model KL penalty. - max_tool_calling_iterations (
int, optional) — Maximum number of tool-calling turns when training an agent. IfNone, there is no limit and generation stops when the model generates a response turn with no tool calls, when the completion (all turns and tool results) reachesmax_completion_lengthtokens, or when the full sequence reaches the model’s maximum length (vllm_max_model_lengthwithvllm_mode="colocate", the model’smax_position_embeddingsotherwise). When the limit is reached, the tool calls of the last generated turn are not executed and the completion ends with that turn, so a final tool call (for example one that submits an answer) is never executed.
Parameters that control the logging
- log_completions (
bool, optional, defaults toFalse) — Whether to log a sample of (prompt, completion) pairs everylogging_stepssteps. Ifrichis installed, it prints the sample. Ifwandband/ortrackiologging is enabled, it logs it towandband/ortrackio. - num_completions_to_print (
int, optional) — Number of completions to print withrich. IfNone, all completions are logged. - log_unique_prompts (
bool, optional, defaults toFalse) — Whether to log unique prompts. IfTrue, only unique prompts are logged. IfFalse, all prompts are logged.
Configuration class for the DistillationTrainer.
Extends TrainingArguments with parameters specific to knowledge distillation. All necessary fields are declared here.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
These parameters have default values different from TrainingArguments:
logging_steps: Defaults to10instead of500.gradient_checkpointing: Defaults toTrueinstead ofFalse.bf16: Defaults toTrueiffp16is not set, instead ofFalse.learning_rate: Defaults to1e-6instead of5e-5.