# 教程：使用 GRPO 训练你自己的推理模型

DeepSeek 开发了 [GRPO](https://unsloth.ai/blog/grpo) （组相对策略优化）来训练他们的 R1 推理模型。

### 快速开始

这些说明适用于我们预先制作好的 Google Colab [笔记本](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md)。如果你在本地安装 Unsloth，也可以把我们的笔记本复制到你喜欢的代码编辑器中。我们将使用以下任意笔记本：

| [**Qwen3.5（4B）**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_5_\(4B\)_Vision_GRPO.ipynb) **- 视觉 - 新** | [**gpt-oss-20b**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-GRPO.ipynb) **-** GSPO   | [Gemma 3（4B）](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision-GRPO.ipynb) - 视觉 GSPO       |
| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| [**Qwen3（4B）**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(4B\)-GRPO.ipynb) - 高级                    | [Qwen3-VL-8B](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_\(8B\)-Vision-GRPO.ipynb) - 视觉 GSPO | [Llama 3.2（3B）](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Advanced_Llama3_2_\(3B\)_GRPO_LoRA.ipynb) - 高级 |

{% stepper %}
{% step %}

#### 安装 Unsloth

如果你使用我们的 Colab 笔记本，请点击 **运行时 > 全部运行**。我们非常建议你先查看我们的 [微调指南](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide.md) 再开始。

如果在本地安装，请确保你拥有正确的 [依赖项](/docs/zh/kai-shi-shi-yong/fine-tuning-for-beginners/unsloth-requirements.md) 并在 Linux 上使用 `pip install unsloth` ，或按照我们的 [Windows 安装 ](/docs/zh/kai-shi-shi-yong/install/windows-installation.md)说明。

<figure><img src="/files/5ee90c3fd3de40376e0047a1cfae1b91ef648b0c" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 了解 GRPO 和奖励函数

在开始之前，建议先进一步了解 GRPO、奖励函数以及它们的工作方式。阅读更多内容，包括 [技巧与窍门](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md#basics-tips)[ 这里](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md#basics-tips).

你还需要足够的 VRAM。一般来说，模型参数量 = 你需要的 VRAM 量。在 Colab 中，我们使用他们免费的 16GB VRAM GPU，可训练参数量最高达 16B 的任何模型。
{% endstep %}

{% step %}

#### 配置所需设置

我们已经为你预先选择了最优设置以获得最佳效果，你也可以把模型改成我们 [支持的模型](/docs/zh/kai-shi-shi-yong/unsloth-model-catalog.md)中列出的任意一个。不建议初学者修改其他设置。

{% hint style="success" %}
关于 **高级 GRPO** 在批处理、生成和训练参数方面的文档， [请阅读我们的指南！](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide/advanced-rl-documentation.md)
{% endhint %}

<figure><img src="/files/d11c0691f955fda64c8a376eb80ff8b906263905" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 数据准备

我们已预先选择 OpenAI 的 [GSM8K](https://huggingface.co/datasets/openai/gsm8k) 数据集，其中包含小学数学题，但你也可以把它改成自己的数据集，或 Hugging Face 上任何公开数据集。你可以在此阅读更多关于 [数据集的内容](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide.md).

。你的数据集仍应至少包含 2 列，用于问题和答案对。不过，答案不能透露它是如何根据问题推导出来的。示例如下：

<figure><img src="/files/4a1b16b990838ef06d0b541ce336364df4792cf6" alt=""><figcaption></figcaption></figure>

我们将把数据结构化，让模型在给出答案之前先阐述其推理过程。首先，我们将为提示和回复都建立清晰的格式。

```
# 定义系统提示，指示模型使用特定格式
SYSTEM_PROMPT = """
请按以下格式回复：
<reasoning>
...
</reasoning>
<answer>
...
</answer>
"""

XML_COT_FORMAT = """\
<reasoning>
{reasoning}
</reasoning>
<answer>
{answer}
</answer>
"""
```

现在，准备数据集：

```
import re
from datasets import load_dataset, Dataset


# 用于从不同格式中提取答案的辅助函数
def extract_xml_answer(text: str) -> str:
    answer = text.split("<answer>")[-1]
    answer = answer.split("</answer>")[0]
    return answer.strip()


def extract_hash_answer(text: str) -> str | None:
    if "####" not in text:
        return None
    return text.split("####")[1].strip()


# 准备 GSM8K 数据集的函数
def get_gsm8k_questions(split="train") -> Dataset:
    data = load_dataset("openai/gsm8k", "main")[split]
    data = data.map(
        lambda x: {
            "prompt": [
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": x["question"]},
            ],
            "answer": extract_hash_answer(x["answer"]),
        }
    )
    return data


dataset = get_gsm8k_questions()
```

数据集通过提取答案并将其格式化为结构化字符串来完成准备。
{% endstep %}

{% step %}

#### 奖励函数/验证器

[奖励函数/验证器](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md#reward-functions-verifier) 让我们根据你提供的数据集知道模型表现得好不好。每次生成都会根据其得分与其他生成结果的平均值进行评估。你可以创建自己的奖励函数，不过我们已经为你预先选择了 [Will 的 GSM8K](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md#gsm8k-reward-functions) 奖励函数。借此，我们有 5 种不同方式来奖励每次生成。

你可以将生成结果输入到像 ChatGPT 4o 或 Llama 3.1（8B）这样的 LLM 中，并设计一个奖励函数和验证器来评估它。例如，把生成结果喂给你选择的 LLM，并设定一条规则："如果答案听起来太机械，就扣 3 分。" 这有助于根据质量标准优化输出。 **查看示例** 看看它们可能是什么样子 [这里](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md#reward-function-examples).

**电子邮件自动化任务的奖励函数示例：**

* **问题：** 传入邮件
* **答案：** 发出邮件
* **奖励函数：**
  * 如果答案包含必需的关键词 → **+1**
  * 如果答案与理想回复完全匹配 → **+1**
  * 如果回复太长 → **-1**
  * 如果包含收件人姓名 → **+1**
  * 如果存在签名块（电话、邮箱、地址）→ **+1**

<figure><img src="/files/e7edc2c193a54bc0f54047726a93492b835fbee0" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 训练你的模型

我们已预先选择了超参数以获得最优结果，不过你也可以修改它们。阅读关于 [此处参数](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide.md)的全部内容。关于 **高级 GRPO** 在批处理、生成和训练参数方面的文档， [请阅读我们的指南！](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide/advanced-rl-documentation.md)

<figure><img src="/files/f0b7d59548a67ca53bb41d4cc77167241333569a" alt="" width="563"><figcaption></figcaption></figure>

这个 **GRPOConfig** 定义了训练的关键超参数：

* `use_vllm`：启用 vLLM 的快速推理。
* `learning_rate`：决定模型的学习速度。
* `num_generations`：指定每个提示生成的完成数量。
* `max_steps`：设置训练总步数。

{% hint style="success" %}
**新！** 我们现在支持 DAPO、Dr. GRPO 以及大多数其他新的 GRPO 技术。你可以在 GRPOConfig 中尝试以下参数来启用：

```python
epsilon=0.2,
epsilon_high=0.28, # 单边
delta=1.5 # 双边

loss_type='bnpo',
# 或：
loss_type='grpo',
# 或：
loss_type='dr_grpo',
# 或：
loss_type='dapo',

mask_truncated_completions=True,
```

{% endhint %}

你应该会看到奖励值随着时间上升。我们建议至少训练 300 步，这可能需要 30 分钟；不过为了获得最佳效果，你应该训练更久。

{% hint style="warning" %}
如果你遇到 GRPO 模型不学习的问题，我们强烈建议使用我们的 [高级 GRPO 笔记本](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md#grpo-reasoning-notebooks) ，因为它的奖励函数好得多，你应该会更快、更频繁地看到结果。
{% endhint %}

你还会看到示例答案，这能让你了解模型是如何学习的。有些可能带有步骤、XML 标签、尝试等；其思路是，随着训练进行，它会越来越好，因为它获得的分数会越来越高，直到我们得到想要的带有长推理链的输出。

<figure><img src="/files/ebdb8c218a5707a90f156d717df12fed3799e6f9" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 运行并评估你的模型

点击播放按钮来运行你的模型。在第一个示例中，答案里通常没有推理；为了看到推理，我们需要先保存刚用 GRPO 训练好的 LoRA 权重，方法如下：

<pre><code><strong>model.save_lora("grpo_saved_lora")
</strong></code></pre>

<figure><img src="/files/026e17fd5135419fee004f7645e033f57a8e25a1" alt=""><figcaption><p>第一次推理示例运行没有推理内容。你必须加载 LoRA 并测试它才能揭示推理过程。</p></figcaption></figure>

然后我们加载 LoRA 并测试它。我们的推理模型要好得多——不过并不总是正确，因为我们只训练了大约一小时；如果延长序列长度并训练更久，它会更好！

然后你可以按照我们的 [这里的指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide/pages/e722e86e330786e5915445b91f900d9f9e0ba067#id-7.-running--saving-the-model).

<figure><img src="/files/6a3c256916641f996612ac0155a1914ee0f4fec6" alt=""><figcaption></figcaption></figure>

将模型保存为 GGUF、Ollama 等格式。如果你仍然没有得到任何推理结果，可能是训练步数太少，或者你的奖励函数/验证器并不理想。
{% endstep %}

{% step %}

#### 保存你的模型

我们提供多种保存微调后模型的选项，但我们将重点介绍最简单、最受欢迎的方法，你可以在 [这里](/docs/zh/ji-chu/inference-and-deployment.md)

**16 位精度保存**

你可以使用以下命令以 16 位精度保存模型：

```python
# 保存为 16 位精度
model.save_pretrained_merged("model", tokenizer, save_method="merged_16bit")
```

**推送到 Hugging Face Hub**

为了分享你的模型，我们将使用 `push_to_hub_merged` 方法把它推送到 Hugging Face Hub。这允许以多种量化格式保存模型。

```python
# 推送到 Hugging Face Hub（需要令牌）
model.push_to_hub_merged(
    "your-username/model-name", tokenizer, save_method="merged_16bit", token="your-token"
)
```

**以 GGUF 格式为 llama.cpp 保存**

Unsloth 也支持保存为 **GGUF 格式**，使其兼容 **llama.cpp** 以及 **Ollama**.

```python
model.push_to_hub_gguf(
    "your-username/model-name",
    tokenizer,
    quantization_method=["q4_k_m", "q8_0", "q5_k_m"],
    token="your-token",
)
```

一旦保存为 GGUF 格式，就可以使用 **llama.cpp** 在轻量级环境中轻松部署，或者用于其他推理引擎。
{% endstep %}
{% endstepper %}

## 视频教程

这里有一些由出色的 YouTuber 制作的视频教程，我们认为它们非常棒！

{% embed url="<https://www.youtube.com/watch?v=9t-BAjzBWj8>" %}

{% columns %}
{% column width="50%" %}
{% embed url="<https://www.youtube.com/watch?t=3289s&v=bbFEYPx9Hpo>" %}
非常适合了解如何准备数据集，以及强化学习 + GRPO 基础知识背后的解释
{% endembed %}

{% embed url="<https://www.youtube.com/watch?v=oF0_eMhzRaQ>" %}
{% endcolumn %}

{% column width="50%" %}
{% embed url="<https://www.youtube.com/watch?v=juOh1afy-IE>" %}

{% embed url="<https://www.youtube.com/watch?v=SoPE1cUz3Hs>" %}
在你自己的设备上本地运行 GRPO
{% endembed %}
{% endcolumn %}
{% endcolumns %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://unsloth.ai/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide/tutorial-train-your-own-reasoning-model-with-grpo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
