> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/advanced-rl-documentation.md).

# 高级强化学习文档

在使用 Unsloth 和 GRPO 时的高级文档设置。

使用 Unsloth 进行 GRPO 的批处理、生成和训练参数详细指南：

## 训练参数

* **`beta`** *(浮点数，默认 0.0)*：KL 系数。
  * `0.0` ⇒ 未加载参考模型（内存占用更低，速度更快）。
  * 更高的 `beta` 会约束策略更接近参考策略。
* **`num_iterations`** *(整数，默认 1)*：每个批次的 PPO 轮数（算法中的 μ）。\
  在每个梯度累积步骤内重复使用数据；例如， `2` = 每个累积步骤进行两次前向传播。
* **`epsilon`** *(浮点数，默认 0.2)*：用于 token 级 log-prob 比率的裁剪值（默认 ε 下典型比率范围约为 \[-1.2, 1.2]）。
* **`delta`** *(浮点数，可选)*：启用 **上限** 裁剪边界，用于 **双边 GRPO** 时生效。如果 `无`，则使用标准 GRPO 裁剪。推荐 `> 1 + ε` 启用时使用（根据 INTELLECT-2 报告）。
* **`epsilon_high`** *(浮点数，可选)*：上界 epsilon；默认为 `epsilon` ，如果未设置。DAPO 建议 **0.28**.
* **`importance_sampling_level`** *（“token” | “sequence”，默认“token”）*:
  * `“token”`：原始的按 token 比率（每个 token 一个权重）。
  * `“sequence”`：将每个 token 的比率平均为单个序列级比率。\
    GSPO 表明，序列级采样通常能为序列级奖励带来更稳定的训练。
* **`reward_weights`** *(浮点数列表，可选)*：每个奖励对应一个权重。如果 `无`，所有权重都为 1.0。
* **`scale_rewards`** *(字符串|布尔值，默认“group”)*:
  * `真` 或 `“group”`：按 **每个组内的标准差** （组内单位方差）。
  * `“batch”`：按 **整个批次的标准差** （依据 PPO-Lite）。
  * `假` 或 `“none”`: **不缩放**。Dr. GRPO 建议不要缩放，以避免标准差缩放带来的难度偏差。
* **`loss_type`** *(字符串，默认“dapo”)*:
  * `“grpo”`：按序列长度归一化（存在长度偏差；不推荐）。
  * `“dr_grpo”`：按一个 **全局常量** （在 Dr. GRPO 中引入；消除长度偏差）。常量约为 `max_completion_length`.
  * `“dapo”` **（默认）**：按 **全局累积批次中的有效 token** （在 DAPO 中引入；消除长度偏差）。
  * `“bnpo”`：按 **本地批次中的有效 token** 仅（结果可能随本地批次大小变化；当 `per_device_train_batch_size == 1`).
* **`mask_truncated_completions`** *(布尔值，默认 False)*：\
  当 `真`，截断的完成会被排除在损失之外（DAPO 为稳定性推荐）。\
  **注意**：此标志会带来一些 KL 问题，因此建议禁用。

  ```python
  # 如果启用了 mask_truncated_completions，则将 completion_mask 中的截断完成置零
  if self.mask_truncated_completions:
      truncated_completions = ~is_eos.any(dim=1)
      completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
  ```

  这可能会将所有 `completion_mask` 条目置零，当很多完成被截断时，会导致 `n_mask_per_reward = 0` 并导致 KL 变为 NaN。 [请看](https://github.com/unslothai/unsloth-zoo/blob/e705f7cb50aa3470a0b6e36052c61b7486a39133/unsloth_zoo/rl_replacements.py#L184)
* **`vllm_importance_sampling_correction`** *(布尔值，默认 True)*：\
  应用 **截断重要性采样（TIS）** 用于在生成（例如 vLLM / fast\_inference）与训练后端不同时修正离策略效应。\
  在 Unsloth 中，这会 **自动设为 True** 如果你使用的是 vLLM/fast\_inference；否则 **假**.
* **`vllm_importance_sampling_cap`** *(浮点数，默认 2.0)*：\
  截断参数 **C** 用于 TIS；设置重要性采样比率的上界以提升稳定性。
* **`dtype`** 在选择 float16 或 bfloat16 时，请参阅 [RL 中的 FP16 与 BF16](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/advanced-rl-documentation/fp16-vs-bf16-for-rl.md)

### 在不受支持的模型上进行 RL：

你也可以在 vLLM 不支持的模型上使用 Unsloth 运行 RL，例如 [Qwen3.5](/docs/zh/mo-xing/qwen3.5/fine-tune.md)。只需设置 `fast_inference=False` 在加载模型时。

```python
from unsloth import FastLanguageModel

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Qwen3.5-4B",
    fast_inference=False,
)
```

## 生成参数

* `temperature (float, defaults to 1.0):`\
  用于采样的温度。温度越高，生成结果越随机。请确保使用相对较高的（1.0）温度，以获得更多样的生成结果，这有助于学习。
* `top_p (float, optional, defaults to 1.0):`\
  控制要考虑的 top token 累积概率的浮点数。必须位于 (0, 1]。设为 1.0 可考虑所有 token。
* `top_k (int, optional):`\
  用于 top-k 过滤保留的最高概率词表 token 数量。如果为 None，则禁用 top-k 过滤，并考虑所有 token。
* `min_p (float, optional):`\
  最小 token 概率，会按最可能 token 的概率进行缩放。其值必须介于 0.0 和 1.0 之间。典型值在 0.01-0.2 范围内。
* `repetition_penalty (float, optional, defaults to 1.0):`\
  根据 token 是否出现在提示和已生成文本中，对新 token 施加惩罚的浮点数。值 > 1.0 会鼓励模型使用新 token，而值 < 1.0 会鼓励模型重复 token。
* `steps_per_generation: (int, optional):`\
  每次生成的步骤数。如果为 None，则默认为 `gradient_accumulation_steps`。与 `generation_batch_size`.

{% hint style="info" %}
调整此参数有点令人困惑，建议修改 `per_device_train_batch_size` 以及梯度累积来控制批次大小
{% endhint %}

## 批次与吞吐量参数

### 控制批次的参数

* **`train_batch_size`**：样本数量 **每个进程** 每步。\
  如果这个整数 **小于 `num_generations`**，则默认为 `num_generations`.
* **`steps_per_generation`**： **微批次** 它们共同参与 **一次生成的** 损失计算（仅前向传播）。\
  每隔 `steps_per_generation` 步会生成一个新数据批次；反向传播时机取决于 `gradient_accumulation_steps`.
* **`num_processes`**：分布式训练进程数量（例如 GPU / worker）。
* **`gradient_accumulation_steps`** （也称 `gradient_accumulation`）：要累积的微批次数量 **之前** ，然后再进行反向传播和优化器更新。
* **有效批次大小**:

  ```
  effective_batch_size = steps_per_generation * num_processes * train_batch_size
  ```

  在一次更新前参与梯度计算的样本总数（跨所有进程和步骤）。
* **每次生成的优化器步数**:

  ```
  optimizer_steps_per_generation = steps_per_generation / gradient_accumulation_steps
  ```

  示例： `4 / 2 = 2`.
* **`num_generations`**：生成的样本数 **每个提示** （在 **在** 计算 `effective_batch_size`时应用）。\
  一个生成周期中的 **唯一提示词** 数量为：

  ```
  unique_prompts = effective_batch_size / num_generations
  ```

  **必须 > 2** GRPO 才能正常工作。

### GRPO 批次示例

下表展示了批次如何在各步骤中流动、何时进行优化器更新，以及新批次如何生成。

#### 示例 1

```
num_gpus = 1
per_device_train_batch_size = 3
gradient_accumulation_steps = 2
steps_per_generation = 4

effective_batch_size = 4 * 3 * 1 = 12
num_generations = 3
```

**生成周期 A**

| 步骤 | 批次       | 说明                     |
| -: | -------- | ---------------------- |
|  0 | \[0,0,0] |                        |
|  1 | \[1,1,1] | → 优化器更新（已达到 accum = 2） |
|  2 | \[2,2,2] |                        |
|  3 | \[3,3,3] | 优化器更新                  |

**生成周期 B**

| 步骤 | 批次       | 说明                     |
| -: | -------- | ---------------------- |
|  0 | \[4,4,4] |                        |
|  1 | \[5,5,5] | → 优化器更新（已达到 accum = 2） |
|  2 | \[6,6,6] |                        |
|  3 | \[7,7,7] | 优化器更新                  |

#### 示例 2

```
num_gpus = 1
per_device_train_batch_size = 3
steps_per_generation = gradient_accumulation_steps = 4

effective_batch_size = 4 * 3 * 1 = 12
num_generations = 3
```

**生成周期 A**

| 步骤 | 批次       | 说明                   |
| -: | -------- | -------------------- |
|  0 | \[0,0,0] |                      |
|  1 | \[1,1,1] |                      |
|  2 | \[2,2,2] |                      |
|  3 | \[3,3,3] | 优化器更新（已达到 accum = 4） |

**生成周期 B**

| 步骤 | 批次       | 说明                   |
| -: | -------- | -------------------- |
|  0 | \[4,4,4] |                      |
|  1 | \[5,5,5] |                      |
|  2 | \[6,6,6] |                      |
|  3 | \[7,7,7] | 优化器更新（已达到 accum = 4） |

#### 示例 3

```
num_gpus = 1
per_device_train_batch_size = 3
steps_per_generation = gradient_accumulation_steps = 4

effective_batch_size = 4 * 3 * 1 = 12
num_generations = 4
unique_prompts = effective_batch_size / num_generations = 3
```

**生成周期 A**

| 步骤 | 批次       | 说明                   |
| -: | -------- | -------------------- |
|  0 | \[0,0,0] |                      |
|  1 | \[0,1,1] |                      |
|  2 | \[1,1,3] |                      |
|  3 | \[3,3,3] | 优化器更新（已达到 accum = 4） |

**生成周期 B**

| 步骤 | 批次       | 说明                   |
| -: | -------- | -------------------- |
|  0 | \[4,4,4] |                      |
|  1 | \[4,5,5] |                      |
|  2 | \[5,5,6] |                      |
|  3 | \[6,6,6] | 优化器更新（已达到 accum = 4） |

#### 示例 4

```
num_gpus = 1
per_device_train_batch_size = 6
steps_per_generation = gradient_accumulation_steps = 2

effective_batch_size = 2 * 6 * 1 = 12
num_generations = 3
unique_prompts = 4
```

**生成周期 A**

| 步骤 | 批次              | 说明                   |
| -: | --------------- | -------------------- |
|  0 | \[0,0,0, 1,1,1] |                      |
|  1 | \[2,2,2, 3,3,3] | 优化器更新（已达到 accum = 2） |

**生成周期 B**

| 步骤 | 批次              | 说明                   |
| -: | --------------- | -------------------- |
|  0 | \[4,4,4, 5,5,5] |                      |
|  1 | \[6,6,6, 7,7,7] | 优化器更新（已达到 accum = 2） |

### 快速公式参考

```
effective_batch_size = steps_per_generation * num_processes * train_batch_size
optimizer_steps_per_generation = steps_per_generation / gradient_accumulation_steps
unique_prompts = effective_batch_size / num_generations   # 必须 > 2
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/advanced-rl-documentation.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
