post-training-grpo-rl-training
하는 일
이 스킬은 TRL 라이브러리로 GRPO 강화 학습을 하는 과정을 AI가 안내합니다. 정답과 오답이 분명한 보상이 있는 작업에서 모델을 학습시키려는 머신러닝 엔지니어를 위한 스킬입니다.
사용하는 경우
- ✓고정된 출력 형식, 예를 들어 XML 태그나 JSON을 따르도록 모델을 가르치고 싶을 때.
- ✓객관적인 보상으로 수학, 코딩, 사실 확인 결과를 개선하고 싶을 때.
- ✓형식, 정확성, 문체처럼 여러 목표를 동시에 최적화해야 하는 경우.
스킬 링크
https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/post-training-grpo-rl-training/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“모델이 고정된 형식으로 수학 문제에 답하도록 GRPO 학습을 설정하는 것을 도와주시겠어요?”
매주 새 스킬 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 스타
- 33k
- 순위
- #8603
- 라이선스
- MIT
- 업데이트
- 2026. 11. 2.
댓글
- …
이 저장소의 다른 스킬
owasp-security
33k웹 앱, API, 모바일, 컨테이너, AI 에이전트를 위한 OWASP 보안 지침을 따르도록 해서, 흔한 약점을 찾고 수정안을 제안하게 합니다.
agent-management
33k에이전트가 AI Maestro 명령줄을 사용해 AI 에이전트를 만들고, 나열하고, 일시 정지하고, 깨우고, 이름을 바꾸고, 삭제하도록 돕습니다.
agent-messaging
33k에이전트가 Agent Messaging Protocol로 AI 에이전트 사이에 서명된 메시지를 보내고, 받고, 답하도록 돕습니다. 대부분 내 컴퓨터에서 작동합니다.
docs-search
33k에이전트가 자동 생성된 코드 문서에서 함수 시그니처, 클래스 정의, 주석을 검색하도록 해서, 코드를 바꾸기 전에 실제 API를 확인하게 합니다.