grpo-rl-training
하는 일
이 스킬은 TRL 라이브러리로 GRPO를 학습하는 방법을 설명합니다. 특정 형식이나 수학, 코드처럼 검증 가능한 기술을 모델에 가르치려는 개발자를 위한 스킬입니다.
사용하는 경우
- ✓XML 태그나 JSON처럼 엄격한 출력 형식을 따르게 하고 싶을 때.
- ✓수학, 코딩, 사실 확인 작업에서 올바른 답에 보상을 주고 싶을 때.
- ✓형식, 정확성, 문체처럼 여러 목표를 함께 적용하고 싶은 경우.
스킬 링크
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/06-post-training/grpo-rl-training/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“제 언어 모델이 수학 문제를 정확하게 풀고, 항상 정해진 형식으로 풀이 과정을 보여 주도록 학습시켜 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
모델은 각 프롬프트마다 여러 답변을 생성합니다. 보상 함수가 각 답변을 점수 매기고, 학습은 같은 그룹 안에서 점수가 높은 답변 쪽으로 모델을 옮깁니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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)
Do NOT use GRPO for:
- 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)
Core Concepts
1. GRPO Algorithm Fundamentals
Key Mechanism:
- 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
Critical Difference from PPO:
- No separate reward model needed
- More sample-efficient (learns from within-group comparisons)
- Simpler to implement and debug
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:
- Compose multiple reward functions - Each handles one aspect (format, correctness, style)
- Scale rewards appropriately - Higher weight = stronger signal
- Use incremental rewards - Partial credit for partial compliance
- 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 |
Implementation Workflow
Step 1: Dataset Preparation
Critical Requirements:
- 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
Example Structure:
from datasets import load_dataset, Dataset
SYSTEM_PROMPT = """
Respond in the following format:
<reasoning>
[Your step-by-step thinking]
</reasoning>
<answer>
[Final answer]
</answer>
"""
def prepare_dataset(raw_data):
"""
Transform raw data into GRPO-compatible format.
Returns: Dataset with columns:
- 'prompt': List[Dict] with role/content (system + user messages)
- 'answer': str (ground truth, optional but recommended)
"""
return raw_data.map(lambda x: {
'prompt': [
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': x['question']}
],
'answer': extract_answer(x['raw_answer'])
})
Pro Tips:
- 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)
Step 2: Reward Function Implementation
Template Structure:
def reward_function_name(
prompts, # List[List[Dict]]: Original prompts
completions, # List[List[Dict]]: Model generations
answer=None, # Optional: Ground truth from dataset
**kwargs # Additional dataset columns
) -> list[float]:
"""
Evaluate completions and return rewards.
Returns: List of floats (one per completion)
"""
# Extract completion text
responses = [comp[0]['content'] for comp in completions]
# Compute rewards
rewards = []
for response in responses:
score = compute_score(response)
rewards.append(score)
return rewards
Example 1: Correctness Reward (Math/Coding)
def correctness_reward(prompts, completions, answer, **kwargs):
"""Rew
자주 묻는 질문
언제 GRPO를 쓰지 말아야 하나요?
간단한 작업에는 지도 미세 조정을, 이미 선호 쌍이 있다면 DPO나 PPO를 쓰라고 이 스킬은 말합니다.
별도의 보상 모델이 필요한가요?
아니요. 보상 함수가 점수를 매기므로 GRPO는 별도의 보상 모델이 필요 없다고 이 스킬은 설명합니다.
프롬프트마다 몇 개의 답변을 생성하나요?
그룹 크기를 4에서 16 사이로 권장합니다.
상세 정보
작성자의 원본 설명
Expert guidance for GRPO/RL fine-tuning with TRL for reasoning and task-specific model training
인기도
- GitHub 스타
- 14k
- 순위
- #11190
- 라이선스
- MIT
- 업데이트
- 2026. 10. 10.
댓글
- …
이 저장소의 다른 스킬
autoresearch
14k에이전트가 문헌 검토부터 실험과 글쓰기까지 AI 연구 프로젝트 전체를 진행하도록 안내합니다. 테스트와 검토를 반복하는 주기를 따릅니다.
prompt-guard
14k에이전트가 Meta의 작은 분류기로, AI 앱에 도달하기 전에 텍스트에서 프롬프트 인젝션과 탈옥 시도를 검사하도록 돕습니다.
pytorch-fsdp2
14k에이전트가 PyTorch FSDP2를 학습 스크립트에 추가해, 큰 모델을 여러 GPU에 나누고 올바르게 저장하도록 보여 줍니다.
ml-training-recipes
14k에이전트에게 모델 선택, 옵티마이저, 학습률, 손실 급등 해결 등 신경망 학습의 검증된 방법을 알려 줍니다.