EmbeddingGemma 2 开发者指南
英文标题:EmbeddingGemma 2: The Developer Guide
EmbeddingGemma 2 是一款采用 Apache 2.0 许可证发布的紧凑型开源多模态嵌入模型,可将文本、代码、图像、视频和音频映射到统一的 768 维向量空间。该模型基于 Gemma 4,开发者可按需加载编码器,参数规模可从仅支持文本和代码的 2.7 亿扩展至全模态的 7.4 亿。通过 Matryoshka Representation Learning(MRL),向量可从 768 维截断至 128 维,以显著降低向量数据库存储成本。对于 RAG、代码搜索、跨模态检索和端侧索引等场景,sentence-transformers 库提供了直接的模型加载、任务提示、媒体输入和向量截断支持。
54.9 KB
674.8 KB
204.4 KB
102.2 KB
105.2 KB
730.2 KB
47.0 KB
351.9 KB
46.3 KB
1.0 MB
中文

现代搜索和检索增强生成(RAG)应用日益需要处理多种内容类型,包括技术文档、源代码、图像、视频片段和音频记录。挑战在于:如何找到既能在所有这些格式上提供强大检索准确率、又能保持低延迟,同时不需要庞大计算基础设施来运行和建立索引的模型。
EmbeddingGemma 2 旨在提供一个采用 Apache 2.0 许可证发布的单一、紧凑型开放模型,并以其规模实现出色的多模态性能。该亚 10 亿参数模型基于 Gemma 4,可将文本、代码、图像、视频和音频映射至统一的 768 维空间。其模块化架构让你只加载所需的部分:从面向文本和代码的 2.7 亿参数,扩展至支持全部模态的 7.4 亿参数。
主要能力包括:
- **原生多模态检索:**可直接在共享的 768 维向量空间中实现跨文本、代码、图像、视频和音频的搜索。
- **卓越的代码理解能力:**在代码搜索和技术检索方面显著优于 EmbeddingGemma 1,非常适合本地代码库索引和 Agent 驱动的代码搜索。
- **模块化内存占用:**在运行时选择性加载所需编码器:2.7 亿参数(文本/代码)、4.4 亿参数(文本 + 视觉)、5.7 亿参数(文本 + 音频),或 7.4 亿参数(完整多模态);它们均投射到同一个兼容的向量空间。
- **灵活的向量存储:**Matryoshka Representation Learning(MRL)支持将 768 维向量动态截断至 128 维,在保留大量原始质量的同时降低向量数据库存储需求。例如,在 256 维时,文本和代码嵌入可保留原始完整嵌入的大部分质量,图像、视频和语音检索则可保留约 95% 的质量。
底层工作原理
EmbeddingGemma 2 以模块化编码器取代了串联模型,并将其投射至共享的 768 维空间:
尽管每种模态均由专门的编码器处理,所有输入都会经过共享骨干网络,所得嵌入也处于相同的维度空间:
- **文本和代码(2.7 亿基础参数):**经过适配的 Gemma 4 解码器,拥有 8,192 token 的上下文窗口。
- **视觉(+1.7 亿参数):**视觉编码器可处理图像、视觉文档(PDF、幻灯片、图表)和视频帧。
- **音频(+3 亿参数):**专用语音与声音编码器,可直接接收原始音频。
- **模块化加载:**只加载所需部分。仅运行文本时为 2.7 亿参数;加入视觉后为 4.4 亿参数;加载完整多模态模型时为 7.4 亿参数。
- **与 Gemma 4 共享分词器和音频编码器:**在端侧 RAG 流水线中与 Gemma 4 配合使用时,两个模型共享相同的文本分词器和音频编码器架构,从而降低总体内存占用。
实际演示
[视频/嵌入内容:浏览器不支持播放该视频]
我们使用仅含 2.7 亿参数的文本配置,对 Hugging Face transformers 代码库进行了嵌入。随后,这些嵌入被用于通过 Agent(搭载 Pi agent harness 的 Gemma 4 26B A4B),依据查询与代码库之间的相似度,高效搜索这个大型代码库。
开发者指南:使用 EmbeddingGemma 2
你可以通过 sentence-transformers 库(v6.1.0 或更高版本),让 EmbeddingGemma 2 处理文本、代码、图像、视频和音频:
pip install -U sentence-transformers[image,audio,video] transformers
Shell
第 1 步:加载模型
完整模型可嵌入文本、代码、图像、视频和音频:
from sentence_transformers import SentenceTransformer
# 完整模型:所有模态(7.4 亿参数)
MODEL_ID = "google/embeddinggemma-2"
model = SentenceTransformer(MODEL_ID)
Python
为尽量减少内存使用,你可以在加载时通过在 config_kwargs 中将 vision_config 或 audio_config 设置为 None,省略未使用的模态编码器。被禁用的编码器不会被加载到内存中,因此可同时节省权重内存和峰值分配内存:
# 仅文本(2.7 亿参数)
text_only_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"vision_config": None, "audio_config": None},
)
# 文本、图像和视频(4.4 亿参数)
text_image_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"audio_config": None},
)
# 文本和音频(5.7 亿参数)
text_audio_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"vision_config": None},
)
Python
第 2 步:使用任务提示嵌入文本和代码
EmbeddingGemma 2 通过简短的任务指令进行训练,以便为特定任务引导表征。请在 encode() 中设置 prompt_name,模型会为你添加相应提示:
对于检索,应使用不同提示分别嵌入查询和文档:
query = "What causes the northern lights?"
document = "The northern lights are caused by charged particles from the sun.." # truncated
# 使用 `prompt_name` 生成嵌入
query_emb = model.encode(query, prompt_name="SearchQuery")
doc_emb = model.encode(document, prompt_name="Document")
print(model.similarity(query_emb, doc_emb))
Python
第 3 步:嵌入图像、视频、音频和交错输入
无需提示,可将媒体作为以模态为键的字典传入。若要将文本与媒体共同嵌入,请使用 <|image|>、<|video|> 或 <|audio|> 标注各项内容的位置:
# 跨模态搜索:一个文本查询与一张照片和一段录音进行匹配
image_emb = model.encode({"image": "sunset_beach.jpg"})
audio_emb = model.encode({"audio": "ocean_waves.wav"})
query_emb = model.encode("ocean waves at sunset", prompt_name="SearchQuery")
print(model.similarity(query_emb, image_emb))
print(model.similarity(query_emb, audio_emb))
# 交错输入:为包含文本、照片和视频的商品列表生成一个嵌入
listing_emb = model.encode({
"text": "Waterproof trail shoe. <|image|> Grip test on wet rock: <|video|>",
"image": "trail_shoe.jpg",
"video": "grip_test.mp4",
})
query_emb = model.encode("waterproof trail shoes", prompt_name="SearchQuery")
print(model.similarity(query_emb, listing_emb))
Python
尽管来自不同模态,EmbeddingGemma 2 生成的嵌入处于相同的维度空间中,因此可按语义相似度进行比较。
第 4 步:通过 Matryoshka(MRL)截断维度
结合 normalize_embeddings=True 传入 truncate_dim(512、256 或 128),即可获得更短的单位长度向量。查询和文档必须使用相同维度:
# 截断查询向量
query_emb = model.encode(
query,
prompt_name="SearchQuery",
truncate_dim=256,
normalize_embeddings=True,
)
Python
如需让每次调用都使用同一维度,也可以在加载时设置:SentenceTransformer(MODEL_ID, truncate_dim=256)。例如,以 bfloat16 精度存储 100 万个 768 维向量大约需要 1.5 GB 内存,而将其截断至 128 维后仅需 250 MB。这种 6 倍缩减可让你在相同内存预算中存储 6 倍数量的嵌入,更容易将大型索引装入内存或部署到设备端。
选择你的配置
在 sentence-transformers 中,全部四种编码器配置均从同一检查点加载,因此共享同一个向量空间:使用仅含 2.7 亿参数的文本配置嵌入的查询,可直接与使用完整模型嵌入的文档匹配。
一般而言,只加载数据所需的编码器;仅在存储容量或搜索速度有要求时截断向量维度。
应加载哪些编码器
如果你先构建仅文本索引,之后再添加图像或音频嵌入,只需重新加载模型并启用额外编码器。已经计算完成的嵌入无需重新计算。
应使用哪个维度
- **768d 或 512d:**适用于多模态和视觉文档检索,或任何召回率比存储空间更重要的场景。
- **256d(存储减少 3 倍):**适用于存储受限的索引。以三分之一的存储空间,保留原始嵌入在文本和代码上的大部分完整质量,以及图像、视频和语音检索约 95% 的质量。
- **128d(存储减少 6 倍):**适用于大型纯文本索引和第一阶段候选筛选(重排序之前的筛选)。文本和代码可保留约 90% 的质量,但图像、视频和语音检索质量会降至约 75%。在为多模态查询部署 128d 前,请先在目标数据上进行验证。
单次输入可容纳多少内容
所有模态共享 8,192 token 的上下文窗口,并采用固定换算比例:
最大值假定只使用单一模态且不包含文本。媒体可通过文件路径(视频使用 MP4)、URL(图像和音频),或内存中的 PIL 图像、数组和张量传入。默认情况下,视频以每秒 1 帧采样,音频应为 16 kHz 单声道。
基准测试与评估
EmbeddingGemma 2 在 MTEB(代码)上的得分比 EmbeddingGemma 1 高 14%,新增了图像、视频和音频检索能力,同时保持了 EmbeddingGemma 1 在多语言文本上的准确率。
立即开始使用
准备好探索多模态嵌入了吗?请查看以下资源以了解更多信息:
English / 原文

Modern search and retrieval augmented generation (RAG) applications increasingly need to work across diverse content types, from technical documentation and source code to images, video clips, and audio recordings. The challenge is finding models that deliver strong retrieval accuracy while maintaining low latency across all these formats without requiring massive compute infrastructure to run and index.
EmbeddingGemma 2 is designed to provide a single, compact open model released under the Apache 2.0 license, delivering exceptional multimodal performance for its size. Based on Gemma 4, this sub-1B model maps text, code, images, video, and audio into a unified 768-dimensional space. Its modular architecture lets you load only what you need, scaling from 270M parameters for text and code up to 740M parameters for all modalities.
Key capabilities include:
- Native multimodal retrieval: Unlocks search across text, code, images, video, and audio directly in a shared 768-dimensional vector space.
- Superior code understanding: Significantly outperforms EmbeddingGemma 1 on code search and technical retrieval, making it ideal for local codebase indexing and agentic code search.
- Modular memory footprint: Selectively load only the encoders you need at runtime: 270M (text/code), 440M (text + vision), 570M (text + audio), or 740M (full multimodal), all projecting into the same compatible vector space.
- Flexible vector storage: Matryoshka Representation Learning (MRL) enables dynamic truncation from 768 dimensions down to 128 dimensions, cutting vector database storage requirements while retaining much of the original quality. For instance, at 256 dimensions, most of the full quality of the original embedding on text and code is retained and about 95% on image, video, and speech retrieval
How it works under the hood
EmbeddingGemma 2 replaces chained models with modular encoders that project into a shared 768-dimensional space:
Even though each modality is processed by a specialized encoder, all inputs are processed through the shared backbone and their resulting embeddings occupy the same dimensional space:
- Text and code (270M base): An adapted Gemma 4 decoder with an 8,192-token context window.
- Vision (+170M): A vision encoder that processes images, visual documents (PDFs, slides, charts), and video frames.
- Audio (+300M): A dedicated speech and sound encoder that directly ingests raw audio.
- Modular loading: You only load what you need. Run text-only at 270M parameters, add vision for 440M parameters, or load the full multimodal model at 740M parameters.
- Shared tokenizer & audio encoder with Gemma 4: When paired with Gemma 4 in an on-device RAG pipeline, both models share the same text tokenizer and audio encoder architecture, reducing the total memory footprint.
See it in action
Sorry, your browser doesn't support playback for this video
We embedded the Hugging Face transformers codebase with the 270M text-only setup. Then, the embeddings are used to efficiently search through this large codebase by matching the similarity of the query with the codebase using an Agent (Gemma 4 26B A4B with the Pi agent harness) .
Developer Guide: Using EmbeddingGemma 2
You can run EmbeddingGemma 2 across text, code, images, video, and audio with the sentence-transformers library (v6.1.0 or later):
pip install -U sentence-transformers[image,audio,video] transformers
Shell
Step 1: Load the Model
The full model embeds text, code, images, video, and audio:
from sentence_transformers import SentenceTransformer
# Full model: all modalities (740M parameters)
MODEL_ID = "google/embeddinggemma-2"
model = SentenceTransformer(MODEL_ID)
Python
To minimize memory usage, you can omit unused modality encoders at load time by setting vision_config or audio_config to None in config_kwargs. Disabled encoders are never loaded into memory, so the savings apply to both the weights and peak allocation:
# Text only (270M parameters)
text_only_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"vision_config": None, "audio_config": None},
)
# Text, images, and video (440M parameters)
text_image_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"audio_config": None},
)
# Text and audio (570M parameters)
text_audio_model = SentenceTransformer(
MODEL_ID,
config_kwargs={"vision_config": None},
)
Python
Step 2: Embed Text and Code with Task Prompts
EmbeddingGemma 2 is trained with short task instructions to steer representations for specific tasks. Set prompt_name in encode() to add it for you:
For retrieval, encode queries and documents with different prompts:
query = "What causes the northern lights?"
document = "The northern lights are caused by charged particles from the sun.." # truncated
# Embed using `prompt_name`
query_emb = model.encode(query, prompt_name="SearchQuery")
doc_emb = model.encode(document, prompt_name="Document")
print(model.similarity(query_emb, doc_emb))
Python
Step 3: Embed Images, Video, Audio, and Interleaved Inputs
Pass media as a dictionary keyed by modality without a prompt. To embed text and media together, mark where each item goes with <|image|>, <|video|>, or <|audio|>:
# Cross-modal search: one text query against a photo and a sound recording
image_emb = model.encode({"image": "sunset_beach.jpg"})
audio_emb = model.encode({"audio": "ocean_waves.wav"})
query_emb = model.encode("ocean waves at sunset", prompt_name="SearchQuery")
print(model.similarity(query_emb, image_emb))
print(model.similarity(query_emb, audio_emb))
# Interleaved: one embedding for a product listing with text, photo, and video
listing_emb = model.encode({
"text": "Waterproof trail shoe. <|image|> Grip test on wet rock: <|video|>",
"image": "trail_shoe.jpg",
"video": "grip_test.mp4",
})
query_emb = model.encode("waterproof trail shoes", prompt_name="SearchQuery")
print(model.similarity(query_emb, listing_emb))
Python
Despite coming from different modalities, the embeddings generated by EmbeddingGemma 2 occupy the same dimensional space and can be compared on their semantic similarity.
Step 4: Truncate Dimensions with Matryoshka (MRL)
Pass truncate_dim (512, 256, or 128) with normalize_embeddings=True to get shorter, unit-length vectors. Queries and documents must use the same dimension:
# Truncate the query
query_emb = model.encode(
query,
prompt_name="SearchQuery",
truncate_dim=256,
normalize_embeddings=True,
)
Python
To use one dimension for every call, set it at load time instead: SentenceTransformer(MODEL_ID, truncate_dim=256). For instance, in bfloat16 precision, storing a million 768-dimensional vectors takes roughly 1.5 GB of memory, while truncating them to 128 dimensions requires just 250 MB. That 6x reduction allows you to store six times as many embeddings in the same memory budget, making it much easier to fit large indexes in memory or on-device.
Choosing Your Configuration
In sentence-transformers, all four encoder setups load from the same checkpoint, so they share one vector space: a query embedded with the 270M text-only setup can be matched directly against documents embedded with the full model.
As a general guideline, load only the encoders your data needs, and truncate dimensions only when storage or search speed require it.
Which Encoders to Load
If you start with a text-only index and later add image or audio embeddings, simply reload the model with the additional encoder enabled. Embeddings you have already computed do not need to be re-computed.
Which Dimension to Use
- 768d or 512d: Multimodal and visual document retrieval, or whenever recall matters more than storage.
- 256d (3x storage reduction): Storage-constrained indexes. Keeps most of the full quality of the original embedding on text and code and about 95% on image, video, and speech retrieval, at a third of the storage.
- 128d (6x storage reduction): Large text-only indexes and first-stage shortlisting (shortlisting before re-ranking). Text and code retains around 90% quality, but image, video, and speech retrieval quality drop to around 75%. Validate on your target data before deploying 128d for multimodal queries..
How Much Fits in One Input
All modalities share the 8,192-token context window, at fixed rates:
The maximums assume a single modality with no text. Pass media as file paths (MP4 for video), URLs (images and audio), or in-memory PIL images, arrays, and tensors. Video is sampled at 1 frame per second by default, and audio should be 16 kHz mono.
Benchmarks & Evaluation
EmbeddingGemma 2 scores 14% higher than EmbeddingGemma 1 on MTEB (Code), adds image, video, and audio retrieval while retaining the accuracy on multilingual text of EmbeddingGemma 1
Getting Started Today
Ready to explore multimodal embeddings? Take a look at the following resources to find out more: