翻篇收录说明
翻篇网页快照

Generate embeddings with EmbeddingGemma 2 - Gemma Docs

https://gemma.ai/models/embeddinggemma/inference/

最近抓取:2026-12-03 05:04:27(北京时间)

最近内容变化:2026-11-29 20:31:15(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Generate text embeddings, compute semantic similarity, apply task prompts, and build RAG and zero-shot classifiers with EmbeddingGemma 2 and Sentence Tr...

正文摘录

Generate Embeddings with Sentence Transformers¶ Models EmbeddingGemma 2 Uses Sentence Transformers Transformers Colab View as markdown EmbeddingGemma 2 is a lightweight, open-source 740M parameter model designed for unified text and multimodal embeddings. Built on the Gemma 4 decoder architecture, it maps inputs into a unified 768-dimensional vector space. Because of its compact footprint, you can run demanding semantic workflows (e.g. Retrieval-Augmented Generation (RAG), semantic search, and zero-shot classification) locally and offline on consumer GPUs or CPUs. What this guide covers: Installing dependencies and loading EmbeddingGemma 2 Generating text embeddings , computing semantic similarity, and applying task-specific prompts Building downstream applications (RAG and zero-shot classification) Optimizing storage and inference speed with Matryoshka Representation Learning (MRL) Looking for image, audio, or video embeddings? Check out Multimodal Embeddings with EmbeddingGemma 2 guide. Setup and Installation¶ Install sentence-transformers and transformers. Sentence Transformers is a Python framework for using and training embedding and reranker models. For more details on the framework, see the Sentence Transformers documentation. pip install -U sentence-transformers transformers pillow soundfile torchcodec Model Initialization¶ Instantiate EmbeddingGemma 2 directly using the SentenceTransformer class. from sentence_transformers import SentenceTransformer model_id = "google/embeddinggemma-2" model = SentenceTransformer(model_id) print(f"device: {model.device}") print(f"dtype: {model.dtype}") print(model) print("Total number of parameters in the model:", sum(p.numel() for p in model.parameters())) Loading weights: 0%| | 0/1376 [00:00<?, ?it/s] device: cuda:0 dtype: torch.bfloat16 SentenceTransformer( (0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'image': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'audio': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'video': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'message': {'method': 'forward', 'method_output_name': 'last_hidden_state', 'format': 'structured'} }, 'module_output_name': 'token_embeddings', 'architecture': 'EmbeddingGemma2Model'}) (1): Pooling({'embedding_dimension': 768, 'pooling_mode': 'mean', 'include_prompt': True}) (2): Normalize({'module_input_name': 'sentence_embedding', 'module_output_name': 'sentence_embedding'}) ) Total number of parameters in the model: 744371488 Text-Only Memory Optimization By default, SentenceTransformer loads all modality encoders (740M parameters). If your workflow only uses text, you can pass config_kwargs={"vision_config": None, "audio_config": None} to skip loading the vision and audio encoders (270M parameters). Note on Precision EmbeddingGemma 2 activations are incompatible with float16. Use bfloat16 (default on supported GPUs) or float32. Text Embeddings and Task Prompts¶ Learn how to encode text into dense vector representations, measure semantic similarity between inputs, and apply task-specific prompt prefixes to optimize embedding quality. Generating Text Embeddings¶ An embedding is a dense numerical vector that captures the semantic meaning of an input. Let's encode three words---["king", "queen", "car"]---to inspect their 768-dimensional representations. words = ["king", "queen", "car"] # Generate embeddings using model.encode() embeddings = model.encode(words) print(embeddings) for idx, embedding in enumerate(embeddings): print(f"Embedding {idx+1} (shape): {embedding.shape}") [[ 0.03222656 0.00285339 0.02160645 ... 0.012146 0.03149414 -0.0067749 ] [ 0.00787354 0.01361084 0.02502441 ... -0.01269531 0.02612305 0.01361084] [-0.04052734 -0.00860596 0.04492188 ... 0.00964355 -0.01501465 -0.00726318]] Embedding 1 (shape): (768,) Embedding 2 (shape): (768,) Embedding 3 (shape): (768,) The key property of embeddings is the distance between vectors in semantic space . Because "king" and "queen" share semantic characteristics as royal titles, their vectors are positioned close together, whereas "car" lies further away. Determining Semantic Similarity¶ We can quantify how semantically similar two inputs are by computing the cosine similarity between their embeddings using model.similarity(). Below are three sentence pairs demonstrating high, medium, and low semantic similarity: High Similarity: Sentence A: "The chef prepared a delicious meal for the guests." Sentence B: "A tasty dinner was cooked by the chef for the visitors." Reasoning: Both sentences describe the exact same event using active vs. passive voice. Medium Similarity: Sentence A: "She is an expert in machine learning." Sentence B: "He has a deep interest in artificial intelligence." Reasoning: Related domains (ML is a subfield of AI), but different subjects and levels of expertise. Low Similarity: Sentence A: "The weather in Tokyo is sunny today." Sentence B: "I need to buy groceries for the week." Reasoning: Completely unrelated topics with no semantic overlap. sentence_high = [ "The chef prepared a delicious meal for the guests.", "A tasty dinner was cooked by the chef for the visitors.", ] sentence_medium = [ "She is an expert in machine learning.", "He has a deep interest in artificial intelligence.", ] sentence_low = [ "The weather in Tokyo is sunny today.", "I need to buy groceries for the week.", ] for pair in [sentence_high, sentence_medium, sentence_low]: print("🙋‍♂️", pair) pair_embeddings = model.encode(pair) score = model.similarity(pair_embeddings[0], pair_embeddings[1]).item() print(f" `-> 🤖 similarity score: {score:.4f}") 🙋‍♂️ ['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.'] `-> 🤖 similarity score: 0.9184 🙋‍♂️ ['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.'] `-> 🤖 similarity score: 0.7835 🙋‍♂️ ['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.'] `-> 🤖 similarity score: 0.6880 Note on interpreting scores Cosine similarity values for text embeddings tend to skew higher than human intuition might suggest, often rarely dropping below 0.5 in practice. For instance, even completely unrelated sentences (like the "Low Similarity" example above) can yield a similarity score of roughly 0.6880. Keep this higher baseline in mind when evaluating semantic overlap. Optimizing Embeddings with Task Prompts¶ To achieve optimal performance with EmbeddingGemma 2 on text tasks, prepend an instructional prompt (task prefix) to your input. Task prompts condition the model for specific objectives (e.g. sentence similarity, asymmetric search retrieval, or classification) and help separate queries from documents. Prefix Notation & Usage We offer two types of task prefixes, depending on how embeddings are used in the task. There are two types of tasks: Asymmetric Tasks (e.g. retrieval): Use a query prefix for queries and a document prefix for corpus items. Symmetric Tasks (e.g. classification, similarity): Apply the same task prefix to all inputs being compared. Use Case Task Type Query Task Instruction Document Task Instruction (use none if no title) Web / document search Asymmetric task: search result | query: {query} title: {title} | text: {content} Question answering Asymmetric task: question answering | query: {question} title: {title} | text: {passage} Fact checking Asymmetric task: fact checking | query: {claim} title: {title} | text: {evidence} Code search Asymmetric task: code retrieval | query: {query} title: {title or filename} | text: {code} Text classification Symmetric task: classification | query: {content} N/A Clustering Symmetric task: clustering | query: {content} N/A Measuring similarity Symmetric task: sentence similarity | query: {content} N/A Please note: Prefixes are used on text inputs only; when encoding images, video, or audio, pass them directly. You can apply prompts during inference in three ways: Using prompt_name (Recommended): Select a built-in task prompt registered in model.prompts: embeddings = model.encode(sentences, prompt_name="STS") Using prompt: Pass a custom prefix string directly to model.encode(): embeddings = model.encode(sentences, prompt="task: sentence similarity | query: ") Using the Default Prompt: If default_prompt_name is configured on the model, calling model.encode(sentences) applies it automatically. Let's inspect all built-in task prompts and re-evaluate our sentence similarity pairs using prompt_name="STS": print("Available task prompts:") for name, prefix in model.prompts.items(): print(f" {name}: {prefix!r}") print("-" * 80) for pair in [sentence_high, sentence_medium, sentence_low]: print("🙋‍♂️", pair) pair_embeddings = model.encode(pair, prompt_name="STS") score = model.similarity(pair_embeddings[0], pair_embeddings[1]).item() print(f" `-> 🤖 STS score: {score:.4f}") Available task prompts: query: 'task: search result | query: ' document: 'title: none | text: ' BitextMining: 'task: search result | query: ' Classification: 'task: classification | query: ' Clustering: 'task: clustering | query: ' CodeRetrieval: 'task: code retrieval | query: ' Document: 'title: none | text: ' FactChecking: 'task: fact checking | query: ' InstructionRetrieval: 'task: code retrieval | query: ' MultilabelClassification: 'task: classification | query: ' PairClassification: 'task: sentence similarity | query: ' QuestionAnswering: 'task: question answering | query: ' Reranking: 'task: search result | query: ' Retrieval: 'task: search result | query: ' Retrieval-document: 'title: none | text: ' Retrieval-query: 'task: search result | query: ' STS: 'task: sentence similarity | query: ' SearchQuery: 'task: search result | query: ' SentenceSimilarity: 'task: sentence similarity | query: ' Summarization: 'task: sentence similarity