Skip to content

Releases

v1.14.0

Choose a tag to compare

@albertvillanova albertvillanova released this 25 Sep 06:40
c6a6a16

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.

Other

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.

Also breaking, and covered above: trl.losses was removed along the way.

Fixes

  • Gradients were never all-reduced for KTO under plain DDP. compute_loss redirected 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_wrapped sized 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, and datasets.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_metric on rank 0 alone hung on NCCL, and log_extra crashed inside gather_object with a 1EB allocation. By @behroozazarkhalili in #7382
  • Special token ids now reach the config the Trainer actually 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...
Read more

v1.13.0

Choose a tag to compare

@qgallouedec qgallouedec released this 10 Sep 00:50
3d9261f

Features

Training beyond 1M tokens

image

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.

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.

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

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.

Dependency floors raised

Other

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 _ChunkedLogProbFunction backward — backward accepted grad_entropy but never used it, so any loss backpropagating through the entropy output silently got zero gradient from that term, with no error or warning. Only AsyncGRPOTrainer read entropy (under no_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...
Read more

v1.12.0

Choose a tag to compare

@qgallouedec qgallouedec released this 26 Aug 20:05
59c4a8e

⚠️ 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

Choose a tag to compare

@qgallouedec qgallouedec released this 26 Aug 20:02
d0a2cd5

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()

by @kashif in #6705

New model & template support

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

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.

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

vLLM version sweep

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 None token logprobs from vLLM in GRPO importance sampling by @behroozazarkhalili in #6693
  • [GRPO] Match the Liger dapo / cispo / vespo normalizer to the non-Liger path — completes the fix from v1.10 (#6024) on the Liger path. By @kashif in #5890
  • [SFT] Treat past_key_values and attentions as optional on the model output by @Hakureirm in #6686
  • Fix AsyncGRPOTrainer crashing on environment-owned datasets by @albertvillanova in #6824
  • Fix SDPO scale_rewards CLI parsing and warn on ignored feedback by @sergiopaniego in #6341
  • Fix opencode.py proxy 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 DistillationTrainer when GKD config is covered (see above)

CI

Big CI-hygiene cycle by @albertvillanova. Highlights:

Read more

v1.10.0

Choose a tag to compare

@qgallouedec qgallouedec released this 13 Aug 01:36
a7be897

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, DistillationTrainer

Also 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

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.

by @kashif in #6003

More model & template support

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 from 256 to 512. By @dhruvnigam93 in #6264
  • GRPOConfig.use_bias_correction_kl now defaults to True. 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

vLLM version sweep

Fixes

  • Fix DAPO / CISPO / VESPO loss normalization when steps_per_generation != gradient_accumulation_steps — gradients were silently mis-scaled by gradient_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=True by @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 cuda in FSDP2 vLLM weight sync by @verma8076 in #6592
  • Fix prepare_deepspeed crash with CPU offload optimizer by @roycho96 in #5916
  • fix(ppo): exclude padding tokens from entropy calculation by @mukund1985 in #6121
  • fix: avoid CopySlices when 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/OpenEnv by @sergiopaniego in #6529
  • Remove symlink support from skills installation by @albertvillanova in #6665

Documentation and Examples

CI

Read more

v1.9.2

Choose a tag to compare

@albertvillanova albertvillanova released this 28 Jul 10:39
33f9e46

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

Choose a tag to compare

@qgallouedec qgallouedec released this 26 Jul 16:49

What's Changed

Full Changelog: v1.9.0...v1.9.1

v1.9.0

Choose a tag to compare

@qgallouedec qgallouedec released this 21 Jul 20:36
35def3e

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 ServerDistillationTrainer for 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 lmbda on/off-policy mixing and the off-policy training branch (#6458, #6460); GKD paper reproduction now points at GKDTrainer (#6459)
  • Accept a prompt column alongside messages (#6461); deprecate messages-format datasets (#6474)
  • ⚠️ Fix num_items_in_batch to 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.

by @kashif in #6191

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

Other

Deprecations and removals

  • Remove the experimental DPPO trainer by @qgallouedec in #6402
  • Deprecate messages-format datasets in DistillationTrainer — use prompt column instead — by @qgallouedec in #6474
  • Deprecate lmbda on/off-policy mixing in DistillationTrainer — 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_max to 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_kernel under DeepSpeed ZeRO-3 by @qgallouedec in #6372
  • Force use_reentrant=True for PEFT + ZeRO-3 + gradient checkpointing across all trainers by @qgallouedec in #6356
  • Fix precompute_ref_log_probs=True with DeepSpeed in DPO and KTO by @qgallouedec in #6403
  • Fix cast_lm_head_to_fp32 under 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...
Read more

v1.8.0

Choose a tag to compare

@qgallouedec qgallouedec released this 09 Jul 18:41
95809b9

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, KTOTrainer

Per 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_budget tokens with a variable sample count, decoupling peak memory from per_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_vlm parameter — #6298
  • Make _tokenize a module-level function — #6301
  • Factor _tokenize into a single shared function — #6302
  • Bundle apply_chat_template kwargs — #6305
  • Pass chat_template as apply_chat_template_kwargs — #6315

All by @albertvillanova. Related: align collators across DPO / SFT / Reward / KTO by @qgallouedec in #6178.

Other

Deprecations and removals

  • Remove GFPOTrainer by @qgallouedec in #6309 — no known usage, and its behavior can be reproduced by adjusting reward_funcs.
  • Remove PAPOTrainer by @qgallouedec in #6235
  • Remove post-training-toolkit integration by @qgallouedec in...
Read more

v1.7.1

Choose a tag to compare

@qgallouedec qgallouedec released this 04 Jul 04:05

What's Changed

Full Changelog: v1.7.0...v1.7.1