File size: 28,794 Bytes
dcdf545 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
{
"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": [
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://ai.google.dev/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers\"><img src=\"https://ai.google.dev/static/site-assets/images/docs/notebook-site-button.png\" height=\"32\" width=\"32\" />View on ai.google.dev</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb\"\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://www.kaggle.com/static/images/logos/kaggle-logo-transparent-300.png\" height=\"32\" width=\"70\"/>Run in Kaggle</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/google/generative-ai-docs/main/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://ai.google.dev/images/cloud-icon.svg\" width=\"40\" />Open in Vertex AI</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
" </td>\n",
"</table>"
]
},
{
"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**<br>\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**<br>\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**<br>\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\"`.<br>\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:<br>\n",
" * **With a title:**<br>\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:**<br>\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
}
|