{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "-u7xRR3DeFXz" }, "source": [ "##### Copyright 2025 Google LLC." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "oed1Dh9SeIlD" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "UpJl85mfqdUB" }, "source": [ "\n", " \n", " \n", " \n", " \n", " \n", "
\n", " View on ai.google.dev\n", " \n", " Run in Google Colab\n", " \n", " Run in Kaggle\n", " \n", " Open in Vertex AI\n", " \n", " View source on GitHub\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "Sq3lJyEiqqD-" }, "source": [ "# Generate Embeddings with Sentence Transformers\n", "\n", "EmbeddingGemma is a lightweight, open embedding model designed for fast, high-quality retrieval on everyday devices like mobile phones. At only 308 million parameters, it's efficient enough to run advanced AI techniques, such as Retrieval Augmented Generation (RAG), directly on your local machine with no internet connection required.\n", "\n", "## Setup\n", "\n", "Before starting this tutorial, complete the following steps:\n", "\n", "* Get access to Gemma by logging into [Hugging Face](https://huggingface.co/google/embeddinggemma-300M) and selecting **Acknowledge license** for a Gemma model.\n", "* Generate a Hugging Face [Access Token](https://huggingface.co/docs/hub/en/security-tokens#how-to-manage-user-access-token) and use it to login from Colab.\n", "\n", "This notebook will run on either CPU or GPU." ] }, { "cell_type": "markdown", "metadata": { "id": "R3TOEqprq-X3" }, "source": [ "### Install Python packages\n", "\n", "Install the libraries required for running the EmbeddingGemma model and generating embeddings. Sentence Transformers is a Python framework for text and image embeddings. For more information, see the [Sentence Transformers](https://www.sbert.net/) documentation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jZFuhT3nrHEK" }, "outputs": [], "source": [ "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview" ] }, { "cell_type": "markdown", "metadata": { "id": "O3ttIyfSA0Lj" }, "source": [ "After you have accepted the license, you need a valid Hugging Face Token to access the model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "WXK1Ev1Sq2iY" }, "outputs": [], "source": [ "# Login into Hugging Face Hub\n", "from huggingface_hub import login\n", "login()" ] }, { "cell_type": "markdown", "metadata": { "id": "NUydcaDBrXDi" }, "source": [ "### Load Model\n", "\n", "Use the `sentence-transformers` libraries to create an instance of a model class with EmbeddingGemma." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mkpmqlU_rcOd", "outputId": "f8458e59-9a6e-4a89-af83-ffdf391c323a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Device: cuda:0\n", "SentenceTransformer(\n", " (0): Transformer({'max_seq_length': 2048, 'do_lower_case': False, 'architecture': 'Gemma3TextModel'})\n", " (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})\n", " (2): Dense({'in_features': 768, 'out_features': 3072, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n", " (3): Dense({'in_features': 3072, 'out_features': 768, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n", " (4): Normalize()\n", ")\n", "Total number of parameters in the model: 307581696\n" ] } ], "source": [ "import torch\n", "from sentence_transformers import SentenceTransformer\n", "\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "\n", "model_id = \"google/embeddinggemma-300M\"\n", "model = SentenceTransformer(model_id).to(device=device)\n", "\n", "print(f\"Device: {model.device}\")\n", "print(model)\n", "print(\"Total number of parameters in the model:\", sum([p.numel() for _, p in model.named_parameters()]))" ] }, { "cell_type": "markdown", "metadata": { "id": "JxrZ8na0A7Hv" }, "source": [ "## Generating Embedding\n", "\n", "An embedding is a numerical representation of text, like a word or sentence, that captures its semantic meaning. Essentially, it's a list of numbers (a vector) that allows computers to understand the relationships and context of words.\n", "\n", "Let's see how EmbeddingGemma would process three different words `[\"apple\", \"banana\", \"car\"]`.\n", "\n", "EmbeddingGemma has been trained on vast amounts of text and has learned the relationships between words and concepts." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "o0UK8UVAA9b7", "outputId": "37c91847-57de-4a47-9c1a-0adffacd1867" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.18476306 0.00167681 0.03773484 ... -0.07996225 -0.02348064\n", " 0.00976741]\n", " [-0.21189538 -0.02657359 0.02513712 ... -0.08042689 -0.01999852\n", " 0.00512146]\n", " [-0.18924113 -0.02551468 0.04486253 ... -0.06377774 -0.03699806\n", " 0.03973572]]\n", "Embedding 1: (768,)\n", "Embedding 2: (768,)\n", "Embedding 3: (768,)\n" ] } ], "source": [ "words = [\"apple\", \"banana\", \"car\"]\n", "\n", "# Calculate embeddings by calling model.encode()\n", "embeddings = model.encode(words)\n", "\n", "print(embeddings)\n", "for idx, embedding in enumerate(embeddings):\n", " print(f\"Embedding {idx+1} (shape): {embedding.shape}\")" ] }, { "cell_type": "markdown", "metadata": { "id": "inuWOAuMBAR7" }, "source": [ "The model outpus a numerical vector for each sentence. The actual vectors are very long (768), but for simplicity, those are presented with a few dimensions.\n", "\n", "The key isn't the individual numbers themselves, but **the distance between the vectors**. If we were to plot these vectors in a multi-dimensional space, The vectors for `apple` and `banana` would be very close to each other. And the vector for `car` would be far away from the other two." ] }, { "cell_type": "markdown", "metadata": { "id": "2oCpMMJUr4RT" }, "source": [ "## Determining Similarity\n", "\n", "In this section, we use embeddings to determine how sementically similar different sentences are. Here we show examples with high, medieum, and low similarity scores.\n", "\n", "- High Similarity:\n", " - Sentence A: \"The chef prepared a delicious meal for the guests.\"\n", " - Sentence B: \"A tasty dinner was cooked by the chef for the visitors.\"\n", " - Reasoning: Both sentences describe the same event using different words and grammatical structures (active vs. passive voice). They convey the same core meaning.\n", "\n", "- Medium Similarity:\n", " - Sentence A: \"She is an expert in machine learning.\"\n", " - Sentence B: \"He has a deep interest in artificial intelligence.\"\n", " - Reasoning: The sentences are related as machine learning is a subfield of artificial intelligence. However, they talk about different people with different levels of engagement (expert vs. interest).\n", "\n", "- Low Similarity:\n", " - Sentence A: \"The weather in Tokyo is sunny today.\"\n", " - Sentence B: \"I need to buy groceries for the week.\"\n", " - Reasoning: The two sentences are on completely unrelated topics and share no semantic overlap." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "VeTEvnTyslyq", "outputId": "b387529f-aad8-4150-e4f1-daef4f30cfc0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🙋‍♂️\n", "['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']\n", "`-> 🤖 score: 0.8002148\n", "🙋‍♂️\n", "['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']\n", "`-> 🤖 score: 0.45417833\n", "🙋‍♂️\n", "['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']\n", "`-> 🤖 score: 0.22262995\n" ] } ], "source": [ "# The sentences to encode\n", "sentence_high = [\n", " \"The chef prepared a delicious meal for the guests.\",\n", " \"A tasty dinner was cooked by the chef for the visitors.\"\n", "]\n", "sentence_medium = [\n", " \"She is an expert in machine learning.\",\n", " \"He has a deep interest in artificial intelligence.\"\n", "]\n", "sentence_low = [\n", " \"The weather in Tokyo is sunny today.\",\n", " \"I need to buy groceries for the week.\"\n", "]\n", "\n", "for sentence in [sentence_high, sentence_medium, sentence_low]:\n", " print(\"🙋‍♂️\")\n", " print(sentence)\n", " embeddings = model.encode(sentence)\n", " similarities = model.similarity(embeddings[0], embeddings[1])\n", " print(\"`-> 🤖 score: \", similarities.numpy()[0][0])" ] }, { "cell_type": "markdown", "metadata": { "id": "obfUiizULZE0" }, "source": [ "### Using Prompts with EmbeddingGemma\n", "\n", "To generate the best embeddings with EmbeddingGemma, you should add an \"instructional prompt\" or \"task\" to the beginning of your input text. These prompts optimize the embeddings for specific tasks, such as document retrieval or question answering, and help the model distinguish between different input types, like a search query versus a document.\n", "\n", "#### How to Apply Prompts\n", "\n", "You can apply a prompt during inference in three ways.\n", "\n", "1. **Using the `prompt` argument**
\n", " Pass the full prompt string directly to the `encode` method. This gives you precise control.\n", " ```python\n", " embeddings = model.encode(\n", " sentence,\n", " prompt=\"task: sentence similarity | query: \"\n", " )\n", " ```\n", "2. **Using the `prompt_name` argument**
\n", " Select a predefined prompt by its name. These prompts are loaded from the model's configuration or during its initialization.\n", " ```python\n", " embeddings = model.encode(sentence, prompt_name=\"STS\")\n", " ```\n", "3. **Using the Default Prompt**
\n", " If you don't specify either `prompt` or `prompt_name`, the system will automatically use the prompt set as `default_prompt_name`, if no default is set, then no prompt is applied.\n", " ```python\n", " embeddings = model.encode(sentence)\n", " ```\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0p3qe3WDJV-I", "outputId": "5fa2638e-e67b-479b-fba4-ca89a22cd10e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available tasks:\n", " query: \"task: search result | query: \"\n", " document: \"title: none | text: \"\n", " BitextMining: \"task: search result | query: \"\n", " Clustering: \"task: clustering | query: \"\n", " Classification: \"task: classification | query: \"\n", " InstructionRetrieval: \"task: code retrieval | query: \"\n", " MultilabelClassification: \"task: classification | query: \"\n", " PairClassification: \"task: sentence similarity | query: \"\n", " Reranking: \"task: search result | query: \"\n", " Retrieval: \"task: search result | query: \"\n", " Retrieval-query: \"task: search result | query: \"\n", " Retrieval-document: \"title: none | text: \"\n", " STS: \"task: sentence similarity | query: \"\n", " Summarization: \"task: summarization | query: \"\n", "--------------------------------------------------------------------------------\n", "🙋‍♂️\n", "['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']\n", "`-> 🤖 score: 0.9363755\n", "🙋‍♂️\n", "['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']\n", "`-> 🤖 score: 0.6425841\n", "🙋‍♂️\n", "['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']\n", "`-> 🤖 score: 0.38587403\n" ] } ], "source": [ "print(\"Available tasks:\")\n", "for name, prefix in model.prompts.items():\n", " print(f\" {name}: \\\"{prefix}\\\"\")\n", "print(\"-\"*80)\n", "\n", "for sentence in [sentence_high, sentence_medium, sentence_low]:\n", " print(\"🙋‍♂️\")\n", " print(sentence)\n", " embeddings = model.encode(sentence, prompt_name=\"STS\")\n", " similarities = model.similarity(embeddings[0], embeddings[1])\n", " print(\"`-> 🤖 score: \", similarities.numpy()[0][0])\n" ] }, { "cell_type": "markdown", "metadata": { "id": "2YAqPXDctw2w" }, "source": [ "#### Use Case: Retrieval-Augmented Generation (RAG)\n", "\n", "For RAG systems, use the following `prompt_name` values to create specialized embeddings for your queries and documents:\n", "\n", "* **For Queries:** Use `prompt_name=\"Retrieval-query\"`.
\n", " ```python\n", " query_embedding = model.encode(\n", " \"How do I use prompts with this model?\",\n", " prompt_name=\"Retrieval-query\"\n", " )\n", " ```\n", "\n", "* **For Documents:** Use `prompt_name=\"Retrieval-document\"`. To further improve document embeddings, you can also include a title by using the `prompt` argument directly:
\n", " * **With a title:**
\n", " ```python\n", " doc_embedding = model.encode(\n", " \"The document text...\",\n", " prompt=\"title: Using Prompts in RAG | text: \"\n", " )\n", " ```\n", " * **Without a title:**
\n", " ```python\n", " doc_embedding = model.encode(\n", " \"The document text...\",\n", " prompt=\"title: none | text: \"\n", " )\n", " ```\n", "\n", "#### Further Reading\n", "\n", "* For details on all available EmbeddingGemma prompts, see the [model card](http://ai.google.dev/gemma/docs/embeddinggemma/model_card#prompt_instructions).\n", "* For general information on prompt templates, see the [Sentence Transformer documentation](https://sbert.net/examples/sentence_transformer/applications/computing-embeddings/README.html#prompt-templates).\n", "* For a demo of RAG, see the [Simple RAG example](https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/%5BGemma_3%5DRAG_with_EmbeddingGemma.ipynb) in the Gemma Cookbook.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "aQh-QFAPsswb" }, "source": [ "## Classification\n", "\n", "Classification is the task of assigning a piece of text to one or more predefined categories or labels. It's one of the most fundamental tasks in Natural Language Processing (NLP).\n", "\n", "A practical application of text classification is customer support ticket routing. This process automatically directs customer queries to the correct department, saving time and reducing manual work." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "C2Ufawl-tXvr", "outputId": "347bd68c-dfee-470d-eef7-e3af5d096e91" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[0.4673, 0.5145, 0.3604],\n", " [0.4191, 0.5010, 0.5966]])\n", "tensor([1, 2])\n", "🙋‍♂️ Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password. -> 🤖 Technical Support\n", "🙋‍♂️ I would like to inquire about your enterprise plan pricing and features for a team of 50 people. -> 🤖 Sales Inquiry\n" ] } ], "source": [ "labels = [\"Billing Issue\", \"Technical Support\", \"Sales Inquiry\"]\n", "\n", "sentence = [\n", " \"Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password.\",\n", " \"I would like to inquire about your enterprise plan pricing and features for a team of 50 people.\",\n", "]\n", "\n", "# Calculate embeddings by calling model.encode()\n", "label_embeddings = model.encode(labels, prompt_name=\"Classification\")\n", "embeddings = model.encode(sentence, prompt_name=\"Classification\")\n", "\n", "# Calculate the embedding similarities\n", "similarities = model.similarity(embeddings, label_embeddings)\n", "print(similarities)\n", "\n", "idx = similarities.argmax(1)\n", "print(idx)\n", "\n", "for example in sentence:\n", " print(\"🙋‍♂️\", example, \"-> 🤖\", labels[idx[sentence.index(example)]])" ] }, { "cell_type": "markdown", "metadata": { "id": "IRUU2EIDPSmW" }, "source": [ "## Matryoshka Representation Learning (MRL)\n", "\n", "EmbeddingGemma leverages MRL to provide multiple embedding sizes from one model. It's a clever training method that creates a single, high-quality embedding where the most important information is concentrated at the beginning of the vector.\n", "\n", "This means you can get a smaller but still very useful embedding by simply taking the first `N` dimensions of the full embedding. Using smaller, truncated embeddings is significantly cheaper to store and faster to process, but this efficiency comes at the cost of potential lower quality of embeddings. MRL gives you the power to choose the optimal balance between this speed and accuracy for your application's specific needs.\n", "\n", "Let's use three words `[\"apple\", \"banana\", \"car\"]` and create simplified embeddings to see how MRL works." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "B1q1F9I5PYSq", "outputId": "a5b28e04-4783-4d79-ae82-3fac7e554a7a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "similarity function: cosine\n", "tensor([[0.7510, 0.6685]])\n", "🙋‍♂️ apple vs. banana -> 🤖 score: 0.75102395\n", "🙋‍♂️ apple vs. car -> 🤖 score: 0.6684626\n" ] } ], "source": [ "def check_word_similarities():\n", " # Calculate the embedding similarities\n", " print(\"similarity function: \", model.similarity_fn_name)\n", " similarities = model.similarity(embeddings[0], embeddings[1:])\n", " print(similarities)\n", "\n", " for idx, word in enumerate(words[1:]):\n", " print(\"🙋‍♂️ apple vs.\", word, \"-> 🤖 score: \", similarities.numpy()[0][idx])\n", "\n", "# Calculate embeddings by calling model.encode()\n", "embeddings = model.encode(words, prompt_name=\"STS\")\n", "\n", "check_word_similarities()" ] }, { "cell_type": "markdown", "metadata": { "id": "_iv1xG0TPxkm" }, "source": [ "Now, for a faster application, you don't need a new model. Simply **truncate** the full embeddings to the first **512 dimensions**. For optimal results, it is also recommended to set `normalize_embeddings=True`, which scales the vectors to a unit length of 1." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9Ue4aWh8PzdL", "outputId": "176dabd4-9d9c-4ce9-c7e5-472ba47ed55f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Embedding 1: (512,)\n", "Embedding 2: (512,)\n", "Embedding 3: (512,)\n", "--------------------------------------------------------------------------------\n", "similarity function: cosine\n", "tensor([[0.7674, 0.7041]])\n", "🙋‍♂️ apple vs. banana -> 🤖 score: 0.767427\n", "🙋‍♂️ apple vs. car -> 🤖 score: 0.7040509\n" ] } ], "source": [ "embeddings = model.encode(words, truncate_dim=512, normalize_embeddings=True)\n", "\n", "for idx, embedding in enumerate(embeddings):\n", " print(f\"Embedding {idx+1}: {embedding.shape}\")\n", "\n", "print(\"-\"*80)\n", "check_word_similarities()" ] }, { "cell_type": "markdown", "metadata": { "id": "lgkmgzfVP24M" }, "source": [ "In extremely constrained environments, you can further shorten the embeddings to just **256 dimensions**. You can also use the more efficient **dot-product** for similarity calculations instead of the standard **cosine** similarity." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Gi4NlPv-P4RS", "outputId": "656d8d6a-1e79-41be-f17a-cab136bf27ea" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Embedding 1: (256,)\n", "Embedding 2: (256,)\n", "Embedding 3: (256,)\n", "--------------------------------------------------------------------------------\n", "similarity function: dot\n", "tensor([[0.7855, 0.7382]])\n", "🙋‍♂️ apple vs. banana -> 🤖 score: 0.7854644\n", "🙋‍♂️ apple vs. car -> 🤖 score: 0.7382126\n" ] } ], "source": [ "model = SentenceTransformer(model_id, truncate_dim=256, similarity_fn_name=\"dot\").to(device=device)\n", "embeddings = model.encode(words, prompt_name=\"STS\", normalize_embeddings=True)\n", "\n", "for idx, embedding in enumerate(embeddings):\n", " print(f\"Embedding {idx+1}: {embedding.shape}\")\n", "\n", "print(\"-\"*80)\n", "check_word_similarities()" ] }, { "cell_type": "markdown", "metadata": { "id": "RYr9uSI_t3fm" }, "source": [ "## Summary and next steps\n", "\n", "You are now equipped to generate high-quality text embeddings using EmbeddingGemma and the Sentence Transformers library. Apply these skills to build powerful features like semantic similarity, text classification, and Retrieval-Augmented Generation (RAG) systems, and continue exploring what's possible with Gemma models.\n", "\n", "Check out the following docs next:\n", "\n", "* [Fine-tune EmbeddingGemma](https://ai.google.dev/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers)\n", "* [Simple RAG example](https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/%5BGemma_3%5DRAG_with_EmbeddingGemma.ipynb) in the Gemma Cookbook\n" ] } ], "metadata": { "colab": { "name": "inference-embeddinggemma-with-sentence-transformers.ipynb", "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }