> 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/jp/meru/reinforcement-learning-rl-guide/grpo-long-context.md).

# 7倍長いコンテキストでの強化学習GRPO

Unslothが超長文コンテキストのRLファインチューニングをどのように実現するかを学びましょう。

強化学習（RL）の最大の課題は、長い推論トレースをサポートすることです。私たちは、〜を実現するための新しいバッチングアルゴリズムを導入します**7倍長いコンテキスト** （12倍以上になることもあります） FA3、カーネル、およびチャンク化ロスを使用する他の最適化済み構成と比べて、精度や速度を低下させることなくRLトレーニングを実現します。

* Unslothは現在、gpt-oss QLoRAを **38万コンテキスト** 単一の192GB NVIDIA B200 GPU上で学習できます
* [Qwen3](/docs/jp/moderu/tutorials/qwen3-how-to-run-and-fine-tune.md#fine-tuning-qwen3-with-unsloth)-8B GRPOは **11万コンテキスト** を達成します（80GB VRAMのH100上で、 [vLLM](#vllm-for-rl) とQLoRA、さらに **65K** を [gpt-oss](/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune/gpt-oss-reinforcement-learning.md) BF16 LoRAでも可能です。
* 24GB VRAMでは、gpt-ossは2万コンテキストに到達し、 [Qwen3-VL](/docs/jp/moderu/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/jp/meru/reinforcement-learning-rl-guide/memory-efficient-rl.md) 機能を [vLLM](https://github.com/vllm-project/vllm) と、そして当社のスタンバイ機能を [メモリ効率の高いRL](/docs/jp/meru/reinforcement-learning-rl-guide/memory-efficient-rl.md)
2. Unslothの [Flex Attention](/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md) で、長いコンテキストのgpt-ossと [500K Context Training](/docs/jp/burogu/500k-context-length-fine-tuning.md)
3. Float8トレーニングを [FP8 RL](/docs/jp/meru/reinforcement-learning-rl-guide/fp8-reinforcement-learning.md) で、さらにUnslothの [非同期勾配チェックポイント化](https://unsloth.ai/blog/long-context) など、その他多数
   {% endhint %}

### :tada:始め方

始めるには、既存の [GRPOノートブック](/docs/jp/meru/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) Vision 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 %}

RLタスクにUnslothを採用すると、大規模モデルを効率よく管理するための堅牢なフレームワークが得られます。Unslothの強化を効果的に活用するには：

* **ハードウェア推奨**：最適なVRAM活用のために、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/jp/meru/reinforcement-learning-rl-guide/memory-efficient-rl.md)なし）は、 `batch_size = 4` そして `gradient_accumulation_steps=2` で実行されました。これは、スタンバイが設計上すべてのVRAMを使うためです。

ベンチマークでは、BF16 GRPOを、すべての最適化を有効にしたHugging Face（kernelsライブラリのすべてのカーネル、Flash Attention 3、chunked lossカーネルなど）と比較します：

### :1234:フラット化されたシーケンス長のチャンク化

以前、Unslothはバッチ次元でチャンク化することにより、logitsテンソル全体を実体化しないことでRLのメモリ使用量を削減していました。順伝播中にlogitsを実体化するために必要なVRAMの概算を式（1）に示します。

$$
\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のVRAM** がlogitsテンソルの保存に必要になります。

を通じて [Long Context gpt-oss](/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md) 昨年、GRPO向けに融合ロスのアプローチを導入しました。このアプローチにより、一度に処理されるのは単一のバッチサンプルだけになり、ピークメモリ使用量が大幅に削減されます。同じ構成では、VRAM使用量はおよそ **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://735611837-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対HF、すべての最適化を有効化）</p></figcaption></figure> <figure><img src="https://735611837-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対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のVRAM** だけで、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://735611837-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://735611837-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://735611837-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://735611837-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]`）を保持するため、バッチ次元に沿って常にチャンク化されます。追加のシーケンスチャンク化は、GRPO設定内の `unsloth_logit_chunk_multiplier` で制御されます。未設定の場合は `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. VRAMを削減し、速度を向上させるために、カスタムのコンパイルオプション付きでtorch.compileを利用しています。
2. すべてのチャンク化されたlogitsは、精度を保つためにfloat32へアップキャストされます。
3. logit softcapping、温度スケーリング、その他すべての機能をサポートしています。

### :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`では、VRAM使用量はおよそ **2 GB**になります。このリリースでは、log確率計算中のhidden statesテンソルに対して、バッチ次元にわたるオプションのチャンク化を導入します。これにより、VRAM使用量はバッチサイズで割られ、この場合は **0.244 GB**になります。これにより、hidden statesの実体化に必要なピークVRAMが削減され、下の更新された式に反映されています：

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

当社の [500K Context Training](/docs/jp/burogu/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` に設定すると、 **VRAM使用量を約5 GB削減しつつ、速度低下はほとんどないか、まったくありません** （旧版のUnslothと比較して）。

<figure><img src="https://735611837-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/jp/meru/reinforcement-learning-rl-guide/advanced-rl-documentation.md).&#x20;
{% endhint %}

### :cactus:log softmaxのためのアクティベーションのオフロード

このリリースの開発中、hidden statesに対してバッチ次元をまたいでタイル化する際、融合済みのlogitsとlogprobsの計算後にアクティベーションがオフロードされていないことが判明しました。logitsは `hidden_states[i] @ lm_head`を使って一度に1バッチずつ計算されるため、モデルの順伝播内で動作するように設計された既存のアクティベーションオフロードおよび勾配チェックポイント化のロジックは、この場合には適用されませんでした。

これに対処するため、以下の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`、次のことを行います **を設定しない場合は** 利用可能なVRAMとコンテキスト長のサイズに応じて、これら2つのパラメータを自動調整します。ただし、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://735611837-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フレームワークの中核コンポーネントでした。UnslothのRLをより良くするうえで重要な役割を果たしているvLLMチームとすべての貢献者の皆さまに、心から感謝します！

より長いコンテキストでのRLを試すには、既存の [GRPOノートブック](/docs/jp/meru/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) Vision 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を支え、これを可能にしてくれたHugging Faceチームとライブラリに心から感謝します。


---

# 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/jp/meru/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.
