Chuyển đến nội dung
Skillpedia
Học máy33k · #8603

post-training-grpo-rl-training

Skill này làm gì

Skill này hướng dẫn AI của bạn qua huấn luyện học tăng cường GRPO với thư viện TRL. Dành cho kỹ sư ML muốn huấn luyện mô hình trên các tác vụ có phần thưởng rõ ràng là đúng hoặc sai.

Khi nào nên dùng

  • ✓Khi bạn muốn dạy mô hình tuân theo một định dạng đầu ra cụ thể, như thẻ XML hoặc JSON.
  • ✓Khi bạn muốn cải thiện kết quả toán, lập trình hoặc kiểm tra sự thật bằng phần thưởng khách quan.
  • ✓Khi bạn cần tối ưu nhiều mục tiêu cùng lúc, như định dạng, tính đúng đắn và văn phong.

Liên kết skill

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/post-training-grpo-rl-training/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/post-training-grpo-rl-training/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Bạn có thể giúp tôi thiết lập huấn luyện GRPO để mô hình học trả lời các bài toán bằng một định dạng cố định không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill giải thích cách viết hàm thưởng, sinh nhiều câu trả lời cho mỗi prompt và so sánh chúng trong từng nhóm. Mô hình sau đó được cập nhật theo hướng các câu trả lời có điểm cao hơn.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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
Câu hỏi thường gặp

Khi nào không nên dùng GRPO?

Hướng dẫn nói nên dùng supervised fine-tuning cho tác vụ đơn giản, và DPO hoặc PPO khi bạn đã có các cặp ưu tiên tốt.

Có cần mô hình thưởng riêng không?

Không. Hướng dẫn nói GRPO dùng hàm thưởng và không cần mô hình thưởng riêng.

Mỗi prompt nên có bao nhiêu completion?

Hướng dẫn gợi ý kích thước nhóm từ 4 đến 16 completion cho mỗi prompt.

Chi tiết

Mô tả gốc của tác giả

Expert guidance for GRPO/RL fine-tuning with TRL for reasoning and task-specific model training

repo: davila7/claude-code-templates

Độ phổ biến

Sao GitHub
33k
Vị trí xếp hạng
#8603
Giấy phép
MIT
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự