Skip to main content
skill CX Codex

trl-training — Claude Code skill: what it does, how to install

Helps write and debug TRL post-training code for language models, including SFT, DPO, GRPO, KTO and reward-model training.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add huggingface/skills --skill trl-training -a claude-code
Open on GitHub

What trl-training does

This skill guides work with the TRL Python API and CLI for post-training language models. It covers SFTTrainer, DPOTrainer, GRPOTrainer, DistillationTrainer, KTOTrainer, and RewardTrainer; their configuration classes extend transformers.TrainingArguments.

It maps training methods to dataset shapes: chosen/rejected pairs for DPO, prompts plus reward functions for GRPO, and per-sample preference labels for KTO. Chat templates are applied automatically to conversational data, so applying them manually is a mistake. Trainers under trl.experimental have unstable APIs, which matters if your code depends on a fixed interface.

For SFT, it covers max_length, sequence packing, padding_free, Liger kernels, and assistant-only loss. For GRPO, reward functions return a list[float] per completion, while the generation batch must divide by num_generations, which defaults to 8. It also covers trl sft, YAML configuration, and accelerate launches.

What it helps with

  • write SFT code with SFTTrainer and SFTConfig
  • format preference pairs for DPOTrainer
  • implement a reward function for GRPOTrainer
  • configure LoRA with peft_config=LoraConfig(...)
  • run training through trl sft

Example prompts for the agent

  • Help me write SFT training code with SFTTrainer for my dataset.
  • Review my GRPOTrainer reward function: why does it receive conversational completions?
  • Build a trl sft command using a YAML config and --accelerate_config zero3.

How to install trl-training

1Skills CLI (Vercel)

npx skills add huggingface/skills --skill trl-training -a claude-code

2Manually: put the files in place

~/.claude/skills/trl-training/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/trl-training/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about trl-training

How do I install trl-training in Claude Code?

Run npx skills add huggingface/skills --skill trl-training -a claude-code. The skill is available at ~/.claude/skills/trl-training/SKILL.md.

What does trl-training do?

It is a skill for writing and debugging TRL post-training code. It covers SFT, DPO, GRPO, KTO, distillation, and reward-model training.

What should I account for when using GRPO?

Reward functions return a list[float], with one value for each completion. The generation batch must be divisible by num_generations; generation can use vLLM through use_vllm=True.

Source text

SKILL.md · Apache-2.0
---
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`).

© huggingface · Apache-2.0 · huggingface/skills

Similar skills

Everything for AI and ML →

From the same set25

huggingface-tool-builder A skill for building reusable command-line scripts that fetch, enrich, and process data from Hugging Face. Useful when chaining multiple API calls or running repeated automation tasks. CX Codex +1 1,600installs train-sentence-transformers A Claude Code skill that walks an agent through training sentence-transformers models, from picking the encoder type to pushing weights to the Hugging Face Hub. CX Codex +1 1,500installs huggingface-zerogpu Skill for Gradio apps on Hugging Face Spaces with ZeroGPU: where @spaces.GPU belongs, how to size duration, what breaks at the worker boundary. CX Codex +1 1,300installs huggingface-spaces This skill helps build, deploy, and debug apps on Hugging Face Spaces. Use it for Gradio, Docker, Static SDKs, model loading, and ZeroGPU. CX Codex +1 1,100installs hf-mem Estimates the memory a Hugging Face model needs for inference without downloading the weights. Useful before you commit a GPU to a model. CX Codex +1 858installs huggingface-lora-space-builder Builds and publishes Gradio demos on Hugging Face Spaces for LoRA checkpoints. Tailors diffusers pipelines and UI inputs, targeting ZeroGPU hardware by default. CX Codex +1 810installs hf-cloud-sagemaker-production-defaults This skill creates SageMaker endpoints with autoscaling, CloudWatch alarms, and tags. Use it for the final model deployment step. CX Codex +1 549installs hf-cloud-python-env-setup Configures an isolated Python environment for AWS and SageMaker automation. It ensures compatible Python versions and installs up-to-date boto3 to avoid API mismatches. CX Codex +1 548installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor