SKILL.md
SKILL.mdBrowse 7 files
3,635 tokens
13,505 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: trl-fine-tuning3description: "TRL: SFT, DPO, GRPO, RLOO reward modeling for LLM RLHF."4version: 1.0.15author: Orchestra Research6license: MIT7dependencies: [trl, transformers, datasets, peft, accelerate, torch]8platforms: [linux, macos, windows]9metadata:10 hermes:11 tags: [Post-Training, TRL, Reinforcement Learning, Fine-Tuning, SFT, DPO, GRPO, RLOO, RLHF, Preference Alignment, HuggingFace]12 13---14 15# TRL - Transformer Reinforcement Learning16 17## Quick start18 19TRL provides post-training methods for aligning language models with human preferences.20 21**Installation**:22```bash23pip install trl transformers datasets peft accelerate24```25 26**Supervised Fine-Tuning** (instruction tuning):27```python28from trl import SFTTrainer29 30trainer = SFTTrainer(31 model="Qwen/Qwen2.5-0.5B",32 train_dataset=dataset, # Prompt-completion pairs33)34trainer.train()35```36 37**DPO** (align with preferences):38```python39from trl import DPOTrainer, DPOConfig40 41config = DPOConfig(output_dir="model-dpo", beta=0.1)42trainer = DPOTrainer(43 model=model,44 args=config,45 train_dataset=preference_dataset, # chosen/rejected pairs46 processing_class=tokenizer47)48trainer.train()49```50 51## Common workflows52 53### Workflow 1: Full RLHF pipeline (SFT → Reward Model → RLOO)54 55Complete pipeline from base model to human-aligned model.56 57> **Note (TRL 1.x):** PPO has been **removed** from TRL — `PPOTrainer`, `PPOConfig`, and58> `python -m trl.scripts.ppo` no longer exist. Use an online-RL trainer TRL still ships:59> **RLOO** (`RLOOTrainer` / `trl rloo`) is the closest drop-in for a reward-model-driven60> RLHF pipeline, and **GRPO** (`GRPOTrainer` / `trl grpo`, see Workflow 3) is the61> memory-efficient alternative. The step below uses RLOO.62 63Copy this checklist:64 65```66RLHF Training:67- [ ] Step 1: Supervised fine-tuning (SFT)68- [ ] Step 2: Train reward model69- [ ] Step 3: RLOO reinforcement learning70- [ ] Step 4: Evaluate aligned model71```72 73**Step 1: Supervised fine-tuning**74 75Train base model on instruction-following data:76 77```python78from transformers import AutoModelForCausalLM, AutoTokenizer79from trl import SFTTrainer, SFTConfig80from datasets import load_dataset81 82# Load model83model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B")84tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")85 86# Load instruction dataset87dataset = load_dataset("trl-lib/Capybara", split="train")88 89# Configure training90training_args = SFTConfig(91 output_dir="Qwen2.5-0.5B-SFT",92 per_device_train_batch_size=4,93 num_train_epochs=1,94 learning_rate=2e-5,95 logging_steps=10,96 save_strategy="epoch"97)98 99# Train100trainer = SFTTrainer(101 model=model,102 args=training_args,103 train_dataset=dataset,104 processing_class=tokenizer105)106trainer.train()107trainer.save_model()108```109 110**Step 2: Train reward model**111 112Train model to predict human preferences:113 114```python115from transformers import AutoModelForSequenceClassification116from trl import RewardTrainer, RewardConfig117 118# Load SFT model as base119model = AutoModelForSequenceClassification.from_pretrained(120 "Qwen2.5-0.5B-SFT",121 num_labels=1 # Single reward score122)123tokenizer = AutoTokenizer.from_pretrained("Qwen2.5-0.5B-SFT")124 125# Load preference data (chosen/rejected pairs)126dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")127 128# Configure training129training_args = RewardConfig(130 output_dir="Qwen2.5-0.5B-Reward",131 per_device_train_batch_size=2,132 num_train_epochs=1,133 learning_rate=1e-5134)135 136# Train reward model137trainer = RewardTrainer(138 model=model,139 args=training_args,140 processing_class=tokenizer,141 train_dataset=dataset142)143trainer.train()144trainer.save_model()145```146 147**Step 3: RLOO reinforcement learning**148 149Optimize policy using the reward model. PPO was removed in TRL 1.x; use the RLOO CLI150(`trl rloo`) with the trained reward model passed via `--reward_model_name_or_path`:151 152```bash153trl rloo \154 --model_name_or_path Qwen2.5-0.5B-SFT \155 --reward_model_name_or_path Qwen2.5-0.5B-Reward \156 --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \157 --output_dir Qwen2.5-0.5B-RLOO \158 --learning_rate 3e-6 \159 --per_device_train_batch_size 64 \160 --num_generations 4161```162 163Equivalent Python (`RLOOTrainer` / `RLOOConfig`):164```python165from trl import RLOOTrainer, RLOOConfig166from transformers import AutoModelForSequenceClassification, AutoTokenizer167 168reward_model = AutoModelForSequenceClassification.from_pretrained(169 "Qwen2.5-0.5B-Reward", num_labels=1170)171 172config = RLOOConfig(173 output_dir="Qwen2.5-0.5B-RLOO",174 per_device_train_batch_size=64,175 learning_rate=3e-6,176 num_generations=4,177)178 179trainer = RLOOTrainer(180 model="Qwen2.5-0.5B-SFT",181 reward_funcs=reward_model, # a reward model (or a callable reward function)182 args=config,183 train_dataset=dataset, # prompt-only dataset184 processing_class=tokenizer,185)186trainer.train()187```188 189**Step 4: Evaluate**190 191```python192from transformers import pipeline193 194# Load aligned model195generator = pipeline("text-generation", model="Qwen2.5-0.5B-RLOO")196 197# Test198prompt = "Explain quantum computing to a 10-year-old"199output = generator(prompt, max_length=200)[0]["generated_text"]200print(output)201```202 203### Workflow 2: Simple preference alignment with DPO204 205Align model with preferences without reward model.206 207Copy this checklist:208 209```210DPO Training:211- [ ] Step 1: Prepare preference dataset212- [ ] Step 2: Configure DPO213- [ ] Step 3: Train with DPOTrainer214- [ ] Step 4: Evaluate alignment215```216 217**Step 1: Prepare preference dataset**218 219Dataset format:220```json221{222 "prompt": "What is the capital of France?",223 "chosen": "The capital of France is Paris.",224 "rejected": "I don't know."225}226```227 228Load dataset:229```python230from datasets import load_dataset231 232dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")233# Or load your own234# dataset = load_dataset("json", data_files="preferences.json")235```236 237**Step 2: Configure DPO**238 239```python240from trl import DPOConfig241 242config = DPOConfig(243 output_dir="Qwen2.5-0.5B-DPO",244 per_device_train_batch_size=4,245 num_train_epochs=1,246 learning_rate=5e-7,247 beta=0.1, # KL penalty strength248 max_prompt_length=512,249 max_length=1024,250 logging_steps=10251)252```253 254**Step 3: Train with DPOTrainer**255 256```python257from transformers import AutoModelForCausalLM, AutoTokenizer258from trl import DPOTrainer259 260model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")261tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")262 263trainer = DPOTrainer(264 model=model,265 args=config,266 train_dataset=dataset,267 processing_class=tokenizer268)269 270trainer.train()271trainer.save_model()272```273 274**CLI alternative**:275```bash276trl dpo \277 --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \278 --dataset_name argilla/Capybara-Preferences \279 --output_dir Qwen2.5-0.5B-DPO \280 --per_device_train_batch_size 4 \281 --learning_rate 5e-7 \282 --beta 0.1283```284 285### Workflow 3: Memory-efficient online RL with GRPO286 287Train with reinforcement learning using minimal memory.288 289For in-depth GRPO guidance — reward function design, critical training insights (loss behavior, mode collapse, tuning), and advanced multi-stage patterns — see **[references/grpo-training.md](references/grpo-training.md)**. A production-ready training script is in **[templates/basic_grpo_training.py](templates/basic_grpo_training.py)**.290 291Copy this checklist:292 293```294GRPO Training:295- [ ] Step 1: Define reward function296- [ ] Step 2: Configure GRPO297- [ ] Step 3: Train with GRPOTrainer298```299 300**Step 1: Define reward function**301 302```python303def reward_function(completions, **kwargs):304 """305 Compute rewards for completions.306 307 Args:308 completions: List of generated texts309 310 Returns:311 List of reward scores (floats)312 """313 rewards = []314 for completion in completions:315 # Example: reward based on length and unique words316 score = len(completion.split()) # Favor longer responses317 score += len(set(completion.lower().split())) # Reward unique words318 rewards.append(score)319 return rewards320```321 322Or use a reward model:323```python324from transformers import pipeline325 326reward_model = pipeline("text-classification", model="reward-model-path")327 328def reward_from_model(completions, prompts, **kwargs):329 # Combine prompt + completion330 full_texts = [p + c for p, c in zip(prompts, completions)]331 # Get reward scores332 results = reward_model(full_texts)333 return [r["score"] for r in results]334```335 336**Step 2: Configure GRPO**337 338```python339from trl import GRPOConfig340 341config = GRPOConfig(342 output_dir="Qwen2-GRPO",343 per_device_train_batch_size=4,344 num_train_epochs=1,345 learning_rate=1e-5,346 num_generations=4, # Generate 4 completions per prompt347 max_new_tokens=128348)349```350 351**Step 3: Train with GRPOTrainer**352 353```python354from datasets import load_dataset355from trl import GRPOTrainer356 357# Load prompt-only dataset358dataset = load_dataset("trl-lib/tldr", split="train")359 360trainer = GRPOTrainer(361 model="Qwen/Qwen2-0.5B-Instruct",362 reward_funcs=reward_function, # Your reward function363 args=config,364 train_dataset=dataset365)366 367trainer.train()368```369 370**CLI**:371```bash372trl grpo \373 --model_name_or_path Qwen/Qwen2-0.5B-Instruct \374 --dataset_name trl-lib/tldr \375 --output_dir Qwen2-GRPO \376 --num_generations 4377```378 379## When to use vs alternatives380 381**Use TRL when:**382- Need to align model with human preferences383- Have preference data (chosen/rejected pairs)384- Want to use reinforcement learning (RLOO, GRPO)385- Need reward model training386- Doing RLHF (full pipeline)387 388**Method selection**:389- **SFT**: Have prompt-completion pairs, want basic instruction following390- **DPO**: Have preferences, want simple alignment (no reward model needed)391- **RLOO**: Have a reward model, want online RL (the reward-model-driven RLHF path; PPO was removed in TRL 1.x)392- **GRPO**: Memory-constrained, want online RL with reward functions393- **Reward Model**: Building RLHF pipeline, need to score generations394 395**Use alternatives instead:**396- **HuggingFace Trainer**: Basic fine-tuning without RL397- **Axolotl**: YAML-based training configuration398- **LitGPT**: Educational, minimal fine-tuning399- **Unsloth**: Fast LoRA training400 401## Common issues402 403**Issue: OOM during DPO training**404 405Reduce batch size and sequence length:406```python407config = DPOConfig(408 per_device_train_batch_size=1, # Reduce from 4409 max_length=512, # Reduce from 1024410 gradient_accumulation_steps=8 # Maintain effective batch411)412```413 414Or use gradient checkpointing:415```python416model.gradient_checkpointing_enable()417```418 419**Issue: Poor alignment quality**420 421Tune beta parameter:422```python423# Higher beta = more conservative (stays closer to reference)424config = DPOConfig(beta=0.5) # Default 0.1425 426# Lower beta = more aggressive alignment427config = DPOConfig(beta=0.01)428```429 430**Issue: Reward model not learning**431 432Check loss type and learning rate:433```python434config = RewardConfig(435 learning_rate=1e-5, # Try different LR436 num_train_epochs=3 # Train longer437)438```439 440Ensure preference dataset has clear winners:441```python442# Verify dataset443print(dataset[0])444# Should have clear chosen > rejected445```446 447**Issue: Online RL (RLOO/GRPO) training unstable**448 449Adjust the KL/beta regularization toward the reference policy:450```python451from trl import RLOOConfig452 453config = RLOOConfig(454 beta=0.05, # KL coefficient toward the reference model (increase for stability)455 num_generations=4, # more samples per prompt = lower-variance advantage estimates456)457```458 459## Advanced topics460 461**SFT training guide**: See [references/sft-training.md](references/sft-training.md) for dataset formats, chat templates, packing strategies, and multi-GPU training.462 463**DPO variants**: See [references/dpo-variants.md](references/dpo-variants.md) for IPO, cDPO, RPO, and other DPO loss functions with recommended hyperparameters.464 465**Reward modeling**: See [references/reward-modeling.md](references/reward-modeling.md) for outcome vs process rewards, Bradley-Terry loss, and reward model evaluation.466 467**Online RL methods**: See [references/online-rl.md](references/online-rl.md) for PPO, GRPO, RLOO, and OnlineDPO with detailed configurations.468 469**GRPO deep dive**: See [references/grpo-training.md](references/grpo-training.md) for expert-level GRPO patterns — reward function design philosophy, training insights (why loss increases, mode collapse detection), hyperparameter tuning, multi-stage training, and troubleshooting. Production-ready template in [templates/basic_grpo_training.py](templates/basic_grpo_training.py).470 471## Hardware requirements472 473- **GPU**: NVIDIA (CUDA required)474- **VRAM**: Depends on model and method475 - SFT 7B: 16GB (with LoRA)476 - DPO 7B: 24GB (stores reference model)477 - RLOO 7B: 40GB (policy + reward model)478 - GRPO 7B: 24GB (more memory efficient)479- **Multi-GPU**: Supported via `accelerate`480- **Mixed precision**: BF16 recommended (A100/H100)481 482**Memory optimization**:483- Use LoRA/QLoRA for all methods484- Enable gradient checkpointing485- Use smaller batch sizes with gradient accumulation486 487## Resources488 489- Docs: https://huggingface.co/docs/trl/490- GitHub: https://github.com/huggingface/trl491- Papers:492 - "Training language models to follow instructions with human feedback" (InstructGPT, 2022)493 - "Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (DPO, 2023)494 - "Group Relative Policy Optimization" (GRPO, 2024)495- Examples: https://github.com/huggingface/trl/tree/main/examples/scripts496 497 498 499 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.