Introduction¶
When using large models for SFT, DPO, or online RL with reward functions, the difficulty often isn’t “do we have libraries,” but how to configure APIs, whether dataset column names and formats are correct, whether generation batch size is divisible by num_generations, and whether we should apply the chat template manually. TRL (Transformers Reinforcement Learning) consolidates many post-training methods into a unified Trainer + Config pattern, but its documentation is scattered and experimental APIs abound, making it easy to flip back and forth when writing training scripts or troubleshooting. Hugging Face provides trl-training in the official Skills repository: it encodes TRL’s Python API and trl CLI conventions into an Agent-followable SKILL.md, suitable for letting coding assistants in environments like Cursor, Codex, or Claude Code write code or look up configuration using the same set of facts.
What Is This¶
trl-training is a workflow Skill in the Hugging Face Skills repository that follows the Agent Skills standard: the directory contains a SKILL.md with a YAML frontmatter, and once activated it guides Agents to perform post-training of language models using TRL.
- Maintainer: Hugging Face (
metadata.author: huggingface) - License: Apache-2.0
- Official documentation entry: https://huggingface.co/docs/trl
- Skill source path: skills/trl-training
The Skill describes its purpose as: use when writing or debugging training code based on TRL’s Python API or the trl CLI; it covers post-training paths such as SFT, DPO, GRPO, KTO, and reward model training.
Unlike huggingface-llm-trainer in the same repository (which focuses on TRL/Unsloth and Hugging Face Jobs infrastructure), trl-training stays closer to local scripts and CLI-level TRL usage and troubleshooting.
Core Features¶
TRL’s design is: each method corresponds to a *Trainer class and a *Config dataclass; the Config inherits from transformers.TrainingArguments, so Transformers training parameters are available in any Trainer config.
| Trainer | Dataset Type |
|---|---|
SFTTrainer |
Language modeling or prompt-completion |
DPOTrainer |
Preference data (chosen/rejected pairs) |
GRPOTrainer |
Prompts only + reward function |
DistillationTrainer |
Prompts only + teacher model (on-policy distillation) |
KTOTrainer |
Unpaired preference (boolean label per sample) |
RewardTrainer |
Preference pairs; trains a scalar reward model instead of a policy |
More Trainers (such as OnlineDPO, ORPO, CPO, GKD, etc.) are located under trl.experimental, and their APIs are unstable; see the experimental overview.
Data and training points emphasized in the Skill also include:
- Model loading:
modelcan be a Hub ID string; loading parameters are passed viamodel_init_kwargs; tokenizer/processor are inferred from the model by default; for LoRA usepeft_config=LoraConfig(...). - Dataset formats: Conversational
messagesorprompt/completion; TRL automatically applies the chat template—do not manually wrap templates. Extra columns can be retained; GRPO passes extra columns to the reward function. See dataset formats. - Common SFT configuration items:
max_length,packing,padding_free(requires FlashAttention),use_liger_kernel,assistant_only_loss, etc. - GRPO: Custom
reward_funcsmust accept**kwargs; with conversational data,completionsare message lists rather than plain strings; the divisibility relationship between generation batch size andnum_generations, and accelerating generation viause_vllm, etc. - CLI: Subcommands map to config fields; supports YAML
--configand distributed presets like--accelerate_config zero3.
Installation and Activation¶
The Skills repository explains: aside from the marketplace/bootstrap hf-cli, other workflow Skills can be installed on demand via hf skills add <skill-name>; clients that support Skills can also discover them via CLI/MCP.
With the Hugging Face CLI in place, install this Skill:
hf skills add trl-training
Cursor: The repository provides .cursor-plugin/plugin.json and MCP config; the marketplace entry is primarily hf-cli, and for additional Skills it’s still recommended to use hf skills add trl-training.
Claude Code: First register the marketplace and install hf-cli, then run hf skills add trl-training.
Codex: Copy or symlink skills/trl-training into Codex’s .agents/skills path, and the client will load SKILL.md per the Agent Skills standard.
If your runtime does not support Skills, the repository provides agentsmd/AGENTS.md as a fallback bundle.
For training itself, you still need to install TRL and dependencies on your machine or job environment (the Skill guides how to use the API; it does not replace pip install trl or similar environment preparation).
Typical Usage¶
Supervised Fine-Tuning (SFT)¶
Below is a minimal runnable example using a small model from the Hub and the trl-lib/Capybara dataset:
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B", # model ID or PreTrainedModel instance
args=SFTConfig(output_dir="Qwen2.5-0.5B-SFT"),
train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()
To control truncation, packing, and memory usage, you can set, for example, in SFTConfig:
SFTConfig(
max_length=1024, # truncation length; None means no truncation
packing=True, # pack sequences into max_length blocks to reduce padding and improve throughput
padding_free=True, # flatten batch, no padding; requires FlashAttention; implied when packing is on
use_liger_kernel=True, # fuse Liger kernel to lower peak memory
assistant_only_loss=True, # compute loss only on assistant turns (for conversational datasets)
)
Online RL: GRPO and Custom Rewards¶
The reward function returns a float for each completion; ignore extra parameters by accepting **kwargs:
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; multiple 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"),
)
The generation stage is usually the bottleneck. You can set use_vllm=True: vllm_mode="colocate" shares GPUs with training (control memory via vllm_gpu_memory_utilization); vllm_mode="server" requires starting trl vllm-serve --model <model_id> separately. The experimental AsyncGRPOTrainer (trl.experimental.async_grpo) can decouple vLLM generation from the training loop to run in parallel.
CLI¶
Config options map to command-line flags; for example:
trl sft --model_name_or_path Qwen/Qwen2.5-0.5B --dataset_name trl-lib/Capybara
You can also use --config to specify YAML; for distributed runs, use --accelerate_config zero3 (on the Python script side, accelerate launch train.py is commonly used).
Use Cases and Caveats¶
Who It’s For
- Those who want to write SFT, DPO, GRPO, KTO, or reward model training scripts with TRL on local machines or their own clusters, and want an Agent to generate code per HF documentation conventions, minimizing formatting and configuration errors.
- Those debugging TRL training (batching and generation,
reward_funcssignatures, vLLM modes, etc.) who need a referenceable Skill context.
Limitations and Notes
- Trainer APIs under
trl.experimentalare unstable; for production, prefer classes in the stable table. - Do not apply chat templates manually to conversational data; mismatched formats can cause abnormal Trainer behavior.
- In GRPO,
generation_batch_size(or derived fromper_device_train_batch_size × num_processes × steps_per_generation) must be divisible bynum_generations(default 8). - The Skill provides workflows and API conventions; it doesn’t guarantee choosing compute or Hub quotas for you. It complements the Jobs flow of huggingface-llm-trainer—choose the Skill based on whether you’re doing “local TRL” or “HF Jobs-hosted training.”
Summary¶
trl-training consolidates TRL’s main post-training Trainers, dataset formats, key SFT/GRPO configurations, and trl CLI usage into Agent-executable instructions, suitable as an official tutorial-style Skill for alignment and fine-tuning topics. For installation and updates, follow the repository docs; for details, refer to the TRL documentation.
- Skill directory: https://github.com/huggingface/skills/tree/main/skills/trl-training
- TRL documentation: https://huggingface.co/docs/trl