Repository navigation
Releases
v1.14.0
Features
trl.losses is gone: DPO, KTO and GRPO stream their own log-probs
Warning
from trl.losses import FusedLinearDPOLoss (or FusedLinearKTOLoss, FusedLinearGRPOLoss, FusedLinearJSDLoss) no longer works. The module introduced in v1.13 has been removed.
v1.13 vendored Liger's chunked_loss into trl.losses as a holding action, not a destination (#7063). The problem it was holding: those classes reimplement each trainer's loss math, so TRL carried two copies of every formula, and copies drift. That drift is where the bugs were. GRPO's grad_norm differed from the default path, KTO ignored the reference model under PEFT, KTO class weights and DPO label_smoothing were silently dropped. Worst of all, under plain DDP the fused path ran the loss on the unwrapped model, so DistributedDataParallel's reducer was never armed and gradients were never all-reduced: every rank silently kept its own.
The fix is to stop reimplementing. All DPO, KTO and GRPO need from the fused path is per-token log-probs of the selected tokens, and TRL already had _ChunkedLogProbFunction for exactly that: it streams the vocabulary with an online logsumexp and recomputes in the backward pass. Each trainer now runs backbone -> _ChunkedLogProbFunction -> its own existing loss code, unchanged. One implementation of each loss, and the memory win is kept, because full logits are still never materialized.
Thirteen restrictions existed only because the loss had been rewritten in a form that could not express those options. Most are gone: DPO with use_liger_kernel=True now accepts mixed loss types, f-divergences and precomputed reference log-probs, and GRPO gains entropy and off-policy masking. Still refused: use_weighting, compute_metrics, a PEFT adapter on lm_head, prompt-learning PEFT, and the MoE auxiliary loss.
Single H100, Qwen3-0.6B, bs=4, seq 512:
| config | median step | peak |
|---|---|---|
| v1.13 fused, inline ref | 0.2243 s | 7.05 GB |
| v1.14 chunked, inline ref | 0.2457 s (+9.5%) | 7.05 GB |
v1.14 chunked, precompute_ref_log_probs=True |
0.1971 s (-12.1%) | 4.83 GB (-31%) |
The third row is the point: that configuration did not exist before, because the fused path rejected precomputed reference log-probs outright.
use_liger_kernel=True still works and still enables Liger's model kernels through transformers. In DPO, GRPO and KTO it now selects TRL's chunked log-probability path instead of Liger's fused loss.
- Stream KTO log probabilities by @kashif in #7075
- Stream GRPO log probabilities by @kashif in #7077
- Move DPO to chunked log probabilities by @kashif in #7243
- Drop the fused Liger JSD path from the experimental distillation trainers by @kashif in #7301
- Skip frozen chunked log probability gradients by @kashif in #7076
- Redirect the KTO liger loss through the distributed wrapper under DDP by @qgallouedec in #7247
- Document what use_liger_kernel actually does in each trainer by @qgallouedec in #7361
A fused Triton logprob + entropy kernel now ships in TRL
The loss head is the only hot path TRL owns: transformers already kernelizes the model internals, and nothing on the Hub covers what happens after the decoder. On one H100 (bf16, V=151936, H=4096, 8192 tokens), selective_log_softmax plus entropy_from_logits cost 12.8 ms and 2.32 GiB over [8, 1024, 151936]. A fused Triton kernel does the same in 0.89 ms, roughly 14x, and lands closer to the fp32 reference than the bf16 path it replaces. GRPO runs this two to four times per step.
It now lives in-tree at trl.kernels and is on by default on CUDA, ROCm and XPU, with the PyTorch implementation as fallback. It was briefly loaded from the Hub; that was reversed because this kernel is pure Triton and compiles at runtime, so the Hub bought nothing while costing a version gate unrelated to whether the kernel works, a download that fails offline, trust_remote_code=True for anyone with kernels installed, a silent except Exception: pass wrapped around all of it, and 13 of 13 tests skipped in CI.
- Use fused kernels for logprobs and entropy by @kashif in #7253
- Move TRL loss kernels into TRL by @kashif in #7266
- Ship the logprob and entropy kernel in trl instead of the Hub by @qgallouedec in #7363
Other
- Ensure device agnostic for examples/docs/templates by @kaixuanliu in #6770
- AsyncGRPO: PEFT/LoRA support with adapter-only vLLM sync by @AmineDiro in #7017
- Add support for vLLM 0.29.0 by @qgallouedec in #7178
- [GOLD] Recommend LFM2.5 and Gemma 4 students by @kashif in #6388
- Add TailSFT example by @kashif in #7212
- [AsyncGRPO] Run sync tools on a thread pool and support async tools by @AmineDiro in #7175
Breaking
Six experimental trainers removed
GRPOWithReplayBufferTrainer, BCOTrainer, PRMTrainer, XPOTrainer, NashMDTrainer and the GSPO-token trainer are gone from trl.experimental.
What changed is not the guarantee, which was always that trl.experimental has none, but the fact that the decision is now written down. Removals used to be argued one pull request at a time, with every thread relitigating the policy before it got to the feature. #7182 settled what the judgment weighs, and #7254 put it in the docs: usage, external issues and pull requests that come from people actually running the feature, whether a stable trainer already covers it, maintenance cost, downstream consumers, owner, and age. Deliberately inputs to a judgment rather than a test: no threshold, no notice cycle, and the numbers stay in the removal pull request where you can check them. A paper index entry outlives the code it described.
The numbers are what make the case. BCOTrainer was 1,600 lines carrying its own reference-model handling, DeepSpeed preparation, tokenization and eval loop, for 11 genuine trainings in two months; it was also the only reason TRL depended on scikit-learn and joblib at all, and both are now gone from pyproject.toml. GRPOWithReplayBufferTrainer had hand-copied _generate_and_score_completions from GRPO and drifted to 385 of 616 lines different, for 8 trainings.
- Remove the experimental BCO trainer by @qgallouedec in #7136
- Remove the experimental GRPO-with-replay-buffer trainer by @qgallouedec in #7132
- Remove the experimental PRM trainer by @qgallouedec in #7133
- Remove the experimental Nash-MD trainer by @albertvillanova in #7255
- Remove the experimental XPO trainer by @albertvillanova in #7256
- Remove the experimental GSPO-token trainer by @albertvillanova in #7331
Also breaking, and covered above: trl.losses was removed along the way.
Fixes
- Gradients were never all-reduced for KTO under plain DDP.
compute_lossredirected through the distributed wrapper only for ZeRO-3 and FSDP, so on plain DDP the loss ran on the unwrapped model,DistributedDataParallel.forward()never ran, its reducer was never armed, and every rank silently kept its own gradients. By @qgallouedec in #7247 - Wrapped packing duplicated data when the input table was sliced.
_pack_wrappedsized the output from the sliced view but read from the raw child buffer, so it re-read from the start of the buffer instead of from the slice, anddatasets.map(batched=True)passes sliced tables. By @qgallouedec in #6670 - A reward function logging on only some ranks hung or crashed the run. GRPO and RLOO looped over the keys each rank held and called one collective per key, so ranks called different collectives:
log_metricon rank 0 alone hung on NCCL, andlog_extracrashed insidegather_objectwith a 1EB allocation. By @behroozazarkhalili in #7382 - Special token ids now reach the config the
Traineractually reads, so it no longer realigns them at train time and logs a change the user did not make (part of #7093): eos in the trainers (#7127), written to the text config for composite models (#7315), the reward model pad token (#7318), and the requested pad token applied to vision datasets (#7316, #7352) - Do not quantize the teacher by default in the distillation and GOLD entry points by @behroozazarkhalili in #6769
- Prepare the dataset once per node when the datasets cache is node-local by @qgallouedec in #7241
- Read the MoE auxiliary loss coefficient from the model config by @qgallouedec in #7248
- Await async reward functions written as callable classes by @albertvillanova in #7213
- Fix two stream races in OffloadActivations by @kashif in #7195
- Only dedupe offloaded activation storages in streams mode by @kashif in #7193
- Pass the FSDP2 ignored_params kwarg only...
v1.13.0
Features
Training beyond 1M tokens
A new long-context guide plus a runnable example that trains a book-length sequence per step on a single 8×H100 node.
Measured: Qwen3-8B at 1,048,576 tokens, 380 s/step, 56.2 GB per GPU (bf16, per_device_train_batch_size=1, loss_type="chunked_nll"). Runs end to end and saves. The guide documents the levers in the order you hit them (chunked_nll, gradient-checkpointing offload, YaRN RoPE) and the constraints (full attention only, no packing). Needs transformers >= 5.16 for checkpointing offload.
- Document 1M-token training and add a context-parallelism example by @qgallouedec in #6846
- Rewrite the long context guide by @qgallouedec in #7003
Chunked-CE lm_head projection now runs on tensor cores
The inner loop of the default loss_type="chunked_nll" was doing h.float() @ w.float().t(). Both operands are already bf16, so the upcast bought no information: it moved the GEMM off the tensor cores onto the fp32 SIMT path and materialized an fp32 copy of the whole lm_head weight (2.03 GB for a 248k vocabulary), rebuilt for every chunk and again on every gradient-checkpoint recompute. In an 8×H100 profile of trl sft on Qwen3.6-35B-A3B those two fp32 SIMT GEMMs were 21.6% of all GPU kernel time.
One chunk, 256 tokens × vocab 248,320 × hidden 2048, 1×H100, bf16, fwd+bwd:
| fwd+bwd | peak mem | |
|---|---|---|
| before | 23.37 ms | 5.99 GB |
| after | 3.86 ms (6.0×) | 3.03 GB |
End to end, 16,384 tokens per step, tokens/s/GPU:
| model | mode | before | after | |
|---|---|---|---|---|
| gemma-3-270m (vocab 262k) | full FT, 1×H100 | 24036 | 31609 | 1.32× |
| Qwen3-0.6B (vocab 152k) | full FT, 1×H100 | 21276 | 26641 | 1.25× |
| Qwen3-8B | full FT, 2×H100 FSDP2 | 3554 | 6009 | 1.69× |
| Qwen3-8B | LoRA r16, 2×H100 FSDP2 | 4531 | 7125 | 1.57× |
| Qwen3-30B-A3B (MoE) | LoRA attn, 2×H100 FSDP2 | 4251 | 5101 | 1.20× |
Same fix applied to the distillation trainers (which paid it twice per chunk, student and teacher). Under accelerate mixed precision the numerics are bit-identical (autocast was already casting the operands back down); without autocast over the projection the GEMM moves to bf16 tensor cores, which is exactly what loss_type="nll" already does.
by @qgallouedec in #6863
Fused linear losses vendored into trl.losses
TRL's only import from liger-kernel was liger_kernel.chunked_loss (the fused linear DPO / KTO / GRPO / JSD losses). That module is pure PyTorch, and most of the GRPO and DPO variants in it were written for TRL. Upstream reviews had stalled, so the code comes home as trl.losses: FusedLinearDPOLoss, FusedLinearKTOLoss, FusedLinearGRPOLoss, FusedLinearJSDLoss (copied from Liger-Kernel v0.8.2, BSD-2 notice kept, bitwise identical to the installed Liger on random inputs).
No new config flag: use_liger_kernel=True keeps selecting the fused loss exactly as before, and still needs liger-kernel installed because transformers' Trainer patches the model kernels with it.
- Vendor the fused linear losses from Liger-Kernel into
trl.lossesby @qgallouedec in #7059 - Fix DPO and KTO Liger loss gaps by @kashif in #7062
- Harden chunked log probabilities by @kashif in #7065
- Drop fused JSD from
DistillationTrainerby @kashif in #7064 - Test liger vs non-liger GRPO loss parity by @kashif in #6814
- Run the vendored loss parity suites as slow tests only by @qgallouedec in #7067
Contributor skills at .agents/skills
Agent skills for contributing to TRL now ship in the repo at .agents/skills.
by @qgallouedec in #6901
Docs: stable vs experimental taxonomy, and how to change the objective
- Split the docs taxonomy into stable and experimental trainers by @qgallouedec in #7022
- Document how to change the training objective by subclassing a trainer by @sergiopaniego in #6918
- Document how to choose and pin a Hub kernel version by @albertvillanova in #6998
- Add missing TRL blog posts to the docs landing page by @qgallouedec in #7023
QLoRA on the quantization_config argument
The QLoRA test suites move onto the quantization_config trainer argument added in v1.8, and gain coverage on the VLM paths.
- Add a QLoRA test to the GRPO and RLOO VLM test suites by @albertvillanova in #6909
- Add a QLoRA test to the trainers that support
quantization_configby @albertvillanova in #6910 - Convert the QLoRA tests to the
quantization_configtrainer argument by @albertvillanova in #6927
Dependency floors raised
- Require
peft>=0.13.0and drop the 0.12 version guards by @qgallouedec in #7102 - Require
deepspeed>=0.18.6and drop the 0.16.4 guard by @albertvillanova in #7118 - Guard
target_parametersuse forpeft<0.17.0by @albertvillanova in #7119 - Add support for vLLM 0.28.0 by @qgallouedec in #7001
- Drop vLLM 0.19.0 support by @qgallouedec in #7002
Other
- Count each token once in
num_tokensunder tensor parallelism by @qgallouedec in #7101 - XPO / NashMD perf: avoid
output_hidden_stateswhen onlylast_hidden_stateis used by @ciaoyizhen in #4755 - Sync the model config pad token id with the tokenizer in the trainers by @albertvillanova in #7097 and (experimental) #7128
- Forward model revision to the auto-loaded
processing_classby @kashif in #6978 - Inject the model revision into concrete config loads too by @albertvillanova in #7099
- Match hub kernels by repo id when checking the attention implementation by @albertvillanova in #6985
- Catch
AsyncDistillationTrainerup with recent AsyncGRPO changes by @kashif in #6823 and #6987 - Remove the leftover
dataset_formattingmodule by @albertvillanova in #7117 - Remove the unused
FLASH_ATTENTION_VARIANTSconstant from the DPO trainer by @albertvillanova in #7013 - Document that padding-free is temporarily unavailable in DPO by @albertvillanova in #7014
- Realign duplicated comments across the trainers by @qgallouedec in #7145
Breaking
⚠️ PPO is removed
PPOTrainer, PPOConfig, and modeling_value_head.py (PreTrainedModelWrapper, AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead) are gone, along with their tests, doc page, and examples.
Bit of a moment for TRL: PPOTrainer predates every PR in this repo. It landed in dfb6a580 on 2020-03-28, the commit that first added the library, back when the package was called lm_ppo. It was the oldest thing in TRL and the last piece of the original codebase.
Why now: unmaintained (no feature work in over a year, every PPO commit since #4482 a drive-by fix), the only trainer never aligned on the input format (it still took tokenized input_ids), near-zero recorded usage, and a magnet for automated bug hunters filing real reports against code nobody runs. Nobody loses anything: from trl import PPOTrainer already stopped working in v1.10, so anyone actually running PPO is pinned to an older TRL and those installs keep resolving exactly as they do today.
create_reference_model stays (BCO, A2PO and Online DPO use it).
by @qgallouedec in #7020
Fixes
- Fix missing entropy gradient in
_ChunkedLogProbFunctionbackward —backwardacceptedgrad_entropybut never used it, so any loss backpropagating through theentropyoutput silently got zero gradient from that term, with no error or warning. OnlyAsyncGRPOTrainerreadentropy(underno_grad, for logging), so no user-facing regression today, but this is exported non-experimental code and an entropy-bonus loss term would have hit it silently. By @verma8076 in #6625 - vLLM weight sync now fails instead of hanging by @AmineDiro in #6913
- Fail fast on incompatible vLLM for default Async GRPO weight transfer by @DimensionSTP in #6830
- Fix VLM support in AsyncGRPO by @AmineDiro in #6839
- Fix variable reference in BCO docs by @albertvillanova in #7046
- Fix the IW-OPD self-distillation loss assertion in tests by @albertvillanova in #7123
- Fix typos in help strings and er...
v1.12.0
⚠️ v1.12.0 is an accidental duplicate of v1.11.0
During the v1.11.0 release, VERSION was bumped to 1.12.0 instead of 1.12.0.dev0. Our publish workflow fires on any push to main that touches VERSION and only skips the upload when the version contains "dev", so trl 1.12.0 was auto-published to PyPI at 19:46 on 2026-08-26, 90 seconds after 1.11.0, with identical code.
trl==1.12.0 on PyPI is bit-identical to trl==1.11.0. There are no features, fixes, or behavior changes in this version.
The version number is burned (PyPI does not allow yanking + re-uploading the same version), so we skip 1.12 entirely for real development. The next feature release is v1.13.0.
Full Changelog: v1.11.0...v1.12.0 (empty)
v1.11.0
Features
Use vLLM's own server instead of TRL's
trl vllm-serve used to run a custom FastAPI app around vLLM's LLM, with its own data-parallel fan-out and a worker extension for weight sync. vLLM's own server covers all of that. The custom server is gone: trl/scripts/vllm_serve.py drops from 1218 to ~130 lines and now translates its flags into vllm serve, prints the equivalent command, forwards any extra argument, and sets the three settings TRL needs (--weight-transfer-config, --logprobs-mode processed_logprobs, --max-logprobs -1). fastapi, uvicorn and pydantic leave the vllm extra.
Weight sync now uses vLLM's NCCL weight-transfer engine — tensors are announced once and streamed in a single packed broadcast, instead of one HTTP request + broadcast per tensor. Distillation teacher logprobs come from prompt_logprobs.
Benchmark (GRPO server-mode on H100, Qwen2.5-1.5B / Qwen2.5-VL-3B, same seed, same data):
| Setup | before | after | speedup |
|---|---|---|---|
| Text, TP=1 | 1.08, 0.91 s/step | 0.63, 0.62 s/step | 1.59× |
| Text, TP=2 | 0.96, 0.96 s/step | 0.62, 0.60 s/step | 1.57× |
| VLM, TP=1 | 2.14, 2.13 s/step | 1.48, 1.48 s/step | 1.44× |
Bit-identical completions vs the old server (16/16 over 4 prompts × n=4, logprobs identical to 0.0 over 499 tokens). trl vllm-serve still accepts the same flags — it just forwards to vllm serve now.
by @qgallouedec in #6765
New experimental AsyncDistillationTrainer (+ multi-teacher MOPD)
Async on-policy distillation, architected like AsyncGRPOTrainer: a background rollout worker generates the student's own completions and scores them against a teacher served over HTTP, so generation and training overlap instead of alternating. The teacher is never loaded locally — just a vLLM server URL.
Also supports MOPD (multi-teacher on-policy distillation): pass more than one entry in teacher_server_urls and route each sample to a teacher via a teacher_id column (e.g. a math teacher and a code teacher, each served independently).
from trl.experimental.async_distillation import AsyncDistillationConfig, AsyncDistillationTrainer
trainer = AsyncDistillationTrainer(
model="Qwen/Qwen3-4B",
args=AsyncDistillationConfig(
teacher_server_urls=["http://teacher-math:8000", "http://teacher-code:8000"],
teacher_top_k=16,
),
train_dataset=dataset, # rows carry a `teacher_id` column for MOPD
)
trainer.train()New model & template support
- Muse Glimmer (+ chat template) by @qgallouedec in #6738 and #6739
- Nemotron 3.5 Lightning by @qgallouedec in #6736
- LFM2.5-VL by @qgallouedec in #6737
- Qwen3.8 by @qgallouedec in #6764
- DeepSeek-R1-Distill chat template by @qgallouedec in #6766
Examples reorganized into per-example folders
examples/ was split by format (scripts/ vs notebooks/), which scattered related files (e.g. sft_nemotron_3 existed as both a script and a notebook, in different folders; OpenEnv notebooks lived apart from OpenEnv scripts). Everything is now one folder per story — the name says the method and the task (grpo_wordle, sft_gpt_oss, ppo_tldr), and the folder holds every file the example needs (scripts, notebooks, prompts, chat templates, eval code). Thin single-trainer demo scripts are removed (they live in trl/scripts/ and each trainer doc page has a runnable snippet). Old examples/scripts/… and examples/notebooks/… GitHub / Colab links will 404 — worth flagging in downstream posts.
by @qgallouedec in #6820
AsyncGRPO: metrics rework, dtype control, and cleanup
- Rework AsyncGRPO metrics + docs by @AmineDiro in #6715
- Training dtype in
AsyncGRPOConfigby @AmineDiro in #6774 - Simplify
AsyncGRPOTrainer— drop redundant metric guards, merge train-begin callbacks by @qgallouedec in #6378 - Fix checkpoint resume triggering unnecessary vLLM inference by @AmmarHassona in #5911
Rewritten TRL skill (Python-API first) + drop trl skills install
The TRL skill is now written around the Python API — trainer selection, dataset format, load-bearing config fields, GRPO reward-function contract — with the CLI as a footnote. trl skills install is dropped and the skill source moves out of the package.
- Rewrite the TRL skill around the Python API by @qgallouedec in #6794
- Drop
trl skills installand move the skill source out of the package by @qgallouedec in #6793
DistillationTrainer supports tool calling
Continuing the graduation cycle from v1.10.
by @qgallouedec in #6723
Suggest migrating to DistillationTrainer when the GKD config is fully covered
GKDTrainer now emits a hint when the config is fully covered by the stable DistillationTrainer — no behavior change, just a nudge for users still on the older API.
by @qgallouedec in #6847
Other
- Allow dict config fields to be set from the command line by @qgallouedec in #6792
- Raise when packing is combined with context parallelism by @qgallouedec in #6843
- Emit
position_idsfrom the SFT collator when sequence parallelism is enabled by @qgallouedec in #6812 - Remove one host sync from SFT
chunked_nllloss by @qgallouedec in #6842 - Align the chunked-loss config access between SFT and Distillation by @qgallouedec in #6744
- Add
dataset_sourceto telemetry by @qgallouedec in #6599 - Raise a clear error when generation returns no completions by @albertvillanova in #6714
- Move GPU CI from T4 to L40S by @qgallouedec in #6741
- Add on-policy multimodal GKD regression test by @sergiopaniego in #6342
vLLM version sweep
- Add support for vLLM 0.27.0 and 0.27.1 by @qgallouedec in #6742
- Drop vLLM 0.17 by @qgallouedec in #6722
- Drop vLLM 0.18 by @qgallouedec in #6844
- Require
liger-kernel0.8.2 and drop the SAPO warning filter by @albertvillanova in #6768
Fixes
- Fix GRPO/RLOO training with multiple images for VLMs without grid metadata by @qgallouedec in #6570
- Fix GRPO/RLOO with dynamic-tiling VLMs (InternVL) by @qgallouedec in #6619
- Handle
Nonetoken logprobs from vLLM in GRPO importance sampling by @behroozazarkhalili in #6693 [GRPO]Match the Ligerdapo/cispo/vesponormalizer to the non-Liger path — completes the fix from v1.10 (#6024) on the Liger path. By @kashif in #5890[SFT]Treatpast_key_valuesandattentionsas optional on the model output by @Hakureirm in #6686- Fix
AsyncGRPOTrainercrashing on environment-owned datasets by @albertvillanova in #6824 - Fix SDPO
scale_rewardsCLI parsing and warn on ignored feedback by @sergiopaniego in #6341 - Fix
opencode.pyproxy trace / log paths after OpenEnv moved them to functions by @sergiopaniego in #6672
Documentation and Examples
- Rework AsyncGRPO docs alongside the metrics rework (@AmineDiro, #6715)
- Reorganize examples into self-contained per-example folders (see above)
- Suggest migrating to
DistillationTrainerwhen GKD config is covered (see above)
CI
Big CI-hygiene cycle by @albertvillanova. Highlights:
- Test one Python version on PRs, matrix nightly by @qgallouedec in #6763
- Notify Slack when the tests of the latest release fail by @albertvillanova in #6900
- Post the Docker image build results to the shared CI Slack channel by @albertvillanova in #6903
- Factor the Slack notification into a local composite action by @albertvillanova in #6895 (+ updates in #6896, #6897, #6908, #6934, #6936)
- Move slow-test job status handling, dependencies, and reporting to Slack by @albertvillanova in #6752, #6754, #6756
- Pin the TruffleHog scanner image by digest + tighten secret scanning by @albertvillanova in #6677, #6757, #6758, #6759
- Various hotfix pins and reverts across the cycle (bitsandbytes / liger-kernel / peft dev builds / transformers dev) by @albertvillanova in #6...
v1.10.0
Features
🎓 DistillationTrainer is now a stable trainer
After a ~30-PR refactor that reshaped its data contract, loss path, generation stack, config surface, and tests, DistillationTrainer and DistillationConfig graduate from trl.experimental.distillation to the top-level trl package. Same import surface as SFT / DPO / GRPO / KTO. The old experimental path still works and emits a FutureWarning (removal in v2.0.0).
# Before
from trl.experimental.distillation import DistillationConfig, DistillationTrainer
# Now
from trl import DistillationConfig, DistillationTrainerAlso lands a trl distillation CLI and moves the tests to tests/. The full refactor arc: switched signature columns to prompt (deprecated messages-format), pinned the generation stack to GRPO's, wired the chunked JSD loss and deleted the full-logit path, cleaned the Liger path to share extraction with the chunked path, adopted GRPO's log() / training_step timing / _save_checkpoint, rebuilt the test suite to GRPO shape, and much more.
by @qgallouedec across ~30 PRs (#6479, #6480, #6481, #6482, #6484, #6487, #6497, #6508, #6509, #6510, #6511, #6512, #6513, #6521, #6522, #6523, #6524, #6525, #6526, #6530, #6537, #6604, #6605, #6606, #6607, #6609, #6610, #6611, #6612, #6613, #6614, #6629, #6630, #6632, #6633, #6634, #6639, #6640, #6641, #6642, #6643, #6644, #6645, #6647, #6653).
DistillationTrainer supports Vision Language Models
Alongside the graduation, VLMs work end-to-end in DistillationTrainer.
by @qgallouedec in #6650
AsyncGRPO: loop-owning agent training (OpenEnv harness)
New experimental loop-owning (black-box) path for AsyncGRPOTrainer — for training external agents like opencode that run their own tool loop, rather than TRL driving each turn as in the environment_factory white-box path.
The agent runs in an OpenEnv session in transparent_proxy mode; an in-sandbox proxy captures each turn's token ids and logprobs. On completion, TRL reads the trace, rebuilds per-turn training rows, and scores the workspace with the session's verify(). Ships with three caller-supplied policy hooks (rollout_reward_fn, train_turn_fn, agent_turn_fn) so you can drop framework aux calls (title generator, context summarizer) and reinforce only the turns you want.
Includes a self-contained examples/scripts/openenv/opencode.py (local subprocess sandbox + DeepCoder held-out stdin/stdout verifier), validated end-to-end on Qwen3-4B.
by @AmineDiro in #6420, plus HF-sandbox variant by @sergiopaniego in #6565
AsyncGRPO: observability + sampling controls
- Record rollout traces to trackio by @AmineDiro in #6491
- Step-time metric by @AmineDiro in #6490
- Fix queue wait time metric by @AmineDiro in #6489
top_p/top_k/min_p/repetition_penaltyinAsyncGRPOConfigby @AmineDiro in #6608- Fork-independent epoch counting — landed in v1.9 window
- Close in-flight harness sessions concurrently on shutdown by @sergiopaniego in #6564
DiffusionGemma block-diffusion SFT example
A new SFT example for google/diffusiongemma-26B-A4B-it implementing the reference recipe: one response block per step, uniform random token corruption with t ~ U(eps, 1), two-pass self-conditioning, flat cross-entropy over the whole canvas plus an autoregressive co-loss on the encoder. LoRA targets attention + dense MLP linears. Requires transformers >= 5.12.0.
Ships with diffusion_gemma.jinja / diffusion_gemma_training.jinja chat templates (with {% generation %} markers) so assistant_only_loss=True works out of the box.
More model & template support
- LFM2 and LFM2.5 — day-zero training support by @qgallouedec in #6428
- Gemma 4 response template by @qgallouedec in #6535
Default changes
Two default flips this cycle — pinning them explicitly is recommended if you want the old behavior.
SFTConfig.max_completion_length/GRPOConfig.max_completion_length: default bumped from256to512. By @dhruvnigam93 in #6264GRPOConfig.use_bias_correction_klnow defaults toTrue. By @gowtham-sai-yadav in #6503
Packing and padding-free on VLMs with text-only data
VLM configurations no longer reject packing / padding-free when the batch happens to be text-only.
by @cris96spa in #6547
Other
- Use a reference adapter with
target_parametersonpeft>=0.20.0by @albertvillanova in #6591 - Reject unsupported
train_datasettypes in core trainers by @albertvillanova in #6493 and #6494 - Reject unsupported
f_divergence_type/ loss type combinations in DPO by @qgallouedec in #6559 - Validate that reward functions return one reward per completion by @gowtham-sai-yadav in #6534
- Validate YAML config root type by @RerankerGuo in #6656
- Respect
TQDM_DISABLEin DPO/KTO/BCO reference log-prob loops by @qgallouedec in #6507 - Respect
use_cpuincreate_model_from_pathdevice_mapdefault by @Strongich in #6295 - Use
dtypeinstead oftorch_dtype(deprecated) by @qgallouedec in #6560 - Add missing logged metrics to the GRPO and RLOO docs by @PoojanTa in #6624
- Add
test_train_moe_peft_modelfor KTO by @albertvillanova in #6589
vLLM version sweep
- Add support for vLLM 0.26.0 by @qgallouedec in #6569
Fixes
- Fix DAPO / CISPO / VESPO loss normalization when
steps_per_generation != gradient_accumulation_steps— gradients were silently mis-scaled bygradient_accumulation_steps / steps_per_generation(e.g. 0.5× or 4× the intended token-mean in common configs). Default-equivalent configs are unaffected. By @0xadvait in #6024 - Fix Liger kernel crash on pre-Ampere GPUs by @albertvillanova in #6518
- Fix vLLM weight synchronization when
vllm_enable_sleep_mode=Trueby @muupan in #5313 - Fix vLLM server-mode communicator initialization to use the current accelerator device by @sywangyi in #6417
- Use accelerator device instead of hardcoded
cudain FSDP2 vLLM weight sync by @verma8076 in #6592 - Fix
prepare_deepspeedcrash with CPU offload optimizer by @roycho96 in #5916 fix(ppo): exclude padding tokens from entropy calculation by @mukund1985 in #6121fix: avoidCopySliceswhen scaling policy logits by @DaoyuanLi2816 in #6554- Fix multimodal field handling in GRPO tool-call loop by @HariomJangra in #6286
[GRPO]Apply the completion mask elementwise in the LuSPO loss aggregation by @YaseenBashaT in #6654[GRPO]Fix entropy bonus normalization inconsistency across loss types by @YaseenBashaT in #6648- Fix incorrect example script path in Online DPO docs by @latent-9 in #6598
- Point the opencode example at
huggingface/OpenEnvby @sergiopaniego in #6529 - Remove symlink support from skills installation by @albertvillanova in #6665
Documentation and Examples
- docs: complete
GRPOConfigloss_typehelp by @gowtham-sai-yadav in #6477 - Fix inaccuracies in the release instructions by @albertvillanova in #6566
- Fix patch release instructions: pull release branch instead of main by @albertvillanova in #6563
- Add
opencode_hf_sandbox.py: loop-owning training in remote HF sandboxes by @sergiopaniego in #6565
CI
test: don't hard-codebf16=Trueon devices that lack bf16 support by @behroozazarkhalili in #6036- Cleanup xpu cache memory after each test by @kaixuanliu in #5771
- Force
use_cpuin tests when no CUDA device is available by @albertvillanova in #6504 - Silence transformers
LOAD REPORTtables in test output by @albertvillanova in #6502 - Require vision for VLM response parsing tests by @albertvillanova in #6602
- Require
jmespathonly on transformers below 5.13.0 by @albertvillanova in #6597 - Add regression tests for evaluating init-time eval datasets after training with precomput...
v1.9.2
What's Changed
- Revert xfail for NemotronH GRPO/RLOO tests now that transformers#47569 fixed the kernels bug by @albertvillanova in #6558
- Fix test_peft_with_quantization tests for bitsandbytes 0.50.0 by @albertvillanova in #6546
Full Changelog: v1.9.1...v1.9.2
v1.9.1
What's Changed
- Fix vLLM server-mode communicator initialization to use the current A… by @sywangyi in #6417
- Fix : queue wait time metric AsyncGRPOTrainer by @AmineDiro in #6489
- Hotfix CI: Temporarily pin liger-kernel < 0.8.1 by @albertvillanova in #6517
- Fix crash when training with Liger kernel on pre-Ampere GPUs by @albertvillanova in #6518
- Fix prepare_deepspeed crash with cpu offload optimizer by @roycho96 in #5916
- Add Gemma4 response template by @qgallouedec in #6535
- fix(grpo): correct DAPO/CISPO/VESPO loss normalization when steps_per_generation != gradient_accumulation_steps by @0xadvait in #6024
- Hotfix CI: Temporarily pin bitsandbytes < 0.50.0 by @albertvillanova in #6544
- Hotfix CI: Xfail NemotronH GRPO/RLOO tests against a broken transformers dev build by @albertvillanova in #6542
Full Changelog: v1.9.0...v1.9.1
v1.9.0
Features
Iterable / streaming datasets in GRPO and RLOO
Long-standing request finally landed. GRPO and RLOO rely on RepeatSampler to repeat each prompt num_generations times and group them across processes — but samplers can't attach to iterable datasets (no length, no indexing), and the old behavior silently bypassed the sampler, quietly corrupting advantage computation.
A new repeat_iterable_dataset generator reproduces RepeatSampler's exact ordering by transforming the stream itself instead of reordering indices. Trainers wrap iterable datasets via IterableDataset.from_generator, force dispatch_batches=False, and shard the stream per-process to preserve prompt groups after cross-process gathering.
from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer
dataset = load_dataset("trl-lib/DeepMath-103K", split="train", streaming=True)
trainer = GRPOTrainer(
model="Qwen/Qwen3-4B",
args=GRPOConfig(max_steps=1000), # required for iterable datasets
train_dataset=dataset,
reward_funcs=accuracy_reward,
)max_steps is required for iterable datasets (no length). A clear error also fires if dispatch_batches=True is combined with an iterable dataset.
by @albertvillanova in #6351
Environment-owned datasets
When an environment_factory is provided, the environment can now own the data. train_dataset becomes optional: reset() returns the prompt. No more fabricating a dummy dataset just to drive the loop.
class WordleEnv:
def reset(self, **kwargs) -> str: # returns the prompt
self._target = sample(words)
return f"Guess a {len(self._target)}-letter word."
def get_reward(self) -> float:
return 1.0 if self._solved else 0.0
def guess(self, word: str) -> str: # exposed tool
self._solved = word == self._target
return _feedback(word, self._target)
trainer = GRPOTrainer(
model="Qwen/Qwen3-4B",
args=GRPOConfig(max_steps=1000),
environment_factory=WordleEnv, # no train_dataset needed
)Applies to both GRPOTrainer and AsyncGRPOTrainer. A provided train_dataset still works exactly as before; multi-environment routing datasets can now be environment-only (no prompt column required).
by @qgallouedec in #6349
Message-level rollouts in AsyncGRPO
An opt-in way to build training rows from a multi-turn conversation. Message mode keeps the conversation as messages and re-tokenizes the whole thing each turn, then checks whether the fresh tokens still start with the tokens held so far. If yes → append the new part (same as token mode). If no → a rewrite happened → close the row and open a new one that matches what the model actually read.
AsyncGRPOConfig(
rollout_protocol="message", # "token" (default) | "message"
fork_threshold_tokens=1024, # message-mode only
)Per-turn drift is classified as CLEAN (append), REALIGN (last-answer tail wobble → overwrite same row), or FORK (real rewrite → new row). One advantage per conversation, stamped on every row it produced; under token-mean loss a fork is invisible. Sets up the plumbing for future tree-trajectory support — scoring is already branch-agnostic (groups by rollout_id).
by @AmineDiro in #6250
AsyncGRPO: VLLMClient and decoupled weight sync
A follow-up to v1.8's rollout worker split. A small VLLMClient becomes the single place that speaks HTTP to the vLLM server (named methods for wait_for_server_ready, get_max_model_len, pause/resume, weight-update endpoints — stateless, so picklable). Generation deliberately stays on its own async aiohttp session in the rollout child.
Weight sync is now built from config independent of rollout_worker (previously a custom rollout worker force-set it to None), and is injectable via a new WeightTransferProtocol. token_budget now waits for /health before defaulting to get_max_model_len(), so a slow-starting vLLM waits instead of failing the run.
by @AmineDiro in #6269
DistillationTrainer refactor
A ~13-PR sweep that reshapes the experimental DistillationTrainer for future stability:
- Extract
ServerDistillationTrainerfor the teacher-server path (#6454) - Move IW-OPD to a dedicated experimental trainer (#6453)
- Remove the local sparse top-1 loss path from the base trainer (#6455)
- Remove top-k support from the base generalized JSD loss (#6456)
- Validate the teacher by vocab size instead of tokenizer identity (#6457)
- Deprecate & remove
lmbdaon/off-policy mixing and the off-policy training branch (#6458, #6460); GKD paper reproduction now points atGKDTrainer(#6459) - Accept a
promptcolumn alongsidemessages(#6461); deprecate messages-format datasets (#6474) ⚠️ Fixnum_items_in_batchto count generated completion tokens — the loss denominator was wrong for on-policy training (counted dataset completions, not generated ones) and NaN'd on prompt-only datasets. This changes loss values for anyone on the old path (#6478)- Preparatory pins on the objective and on/off-policy behavior end to end (#6450, #6451, #6452)
All by @qgallouedec.
New IW-OPD distillation objective
Importance-Weighted On-Policy Distillation lands as an optional objective on the experimental DistillationTrainer — detached IW-OPD advantages built from sampled-token teacher and rollout logprobs (with cached vLLM rollout logprobs when use_vllm=True).
DistillationConfig(
distillation_objective="iw_opd",
iw_opd_gamma=1.0,
iw_opd_epsilon=0.2,
lmbda=1.0, reverse_kl_top_1_mode="sampled", # required
)Now split into its own experimental trainer as part of the refactor above.
log_multimodal for GRPO / RLOO
New config toggle to control whether images from multimodal completions are logged to trackers. Also applied to experimental DPPO and GRPO-with-replay-buffer.
by @apardyl in #5408 and by @albertvillanova in #6352
vLLM version sweep
- Support vLLM 0.24.0 by @qgallouedec in #6355
- Support vLLM 0.25.0 and 0.25.1 by @qgallouedec in #6406
- Drop vLLM 0.16 by @qgallouedec in #6404
Other
- Simplify KTO KL completion construction into a single batched map by @albertvillanova in #6335
- Add security policy to the repo by @albertvillanova in #6362
- Removed
generate_rollout_completionsby @sergiopaniego in #5870 - Set explicit neutral
top_pin GKD on-policy generation by @sergiopaniego in #6337 - Support
DatasetDictandIterableDatasetDictaseval_datasetinevaluateby @albertvillanova in #6326 - AsyncGRPO fork-independent epoch counting by @AmineDiro in #6385
- Align
AsyncGRPOTrainerargs handling with stable trainers by @qgallouedec in #6377 - Reject
auto_find_batch_sizein GRPO and RLOO by @qgallouedec in #6411 - Drop fully-masked examples after truncation in SFT by @qgallouedec in #6320
- Drop examples with no completion left after truncation in DPO and KTO by @qgallouedec in #6321
- Add
GMPOTrainerto the telemetry allowlist by @qgallouedec in #6410 [GRPO]Treat explicitmax_tool_calling_iterations=0as zero, not unlimited by @Strongich in #6423- Add a tip to the Paper Index on reading papers with the
hfCLI by @davanstrien in #6422
Deprecations and removals
- Remove the experimental DPPO trainer by @qgallouedec in #6402
- Deprecate
messages-format datasets inDistillationTrainer— usepromptcolumn instead — by @qgallouedec in #6474 - Deprecate
lmbdaon/off-policy mixing inDistillationTrainer— off-policy path fully removed by @qgallouedec in #6458 and #6460
Fixes
- Fix biased cross-rank aggregation of token-weighted metrics in GRPO / RLOO — mean-of-means was biased when per-rank token counts differ; now reduces numerator + count jointly for a true global mean. Also fixes
clip_ratio/low_min/high_maxto be per-completion instead of per-rank-batch-mean (DP-layout-independent). Logging-only, no loss change. By @qgallouedec in #6380 - Fix DPO/KTO
use_liger_kernelunder DeepSpeed ZeRO-3 by @qgallouedec in #6372 - Force
use_reentrant=Truefor PEFT + ZeRO-3 + gradient checkpointing across all trainers by @qgallouedec in #6356 - Fix
precompute_ref_log_probs=Truewith DeepSpeed in DPO and KTO by @qgallouedec in #6403 - Fix
cast_lm_head_to_fp32under FSDP2 / DeepSpeed ZeRO-3 by @qgallouedec in #6330 - Fix corrupted reasoning blocks in Qwen3-family training chat templates — the both-tags guard broke replay of s...
v1.8.0
Features
🎓 KTO is now a stable trainer
After many cycles of KTOTrainer ↔ DPOTrainer alignment work, KTO graduates from trl.experimental.kto to the top-level trl package. Same API as DPO/GRPO/SFT — imports move from experimental, tests move to the main test tree, docs no longer flag it as experimental. The experimental path still works and emits a FutureWarning (removal in v2.0.0).
# Before
from trl.experimental.kto import KTOConfig, KTOTrainer
# Now
from trl import KTOConfig, KTOTrainerPer our telemetry, KTO is the 4th most used trainer in TRL — this graduation was overdue.
by @albertvillanova in #6175, #6287 and #6345
Environment-owned rewards & multi-environment support
Three interrelated changes make agentic RL training with environments substantially more ergonomic.
Environment-owned reward. If your environment_factory env defines a reserved get_reward() method (no args → float), it's called once per completed rollout and treated as a reward source. reward_funcs becomes optional — no more leaking env state back out to trainer-owned reward funcs.
class WordleEnv:
def reset(self, **kwargs):
self._target = sample(words); self._solved = False
def get_reward(self) -> float: # optional, reserved (not a tool)
return 1.0 if self._solved else 0.0
def guess(self, word: str) -> str: # exposed as a tool
self._solved = word == self._target; ...
trainer = GRPOTrainer(
model=model,
train_dataset=dataset,
environment_factory=WordleEnv, # no reward_funcs needed
)Multi-environment support. environment_factory now accepts dict[str, factory] in addition to a single callable. Each dataset row selects its environment via an environment column, and only that env's tools are exposed in that row's prompt — so a coding task and a game can train together in one run without leaking each other's tool schemas. Single-callable usage is unchanged.
Same wiring lands in GRPO, AsyncGRPO, DPPO, and GRPO-with-replay-buffer.
Env-owned reward by @qgallouedec in #6238; multi-env in #6001 and #6002
Entropy regularization for GRPO
GRPOConfig now supports both static and adaptive entropy regularization (Skywork-OR1). The bonus encourages exploration and helps prevent premature policy collapse.
GRPOConfig(
entropy_coef=0.01, # static
# or:
use_adaptive_entropy=True, # adjust to target entropy
entropy_target=1.5,
entropy_coef_delta=0.01,
entropy_coef_min=0.0,
entropy_coef_max=0.1,
)Adaptive mode adjusts the coefficient once per optimizer step from window-aggregated entropy (gradient accumulation-aware) and persists entropy_coef in the checkpoint for resume. Not compatible with the Liger kernel.
by @albertvillanova in #6140
quantization_config trainer argument (streamlined QLoRA)
QLoRA no longer requires reaching into model_init_kwargs or pre-loading the model manually.
SFTTrainer(
model="meta-llama/Llama-2-7b-hf",
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
peft_config=LoraConfig(),
train_dataset=dataset,
)Added to SFTTrainer, DPOTrainer, GRPOTrainer, RLOOTrainer, RewardTrainer, and KTOTrainer. Sits next to peft_config (the other non-serializable QLoRA ingredient), flows into from_pretrained, and raises if also set in args.model_init_kwargs. Also drops the redundant get_kbit_device_map() line — QLoRA trains identically without it across all tested configurations.
by @qgallouedec in #6157 and #6276
MoE aux loss extends to DPO and KTO
v1.7 added the router load-balancing auxiliary loss to GRPOTrainer / RLOOTrainer / AsyncGRPOTrainer. It's now on DPOTrainer and KTOTrainer too, so post-training MoE models with preference data keeps experts balanced.
by @qgallouedec in #6208 and #6275
Neuron-friendly chunked_nll via static-shape token packing
The chunked NLL path had data-dependent indexing that broke XLA/Neuron compilation. This PR reworks it to pack valid tokens to the front via a stable argsort on the validity mask, iterate over ceil(n_valid / chunk_size) * chunk_size whole chunks (a tensor, no Python-int sync), and use ignore_index=-100 inside each chunk. GPU behavior is unchanged; Neuron now works too — same tiny memory footprint (~1.33 GiB vs the naive 5.94 GiB alternative) with no per-mask recompilation.
by @michaelbenayoun in #6314
Packing-aware dynamic batching in AsyncGRPO
AsyncGRPO micro-batching becomes packing-aware and token-bounded on top of the padding-free path from v1.7:
- Σ Lᵢ² row balancing — a greedy longest-first assignment gives every DP row the same Σ Lᵢ² instead of the same token count (attention is O(L²), FFN is O(L), so equal token counts don't equalize wall-clock). Cross-rank stragglers vanish; +19% MFU at 4B in the benchmark.
- Token-budget packing (opt-in) — cap each row at
token_budgettokens with a variable sample count, decoupling peak memory fromper_device_train_batch_size. Useful in memory-bound regimes (no gradient checkpointing, long context, very large models).
Both ride HF Trainer's existing gradient accumulation — no training-loop surgery, FSDP/EP collectives stay in lockstep.
by @AmineDiro in #6092
VLM support in GOLDTrainer
GOLDTrainer now supports vision-language models end-to-end.
by @Strongich in #5969
Support tool calling in KTO
by @qgallouedec in #6259
Support PEFT + Liger in DPO and KTO
by @albertvillanova in #6159 and #6277
Per-dataset fraction in dataset mixtures
You can now weight a DatasetMixtureConfig by fraction instead of only by explicit counts.
by @qgallouedec in #6199
SFT: truncate during dataset preparation
Continuing the label-refactor from v1.7 (#6037), truncation moves out of the collator and into dataset preparation. SFTTrainer and DPOTrainer now truncate consistently at the same phase.
by @qgallouedec in #6155
Simplify tokenization [1-5/N]
A big refactor pass merging DPO / SFT / Reward / KTO tokenization into one shared implementation:
- Remove redundant
is_vlmparameter — #6298 - Make
_tokenizea module-level function — #6301 - Factor
_tokenizeinto a single shared function — #6302 - Bundle
apply_chat_templatekwargs — #6305 - Pass
chat_templateasapply_chat_template_kwargs— #6315
All by @albertvillanova. Related: align collators across DPO / SFT / Reward / KTO by @qgallouedec in #6178.
Other
- Support
DatasetDictandIterableDatasetDictaseval_datasetin trainers by @albertvillanova in #6322 - Auto-load
processing_classin CPO/ORPO trainers when omitted by @DaoyuanLi2816 in #6087 - Add
trust_remote_codetoGRPOConfigby @muupan in #4186 - Integrate the new response parsing API by @qgallouedec in #5791
- Raise a clear error when the ChatML collator truncates the whole prompt by @qgallouedec in #6310
- Raise a clear error when GKD student and teacher vocab sizes differ by @sergiopaniego in #6252
- Add prompt-learning guard for PEFT with Liger in GRPO by @albertvillanova in #6186
[async GRPO]Per-generationreset()observation by @qgallouedec in #6072- Default AsyncGRPO
token_budgetto vLLMmax_model_lenby @AmineDiro in #6218 - Drop vLLM 0.14 support by @qgallouedec in #6209
- Drop vLLM 0.15 support by @qgallouedec in #6239
- Log
entropyandnum_tokensmetrics in KTO by @qgallouedec in #6257 and #6256 - Standardize
TrainerCallbackimport to the public top-level path by @qgallouedec in #6249 - Remove redundant
get_kbit_device_map()by @qgallouedec in #6158 - Factorize
get_dataset_column_namesfrom core and experimental trainers by @albertvillanova in #6272 and #6273
Deprecations and removals
- Remove
GFPOTrainerby @qgallouedec in #6309 — no known usage, and its behavior can be reproduced by adjustingreward_funcs. - Remove
PAPOTrainerby @qgallouedec in #6235 - Remove post-training-toolkit integration by @qgallouedec in...
v1.7.1
What's Changed
- Fix GRPO + vLLM colocate + PEFT hang on non-NVLink hardware by @albertvillanova in #6139
- Fix dataset fingerprinting in DPO/SFT tokenization by @qgallouedec in #6206
- Pass GPU device_ids to barrier fix in GRPO + vLLM colocate + PEFT by @albertvillanova in #6187
- Integrate the new response parsing API by @qgallouedec in #5791
- Fix
add_response_schematests for the newparse_responseprefix requirement by @qgallouedec in #6236 - Add prompt-learning guard for PEFT with Liger in GRPO by @albertvillanova in #6186
- Fix activation offload storage dedupe reuse by @winglian in #6241
Full Changelog: v1.7.0...v1.7.1