name: grpo-rl-training
description: Expert guidance for GRPO/RL fine-tuning with TRL for reasoning and task-specific model training
version: 1.0.0
author: Orchestra Research
license: MIT
dependencies: [transformers>=4.47.0, trl>=0.14.0, datasets>=3.2.0, peft>=0.14.0, torch]
metadata:
hermes:
tags: [Post-Training, Reinforcement Learning, GRPO, TRL, RLHF, Reward Modeling, Reasoning, DPO, PPO, Structured Output]
GRPO/RL Training with TRL
Expert-level guidance for implementing Group Relative Policy Optimization (GRPO) using the Transformer Reinforcement Learning (TRL) library. This skill provides battle-tested patterns, critical insights, and production-ready workflows for fine-tuning language models with custom reward functions.
When to Use This Skill
Use GRPO training when you need to:
- - Enforce specific output formats (e.g., XML tags, JSON, structured reasoning)
- - Teach verifiable tasks with objective correctness metrics (math, coding, fact-checking)
- - Improve reasoning capabilities by rewarding chain-of-thought patterns
- - Align models to domain-specific behaviors without labeled preference data
- - Optimize for multiple objectives simultaneously (format + correctness + style)
- - Simple supervised fine-tuning tasks (use SFT instead)
- - Tasks without clear reward signals
- - When you already have high-quality preference pairs (use DPO/PPO instead)
- - Generates multiple completions for each prompt (group size: 4-16)
- - Compares completions within each group using reward functions
- - Updates policy to favor higher-rewarded responses relative to the group
- - No separate reward model needed
- - More sample-efficient (learns from within-group comparisons)
- - Simpler to implement and debug
- - Prompts in chat format (list of dicts with 'role' and 'content')
- - Include system prompts to set expectations
- - For verifiable tasks, include ground truth answers as additional columns
- - Use one-shot or few-shot examples in system prompt for complex formats
- - Keep prompts concise (max_prompt_length: 256-512 tokens)
- - Validate data quality before training (garbage in = garbage out)
- - Loss starts near 0 and INCREASES during training
- - This is CORRECT - loss measures KL divergence from initial policy
- - Model is learning (diverging from original behavior to optimize rewards)
- - Monitor reward metrics instead of loss for progress
- -
reward: Average across all completions - -
reward_std: Diversity within groups (should remain > 0) - -
kl: KL divergence from reference (should grow moderately) - - Reward std → 0 (model collapsing to single response)
- - KL exploding (> 0.5) (diverging too much, reduce LR)
- - Reward stuck (reward functions too harsh or model capacity issue)
- - [ ] Validate dataset format (prompts as List[Dict])
- - [ ] Test reward functions on sample data
- - [ ] Calculate expected max_prompt_length from data
- - [ ] Choose appropriate num_generations based on GPU memory
- - [ ] Set up logging (wandb recommended)
- - [ ] Monitor reward progression (should increase)
- - [ ] Check reward_std (should stay > 0.1)
- - [ ] Watch for OOM errors (reduce batch size if needed)
- - [ ] Sample generations every 50-100 steps
- - [ ] Validate format compliance on holdout set
- - [ ] Merge LoRA weights if using PEFT
- - [ ] Test on diverse prompts
- - [ ] Compare to baseline model
- - [ ] Document reward weights and hyperparameters
- - [ ] Save reproducibility config
- - TRL GRPO Trainer: https://huggingface.co/docs/trl/grpo_trainer
- - DeepSeek R1 Paper: https://arxiv.org/abs/2501.12948
- - Unsloth Docs: https://docs.unsloth.ai/
- - Open R1 Implementation: https://github.com/huggingface/open-r1
- - TRL Examples: https://github.com/huggingface/trl/tree/main/examples
- - Progressive Disclosure Pattern for agent instructions
- - Reward shaping in RL (Ng et al.)
- - LoRA paper (Hu et al., 2021)
- - Always use multiple reward functions (3-5 is optimal)
- - Monitor reward metrics, not loss
- - Test reward functions before training
- - Start small (num_generations=4), scale up gradually
- - Save checkpoints frequently (every 100 steps)
Do NOT use GRPO for:
Core Concepts
1. GRPO Algorithm Fundamentals
Key Mechanism:
Critical Difference from PPO:
Mathematical Intuition:
`
For each prompt p:
1. Generate N completions: {c₁, c₂, ..., cₙ}
2. Compute rewards: {r₁, r₂, ..., rₙ}
3. Learn to increase probability of high-reward completions
relative to low-reward ones in the same group
`
2. Reward Function Design Philosophy
Golden Rules:
1. Compose multiple reward functions - Each handles one aspect (format, correctness, style)
2. Scale rewards appropriately - Higher weight = stronger signal
3. Use incremental rewards - Partial credit for partial compliance
4. Test rewards independently - Debug each reward function in isolation
Reward Function Types:
| Type | Use Case | Example Weight |
| ------ | ---------- | ---------------- |
| Correctness | Verifiable tasks (math, code) | 2.0 (highest) |
| Format | Strict structure enforcement | 0.5-1.0 |
| Length | Encourage verbosity/conciseness | 0.1-0.5 |
| Style | Penalize unwanted patterns | -0.5 to 0.5 |
| Parameter | Impact | Tuning Advice |
| ----------- | -------- | --------------- |
num_generations | Group size for comparison | Start with 8, increase to 16 if GPU allows |
learning_rate | Convergence speed/stability | 5e-6 (safe), 1e-5 (faster, riskier) |
max_completion_length | Output verbosity | Match your task (512 for reasoning, 256 for short answers) |
gradient_accumulation_steps | Effective batch size | Increase if GPU memory limited |
| Problem | Symptom | Solution |
| --------- | --------- | ---------- |
| Mode collapse | All completions identical | Increase num_generations, add diversity penalty |
| No learning | Flat rewards | Check reward function logic, increase LR |
| OOM errors | GPU memory exceeded | Reduce num_generations, enable gradient checkpointing |
| Slow training | < 1 it/s | Enable use_vllm=True, use Unsloth, reduce seq length |
| Format ignored | Model doesn't follow structure | Increase format reward weight, add incremental rewards |
Advanced Patterns
1. Multi-Stage Training
For complex tasks, train in stages:
`python
Stage 1: Format compliance (epochs=1)
trainer_stage1 = GRPOTrainer(
model=model,
reward_funcs=[incremental_format_reward, format_reward],
...
)
trainer_stage1.train()
Stage 2: Correctness (epochs=1)
trainer_stage2 = GRPOTrainer(
model=model,
reward_funcs=[format_reward, correctness_reward],
...
)
trainer_stage2.train()
`
2. Adaptive Reward Scaling
`python
class AdaptiveReward:
def __init__(self, base_reward_func, initial_weight=1.0):
self.func = base_reward_func
self.weight = initial_weight
def __call__(self, args, *kwargs):
rewards = self.func(args, *kwargs)
return [r * self.weight for r in rewards]
def adjust_weight(self, success_rate):
"""Increase weight if model struggling, decrease if succeeding."""
if success_rate < 0.3:
self.weight *= 1.2
elif success_rate > 0.8:
self.weight *= 0.9
`
3. Custom Dataset Integration
`python
def load_custom_knowledge_base(csv_path):
"""Example: School communication platform docs."""
import pandas as pd
df = pd.read_csv(csv_path)
dataset = Dataset.from_pandas(df).map(lambda x: {
'prompt': [
{'role': 'system', 'content': CUSTOM_SYSTEM_PROMPT},
{'role': 'user', 'content': x['question']}
],
'answer': x['expert_answer']
})
return dataset
`
Deployment and Inference
Save and Merge LoRA
`python
Merge LoRA adapters into base model
if hasattr(trainer.model, 'merge_and_unload'):
merged_model = trainer.model.merge_and_unload()
merged_model.save_pretrained("production_model")
tokenizer.save_pretrained("production_model")
`
Inference Example
`python
from transformers import pipeline
generator = pipeline(
"text-generation",
model="production_model",
tokenizer=tokenizer
)
result = generator(
[
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': "What is 15 + 27?"}
],
max_new_tokens=256,
do_sample=True,
temperature=0.7,
top_p=0.9
)
print(result[0]['generated_text'])
`
Best Practices Checklist
Before Training:
During Training:
After Training:
Troubleshooting Guide
Debugging Workflow
1. Isolate reward functions - Test each independently
2. Check data distribution - Ensure diversity in prompts
3. Reduce complexity - Start with single reward, add gradually
4. Monitor generations - Print samples every N steps
5. Validate extraction logic - Ensure answer parsing works
Quick Fixes
`python
Debug reward function
def debug_reward(completions, **kwargs):
responses = [comp[0]['content'] for comp in completions]
for i, r in enumerate(responses[:2]): # Print first 2
print(f"Response {i}: {r[:200]}...")
return [1.0] * len(responses) # Dummy rewards
Test without training
trainer = GRPOTrainer(..., reward_funcs=[debug_reward])
trainer.generate_completions(dataset[:1]) # Generate without updating
`
References and Resources
Official Documentation:
Example Repositories:
Recommended Reading:
Usage Instructions for Agents
When this skill is loaded:
1. Read this entire file before implementing GRPO training
2. Start with the simplest reward function (e.g., length-based) to validate setup
3. Use the templates in templates/ directory as starting points
4. Reference examples in examples/ for task-specific implementations
5. Follow the workflow sequentially (don't skip steps)
6. Debug incrementally - add one reward function at a time
Critical Reminders:
This skill is designed for expert-level implementation. Beginners should start with supervised fine-tuning before attempting GRPO.