trl-training
它能做什么
这个技能帮助 AI 编写和修复在语言模型初次训练之后对其进行改进的训练代码。适合希望使用 TRL 微调或对齐模型的开发者。
适用场景
- ✓当你想用 SFT 微调语言模型,或用偏好数据对其进行对齐时。
- ✓当你想用 Python 或命令行编写或调试 TRL 训练代码的时候。
- ✓当你需要使用奖励函数进行强化学习,例如 GRPO 的时候。
技能链接
https://github.com/huggingface/skills/blob/main/skills/trl-training/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请用 TRL 写一个 DPO 训练脚本,使用我选择和拒绝的答案配对,训练一个小型 Qwen 模型。”
每周 5 个新技能,1 分钟读完。
工作原理
AI 会根据方法和数据集类型,选择合适的训练器以及匹配的配置。然后它使用标准的 TRL 类和选项,编写或修复 Python 代码或命令。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
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
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).
常见问题
它涵盖哪些训练方法?
它涵盖 SFT、DPO、GRPO、KTO、奖励建模和蒸馏,其他实验性方法也有列出。
数据需要什么格式?
格式取决于训练器,例如 DPO 需要选择和拒绝的配对,GRPO 需要带奖励函数的提示。
它会处理模型加载吗?
会。它以模型名称传入模型,并使用加载选项,而不是手动加载模型。
详情
作者的原始描述
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.
repo: huggingface/skills
热度
- GitHub 星标
- 11k
- 排名
- #11783
- 许可证
- Apache-2.0
- 更新时间
- 2026/10/30
评论
- …
同一仓库的更多技能
hf-cli
11k帮你的智能体使用 Hugging Face 命令行工具,下载、上传和管理模型、数据集、Spaces、仓库以及本地缓存。
hf-cloud-aws-context-discovery
11k帮你的智能体在进行任何云端工作之前,找到你的 AWS 配置文件、区域和账户信息,避免猜测该使用哪个账户。
hf-cloud-python-env-setup
11k帮你的智能体设置一个干净的 Python 环境,使用合适的 Python 版本和最新的库,然后再运行 SageMaker 或 AWS 自动化脚本。
hf-cloud-sagemaker-deployment-planner
11k帮你的智能体规划如何把模型部署到 Amazon SageMaker,在实时、无服务器、异步或批量托管之间进行选择,并使用合理的默认设置。