> 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/burogu/3x-faster-training-packing.md).

# Unsloth Kernels + Packing による 3 倍高速な LLM 学習

Unsloth が学習スループットをどのように向上させ、ファインチューニング時のパディングの無駄をなくすかを学びます。

Unsloth は現在、最大で **5倍高速** （通常は3倍）私たちの新しいカスタムによる学習 **RoPE と MLP の Triton カーネル**、さらに新しいスマートな自動パッキングも追加されています。Unsloth の新しいカーネル＋機能は、学習速度を向上させるだけでなく、さらに **VRAM 使用量を削減します（30%〜90%）** 精度の低下はありません。 [Unsloth GitHub](https://github.com/unslothai/unsloth)\
\
つまり、現在は次のような LLM を学習できるということです [Qwen3](/docs/jp/moderu/tutorials/qwen3-how-to-run-and-fine-tune.md)-4B だけではなく **3GBのVRAM**、さらに3倍高速に。

私たちの自動 [**padding-free**](#padding-free-by-default) コンタミネーションのないパッキングは、変更なしで全ての学習実行に対して自動的に有効化され、すべての高速アテンションバックエンド（FlashAttention 3、xFormers、SDPA）にも対応します。 [ベンチマーク](#analysis-and-benchmarks) 学習損失がパッキングなしの実行と一致することを示しています **完全に**.

* **QK Rotary Embedding が 2.3倍高速** パッキング対応の fused Triton カーネル
* SwiGLU、GeGLU カーネルを更新し、 **長いコンテキスト向けの int64 インデックス**
* **コンタミネーションのないパッキングが 2.5倍〜5倍高速** xFormers、SDPA、FA3 バックエンドで
* **padding-free が 2.1倍高速、VRAM を 50%削減**、精度変化 0%
* Unsloth では、SFT 損失の安定性が改善され、GPU 使用率の予測性も向上しました。
* この新しいアップグレードは **すべての学習手法で** 例: フルファインチューニング、事前学習など。

### :drum:パッキング対応の Fused QK RoPE Triton カーネル

2023年12月、Unsloth のリリースの一環として、Triton で実装した RoPE カーネルを導入しました。2024年3月には、コミュニティメンバーがヘッドのグループごとにブロックを起動できるよう RoPE カーネルを最適化し、エンドツーエンド学習を1〜2%高速化しました。参照: [PR 238](https://github.com/unslothai/unsloth/pull/238).

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FewadBu05vK7zAmJRJcj6%2Frope_varlen_qk_rope_kernel_benchmark_v5.png?alt=media&amp;token=04d277d4-c289-4943-9312-e3d3e2d60bec" alt="" width="563"><figcaption></figcaption></figure>

1つの問題は、Q と K それぞれに 2 つの Triton カーネルがあることでした。現在はそれらを 1 つの Triton カーネルに統合し、 padding-free と packing 対応に不可欠な可変長 RoPE を有効化しました。これにより、マイクロベンチマークにおける RoPE カーネルは **より長いコンテキスト長で 2.3倍高速**、より短いコンテキスト長で 1.9倍高速です。

さらに、すべての clone と contiguous な transpose 操作を排除したため、 **RoPE は現在完全に inplace です**、GPU メモリをさらに削減します。逆伝播では、次のことが分かります。 `sin1 = -sin1` なぜなら:

```
Q * cos + rotate_half(Q) * sin
は次と等価です
Q * cos + Q @ R * sin
ここで R は回転行列 [ 0,  I]
                             [-I,  0]
dC/dY = dY * cos + dY @ R.T * sin
ここで R.T も同様に [ 0, -I]
ただしマイナスは転置されています。 [ I,  0]
```

### :railway\_car:Triton カーネルの int64 インデックス

私たちが導入した 50万件の長コンテキスト学習中に [500K Context Training](/docs/jp/burogu/500k-context-length-fine-tuning.md)、CUDA の範囲外エラーが発生していました。これは、SwiGLU、GeGLU 用の MLP カーネルが int32 インデックスを使用しており、これは Triton と CUDA のデフォルトだからです。

単純に次のようにはできません `tl.program_id(0).to(tl.int64)` なぜなら、int64 インデックスのため学習がわずかに遅くなるからです。代わりにこれを `LONG_INDEXING: tl.constexpr` 変数にして、Triton コンパイラがこれを特化できるようにします。これにより、短いコンテキストでも長いコンテキストでもどちらも快適に実行できます！

{% code overflow="wrap" %}

```python
block_idx = tl.program_id(0)
if LONG_INDEXING:
    offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to(tl.int64)
    n_elements = tl.cast(n_elements, tl.int64)
else:
    offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
```

{% endcode %}

### :abacus:なぜ padding が必要か & 数学的な高速化

コンピュータや GPU は長さの異なるデータセットをそのまま処理できないため、0 で埋める必要があります。これにより無駄が発生します。50% が短い系列 S、50% が長い系列 L のデータセットがあると仮定すると、最悪の場合、padding によりトークン使用量は $$\text{batchsize} \times L$$ 最長の系列長が支配的になるためです。

複数の例を 1 つの長い 1 次元テンソルにパックすることで、かなりの量の padding を削減できます。実際、次のトークン使用量になります:

$$
\text{Token Usage} = \frac{\text{batchsize}}{2}L+\frac{\text{batchsize}}{2}S
$$

少し数式と代数を使うと、次の式で高速化を求められます:

$$
\text{Speedup} = \frac{\text{batchsize} \times L}{\frac{\text{batchsize}}{2}L+\frac{\text{batchsize}}{2}S} = 2 \frac{L}{L + S}
$$

次を仮定すると $$S\rightarrow0$$ すると、理論上 2倍の高速化が得られます。なぜなら $$2 \frac{L}{L + 0} = 2$$

50% の短い系列という比率を変え、短い系列がさらに多いと仮定すると、たとえば長い系列が20%、短い系列が80%の場合、次が得られます $$\frac{L}{0.2L + 0.8S}\rightarrow\frac{L}{0.2L}=5$$ つまり、学習が 5倍高速になります！ これは、packing による高速化がデータセットにどれだけ短い行があるかに依存することを意味します（短いものが多いほど速い）。

### :clapper:デフォルトで padding-free

次を設定した場合に得られる大きなスループット向上に加えて `packing = True` あなたの `SFTConfig` 、次のことを行います **自動的に padding-free バッチ処理を使用し** padding の無駄を減らし、スループットを向上させ、tokens/s スループットを増やすためです。その結果、 ***まったく同じ損失*** 前バージョンの Unsloth と同じになります。

たとえば Qwen3-8B と Qwen3-32B では、メモリ使用量が 60% 減少し、2倍高速になり、損失と勾配ノルム曲線もまったく同じです！

<div><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FPATEJoJwIotXNPsYT1hu%2FW%26B%20Chart%2010_12_2025%2C%203_57_51%20am.png?alt=media&amp;token=e31ee2cd-cd6e-4fd2-9c59-7f2148179815" alt=""><figcaption></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FjjnXdgPSgUxL9WNzx9wc%2FW%26B%20Chart%2010_12_2025%2C%203_58_19%20am.png?alt=media&amp;token=54368c73-2ce1-4faa-a1f4-c82341638be3" alt=""><figcaption></figcaption></figure></div>

<div><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FA61fgCtUj0K9dhrHCt0C%2FW%26B%20Chart%2010_12_2025%2C%203_54_40%20am.png?alt=media&amp;token=b8472635-4b05-430e-9df1-3820ed381c3f" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FPh0Xfaup0CTz8REL6P9F%2FW%26B%20Chart%2010_12_2025%2C%203_56_38%20am.png?alt=media&amp;token=86ed33c3-e5ac-4b71-82c3-f8f86ca79862" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F6FKM6pkRkQX3gzQLdcIP%2FW%26B%20Chart%2010_12_2025%2C%203_55_38%20am.png?alt=media&amp;token=48d2c1d3-e6f2-420c-8209-70ef247ce63d" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FxbhcPeELu78xh3M01xkf%2FW%26B%20Chart%2010_12_2025%2C%203_56_07%20am.png?alt=media&amp;token=375c3f27-5af8-43e5-93eb-3818cb401f95" alt="" width="563"><figcaption></figcaption></figure></div>

### :spades:コンタミネーションのないパッキングで学習が 2〜5倍高速

実際のデータセットにはさまざまな系列長が含まれるため、たとえばバッチサイズを32に増やすと padding が発生し、学習が遅くなり、VRAM も多く使用します。

{% hint style="success" %}
以前は、増やすと `batch_size` を大きな数（>32）にすると、学習は速くなるのではなく遅くなっていました。これは padding が原因でしたが、今では次の方法でこの問題を解消できます `packing = True`そのため、学習はより速くなります！
{% endhint %}

複数のサンプルを 1 つの 1 次元テンソルにパックする際、サンプル間でアテンションが漏れないように、各サンプルを適切にマスクするための系列長メタデータを保持します。また、次で説明する RoPE カーネルも必要です [#fused-qk-rope-triton-kernel-with-packing](#fused-qk-rope-triton-kernel-with-packing "mention") position id のリセットを可能にするためです。

{% columns %}
{% column width="41.66666666666667%" %}

<div align="center" data-full-width="false"><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F508zS4YN2sYnYjYkt8ej%2Fimage.png?alt=media&amp;token=a05f917a-f593-4abd-a834-2f3f6652ca5a" alt="" width="563"><figcaption><p>パッキングなしの 4 つの例はスペースを無駄にします</p></figcaption></figure></div>

{% endcolumn %}

{% column width="58.33333333333333%" %}

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F8azEy9wbeF2RWSWbNdma%2Fimage.png?alt=media&amp;token=a4b96567-244a-45ed-8b18-b16074bac88c" alt=""><figcaption><p>コンタミネーションのないパッキングは正しいアテンションパターンを作成します</p></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

50% の短い系列という比率を変え、短い系列がさらに多いと仮定すると、たとえば長い系列が20%、長い系列が80%の場合、次が得られます $$\frac{L}{0.2L + 0.8S}\rightarrow\frac{L}{0.2L}=5$$ つまり、学習が 5倍高速になります！ これは、packing による高速化がデータセットにどれだけ短い行があるかに依存することを意味します（短いものが多いほど速い）。

### :beach:分析とベンチマーク

新しいカーネルとパック済みデータで学習した際のさまざまな改善を示すために、次のモデルでファインチューニングを実行しました [Qwen3-32B](/docs/jp/moderu/tutorials/qwen3-how-to-run-and-fine-tune.md)、Qwen3-8B、Llama 3 8B を用いて `yahma/alpaca-cleaned` データセットでさまざまな [学習損失](#padding-free-by-default) スループットと効率の指標を測定しました。新しい実行と、独自のカーネル/最適化を有効にし、Flash Attention 3（FA3）などのカーネルを有効にした標準的な最適化済み学習実行を比較しました。次を固定しました `max_length = 1024` そしてバッチサイズを {1, 2, 4, 8, 16, 32} で変化させました。これにより、バッチごとの最大トークン数は {1024, 2048, 4096, 8192, 16K, 32K} の範囲で変化します。

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FFfmdok7AmeretPSGlZjg%2Fnew%20rope%20kernel%20graph.png?alt=media&amp;token=d890fd95-c8c0-4817-9ee3-18e3095cde5f" alt="" width="563"><figcaption></figcaption></figure>

上の図は、バッチサイズを変えたときに新しい Unsloth の tokens per second（tokens/s）学習スループットがどのように変化するかを示しています。これは、データセットの 1 エポックでモデルを学習する際に **1.7〜3倍高速（場合によっては5倍以上）**！これらの向上は、データに短い系列が多い場合や、学習が長時間にわたる場合により顕著になります。これは次で説明したとおりです [#why-is-padding-needed-and-mathematical-speedup](#why-is-padding-needed-and-mathematical-speedup "mention")

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FReViERxLWBHnT8GOv0ql%2Fpacking_efficiency_by_per_device_train_batch_size.png?alt=media&amp;token=1c4a78c7-a611-4374-ac03-94aabb1d3184" alt="" width="563"><figcaption></figcaption></figure>

上の図は、各バッチ内で有効なトークン（つまり padding ではないトークン）の平均割合を示しています。バッチサイズが大きくなるほど、パックされていない場合には padding トークンが大幅に増えますが、パックされた場合は最大系列長に関係なく高いパッキング効率を達成できます。

なお、バッチ処理のロジックはバッチ内で見られた最大系列長に合わせてバッチを切り詰めるため、バッチサイズが1のときは、パックされていないデータはすべて有効トークン（つまり padding なし）です。しかし、バッチに例を追加するほど、平均的に padding は増え、バッチサイズ8ではほぼ 50% の padding に達します！私たちのサンプルパッキング実装はその無駄をなくします。

<div><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FRfzNZVz9uzDPhEe3frGe%2Funknown.png?alt=media&amp;token=e9fe893e-6b94-4c0d-b144-ef8315067c1e" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FTHtcpIdQ0z0mGRYYBfuF%2Funknown.png?alt=media&amp;token=ec52b2c1-1e60-4ed2-969a-d760af26be2a" alt="" width="563"><figcaption></figcaption></figure></div>

最初のグラフ（上）は、次の条件での進捗をプロットしています `yahma/alpaca-cleaned` を `max_length = 2048`、packing + kernels を備えた新しい Unsloth（えんじ色）と古い Unsloth（灰色）の比較です。どちらも次で学習されています `max_steps = 500`ただし、x 軸は実時間でプロットしています。パックされた場合、同じステップ数（そして実時間も少しだけ長い程度）でエポックの約40%を学習できる一方、パックされていない場合はエポックの5%未満しか学習できないことに注目してください。

同様に、2番目のグラフ（上）は同じ実行の損失を示しており、今度は x 軸に学習ステップを取っています。損失のスケールと傾向は一致していますが、packing した場合の損失は、1学習ステップあたりにモデルがより多くのトークンを見るため、ばらつきが小さくなっています。

### :sparkles:packing を有効にするには？

**まず Unsloth を更新してください。padding-free はデフォルトで有効です**！そのため、すべての学習が直ちに 1.1〜2倍高速になり、少なくともメモリ使用量は 30% 減少し、損失曲線の指標はまったく変わりません！

{% code overflow="wrap" %}

```bash
pip install --upgrade --force-reinstall --no-cache-dir --no-deps unsloth
pip install --upgrade --force-reinstall --no-cache-dir --no-deps unsloth_zoo
```

{% endcode %}

また、Xformers 経由の Flash Attention 3、SDPA 対応、Flash Attention 2 もサポートしており、Tesla T4、RTX 2080 などの古い GPU や、H100、B200 などの新しい GPU でも動作します！サンプルパッキングは *アテンションバックエンドやモデルファミリーの選択に関係なく*そのため、これらの高速アテンション実装で以前得られたのと同じ高速化を楽しめます！

明示的に packing を有効にしたい場合は、次を追加してください `packing = True` 最大で 5倍高速な学習を有効にします！

{% hint style="warning" %}
注意 `packing=True` 複数の短い系列が 1 つの系列にパックされるため、学習損失が変わり、データセットの行数も切り詰められます。データセット内の例の数が減って見えるかもしれません。

学習損失の値を変えたくない場合は、単に次を設定してください `packing=False` そうすると、自動 padding-free が有効になり、それだけで学習がすでに高速になります！
{% endhint %}

```python
from unsloth import FastLanguageModel
from trl import SFTTrainer, SFTConfig

model, tokenizer = FastLanguageModel.from_pretrained(
    "unsloth/Qwen3-14B",
)

trainer = SFTTrainer(
    model = model,
    processing_class = tokenizer,
    train_dataset = dataset,
    args = SFTConfig(
        per_device_train_batch_size = 1,
        max_length = 4096,
        …,
        packing = True, # サンプルパッキングを有効にするために必要です！
    ),
)
trainer.train()
```

私たちのノートブックはすべて自動的に高速化されています（何もする必要はありません）。参照: [Unslothノートブック](/docs/jp/meru/unsloth-notebooks.md)

{% columns %}
{% column %}
Qwen3 14B が高速化:

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(14B)-Reasoning-Conversational.ipynb>" %}
{% endcolumn %}

{% column %}
Llama 3.1 Conversational が高速化:

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_(1B_and_3B)-Conversational.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

ありがとうございます！興味があれば、次を参照してください: [500K Context Training](/docs/jp/burogu/500k-context-length-fine-tuning.md) ブログ、 [メモリ効率の高いRL](/docs/jp/meru/reinforcement-learning-rl-guide/memory-efficient-rl.md) ブログ、 [Long Context gpt-oss](/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md) ブログでは、カーネルや性能向上に関するさらに多くのトピックを紹介しています！


---

# 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/burogu/3x-faster-training-packing.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.
