> 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/moderu/tutorials/gemma-3-how-to-run-and-fine-tune.md).

# Gemma 3 - 実行ガイド

Google が、270M の新モデルと従来の 1B、4B、12B、27B サイズを備えた Gemma 3 をリリースしました。270M と 1B はテキスト専用で、より大きいモデルはテキストと視覚の両方を扱います。GGUF と、効果的な実行方法、およびファインチューニングと実施方法のガイドを提供します [RL](/docs/jp/meru/reinforcement-learning-rl-guide.md) 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 ガイド](/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune.md).
{% 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 Dynamic 4-bit Instruct                                                                                                                                                                                                                                                                                                                                                                                                                           | 16-bit Instruct                                                                                                                                                                                                                                                                                                                                                                 |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <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-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-GGUF">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-GGUF">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-GGUF">27B-it</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-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-bnb-4bit">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-unsloth-bnb-4bit">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-bnb-4bit">27B-it</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-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b">27B-it</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
* 反復ペナルティ 1.0。（1.0 は llama.cpp と transformers では無効を意味します）
* チャットテンプレート：

  <pre data-overflow="wrap"><code><strong>&#x3C;bos>&#x3C;start_of_turn>user\nこんにちは！&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\nやあ！&#x3C;end_of_turn>\n&#x3C;start_of_turn>user\n1+1 は？&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\n
  </strong></code></pre>
* \n付きのチャットテンプレート `\n`改行を表示したもの（最後のものを除く）

{% code overflow="wrap" %}

```
<bos><start_of_turn>user
こんにちは！<end_of_turn>
<start_of_turn>model
やあ！<end_of_turn>
<start_of_turn>user
1+1 は？<end_of_turn>
<start_of_turn>model\n
```

{% endcode %}

{% hint style="danger" %}
llama.cpp とその他の推論エンジンは \<bos> を自動追加します。\<bos> トークンを 2 つ入れないでください！ モデルにプロンプトを与えるときは \<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
curl -fsSL https://ollama.com/install.sh | sh
```

2. モデルを実行してください！失敗した場合は、 `ollama serve`を別の端末で呼び出せます。修正点と推奨パラメータ（temperature など）はすべて `params` 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`

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

3. **または** （インストール後に）経由でモデルをダウンロードします `pip install huggingface_hub hf_transfer` 。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 スレッド数について、 `--ctx-size 16384` コンテキスト長用（Gemma 3 は 128K のコンテキスト長をサポートします！） `--n-gpu-layers 99` GPU オフロードするレイヤー数について。GPU がメモリ不足になったら調整してみてください。CPU のみで推論する場合は、これも削除してください。
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 \
    --ctx-size 16384 \\
    --n-gpu-layers 99 \\
    --seed 3407 \\
    --prio 2 \
    --temp 1.0 \\
    --repeat-penalty 1.0 \
    --min-p 0.01 \\
    --top-k 64 \
    --top-p 0.95
```

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

```bash
./llama.cpp/llama-cli \\
    --model unsloth/gemma-3-27b-it-GGUF/gemma-3-27b-it-Q4_K_XL.gguf \
    --ctx-size 16384 \\
    --n-gpu-layers 99 \\
    --seed 3407 \\
    --prio 2 \
    --temp 1.0 \\
    --repeat-penalty 1.0 \
    --min-p 0.01 \\
    --top-k 64 \
    --top-p 0.95 \\
    -no-cnv \\
    --prompt "<start_of_turn>user\nPython で Flappy Bird ゲームを作成してください。以下を必ず含めてください:\n1. pygame を使用すること。\n2. 背景色はランダムに選ばれた明るい色にすること。最初は薄い青色から始めること。\n3. SPACE を複数回押すと鳥が加速すること。\n4. 鳥の形はランダムに正方形、円、三角形のいずれかにすること。色はランダムに暗い色にすること。\n5. 下部に、ランダムに選ばれた濃い茶色または黄色の地面を置くこと。\n6. 右上にスコアを表示すること。パイプを通過して当たらなければ加点すること。\n7. 十分な間隔のあるパイプをランダムに配置すること。色はランダムに濃い緑、薄茶色、または暗い灰色系にすること。\n8. 負けたらベストスコアを表示すること。テキストは画面内に収めること。q または Esc を押すとゲーム終了。再開はもう一度 SPACE を押すこと。\n最終的なゲームは Python の Markdown セクション内に入れること。最終の Markdown セクションの前にコードのエラーを確認して修正してください。<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
Python で Flappy Bird ゲームを作成してください。以下を必ず含めてください：
1. pygame を使用すること。
2. 背景色はランダムに選ばれた明るい色にすること。最初は薄い青色から始めること。
3. SPACE を複数回押すと鳥が加速すること。
4. 鳥の形はランダムに正方形、円、三角形のいずれかにすること。色はランダムに暗い色にすること。
5. 下部に、ランダムに選ばれた濃い茶色または黄色の地面を置くこと。
6. 右上にスコアを表示すること。パイプを通過して当たらなければ加点すること。
7. 十分な間隔のあるパイプをランダムに配置すること。色はランダムに濃い緑、薄茶色、または暗い灰色系にすること。
8. 負けたらベストスコアを表示すること。テキストは画面内に収めること。q または Esc を押すとゲーム終了。再開はもう一度 SPACE を押すこと。
最終的なゲームは Python の Markdown セクション内に入れること。コードのエラーを確認し
```

{% 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)](/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune.md) で [テキスト](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" %}
Gemma 3 を完全ファインチューニング（FFT）しようとすると、float16 デバイスでは全レイヤーがデフォルトで float32 になります。Unsloth は float16 を前提としており、動的に upcast します。修正するには、次を実行してください `model.to(torch.float16)` 読み込み後、または bfloat16 対応の GPU を使用してください。
{% endhint %}

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

Unsloth での私たちの解決策は 3 段階です：

1. すべての中間活性化を bfloat16 形式に保つ - float32 でもよいですが、その場合は 2 倍の VRAM または RAM を使用します（Unsloth の非同期勾配チェックポイント処理を使用）
2. テンソルコアを使ってすべての行列乗算を float16 で行い、ただし PyTorch の mixed precision autocast の助けを借りずに、手動で upcast / downcast します。
3. 行列乗算を必要としないその他の項目（layernorm など）はすべて float32 に upcast します。

## 🤔 Gemma 3 修正の分析

<figure><img src="/files/ed0562b9c5e28cddcbeb47d1c105497bcac6de89" alt="" width="563"><figcaption><p>Gemma 3 1B から 27B は float16 の最大値 65504 を超えます</p></figcaption></figure>

まず、Gemma 3 をファインチューニングまたは実行する前に、float16 の mixed precision を使用すると、勾配と **活性化が無限大になります** 残念ながらこれは、float16 の tensor core しか持たない T4 GPU、RTX 20x シリーズ、V100 GPU で起こります。

RTX 30x 以上、A100、H100 などの新しい GPU では、これらの GPU は bfloat16 tensor core を備えているため、この問題は発生しません！ **では、なぜ？**

<figure><img src="/files/f2e9b4448f30ea936c16b266fedaa183faf6c03b" alt="" width="375"><figcaption><p>Wikipedia <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 倍も遅くなります！ そのため、これは使えません。


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://unsloth.ai/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
