本文へスキップ
Skillpedia
機械学習14k · #11190

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がスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/06-post-training/grpo-rl-training/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

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:

  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

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

repo: Orchestra-Research/AI-Research-SKILLs

人気

GitHubのスター
14k
ランキング
#11190
ライセンス
MIT
更新日
2026/10/10

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル