Agent Skill
TRL post-training (Hugging Face)
Hugging Face's compact reference for TRL trainers (SFT, DPO, GRPO, KTO, reward models): dataset formats, the config fields that matter and the TRL CLI.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkInstall
Commands are pinned to commit 5291c2b, the version we read, wherever the install method supports it.
npx skills
npx skills add huggingface/skills@5291c2b9365e06b175dc04817610c778623f4836 --skill trl-training -a claude-codeCopies the skill into .claude/skills/ in this project, pinned to the reviewed commit.
npx skills
npx skills add huggingface/skills@5291c2b9365e06b175dc04817610c778623f4836 --skill trl-training -a codexInstalls to .agents/skills/, which Codex scans from the working directory up to the repo root.
npx skills
npx skills add huggingface/skills@5291c2b9365e06b175dc04817610c778623f4836 --skill trl-training -a cursorInstalls to .agents/skills/, one of the folders Cursor reads skills from.
gh skill
gh skill install huggingface/skills skills/trl-training --pin 5291c2b9365e06b175dc04817610c778623f4836 --agent github-copilotNeeds GitHub CLI 2.90.0 or later. Use --scope user to install for every repository.
npx skills
npx skills add huggingface/skills@5291c2b9365e06b175dc04817610c778623f4836 --skill trl-trainingPinned to the commit we reviewed. The CLI asks which agents to install for; add -g to install for your user instead of this project.
What it does
A compact reference for TRL, Hugging Face’s post-training library. A table maps each trainer to the dataset it expects: SFTTrainer for language modelling or prompt-completion data, DPOTrainer and RewardTrainer for chosen and rejected pairs, GRPOTrainer for prompts plus reward functions, KTOTrainer for unpaired preferences, and DistillationTrainer for on-policy distillation from a teacher. It then gives the details models tend to get wrong: pass the model as a string and route loading options through model_init_kwargs, never apply the chat template yourself, the SFT fields that matter (max_length, packing, assistant_only_loss, Liger kernels), how GRPO reward functions receive their arguments, how the generation batch must divide by num_generations, and when to turn on vLLM. It ends with the trl CLI.
When to use it
Writing or debugging a TRL training script on your own hardware or a cloud GPU you manage. At 77 lines it loads cheaply and gets straight to the parameters.
When to skip it
When you want the agent to run the job for you on Hugging Face’s infrastructure: use huggingface-llm-trainer, which covers submission, cost and monitoring. And when fine-tuning may not be the right answer at all; our fine-tuning page covers when it pays off.
Try it
Write a DPO training script with TRL for Qwen2.5-0.5B-Instruct on my
preference dataset data/prefs.jsonl (fields: prompt, chosen, rejected).
Use bf16, a 1,024-token max length and a held-out 5% eval split.
What it can touch
- Bundles scripts
- No
- Pre-approved tools
- None declared
- Needs
- Python with trl installed; A GPU for real runs
- Client-specific fields
- None, spec fields only
- Files
- At commit
5291c2bthe SKILL.md is 77 lines long and is the only file in the folder.
Its instructions steer what your agent does, and it may have changed since the commit we read. How to check a skill.
Instructions only, with links to TRL’s documentation. Training runs that the agent starts use your GPU and download models and datasets from the Hub. Licensed Apache-2.0.
Alternatives
huggingface-llm-trainer for managed jobs, and hf-cli for moving models and datasets to and from the Hub. Glossary entries for GRPO, DPO and LoRA explain the methods.
SKILL.md
The file exactly as published at the reviewed commit, reproduced under its Apache-2.0 licence.
---
name: trl-training
description: 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.
license: Apache-2.0
metadata:
author: huggingface
documentation: https://huggingface.co/docs/trl
---
# 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.
| Trainer | Dataset type |
|---|---|
| `SFTTrainer` | language modeling or prompt-completion |
| `DPOTrainer` | preference (chosen/rejected pairs) |
| `GRPOTrainer` | prompt-only + reward function(s) |
| `DistillationTrainer` | prompt-only + a teacher model (on-policy distillation) |
| `KTOTrainer` | unpaired preference (per-sample bool label) |
| `RewardTrainer` | preference (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
```python
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
```python
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
```python
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`).Related skills
LLM trainer on Hugging Face Jobs (Hugging Face)
Fine-tunes language and vision models with TRL or Unsloth on Hugging Face Jobs: SFT, DPO, GRPO, cost estimates, dataset checks and GGUF export.
MCP server builder
A four-phase guide to designing, building, testing and evaluating MCP servers in Python (FastMCP) or TypeScript, with reference docs and an eval harness.
Build an MCP server
Anthropic's entry point for MCP server work in Claude Code: asks about your use case, picks a deployment model and tool-design pattern, then hands off.
Guides and recipes that use TRL post-training (Hugging Face)
- TRL
Hugging Face's post-training library: supervised fine-tuning, DPO, GRPO and reward models.
- GRPO
Group Relative Policy Optimization: an RL method that samples a group of answers to one prompt and learns from their relative rewards.
- Fine-tuning
Further training a model on task-specific examples, and knowing when RAG is enough.