danielhanchen commited on
Commit
bfa3c84
·
verified ·
1 Parent(s): 34dbe9a

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +33 -16
  2. notebook.ipynb +656 -0
README.md CHANGED
@@ -7,8 +7,11 @@ tags:
7
  - sentence-similarity
8
  - feature-extraction
9
  - text-embeddings-inference
10
- base_model:
11
- - google/embeddinggemma-300M
 
 
 
12
  ---
13
 
14
  # EmbeddingGemma model card
@@ -33,6 +36,8 @@ EmbeddingGemma is a 300M parameter, state-of-the-art for its size, open embeddin
33
 
34
  The small size and on-device focus makes it possible to deploy in environments with limited resources such as mobile phones, laptops, or desktops, democratizing access to state of the art AI models and helping foster innovation for everyone.
35
 
 
 
36
  ### Inputs and outputs
37
 
38
  - **Input:**
@@ -43,6 +48,18 @@ The small size and on-device focus makes it possible to deploy in environments w
43
  - Numerical vector representations of input text data
44
  - Output embedding dimension size of 768, with smaller options available (512, 256, or 128) via Matryoshka Representation Learning (MRL). MRL allows users to truncate the output embedding of size 768 to their desired size and then re-normalize for efficient and accurate representation.
45
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  ### Usage
47
 
48
  These model weights are designed to be used with [Sentence Transformers](https://www.SBERT.net), using the [Gemma 3](https://huggingface.co/docs/transformers/main/en/model_doc/gemma3) implementation from [Hugging Face Transformers](https://huggingface.co/docs/transformers/en/index) as the backbone.
@@ -169,23 +186,23 @@ The model was evaluated against a large collection of different datasets and met
169
  </tr>
170
  <tr>
171
  <td>768d</td>
172
- <td>68.36</td>
173
- <td>64.15</td>
174
  </tr>
175
  <tr>
176
  <td>512d</td>
177
- <td>67.80</td>
178
- <td>63.59</td>
179
  </tr>
180
  <tr>
181
  <td>256d</td>
182
- <td>66.89</td>
183
- <td>62.94</td>
184
  </tr>
185
  <tr>
186
  <td>128d</td>
187
- <td>65.09</td>
188
- <td>61.56</td>
189
  </tr>
190
  </tbody>
191
  </table>
@@ -271,18 +288,18 @@ The model was evaluated against a large collection of different datasets and met
271
  </tr>
272
  <tr>
273
  <td>Q4_0 (768d)</td>
274
- <td>67.91</td>
275
- <td>63.64</td>
276
  </tr>
277
  <tr>
278
  <td>Q8_0 (768d)</td>
279
- <td>68.13</td>
280
- <td>63.85</td>
281
  </tr>
282
  <tr>
283
  <td>Mixed Precision* (768d)</td>
284
- <td>67.95</td>
285
- <td>63.83</td>
286
  </tr>
287
  </tbody>
288
  </table>
 
7
  - sentence-similarity
8
  - feature-extraction
9
  - text-embeddings-inference
10
+ extra_gated_heading: Access EmbeddingGemma on Hugging Face
11
+ extra_gated_prompt: To access EmbeddingGemma on Hugging Face, you’re required to review and
12
+ agree to Google’s usage license. To do this, please ensure you’re logged in to Hugging
13
+ Face and click below. Requests are processed immediately.
14
+ extra_gated_button_content: Acknowledge license
15
  ---
16
 
17
  # EmbeddingGemma model card
 
36
 
37
  The small size and on-device focus makes it possible to deploy in environments with limited resources such as mobile phones, laptops, or desktops, democratizing access to state of the art AI models and helping foster innovation for everyone.
38
 
39
+ For more technical details, refer to our paper: [EmbeddingGemma: Powerful and Lightweight Text Representations](https://arxiv.org/abs/2509.20354).
40
+
41
  ### Inputs and outputs
42
 
43
  - **Input:**
 
48
  - Numerical vector representations of input text data
49
  - Output embedding dimension size of 768, with smaller options available (512, 256, or 128) via Matryoshka Representation Learning (MRL). MRL allows users to truncate the output embedding of size 768 to their desired size and then re-normalize for efficient and accurate representation.
50
 
51
+ ### Citation
52
+
53
+ ```none
54
+ @article{embedding_gemma_2025,
55
+ title={EmbeddingGemma: Powerful and Lightweight Text Representations},
56
+ author={Schechter Vera, Henrique* and Dua, Sahil* and Zhang, Biao and Salz, Daniel and Mullins, Ryan and Raghuram Panyam, Sindhu and Smoot, Sara and Naim, Iftekhar and Zou, Joe and Chen, Feiyang and Cer, Daniel and Lisak, Alice and Choi, Min and Gonzalez, Lucas and Sanseviero, Omar and Cameron, Glenn and Ballantyne, Ian and Black, Kat and Chen, Kaifeng and Wang, Weiyi and Li, Zhe and Martins, Gus and Lee, Jinhyuk and Sherwood, Mark and Ji, Juyeong and Wu, Renjie and Zheng, Jingxiao and Singh, Jyotinder and Sharma, Abheesht and Sreepat, Divya and Jain, Aashi and Elarabawy, Adham and Co, AJ and Doumanoglou, Andreas and Samari, Babak and Hora, Ben and Potetz, Brian and Kim, Dahun and Alfonseca, Enrique and Moiseev, Fedor and Han, Feng and Palma Gomez, Frank and Hernández Ábrego, Gustavo and Zhang, Hesen and Hui, Hui and Han, Jay and Gill, Karan and Chen, Ke and Chen, Koert and Shanbhogue, Madhuri and Boratko, Michael and Suganthan, Paul and Duddu, Sai Meher Karthik and Mariserla, Sandeep and Ariafar, Setareh and Zhang, Shanfeng and Zhang, Shijie and Baumgartner, Simon and Goenka, Sonam and Qiu, Steve and Dabral, Tanmaya and Walker, Trevor and Rao, Vikram and Khawaja, Waleed and Zhou, Wenlei and Ren, Xiaoqi and Xia, Ye and Chen, Yichang and Chen, Yi-Ting and Dong, Zhe and Ding, Zhongli and Visin, Francesco and Liu, Gaël and Zhang, Jiageng and Kenealy, Kathleen and Casbon, Michelle and Kumar, Ravin and Mesnard, Thomas and Gleicher, Zach and Brick, Cormac and Lacombe, Olivier and Roberts, Adam and Sung, Yunhsuan and Hoffmann, Raphael and Warkentin, Tris and Joulin, Armand and Duerig, Tom and Seyedhosseini, Mojtaba},
57
+ publisher={Google DeepMind},
58
+ year={2025},
59
+ url={https://arxiv.org/abs/2509.20354}
60
+ }
61
+ ```
62
+
63
  ### Usage
64
 
65
  These model weights are designed to be used with [Sentence Transformers](https://www.SBERT.net), using the [Gemma 3](https://huggingface.co/docs/transformers/main/en/model_doc/gemma3) implementation from [Hugging Face Transformers](https://huggingface.co/docs/transformers/en/index) as the backbone.
 
186
  </tr>
187
  <tr>
188
  <td>768d</td>
189
+ <td>69.67</td>
190
+ <td>65.11</td>
191
  </tr>
192
  <tr>
193
  <td>512d</td>
194
+ <td>69.18</td>
195
+ <td>64.59</td>
196
  </tr>
197
  <tr>
198
  <td>256d</td>
199
+ <td>68.37</td>
200
+ <td>64.02</td>
201
  </tr>
202
  <tr>
203
  <td>128d</td>
204
+ <td>66.66</td>
205
+ <td>62.70</td>
206
  </tr>
207
  </tbody>
208
  </table>
 
288
  </tr>
289
  <tr>
290
  <td>Q4_0 (768d)</td>
291
+ <td>69.31</td>
292
+ <td>64.65</td>
293
  </tr>
294
  <tr>
295
  <td>Q8_0 (768d)</td>
296
+ <td>69.49</td>
297
+ <td>64.84</td>
298
  </tr>
299
  <tr>
300
  <td>Mixed Precision* (768d)</td>
301
+ <td>69.32</td>
302
+ <td>64.82</td>
303
  </tr>
304
  </tbody>
305
  </table>
notebook.ipynb ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "-u7xRR3DeFXz"
7
+ },
8
+ "source": [
9
+ "##### Copyright 2025 Google LLC."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "cellView": "form",
17
+ "id": "oed1Dh9SeIlD"
18
+ },
19
+ "outputs": [],
20
+ "source": [
21
+ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
22
+ "# you may not use this file except in compliance with the License.\n",
23
+ "# You may obtain a copy of the License at\n",
24
+ "#\n",
25
+ "# https://www.apache.org/licenses/LICENSE-2.0\n",
26
+ "#\n",
27
+ "# Unless required by applicable law or agreed to in writing, software\n",
28
+ "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
29
+ "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
30
+ "# See the License for the specific language governing permissions and\n",
31
+ "# limitations under the License."
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "markdown",
36
+ "metadata": {
37
+ "id": "UpJl85mfqdUB"
38
+ },
39
+ "source": [
40
+ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
41
+ " <td>\n",
42
+ " <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",
43
+ " </td>\n",
44
+ " <td>\n",
45
+ " <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",
46
+ " </td>\n",
47
+ " <td>\n",
48
+ " <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",
49
+ " </td>\n",
50
+ " <td>\n",
51
+ " <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",
52
+ " </td>\n",
53
+ " <td>\n",
54
+ " <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",
55
+ " </td>\n",
56
+ "</table>"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "markdown",
61
+ "metadata": {
62
+ "id": "Sq3lJyEiqqD-"
63
+ },
64
+ "source": [
65
+ "# Generate Embeddings with Sentence Transformers\n",
66
+ "\n",
67
+ "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",
68
+ "\n",
69
+ "## Setup\n",
70
+ "\n",
71
+ "Before starting this tutorial, complete the following steps:\n",
72
+ "\n",
73
+ "* Get access to Gemma by logging into [Hugging Face](https://huggingface.co/google/embeddinggemma-300M) and selecting **Acknowledge license** for a Gemma model.\n",
74
+ "* 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",
75
+ "\n",
76
+ "This notebook will run on either CPU or GPU."
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "markdown",
81
+ "metadata": {
82
+ "id": "R3TOEqprq-X3"
83
+ },
84
+ "source": [
85
+ "### Install Python packages\n",
86
+ "\n",
87
+ "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."
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "metadata": {
94
+ "id": "jZFuhT3nrHEK"
95
+ },
96
+ "outputs": [],
97
+ "source": [
98
+ "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "metadata": {
104
+ "id": "O3ttIyfSA0Lj"
105
+ },
106
+ "source": [
107
+ "After you have accepted the license, you need a valid Hugging Face Token to access the model."
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": null,
113
+ "metadata": {
114
+ "id": "WXK1Ev1Sq2iY"
115
+ },
116
+ "outputs": [],
117
+ "source": [
118
+ "# Login into Hugging Face Hub\n",
119
+ "from huggingface_hub import login\n",
120
+ "login()"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "markdown",
125
+ "metadata": {
126
+ "id": "NUydcaDBrXDi"
127
+ },
128
+ "source": [
129
+ "### Load Model\n",
130
+ "\n",
131
+ "Use the `sentence-transformers` libraries to create an instance of a model class with EmbeddingGemma."
132
+ ]
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "execution_count": null,
137
+ "metadata": {
138
+ "id": "mkpmqlU_rcOd",
139
+ "outputId": "f8458e59-9a6e-4a89-af83-ffdf391c323a"
140
+ },
141
+ "outputs": [
142
+ {
143
+ "name": "stdout",
144
+ "output_type": "stream",
145
+ "text": [
146
+ "Device: cuda:0\n",
147
+ "SentenceTransformer(\n",
148
+ " (0): Transformer({'max_seq_length': 2048, 'do_lower_case': False, 'architecture': 'Gemma3TextModel'})\n",
149
+ " (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",
150
+ " (2): Dense({'in_features': 768, 'out_features': 3072, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n",
151
+ " (3): Dense({'in_features': 3072, 'out_features': 768, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n",
152
+ " (4): Normalize()\n",
153
+ ")\n",
154
+ "Total number of parameters in the model: 307581696\n"
155
+ ]
156
+ }
157
+ ],
158
+ "source": [
159
+ "import torch\n",
160
+ "from sentence_transformers import SentenceTransformer\n",
161
+ "\n",
162
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
163
+ "\n",
164
+ "model_id = \"google/embeddinggemma-300M\"\n",
165
+ "model = SentenceTransformer(model_id).to(device=device)\n",
166
+ "\n",
167
+ "print(f\"Device: {model.device}\")\n",
168
+ "print(model)\n",
169
+ "print(\"Total number of parameters in the model:\", sum([p.numel() for _, p in model.named_parameters()]))"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "metadata": {
175
+ "id": "JxrZ8na0A7Hv"
176
+ },
177
+ "source": [
178
+ "## Generating Embedding\n",
179
+ "\n",
180
+ "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",
181
+ "\n",
182
+ "Let's see how EmbeddingGemma would process three different words `[\"apple\", \"banana\", \"car\"]`.\n",
183
+ "\n",
184
+ "EmbeddingGemma has been trained on vast amounts of text and has learned the relationships between words and concepts."
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": null,
190
+ "metadata": {
191
+ "id": "o0UK8UVAA9b7",
192
+ "outputId": "37c91847-57de-4a47-9c1a-0adffacd1867"
193
+ },
194
+ "outputs": [
195
+ {
196
+ "name": "stdout",
197
+ "output_type": "stream",
198
+ "text": [
199
+ "[[-0.18476306 0.00167681 0.03773484 ... -0.07996225 -0.02348064\n",
200
+ " 0.00976741]\n",
201
+ " [-0.21189538 -0.02657359 0.02513712 ... -0.08042689 -0.01999852\n",
202
+ " 0.00512146]\n",
203
+ " [-0.18924113 -0.02551468 0.04486253 ... -0.06377774 -0.03699806\n",
204
+ " 0.03973572]]\n",
205
+ "Embedding 1: (768,)\n",
206
+ "Embedding 2: (768,)\n",
207
+ "Embedding 3: (768,)\n"
208
+ ]
209
+ }
210
+ ],
211
+ "source": [
212
+ "words = [\"apple\", \"banana\", \"car\"]\n",
213
+ "\n",
214
+ "# Calculate embeddings by calling model.encode()\n",
215
+ "embeddings = model.encode(words)\n",
216
+ "\n",
217
+ "print(embeddings)\n",
218
+ "for idx, embedding in enumerate(embeddings):\n",
219
+ " print(f\"Embedding {idx+1} (shape): {embedding.shape}\")"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "metadata": {
225
+ "id": "inuWOAuMBAR7"
226
+ },
227
+ "source": [
228
+ "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",
229
+ "\n",
230
+ "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."
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "markdown",
235
+ "metadata": {
236
+ "id": "2oCpMMJUr4RT"
237
+ },
238
+ "source": [
239
+ "## Determining Similarity\n",
240
+ "\n",
241
+ "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",
242
+ "\n",
243
+ "- High Similarity:\n",
244
+ " - Sentence A: \"The chef prepared a delicious meal for the guests.\"\n",
245
+ " - Sentence B: \"A tasty dinner was cooked by the chef for the visitors.\"\n",
246
+ " - Reasoning: Both sentences describe the same event using different words and grammatical structures (active vs. passive voice). They convey the same core meaning.\n",
247
+ "\n",
248
+ "- Medium Similarity:\n",
249
+ " - Sentence A: \"She is an expert in machine learning.\"\n",
250
+ " - Sentence B: \"He has a deep interest in artificial intelligence.\"\n",
251
+ " - 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",
252
+ "\n",
253
+ "- Low Similarity:\n",
254
+ " - Sentence A: \"The weather in Tokyo is sunny today.\"\n",
255
+ " - Sentence B: \"I need to buy groceries for the week.\"\n",
256
+ " - Reasoning: The two sentences are on completely unrelated topics and share no semantic overlap."
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "execution_count": null,
262
+ "metadata": {
263
+ "id": "VeTEvnTyslyq",
264
+ "outputId": "b387529f-aad8-4150-e4f1-daef4f30cfc0"
265
+ },
266
+ "outputs": [
267
+ {
268
+ "name": "stdout",
269
+ "output_type": "stream",
270
+ "text": [
271
+ "🙋‍♂️\n",
272
+ "['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']\n",
273
+ "`-> 🤖 score: 0.8002148\n",
274
+ "🙋‍♂️\n",
275
+ "['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']\n",
276
+ "`-> 🤖 score: 0.45417833\n",
277
+ "🙋‍♂️\n",
278
+ "['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']\n",
279
+ "`-> 🤖 score: 0.22262995\n"
280
+ ]
281
+ }
282
+ ],
283
+ "source": [
284
+ "# The sentences to encode\n",
285
+ "sentence_high = [\n",
286
+ " \"The chef prepared a delicious meal for the guests.\",\n",
287
+ " \"A tasty dinner was cooked by the chef for the visitors.\"\n",
288
+ "]\n",
289
+ "sentence_medium = [\n",
290
+ " \"She is an expert in machine learning.\",\n",
291
+ " \"He has a deep interest in artificial intelligence.\"\n",
292
+ "]\n",
293
+ "sentence_low = [\n",
294
+ " \"The weather in Tokyo is sunny today.\",\n",
295
+ " \"I need to buy groceries for the week.\"\n",
296
+ "]\n",
297
+ "\n",
298
+ "for sentence in [sentence_high, sentence_medium, sentence_low]:\n",
299
+ " print(\"🙋‍♂️\")\n",
300
+ " print(sentence)\n",
301
+ " embeddings = model.encode(sentence)\n",
302
+ " similarities = model.similarity(embeddings[0], embeddings[1])\n",
303
+ " print(\"`-> 🤖 score: \", similarities.numpy()[0][0])"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "markdown",
308
+ "metadata": {
309
+ "id": "obfUiizULZE0"
310
+ },
311
+ "source": [
312
+ "### Using Prompts with EmbeddingGemma\n",
313
+ "\n",
314
+ "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",
315
+ "\n",
316
+ "#### How to Apply Prompts\n",
317
+ "\n",
318
+ "You can apply a prompt during inference in three ways.\n",
319
+ "\n",
320
+ "1. **Using the `prompt` argument**<br>\n",
321
+ " Pass the full prompt string directly to the `encode` method. This gives you precise control.\n",
322
+ " ```python\n",
323
+ " embeddings = model.encode(\n",
324
+ " sentence,\n",
325
+ " prompt=\"task: sentence similarity | query: \"\n",
326
+ " )\n",
327
+ " ```\n",
328
+ "2. **Using the `prompt_name` argument**<br>\n",
329
+ " Select a predefined prompt by its name. These prompts are loaded from the model's configuration or during its initialization.\n",
330
+ " ```python\n",
331
+ " embeddings = model.encode(sentence, prompt_name=\"STS\")\n",
332
+ " ```\n",
333
+ "3. **Using the Default Prompt**<br>\n",
334
+ " 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",
335
+ " ```python\n",
336
+ " embeddings = model.encode(sentence)\n",
337
+ " ```\n"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "execution_count": null,
343
+ "metadata": {
344
+ "id": "0p3qe3WDJV-I",
345
+ "outputId": "5fa2638e-e67b-479b-fba4-ca89a22cd10e"
346
+ },
347
+ "outputs": [
348
+ {
349
+ "name": "stdout",
350
+ "output_type": "stream",
351
+ "text": [
352
+ "Available tasks:\n",
353
+ " query: \"task: search result | query: \"\n",
354
+ " document: \"title: none | text: \"\n",
355
+ " BitextMining: \"task: search result | query: \"\n",
356
+ " Clustering: \"task: clustering | query: \"\n",
357
+ " Classification: \"task: classification | query: \"\n",
358
+ " InstructionRetrieval: \"task: code retrieval | query: \"\n",
359
+ " MultilabelClassification: \"task: classification | query: \"\n",
360
+ " PairClassification: \"task: sentence similarity | query: \"\n",
361
+ " Reranking: \"task: search result | query: \"\n",
362
+ " Retrieval: \"task: search result | query: \"\n",
363
+ " Retrieval-query: \"task: search result | query: \"\n",
364
+ " Retrieval-document: \"title: none | text: \"\n",
365
+ " STS: \"task: sentence similarity | query: \"\n",
366
+ " Summarization: \"task: summarization | query: \"\n",
367
+ "--------------------------------------------------------------------------------\n",
368
+ "🙋‍♂️\n",
369
+ "['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']\n",
370
+ "`-> 🤖 score: 0.9363755\n",
371
+ "🙋‍♂️\n",
372
+ "['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']\n",
373
+ "`-> 🤖 score: 0.6425841\n",
374
+ "🙋‍♂️\n",
375
+ "['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']\n",
376
+ "`-> 🤖 score: 0.38587403\n"
377
+ ]
378
+ }
379
+ ],
380
+ "source": [
381
+ "print(\"Available tasks:\")\n",
382
+ "for name, prefix in model.prompts.items():\n",
383
+ " print(f\" {name}: \\\"{prefix}\\\"\")\n",
384
+ "print(\"-\"*80)\n",
385
+ "\n",
386
+ "for sentence in [sentence_high, sentence_medium, sentence_low]:\n",
387
+ " print(\"🙋‍♂️\")\n",
388
+ " print(sentence)\n",
389
+ " embeddings = model.encode(sentence, prompt_name=\"STS\")\n",
390
+ " similarities = model.similarity(embeddings[0], embeddings[1])\n",
391
+ " print(\"`-> 🤖 score: \", similarities.numpy()[0][0])\n"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "markdown",
396
+ "metadata": {
397
+ "id": "2YAqPXDctw2w"
398
+ },
399
+ "source": [
400
+ "#### Use Case: Retrieval-Augmented Generation (RAG)\n",
401
+ "\n",
402
+ "For RAG systems, use the following `prompt_name` values to create specialized embeddings for your queries and documents:\n",
403
+ "\n",
404
+ "* **For Queries:** Use `prompt_name=\"Retrieval-query\"`.<br>\n",
405
+ " ```python\n",
406
+ " query_embedding = model.encode(\n",
407
+ " \"How do I use prompts with this model?\",\n",
408
+ " prompt_name=\"Retrieval-query\"\n",
409
+ " )\n",
410
+ " ```\n",
411
+ "\n",
412
+ "* **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",
413
+ " * **With a title:**<br>\n",
414
+ " ```python\n",
415
+ " doc_embedding = model.encode(\n",
416
+ " \"The document text...\",\n",
417
+ " prompt=\"title: Using Prompts in RAG | text: \"\n",
418
+ " )\n",
419
+ " ```\n",
420
+ " * **Without a title:**<br>\n",
421
+ " ```python\n",
422
+ " doc_embedding = model.encode(\n",
423
+ " \"The document text...\",\n",
424
+ " prompt=\"title: none | text: \"\n",
425
+ " )\n",
426
+ " ```\n",
427
+ "\n",
428
+ "#### Further Reading\n",
429
+ "\n",
430
+ "* For details on all available EmbeddingGemma prompts, see the [model card](http://ai.google.dev/gemma/docs/embeddinggemma/model_card#prompt_instructions).\n",
431
+ "* 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",
432
+ "* 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"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "markdown",
437
+ "metadata": {
438
+ "id": "aQh-QFAPsswb"
439
+ },
440
+ "source": [
441
+ "## Classification\n",
442
+ "\n",
443
+ "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",
444
+ "\n",
445
+ "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."
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": null,
451
+ "metadata": {
452
+ "id": "C2Ufawl-tXvr",
453
+ "outputId": "347bd68c-dfee-470d-eef7-e3af5d096e91"
454
+ },
455
+ "outputs": [
456
+ {
457
+ "name": "stdout",
458
+ "output_type": "stream",
459
+ "text": [
460
+ "tensor([[0.4673, 0.5145, 0.3604],\n",
461
+ " [0.4191, 0.5010, 0.5966]])\n",
462
+ "tensor([1, 2])\n",
463
+ "🙋‍♂️ Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password. -> 🤖 Technical Support\n",
464
+ "🙋‍♂️ I would like to inquire about your enterprise plan pricing and features for a team of 50 people. -> 🤖 Sales Inquiry\n"
465
+ ]
466
+ }
467
+ ],
468
+ "source": [
469
+ "labels = [\"Billing Issue\", \"Technical Support\", \"Sales Inquiry\"]\n",
470
+ "\n",
471
+ "sentence = [\n",
472
+ " \"Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password.\",\n",
473
+ " \"I would like to inquire about your enterprise plan pricing and features for a team of 50 people.\",\n",
474
+ "]\n",
475
+ "\n",
476
+ "# Calculate embeddings by calling model.encode()\n",
477
+ "label_embeddings = model.encode(labels, prompt_name=\"Classification\")\n",
478
+ "embeddings = model.encode(sentence, prompt_name=\"Classification\")\n",
479
+ "\n",
480
+ "# Calculate the embedding similarities\n",
481
+ "similarities = model.similarity(embeddings, label_embeddings)\n",
482
+ "print(similarities)\n",
483
+ "\n",
484
+ "idx = similarities.argmax(1)\n",
485
+ "print(idx)\n",
486
+ "\n",
487
+ "for example in sentence:\n",
488
+ " print(\"🙋‍♂️\", example, \"-> 🤖\", labels[idx[sentence.index(example)]])"
489
+ ]
490
+ },
491
+ {
492
+ "cell_type": "markdown",
493
+ "metadata": {
494
+ "id": "IRUU2EIDPSmW"
495
+ },
496
+ "source": [
497
+ "## Matryoshka Representation Learning (MRL)\n",
498
+ "\n",
499
+ "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",
500
+ "\n",
501
+ "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",
502
+ "\n",
503
+ "Let's use three words `[\"apple\", \"banana\", \"car\"]` and create simplified embeddings to see how MRL works."
504
+ ]
505
+ },
506
+ {
507
+ "cell_type": "code",
508
+ "execution_count": null,
509
+ "metadata": {
510
+ "id": "B1q1F9I5PYSq",
511
+ "outputId": "a5b28e04-4783-4d79-ae82-3fac7e554a7a"
512
+ },
513
+ "outputs": [
514
+ {
515
+ "name": "stdout",
516
+ "output_type": "stream",
517
+ "text": [
518
+ "similarity function: cosine\n",
519
+ "tensor([[0.7510, 0.6685]])\n",
520
+ "🙋‍♂️ apple vs. banana -> 🤖 score: 0.75102395\n",
521
+ "🙋‍♂️ apple vs. car -> 🤖 score: 0.6684626\n"
522
+ ]
523
+ }
524
+ ],
525
+ "source": [
526
+ "def check_word_similarities():\n",
527
+ " # Calculate the embedding similarities\n",
528
+ " print(\"similarity function: \", model.similarity_fn_name)\n",
529
+ " similarities = model.similarity(embeddings[0], embeddings[1:])\n",
530
+ " print(similarities)\n",
531
+ "\n",
532
+ " for idx, word in enumerate(words[1:]):\n",
533
+ " print(\"🙋‍♂️ apple vs.\", word, \"-> 🤖 score: \", similarities.numpy()[0][idx])\n",
534
+ "\n",
535
+ "# Calculate embeddings by calling model.encode()\n",
536
+ "embeddings = model.encode(words, prompt_name=\"STS\")\n",
537
+ "\n",
538
+ "check_word_similarities()"
539
+ ]
540
+ },
541
+ {
542
+ "cell_type": "markdown",
543
+ "metadata": {
544
+ "id": "_iv1xG0TPxkm"
545
+ },
546
+ "source": [
547
+ "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."
548
+ ]
549
+ },
550
+ {
551
+ "cell_type": "code",
552
+ "execution_count": null,
553
+ "metadata": {
554
+ "id": "9Ue4aWh8PzdL",
555
+ "outputId": "176dabd4-9d9c-4ce9-c7e5-472ba47ed55f"
556
+ },
557
+ "outputs": [
558
+ {
559
+ "name": "stdout",
560
+ "output_type": "stream",
561
+ "text": [
562
+ "Embedding 1: (512,)\n",
563
+ "Embedding 2: (512,)\n",
564
+ "Embedding 3: (512,)\n",
565
+ "--------------------------------------------------------------------------------\n",
566
+ "similarity function: cosine\n",
567
+ "tensor([[0.7674, 0.7041]])\n",
568
+ "🙋‍♂️ apple vs. banana -> 🤖 score: 0.767427\n",
569
+ "🙋‍♂️ apple vs. car -> 🤖 score: 0.7040509\n"
570
+ ]
571
+ }
572
+ ],
573
+ "source": [
574
+ "embeddings = model.encode(words, truncate_dim=512, normalize_embeddings=True)\n",
575
+ "\n",
576
+ "for idx, embedding in enumerate(embeddings):\n",
577
+ " print(f\"Embedding {idx+1}: {embedding.shape}\")\n",
578
+ "\n",
579
+ "print(\"-\"*80)\n",
580
+ "check_word_similarities()"
581
+ ]
582
+ },
583
+ {
584
+ "cell_type": "markdown",
585
+ "metadata": {
586
+ "id": "lgkmgzfVP24M"
587
+ },
588
+ "source": [
589
+ "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."
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "code",
594
+ "execution_count": null,
595
+ "metadata": {
596
+ "id": "Gi4NlPv-P4RS",
597
+ "outputId": "656d8d6a-1e79-41be-f17a-cab136bf27ea"
598
+ },
599
+ "outputs": [
600
+ {
601
+ "name": "stdout",
602
+ "output_type": "stream",
603
+ "text": [
604
+ "Embedding 1: (256,)\n",
605
+ "Embedding 2: (256,)\n",
606
+ "Embedding 3: (256,)\n",
607
+ "--------------------------------------------------------------------------------\n",
608
+ "similarity function: dot\n",
609
+ "tensor([[0.7855, 0.7382]])\n",
610
+ "🙋‍♂️ apple vs. banana -> 🤖 score: 0.7854644\n",
611
+ "🙋‍♂️ apple vs. car -> 🤖 score: 0.7382126\n"
612
+ ]
613
+ }
614
+ ],
615
+ "source": [
616
+ "model = SentenceTransformer(model_id, truncate_dim=256, similarity_fn_name=\"dot\").to(device=device)\n",
617
+ "embeddings = model.encode(words, prompt_name=\"STS\", normalize_embeddings=True)\n",
618
+ "\n",
619
+ "for idx, embedding in enumerate(embeddings):\n",
620
+ " print(f\"Embedding {idx+1}: {embedding.shape}\")\n",
621
+ "\n",
622
+ "print(\"-\"*80)\n",
623
+ "check_word_similarities()"
624
+ ]
625
+ },
626
+ {
627
+ "cell_type": "markdown",
628
+ "metadata": {
629
+ "id": "RYr9uSI_t3fm"
630
+ },
631
+ "source": [
632
+ "## Summary and next steps\n",
633
+ "\n",
634
+ "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",
635
+ "\n",
636
+ "Check out the following docs next:\n",
637
+ "\n",
638
+ "* [Fine-tune EmbeddingGemma](https://ai.google.dev/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers)\n",
639
+ "* [Simple RAG example](https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/%5BGemma_3%5DRAG_with_EmbeddingGemma.ipynb) in the Gemma Cookbook\n"
640
+ ]
641
+ }
642
+ ],
643
+ "metadata": {
644
+ "colab": {
645
+ "name": "inference-embeddinggemma-with-sentence-transformers.ipynb",
646
+ "provenance": [],
647
+ "toc_visible": true
648
+ },
649
+ "kernelspec": {
650
+ "display_name": "Python 3",
651
+ "name": "python3"
652
+ }
653
+ },
654
+ "nbformat": 4,
655
+ "nbformat_minor": 0
656
+ }