model2vec 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {model2vec-0.2.1 → model2vec-0.2.3}/.gitignore +1 -0
  2. {model2vec-0.2.1 → model2vec-0.2.3}/PKG-INFO +58 -23
  3. {model2vec-0.2.1 → model2vec-0.2.3}/README.md +57 -22
  4. model2vec-0.2.3/assets/images/speed_vs_accuracy_v2.png +0 -0
  5. model2vec-0.2.3/assets/images/speed_vs_accuracy_v3.png +0 -0
  6. model2vec-0.2.3/model2vec/distill/__init__.py +3 -0
  7. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/distill/distillation.py +101 -30
  8. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/distill/inference.py +18 -2
  9. model2vec-0.2.3/model2vec/distill/tokenizer.py +115 -0
  10. model2vec-0.2.3/model2vec/distill/utils.py +26 -0
  11. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/model.py +80 -8
  12. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec.egg-info/PKG-INFO +58 -23
  13. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec.egg-info/SOURCES.txt +3 -0
  14. {model2vec-0.2.1 → model2vec-0.2.3}/pyproject.toml +1 -1
  15. {model2vec-0.2.1 → model2vec-0.2.3}/tests/conftest.py +4 -4
  16. {model2vec-0.2.1 → model2vec-0.2.3}/tests/test_distillation.py +94 -6
  17. {model2vec-0.2.1 → model2vec-0.2.3}/tests/test_model.py +45 -2
  18. model2vec-0.2.3/tests/test_utils.py +52 -0
  19. {model2vec-0.2.1 → model2vec-0.2.3}/uv.lock +1 -1
  20. model2vec-0.2.1/model2vec/distill/__init__.py +0 -3
  21. model2vec-0.2.1/model2vec/distill/tokenizer.py +0 -80
  22. model2vec-0.2.1/tests/test_utils.py +0 -25
  23. {model2vec-0.2.1 → model2vec-0.2.3}/.github/workflows/ci.yaml +0 -0
  24. {model2vec-0.2.1 → model2vec-0.2.3}/.pre-commit-config.yaml +0 -0
  25. {model2vec-0.2.1 → model2vec-0.2.3}/LICENSE +0 -0
  26. {model2vec-0.2.1 → model2vec-0.2.3}/Makefile +0 -0
  27. {model2vec-0.2.1 → model2vec-0.2.3}/assets/images/logo.png +0 -0
  28. {model2vec-0.2.1 → model2vec-0.2.3}/assets/images/model2vec_model_diagram.png +0 -0
  29. {model2vec-0.2.1 → model2vec-0.2.3}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  30. {model2vec-0.2.1 → model2vec-0.2.3}/assets/images/speed_vs_accuracy.png +0 -0
  31. {model2vec-0.2.1 → model2vec-0.2.3}/assets/images/tutorial_ezlo.png +0 -0
  32. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/__init__.py +0 -0
  33. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/distill/__main__.py +0 -0
  34. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/model_card_template.md +0 -0
  35. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec/utils.py +0 -0
  36. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec.egg-info/dependency_links.txt +0 -0
  37. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec.egg-info/requires.txt +0 -0
  38. {model2vec-0.2.1 → model2vec-0.2.3}/model2vec.egg-info/top_level.txt +0 -0
  39. {model2vec-0.2.1 → model2vec-0.2.3}/setup.cfg +0 -0
  40. {model2vec-0.2.1 → model2vec-0.2.3}/tests/__init__.py +0 -0
  41. {model2vec-0.2.1 → model2vec-0.2.3}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  42. {model2vec-0.2.1 → model2vec-0.2.3}/tests/data/test_tokenizer/tokenizer.json +0 -0
  43. {model2vec-0.2.1 → model2vec-0.2.3}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  44. {model2vec-0.2.1 → model2vec-0.2.3}/tutorials/README.md +0 -0
  45. {model2vec-0.2.1 → model2vec-0.2.3}/tutorials/recipe_search.ipynb +0 -0
@@ -171,4 +171,5 @@ model2vec_models
171
171
  results/*
172
172
  counts/*
173
173
  results_old/*
174
+ local/*
174
175
  lightning_logs/*
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Distill a Small Fast Model from any Sentence Transformer
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
@@ -133,6 +133,9 @@ model = StaticModel.from_pretrained(model_name)
133
133
 
134
134
  # Make embeddings
135
135
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
136
+
137
+ # Make sequences of token embeddings
138
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
136
139
  ```
137
140
 
138
141
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
@@ -151,17 +154,36 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
151
154
  m2v_model.save_pretrained("m2v_model")
152
155
  ```
153
156
 
154
- Distillation is really fast, and only takes about 30 seconds on a 2024 macbook using the MPS backend. Best of all, distillation requires no training data.
157
+ If you already have a model loaded, or need to load a model in some special way, we also offer an interface to distill models in memory.
158
+
159
+ ```python
160
+ from transformers import AutoModel, AutoTokenizer
161
+
162
+ from model2vec.distill import distill_from_model
163
+
164
+ # Assuming a loaded model and tokenizer
165
+ model_name = "baai/bge-base-en-v1.5"
166
+ model = AutoModel.from_pretrained(model_name)
167
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
168
+
169
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
170
+
171
+ m2v_model.save_pretrained("m2v_model")
172
+
173
+ ```
174
+
175
+ Distillation is really fast, and only takes about 5 seconds on a 2024 macbook using the MPS backend, 30 seconds on CPU. Best of all, distillation requires no training data.
155
176
 
156
177
  ## What is Model2Vec?
157
178
 
158
- Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Best of all, you don't need _any_ data to distill a model using Model2Vec.
179
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Best of all, you don't need _any_ data to distill a model using Model2Vec.
159
180
 
160
181
  It works by passing a vocabulary through a sentence transformer model, then reducing the dimensionality of the resulting embeddings using PCA, and finally weighting the embeddings using zipf weighting. During inference, we simply take the mean of all token embeddings occurring in a sentence.
161
182
 
162
- Model2vec has 2 modes:
163
- - **Output**: behaves much a like a real sentence transformer, i.e., it uses a subword tokenizer and encodes all wordpieces. This is really quick to create, very small (30 MB), but might be less performant on some tasks.
164
- - **Vocab**: behaves much like GloVe or regular word2vec vectors, albeit with much better performance. These models are a bit bigger, depending on your vocabulary size, but still very fast, and are useful in situations in which you have a bit more RAM, but still need to go fast.
183
+ Model2vec has 3 modes:
184
+ - **Output**: behaves much like a real sentence transformer, i.e., it uses a subword tokenizer and simply encodes all wordpieces in its vocab. This is really quick to create (30 seconds on a CPU), very small (30 MB in float32), but might be less performant on some tasks.
185
+ - **Vocab (word level)**: creates a word-level tokenizer and only encodes words that are in the vocabulary. This is a bit slower to create and creates a larger model, but might be more performant on some tasks. Note that this model can go out-of-vocabulary, which might be beneficial if your domain is very noisy
186
+ - **Vocab (subword)**: a combination of the two methods above. In this mode, you can pass your own vocabulary, but it also uses the subword vocabulary to create representations for words not in the passed vocabulary.
165
187
 
166
188
  ## Main Features
167
189
 
@@ -239,6 +261,9 @@ model = StaticModel.from_pretrained(model_name, token=None)
239
261
 
240
262
  # Make embeddings
241
263
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
264
+
265
+ # Make sequences of token embeddings
266
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
242
267
  ```
243
268
 
244
269
  ### Evaluating a Model2Vec model
@@ -287,6 +312,7 @@ print(make_leaderboard(task_scores))
287
312
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
288
313
  | [M2V_base_glove](https://huggingface.co/minishlab/M2V_base_glove) | English | Flagship embedding model based on GloVe vocab. | GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 102M |
289
314
  | [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | English | Flagship embedding model based on bge-base-en-v1.5 vocab. Uses a subword tokenizer. | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M |
315
+ | [M2V_base_glove_subword](https://huggingface.co/minishlab/M2V_base_glove_subword) | English | Flagship embedding model based on bge-base-en-v1.5 + glove vocab. Uses a subword tokenizer. | Output + GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 103M |
290
316
  | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Flagship multilingual embedding model based on LaBSE vocab. Uses a subword tokenizer. | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M |
291
317
  ## Results
292
318
 
@@ -294,13 +320,18 @@ print(make_leaderboard(task_scores))
294
320
 
295
321
  Model2Vec is evaluated on MTEB, as well as two additional tasks: [PEARL](https://github.com/tigerchen52/PEARL) (a phrase representation task) and WordSim (a collection of _word_ similarity tasks). The results are shown in the table below.
296
322
 
297
- | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
298
- |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
299
- | all-MiniLM-L6-v2 | 56.08 | 56.09 | 62.62 | 41.94 | 82.37 | 58.04 | 41.95 | 78.90 | 30.81 | 60.83 | 49.91 |
300
- | M2V_base_glove | 48.58 | 47.60 | 61.35 | 30.52 | 75.34 | 48.50 | 29.26 | 70.31 | 31.50 | 50.28 | 54.29 |
301
- | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.90 | 47.63 | 26.14 | 68.58 | 29.20 | 54.02 | 49.18 |
302
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
303
- | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
323
+
324
+
325
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
326
+ |:-----------------------|:---------:|:----------:|:------:|:------:|:---------:|:------:|:------:|:------:|:------:|:------:|:-------:|
327
+ | all-MiniLM-L6-v2 | 56.08 | 56.09 | 62.62 | 41.94 | 82.37 | 58.04 | 41.95 | 78.90 | 30.81 | 60.83 | 49.91 |
328
+ | M2V_base_glove_subword | 49.06 | 46.69 | 61.27 | 30.03 | 74.71 | 49.15 | 27.16 | 69.09 | 30.08 | 56.82 | 57.99 |
329
+ | M2V_base_glove | 48.58 | 47.60 | 61.35 | 30.52 | 75.34 | 48.50 | 29.26 | 70.31 | 31.50 | 50.28 | 54.29 |
330
+ | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.90 | 47.63 | 26.14 | 68.58 | 29.20 | 54.02 | 49.18 |
331
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
332
+ | BPEmb_50k_300d | 39.34 | 37.78 | 55.76 | 23.35 | 57.86 | 43.21 | 17.50 | 55.10 | 29.74 | 47.56 | 41.28 |
333
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
334
+
304
335
 
305
336
  <details>
306
337
  <summary> Task Abbreviations </summary>
@@ -322,21 +353,25 @@ For readability, the MTEB task names are abbreviated as follows:
322
353
 
323
354
  In addition to the MTEB evaluation, we evaluate Model2Vec on a number of classification datasets. These are used as additional evidence to avoid overfitting to the MTEB dataset and to benchmark the speed of the model. The results are shown in the table below.
324
355
 
325
- | model | Average | sst2 | imdb | trec | ag_news |
326
- |:-----------------|----------:|---------:|-------:|---------:|----------:|
327
- | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
328
- | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
329
- | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
330
- | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
331
- | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
332
- | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
333
356
 
334
- As can be seen, Model2Vec models outperform the GloVe and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
357
+ | Model | Average | SST2 | IMDB | TREC | AG News |
358
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
359
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
360
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
361
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
362
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
363
+ | BPEmb_50k_300d | 81.15 | 80.42 | 84.04 | 71.25 | 88.92 |
364
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
365
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
366
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
367
+
368
+
369
+ As can be seen, Model2Vec models outperform the GloVe, BPEmb, and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
335
370
 
336
371
  The figure below shows the relationship between the number of sentences per second and the average classification score. The circle sizes correspond to the number of parameters in the models (larger = more parameters).
337
372
  This plot shows that the Model2Vec models are much faster than the other models, while still being competitive in terms of classification performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
338
373
 
339
- | ![Description](assets/images/speed_vs_accuracy.png) |
374
+ | ![Description](assets/images/speed_vs_accuracy_v3.png) |
340
375
  |:--:|
341
376
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
342
377
 
@@ -70,6 +70,9 @@ model = StaticModel.from_pretrained(model_name)
70
70
 
71
71
  # Make embeddings
72
72
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
73
+
74
+ # Make sequences of token embeddings
75
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
73
76
  ```
74
77
 
75
78
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
@@ -88,17 +91,36 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
88
91
  m2v_model.save_pretrained("m2v_model")
89
92
  ```
90
93
 
91
- Distillation is really fast, and only takes about 30 seconds on a 2024 macbook using the MPS backend. Best of all, distillation requires no training data.
94
+ If you already have a model loaded, or need to load a model in some special way, we also offer an interface to distill models in memory.
95
+
96
+ ```python
97
+ from transformers import AutoModel, AutoTokenizer
98
+
99
+ from model2vec.distill import distill_from_model
100
+
101
+ # Assuming a loaded model and tokenizer
102
+ model_name = "baai/bge-base-en-v1.5"
103
+ model = AutoModel.from_pretrained(model_name)
104
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
105
+
106
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
107
+
108
+ m2v_model.save_pretrained("m2v_model")
109
+
110
+ ```
111
+
112
+ Distillation is really fast, and only takes about 5 seconds on a 2024 macbook using the MPS backend, 30 seconds on CPU. Best of all, distillation requires no training data.
92
113
 
93
114
  ## What is Model2Vec?
94
115
 
95
- Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Best of all, you don't need _any_ data to distill a model using Model2Vec.
116
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Best of all, you don't need _any_ data to distill a model using Model2Vec.
96
117
 
97
118
  It works by passing a vocabulary through a sentence transformer model, then reducing the dimensionality of the resulting embeddings using PCA, and finally weighting the embeddings using zipf weighting. During inference, we simply take the mean of all token embeddings occurring in a sentence.
98
119
 
99
- Model2vec has 2 modes:
100
- - **Output**: behaves much a like a real sentence transformer, i.e., it uses a subword tokenizer and encodes all wordpieces. This is really quick to create, very small (30 MB), but might be less performant on some tasks.
101
- - **Vocab**: behaves much like GloVe or regular word2vec vectors, albeit with much better performance. These models are a bit bigger, depending on your vocabulary size, but still very fast, and are useful in situations in which you have a bit more RAM, but still need to go fast.
120
+ Model2vec has 3 modes:
121
+ - **Output**: behaves much like a real sentence transformer, i.e., it uses a subword tokenizer and simply encodes all wordpieces in its vocab. This is really quick to create (30 seconds on a CPU), very small (30 MB in float32), but might be less performant on some tasks.
122
+ - **Vocab (word level)**: creates a word-level tokenizer and only encodes words that are in the vocabulary. This is a bit slower to create and creates a larger model, but might be more performant on some tasks. Note that this model can go out-of-vocabulary, which might be beneficial if your domain is very noisy
123
+ - **Vocab (subword)**: a combination of the two methods above. In this mode, you can pass your own vocabulary, but it also uses the subword vocabulary to create representations for words not in the passed vocabulary.
102
124
 
103
125
  ## Main Features
104
126
 
@@ -176,6 +198,9 @@ model = StaticModel.from_pretrained(model_name, token=None)
176
198
 
177
199
  # Make embeddings
178
200
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
201
+
202
+ # Make sequences of token embeddings
203
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
179
204
  ```
180
205
 
181
206
  ### Evaluating a Model2Vec model
@@ -224,6 +249,7 @@ print(make_leaderboard(task_scores))
224
249
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
225
250
  | [M2V_base_glove](https://huggingface.co/minishlab/M2V_base_glove) | English | Flagship embedding model based on GloVe vocab. | GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 102M |
226
251
  | [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | English | Flagship embedding model based on bge-base-en-v1.5 vocab. Uses a subword tokenizer. | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M |
252
+ | [M2V_base_glove_subword](https://huggingface.co/minishlab/M2V_base_glove_subword) | English | Flagship embedding model based on bge-base-en-v1.5 + glove vocab. Uses a subword tokenizer. | Output + GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 103M |
227
253
  | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Flagship multilingual embedding model based on LaBSE vocab. Uses a subword tokenizer. | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M |
228
254
  ## Results
229
255
 
@@ -231,13 +257,18 @@ print(make_leaderboard(task_scores))
231
257
 
232
258
  Model2Vec is evaluated on MTEB, as well as two additional tasks: [PEARL](https://github.com/tigerchen52/PEARL) (a phrase representation task) and WordSim (a collection of _word_ similarity tasks). The results are shown in the table below.
233
259
 
234
- | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
235
- |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
236
- | all-MiniLM-L6-v2 | 56.08 | 56.09 | 62.62 | 41.94 | 82.37 | 58.04 | 41.95 | 78.90 | 30.81 | 60.83 | 49.91 |
237
- | M2V_base_glove | 48.58 | 47.60 | 61.35 | 30.52 | 75.34 | 48.50 | 29.26 | 70.31 | 31.50 | 50.28 | 54.29 |
238
- | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.90 | 47.63 | 26.14 | 68.58 | 29.20 | 54.02 | 49.18 |
239
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
240
- | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
260
+
261
+
262
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
263
+ |:-----------------------|:---------:|:----------:|:------:|:------:|:---------:|:------:|:------:|:------:|:------:|:------:|:-------:|
264
+ | all-MiniLM-L6-v2 | 56.08 | 56.09 | 62.62 | 41.94 | 82.37 | 58.04 | 41.95 | 78.90 | 30.81 | 60.83 | 49.91 |
265
+ | M2V_base_glove_subword | 49.06 | 46.69 | 61.27 | 30.03 | 74.71 | 49.15 | 27.16 | 69.09 | 30.08 | 56.82 | 57.99 |
266
+ | M2V_base_glove | 48.58 | 47.60 | 61.35 | 30.52 | 75.34 | 48.50 | 29.26 | 70.31 | 31.50 | 50.28 | 54.29 |
267
+ | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.90 | 47.63 | 26.14 | 68.58 | 29.20 | 54.02 | 49.18 |
268
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
269
+ | BPEmb_50k_300d | 39.34 | 37.78 | 55.76 | 23.35 | 57.86 | 43.21 | 17.50 | 55.10 | 29.74 | 47.56 | 41.28 |
270
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
271
+
241
272
 
242
273
  <details>
243
274
  <summary> Task Abbreviations </summary>
@@ -259,21 +290,25 @@ For readability, the MTEB task names are abbreviated as follows:
259
290
 
260
291
  In addition to the MTEB evaluation, we evaluate Model2Vec on a number of classification datasets. These are used as additional evidence to avoid overfitting to the MTEB dataset and to benchmark the speed of the model. The results are shown in the table below.
261
292
 
262
- | model | Average | sst2 | imdb | trec | ag_news |
263
- |:-----------------|----------:|---------:|-------:|---------:|----------:|
264
- | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
265
- | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
266
- | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
267
- | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
268
- | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
269
- | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
270
293
 
271
- As can be seen, Model2Vec models outperform the GloVe and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
294
+ | Model | Average | SST2 | IMDB | TREC | AG News |
295
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
296
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
297
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
298
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
299
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
300
+ | BPEmb_50k_300d | 81.15 | 80.42 | 84.04 | 71.25 | 88.92 |
301
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
302
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
303
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
304
+
305
+
306
+ As can be seen, Model2Vec models outperform the GloVe, BPEmb, and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
272
307
 
273
308
  The figure below shows the relationship between the number of sentences per second and the average classification score. The circle sizes correspond to the number of parameters in the models (larger = more parameters).
274
309
  This plot shows that the Model2Vec models are much faster than the other models, while still being competitive in terms of classification performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
275
310
 
276
- | ![Description](assets/images/speed_vs_accuracy.png) |
311
+ | ![Description](assets/images/speed_vs_accuracy_v3.png) |
277
312
  |:--:|
278
313
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
279
314
 
@@ -0,0 +1,3 @@
1
+ from model2vec.distill.distillation import distill, distill_from_model
2
+
3
+ __all__ = ["distill", "distill_from_model"]
@@ -1,8 +1,11 @@
1
1
  import logging
2
+ from typing import Literal
2
3
 
3
4
  import numpy as np
4
5
  from huggingface_hub import model_info
6
+ from huggingface_hub.utils._errors import RepositoryNotFoundError
5
7
  from sklearn.decomposition import PCA
8
+ from tokenizers.models import BPE, Unigram
6
9
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
7
10
 
8
11
  from model2vec.distill.inference import (
@@ -10,16 +13,21 @@ from model2vec.distill.inference import (
10
13
  create_output_embeddings_from_model_name_and_tokens,
11
14
  )
12
15
  from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
16
+ from model2vec.distill.utils import select_optimal_device
13
17
  from model2vec.model import StaticModel
14
18
 
15
19
  logger = logging.getLogger(__name__)
16
20
 
17
21
 
18
- def distill(
19
- model_name: str,
22
+ PCADimType = int | None | Literal["auto"]
23
+
24
+
25
+ def distill_from_model(
26
+ model: PreTrainedModel,
27
+ tokenizer: PreTrainedTokenizerFast,
20
28
  vocabulary: list[str] | None = None,
21
- device: str = "cpu",
22
- pca_dims: int | None = 256,
29
+ device: str | None = None,
30
+ pca_dims: PCADimType = 256,
23
31
  apply_zipf: bool = True,
24
32
  use_subword: bool = True,
25
33
  ) -> StaticModel:
@@ -32,10 +40,13 @@ def distill(
32
40
  If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
33
41
  If you don't pass a vocabulary, we use the model's tokenizer directly.
34
42
 
35
- :param model_name: The model name to use. Any sentencetransformer compatible model works.
43
+ :param model: The model to use.
44
+ :param tokenizer: The tokenizer to use.
36
45
  :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
37
46
  :param device: The device to use.
38
- :param pca_dims: The number of components to use for PCA. If this is None, we don't apply PCA.
47
+ :param pca_dims: The number of components to use for PCA.
48
+ If this is None, we don't apply PCA.
49
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
39
50
  :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
40
51
  :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
41
52
  :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
@@ -43,45 +54,46 @@ def distill(
43
54
  :return: A StaticModel
44
55
 
45
56
  """
57
+ device = select_optimal_device(device)
46
58
  if not use_subword and vocabulary is None:
47
59
  raise ValueError(
48
60
  "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
49
61
  )
50
62
 
51
- # Load original tokenizer. We need to keep this to tokenize any tokens in the vocabulary.
52
- original_tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
53
- original_model: PreTrainedModel = AutoModel.from_pretrained(model_name)
63
+ if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
64
+ raise ValueError(
65
+ "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
66
+ "This is not supported yet."
67
+ "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
68
+ )
69
+
54
70
  # Make a base list of tokens.
55
71
  tokens: list[str] = []
56
72
  if use_subword:
57
73
  # Create the subword embeddings.
58
- tokens, embeddings = create_output_embeddings_from_model_name(
59
- model=original_model, tokenizer=original_tokenizer, device=device
60
- )
74
+ tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
61
75
 
62
76
  # Remove any unused tokens from the tokenizer and embeddings.
63
77
  wrong_tokens = [x for x in tokens if x.startswith("[unused")]
64
- vocab = original_tokenizer.get_vocab()
78
+ vocab = tokenizer.get_vocab()
65
79
  # Get the ids of the unused token.
66
80
  wrong_token_ids = [vocab[token] for token in wrong_tokens]
67
81
  # Remove the unused tokens from the tokenizer.
68
- new_tokenizer = remove_tokens(original_tokenizer.backend_tokenizer, wrong_tokens)
82
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
69
83
  # Remove the embeddings of the unused tokens.
70
84
  embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
71
85
  logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
72
86
  else:
73
87
  # We need to keep the unk token in the tokenizer.
74
- unk_token = original_tokenizer.backend_tokenizer.model.unk_token
88
+ unk_token = tokenizer.backend_tokenizer.model.unk_token
75
89
  # Remove all tokens except the UNK token.
76
- new_tokenizer = remove_tokens(
77
- original_tokenizer.backend_tokenizer, list(set(original_tokenizer.get_vocab()) - {unk_token})
78
- )
90
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, list(set(tokenizer.get_vocab()) - {unk_token}))
79
91
  # We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
80
92
  embeddings = None
81
93
 
82
- if vocabulary is not None:
94
+ if vocabulary:
83
95
  # Preprocess the vocabulary with the original tokenizer.
84
- preprocessed_vocabulary = preprocess_vocabulary(original_tokenizer.backend_tokenizer, vocabulary)
96
+ preprocessed_vocabulary = preprocess_vocabulary(tokenizer.backend_tokenizer, vocabulary)
85
97
  n_tokens_before = len(preprocessed_vocabulary)
86
98
  # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
87
99
  cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
@@ -93,8 +105,8 @@ def distill(
93
105
  if cleaned_vocabulary:
94
106
  # Create the embeddings.
95
107
  _, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
96
- model=original_model,
97
- tokenizer=original_tokenizer,
108
+ model=model,
109
+ tokenizer=tokenizer,
98
110
  tokens=cleaned_vocabulary,
99
111
  device=device,
100
112
  )
@@ -112,28 +124,87 @@ def distill(
112
124
  # Post process the embeddings by applying PCA and Zipf weighting.
113
125
  embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
114
126
 
115
- config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
127
+ model_name = getattr(model, "name_or_path", "")
128
+
129
+ config = {
130
+ "tokenizer_name": model_name,
131
+ "apply_pca": pca_dims,
132
+ "apply_zipf": apply_zipf,
133
+ "hidden_dim": embeddings.shape[1],
134
+ "seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
135
+ }
116
136
  # Get the language from the model card
117
- info = model_info(model_name)
118
- language = info.cardData.get("language")
137
+ try:
138
+ info = model_info(model_name)
139
+ language = info.cardData.get("language")
140
+ except RepositoryNotFoundError:
141
+ logger.info("No model info found for model. Setting `language` to None.")
142
+ language = None
119
143
 
120
144
  return StaticModel(
121
145
  vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
122
146
  )
123
147
 
124
148
 
125
- def _post_process_embeddings(embeddings: np.ndarray, pca_dims: int | None, apply_zipf: bool) -> np.ndarray:
149
+ def distill(
150
+ model_name: str,
151
+ vocabulary: list[str] | None = None,
152
+ device: str | None = None,
153
+ pca_dims: PCADimType = 256,
154
+ apply_zipf: bool = True,
155
+ use_subword: bool = True,
156
+ ) -> StaticModel:
157
+ """
158
+ Distill a staticmodel from a sentence transformer.
159
+
160
+ This function creates a set of embeddings from a sentence transformer. It does this by doing either
161
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
162
+
163
+ If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
164
+ If you don't pass a vocabulary, we use the model's tokenizer directly.
165
+
166
+ :param model_name: The model name to use. Any sentencetransformer compatible model works.
167
+ :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
168
+ :param device: The device to use.
169
+ :param pca_dims: The number of components to use for PCA.
170
+ If this is None, we don't apply PCA.
171
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
172
+ :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
173
+ :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
174
+ :return: A StaticModel
175
+
176
+ """
177
+ model: PreTrainedModel = AutoModel.from_pretrained(model_name)
178
+ tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
179
+
180
+ return distill_from_model(
181
+ model=model,
182
+ tokenizer=tokenizer,
183
+ vocabulary=vocabulary,
184
+ device=device,
185
+ pca_dims=pca_dims,
186
+ apply_zipf=apply_zipf,
187
+ use_subword=use_subword,
188
+ )
189
+
190
+
191
+ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
126
192
  """Post process embeddings by applying PCA and Zipf weighting."""
127
193
  if pca_dims is not None:
128
- if pca_dims >= embeddings.shape[1]:
129
- raise ValueError(
130
- f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
194
+ if pca_dims == "auto":
195
+ pca_dims = embeddings.shape[1]
196
+ if pca_dims > embeddings.shape[1]:
197
+ logger.warning(
198
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
199
+ "Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
200
+ "Applying PCA will probably improve performance, so consider just leaving it."
131
201
  )
202
+ pca_dims = embeddings.shape[1]
132
203
  if pca_dims >= embeddings.shape[0]:
133
204
  logger.warning(
134
205
  f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
135
206
  )
136
- elif pca_dims < embeddings.shape[1]:
207
+ elif pca_dims <= embeddings.shape[1]:
137
208
  logger.info(f"Applying PCA with n_components {pca_dims}")
138
209
 
139
210
  p = PCA(n_components=pca_dims, whiten=False)
@@ -67,7 +67,12 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
67
67
  """
68
68
  encodings = tokenizer(tokens, return_tensors="pt", padding=True, truncation=True).to(model.device)
69
69
  encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
70
- out = encoded.last_hidden_state.cpu()
70
+ out: torch.Tensor = encoded.last_hidden_state.cpu()
71
+ # NOTE: If the dtype is bfloat 16, we convert to float32,
72
+ # because numpy does not suport bfloat16
73
+ # See here: https://github.com/numpy/numpy/issues/19808
74
+ if out.dtype == torch.bfloat16:
75
+ out = out.float()
71
76
 
72
77
  mask = encodings["attention_mask"].cpu()
73
78
  # NOTE: evil hack. For any batch, there will be a mask vector
@@ -122,8 +127,19 @@ def create_output_embeddings_from_model_name(
122
127
  for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
123
128
  batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
124
129
  with torch.no_grad():
125
- encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(input_ids=batch.to(device))
130
+ # NOTE: we create these masks because nomic embed requires them.
131
+ # Normally, we could set them to None
132
+ token_type_ids = torch.zeros_like(batch)
133
+ attention_mask = torch.ones_like(batch)
134
+ encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(
135
+ input_ids=batch.to(device), attention_mask=attention_mask, token_type_ids=token_type_ids
136
+ )
126
137
  out: torch.Tensor = encoded.last_hidden_state
138
+ # NOTE: If the dtype is bfloat 16, we convert to float32,
139
+ # because numpy does not suport bfloat16
140
+ # See here: https://github.com/numpy/numpy/issues/19808
141
+ if out.dtype == torch.bfloat16:
142
+ out = out.float()
127
143
  intermediate_weights.append(out[:, 1].cpu().numpy())
128
144
  out_weights = np.concatenate(intermediate_weights)
129
145