trl

huggingfaceApache-2.0活跃维护

用强化学习训练 Transformer 语言模型的全流程库,覆盖 SFT、奖励建模到 PPO/DPO 等 RLHF 算法,省去自己拼训练管线。

Train transformer language models with reinforcement learning.

v1.17.1发布于 2026-10-30 14:15 UTC19,702star +16 / 7 天3,127fork同步于 2026-11-10 11:24 UTC

怎么上手

由 README 提炼,执行前请确认
pip install trl
硬件要求按 README 说明

README 未给出具体显存要求;支持单 GPU 到多节点集群,可通过 ROCm 在 AMD Instinct GPU 上运行,也支持 AWS Trainium。

支持 ROCm / AMD
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

Hugging Face 出品的后训练库,用 SFT、DPO、GRPO 等方法微调大模型

用强化学习训练 Transformer 语言模型的全流程库,覆盖 SFT、奖励建模到 PPO/DPO 等 RLHF 算法,省去自己拼训练管线。

核心能力

  • 提供 SFTTrainer、DPOTrainer、GRPOTrainer、KTOTrainer、RewardTrainer 等训练器
  • 基于 Accelerate 支持 DDP、DeepSpeed ZeRO、FSDP 分布式训练
  • 集成 PEFT 与 LoRA/QLoRA,量化后在有限硬件上训练大模型
  • 集成 Unsloth 优化内核加速训练
  • 提供 trl sft/dpo/kto 命令行接口,无需写代码即可微调

容易踩的坑

GRPO 的 accuracy_reward 依赖 math-verify,需额外执行 pip install trl[math_verify];trl.experimental 下的功能不稳定,可能随时变更或移除;示例代码需从 Hugging Face Hub 下载模型和数据集,需保证网络与缓存空间。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v1.17.1
  1. v1.17.1最新正式版2026-10-30 · 2026-10-30 14:15 UTC

    What's Changed

    Full Changelog: https://github.com/huggingface/trl/compare/v1.17.0...v1.17.1

  2. v1.17.02026-10-29 · 2026-10-29 15:51 UTC
    查看更新说明

    Features

    🔥 Mistral Large 4: fine-tune a 1T-parameter model on one node

    TRL now supports mistralai/Mistral-Large-4-1T-A52B: 1T parameters, 52B active. The new LoRA example fine-tunes it with SFTTrainer on a single 8×B300 node, on top of its FP8 weights: the experts are split 8 ways with token dispatch, everything else is sharded across the 8 GPUs at load time by transformers' DistributedConfig, and LoRA trains attention and the dense and shared-expert MLPs.

    Measured: 32.7k tokens per step in ~8 s, 142 GiB per GPU, with packing and assistant-only loss on reasoning conversations.

    https://github.com/user-attachments/assets/5aa86ec7-6444-4bed-bfdc-0445e99bea0d

    training_args = SFTConfig(
        model_init_kwargs={
            "dtype": "auto",  # keep the FP8 weights
            "distributed_config": DistributedConfig(fsdp_size=8, ep_size=8),
        },
        packing=True,
        assistant_only_loss=True,
        ...
    )
    trainer = SFTTrainer(model="mistralai/Mistral-Large-4-1T-A52B", args=training_args, peft_config=LoraConfig(...), ...)
    

    assistant_only_loss=True works out of the box: TRL ships a training chat template that matches the released checkpoint's, including its reasoning_effort levels (low, medium, high). Needs transformers>=5.22.0, peft>=0.21.0 and accelerate>=1.15.0.

    🎯 Unbiased importance sampling under top-k, top-p and min-p

    vLLM normalizes its log-probabilities over the tokens left after top_k, top_p and min_p filtering, while the trainer normalized over the whole vocabulary. Every sampled token's log-ratio was off by the log of the probability mass the filter kept, so the vLLM importance sampling ratio was biased towards 0 (around 1e-4 instead of 1 with top_p=0.9). The trainers now normalize over the candidate set each token was sampled from, following Keep Sampling Mask from DeepSeek-V3.2.

    💥 What this changes for you. vLLM bounds the candidate set it returns with top_k, so with vLLM and the importance sampling correction on (the default), GRPOConfig now raises when top_p < 1.0 or min_p > 0.0 is set without top_k > 0. Set top_k (e.g. top_k=512), or vllm_importance_sampling_correction=False.

    ⚖️ Score centering is the default AsyncGRPO objective

    AsyncGRPO's old log-probs are the vLLM sampler's, so its ratio mixes staleness with the numerical mismatch between the server and the trainer. With an FP8 sampler and a bf16 trainer, the clipped objective collapses: reward goes from 0.60 to 0.34 (FP8 weights) or 0.10 (FP8 weights + KV cache) by step 300, against 0.71 with a bf16 sampler.

    [Score centering](htt

  3. v1.16.02026-10-15 · 2026-10-15 18:00 UTC
    查看更新说明

    Features

    🛠️ TRL now trains on AWS Trainium

    The fused LM head from v1.15 is what made Neuron tractable; the remaining gaps are closed here. There is a guide to go with it.

    Neuron recompiles once per input shape, so an unpadded run stalls about a minute on every new sequence length. pad_to_multiple_of now defaults to "auto": 128 on Neuron, None elsewhere, so nothing changes on GPU. Trainium2, Qwen3-0.6B SFT, 20 steps: 130 s with the default against 260 s without.

    🌳 Tree attention for AsyncGRPO

    AsyncGRPO now packs every micro-batch row as a prefix tree instead of a flat sequence. Multi-turn and multi-generation rollouts repeat a lot of prefix: on a shared prompt, those tokens used to be forwarded once per row. Tree packing forwards them once.

    rollout 0:  [ prompt ] [ completion A ]              prompt ──┬── completion A ── later turn
    rollout 1:  [ prompt ] [ completion B ]        =>             └── completion B
    rollout 2:  [ prompt ] [ completion A ] [ … ]
    

    Chains without a fork collapse into segments, and each segment's queries attend to the K/V gathered along its root-to-segment path in a single FA3 varlen call. No mask tensor: every layer except attention runs once per unique token, and only K/V is duplicated along shared prefixes.

    Qwen3-1.7B, 32K tokens per rollout, forward + backward:

    layoutpacking ratiosequence packingtree packingpeak GiB
    shared prompt1.008677 ms8737 ms (0.99×)35.2 → 35.2
    shared prompt2.298266 ms4341 ms (1.90×)35.2 → 18.0
    shared prompt3.378179 ms2755 ms (2.97×)35.2 → 13.6
    nested fork1.608557 ms6217 ms (1.38×)35.2 → 23.8
    nested fork3.568172 ms2635 ms (3.10×)35.2 → 13.5

    There is no packing option to choose: with nothing shared a tree row is exactly the old sequence packing, at a ~1% cost.

    by @AmineDiro in https://github.com/huggingface/trl/pull/7328

    Muse Spark Open

    Support for meta-models/Muse-Spark-Open-816B-A42B: the tiny-model script, coverage in the VLM tests (SFT, DPO, KTO, chat-template utils, fused LM head), and a LoRA SFT example on 8 nodes of 8×H100 with DistributedConfig(fsdp_size=64, ep_size=8), token dispatch and packing. Measured at 14.2 s/step, 131k tokens/step, 40.2 GB per GPU.

    Needs transformers>=5.20.0; the adapter save additionally needs transformers#49500 with peft 0.21.2.

    by @qgallouedec in https://github.com/huggingface/trl/pull/7536

    AMD GPUs in the async trainers

    Tool-call arguments typed by the tool's JSON schema

    parse_response now receives the tools, so tool-call arguments come back typed from the tool's own schema instead of whatever the raw parse pr

  4. v1.15.02026-10-08 · 2026-10-08 19:26 UTC
    查看更新说明

    Features

    ⚡ Fused LM head: up to 6.9× longer sequences on the same GPU

    SFT, DPO, KTO, GRPO, RLOO and Distillation now score tokens with a fused LM head: a Triton kernel projects the hidden states through the LM head in tiles and reduces to per-token log-probs and entropy directly, so the [batch, seq, vocab] logits tensor is never built. It is on by default, there is nothing to turn on.

    Max trainable sequence length (gemma-3-1b, 262k vocabulary, 79 GiB of GPU memory, bf16, batch size 1, gradient checkpointing, sdpa):

    Trainerv1.14.2v1.15.0
    DPO10,24059,3925.80×
    KTO (batch size 2)9,21663,4886.89×
    GRPO (scoring only)28,672114,6884.00×
    RLOO (scoring only)23,552100,3524.26×
    SFT (loss_type="nll")20,480107,5205.25×
    SFT (default chunked_nll)107,520107,5201.00×

    At 8,192 tokens, peak memory drops 52% to 82% and steps are 2.3% to 10.9% faster:

    TrainerPeak GiB v1.14.2 → v1.15.0Tokens/s
    DPO48.97 → 12.00 (-75.5%)1.035×
    KTO64.91 → 11.98 (-81.5%)1.045×
    GRPO24.15 → 10.30 (-57.4%)1.023×
    RLOO29.28 → 14.02 (-52.1%)1.029×
    SFT (nll)30.33 → 8.87 (-70.7%)1.029×

    The gain is largest for small models with large vocabularies. SFT's previous default (chunked_nll) already avoided full logits, so it is unchanged. Scoring needs Triton on a GPU (Linux with CUDA, ROCm or XPU).

    💥 What this changes for you. The full-logits scoring path, the use_liger_kernel chunked path and _forward_redirection are gone from GRPO, RLOO, DPO and KTO:

    • A PEFT adapter on lm_head now raises. Use modules_to_save=["lm_head"] instead.
    • use_liger_kernel=True is deprecated in these four trainers and will be removed in v2.0.0. Liger's layer kernels still apply, but fused_linear_cross_entropy is forced to False (it would replace the fused head) and setting it explicitly raises. Use model_init_kwargs={"use_kernels": True}.
    • In DPO and KTO, compute_metrics and compute_loss(..., return_outputs=True) still receive the full logits, from an extra forward pass taken only when they are used. Both warn that this is deprecated and will be removed in v2.0.0.

    Nothing else the trainers logged is lost: the kernel gained log_sum_sq_probs (WPO weighting), mean_logits (logits/chosen, logits/rejected) and is_top1 (DPO's mean_token_accuracy) as opt-in outputs, each checked against the full logits in tests.

    1× B300 with the PyTorch allocator capped at 79 GiB (about an H100 80GB's usable memory), google/gemma-3-1b-pt built from its config with random bf16 weights, lr 1e-6, AdamW, synthetic token ids at exact length. Max length: one fresh process per attempt, 2 training steps, doubling from 8k then bisection to 1024 tokens, arms interleaved round-robin in the same job. Throughput: 12 steps, first 2 discarded, median of 3 A/B/A/B repeats in the same job. Noise floor (A vs A) is 0.1% to 0.8%, below every gap reported. GRPO/RLOO replace generation with fixed random completions, so only scoring is measured.

    Not measured: H100 hardware itself, flash-attention (sdpa only), real generation, multi-GPU.

  5. v1.14.22026-10-06 · 2026-10-06 20:30 UTC
    查看更新说明

    Patch release fixing two cases of silently wrong training and three crashes.

    Worth calling out: #7505 affects GRPO, RLOO and Distillation on the default generation path (use_vllm=False). Models that end a turn with an id only their generation config declares (Gemma 3/4, Phi-3.5, ...) did not stop at the end of the turn, and everything generated after it was trained on, up to max_completion_length. The only visible sign was completions/clipped_ratio close to 1. With vLLM, generation stopped correctly but the metrics were still wrong, and mask_truncated_completions=True dropped every finished completion. Runs on models whose tokenizer eos is their only end-of-turn id are unchanged.

    What's Changed

    Full Changelog: https://github.com/huggingface/trl/compare/v1.14.1...v1.14.2

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    TRL - Transformers Reinforcement Learning

    🎉 What's New

    🔥 Mistral Large 4: Fine-tune Mistral Large 4 with SFTTrainer on a single node of 8 B300s, on top of its FP8 weights. See the LoRA example.

    🚀 Training on AMD GPUs: TRL's trainers now run on AMD Instinct GPUs through PyTorch's ROCm build.

    🔥 Beam: Fine-tune Beam with SFTTrainer on a single node of 8 B300s. See the LoRA example.

    🔥 Muse Spark Open: Fine-tune Muse Spark Open with SFTTrainer, sharded across your GPUs at load time. See the 8-node LoRA example.

    🚀 Training on AWS Trainium: TRL's trainers now run on AWS Trainium through TorchNeuron, PyTorch's native Neuron backend.

    Overview

    TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), and Direct Preference Optimization (DPO). Built on top of the 🤗 Transformers ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups.

    Highlights

    • Trainers: Various fine-tuning methods are easily accessible via trainers like SFTTrainer, GRPOTrainer, DPOTrainer, KTOTrainer and more.

    • Efficient and scalable:

      • Leverages 🤗 Accelerate to scale from single GPU to multi-node clusters using methods like DDP and DeepSpeed.
      • Full integration with 🤗 PEFT enables training on large models with modest hardware via quantization and LoRA/QLoRA.
      • Integrates 🦥 Unsloth for accelerating training using optimized kernels.
    • Command Line Interface (CLI): A simple interface lets you fine-tune with models without needing to write code.

    Installation

    Python Package

    Install the library using pip:

    pip install trl
    

    From source

    If you want to use the latest features before an official release, you can install TRL from source:

    pip install git+https://github.com/huggingface/trl.git
    

    Repository

    If you want to use the examples you can clone the repository with the following command:

    git clone https://github.com/huggingface/trl.git
    

    Quick Start

    For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP.

    SFTTrainer

    Here is a basic example of how to use the SFTTrainer:

    from trl import SFTTrainer
    from datasets import load_dataset
    
    dataset = load_dataset("trl-lib/Capybara", split="train")
    
    trainer = SFTTrainer(
        model="Qwen/Qwen2.5-0.5B",
        train_dataset=dataset,
    )
    trainer.train()
    

    GRPOTrainer

    GRPOTrainer implements the Group Relative Policy Optimization (GRPO) algorithm that is more memory-efficient than PPO and was used to train Deepseek AI's R1. accuracy_reward needs math-verify, which you can install with pip install trl[math_verify].

    from datasets import load_dataset
    from trl import GRPOTrainer
    from trl.rewards import accuracy_reward
    
    dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
    
    trainer = GRPOTrainer(
        model="Qwen/Qwen2.5-0.5B-Instruct",
        reward_funcs=accuracy_reward,
        train_dataset=dataset,
    )
    trainer.train()
    

    [!NOTE] For reasoning models, use the reasoning_accuracy_reward() function for better results.

    DPOTrainer

    DPOTrainer implements the popular Direct Preference Optimization (DPO) algorithm that was used to post-train Llama 3 and many other models. Here is a basic example of how to use the DPOTrainer:

    from datasets import load_dataset
    from trl import DPOTrainer
    
    dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
    
    trainer = DPOTrainer(
        model="Qwen/Qwen3-0.6B",
        train_dataset=dataset,
    )
    trainer.train()
    

    KTOTrainer

    KTOTrainer implements the Kahneman-Tversky Optimization (KTO) algorithm, which aligns models from simple binary (desirable / undesirable) feedback rather than paired preferences. Here is a basic example of how to use the KTOTrainer:

    from datasets import load_dataset
    from trl import KTOTrainer
    
    dataset = load_dataset("trl-lib/kto-mix-14k", split="train")
    
    trainer = KTOTrainer(
        model="Qwen/Qwen3-0.6B",
        train_dataset=dataset,
    )
    trainer.train()
    

    RewardTrainer

    Here is a basic example of how to use the RewardTrainer:

    from trl import RewardTrainer
    from datasets import load_dataset
    
    dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
    
    trainer = RewardTrainer(
        model="Qwen/Qwen2.5-0.5B-Instruct",
        train_dataset=dataset,
    )
    trainer.train()
    

    Command Line Interface (CLI)

    You can use the TRL Command Line Interface (CLI) to quickly get started with post-training methods like Supervised Fine-Tuning (SFT) or Direct Preference Optimization (DPO):

    SFT:

    trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \
        --dataset_name trl-lib/Capybara \
        --output_dir Qwen2.5-0.5B-SFT
    

    DPO:

    trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
        --dataset_name argilla/Capybara-Preferences \
        --output_dir Qwen2.5-0.5B-DPO
    

    KTO:

    trl kto --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
        --dataset_name trl-lib/kto-mix-14k \
        --output_dir Qwen2.5-0.5B-KTO
    

    Read more about CLI in the relevant documentation section or use --help for more details.

    Development

    If you want to contribute to trl or customize it to your needs make sure to read the contribution guide and make sure you make a dev install:

    git clone https://github.com/huggingface/trl.git
    cd trl/
    pip install -e .[dev]
    

    Experimental

    A minimal incubation area is available under trl.experimental for unstable / fast-evolving features. Anything there may change or be removed in any release without notice.

    Example:

    from trl.experimental.new_trainer import NewTrainer
    

    Read more in the Experimental docs.

    Citation

    @software{vonwerra2020trl,
      title   = {{TRL: Transformers Reinforcement Learning}},
      author  = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin},
      license = {Apache-2.0},
      url     = {https://github.com/huggingface/trl},
      year    = {2020}
    }
    

    License

    This repository's source code is available under the Apache-2.0 License.