> 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/embeddinggemma-2.md).

# EmbeddingGemma 2 - ローカル実行

EmbeddingGemma 2 をローカルで実行し、Unsloth でモデルをファインチューニングします。

**EmbeddingGemma 2** は、テキスト、コード、画像、動画、音声向けの Google の新しい埋め込みモデルです。このモデルは **7億4,000万パラメータ**、 **270M** パラメータ **text** モジュール式の **視覚（1億7,000万）** と **音声（3億）** エンコーダーを備えています。Apache 2.0 ライセンスをサポートし、 **100以上の言語** および **8Kのコンテキストウィンドウ** を備え、セマンティック検索、RAG、分類などのタスクに対応します。テキストとコードのみの場合は、より小さい **2億7,000万のテキストモデル**.

EmbeddingGemma 2 は、次の方法でローカル実行できます。 **GGUF** を使って [**Unsloth Desktop**](#use-embeddinggemma-2-in-unsloth-desktop) あるいは **モデルをファインチューニングする** Unsloth を介して。 [**embeddinggemma-2-GGUF**](https://huggingface.co/unsloth/embeddinggemma-2-GGUF)

<a href="#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">EmbeddingGemma 2 実行ガイド</a><a href="#fine-tune-embeddinggemma-2-with-unsloth" class="button secondary">ファインチューニングガイド</a>

### ⚙️ 使用ガイド

| 機能      | EmbeddingGemma 2                                                |
| ------- | --------------------------------------------------------------- |
| パラメータ   | <p>合計740M（使用する構成を選択可能）:</p><p>270Mのテキスト + 170Mの視覚 + 300Mの音声</p> |
| 入力      | テキスト、コード、画像、動画、音声、および混合入力                                       |
| コンテキスト長 | 8,192トークン。すべての入力で共通                                             |
| 埋め込み次元  | 768、512、256、または128                                              |

#### 推奨設定

* **精度:** 対応ハードウェアでは BF16、それ以外では FP32。
* **次元:** まずは **768**に似ています。 **512または256** から始めてベクトル保存量を削減し、評価してください **128** テキストのワークロードに対して。
* **正規化:** ベクトルを L2 正規化します。切り詰めた後も含みます。
* **プロンプト:** クエリには検索用プロンプトを、インデックス化するコンテンツには文書フォーマットを使用します。

{% hint style="warning" %}
**FP16 は使用しないでください。** EmbeddingGemma 2 は、FP16 では NaN や劣化した埋め込みを生成することがあります。量子化重みを読み込む際は、互換性のある計算 dtype を含め、BF16 または FP32 を使用してください。
{% endhint %}

### EmbeddingGemma 2 実行ガイド

<a href="#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">Unsloth Desktop チュートリアル</a><a href="#run-embeddinggemma-2-ggufs-in-llama.cpp" class="button secondary">Llama.cpp チュートリアル</a>

#### 🦥 Unsloth Desktop で EmbeddingGemma 2 を使用

EmbeddingGemma 2 を使って、ドキュメントのインデックス作成と検索をローカルで行えます。 **macOS、Windows、Linux**.

{% stepper %}
{% step %}

#### Unslothをインストール

始める最も簡単な方法は、 [Unsloth Desktopアプリ](/docs/jp/desktop.md)をダウンロードすることです。 [macOS](/docs/jp/meru/install/mac.md), [Windows](/docs/jp/meru/install/windows-installation.md)と [Linux](/docs/jp/meru/install/linux.md).

<a href="https://unsloth.ai/download" class="button primary" data-icon="down-to-bracket">Unslothをダウンロード</a>

* <i class="fa-apple">:apple:</i> [macOS用をダウンロード](https://unsloth.ai/download/mac)
* <i class="fa-windows">:windows:</i> [Windows用をダウンロード](https://unsloth.ai/download/windows)
* <i class="fa-linux">:linux:</i> [Linux用をダウンロード](https://unsloth.ai/download/linux)

または、手動でインストールしたい場合：

MacOS、Linux、WSL：

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

Windows PowerShell：

```bash
irm https://unsloth.ai/install.ps1 | iex
```

{% endstep %}

{% step %}

#### 埋め込みモデルを検索

<div data-with-frame="true"><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FA5YLVJdX7p1jXPhQ7MMr%2Fimage.png?alt=media&amp;token=b32b20b1-3c65-4c0e-b561-93f66eb30e60" alt="" width="563"><figcaption></figcaption></figure></div>

で **設定**、開いて **一般** までスクロールし **Documents & RAG**。選択し **EmbeddingGemma 2** の **Embedding model** ドロップダウンで、次にクリックし **ダウンロード** 必要に応じて。

必要であれば、GGUF のアップロードも使用できます。
{% endstep %}

{% step %}

#### ドキュメントを追加

<div data-with-frame="true"><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fo3Mu42tY5xZ9XtitMgSq%2Fimage.png?alt=media&amp;token=823216c4-1d79-432e-b428-dacc76497fc7" alt="" width="563"><figcaption></figcaption></figure></div>

チャットを開き、クリックし **+**、有効にします **Chat with Files**。次にクリックし **チャットにファイルを追加** して、ドキュメントを選択します。

Unsloth は、選択した埋め込みモデルを使ってドキュメントを検索可能にします。

{% hint style="info" %}
埋め込みモデルの変更は、新しくインデックス化されるドキュメントにのみ反映されます。既存のドキュメントを新しいモデルで使うには再アップロードしてください。
{% endhint %}
{% endstep %}
{% endstepper %}

Unsloth で EmbeddingGemma 2 を実行するその他の方法については、以下の **Python** に渡すことで有効にできます。 **GGUF** ガイドに従ってください。

### 📓 ノートブックをお試しください

ステップごとのノートブックを使って、Google Colab で EmbeddingGemma 2 を実行・学習できます。

| ノートブック                                                                                                                                    | できること                           |
| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| [マルチモーダル検索](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Multimodal_Search.ipynb)   | テキスト、画像、動画、音声を横断して検索してみてください。   |
| [テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\).ipynb)               | データに合わせてテキスト埋め込みをファインチューニングします。 |
| [画像-テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Image_Text.ipynb) | 画像とキャプションで学習し、その後検索品質を比較します。    |
| [音声のファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Audio.ipynb)           | 音声とキャプションで学習し、その後検索品質を比較します。    |

#### 🦙 llama.cpp で EmbeddingGemma 2 の GGUF を実行

EmbeddingGemma 2 をローカルで実行するには [Unsloth GGUF](https://huggingface.co/unsloth/embeddinggemma-2-GGUF)。次を含む llama.cpp ビルドを使用してください [EmbeddingGemma 2 サポート](https://github.com/ggml-org/llama.cpp/pull/30054)。以下のコマンドは、テキストおよびコード埋め込み用の最新ソースをビルドします。

{% stepper %}
{% step %}
**llama.cpp をビルドして GGUF をダウンロード**

Git、CMake、C++ コンパイラをインストールし、新しい作業ディレクトリで次のコマンドを実行します。最新の llama.cpp ソースをビルドし、Unsloth の 176 MB UD-Q4\_K\_XL GGUF をダウンロードします:

```bash
git clone https://github.com/ggml-org/llama.cpp.git
cmake -S llama.cpp -B llama.cpp/build -DCMAKE_BUILD_TYPE=Release
cmake --build llama.cpp/build --config Release -j 8 --target llama-server

pip install -U huggingface_hub

hf download unsloth/embeddinggemma-2-GGUF embeddinggemma-2-UD-Q4_K_XL.gguf \
  --local-dir embeddinggemma2-gguf
```

{% endstep %}

{% step %}
**埋め込みサーバーを起動**

この例では **テキストとコードの埋め込みを提供します**。2,048トークンのコンテキストから始めます:

```bash
./llama.cpp/build/bin/llama-server \
  --model "embeddinggemma2-gguf/embeddinggemma-2-UD-Q4_K_XL.gguf" \
  --alias embeddinggemma2 \
  --embeddings \
  --pooling mean \
  --ctx-size 2048 \
  --batch-size 2048 \
  --ubatch-size 2048 \
  --parallel 1 \
  --host 127.0.0.1 \
  --port 8080
```

2,048トークンを超える入力では、 `--ctx-size`, `--batch-size` と `--ubatch-size` をまとめて増やし、最大 `8192`までにしてください。各入力は1つの物理バッチに収まる必要があります。
{% endstep %}

{% step %}
**埋め込みをリクエスト**

API を呼び出す際は、タスク接頭辞を自分で追加してください:

```bash
curl http://127.0.0.1:8080/v1/embeddings \
  -H "Content-Type: application/json" \\
  -d '{
    "model": "embeddinggemma2",
    "input": [
      "task: search result | query: パスワードをリセットするにはどうすればよいですか？",
      "title: none | text: リセットリンクを受け取るには［パスワードをお忘れですか］を選択してください。"
    ],
    "encoding_format": "float"
  }'
```

embeddings エンドポイントは正規化されたベクトルを返します。インデックスを構築する前に、各ベクトルに 768 個の有限値があることを確認してください。
{% endstep %}
{% endstepper %}

{% hint style="info" %}
EmbeddingGemma 2 が学習した埋め込み射影を保持する GGUF とランタイムを使用してください。画像、動画、音声の場合は、それらのエンコーダーと対応するプロセッサーファイルを明示的にサポートするランタイムを使用してください。上記のコマンドはテキスト埋め込みに対応しています。
{% endhint %}

### 🛠️ Unsloth で EmbeddingGemma 2 をファインチューニング

ファインチューニングにより、ドキュメント、コード、用語の検索精度を向上できます。質問と関連ドキュメントのペアで学習し、学習前後の検索結果を比較してください。

無料のステップごとのノートブックを使って、Google Colab で EmbeddingGemma 2 を実行・学習できます。

| ノートブック                                                                                                                                    | できること                           |
| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| [マルチモーダル検索](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Multimodal_Search.ipynb)   | テキスト、画像、動画、音声を横断して検索してみてください。   |
| [テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\).ipynb)               | データに合わせてテキスト埋め込みをファインチューニングします。 |
| [画像-テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Image_Text.ipynb) | 画像とキャプションで学習し、その後検索品質を比較します。    |
| [音声のファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_\(300M\)-Audio.ipynb)           | 音声とキャプションで学習し、その後検索品質を比較します。    |

#### モデルを準備

Python の例からテキストモデルを保存します:

```python
text_model.save_pretrained("embeddinggemma2-text")
```

新しい Python セッションを開始し、最初に Unsloth をインポートします。保存したモデルを 4-bit で読み込み、学習用に LoRA アダプターを追加します:

```python
from unsloth import FastSentenceTransformer
import torch

model = FastSentenceTransformer.from_pretrained(
    model_name = "embeddinggemma2-text",
    max_seq_length = 1024,
    dtype = torch.bfloat16,
    load_in_4bit = True,
    load_in_16bit = False,
    full_finetuning = False,
)

model = FastSentenceTransformer.get_peft_model(
    model,
    r = 16,
    target_modules = [
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj",
    ],
    lora_alpha = 32,
    lora_dropout = 0,
    bias = "none",
    use_gradient_checkpointing = "unsloth",
    random_state = 3407,
    task_type = "FEATURE_EXTRACTION",
)
```

#### 学習と評価

次を参照してください [埋め込みファインチューニングガイド](https://unsloth.ai/docs/basics/embedding-finetuning) を使ってデータセットを準備し、 `SentenceTransformerTrainer`.

* Python の検索例のように、クエリと文書の接頭辞は1回だけ適用してください。
* まずは `MultipleNegativesRankingLoss` および重複を避けるバッチサンプラーを使います。
* 設定してください `bf16=True` と `fp16=False`.
* 学習に含めなかったクエリで検索品質をテストします。

ガイドの **EmbeddingGemma 300M ノートブック** は以前のモデルを扱っています。ワークフローの参考として使用してください。

#### アダプターを保存

学習後、LoRA アダプターを保存します:

```python
model.save_pretrained("embeddinggemma2-lora")
```

アダプターを単独モデルに統合する方法は、リンク先のガイドを参照してください。画像、動画、音声での学習には別のワークフローが必要です。

### 🚀 Python で EmbeddingGemma 2 を実行

この例では3つのドキュメントを検索し、質問との一致度で順位付けします。メモリ節約のため、テキストモデルのみを読み込みます。

EmbeddingGemma 2 をサポートする SentenceTransformers と Transformers をインストールします:

```bash
pip install -U sentence-transformers transformers
```

この例では、デバイスと対応精度を自動的に選択します。

```python
import torch
from sentence_transformers import SentenceTransformer

device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = (
    torch.bfloat16
    if device == "cuda" and torch.cuda.is_bf16_supported()
    else torch.float32
)

text_model = SentenceTransformer(
    "unsloth/embeddinggemma-2",
    device = device,
    model_kwargs = {"torch_dtype": dtype},
    config_kwargs = {"vision_config": None, "audio_config": None},
)

query = "パスワードをリセットするにはどうすればよいですか？"
documents = [
    "サインインページで［パスワードをお忘れですか］を選択すると、リセットリンクを受け取れます。",
    "アカウント設定ページから請求先情報を更新してください。",
    "アカウントを保護するために2要素認証を有効にしてください。",
]
embedding_dim = 768

query_embedding = text_model.encode(
    [query],
    prompt_name = "SearchQuery",
    truncate_dim = embedding_dim,
    normalize_embeddings = True,
)
document_embeddings = text_model.encode(
    documents,
    prompt_name = "Document",
    truncate_dim = embedding_dim,
    normalize_embeddings = True,
)

scores = text_model.similarity(query_embedding, document_embeddings)[0]
for idx in scores.argsort(descending = True).tolist():
    print(f"{scores[idx].item():.4f} | {documents[idx]}")
```

スコアが高いほど一致度が高いことを示します。質問とドキュメントはご自身の内容に置き換えてください。

#### 埋め込みを調整

**保存容量を節約:** 設定してください `embedding_dim` を **256** で埋め込み保存容量の3分の1を使用できますが、検索精度は多少低下します。クエリとドキュメントには同じ次元を使用してください。

**プロンプトを選択:** この例では `SearchQuery` を質問に、 `Document` を検索可能なコンテンツに使用します。コード検索では、 `CodeRetrieval` をクエリに使用します。2つのテキストの類似度を比較するには、 `SentenceSimilarity` を両方に使用します。

### 🖼️ 画像、動画、音声を埋め込み

テキストとメディアを1つの検索可能な項目にまとめます。この例では、製品説明、2枚の写真、1本の動画から単一の埋め込みを作成します。

上記のセットアップ後に実行し、ファイル名を自分のファイルに置き換えてください。インストールには、モデルプロセッサーの画像および動画の依存関係も必要です。

```python
multimodal_model = SentenceTransformer(
    "unsloth/embeddinggemma-2",
    device = device,
    model_kwargs = {"torch_dtype": dtype},
    config_kwargs = {"audio_config": None},
)

listing_embedding = multimodal_model.encode(
    {
        "text": "トレイルランニングシューズ。 <|image|> メッシュのアッパー。 <|image|> グリップテスト: <|video|>",
        "image": ["shoe.jpg", "mesh.jpg"],
        "video": "demo.mp4",
    },
    "",
    normalize_embeddings = True,
)
```

ファイル名を自分の画像と動画に置き換え、プレースホルダーの順序はそのままにしてください。モデルはそれらを1つの埋め込みに統合し、テキストで検索できます。

{% hint style="info" %}
メモリ節約のため音声は無効になっています。含めるには、 `config_kwargs` を削除し、 `音声` を付けた入力を追加します `<|audio|>` プレースホルダーを使用してください。モノラル音声を16 kHzで使います。
{% endhint %}

テキストとメディアは **8Kのコンテキスト制限を共有します**。画像、動画、音声にタスク接頭辞は不要です。


---

# 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/embeddinggemma-2.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.
