model2vec 0.2.1__tar.gz → 0.2.2__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 (44) hide show
  1. {model2vec-0.2.1 → model2vec-0.2.2}/.gitignore +1 -0
  2. {model2vec-0.2.1 → model2vec-0.2.2}/PKG-INFO +45 -21
  3. {model2vec-0.2.1 → model2vec-0.2.2}/README.md +44 -20
  4. model2vec-0.2.2/assets/images/speed_vs_accuracy_v2.png +0 -0
  5. model2vec-0.2.2/model2vec/distill/__init__.py +3 -0
  6. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/distill/distillation.py +87 -27
  7. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/distill/inference.py +18 -2
  8. model2vec-0.2.2/model2vec/distill/tokenizer.py +115 -0
  9. model2vec-0.2.2/model2vec/distill/utils.py +26 -0
  10. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec.egg-info/PKG-INFO +45 -21
  11. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec.egg-info/SOURCES.txt +2 -0
  12. {model2vec-0.2.1 → model2vec-0.2.2}/pyproject.toml +1 -1
  13. {model2vec-0.2.1 → model2vec-0.2.2}/tests/conftest.py +4 -4
  14. {model2vec-0.2.1 → model2vec-0.2.2}/tests/test_distillation.py +81 -6
  15. model2vec-0.2.2/tests/test_utils.py +52 -0
  16. {model2vec-0.2.1 → model2vec-0.2.2}/uv.lock +1 -1
  17. model2vec-0.2.1/model2vec/distill/__init__.py +0 -3
  18. model2vec-0.2.1/model2vec/distill/tokenizer.py +0 -80
  19. model2vec-0.2.1/tests/test_utils.py +0 -25
  20. {model2vec-0.2.1 → model2vec-0.2.2}/.github/workflows/ci.yaml +0 -0
  21. {model2vec-0.2.1 → model2vec-0.2.2}/.pre-commit-config.yaml +0 -0
  22. {model2vec-0.2.1 → model2vec-0.2.2}/LICENSE +0 -0
  23. {model2vec-0.2.1 → model2vec-0.2.2}/Makefile +0 -0
  24. {model2vec-0.2.1 → model2vec-0.2.2}/assets/images/logo.png +0 -0
  25. {model2vec-0.2.1 → model2vec-0.2.2}/assets/images/model2vec_model_diagram.png +0 -0
  26. {model2vec-0.2.1 → model2vec-0.2.2}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  27. {model2vec-0.2.1 → model2vec-0.2.2}/assets/images/speed_vs_accuracy.png +0 -0
  28. {model2vec-0.2.1 → model2vec-0.2.2}/assets/images/tutorial_ezlo.png +0 -0
  29. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/__init__.py +0 -0
  30. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/distill/__main__.py +0 -0
  31. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/model.py +0 -0
  32. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/model_card_template.md +0 -0
  33. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec/utils.py +0 -0
  34. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec.egg-info/dependency_links.txt +0 -0
  35. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec.egg-info/requires.txt +0 -0
  36. {model2vec-0.2.1 → model2vec-0.2.2}/model2vec.egg-info/top_level.txt +0 -0
  37. {model2vec-0.2.1 → model2vec-0.2.2}/setup.cfg +0 -0
  38. {model2vec-0.2.1 → model2vec-0.2.2}/tests/__init__.py +0 -0
  39. {model2vec-0.2.1 → model2vec-0.2.2}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  40. {model2vec-0.2.1 → model2vec-0.2.2}/tests/data/test_tokenizer/tokenizer.json +0 -0
  41. {model2vec-0.2.1 → model2vec-0.2.2}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  42. {model2vec-0.2.1 → model2vec-0.2.2}/tests/test_model.py +0 -0
  43. {model2vec-0.2.1 → model2vec-0.2.2}/tutorials/README.md +0 -0
  44. {model2vec-0.2.1 → model2vec-0.2.2}/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.2
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
@@ -151,7 +151,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
151
151
  m2v_model.save_pretrained("m2v_model")
152
152
  ```
153
153
 
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.
154
+ 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.
155
+
156
+ ```python
157
+ from transformers import AutoModel, AutoTokenizer
158
+
159
+ from model2vec.distill import distill_from_model
160
+
161
+ # Assuming a loaded model and tokenizer
162
+ model_name = "baai/bge-base-en-v1.5"
163
+ model = AutoModel.from_pretrained(model_name)
164
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
165
+
166
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
167
+
168
+ m2v_model.save_pretrained("m2v_model")
169
+
170
+ ```
171
+
172
+ 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
173
 
156
174
  ## What is Model2Vec?
157
175
 
@@ -159,9 +177,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
159
177
 
160
178
  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
179
 
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.
180
+ Model2vec has 3 modes:
181
+ - **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.
182
+ - **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
183
+ - **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
184
 
166
185
  ## Main Features
167
186
 
@@ -287,6 +306,7 @@ print(make_leaderboard(task_scores))
287
306
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
288
307
  | [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
308
  | [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 |
309
+ | [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
310
  | [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
311
  ## Results
292
312
 
@@ -294,13 +314,16 @@ print(make_leaderboard(task_scores))
294
314
 
295
315
  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
316
 
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 |
317
+
318
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
319
+ |------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
320
+ | 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 |
321
+ | 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 |
322
+ | M2V_base_glove | 48.58 | 47.6 | 61.35 | 30.52 | 75.34 | 48.5 | 29.26 | 70.31 | 31.5 | 50.28 | 54.29 |
323
+ | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 |
324
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
325
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
326
+
304
327
 
305
328
  <details>
306
329
  <summary> Task Abbreviations </summary>
@@ -322,21 +345,22 @@ For readability, the MTEB task names are abbreviated as follows:
322
345
 
323
346
  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
347
 
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 |
348
+ | Model | Average | SST2 | IMDB | TREC | AG News |
349
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
350
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
351
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
352
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
353
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
354
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
355
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
356
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
333
357
 
334
358
  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.
335
359
 
336
360
  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
361
  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
362
 
339
- | ![Description](assets/images/speed_vs_accuracy.png) |
363
+ | ![Description](assets/images/speed_vs_accuracy_v2.png) |
340
364
  |:--:|
341
365
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
342
366
 
@@ -88,7 +88,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
88
88
  m2v_model.save_pretrained("m2v_model")
89
89
  ```
90
90
 
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.
91
+ 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.
92
+
93
+ ```python
94
+ from transformers import AutoModel, AutoTokenizer
95
+
96
+ from model2vec.distill import distill_from_model
97
+
98
+ # Assuming a loaded model and tokenizer
99
+ model_name = "baai/bge-base-en-v1.5"
100
+ model = AutoModel.from_pretrained(model_name)
101
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
102
+
103
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
104
+
105
+ m2v_model.save_pretrained("m2v_model")
106
+
107
+ ```
108
+
109
+ 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
110
 
93
111
  ## What is Model2Vec?
94
112
 
@@ -96,9 +114,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
96
114
 
97
115
  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
116
 
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.
117
+ Model2vec has 3 modes:
118
+ - **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.
119
+ - **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
120
+ - **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
121
 
103
122
  ## Main Features
104
123
 
@@ -224,6 +243,7 @@ print(make_leaderboard(task_scores))
224
243
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
225
244
  | [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
245
  | [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 |
246
+ | [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
247
  | [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
248
  ## Results
229
249
 
@@ -231,13 +251,16 @@ print(make_leaderboard(task_scores))
231
251
 
232
252
  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
253
 
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 |
254
+
255
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
256
+ |------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
257
+ | 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 |
258
+ | 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 |
259
+ | M2V_base_glove | 48.58 | 47.6 | 61.35 | 30.52 | 75.34 | 48.5 | 29.26 | 70.31 | 31.5 | 50.28 | 54.29 |
260
+ | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 |
261
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
262
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
263
+
241
264
 
242
265
  <details>
243
266
  <summary> Task Abbreviations </summary>
@@ -259,21 +282,22 @@ For readability, the MTEB task names are abbreviated as follows:
259
282
 
260
283
  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
284
 
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 |
285
+ | Model | Average | SST2 | IMDB | TREC | AG News |
286
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
287
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
288
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
289
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
290
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
291
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
292
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
293
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
270
294
 
271
295
  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.
272
296
 
273
297
  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
298
  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
299
 
276
- | ![Description](assets/images/speed_vs_accuracy.png) |
300
+ | ![Description](assets/images/speed_vs_accuracy_v2.png) |
277
301
  |:--:|
278
302
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
279
303
 
@@ -0,0 +1,3 @@
1
+ from model2vec.distill.distillation import distill, distill_from_model
2
+
3
+ __all__ = ["distill", "distill_from_model"]
@@ -1,8 +1,10 @@
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
5
6
  from sklearn.decomposition import PCA
7
+ from tokenizers.models import BPE, Unigram
6
8
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
7
9
 
8
10
  from model2vec.distill.inference import (
@@ -10,16 +12,21 @@ from model2vec.distill.inference import (
10
12
  create_output_embeddings_from_model_name_and_tokens,
11
13
  )
12
14
  from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
15
+ from model2vec.distill.utils import select_optimal_device
13
16
  from model2vec.model import StaticModel
14
17
 
15
18
  logger = logging.getLogger(__name__)
16
19
 
17
20
 
18
- def distill(
19
- model_name: str,
21
+ PCADimType = int | None | Literal["auto"]
22
+
23
+
24
+ def distill_from_model(
25
+ model: PreTrainedModel,
26
+ tokenizer: PreTrainedTokenizerFast,
20
27
  vocabulary: list[str] | None = None,
21
- device: str = "cpu",
22
- pca_dims: int | None = 256,
28
+ device: str | None = None,
29
+ pca_dims: PCADimType = 256,
23
30
  apply_zipf: bool = True,
24
31
  use_subword: bool = True,
25
32
  ) -> StaticModel:
@@ -32,10 +39,13 @@ def distill(
32
39
  If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
33
40
  If you don't pass a vocabulary, we use the model's tokenizer directly.
34
41
 
35
- :param model_name: The model name to use. Any sentencetransformer compatible model works.
42
+ :param model: The model to use.
43
+ :param tokenizer: The tokenizer to use.
36
44
  :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
37
45
  :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.
46
+ :param pca_dims: The number of components to use for PCA.
47
+ If this is None, we don't apply PCA.
48
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
39
49
  :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
40
50
  :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
51
  :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
@@ -43,45 +53,46 @@ def distill(
43
53
  :return: A StaticModel
44
54
 
45
55
  """
56
+ device = select_optimal_device(device)
46
57
  if not use_subword and vocabulary is None:
47
58
  raise ValueError(
48
59
  "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
49
60
  )
50
61
 
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)
62
+ if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
63
+ raise ValueError(
64
+ "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
65
+ "This is not supported yet."
66
+ "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
67
+ )
68
+
54
69
  # Make a base list of tokens.
55
70
  tokens: list[str] = []
56
71
  if use_subword:
57
72
  # Create the subword embeddings.
58
- tokens, embeddings = create_output_embeddings_from_model_name(
59
- model=original_model, tokenizer=original_tokenizer, device=device
60
- )
73
+ tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
61
74
 
62
75
  # Remove any unused tokens from the tokenizer and embeddings.
63
76
  wrong_tokens = [x for x in tokens if x.startswith("[unused")]
64
- vocab = original_tokenizer.get_vocab()
77
+ vocab = tokenizer.get_vocab()
65
78
  # Get the ids of the unused token.
66
79
  wrong_token_ids = [vocab[token] for token in wrong_tokens]
67
80
  # Remove the unused tokens from the tokenizer.
68
- new_tokenizer = remove_tokens(original_tokenizer.backend_tokenizer, wrong_tokens)
81
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
69
82
  # Remove the embeddings of the unused tokens.
70
83
  embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
71
84
  logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
72
85
  else:
73
86
  # We need to keep the unk token in the tokenizer.
74
- unk_token = original_tokenizer.backend_tokenizer.model.unk_token
87
+ unk_token = tokenizer.backend_tokenizer.model.unk_token
75
88
  # 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
- )
89
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, list(set(tokenizer.get_vocab()) - {unk_token}))
79
90
  # We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
80
91
  embeddings = None
81
92
 
82
- if vocabulary is not None:
93
+ if vocabulary:
83
94
  # Preprocess the vocabulary with the original tokenizer.
84
- preprocessed_vocabulary = preprocess_vocabulary(original_tokenizer.backend_tokenizer, vocabulary)
95
+ preprocessed_vocabulary = preprocess_vocabulary(tokenizer.backend_tokenizer, vocabulary)
85
96
  n_tokens_before = len(preprocessed_vocabulary)
86
97
  # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
87
98
  cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
@@ -93,8 +104,8 @@ def distill(
93
104
  if cleaned_vocabulary:
94
105
  # Create the embeddings.
95
106
  _, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
96
- model=original_model,
97
- tokenizer=original_tokenizer,
107
+ model=model,
108
+ tokenizer=tokenizer,
98
109
  tokens=cleaned_vocabulary,
99
110
  device=device,
100
111
  )
@@ -112,6 +123,8 @@ def distill(
112
123
  # Post process the embeddings by applying PCA and Zipf weighting.
113
124
  embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
114
125
 
126
+ model_name = getattr(model, "name_or_path", "")
127
+
115
128
  config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
116
129
  # Get the language from the model card
117
130
  info = model_info(model_name)
@@ -122,18 +135,65 @@ def distill(
122
135
  )
123
136
 
124
137
 
125
- def _post_process_embeddings(embeddings: np.ndarray, pca_dims: int | None, apply_zipf: bool) -> np.ndarray:
138
+ def distill(
139
+ model_name: str,
140
+ vocabulary: list[str] | None = None,
141
+ device: str | None = None,
142
+ pca_dims: PCADimType = 256,
143
+ apply_zipf: bool = True,
144
+ use_subword: bool = True,
145
+ ) -> StaticModel:
146
+ """
147
+ Distill a staticmodel from a sentence transformer.
148
+
149
+ This function creates a set of embeddings from a sentence transformer. It does this by doing either
150
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
151
+
152
+ If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
153
+ If you don't pass a vocabulary, we use the model's tokenizer directly.
154
+
155
+ :param model_name: The model name to use. Any sentencetransformer compatible model works.
156
+ :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
157
+ :param device: The device to use.
158
+ :param pca_dims: The number of components to use for PCA.
159
+ If this is None, we don't apply PCA.
160
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
161
+ :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
162
+ :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.
163
+ :return: A StaticModel
164
+
165
+ """
166
+ model: PreTrainedModel = AutoModel.from_pretrained(model_name)
167
+ tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
168
+
169
+ return distill_from_model(
170
+ model=model,
171
+ tokenizer=tokenizer,
172
+ vocabulary=vocabulary,
173
+ device=device,
174
+ pca_dims=pca_dims,
175
+ apply_zipf=apply_zipf,
176
+ use_subword=use_subword,
177
+ )
178
+
179
+
180
+ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
126
181
  """Post process embeddings by applying PCA and Zipf weighting."""
127
182
  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]})"
183
+ if pca_dims == "auto":
184
+ pca_dims = embeddings.shape[1]
185
+ if pca_dims > embeddings.shape[1]:
186
+ logger.warning(
187
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
188
+ "Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
189
+ "Applying PCA will probably improve performance, so consider just leaving it."
131
190
  )
191
+ pca_dims = embeddings.shape[1]
132
192
  if pca_dims >= embeddings.shape[0]:
133
193
  logger.warning(
134
194
  f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
135
195
  )
136
- elif pca_dims < embeddings.shape[1]:
196
+ elif pca_dims <= embeddings.shape[1]:
137
197
  logger.info(f"Applying PCA with n_components {pca_dims}")
138
198
 
139
199
  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
 
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+
6
+ from tokenizers import Tokenizer
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def preprocess_vocabulary(tokenizer: Tokenizer, vocabulary: list[str]) -> list[str]:
12
+ """Preprocess a vocabulary with a tokenizer by doing a roundtrip encode/decode."""
13
+ encoded_ids: list[list[int]] = [
14
+ encoding.ids for encoding in tokenizer.encode_batch(vocabulary, add_special_tokens=False)
15
+ ]
16
+ return tokenizer.decode_batch(encoded_ids)
17
+
18
+
19
+ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenizer:
20
+ """
21
+ Remove tokens from a tokenizer.
22
+
23
+ :param tokenizer: The tokenizer to remove tokens from.
24
+ :param tokens_to_remove: The tokens to remove.
25
+ :return: The modified tokenizer.
26
+ :raises ValueError: If the tokenizer model type is not supported.
27
+ """
28
+ model_vocab = set(tokenizer.get_vocab())
29
+ # This triggers when tokens_to_remove is empty or when there is no overlap
30
+ # between the tokens to remove and the model vocabulary.
31
+ if not set(tokens_to_remove).intersection(model_vocab):
32
+ # NOTE: return a copy.
33
+ if tokens_to_remove:
34
+ logger.info("No tokens to remove, none of the tokens were in the vocabulary.")
35
+ else:
36
+ logger.info("No tokens to remove.")
37
+ return Tokenizer.from_str(tokenizer.to_str())
38
+
39
+ tokenizer_data = json.loads(tokenizer.to_str())
40
+
41
+ # Find all added tokens
42
+ added_tokens = tokenizer_data["added_tokens"]
43
+ added_tokens_str = {token["content"] for token in added_tokens}
44
+
45
+ # Remove all added tokens from the list of tokens to remove.
46
+ # Things will go bad if we keep them.
47
+ tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
48
+
49
+ # Load the vocabulary.
50
+ model_type = tokenizer_data["model"]["type"]
51
+
52
+ match model_type:
53
+ case "WordPiece":
54
+ # Vocab is a dictionary.
55
+ vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
56
+ n_tokens = len(vocab)
57
+
58
+ # Remove the tokens.
59
+ for token in tokens_to_remove:
60
+ if vocab.pop(token, None) is None:
61
+ logger.warning(f"Token {token} was not in the vocabulary.")
62
+
63
+ n_removed = n_tokens - len(vocab)
64
+ logger.info(f"Removed {n_removed} tokens from the vocabulary.")
65
+
66
+ # Reindex the vocabulary so that it is contiguous.
67
+ reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
68
+ tokenizer_data["model"]["vocab"] = reindexed
69
+ case "Unigram":
70
+ raise ValueError("Removing tokens from a unigram tokenizer is not supported.")
71
+ case "BPE":
72
+ raise ValueError("Removing tokens from a bpe tokenizer is not supported.")
73
+ case _:
74
+ raise ValueError(f"Unknown model type {model_type}")
75
+
76
+ # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
77
+ special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
78
+ for token, token_data in special_tokens_post_processor.items():
79
+ token_data["ids"] = [reindexed[token] for token in token_data["tokens"]]
80
+
81
+ # Reinitialize the tokenizer from the json.
82
+ tokenizer = Tokenizer.from_str(json.dumps(tokenizer_data))
83
+
84
+ return tokenizer
85
+
86
+
87
+ def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
88
+ """
89
+ Add tokens to a tokenizer.
90
+
91
+ :param tokenizer: The tokenizer to add tokens to.
92
+ :param tokens_to_add: The tokens to add.
93
+ :return: The modified tokenizer.
94
+ :raises ValueError: If the tokenizer model type is not supported.
95
+ """
96
+ data = json.loads(tokenizer.to_str())
97
+
98
+ model = data["model"]["type"]
99
+
100
+ match model:
101
+ case "WordPiece":
102
+ wordpiece_vocab: dict[str, int] = data["model"]["vocab"]
103
+ for token in tokens_to_add:
104
+ if token not in wordpiece_vocab:
105
+ wordpiece_vocab[token] = len(wordpiece_vocab)
106
+ case "Unigram":
107
+ raise ValueError("Adding tokens to a unigram tokenizer is not supported.")
108
+ case "BPE":
109
+ raise ValueError("Adding tokens to a bpe tokenizer is not supported.")
110
+ case _:
111
+ raise ValueError(f"Unknown model type {model}")
112
+
113
+ tokenizer = Tokenizer.from_str(json.dumps(data))
114
+
115
+ return tokenizer
@@ -0,0 +1,26 @@
1
+ from logging import getLogger
2
+
3
+ import torch
4
+
5
+ logger = getLogger(__name__)
6
+
7
+
8
+ def select_optimal_device(device: str | None) -> str:
9
+ """
10
+ Guess what your optimal device should be based on backend availability.
11
+
12
+ If you pass a device, we just pass it through.
13
+
14
+ :param device: The device to use. If this is not None you get back what you passed.
15
+ :return: The selected device.
16
+ """
17
+ if device is None:
18
+ if torch.cuda.is_available():
19
+ device = "cuda"
20
+ elif torch.backends.mps.is_available():
21
+ device = "mps"
22
+ else:
23
+ device = "cpu"
24
+ logger.info(f"Automatically selected device: {device}")
25
+
26
+ return device
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.2.1
3
+ Version: 0.2.2
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
@@ -151,7 +151,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
151
151
  m2v_model.save_pretrained("m2v_model")
152
152
  ```
153
153
 
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.
154
+ 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.
155
+
156
+ ```python
157
+ from transformers import AutoModel, AutoTokenizer
158
+
159
+ from model2vec.distill import distill_from_model
160
+
161
+ # Assuming a loaded model and tokenizer
162
+ model_name = "baai/bge-base-en-v1.5"
163
+ model = AutoModel.from_pretrained(model_name)
164
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
165
+
166
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
167
+
168
+ m2v_model.save_pretrained("m2v_model")
169
+
170
+ ```
171
+
172
+ 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
173
 
156
174
  ## What is Model2Vec?
157
175
 
@@ -159,9 +177,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
159
177
 
160
178
  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
179
 
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.
180
+ Model2vec has 3 modes:
181
+ - **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.
182
+ - **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
183
+ - **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
184
 
166
185
  ## Main Features
167
186
 
@@ -287,6 +306,7 @@ print(make_leaderboard(task_scores))
287
306
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
288
307
  | [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
308
  | [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 |
309
+ | [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
310
  | [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
311
  ## Results
292
312
 
@@ -294,13 +314,16 @@ print(make_leaderboard(task_scores))
294
314
 
295
315
  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
316
 
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 |
317
+
318
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
319
+ |------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
320
+ | 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 |
321
+ | 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 |
322
+ | M2V_base_glove | 48.58 | 47.6 | 61.35 | 30.52 | 75.34 | 48.5 | 29.26 | 70.31 | 31.5 | 50.28 | 54.29 |
323
+ | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 |
324
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
325
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
326
+
304
327
 
305
328
  <details>
306
329
  <summary> Task Abbreviations </summary>
@@ -322,21 +345,22 @@ For readability, the MTEB task names are abbreviated as follows:
322
345
 
323
346
  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
347
 
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 |
348
+ | Model | Average | SST2 | IMDB | TREC | AG News |
349
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
350
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
351
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
352
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
353
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
354
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
355
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
356
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
333
357
 
334
358
  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.
335
359
 
336
360
  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
361
  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
362
 
339
- | ![Description](assets/images/speed_vs_accuracy.png) |
363
+ | ![Description](assets/images/speed_vs_accuracy_v2.png) |
340
364
  |:--:|
341
365
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
342
366
 
@@ -10,6 +10,7 @@ assets/images/logo.png
10
10
  assets/images/model2vec_model_diagram.png
11
11
  assets/images/sentences_per_second_vs_average_score.png
12
12
  assets/images/speed_vs_accuracy.png
13
+ assets/images/speed_vs_accuracy_v2.png
13
14
  assets/images/tutorial_ezlo.png
14
15
  model2vec/__init__.py
15
16
  model2vec/model.py
@@ -25,6 +26,7 @@ model2vec/distill/__main__.py
25
26
  model2vec/distill/distillation.py
26
27
  model2vec/distill/inference.py
27
28
  model2vec/distill/tokenizer.py
29
+ model2vec/distill/utils.py
28
30
  tests/__init__.py
29
31
  tests/conftest.py
30
32
  tests/test_distillation.py
@@ -3,7 +3,7 @@ name = "model2vec"
3
3
  description = "Distill a Small Fast Model from any Sentence Transformer"
4
4
  readme = { file = "README.md", content-type = "text/markdown" }
5
5
  license = { file = "LICENSE" }
6
- version = "0.2.1"
6
+ version = "0.2.2"
7
7
  requires-python = ">=3.10"
8
8
  authors = [{ name = "Stéphan Tulkens", email = "stephantul@gmail.com"}, {name = "Thomas van Dongen", email = "thomas123@live.nl"}]
9
9
 
@@ -9,7 +9,7 @@ import torch
9
9
  from tokenizers import Tokenizer
10
10
  from tokenizers.models import WordLevel
11
11
  from tokenizers.pre_tokenizers import Whitespace
12
- from transformers import AutoModel, BertTokenizerFast
12
+ from transformers import AutoModel, AutoTokenizer
13
13
 
14
14
 
15
15
  @pytest.fixture
@@ -26,10 +26,9 @@ def mock_tokenizer() -> Tokenizer:
26
26
 
27
27
 
28
28
  @pytest.fixture
29
- def mock_berttokenizer() -> BertTokenizerFast:
29
+ def mock_berttokenizer() -> AutoTokenizer:
30
30
  """Load the real BertTokenizerFast from the provided tokenizer.json file."""
31
- tokenizer_path = Path("tests/data/test_tokenizer/tokenizer.json")
32
- return BertTokenizerFast(tokenizer_file=str(tokenizer_path))
31
+ return AutoTokenizer.from_pretrained("tests/data/test_tokenizer")
33
32
 
34
33
 
35
34
  @pytest.fixture
@@ -39,6 +38,7 @@ def mock_transformer() -> AutoModel:
39
38
  class MockPreTrainedModel:
40
39
  def __init__(self) -> None:
41
40
  self.device = "cpu"
41
+ self.name_or_path = "mock-model"
42
42
 
43
43
  def to(self, device: str) -> MockPreTrainedModel:
44
44
  self.device = device
@@ -1,3 +1,4 @@
1
+ import json
1
2
  from importlib import import_module
2
3
  from unittest.mock import MagicMock, patch
3
4
 
@@ -6,12 +7,88 @@ import pytest
6
7
  from pytest import LogCaptureFixture
7
8
  from transformers import AutoModel, BertTokenizerFast
8
9
 
9
- from model2vec.distill.distillation import _clean_vocabulary, _post_process_embeddings, distill
10
+ from model2vec.distill.distillation import _clean_vocabulary, _post_process_embeddings, distill, distill_from_model
10
11
  from model2vec.model import StaticModel
11
12
 
12
13
  rng = np.random.default_rng()
13
14
 
14
15
 
16
+ @pytest.mark.parametrize(
17
+ "vocabulary, use_subword, pca_dims, apply_zipf",
18
+ [
19
+ (None, True, 256, True), # Output vocab with subwords, PCA applied
20
+ (
21
+ ["wordA", "wordB"],
22
+ False,
23
+ 4,
24
+ False,
25
+ ), # Custom vocab without subword , PCA applied
26
+ (["wordA", "wordB"], True, 4, False), # Custom vocab with subword, PCA applied
27
+ (None, True, "auto", False), # Subword, PCA set to 'auto'
28
+ (None, True, 1024, False), # Subword, PCA set to high number.
29
+ (None, True, None, True), # No PCA applied
30
+ (["wordA", "wordB"], False, 4, True), # Custom vocab without subwords PCA and Zipf applied
31
+ (None, False, 256, True), # use_subword = False without passing a vocabulary should raise an error
32
+ ],
33
+ )
34
+ @patch.object(import_module("model2vec.distill.distillation"), "model_info")
35
+ @patch("transformers.AutoModel.from_pretrained")
36
+ def test_distill_from_model(
37
+ mock_auto_model: MagicMock,
38
+ mock_model_info: MagicMock,
39
+ mock_berttokenizer: BertTokenizerFast,
40
+ mock_transformer: AutoModel,
41
+ vocabulary: list[str] | None,
42
+ use_subword: bool,
43
+ pca_dims: int | None,
44
+ apply_zipf: bool,
45
+ ) -> None:
46
+ """Test distill function with different parameters."""
47
+ # Mock the return value of model_info to avoid calling the Hugging Face API
48
+ mock_model_info.return_value = type("ModelInfo", (object,), {"cardData": {"language": "en"}})
49
+
50
+ # Patch the tokenizers and models to return the real BertTokenizerFast and mock model instances
51
+ # mock_auto_tokenizer.return_value = mock_berttokenizer
52
+ mock_auto_model.return_value = mock_transformer
53
+
54
+ if vocabulary is None and not use_subword:
55
+ with pytest.raises(ValueError):
56
+ static_model = distill_from_model(
57
+ model=mock_transformer,
58
+ tokenizer=mock_berttokenizer,
59
+ vocabulary=vocabulary,
60
+ device="cpu",
61
+ pca_dims=pca_dims,
62
+ apply_zipf=apply_zipf,
63
+ use_subword=use_subword,
64
+ )
65
+ else:
66
+ # Call the distill function with the parametrized inputs
67
+ static_model = distill_from_model(
68
+ model=mock_transformer,
69
+ tokenizer=mock_berttokenizer,
70
+ vocabulary=vocabulary,
71
+ device="cpu",
72
+ pca_dims=pca_dims,
73
+ apply_zipf=apply_zipf,
74
+ use_subword=use_subword,
75
+ )
76
+
77
+ static_model2 = distill(
78
+ model_name="tests/data/test_tokenizer",
79
+ vocabulary=vocabulary,
80
+ device="cpu",
81
+ pca_dims=pca_dims,
82
+ apply_zipf=apply_zipf,
83
+ use_subword=use_subword,
84
+ )
85
+
86
+ assert static_model.embedding.weight.shape == static_model2.embedding.weight.shape
87
+ assert static_model.config == static_model2.config
88
+ assert json.loads(static_model.tokenizer.to_str()) == json.loads(static_model2.tokenizer.to_str())
89
+ assert static_model.base_model_name == static_model2.base_model_name
90
+
91
+
15
92
  @pytest.mark.parametrize(
16
93
  "vocabulary, use_subword, pca_dims, apply_zipf, expected_shape",
17
94
  [
@@ -23,6 +100,8 @@ rng = np.random.default_rng()
23
100
  False,
24
101
  (7, 4),
25
102
  ), # Custom vocab without subword , PCA applied
103
+ (None, True, "auto", False, (29528, 768)), # Subword, PCA set to 'auto'
104
+ (None, True, 1024, False, (29528, 768)), # Subword, PCA set to high number.
26
105
  (["wordA", "wordB"], True, 4, False, (29530, 4)), # Custom vocab with subword, PCA applied
27
106
  (None, True, None, True, (29528, 768)), # No PCA applied
28
107
  (["wordA", "wordB"], False, 4, True, (7, 4)), # Custom vocab without subwords PCA and Zipf applied
@@ -30,13 +109,10 @@ rng = np.random.default_rng()
30
109
  ],
31
110
  )
32
111
  @patch.object(import_module("model2vec.distill.distillation"), "model_info")
33
- @patch("transformers.AutoTokenizer.from_pretrained")
34
112
  @patch("transformers.AutoModel.from_pretrained")
35
113
  def test_distill(
36
114
  mock_auto_model: MagicMock,
37
- mock_auto_tokenizer: MagicMock,
38
115
  mock_model_info: MagicMock,
39
- mock_berttokenizer: BertTokenizerFast,
40
116
  mock_transformer: AutoModel,
41
117
  vocabulary: list[str] | None,
42
118
  use_subword: bool,
@@ -49,10 +125,9 @@ def test_distill(
49
125
  mock_model_info.return_value = type("ModelInfo", (object,), {"cardData": {"language": "en"}})
50
126
 
51
127
  # Patch the tokenizers and models to return the real BertTokenizerFast and mock model instances
52
- mock_auto_tokenizer.return_value = mock_berttokenizer
53
128
  mock_auto_model.return_value = mock_transformer
54
129
 
55
- model_name = "mock-model"
130
+ model_name = "tests/data/test_tokenizer"
56
131
 
57
132
  if vocabulary is None and not use_subword:
58
133
  with pytest.raises(ValueError):
@@ -0,0 +1,52 @@
1
+ from pathlib import Path
2
+ from tempfile import NamedTemporaryFile
3
+ from unittest.mock import patch
4
+
5
+ import pytest
6
+
7
+ from model2vec.distill.utils import select_optimal_device
8
+ from model2vec.utils import _get_metadata_from_readme
9
+
10
+
11
+ def test__get_metadata_from_readme_not_exists() -> None:
12
+ """Test getting metadata from a README."""
13
+ assert _get_metadata_from_readme(Path("zzz")) == {}
14
+
15
+
16
+ def test__get_metadata_from_readme_mocked_file() -> None:
17
+ """Test getting metadata from a README."""
18
+ with NamedTemporaryFile() as f:
19
+ f.write(b"---\nkey: value\n---\n")
20
+ f.flush()
21
+ assert _get_metadata_from_readme(Path(f.name))["key"] == "value"
22
+
23
+
24
+ def test__get_metadata_from_readme_mocked_file_keys() -> None:
25
+ """Test getting metadata from a README."""
26
+ with NamedTemporaryFile() as f:
27
+ f.write(b"")
28
+ f.flush()
29
+ assert set(_get_metadata_from_readme(Path(f.name))) == set()
30
+
31
+
32
+ @pytest.mark.parametrize(
33
+ "device, expected, cuda, mps",
34
+ [
35
+ ("cpu", "cpu", True, True),
36
+ ("cpu", "cpu", True, False),
37
+ ("cpu", "cpu", False, True),
38
+ ("cpu", "cpu", False, False),
39
+ ("clown", "clown", False, False),
40
+ (None, "cuda", True, True),
41
+ (None, "cuda", True, False),
42
+ (None, "mps", False, True),
43
+ (None, "cpu", False, False),
44
+ ],
45
+ )
46
+ def test_select_optimal_device(device: str | None, expected: str, cuda: bool, mps: bool) -> None:
47
+ """Test whether the optimal device is selected."""
48
+ with (
49
+ patch("torch.cuda.is_available", return_value=cuda),
50
+ patch("torch.backends.mps.is_available", return_value=mps),
51
+ ):
52
+ assert select_optimal_device(device) == expected
@@ -433,7 +433,7 @@ wheels = [
433
433
 
434
434
  [[package]]
435
435
  name = "model2vec"
436
- version = "0.1.2"
436
+ version = "0.2.1"
437
437
  source = { editable = "." }
438
438
  dependencies = [
439
439
  { name = "click" },
@@ -1,3 +0,0 @@
1
- from model2vec.distill.__main__ import distill
2
-
3
- __all__ = ["distill"]
@@ -1,80 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import json
4
- import logging
5
-
6
- from tokenizers import Tokenizer
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- def preprocess_vocabulary(tokenizer: Tokenizer, vocabulary: list[str]) -> list[str]:
12
- """Preprocess a vocabulary with a tokenizer by doing a roundtrip encode/decode."""
13
- encoded_ids: list[list[int]] = [
14
- encoding.ids for encoding in tokenizer.encode_batch(vocabulary, add_special_tokens=False)
15
- ]
16
- return tokenizer.decode_batch(encoded_ids)
17
-
18
-
19
- def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenizer:
20
- """
21
- Remove tokens from a tokenizer.
22
-
23
- :param tokenizer: The tokenizer to remove tokens from.
24
- :param tokens_to_remove: The tokens to remove.
25
- :return: The modified tokenizer.
26
- """
27
- tokenizer_data = json.loads(tokenizer.to_str())
28
-
29
- # Find all added tokens
30
- added_tokens = tokenizer_data["added_tokens"]
31
- added_tokens_str = {token["content"] for token in added_tokens}
32
-
33
- # Remove all added tokens from the list of tokens to remove.
34
- # Things will go bad if we keep them.
35
- tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
36
-
37
- # Load the vocabulary.
38
- vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
39
- n_tokens = len(vocab)
40
-
41
- # Remove the tokens.
42
- for token in tokens_to_remove:
43
- if vocab.pop(token, None) is None:
44
- logger.warning(f"Token {token} was not in the vocabulary.")
45
-
46
- n_removed = n_tokens - len(vocab)
47
- logger.info(f"Removed {n_removed} tokens from the vocabulary.")
48
-
49
- # Reindex the vocabulary so that it is contiguous.
50
- reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
51
- tokenizer_data["model"]["vocab"] = reindexed
52
-
53
- # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
54
- special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
55
- for token, token_data in special_tokens_post_processor.items():
56
- token_data["ids"] = [reindexed[token] for token in token_data["tokens"]]
57
-
58
- # Reinitialize the tokenizer from the json.
59
- tokenizer = Tokenizer.from_str(json.dumps(tokenizer_data))
60
-
61
- return tokenizer
62
-
63
-
64
- def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
65
- """
66
- Add tokens to a tokenizer.
67
-
68
- :param tokenizer: The tokenizer to add tokens to.
69
- :param tokens_to_add: The tokens to add.
70
- :return: The modified tokenizer.
71
- """
72
- data = json.loads(tokenizer.to_str())
73
-
74
- vocab: dict[str, int] = data["model"]["vocab"]
75
- for token in tokens_to_add:
76
- vocab[token] = len(vocab)
77
-
78
- tokenizer = Tokenizer.from_str(json.dumps(data))
79
-
80
- return tokenizer
@@ -1,25 +0,0 @@
1
- from pathlib import Path
2
- from tempfile import NamedTemporaryFile
3
-
4
- from model2vec.utils import _get_metadata_from_readme
5
-
6
-
7
- def test__get_metadata_from_readme_not_exists() -> None:
8
- """Test getting metadata from a README."""
9
- assert _get_metadata_from_readme(Path("zzz")) == {}
10
-
11
-
12
- def test__get_metadata_from_readme_mocked_file() -> None:
13
- """Test getting metadata from a README."""
14
- with NamedTemporaryFile() as f:
15
- f.write(b"---\nkey: value\n---\n")
16
- f.flush()
17
- assert _get_metadata_from_readme(Path(f.name))["key"] == "value"
18
-
19
-
20
- def test__get_metadata_from_readme_mocked_file_keys() -> None:
21
- """Test getting metadata from a README."""
22
- with NamedTemporaryFile() as f:
23
- f.write(b"")
24
- f.flush()
25
- assert set(_get_metadata_from_readme(Path(f.name))) == set()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes