Generated banner for Trl Training
Generated logo for Trl Training

Trl Training

Hugging FaceOfficialCreated by huggingfaceDistributed by Hugging Face

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • No issues found

From the author

Post-train LLMs with TRL (Transformers Reinforcement Learning) — SFT, DPO, GRPO, KTO, and reward-model training. Use when writing or debugging training code with the TRL Python API or the trl CLI.
— the description by huggingface

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The TRL library provides a robust framework for post-training Large Language Models. It offers specialized trainer classes such as SFTTrainer, DPOTrainer, and GRPOTrainer, each paired with corresponding configuration dataclasses. This skill covers the implementation of various training methods, dataset formatting requirements, and performance optimization techniques like sequence packing and vLLM integration for online reinforcement learning.

What it does

  • Provides implementation patterns for SFT, DPO, GRPO, KTO, and reward model training.
  • Explains the mapping between trainer classes and required dataset formats.
  • Details configuration options for memory optimization and training throughput.
  • Demonstrates how to define and integrate custom reward functions for GRPO.
  • Outlines CLI usage for launching training jobs and managing distributed configurations.
  • Covers advanced features like asynchronous training and vLLM integration.

When to use it

  • When you need to perform supervised fine-tuning or alignment on an LLM.
  • When implementing preference-based training like DPO or KTO.
  • When setting up online reinforcement learning workflows using GRPO.
  • When debugging or optimizing existing TRL training scripts.
  • When configuring training parameters for specific hardware constraints.

Advantages

  • Standardized API for multiple post-training methodologies.
  • Seamless integration with Hugging Face Transformers and Datasets.
  • Built-in support for performance features like packing and Liger kernels.
  • Flexible reward function definition for custom RL objectives.
  • Supports both Python script and CLI-based workflows.

Usage examples

“How do I initialize an SFTTrainer for a Qwen model?”
The agent provides a Python snippet using SFTTrainer and SFTConfig, demonstrating how to load a dataset and initiate the training loop.
“How can I define a custom reward function for GRPO?”
The agent explains how to write a function that accepts completions and returns a list of floats, showing how to pass it to the GRPOTrainer.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/huggingface/trl-training/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip trl-training.zip -d .agents/skills

Documentation by huggingface

TRL

Each method pairs a *Trainer class with a *Config dataclass. Configs extend transformers.TrainingArguments, so all of its arguments work in any trainer config.

TrainerDataset type
SFTTrainerlanguage modeling or prompt-completion
DPOTrainerpreference (chosen/rejected pairs)
GRPOTrainerprompt-only + reward function(s)
DistillationTrainerprompt-only + a teacher model (on-policy distillation)
KTOTrainerunpaired preference (per-sample bool label)
RewardTrainerpreference (chosen/rejected pairs); trains a scalar reward model, not a policy

Many more trainers (OnlineDPO, ORPO, CPO, GKD, …) live in trl.experimental with unstable APIs: https://huggingface.co/docs/trl/experimental_overview

from datasets import load_dataset
from trl import SFTConfig, SFTTrainer

trainer = SFTTrainer(
    model="Qwen/Qwen2.5-0.5B",  # model ID or a PreTrainedModel instance
    args=SFTConfig(output_dir="Qwen2.5-0.5B-SFT"),
    train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()

Pass model as a string and route loading kwargs through model_init_kwargs (e.g. {"dtype": "bfloat16", "attn_implementation": "kernels-community/flash-attn2"}) instead of calling from_pretrained yourself. The tokenizer/processor is inferred from the model; pass processing_class only when it differs. For LoRA, pass peft_config=LoraConfig(...).

Dataset formats

Conversational: {"messages": [{"role": ..., "content": ...}]} (language modeling) or {"prompt": [...], "completion": [...]}. The chat template is applied automatically — never apply it yourself. Extra columns are allowed; GRPO forwards them to reward functions. Reference: https://huggingface.co/docs/trl/dataset_formats

SFT: the fields that matter

SFTConfig(
    max_length=1024,        # truncation length; None disables truncation
    packing=True,           # pack sequences into max_length blocks: fewer pad tokens, higher throughput
    padding_free=True,      # flatten batch, no padding; requires FlashAttention; implied by packing
    use_liger_kernel=True,  # fused Liger kernels, reduces peak memory
    assistant_only_loss=True,  # loss only on assistant turns (conversational datasets)
)

GRPO: online RL

def reward_len(completions, **kwargs):
    return [-abs(20 - len(c[0]["content"])) for c in completions]

trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    reward_funcs=reward_len,  # or a list; rewards are summed
    args=GRPOConfig(output_dir="Qwen2.5-0.5B-GRPO", max_completion_length=512),
    train_dataset=load_dataset("trl-lib/DeepMath-103K", split="train"),
)

Reward functions are called with keyword arguments prompts, completions, completion_ids, trainer_state, plus every extra dataset column — accept **kwargs for the ones you ignore. Return list[float], one reward per completion. With conversational data, completions is a list of message lists, not strings.

The generation batch is per_device_train_batch_size × num_processes × steps_per_generation (or set generation_batch_size directly) and must be divisible by num_generations (default 8). Generation is the usual bottleneck — enable vLLM with use_vllm=True: vllm_mode="colocate" shares the training GPUs (size with vllm_gpu_memory_utilization); vllm_mode="server" uses a separate trl vllm-serve --model <model_id>.

AsyncGRPOTrainer (trl.experimental.async_grpo) implements the same algorithm with generation decoupled from training: a background worker streams completions from a vLLM server while the training loop consumes them, so the two overlap instead of alternating.

CLI

Flags mirror the config fields: trl sft --model_name_or_path Qwen/Qwen2.5-0.5B --dataset_name trl-lib/Capybara. YAML via --config; distributed presets via --accelerate_config zero3 (Python scripts: accelerate launch train.py).

Files

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
huggingface
Publisher
Hugging Face (Official)
Distributed by
Hugging Face
Source
huggingface/skills · skills/trl-training · commit 25910b3
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by huggingface or Hugging Face.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download trl-training.zip