> 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万パラメータを持ち**、 1つの **270M** パラメータ **テキスト** モジュール式 **ビジョン (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="/docs/jp/moderu/embeddinggemma-2.md#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">EmbeddingGemma 2 実行ガイド</a><a href="/docs/jp/moderu/embeddinggemma-2.md#fine-tune-embeddinggemma-2-with-unsloth" class="button secondary">ファインチューニングガイド</a>

### ⚙️ 使用ガイド

| 機能      | EmbeddingGemma 2                                                           |
| ------- | -------------------------------------------------------------------------- |
| パラメータ   | <p>合計7億4,000万（使用するものを選択できます）:</p><p>2億7,000万テキスト + 1億7,000万ビジョン + 3億音声</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="/docs/jp/moderu/embeddinggemma-2.md#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">Unsloth Desktop チュートリアル</a><a href="/pages/a107d71395963b75e5ef700da940e15d9713921f#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** の **埋め込みモデル** のドロップダウンを開き、必要に応じて **ダウンロード** をクリックします。

必要であれば、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>

チャットを開き、 **+**&#x3092;クリックして、 **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_%28300M%29-Multimodal_Search.ipynb)   | テキスト、画像、動画、音声をまたいだ検索を試せます。      |
| [テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29.ipynb)               | データに合わせてテキスト埋め込みをファインチューニングします。 |
| [画像-テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29-Image_Text.ipynb) | 画像とキャプションで学習し、その後検索品質を比較します。    |
| [音声のファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29-Audio.ipynb)           | 音声とキャプションで学習し、その後検索品質を比較します。    |

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

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

{% 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`までにしてください。各入力は単一の物理バッチに収まる必要があります。
{% 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: リセットリンクを受け取るには、Forgot password を選択してください。"
    ],
    "encoding_format": "float"
  }'
```

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

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

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

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

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

| ノートブック                                                                                                                                      | できること                           |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| [マルチモーダル検索](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29-Multimodal_Search.ipynb)   | テキスト、画像、動画、音声をまたいだ検索を試せます。      |
| [テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29.ipynb)               | データに合わせてテキスト埋め込みをファインチューニングします。 |
| [画像-テキストのファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29-Image_Text.ipynb) | 画像とキャプションで学習し、その後検索品質を比較します。    |
| [音声のファインチューニング](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma2_%28300M%29-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 = [
    "サインインページで Forgot password を選ぶと、リセットリンクを受け取れます。",
    "アカウント設定ページから請求情報を更新します。",
    "アカウントを保護するために二要素認証を有効にします。",
]
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 本の動画から単一の埋め込みを作成します。

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

```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",
    },
    prompt = "",
    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.
