> 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/advanced-rl-documentation.md).

# 高度な強化学習ドキュメント

UnslothとGRPOを使う際の高度なドキュメント設定。

バッチ処理、生成、学習パラメータのための Unsloth を使った GRPO 実行に関する詳細ガイド:

## 学習パラメータ

* **`beta`** *(float, デフォルト 0.0)*: KL係数。
  * `0.0` ⇒ 参照モデルは読み込まれていません（メモリ使用量が少なく、高速）。
  * より高い `beta` ことで、ポリシーを参照ポリシーにより近く保つよう制約します。
* **`num_iterations`** *(int, デフォルト 1)*: バッチごとの PPO エポック数（アルゴリズム内の μ）。\
  各勾配蓄積ステップ内でデータを再実行します。例えば、 `2` = 蓄積ステップごとに 2 回の順伝播。
* **`epsilon`** *(float, デフォルト 0.2)*: トークンレベルの対数確率比に対するクリッピング値（通常の比率範囲は、デフォルトの ε で ≈ \[-1.2, 1.2]）。
* **`delta`** *(float, オプション)*: を有効にします **上側の** クリッピング境界を **双方向 GRPO の** 場合に設定します。 `なし`の場合、標準の GRPO クリッピングが使用されます。推奨値 `は > 1 + ε` です（有効時、INTELLECT-2 レポートに基づく）。
* **`epsilon_high`** *(float, オプション)*: 上限側の epsilon。未設定の場合は `epsilon` が既定です。DAPO では **0.28**.
* **`importance_sampling_level`** *（"token" | "sequence", デフォルト "token"）*:
  * `"token"`: トークンごとの生の比率（トークンあたり 1 つの重み）。
  * `"sequence"`: トークンごとの比率を平均して 1 つの系列レベル比率にします。\
    GSPO では、系列レベルのサンプリングの方が、系列レベル報酬に対してより安定した学習になりやすいことが示されています。
* **`reward_weights`** *(list\[float], オプション)*: 報酬ごとに 1 つの重み。 `なし`の場合、すべての重み = 1.0。
* **`scale_rewards`** *(str|bool, デフォルト "group")*:
  * `True` または `"group"`: でスケーリング **各グループ内の標準偏差により** （グループ内で分散 1）。
  * `"batch"`: でスケーリング **バッチ全体の標準偏差で** （PPO-Lite による）。
  * `False` または `"none"`: **スケーリングなし**. Dr. GRPO では、標準偏差によるスケーリングが難易度バイアスを生むのを避けるため、スケーリングしないことを推奨しています。
* **`loss_type`** *(str, デフォルト "dapo")*:
  * `"grpo"`: 系列長で正規化します（長さバイアスあり。非推奨）。
  * `"dr_grpo"`: により正規化します **グローバル定数** （Dr. GRPO で導入；長さバイアスを除去）。定数 ≈ `max_completion_length`.
  * `"dapo"` **（デフォルト）**: により正規化します **グローバルに蓄積されたバッチ内のアクティブトークン** （DAPO で導入；長さバイアスを除去）。
  * `"bnpo"`: により正規化します **ローカルバッチ内のアクティブトークン** のみ（結果はローカルバッチサイズによって変わる場合があります。 `per_device_train_batch_size == 1`).
* **`mask_truncated_completions`** *(bool, デフォルト False)*:\
  の場合、 `True`切り詰められた completion は loss から除外されます（安定性のため DAPO が推奨）。\
  **注意**: このフラグには KL の問題がいくつかあるため、無効にすることを推奨します。

  ```python
  # mask_truncated_completions が有効な場合、completion_mask 内の切り詰められた completion を 0 にする
  if self.mask_truncated_completions:
      truncated_completions = ~is_eos.any(dim=1)
      completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
  ```

  これにより、すべての `completion_mask` エントリが 0 になる場合があり、 `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`** *(bool, デフォルト True)*:\
  を適用します **打ち切り重要度サンプリング (TIS)** を用いて、生成（例: vLLM / fast\_inference）と学習バックエンドが異なる場合のオフポリシー効果を補正します。\
  Unsloth では、これは **自動的に True に設定されます** vLLM/fast\_inference を使用している場合は。そうでなければ **False**.
* **`vllm_importance_sampling_cap`** *(float, デフォルト 2.0)*:\
  打ち切りパラメータ **C** TIS 用。安定性向上のため、重要度サンプリング比の上限を設定します。
* **`dtype`** float16 または bfloat16 を選ぶ場合は、こちらを参照してください [RLにおけるFP16とBF16](/docs/jp/meru/reinforcement-learning-rl-guide/advanced-rl-documentation/fp16-vs-bf16-for-rl.md)

### 未対応モデルでの RL:

vLLM でサポートされていないモデルでも、Unsloth を使って RL を実行できます。例えば [Qwen3.5](/docs/jp/moderu/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, デフォルト 1.0):`\
  サンプリング用の温度です。温度が高いほど、生成結果はよりランダムになります。学習に役立つ多様性を生成に持たせるため、比較的高い (1.0) 温度を使用してください。
* `top_p (float, オプション、デフォルト 1.0):`\
  考慮する上位トークンの累積確率を制御する float です。値は (0, 1] の範囲でなければなりません。すべてのトークンを考慮するには 1.0 に設定します。
* `top_k (int, オプション):`\
  top-k フィルタリングで保持する、最も確率の高い語彙トークンの数。None の場合、top-k フィルタリングは無効になり、すべてのトークンが考慮されます。
* `min_p (float, オプション):`\
  最小トークン確率。これは最も起こりやすいトークンの確率でスケーリングされます。0.0 から 1.0 の値である必要があります。一般的な値は 0.01〜0.2 の範囲です。
* `repetition_penalty (float, オプション、デフォルト 1.0):`\
  プロンプトやこれまでに生成されたテキストに出現したかどうかに基づいて、新しいトークンにペナルティを与える float です。1.0 を超える値はモデルに新しいトークンの使用を促し、1.0 未満の値はトークンの繰り返しを促します。
* `steps_per_generation: (int, オプション):`\
  生成ごとのステップ数。None の場合、既定値は `gradient_accumulation_steps`です。 `generation_batch_size`.

{% hint style="info" %}
このパラメータをいじるのは少し分かりにくいため、 `per_device_train_batch_size` および勾配蓄積をバッチサイズ用に編集することを推奨します
{% endhint %}

## バッチおよびスループットのパラメータ

### バッチを制御するパラメータ

* **`train_batch_size`**: サンプル数 **各プロセスあたり** 各ステップごと。\
  この整数が **より小さい `num_generations`**&#x5834;合、既定で `num_generations`.
* **`steps_per_generation`**: の数 **マイクロバッチ** が寄与する **1 回の生成の** loss 計算に（順伝播のみ）。\
  新しいデータバッチは `steps_per_generation` ステップごとに生成されます。逆伝播のタイミングは `gradient_accumulation_steps`.
* **`num_processes`**: 分散学習プロセス数（例: GPU / ワーカー）。
* **`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
  ```

  **GRPO が機能するには > 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   # must be > 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/jp/meru/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.
