# Gemma 3 - 実行方法ガイド

Googleは新しい270Mモデルと、以前の1B、4B、12B、27Bサイズを備えたGemma 3をリリースしました。270Mと1Bはテキスト専用で、より大きなモデルはテキストとビジョンの両方を扱います。私たちはGGUFを提供しており、効果的に実行する方法や、微調整と実行方法のガイドを提供します。 [強化学習（RL）](https://unsloth.ai/docs/jp/meru/reinforcement-learning-rl-guide) Gemma 3で！

{% hint style="success" %}
**新着 2025年8月14日 更新：** 私たちのファインチューニングを試してください [Gemma 3（270M）ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(270M\).ipynb) と [実行用のGGUF](https://huggingface.co/collections/unsloth/gemma-3-67d12b7e8816ec6efa7e4e5b).

こちらも参照してください [Gemma 3nガイド](https://unsloth.ai/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune).
{% endhint %}

<a href="#gmail-running-gemma-3-on-your-phone" class="button primary">実行チュートリアル</a><a href="#fine-tuning-gemma-3-in-unsloth" class="button secondary">ファインチューニングチュートリアル</a>

**Unslothは、Gemma 3の推論とトレーニングでfloat16マシン上で動作する唯一のフレームワークです。** これは、無料のTesla T4 GPUを備えたColabノートブックでも動作することを意味します！

* 視覚サポート付きのGemma 3（4B）を私たちのノートブックでファインチューニングしてください [無料のColabノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision.ipynb)

{% hint style="info" %}
Gemmaチームによれば、推論の最適な設定は次のとおりです\
`temperature = 1.0、top_k = 64、top_p = 0.95、min_p = 0.0`
{% endhint %}

**UnslothがアップロードしたGemma 3（最適設定）：**

| GGUF                                                                                                                                                                                                                                                                                                                                                                                                          | Unsloth ダイナミック 4ビット 指示（Instruct）                                                                                                                                                                                                                                                                                                                                                                                                             | 16ビット指示用                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it-GGUF">270M</a> - 新着</li><li><a href="https://huggingface.co/unsloth/gemma-3-1b-it-GGUF">1B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-GGUF">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-GGUF">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-GGUF">27B</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it-unsloth-bnb-4bit">270M</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-1b-it-bnb-4bit">1B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-bnb-4bit">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-unsloth-bnb-4bit">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-bnb-4bit">27B</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it">270M</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-1b">1B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b">27B</a></li></ul> |

## :gear: 推奨推論設定

Gemmaチームによると、推論の公式推奨設定は次のとおりです：

* Temperature（温度）を1.0に設定
* Top\_K は 64
* Min\_Pを0.00（オプション、但し0.01がよく機能します。llama.cppのデフォルトは0.1）
* Top\_P は 0.95
* Repetition Penalty は 1.0（llama.cpp と transformers では 1.0 が無効化を意味します）
* チャットテンプレート：

  <pre data-overflow="wrap"><code><strong>&#x3C;bos>&#x3C;start_of_turn>user\nHello!&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\nHey there!&#x3C;end_of_turn>\n&#x3C;start_of_turn>user\nWhat is 1+1?&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\n
  </strong></code></pre>
* チャットテンプレート（含む） `\n`改行がレンダリングされます（最後を除く）

{% code overflow="wrap" %}

```
<bos><start_of_turn>user
Hello!<end_of_turn>
<start_of_turn>model
Hey there!<end_of_turn>
<start_of_turn>user
What is 1+1?<end_of_turn>
<start_of_turn>model\n
```

{% endcode %}

{% hint style="danger" %}
llama.cppやその他の推論エンジンは自動的に\<bos>を追加します - \<bos>を二重に追加しないでください！モデルにプロンプトを与えるときは\<bos>を無視するべきです！
{% endhint %}

### ✨スマートフォンでGemma 3を実行する <a href="#gmail-running-gemma-3-on-your-phone" id="gmail-running-gemma-3-on-your-phone"></a>

モデルをスマートフォンで実行するには、携帯電話などのエッジデバイス上でGGUFをローカル実行できる任意のモバイルアプリを使用することを推奨します。ファインチューニング後にGGUFへエクスポートして、スマートフォン上でローカル実行できます。モデルの処理で過熱する可能性があるため、スマートフォンに十分なRAM/処理能力があることを確認してください。このユースケースにはGemma 3 270MやGemma 3nモデルを推奨します。次のものを試すことができます： [オープンソースプロジェクト AnythingLLM の](https://github.com/Mintplex-Labs/anything-llm) ダウンロードできるモバイルアプリ（場所） [Androidはこちら](https://play.google.com/store/apps/details?id=com.anythingllm) または [ChatterUI](https://github.com/Vali-98/ChatterUI)、これらはスマートフォンでGGUFを実行するのに適した優れたアプリです。

{% hint style="success" %}
チュートリアルのすべてで、モデル名 'gemma-3-27b-it-GGUF' を 'gemma-3-270m-it-GGUF:Q8\_K\_XL' のような任意のGemmaモデル名に変更できます。
{% endhint %}

## :llama: チュートリアル：OllamaでGemma 3を実行する方法

1. Ollamaで実行する `をインストールしてください` まだインストールしていない場合は！

```bash
apt-get update
こちらを参照してください
apt-get install pciutils -y
```

2. curl -fsSL <https://ollama.com/install.sh> | sh `モデルを実行してください！失敗した場合は別のターミナルで`ollama serve `を呼び出すことができます！私たちはすべての修正と推奨パラメータ（temperatureなど）を` 私たちのHugging Faceアップロードで！モデル名 'gemma-3-27b-it-GGUF' を 'gemma-3-270m-it-GGUF:Q8\_K\_XL' のような任意のGemmaモデルに変更できます。

```bash
ollama run hf.co/unsloth/gemma-3-27b-it-GGUF:Q4_K_XL
```

## 📖 チュートリアル：llama.cppでGemma 3 27Bを実行する方法

1. 最新の `llama.cpp` を [GitHubで入手してください](https://github.com/ggml-org/llama.cpp)。以下のビルド手順にも従うことができます。を変更してください `-DGGML_CUDA=ON` に `-DGGML_CUDA=OFF` GPUを持っていない場合やCPUで推論したい場合は **Apple Mac / Metalデバイスの場合**、次を設定してください `-DGGML_CUDA=OFF` その後通常通り続行してください — Metalサポートはデフォルトで有効です。

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=ON -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split llama-mtmd-cli
cp llama.cpp/build/bin/llama-* llama.cpp
```

2. もし直接 `llama.cpp` を使用したい場合、以下のようにできます：（:Q4\_K\_XL）は量子化タイプです。Hugging Face（ポイント3）からダウンロードすることもできます。これはollama runに類似しています。 `ollama run`

```bash
./llama.cpp/llama-mtmd-cli \
    -hf unsloth/gemma-3-4b-it-GGUF:Q4_K_XL
```

3. **または** モデルをダウンロードする（以下をインストールした後） `モデルをダウンロードするには（` ）。Q4\_K\_Mや他の量子化バージョン（BF16フル精度など）を選択できます。その他のバージョンは： <https://huggingface.co/unsloth/gemma-3-27b-it-GGUF>

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/gemma-3-27b-it-GGUF",
    local_dir = "unsloth/gemma-3-27b-it-GGUF",
    allow_patterns = ["*Q4_K_XL*", "mmproj-BF16.gguf"], # Q4_K_M用
)
```

4. UnslothのFlappy Birdテストを実行する
5. 編集 `次の` --threads 32 `はCPUスレッドの数、` コンテキスト長用（Gemma 3は128Kのコンテキスト長をサポートします！）、 `--n-gpu-layers 99` --n-gpu-layers 2
6. 会話モードの場合：

```bash
./llama.cpp/llama-mtmd-cli \
    --model unsloth/gemma-3-27b-it-GGUF/gemma-3-27b-it-Q4_K_XL.gguf \
    --mmproj unsloth/gemma-3-27b-it-GGUF/mmproj-BF16.gguf \
    --jinja \
    --n-gpu-layers 99 \
    --model unsloth/GLM-4.7-GGUF/UD-Q2_K_XL/GLM-4.7-UD-Q2_K_XL-00001-of-00003.gguf \
    --prio 2 \
    --flash-attn on \
    --repeat-penalty 1.0 \
    --min-p 0.01 \
    --top-k 64 \
    --top-p 0.95
```

7. 会話モード以外でFlappy Birdをテストするには：

```bash
export LLAMA_CACHE="unsloth/GLM-4.7-GGUF"
    --model unsloth/gemma-3-27b-it-GGUF/gemma-3-27b-it-Q4_K_XL.gguf \
    --jinja \
    --n-gpu-layers 99 \
    --model unsloth/GLM-4.7-GGUF/UD-Q2_K_XL/GLM-4.7-UD-Q2_K_XL-00001-of-00003.gguf \
    --prio 2 \
    --flash-attn on \
    --repeat-penalty 1.0 \
    --min-p 0.01 \
    --top-k 64 \
    --temp 1.0 \
    -no-cnv \
    --prompt "<start_of_turn>user\nCreate a Flappy Bird game in Python. You must include these things:\n1. You must use pygame.\n2. The background color should be randomly chosen and is a light shade. Start with a light blue color.\n3. Pressing SPACE multiple times will accelerate the bird.\n4. The bird's shape should be randomly chosen as a square, circle or triangle. The color should be randomly chosen as a dark color.\n5. Place on the bottom some land colored as dark brown or yellow chosen randomly.\n6. Make a score shown on the top right side. Increment if you pass pipes and don't hit them.\n7. Make randomly spaced pipes with enough space. Color them randomly as dark green or light brown or a dark gray shade.\n8. When you lose, show the best score. Make the text inside the screen. Pressing q or Esc will quit the game. Restarting is pressing SPACE again.\nThe final game should be inside a markdown section in Python. Check your code for errors and fix them before the final markdown section.<end_of_turn>\n<start_of_turn>model\n"
```

私たちの完全な入力は <https://unsloth.ai/blog/deepseekr1-dynamic> 1.58bitのブログは：

{% hint style="danger" %}
Gemma 3は自動的に\<bos>を追加するので、\<bos>を削除することを忘れないでください！
{% endhint %}

{% code overflow="wrap" %}

```
<start_of_turn>user
Heptagon
1. pygame を使用すること。
2. 背景色はランダムに選択され、淡い色合いにすること。最初は薄い青色から始めること。
3. SPACE を複数回押すと鳥が加速すること。
4. 鳥の形状はランダムに四角形、円、三角形のいずれかにし、色はランダムに暗い色にすること。
5. 画面下部に、ランダムに選ばれた暗い茶色または黄色の土地を配置すること。
6. スコアを右上に表示すること。パイプを通過して当たらなかった場合に増加させること。
7. 十分な間隔のランダムな間隔でパイプを配置すること。色はランダムに濃い緑、薄い茶色、または暗い灰色のいずれかにすること。
8. ゲームオーバー時にベストスコアを表示すること。テキストは画面内に表示すること。q または Esc を押すとゲームを終了すること。再開は再び SPACE を押すこと。
最終的なゲームはPythonのマークダウンセクション内にするべきです。コードのエラーを確認してください
```

{% endcode %}

## :sloth: UnslothでのGemma 3のファインチューニング

**Unslothは、Gemma 3の推論とトレーニングでfloat16マシン上で動作する唯一のフレームワークです。** これは、無料のTesla T4 GPUを備えたColabノートブックでも動作することを意味します！

* 私たちの新しいものを試してください [Gemma 3（270M）ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(270M\).ipynb) これは270Mパラメータモデルをチェスが非常に強くなるようにし、次のチェスの手を予測できます。
* 次のためのノートブックを使ってGemma 3（4B）をファインチューニングしてください： [**テキスト**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\).ipynb) または [**ビジョン**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision.ipynb)
* または微調整する： [Gemma 3n（E4B）](https://unsloth.ai/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune) と一緒に [テキスト](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Conversational.ipynb) • [ビジョン](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Vision.ipynb) • [オーディオ](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Audio.ipynb)

{% hint style="warning" %}
完全なフルファインチューニング（FFT）でGemma 3を試すと、float16デバイスではすべてのレイヤーがデフォルトでfloat32になります。Unslothはfloat16を想定して動的にアップキャストします。修正するには、読み込み後に `model.to(torch.float16)` を実行するか、bfloat16をサポートするGPUを使用してください。
{% endhint %}

### Unslothのファインチューニング修正

Unslothにおける私たちの解決策は3つあります：

1. すべての中間活性化をbfloat16形式で保持する — float32でも可能ですが、その場合はVRAMまたはRAMを2倍使用します（Unslothの非同期勾配チェックポイント機能を介して）
2. テンソルコアで行うすべての行列乗算をfloat16で実行しますが、Pytorchの混合精度autocastの助けを借りずに手動でアップキャスト/ダウンキャストを行います。
3. 行列乗算を必要としない他のオプション（layernormなど）をfloat32にアップキャストします。

## 🤔 Gemma 3 修正の分析

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-6d6081cbb6f8b4b999c57803ac863c0ee9636ee1%2Foutput(1).png?alt=media" alt="" width="563"><figcaption><p>Gemma 3の1Bから27Bはfloat16の最大値65504を超えます</p></figcaption></figure>

まず、私たちがGemma 3をファインチューニングまたは実行する前に、float16混合精度を使用すると勾配と **活性化が無限大になってしまう** という問題が見つかりました。残念ながらこれは、float16テンソルコアのみを持つT4 GPU、RTX 20xシリーズ、V100 GPUで発生します。

RTX 30x以降、A100、H100などの新しいGPUではbfloat16テンソルコアを持っているため、この問題は発生しません！ **しかし、なぜでしょうか？**

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-e616649aa69253e34ea1d92b291dbda62d08044a%2Ffloat16%20bfloat16.png?alt=media" alt="" width="375"><figcaption><p>ウィキペディア <a href="https://en.wikipedia.org/wiki/Bfloat16_floating-point_format">https://en.wikipedia.org/wiki/Bfloat16_floating-point_format</a></p></figcaption></figure>

Float16は表現できる数値の最大が **65504**だけですが、bfloat16は非常に大きな数値まで表現できます **10^38**！しかし両方の数値形式はわずか16ビットしか使いません！これは、float16がより小さな小数をより良く表現するためにより多くのビットを割り当てているのに対し、bfloat16は小数をあまり表現できないためです。

ではなぜfloat16なのか？単にfloat32を使えば良いのでは？しかし残念ながらGPU上のfloat32は行列乗算で非常に遅く、場合によっては4〜10倍遅くなります！そのためこれを使うことはできません。
