From fd86bda126af84e41d0fa8b38e0700cdd9fdc901 Mon Sep 17 00:00:00 2001 From: Juyeong Ji Date: Thu, 4 Sep 2025 18:39:44 +0900 Subject: [PATCH 1/2] add notebook --- ...dinggemma-with-sentence-transformers.ipynb | 513 ++++++++++++++ ...dinggemma-with-sentence-transformers.ipynb | 647 ++++++++++++++++++ 2 files changed, 1160 insertions(+) create mode 100644 site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb create mode 100644 site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb diff --git a/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb b/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb new file mode 100644 index 000000000..657e6c053 --- /dev/null +++ b/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb @@ -0,0 +1,513 @@ +{ + "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": "DzkEdu7YxUOM" + }, + "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": "Txf-DZy2yCJ5" + }, + "source": [ + "# Fine-tune EmbeddingGemma\n", + "\n", + "Fine-tuning helps close the gap between a model's general-purpose understanding and the specialized, high-performance accuracy that your application requires. Since no single model is perfect for every task, fine-tuning adapts it to your specific domain.\n", + "\n", + "Imagine your company, \"Shibuya Financial\" offers various complex financial products like investment trusts, NISA accounts (a tax-advantaged savings account), and home loans. Your customer support team uses an internal knowledge base to quickly find answers to customer questions.\n", + "\n", + "## Setup\n", + "\n", + "Before starting this tutorial, complete the following steps:\n", + "\n", + "* Get access to EmbeddingGemma 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": "rZdmGmJq0NJX" + }, + "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": "zhVtxMWG0TP7" + }, + "outputs": [], + "source": [ + "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma" + ] + }, + { + "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": "Ev43EyYQ0Gj8" + }, + "outputs": [], + "source": [ + "# Login into Hugging Face Hub\n", + "from huggingface_hub import login\n", + "login()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XyzbOscl0ack" + }, + "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": "E6w85SW70gph" + }, + "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": "WJA4tSu-0s4Y" + }, + "source": [ + "## Prepare the Fine-Tuning Dataset\n", + "\n", + "This is the most crucial part. You need to create a dataset that teaches the model what \"similar\" means in your specific context. This data is often structured as triplets: (anchor, positive, negative)\n", + "\n", + "- Anchor: The original query or sentence.\n", + "- Positive: A sentence that is semantically very similar or identical to the anchor.\n", + "- Negative: A sentence that is on a related topic but semantically distinct.\n", + "\n", + "In this example, we only prepared 3 triplets, but for a real application, you would need a much larger dataset to perform well." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "CIkQ7fyR0vSR" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dataset({\n", + " features: ['anchor', 'positive', 'negative'],\n", + " num_rows: 3\n", + "})\n" + ] + } + ], + "source": [ + "from datasets import Dataset\n", + "\n", + "dataset = [\n", + " [\"How do I open a NISA account?\", \"What is the procedure for starting a new tax-free investment account?\", \"I want to check the balance of my regular savings account.\"],\n", + " [\"Are there fees for making an early repayment on a home loan?\", \"If I pay back my house loan early, will there be any costs?\", \"What is the management fee for this investment trust?\"],\n", + " [\"What is the coverage for medical insurance?\", \"Tell me about the benefits of the health insurance plan.\", \"What is the cancellation policy for my life insurance?\"],\n", + "]\n", + "\n", + "# Convert the list-based dataset into a list of dictionaries.\n", + "data_as_dicts = [ {\"anchor\": row[0], \"positive\": row[1], \"negative\": row[2]} for row in dataset ]\n", + "\n", + "# Create a Hugging Face `Dataset` object from the list of dictionaries.\n", + "train_dataset = Dataset.from_list(data_as_dicts)\n", + "print(train_dataset)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "31jCsHUy0zwP" + }, + "source": [ + "## Before Fine-Tuning\n", + "\n", + "A search for \"tax-free investment\" might have given the following results, with similarity scores:\n", + "\n", + "1. Document: Opening a NISA account (Score: 0.45)\n", + "2. Document: Opening a Regular Saving Account (Score: 0.48) <- *Similar score, potentially confusing*\n", + "3. Document: Home Loan Application Guide (Score: 0.42)\n", + "\n", + "> Note: To generate optimal embeddings with EmbeddingGemma, you should add an \"instructional prompt\" or \"task\" to the beginning of your input text. You will use `STS` for sentence similarity. For details on all available EmbeddingGemma prompts, see the [model card](http://ai.google.dev/gemma/docs/embeddinggemma/model_card#prompt_instructions)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "eM06urFi1Br_" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Document: Opening a NISA Account -> 🤖 Score: 0.45698774\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.48092696\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.42127067\n" + ] + } + ], + "source": [ + "task_name = \"STS\"\n", + "\n", + "def get_scores(query, documents):\n", + " # Calculate embeddings by calling model.encode()\n", + " query_embeddings = model.encode(query, prompt=task_name)\n", + " doc_embeddings = model.encode(documents, prompt=task_name)\n", + "\n", + " # Calculate the embedding similarities\n", + " similarities = model.similarity(query_embeddings, doc_embeddings)\n", + "\n", + " for idx, doc in enumerate(documents):\n", + " print(\"Document: \", doc, \"-> 🤖 Score: \", similarities.numpy()[0][idx])\n", + "\n", + "query = \"I want to start a tax-free installment investment, what should I do?\"\n", + "documents = [\"Opening a NISA Account\", \"Opening a Regular Savings Account\", \"Home Loan Application Guide\"]\n", + "\n", + "get_scores(query, documents)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "LfzasM-41Yb3" + }, + "source": [ + "## Training\n", + "\n", + "Using a framework like `sentence-transformers` in Python, the base model gradually learns the subtle distinctions in your financial vocabulary." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "8OX8XPUL1d2V" + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
StepTraining Loss
30.048300
60.000000
90.000000
120.000000
150.000000

" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Step 3 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.6449194\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.44123\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.46752414\n", + "Step 6 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.68873787\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.34069622\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.50065553\n", + "Step 9 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.7148906\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.30480516\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.52454984\n", + "Step 12 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.72614634\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.29255486\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.5370023\n", + "Step 15 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.7294032\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.54087913\n", + "Step 15 finished. Running evaluation:\n", + "Document: Opening a NISA Account -> 🤖 Score: 0.7294032\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.54087913\n" + ] + }, + { + "data": { + "text/plain": [ + "TrainOutput(global_step=15, training_loss=0.009651281436261646, metrics={'train_runtime': 63.2486, 'train_samples_per_second': 0.237, 'train_steps_per_second': 0.237, 'total_flos': 0.0, 'train_loss': 0.009651281436261646, 'epoch': 5.0})" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from sentence_transformers import SentenceTransformerTrainer, SentenceTransformerTrainingArguments\n", + "from sentence_transformers.losses import MultipleNegativesRankingLoss\n", + "from transformers import TrainerCallback\n", + "\n", + "loss = MultipleNegativesRankingLoss(model)\n", + "\n", + "args = SentenceTransformerTrainingArguments(\n", + " # Required parameter:\n", + " output_dir=\"my-embedding-gemma\",\n", + " # Optional training parameters:\n", + " prompts=model.prompts[task_name], # use model's prompt to train\n", + " num_train_epochs=5,\n", + " per_device_train_batch_size=1,\n", + " learning_rate=2e-5,\n", + " warmup_ratio=0.1,\n", + " # Optional tracking/debugging parameters:\n", + " logging_steps=train_dataset.num_rows,\n", + " report_to=\"none\",\n", + ")\n", + "\n", + "class MyCallback(TrainerCallback):\n", + " \"A callback that evaluates the model at the end of eopch\"\n", + " def __init__(self, evaluate):\n", + " self.evaluate = evaluate # evaluate function\n", + "\n", + " def on_log(self, args, state, control, **kwargs):\n", + " # Evaluate the model using text generation\n", + " print(f\"Step {state.global_step} finished. Running evaluation:\")\n", + " self.evaluate()\n", + "\n", + "def evaluate():\n", + " get_scores(query, documents)\n", + "\n", + "trainer = SentenceTransformerTrainer(\n", + " model=model,\n", + " args=args,\n", + " train_dataset=train_dataset,\n", + " loss=loss,\n", + " callbacks=[MyCallback(evaluate)]\n", + ")\n", + "trainer.train()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8rcmxOME1kCg" + }, + "source": [ + "## After Fine-Tuning\n", + "\n", + "The same search now yields much clearer results:\n", + "\n", + "1. Document: Opening a NISA account (Score: 0.72) <- *Much more confident*\n", + "2. Document: Opening a Regular Saving Account (Score: 0.28) <- *Clearly less relevant*\n", + "3. Document: Home Loan Application Guide (Score: 0.54)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Zdt-ve0x1mD3" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Document: Opening a NISA Account -> 🤖 Score: 0.7294032\n", + "Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038\n", + "Document: Home Loan Application Guide -> 🤖 Score: 0.54087913\n" + ] + } + ], + "source": [ + "get_scores(query, documents)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "x0bSI_PUQBw7" + }, + "source": [ + "To upload your model to the Hugging Face Hub, you can use the `push_to_hub` method from the Sentence Transformers library.\n", + "\n", + "Uploading your model makes it easy to access for inference directly from the Hub, share with others, and version your work. Once uploaded, anyone can load your model with a single line of code, simply by referencing its unique model ID `/my-embedding-gemma`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "4wioFS7oQP6I" + }, + "outputs": [], + "source": [ + "# Push to Hub\n", + "model.push_to_hub(\"my-embedding-gemma\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Y8te9XtU1r3m" + }, + "source": [ + "## Summary and next steps\n", + "\n", + "You have now learned how to adapt an EmbeddingGemma model for a specific domain by fine-tuning it with the Sentence Transformers library.\n", + "\n", + "Explore what more you can do with EmbeddingGemma:\n", + "\n", + "* [Training Overview](https://sbert.net/docs/sentence_transformer/training_overview.html) in Sentence Transformers Documentation\n", + "* [Generate embeddings with Sentence Transformers](https://ai.google.dev/gemma/docs/embeddinggemma/inference-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": "fine-tuning-embeddinggemma-with-sentence-transformers.ipynb", + "toc_visible": true + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb b/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb new file mode 100644 index 000000000..4696734e5 --- /dev/null +++ b/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb @@ -0,0 +1,647 @@ +{ + "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" + ] + }, + { + "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" + }, + "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" + }, + "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" + }, + "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": 34, + "metadata": { + "id": "0p3qe3WDJV-I" + }, + "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" + }, + "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, still very useful embedding by simply taking the first `N` dimensions of the full embedding. Using smaller, truncated embedding 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" + }, + "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 **turncate** the full embeddings to the first **512 dimensions**. For optimal result, 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" + }, + "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 extreamly 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" + }, + "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", + "toc_visible": true + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} From 2c16c75501e08316f55e891ac886c22cb6f6db1e Mon Sep 17 00:00:00 2001 From: Juyeong Ji Date: Fri, 5 Sep 2025 00:14:43 +0900 Subject: [PATCH 2/2] new package url --- .../fine-tuning-embeddinggemma-with-sentence-transformers.ipynb | 2 +- .../inference-embeddinggemma-with-sentence-transformers.ipynb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb b/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb index 657e6c053..352d11d73 100644 --- a/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb +++ b/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb @@ -97,7 +97,7 @@ }, "outputs": [], "source": [ - "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma" + "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview" ] }, { diff --git a/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb b/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb index 4696734e5..48088fcb3 100644 --- a/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb +++ b/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb @@ -95,7 +95,7 @@ }, "outputs": [], "source": [ - "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma" + "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview" ] }, {