> 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 - 実行ガイド

llama.cpp、Ollama、Open WebUI上で当社のGGUFを使ってGemma 3を効果的に実行する方法と、Unslothでファインチューニングする方法を学びましょう！

Google は、270M の新モデルと、従来の 1B、4B、12B、27B サイズを備えた Gemma 3 をリリースしました。270M と 1B はテキスト専用ですが、より大きいモデルはテキストとビジョンの両方を扱えます。GGUF と、効果的な実行方法、さらに finetune と実行する方法のガイドを提供します [RL](/docs/jp/meru/reinforcement-learning-rl-guide.md) Gemma 3 で！

{% hint style="success" %}
**NEW 2025年8月14日 更新：** こちらの fine-tuning を試してみてください [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) を fine-tune しましょう [無料の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 チームによると、推論の公式推奨設定は次のとおりです：

* 温度 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`が表示されます（最後を除く）

{% 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 をローカル実行できるモバイルアプリの使用をおすすめします。fine-tuning 後、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 を fine-tuning する

**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) を fine-tune してください： [**テキスト**](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)
* または fine-tune [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 をフル fine-tune (FFT) しようとすると、float16 デバイスではすべての層がデフォルトで float32 になります。Unsloth は float16 を前提としており、動的にアップキャストします。これを修正するには、次を実行してください `model.to(torch.float16)` 読み込み後、または bfloat16 対応の GPU を使用してください。
{% endhint %}

### Unsloth の fine-tuning 修正

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

1. すべての中間活性化を bfloat16 形式で保持する - float32 にすることもできますが、その場合は 2 倍の VRAM または RAM を消費します（Unsloth の非同期勾配チェックポイントを使用）
2. テンソルコアを使ってすべての行列積を float16 で行いますが、Pytorch の mixed precision 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 を fine-tune したり実行したりする前に、float16 の混合精度を使うと勾配と **活性化が無限大になることを確認しました** 残念ながら、これは T4 GPU、RTX 20x シリーズ、V100 GPU で起こります。これらは float16 のテンソルコアしか持たないためです。

RTX 30x 以上、A100、H100 などの新しい GPU では、これらの 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>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 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/moderu/tutorials/gemma-3-how-to-run-and-fine-tune.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.
