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

# EmbeddingGemma 2 - 本地运行

在本地运行 EmbeddingGemma 2，并使用 Unsloth 对该模型进行微调。

**EmbeddingGemma 2** 是 Google 面向文本、代码、图像、视频和音频的新嵌入模型。该模型具有 **7.4 亿参数**，结合了 一个 **270M** 参数 **text** 带有模块化 **视觉（1.7 亿）** 和 **音频（3 亿）** 编码器。它采用 Apache 2.0 许可证， **支持 100 多种语言** 以及一个 **8K 上下文窗口** ，适用于语义搜索、RAG 和分类等任务。对于仅文本和代码的场景，你可以加载更小的 **2.7 亿文本模型**.

你可以通过我们的 **GGUF 文件** 使用 [**Unsloth Desktop**](#use-embeddinggemma-2-in-unsloth-desktop) ，甚至可以 **微调模型** ，通过 Unsloth。 [**embeddinggemma-2-GGUF**](https://huggingface.co/unsloth/embeddinggemma-2-GGUF)

<a href="/docs/zh/mo-xing/embeddinggemma-2.md#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">EmbeddingGemma 2 运行指南</a><a href="/docs/zh/mo-xing/embeddinggemma-2.md#fine-tune-embeddinggemma-2-with-unsloth" class="button secondary">微调指南</a>

### ⚙️ 使用指南

| 特性    | EmbeddingGemma 2                                          |
| ----- | --------------------------------------------------------- |
| 参数    | <p>总计 7.4 亿（可选择使用哪个）：</p><p>2.7 亿文本 + 1.7 亿视觉 + 3 亿音频</p> |
| 输入    | 文本、代码、图像、视频、音频和混合输入                                       |
| 上下文长度 | 8,192 个 token，所有输入共享                                      |
| 嵌入维度  | 768、512、256 或 128                                         |

#### 推荐设置

* **精度：** 在受支持的硬件上使用 BF16，否则使用 FP32。
* **维度：** 先从 **768**。使用 **512 或 256** 开始，以减少向量存储；评估 **128** 在文本工作负载上的效果。
* **归一化：** 对向量进行 L2 归一化，包括截断后。
* **提示：** 对查询使用搜索提示，对你要索引的内容使用文档格式。

{% hint style="warning" %}
**不要使用 FP16。** EmbeddingGemma 2 在 FP16 下可能产生 NaN 或退化的嵌入。请使用 BF16 或 FP32，包括在加载量化权重时使用兼容的计算 dtype。
{% endhint %}

### EmbeddingGemma 2 运行指南

<a href="/docs/zh/mo-xing/embeddinggemma-2.md#use-embeddinggemma-2-in-unsloth-desktop" class="button primary">Unsloth Desktop 教程</a><a href="/pages/894b6ec8e2c463d5a64496786f8074faab8e8dd6#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/zh/desktop.md)。支持 [macOS](/docs/zh/kuai-su-kai-shi/install/mac.md), [Windows](/docs/zh/kuai-su-kai-shi/install/windows-installation.md)，以及 [Linux](/docs/zh/kuai-su-kai-shi/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://2657992854-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>

在 **设置**中，打开 **通用** 并滚动到 **文档与 RAG**。选择 **EmbeddingGemma 2** 来自 **嵌入模型** 下拉菜单，然后点击 **下载** （如有需要）。

如有需要，你也可以使用我们的 GGUF 上传。
{% endstep %}

{% step %}

#### 添加你的文档

<div data-with-frame="true"><figure><img src="https://2657992854-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>

打开聊天，点击 **+**，并启用 **使用文件聊天**。然后点击 **向聊天添加文件** 并选择你的文档。

Unsloth 会使用你选择的嵌入模型使文档可搜索。

{% hint style="info" %}
更改嵌入模型只会影响新索引的文档。要使用新模型，请重新上传现有文档。
{% endhint %}
{% endstep %}
{% endstepper %}

若想通过 Unsloth 以更多方式运行 EmbeddingGemma 2，请按照 **Python** 或 **GGUF** 以下指南。

### 📓 试试我们的 notebooks

使用我们循序渐进的 notebooks 在 Google Colab 中运行并训练 EmbeddingGemma 2。

| Notebook                                                                                                                              | 你可以做什么              |
| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| [多模态搜索](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

使用 [Unsloth GGUF](https://huggingface.co/unsloth/embeddinggemma-2-GGUF)在本地运行 EmbeddingGemma 2。使用包含 [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 token 的上下文开始：

```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 个 token 的输入，将 `--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: How do I reset my password?",
      "title: none | text: Select Forgot password to receive a reset link."
    ],
    "encoding_format": "float"
  }'
```

embeddings 端点会返回归一化向量。在构建索引之前，请检查每个向量是否具有 768 个有限值。
{% endstep %}
{% endstepper %}

{% hint style="info" %}
使用能够保留 EmbeddingGemma 2 学习到的嵌入投影的 GGUF 和运行时。对于图像、视频或音频，请使用对这些编码器及其处理器文件有显式支持的运行时。上面的命令覆盖的是文本嵌入。
{% endhint %}

### 🛠️ 使用 Unsloth 微调 EmbeddingGemma 2

微调可以改善对你的文档、代码和术语的搜索。使用问题与相关文档的配对进行训练，然后比较训练前后的搜索结果。

使用我们免费的分步 notebooks 在 Google Colab 中运行并训练 EmbeddingGemma 2。

| Notebook                                                                                                                              | 你可以做什么              |
| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| [多模态搜索](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 搜索示例中那样，只应用一次查询和文档前缀。
* 先从 `MultipleNegativesRankingLoss` 以及避免重复的批次采样器。
* 将 `bf16=True` 和 `fp16=False`.
* 在你留作训练集之外的查询上测试搜索质量。

该指南中的 **EmbeddingGemma 300M notebook** 涵盖了早期模型。可将其作为工作流程参考。

#### 保存你的适配器

训练结束后，保存 LoRA 适配器：

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

请参见链接的指南，了解如何将适配器合并为独立模型。在图像、视频或音频上训练需要单独的工作流程。

### 🚀 在 Python 中运行 EmbeddingGemma 2

此示例会搜索三份文档，并根据它们与你的问题的匹配程度进行排序。它仅加载文本模型以节省内存。

安装支持 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 = "How do I reset my password?"
documents = [
    "在登录页面选择“忘记密码”以接收重置链接。",
    "从账户设置页面更新你的账单信息。",
    "启用双重身份验证以保护你的账户。",
]
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** 以使用三分之一的嵌入存储，但搜索准确率会有所下降。查询和文档请使用相同的维度。

**选择一个提示：** 该示例使用 `SearchQuery` 来表示问题，并使用 `Document` 来表示可搜索内容。对于代码搜索，请使用 `CodeRetrieval` 作为查询。若要比较两个文本的相似度，请对两者都使用 `SentenceSimilarity` 。

### 🖼️ 嵌入图像、视频和音频

将文本和媒体组合成一个可搜索条目。此示例会为产品描述、两张照片和一个视频创建单个嵌入。

在完成上面的设置后运行它，并将文件名替换为你自己的文件。你的安装还需要模型处理器的图像和视频依赖项。

```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": "Trail running shoes. <|image|> Mesh upper. <|image|> Grip test: <|video|>",
        "image": ["shoe.jpg", "mesh.jpg"],
        "video": "demo.mp4",
    },
    prompt = "",
    normalize_embeddings = True,
)
```

将文件名替换为你自己的图像和视频，同时保持占位符顺序不变。模型会将它们合并为一个可用文本搜索的嵌入。

{% 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/zh/mo-xing/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.
