> 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/grpo-long-context.md).

# 具有 7 倍更长上下文的强化学习 GRPO

了解 Unsloth 如何实现超长上下文 RL 微调。

强化学习（RL）最大的挑战是支持长推理轨迹。我们正在引入新的批处理算法，以实现约**7倍更长的上下文** （可超过12倍） 在不降低准确率或速度的情况下进行RL训练，相比之下，这优于其他使用FA3、kernels和分块损失的优化方案。

* Unsloth 现在使用 **38万上下文** 在单张192GB NVIDIA B200 GPU上训练 gpt-oss QLoRA
* [Qwen3](/docs/zh/mo-xing/tutorials/qwen3-how-to-run-and-fine-tune.md#fine-tuning-qwen3-with-unsloth)-8B GRPO 可达到 **11万上下文** 在80GB显存的H100上通过 [vLLM](#vllm-for-rl) 以及 QLoRA，并且 **6.5万** 用于 [gpt-oss](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/gpt-oss-reinforcement-learning.md) 使用 BF16 LoRA。
* 在24GB显存上，gpt-oss 可达到2万上下文，而 [Qwen3-VL](/docs/zh/mo-xing/tutorials/qwen3-how-to-run-and-fine-tune/qwen3-vl-how-to-run-and-fine-tune.md)-8B QLoRA 可达到3.2万
* Unsloth GRPO RL 可与 Llama、Gemma 及所有模型一起运行，自动支持更长上下文

我们新的数据迁移和批处理内核与算法解锁了更多 上下文 ，方式如下：

* Dynamic [扁平化序列分块](#flattened-sequence-length-chunking) 以避免生成巨大的logit张量，并且
* [卸载 log softmax](#offloading-activations-for-log-softmax) 激活值，从而防止随着时间推移出现静默的内存增长。

{% hint style="info" %}
**你可以在 Unsloth 中把所有特性一起组合使用：**

1. Unsloth 的 [权重共享](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/memory-efficient-rl.md) 功能与 [vLLM](https://github.com/vllm-project/vllm) 以及我们在 [内存高效的 RL](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/memory-efficient-rl.md)
2. Unsloth 的 [Flex Attention](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md) 中的待机特性，可用于长上下文 gpt-oss 以及我们的 [500K Context Training](/docs/zh/bo-ke/500k-context-length-fine-tuning.md)
3. Float8 训练， [FP8 RL](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/fp8-reinforcement-learning.md) 以及 Unsloth 的 [异步梯度检查点](https://unsloth.ai/blog/long-context) 等等
   {% endhint %}

### :tada:开始使用

要开始使用，你可以使用任何现有的 [GRPO 笔记本](/docs/zh/kuai-su-kai-shi/unsloth-notebooks.md#grpo-reasoning-rl-notebooks) （如果本地使用，则更新 Unsloth）：

{% columns %}
{% column width="33.33333333333333%" %}
[**gpt-oss-20b**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-GRPO.ipynb) GSPO

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-(20B)-GRPO.ipynb>" %}
{% endcolumn %}

{% column width="33.33333333333333%" %}
[**Qwen3-VL-8B**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_\(8B\)-Vision-GRPO.ipynb) 视觉 RL

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_(8B)-Vision-GRPO.ipynb>" %}
{% endcolumn %}

{% column width="33.33333333333333%" %}
[Qwen3-8B - **FP8**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_8B_FP8_GRPO.ipynb) L4 GPU

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_8B_FP8_GRPO.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

将 Unsloth 应用于你的 RL 任务，可为高效管理大规模模型提供一个稳健的框架。为了有效利用 Unsloth 的增强功能：

* **硬件建议**：为获得最佳显存利用率，建议使用 NVIDIA H100 或同等配置。
* **配置提示**：请确保 `batch_size` 和 `gradient_accumulation_steps` 设置与您的计算资源相匹配，以获得最佳性能。

{% hint style="success" %}
将 Unsloth 更新到最新的 Pypi 版本以获取最新更新：

```
pip install --upgrade --no-cache-dir unsloth unsloth_zoo
```

{% endhint %}

我们的基准测试强调了与早期版本相比，GPT OSS 和 Qwen3-8B 所实现的显存节省。下面两个图（不含 [待机](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/memory-efficient-rl.md)）是在以下设置下运行的 `batch_size = 4` 和 `gradient_accumulation_steps=2` ，因为待机模式按设计会使用全部显存。

在我们的基准测试中，我们将 BF16 GRPO 与启用所有优化的 Hugging Face 进行比较（kernels 库中的所有内核、Flash Attention 3、分块损失内核等）：

### :1234:扁平化序列长度分块

此前，Unsloth 通过在批维度上进行分块，避免完整物化 logits 张量，从而降低了 RL 的内存使用。公式（1）展示了在前向传播期间物化 logits 所需显存的粗略估计。

$$
\text{Equation 1: } \text{Logit Memory (GB)} = \frac{\text{batch size} \times\text{context length} \times \text{vocab dim}}{1024^3}
$$

使用该公式，对于以下配置 `batch_size = 4`, `context_length = 8192`，以及 `vocab_dim = 128,000` ，大约需要 **3.3 GB 显存** 来存储 logits 张量。

通过 [Long Context gpt-oss](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md) 在去年，我们随后为 GRPO 引入了一种融合损失方法。该方法确保一次只处理一个批样本，从而显著降低峰值内存使用。在相同配置下，显存占用降至约 **0.83 GB**，如公式（2）所示。

$$
\text{Equation 2: }\text{Logit Memory (GB)} = \frac{\text{context length} \times \text{vocab dim}}{1024^3}
$$

<div><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fy1TkzxySrNAeeSWJSVLU%2Funsloth_vs_trl_gpt_oss.png?alt=media&amp;token=0303423d-1454-4410-8be8-7d6110ac1df0" alt="" width="375"><figcaption><p>图1：gpt-oss BF16 GRPO LoRA（Unsloth vs. 启用所有优化的 HF）</p></figcaption></figure> <figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FmfKhenN0TGRDlMcuxob6%2Fqwen38b%20long%20context%20grpo.png?alt=media&amp;token=22883f90-5bf0-4478-91a9-6a191c920f12" alt="" width="375"><figcaption><p>图2：Qwen3-8B QLoRA GRPO LoRA（Unsloth vs. 启用所有优化的 HF）</p></figcaption></figure></div>

在此次更新中，我们进一步扩展了同样的思路，引入了对 **序列维度** 的分块。我们不再一次性物化整个 `（batch_size × context_length）` 空间中的 logits，而是将这些维度展平，并使用可配置的乘数以更小的块进行处理。这使 Unsloth 能够在不增加峰值显存的情况下支持更长的上下文。

在下图5中，我们使用的乘数为 `max(4, context_length // 4096)`，不过可根据所需的显存—性能权衡指定任意乘数。在此设置下，相同的示例配置（`batch_size = 4`, `context_length = 8192`, `vocab_dim = 128,000`）现在只需要 **0.207 GB 显存** 来物化 logits。

$$
\text{Equation 3: }\text{Logit Memory (GB)} = \frac{\frac{\text{context length}}{\text{multiplier}} \times \text{vocab dim}}{1024^3}
$$

<div><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FWFTbejdIn3T6E6yHgF1Z%2FCode_Generated_Image%20(2).png?alt=media&amp;token=790a1ee4-2814-4b29-afcb-bb9ffd1eb729" alt="" width="375"><figcaption><p>图3：gpt-oss-20b（H100）Unsloth 新版 vs. 旧版</p></figcaption></figure> <figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fi4QipufoavtPKyeRU0Vv%2FCode_Generated_Image%20(3).png?alt=media&amp;token=226c5a3c-a0a4-458d-a0df-8c84523b04b5" alt="" width="375"><figcaption><p>图4：Qwen3-8B（H100）Unsloth 新版 vs. 旧版</p></figcaption></figure> <figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FkSIh5DIWvKGemnNHowPs%2FCode_Generated_Image_4.png?alt=media&amp;token=0a3dfe85-ae8c-4280-bc0a-6c1f1523c90e" alt="" width="375"><figcaption><p>图5：gpt-oss-20b（H100）</p></figcaption></figure> <figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FRP1RPiOeIYOt82L1Ifkc%2FCode_Generated_Image_5.png?alt=media&amp;token=4ce06b0f-2464-41fd-8795-e5bf0dbf4327" alt="" width="375"><figcaption><p>图6：Qwen3-8B（B200）</p></figcaption></figure></div>

这一更新体现在编译后的 `chunked_hidden_states_selective_log_softmax` 中，该实现现在支持同时对批维度和序列维度进行分块。为了保留 logits 张量（`[batch_size, context_length, vocab_dim]`），它始终会先在批维度上分块。额外的序列分块通过 `unsloth_logit_chunk_multiplier` 在 GRPO 配置中控制；如果未设置，则默认为 `max(4, context_length // 4096)`。在下面的示例中， `input_ids_chunk[0]` 对应于优化2中的 hidden states 小批量大小。

```python
logprobs_chunk = chunked_hidden_states_selective_log_softmax(
    new_hidden_states_chunk, 
    lm_head, 
    completion_ids, 
    chunks=input_ids_chunk.shape[0]*multiplier, 
    logit_scale_multiply=logit_scale_multiply,
    logit_scale_divide=logit_scale_divide,
    logit_softcapping=logit_softcapping,
    temperature=temperature,                
)
```

1. 我们使用带有自定义编译选项的 torch.compile 来减少显存并提升速度。
2. 所有分块的 logits 都会提升为 float32 以保持准确性。
3. 我们支持 logit softcapping、temperature scaling 以及所有其他功能。

### :ghost:Hidden States 分块

我们还观察到，在更长的上下文长度下，hidden states 也会成为显存使用的重要组成部分。为了演示，我们假设 `hidden_states_dim=4096`。相应的显存使用与 logits 情况类似，其公式如下。&#x20;

$$
\text{Hidden States Memory (GB)} = \frac{\text{batch size} \times\text{context length} \times \text{hidden states dim}}{1024^3}
$$

使用 `batch_size = 8` 和 `context_length = 64000`，这将导致大约 **2 GB**的显存占用。在此版本中，我们在计算 log-probability 时，为 hidden states 张量引入了可选的批维度分块。这会使显存占用按 batch size 平均分摊，或在此情况下为 **0.244 GB**。这减少了物化 hidden states 所需的峰值显存，如下方更新后的公式所示：

$$
\text{Hidden States Memory (GB)} = \frac{\text{context length} \times \text{hidden states dim}}{1024^3}
$$

类似于我们在 [500K Context Training](/docs/zh/bo-ke/500k-context-length-fine-tuning.md) 版本中的交叉熵损失实现，新的实现 **会自动调节 hidden state 的批处理**。用户也可以通过 `unsloth_grpo_mini_batch`来控制这一行为。不过，将 `unsloth_grpo_mini_batch` 提升到最优值以上，可能会相比之前的损失函数带来轻微的性能提升或下降（通常更快）。

不过，在一次 GPT-OSS 运行中（`context_length = 8192, batch_size = 4, gradient_accumulation_steps = 2`），设置 `unsloth_grpo_mini_batch = 1` 和 `unsloth_logit_chunk_multiplier = 4` 会带来 **几乎没有速度下降，同时将显存占用降低约 5 GB** ，相比旧版 Unsloth。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FYZsgoKpZKyJKrNmbvehR%2FCode_Generated_Image%20(4).png?alt=media&amp;token=5d3c0605-9ed8-4d4a-a722-a85132510222" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="success" %}
**注意：** 在图3和图4中，我们使用的是最大有效批大小，在此设置中为8。有效批大小的计算方式为 `batch_size × gradient_accumulation_steps`，即 `4 × 2 = 8`。关于 RL 中有效批大小如何工作的更深入说明，请参阅我们的 [高级 RL 文档](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/advanced-rl-documentation.md).&#x20;
{% endhint %}

### :cactus:用于 log softmax 的激活卸载

在此版本开发过程中，我们发现当在 hidden states 上沿批维度切块时，融合后的 logits 和 logprobs 计算完成后，激活值并未被卸载。由于 logits 是通过以下方式一次处理一个批次计算的 `hidden_states[i] @ lm_head`，原本设计用于模型前向传播内部运行的现有激活卸载和梯度检查点逻辑在这种情况下并不适用。

为解决这一问题，我们在模型前向传播之外添加了显式逻辑来卸载这些激活，如下方 Python 伪代码所示：

```python
class Unsloth_Offloaded_Log_Softmax(torch.autograd.Function):
    def forward(...):
        with torch.no_grad():
            output = chunked_hidden_states_selective_log_softmax(hidden_states, lm_head, ...)
        return output
    def backward(ctx, grad_output):
        hidden_states = ctx.saved_hidden_states
        hidden_states.requires_grad_(True)
        with torch.enable_grad():
            output = chunked_hidden_states_selective_log_softmax(hidden_states, lm_head, ...)
        torch.autograd.backward(output, grad_output)
        return ...
```

{% hint style="success" %}
**注意：** 此功能仅在按批维度分块时，或当 `unsloth_grpo_mini_batch > 1`时才有效。如果在前向传播过程中一次性物化所有 hidden states（即， `unsloth_grpo_mini_batch = 1`），那么无论是否卸载激活值，反向传播都需要在 GPU 中占用相同数量的内存。由于在这种情况下激活卸载会带来轻微的性能下降却无法减少内存占用，因此没有收益。
{% endhint %}

### :sparkles:配置参数：

如果你不配置 `unsloth_grpo_mini_batch` 和 `unsloth_logit_chunk_multiplier`中，我们将 **会自动调优这两个参数** ，使其基于你可用的显存并根据上下文长度大小为你设置。下面则是你在 GRPO 运行中如何修改这些变量：

```python
training_args = GRPOConfig(
    ...
    unsloth_grpo_mini_batch = 3
    unsloth_logit_chunk_multiplier = 2
    ...
)
```

这些优化的可视化以及 `unsloth_grpo_mini_batch` 和 `unsloth_logit_chunk_multiplier` 可在下图中看到。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F2OmZA297HzG3CdRzi3X5%2FLogit%20Chunking%20(1).png?alt=media&amp;token=b953a62b-fefa-43f2-a9ce-108675b8735f" alt="" width="375"><figcaption></figcaption></figure>

这3个矩阵代表更大的整体批次或 `unsloth_grpo_mini_batch` （由黑色括号的数量表示），而每个矩阵的行表示该 `unsloth_logit_chunk_multiplier`  将序列长度按块划分（由红色括号的数量表示）。&#x20;

### :vhs:RL 中的 vLLM

**对于 RL 工作流，推理/生成阶段是主要瓶颈**。为了解决这一问题，我们采用 [vLLM](https://github.com/vllm-project/vllm)，与普通生成相比，其生成速度最高可提升11倍。自从 GRPO 在去年流行以来，vLLM 一直是包括 Unsloth 在内的大多数 RL 框架的核心组件。我们要感谢 vLLM 团队及其所有贡献者的工作，因为他们在让 Unsloth 的 RL 更出色方面发挥了关键作用！

要尝试更长上下文的 RL，你可以使用任何现有的 [GRPO 笔记本](/docs/zh/kuai-su-kai-shi/unsloth-notebooks.md#grpo-reasoning-rl-notebooks) （如果本地使用，则更新 Unsloth）：

{% columns %}
{% column width="33.33333333333333%" %}
[**gpt-oss-20b**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-GRPO.ipynb) - GSPO

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-(20B)-GRPO.ipynb>" %}
{% endcolumn %}

{% column width="33.33333333333333%" %}
[**Qwen3-VL-8B**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_\(8B\)-Vision-GRPO.ipynb) 视觉 RL

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_(8B)-Vision-GRPO.ipynb>" %}
{% endcolumn %}

{% column width="33.33333333333333%" %}
[Qwen3-8B - **FP8**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_8B_FP8_GRPO.ipynb) L4 GPU

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_8B_FP8_GRPO.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

致谢：衷心感谢 Hugging Face 团队及其库为 Unsloth 提供支持并使这一切成为可能。


---

# 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/grpo-long-context.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.
