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に貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“私が選んだ回答と選ばれなかった回答のペアを使い、小さなQwenモデル向けに、TRLでDPOの学習スクリプトを書いてください。”
毎週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のコマンドラインツールhfでモデル、データセット、Spaces、リポジトリ、ローカルのキャッシュをダウンロード、アップロード、管理できるよう支援します。
hf-cloud-aws-context-discovery
11kエージェントが、クラウドの作業を始める前にAWSのプロファイル、リージョン、アカウントの詳細を見つけ、どのアカウントを使うかを推測しないよう支援します。
hf-cloud-python-env-setup
11kエージェントが、SageMakerやAWSの自動化を実行する前に、適切なPythonのバージョンと最新のライブラリで、クリーンなPython環境を設定できるよう支援します。
hf-cloud-sagemaker-deployment-planner
11kエージェントが、モデルをAmazon SageMakerにデプロイする方法を計画し、リアルタイム、サーバーレス、非同期、バッチのホスティングから、適切な既定値とともに選べるよう支援します。