
EmbeddingGemma 2: Build Text and Image Search in Python
Summary
Run Google's new open multimodal embedder locally and search text, images and video with one index.
On October 6, Google DeepMind released EmbeddingGemma 2, an Apache 2.0 embedding model that puts text, code, images, video and audio into the same 768-dimensional vector space. It is built on a Gemma 4 text encoder and ships in sizes from 270M to 740M parameters, which means a laptop CPU can run it. The Hugging Face card and Google's developer guide both went up the same day, and the model has been climbing the trending lists since.
Why it matters: most RAG stacks today use one embedding model for text and a second, completely separate pipeline for images (usually OCR plus captioning). EmbeddingGemma 2 lets you skip that. A text query like 'how do I get my money back' can land directly on a screenshot of a refund policy slide, with no OCR step in between. And because the encoders are modular, you can load only the parts you need.
In this guide you will install the model, verify the task prompts, build a small multimodal search index, shrink it with Matryoshka truncation, and learn the traps that quietly wreck retrieval quality. Every code block below was run against the real google/embeddinggemma-2 weights on a CPU, and the printed outputs are the real ones.
Prerequisites
- Python 3.10+ and about 3 GB of free disk for the weights and PyTorch.
sentence-transformers6.1.0 or newer (earlier versions do not know the model's processor).torchvisioninstalled, even if you only plan to embed text (more on this in the pitfalls).- No GPU needed. The examples here ran on CPU; the full model loaded in about five seconds once cached.
Step 1: Install and load only the encoders you need
Google's guide gives the install line with extras for images, audio and video:
pip install -U "sentence-transformers[image,audio,video]" transformers
The model is modular. A text-only load is 270M parameters, adding vision brings it to 440M, adding audio gives 570M, and everything together is 740M. You choose by nulling out the configs you do not want, and the disabled encoders are never loaded into memory:
from sentence_transformers import SentenceTransformer
MODEL_ID = "google/embeddinggemma-2"
# 270M: text and code only
text_model = SentenceTransformer(
MODEL_ID, config_kwargs={"vision_config": None, "audio_config": None}
)
# 440M: text + images + video
vision_model = SentenceTransformer(MODEL_ID, config_kwargs={"audio_config": None})
# 570M: text + audio
audio_model = SentenceTransformer(MODEL_ID, config_kwargs={"vision_config": None})
# 740M: everything
full_model = SentenceTransformer(MODEL_ID)
print(text_model.get_embedding_dimension()) # 768
All four variants write into the same vector space. The practical consequence is big: you can index your media once with the 440M model on a beefy box, then answer queries with the 270M text-only model on a small server, and the vectors still line up. Section 4 proves this with numbers.
Step 2: Text retrieval, and why the prompts matter
EmbeddingGemma 2 was trained with short task prefixes on text inputs. In sentence-transformers you do not type the prefix yourself, you pass prompt_name. Print the table to see exactly what gets prepended:
print(text_model.prompts["SearchQuery"])
print(text_model.prompts["Document"])
print(text_model.prompts["CodeRetrieval"])
task: search result | query:
title: none | text:
task: code retrieval | query:
Queries and documents are asymmetric: queries use SearchQuery, documents use Document. Symmetric jobs such as clustering use the same prefix on everything (Clustering, Classification, SentenceSimilarity). Images, video and audio take no prefix at all.
query = "What causes the aurora borealis?"
docs = [
"The northern lights are caused by charged particles from the sun striking the atmosphere.",
"To rotate an API key, open Settings, choose Security, then click Regenerate.",
"def retry(fn, n=3): loop n times calling fn and catch exceptions",
]
q = text_model.encode(query, prompt_name="SearchQuery")
d = text_model.encode(docs, prompt_name="Document")
print(text_model.similarity(q, d))
tensor([[0.8225, 0.5176, 0.5198]])
The relevant sentence scores 0.82 and the two unrelated ones sit near 0.52. That gap of roughly 0.3 is what you want to see from a healthy setup. If your scores all cluster in a narrow band, check your prompts first.
Step 3: Build a multimodal search index
Now the part that is new. We will index four images and search them with plain text. To keep this reproducible without downloading anything, the script below draws four small 'documents' with Pillow: a bar chart, a refund policy slide, an architecture diagram and a sunset gradient.
from PIL import Image, ImageDraw, ImageFont
import os
os.makedirs("media", exist_ok=True)
F = ImageFont.load_default(size=28)
def card(name, bg, lines, extra=None):
im = Image.new("RGB", (640, 420), bg)
d = ImageDraw.Draw(im)
for i, l in enumerate(lines):
d.text((30, 30 + i * 44), l, fill="white", font=F)
if extra:
extra(d)
im.save(f"media/{name}.png")
def bars(d):
for i, h in enumerate([80, 140, 200, 260]):
d.rectangle((60 + i * 130, 380 - h, 150 + i * 130, 380), fill=(80, 200, 120))
card("revenue_chart", (20, 30, 60), ["Q3 revenue by region", "EMEA APAC AMER LATAM"], bars)
card("refund_slide", (90, 30, 30), ["Refund policy", "Full refund within 30 days", "Contact billing support"])
card("arch_diagram", (30, 60, 40), ["Architecture", "Client -> API gateway -> Queue", "Worker -> Postgres"])
im = Image.new("RGB", (640, 420)); d = ImageDraw.Draw(im)
for y in range(420):
d.line((0, y, 640, y), fill=(255, min(255, 60 + y // 2), max(0, 120 - y // 4)))
d.ellipse((260, 220, 380, 340), fill=(255, 230, 120))
im.save("media/sunset.png")
Embed the images with the vision-enabled model. Media goes in as a dict keyed by modality, with no prompt. Then run four queries that share no keywords with the images beyond what the model has to infer:
import numpy as np
model = SentenceTransformer(MODEL_ID, config_kwargs={"audio_config": None})
files = ["revenue_chart", "refund_slide", "arch_diagram", "sunset"]
I = model.encode([{"image": f"media/{f}.png"} for f in files], normalize_embeddings=True)
print(I.shape)
for q in ["bar chart of quarterly sales",
"how do I get my money back",
"system design diagram with a queue",
"orange sky at dusk"]:
qe = model.encode(q, prompt_name="SearchQuery", normalize_embeddings=True)
s = I @ qe
print(f"{q!r:42} ->", files[int(s.argmax())], np.round(s, 3))
(4, 768)
'bar chart of quarterly sales' -> revenue_chart [0.67 0.546 0.543 0.515]
'how do I get my money back' -> refund_slide [0.538 0.694 0.587 0.549]
'system design diagram with a queue' -> arch_diagram [0.55 0.544 0.695 0.522]
'orange sky at dusk' -> sunset [0.517 0.586 0.578 0.66 ]
Four for four. Notice the second row: the query says 'money back' and the slide says 'refund'. Neither the pixels nor the word overlap give that away, so the model is reading the text inside the image. The sunset has no text at all and still wins 'orange sky at dusk', so it is handling pure visual content too. The margins are modest (0.66 vs 0.58 on the sunset), which is normal for cross-modal similarity, so rank rather than threshold on absolute scores.
Step 4: Index on a big model, query on a small one
Because every configuration shares one space, a text-only query model can search vectors produced by the vision model. This is the setup I would use in production: heavy encoders run in a batch job, and the serving path loads only the 270M text tower.
small = SentenceTransformer(
MODEL_ID, config_kwargs={"vision_config": None, "audio_config": None}
)
qs = small.encode("bar chart of quarterly sales", prompt_name="SearchQuery",
normalize_embeddings=True)
print(np.round(I @ qs, 3))
[0.67 0.546 0.543 0.515]
The scores are identical to the full model's, down to the third decimal. That matches Google's note that you never need to recompute stored embeddings when you add or drop an encoder.
Step 5: Interleaved inputs for one embedding per record
Real records are mixed: a product listing has text, a photo and maybe a clip. You can embed them as a single vector by writing placeholders in the text. The placeholders are <|image|>, <|video|> and <|audio|>, and each one is filled in order from the matching key of the dict.
e = model.encode(
{"text": "Refund policy slide: <|image|>", "image": "media/refund_slide.png"},
normalize_embeddings=True,
)
q = model.encode("money back guarantee", prompt_name="SearchQuery", normalize_embeddings=True)
print(e.shape, float(e @ q))
(768,) 0.6837245225906372
A 0.68 against a query that appears nowhere in the text. For video, pass a path to an MP4 under the video key; it is sampled at 1 frame per second by default. For audio, supply 16 kHz mono.
Step 6: Shrink the index with Matryoshka truncation
The model supports output sizes of 768, 512, 256 and 128 dimensions. Smaller vectors mean less storage and faster search. Google's numbers: 256 dimensions keep most text and code quality and about 95% on image, video and speech retrieval, while 128 holds about 90% on text but only about 75% on other modalities. Pass truncate_dim and normalize_embeddings=True together.
I ran a small test: 12 support-center snippets (password reset, refunds, API limits, SSO, webhooks and so on) and 12 paraphrased queries that share few words with their targets, like 'close my account' for the deletion policy. Metric is top-1 accuracy.
for dim in (768, 512, 256, 128):
D = text_model.encode(list(corpus.values()), prompt_name="Document",
truncate_dim=dim, normalize_embeddings=True)
Q = text_model.encode(list(queries), prompt_name="SearchQuery",
truncate_dim=dim, normalize_embeddings=True)
top = (Q @ D.T).argmax(1)
hits = sum(keys[t] == gold for t, gold in zip(top, queries.values()))
print(dim, f"top1 {hits}/{len(queries)}", f"{dim*2/1024:.2f} KB/vec bf16")
768 top1 12/12 1.50 KB/vec bf16
512 top1 12/12 1.00 KB/vec bf16
256 top1 12/12 0.50 KB/vec bf16
128 top1 11/12 0.25 KB/vec bf16
At 256 dimensions nothing was lost and storage dropped threefold. At 128 one query slipped. This is a tiny corpus, so treat it as a smoke test, not a benchmark. The rule that matters is to measure on your own queries before committing, and to be more conservative if the index holds images or audio.
A worked example: one index for a support center
Here is how the pieces fit into a real service. The goal: customers type a question, and the hits can be help-center text, screenshots, or short screen recordings. The class below keeps one normalized matrix at 256 dimensions plus a parallel list of records.
import numpy as np
from sentence_transformers import SentenceTransformer
DIM = 256
class MediaIndex:
def __init__(self, model_id="google/embeddinggemma-2", audio=False):
cfg = {} if audio else {"audio_config": None}
self.model = SentenceTransformer(model_id, config_kwargs=cfg)
self.records, self.vecs = [], None
def _enc(self, item, query=False):
if isinstance(item, str):
return self.model.encode(
item, prompt_name="SearchQuery" if query else "Document",
truncate_dim=DIM, normalize_embeddings=True)
return self.model.encode(item, truncate_dim=DIM, normalize_embeddings=True)
def add(self, record_id, item):
v = self._enc(item)[None, :]
self.vecs = v if self.vecs is None else np.vstack([self.vecs, v])
self.records.append(record_id)
def search(self, text, k=3):
s = self.vecs @ self._enc(text, query=True)
order = np.argsort(-s)[:k]
return [(self.records[i], round(float(s[i]), 3)) for i in order]
idx = MediaIndex()
idx.add("kb/refunds", "Refunds are issued to the original payment method within 5 days.")
idx.add("img/refund_slide", {"image": "media/refund_slide.png"})
idx.add("img/revenue_chart", {"image": "media/revenue_chart.png"})
print(idx.search("how do I get my money back"))
[('kb/refunds', 0.775), ('img/refund_slide', 0.709), ('img/revenue_chart', 0.562)]
Text goes through prompt_name="Document", media goes in as a dict, and queries always use SearchQuery. Persist idx.vecs with np.save and the records as JSON. Past a few hundred thousand vectors, hand the matrix to FAISS, pgvector or your vector database of choice; the model does not care which.
Common pitfalls and gotchas
- Do not use float16. Google's model card warns the range is too small for this model and can give NaN or silently degraded embeddings. Use bfloat16 on GPU or float32 on CPU, e.g.
model_kwargs={"torch_dtype": torch.bfloat16}. - torchvision is required even for text-only use. On a fresh environment where I installed only
sentence-transformers, loading failed withCould not import module 'EmbeddingGemma2Processor'. The root cause was a missingtorchvisionimport inside the processor code. Installing the[image,audio,video]extras (ortorchvisionalone) fixes it. - Slicing is not truncating. If you cut a stored 768-d vector to its first 128 values yourself, the length is no longer 1. In my test the norms came out around 0.58. Re-normalize, or let
truncate_dimplusnormalize_embeddings=Truedo it. - Queries and documents must share a dimension. A 256-d query against a 768-d index is an error at best and garbage at worst. Pick the dimension once and store it with the index.
- Skipping the prompts costs accuracy. With no
prompt_nameon either side, my 12-query test dropped from 12/12 to 11/12. It is small here, but it grows on harder corpora. - One 8,192-token budget for everything. Text, images, video frames and audio share it. An image costs 280 tokens by default (adjustable from 70 to 1120), a video frame 140 at one frame per second, and audio 25 tokens per second. A 5 minute clip nearly fills the window by itself, so chunk long media.
- Titled documents need manual formatting.
prompt_name="Document"appliestitle: none. If you have titles, build the string yourself astitle: {title} | text: {content}. - Do not trust 128-d for images or audio until you have tested it. Google's own figure is about 75% retention there.
- Check the license page. The weights are Apache 2.0 per the guide, but the card also links the Gemma terms and Prohibited Use Policy. Read them before shipping.
Quick reference
| Need | Setting | Notes |
|---|---|---|
| Text/code only | config_kwargs={'vision_config': None, 'audio_config': None} | 270M params |
| Text + image/video | config_kwargs={'audio_config': None} | 440M params |
| Text + audio | config_kwargs={'vision_config': None} | 570M params |
| Everything | SentenceTransformer(MODEL_ID) | 740M params |
| Query | prompt_name='SearchQuery' | task: search result | query: |
| Document | prompt_name='Document' | title: none | text: |
| Smaller vectors | truncate_dim=256, normalize_embeddings=True | 512 / 256 / 128 supported |
| Interleaved | <|image|> <|video|> <|audio|> | filled from dict keys in order |
| Precision | bfloat16 or float32 | never float16 |
| Context | 8,192 tokens shared | image 280, frame 140, audio 25/s |
Next steps
- Swap my four Pillow images for your own screenshots and slides, and write 20 real queries to measure top-1 at 768, 256 and 128 dimensions.
- Add a short MP4 and a WAV file (16 kHz mono) with the full 740M model and see whether a spoken-word clip surfaces for a text query.
- Put the matrix in FAISS or pgvector and add a reranker on top of the top 20 for text-heavy results.
- Fine-tune on your domain: Google lists Unsloth support for exactly this.
- Primary sources: the Google Developers guide and the Hugging Face model card.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,605 newsletter subscribers.