model2vec 0.2.0__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.0 → model2vec-0.2.2}/.gitignore +1 -0
  2. {model2vec-0.2.0 → model2vec-0.2.2}/PKG-INFO +49 -21
  3. {model2vec-0.2.0 → model2vec-0.2.2}/README.md +48 -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.0 → model2vec-0.2.2}/model2vec/distill/distillation.py +87 -27
  7. {model2vec-0.2.0 → 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.0 → model2vec-0.2.2}/model2vec/model.py +5 -0
  11. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec.egg-info/PKG-INFO +49 -21
  12. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec.egg-info/SOURCES.txt +2 -0
  13. {model2vec-0.2.0 → model2vec-0.2.2}/pyproject.toml +1 -1
  14. {model2vec-0.2.0 → model2vec-0.2.2}/tests/conftest.py +4 -4
  15. {model2vec-0.2.0 → model2vec-0.2.2}/tests/test_distillation.py +81 -6
  16. model2vec-0.2.2/tests/test_utils.py +52 -0
  17. {model2vec-0.2.0 → model2vec-0.2.2}/uv.lock +1 -1
  18. model2vec-0.2.0/model2vec/distill/__init__.py +0 -3
  19. model2vec-0.2.0/model2vec/distill/tokenizer.py +0 -80
  20. model2vec-0.2.0/tests/test_utils.py +0 -25
  21. {model2vec-0.2.0 → model2vec-0.2.2}/.github/workflows/ci.yaml +0 -0
  22. {model2vec-0.2.0 → model2vec-0.2.2}/.pre-commit-config.yaml +0 -0
  23. {model2vec-0.2.0 → model2vec-0.2.2}/LICENSE +0 -0
  24. {model2vec-0.2.0 → model2vec-0.2.2}/Makefile +0 -0
  25. {model2vec-0.2.0 → model2vec-0.2.2}/assets/images/logo.png +0 -0
  26. {model2vec-0.2.0 → model2vec-0.2.2}/assets/images/model2vec_model_diagram.png +0 -0
  27. {model2vec-0.2.0 → model2vec-0.2.2}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  28. {model2vec-0.2.0 → model2vec-0.2.2}/assets/images/speed_vs_accuracy.png +0 -0
  29. {model2vec-0.2.0 → model2vec-0.2.2}/assets/images/tutorial_ezlo.png +0 -0
  30. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec/__init__.py +0 -0
  31. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec/distill/__main__.py +0 -0
  32. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec/model_card_template.md +0 -0
  33. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec/utils.py +0 -0
  34. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec.egg-info/dependency_links.txt +0 -0
  35. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec.egg-info/requires.txt +0 -0
  36. {model2vec-0.2.0 → model2vec-0.2.2}/model2vec.egg-info/top_level.txt +0 -0
  37. {model2vec-0.2.0 → model2vec-0.2.2}/setup.cfg +0 -0
  38. {model2vec-0.2.0 → model2vec-0.2.2}/tests/__init__.py +0 -0
  39. {model2vec-0.2.0 → model2vec-0.2.2}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  40. {model2vec-0.2.0 → model2vec-0.2.2}/tests/data/test_tokenizer/tokenizer.json +0 -0
  41. {model2vec-0.2.0 → model2vec-0.2.2}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  42. {model2vec-0.2.0 → model2vec-0.2.2}/tests/test_model.py +0 -0
  43. {model2vec-0.2.0 → model2vec-0.2.2}/tutorials/README.md +0 -0
  44. {model2vec-0.2.0 → 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.0
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
@@ -87,6 +87,10 @@ Requires-Dist: ruff; extra == "dev"
87
87
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
88
88
  <a href="https://pepy.tech/project/model2vec">
89
89
  <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
90
+ </a>
91
+ <a href="https://app.codecov.io/gh/MinishLab/model2vec">
92
+ <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
93
+ </a>
90
94
  </a>
91
95
  <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
92
96
  </h2>
@@ -147,7 +151,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
147
151
  m2v_model.save_pretrained("m2v_model")
148
152
  ```
149
153
 
150
- 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.
151
173
 
152
174
  ## What is Model2Vec?
153
175
 
@@ -155,9 +177,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
155
177
 
156
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.
157
179
 
158
- Model2vec has 2 modes:
159
- - **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.
160
- - **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.
161
184
 
162
185
  ## Main Features
163
186
 
@@ -283,6 +306,7 @@ print(make_leaderboard(task_scores))
283
306
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
284
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 |
285
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 |
286
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 |
287
311
  ## Results
288
312
 
@@ -290,13 +314,16 @@ print(make_leaderboard(task_scores))
290
314
 
291
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.
292
316
 
293
- | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
294
- |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
295
- | 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 |
296
- | 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 |
297
- | 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 |
298
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
299
- | 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
+
300
327
 
301
328
  <details>
302
329
  <summary> Task Abbreviations </summary>
@@ -318,21 +345,22 @@ For readability, the MTEB task names are abbreviated as follows:
318
345
 
319
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.
320
347
 
321
- | model | Average | sst2 | imdb | trec | ag_news |
322
- |:-----------------|----------:|---------:|-------:|---------:|----------:|
323
- | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
324
- | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
325
- | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
326
- | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
327
- | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
328
- | 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 |
329
357
 
330
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.
331
359
 
332
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).
333
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.
334
362
 
335
- | ![Description](assets/images/speed_vs_accuracy.png) |
363
+ | ![Description](assets/images/speed_vs_accuracy_v2.png) |
336
364
  |:--:|
337
365
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
338
366
 
@@ -24,6 +24,10 @@
24
24
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
25
25
  <a href="https://pepy.tech/project/model2vec">
26
26
  <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
27
+ </a>
28
+ <a href="https://app.codecov.io/gh/MinishLab/model2vec">
29
+ <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
30
+ </a>
27
31
  </a>
28
32
  <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
29
33
  </h2>
@@ -84,7 +88,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
84
88
  m2v_model.save_pretrained("m2v_model")
85
89
  ```
86
90
 
87
- 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.
88
110
 
89
111
  ## What is Model2Vec?
90
112
 
@@ -92,9 +114,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
92
114
 
93
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.
94
116
 
95
- Model2vec has 2 modes:
96
- - **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.
97
- - **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.
98
121
 
99
122
  ## Main Features
100
123
 
@@ -220,6 +243,7 @@ print(make_leaderboard(task_scores))
220
243
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
221
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 |
222
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 |
223
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 |
224
248
  ## Results
225
249
 
@@ -227,13 +251,16 @@ print(make_leaderboard(task_scores))
227
251
 
228
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.
229
253
 
230
- | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
231
- |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
232
- | 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 |
233
- | 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 |
234
- | 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 |
235
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
236
- | 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
+
237
264
 
238
265
  <details>
239
266
  <summary> Task Abbreviations </summary>
@@ -255,21 +282,22 @@ For readability, the MTEB task names are abbreviated as follows:
255
282
 
256
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.
257
284
 
258
- | model | Average | sst2 | imdb | trec | ag_news |
259
- |:-----------------|----------:|---------:|-------:|---------:|----------:|
260
- | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
261
- | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
262
- | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
263
- | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
264
- | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
265
- | 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 |
266
294
 
267
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.
268
296
 
269
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).
270
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.
271
299
 
272
- | ![Description](assets/images/speed_vs_accuracy.png) |
300
+ | ![Description](assets/images/speed_vs_accuracy_v2.png) |
273
301
  |:--:|
274
302
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
275
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