model2vec 0.1.0__tar.gz → 0.1.1__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 (31) hide show
  1. {model2vec-0.1.0 → model2vec-0.1.1}/.gitignore +0 -2
  2. model2vec-0.1.1/PKG-INFO +333 -0
  3. model2vec-0.1.1/README.md +270 -0
  4. model2vec-0.1.1/assets/images/sentences_per_second_vs_average_score.png +0 -0
  5. model2vec-0.1.1/assets/images/speed_vs_accuracy.png +0 -0
  6. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/distill/__main__.py +9 -5
  7. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/model.py +80 -36
  8. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/utils.py +10 -12
  9. model2vec-0.1.1/model2vec.egg-info/PKG-INFO +333 -0
  10. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec.egg-info/SOURCES.txt +1 -0
  11. {model2vec-0.1.0 → model2vec-0.1.1}/pyproject.toml +1 -1
  12. {model2vec-0.1.0 → model2vec-0.1.1}/tests/test_model.py +46 -18
  13. model2vec-0.1.1/uv.lock +1481 -0
  14. model2vec-0.1.0/PKG-INFO +0 -307
  15. model2vec-0.1.0/README.md +0 -244
  16. model2vec-0.1.0/assets/images/sentences_per_second_vs_average_score.png +0 -0
  17. model2vec-0.1.0/model2vec.egg-info/PKG-INFO +0 -307
  18. model2vec-0.1.0/uv.lock +0 -2816
  19. {model2vec-0.1.0 → model2vec-0.1.1}/.pre-commit-config.yaml +0 -0
  20. {model2vec-0.1.0 → model2vec-0.1.1}/LICENSE +0 -0
  21. {model2vec-0.1.0 → model2vec-0.1.1}/Makefile +0 -0
  22. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/__init__.py +0 -0
  23. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/distill/__init__.py +0 -0
  24. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/distill/inference.py +0 -0
  25. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec/distill/tokenizer.py +0 -0
  26. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec.egg-info/dependency_links.txt +0 -0
  27. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec.egg-info/requires.txt +0 -0
  28. {model2vec-0.1.0 → model2vec-0.1.1}/model2vec.egg-info/top_level.txt +0 -0
  29. {model2vec-0.1.0 → model2vec-0.1.1}/setup.cfg +0 -0
  30. {model2vec-0.1.0 → model2vec-0.1.1}/tests/__init__.py +0 -0
  31. {model2vec-0.1.0 → model2vec-0.1.1}/tests/conftest.py +0 -0
@@ -1,5 +1,3 @@
1
- local/*
2
-
3
1
  # Byte-compiled / optimized / DLL files
4
2
  __pycache__/
5
3
  *.py[cod]
@@ -0,0 +1,333 @@
1
+ Metadata-Version: 2.1
2
+ Name: model2vec
3
+ Version: 0.1.1
4
+ Summary: Distill a Small Fast Model from any Sentence Transformer
5
+ Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Thomas van Dongen
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/MinishLab
29
+ Project-URL: Bug Reports, https://github.com/MinishLab/model2vec/issues
30
+ Project-URL: Source, https://github.com/MinishLab/model2vec
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
35
+ Classifier: Topic :: Software Development :: Libraries
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Programming Language :: Python :: 3 :: Only
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Natural Language :: English
42
+ Requires-Python: >=3.10
43
+ Description-Content-Type: text/markdown
44
+ License-File: LICENSE
45
+ Requires-Dist: click
46
+ Requires-Dist: numpy
47
+ Requires-Dist: rich
48
+ Requires-Dist: tqdm
49
+ Requires-Dist: typer
50
+ Requires-Dist: transformers
51
+ Requires-Dist: torch
52
+ Requires-Dist: sentence_transformers
53
+ Requires-Dist: tokenizers
54
+ Requires-Dist: scikit-learn
55
+ Provides-Extra: dev
56
+ Requires-Dist: black; extra == "dev"
57
+ Requires-Dist: ipython; extra == "dev"
58
+ Requires-Dist: mypy; extra == "dev"
59
+ Requires-Dist: pre-commit; extra == "dev"
60
+ Requires-Dist: pytest; extra == "dev"
61
+ Requires-Dist: pytest-coverage; extra == "dev"
62
+ Requires-Dist: ruff; extra == "dev"
63
+
64
+ # Model2Vec: Distill a Small Fast Model from any Sentence Transformer
65
+
66
+ **Model2Vec** is a method to distill a small, fast model from any Sentence Transformer model.
67
+
68
+ | ![Description](assets/images/speed_vs_accuracy.png) |
69
+ |:--:|
70
+ |*Model2vec allows you to create really fast small models that still perform well.*|
71
+
72
+
73
+ ## Table of Contents
74
+ - [Quickstart](#quickstart)
75
+ - [What is Model2Vec?](#what-is-model2vec)
76
+ - [Main Features](#main-features)
77
+ - [Usage](#usage)
78
+ - [Distilling a Model2Vec model](#distilling-a-model2vec-model)
79
+ - [Inferencing a Model2Vec model](#inference-with-a-model2vec-model)
80
+ - [Evaluating a Model2Vec model](#evaluating-a-model2vec-model)
81
+ - [Model List](#model-list)
82
+ - [Results](#results)
83
+ - [Related Work](#related-work)
84
+ - [Citing](#citing)
85
+
86
+ ## Quickstart
87
+
88
+ Install the package with:
89
+ ```bash
90
+ pip install model2vec
91
+ ```
92
+
93
+ The easiest way to get started with Model2Vec is to download one of our [flagship models from the HuggingFace hub](https://huggingface.co/minishlab). These models are pre-trained and ready to use. The following code snippet shows how to load a model and make embeddings:
94
+ ```python
95
+ from model2vec import StaticModel
96
+
97
+ # Load a model from the HuggingFace hub (in this case the M2V_base_output model)
98
+ model_name = "minishlab/M2V_base_output"
99
+ model = StaticModel.from_pretrained(model_name)
100
+
101
+ # Make embeddings
102
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
103
+ ```
104
+
105
+ And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
106
+
107
+ Instead of using on of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
108
+ ```python
109
+ from model2vec.distill import distill
110
+
111
+ # Choose a Sentence Transformer model
112
+ model_name = "BAAI/bge-base-en-v1.5"
113
+
114
+ # Distill the model
115
+ m2v_model = distill(model_name=model_name, pca_dims=256)
116
+
117
+ # Save the model
118
+ m2v_model.save_pretrained("m2v_model")
119
+ ```
120
+
121
+ 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.
122
+
123
+ ## What is Model2Vec?
124
+
125
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Best of all, you don't need _any_ data to distill a model using Model2Vec.
126
+
127
+ 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.
128
+
129
+ Model2vec has 2 modes:
130
+ - **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.
131
+ - **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.
132
+
133
+ ## Main Features
134
+
135
+ Model2Vec is:
136
+
137
+ - **Small**: reduces the size of a Sentence Transformer model by a factor of 15, from 120M params, down to 7.5M (30 MB on disk!).
138
+ - **Static, but better**: smaller than GLoVe, but much more performant, even with the same vocabulary.
139
+ - **Fast distillation**: make your own model in 30 seconds.
140
+ - **Fast inference**: up to 500 times faster on CPU than the original model. Go green or go home.
141
+ - **No data needed**: Distillation happens directly on the token level, so no dataset is needed.
142
+ - **Simple to use**: An easy to use interface for distilling and inferencing.
143
+ - **Bring your own model**: Can be applied to any Sentence Transformer model.
144
+ - **Bring your own vocabulary**: Can be applied to any vocabulary, allowing you to use your own domain-specific vocabulary. Need biomedical? Just get a medical dictionary, a biomedical model, and inference it.
145
+ - **Multi-lingual**: Use any language. Need a French model? [Pick one](https://huggingface.co/models?library=sentence-transformers&language=fr&sort=trending). Need multilingual? [Here you go](https://huggingface.co/sentence-transformers/LaBSE).
146
+ - **Tightly integrated with HuggingFace hub**: easily share and load models from the HuggingFace hub, using the familiar `from_pretrained` and `push_to_hub`. Our own models can be found [here](https://huggingface.co/minishlab). Feel free to share your own.
147
+ - **Easy Evaluation**: evaluate your models on MTEB and some of our own tasks to measure the performance of the distilled model. Model2Vec models work out of the box on [MTEB](https://huggingface.co/spaces/mteb/leaderboard).
148
+
149
+ ## Usage
150
+
151
+ ### Distilling a Model2Vec model
152
+
153
+ Distilling a model from the output embeddings of a Sentence Transformer model. As mentioned above, this leads to really small model that might be less performant.
154
+ ```python
155
+ from model2vec.distill import distill
156
+
157
+ # Choose a Sentence Transformer model
158
+ model_name = "BAAI/bge-base-en-v1.5"
159
+
160
+ # Distill the model
161
+ m2v_model = distill(model_name=model_name, pca_dims=256)
162
+
163
+ # Save the model
164
+ m2v_model.save_pretrained("m2v_model")
165
+
166
+ ```
167
+
168
+ If you pass a vocabulary, you get a set of static word embeddings, together with a custom tokenizer for exactly that vocabulary. This is comparable to how you would use GLoVe or traditional word2vec, but doesn't actually require a corpus or data.
169
+ ```python
170
+ from model2vec.distill import distill
171
+
172
+ # Load a vocabulary as a list of strings
173
+ vocabulary = ["word1", "word2", "word3"]
174
+ # Choose a Sentence Transformer model
175
+ model_name = "BAAI/bge-base-en-v1.5"
176
+
177
+ # Distill the model with the custom vocabulary
178
+ m2v_model = distill(model_name=model_name,
179
+ vocabulary=vocabulary,
180
+ pca_dims=None,
181
+ apply_zipf=True)
182
+
183
+ # Save the model
184
+ m2v_model.save_pretrained("m2v_model")
185
+
186
+ # Or push it to the hub
187
+ m2v_model.push_to_hub("my_organization/my_model", token="<it's a secret to everybody>")
188
+ ```
189
+
190
+ **Important note:** we assume the passed vocabulary is sorted in rank frequency. i.e., we don't care about the actual word frequencies, but do assume that the most frequent word is first, and the least frequent word is last. If you're not sure whether this is case, set `apply_zipf` to `False`. This disables the weighting, but will also make performance a little bit worse.
191
+
192
+ We also provide a command line interface for distillation. Note that `vocab.txt` should be a file with one word per line.
193
+ ```bash
194
+ python3 -m model2vec.distill --model-name BAAI/bge-base-en-v1.5 --vocabulary-path vocab.txt --device mps --save-path model2vec_model
195
+ ```
196
+
197
+ ### Inference with a Model2Vec model
198
+ Inference works as follows. The example shows one of our own models, but you can also just load a local one, or another one from the hub.
199
+ ```python
200
+ from model2vec import StaticModel
201
+
202
+ # Load a model from the HuggingFace hub, or a local one.
203
+ model_name = "minishlab/M2V_base_output"
204
+ # You can optionally pass a token if you're loading a private model
205
+ model = StaticModel.from_pretrained(model_name, token=None)
206
+
207
+ # Make embeddings
208
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
209
+ ```
210
+
211
+ ### Evaluating a Model2Vec model
212
+
213
+ Our models can be evaluated using our [evaluation package](https://github.com/MinishLab/evaluation). To run this, first install the optional evaluation package:
214
+ ```bash
215
+ pip install evaluation@git+https://github.com/MinishLab/evaluation@main
216
+ ```
217
+
218
+ Then, the following code snippet shows how to evaluate a Model2Vec model:
219
+ ```python
220
+ from model2vec import StaticModel
221
+
222
+ from evaluation import CustomMTEB, get_tasks, parse_mteb_results, make_leaderboard, summarize_results
223
+ from mteb import ModelMeta
224
+
225
+ # Get all available tasks
226
+ tasks = get_tasks()
227
+ # Define the CustomMTEB object with the specified tasks
228
+ evaluation = CustomMTEB(tasks=tasks)
229
+
230
+ # Load the model
231
+ model_name = "m2v_model"
232
+ model = StaticModel.from_pretrained(model_name)
233
+
234
+ # Optionally, add model metadata in MTEB format
235
+ model.mteb_model_meta = ModelMeta(
236
+ name=model_name, revision="no_revision_available", release_date=None, languages=None
237
+ )
238
+
239
+ # Run the evaluation
240
+ results = evaluation.run(model, eval_splits=["test"], output_folder=f"results")
241
+
242
+ # Parse the results and summarize them
243
+ parsed_results = parse_mteb_results(mteb_results=results, model_name=model_name)
244
+ task_scores = summarize_results(parsed_results)
245
+
246
+ # Print the results in a leaderboard format
247
+ print(make_leaderboard(task_scores))
248
+ ```
249
+
250
+ ## Model List
251
+
252
+
253
+ | Model | Language | Description | Vocab | Sentence Transformer | Params |
254
+ |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
255
+ | [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 |
256
+ | [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 |
257
+ | [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 |
258
+ ## Results
259
+
260
+ ### Main Results
261
+
262
+ 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.
263
+
264
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
265
+ |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
266
+ | 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 |
267
+ | 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 |
268
+ | 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 |
269
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
270
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
271
+
272
+ <details>
273
+ <summary> Task Abbreviations </summary>
274
+
275
+ For readability, the MTEB task names are abbreviated as follows:
276
+ - Class: Classification
277
+ - Clust: Clustering
278
+ - PairClass: PairClassification
279
+ - Rank: Reranking
280
+ - Ret: Retrieval
281
+ - STS: Semantic Textual Similarity
282
+ - Sum: Summarization
283
+ </details>
284
+
285
+ \
286
+ \* WL256, introduced in the [WordLlama](https://github.com/dleemiller/WordLlama/tree/main) package is included for comparison due to its similarities to Model2Vec. However, we believe it is heavily overfit to the MTEB dataset since it is trained on datasets used in MTEB itself. This can be seen by the fact that the WL256 model performs much worse on the non-MTEB tasks (PEARL and WordSim) than our models and GLoVe. The results shown in the [Classification and Speed Benchmarks](#classification-and-speed-benchmarks) further support this.
287
+
288
+ ### Classification and Speed Benchmarks
289
+
290
+ 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.
291
+
292
+ | model | Average | sst2 | imdb | trec | ag_news |
293
+ |:-----------------|----------:|---------:|-------:|---------:|----------:|
294
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
295
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
296
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
297
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
298
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
299
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
300
+
301
+ 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.
302
+
303
+ 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).
304
+ 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.
305
+
306
+ | ![Description](assets/images/speed_vs_accuracy.png) |
307
+ |:--:|
308
+ |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
309
+
310
+ ## Related work
311
+
312
+ If you are interested in fast small models, also consider looking at these techniques:
313
+ * [BPEmb](https://bpemb.h-its.org/): GLoVE embeddings trained on BPE-encoded Wikipedias. Huge inspiration to this project, multilingual, very fast. If you don't find a sentence transformer in the language you need, check this out.
314
+ * [fast-sentence-transformers](https://github.com/davidberenstein1957/fast-sentence-transformers): distillation using Model2Vec comes at a cost. If that cost is too steep for you, and you have access to a GPU, this package is for you. It automates the quantization and optimization of sentence transformers without loss of performance.
315
+ * [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. As we show above, we think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. It provides an interesting point of comparison to Model2Vec, and, fun fact, was invented at the same time.
316
+
317
+ If you find other related work, please let us know.
318
+
319
+ ## License
320
+
321
+ MIT
322
+
323
+ ## Citing
324
+
325
+ If you use Model2Vec in your research, please cite the following:
326
+ ```bibtex
327
+ @software{minishlab2024word2vec,
328
+ authors = {Stephan Tulkens, Thomas van Dongen},
329
+ title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
330
+ year = {2024},
331
+ url = {https://github.com/MinishLab/model2vec},
332
+ }
333
+ ```
@@ -0,0 +1,270 @@
1
+ # Model2Vec: Distill a Small Fast Model from any Sentence Transformer
2
+
3
+ **Model2Vec** is a method to distill a small, fast model from any Sentence Transformer model.
4
+
5
+ | ![Description](assets/images/speed_vs_accuracy.png) |
6
+ |:--:|
7
+ |*Model2vec allows you to create really fast small models that still perform well.*|
8
+
9
+
10
+ ## Table of Contents
11
+ - [Quickstart](#quickstart)
12
+ - [What is Model2Vec?](#what-is-model2vec)
13
+ - [Main Features](#main-features)
14
+ - [Usage](#usage)
15
+ - [Distilling a Model2Vec model](#distilling-a-model2vec-model)
16
+ - [Inferencing a Model2Vec model](#inference-with-a-model2vec-model)
17
+ - [Evaluating a Model2Vec model](#evaluating-a-model2vec-model)
18
+ - [Model List](#model-list)
19
+ - [Results](#results)
20
+ - [Related Work](#related-work)
21
+ - [Citing](#citing)
22
+
23
+ ## Quickstart
24
+
25
+ Install the package with:
26
+ ```bash
27
+ pip install model2vec
28
+ ```
29
+
30
+ The easiest way to get started with Model2Vec is to download one of our [flagship models from the HuggingFace hub](https://huggingface.co/minishlab). These models are pre-trained and ready to use. The following code snippet shows how to load a model and make embeddings:
31
+ ```python
32
+ from model2vec import StaticModel
33
+
34
+ # Load a model from the HuggingFace hub (in this case the M2V_base_output model)
35
+ model_name = "minishlab/M2V_base_output"
36
+ model = StaticModel.from_pretrained(model_name)
37
+
38
+ # Make embeddings
39
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
40
+ ```
41
+
42
+ And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
43
+
44
+ Instead of using on of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
45
+ ```python
46
+ from model2vec.distill import distill
47
+
48
+ # Choose a Sentence Transformer model
49
+ model_name = "BAAI/bge-base-en-v1.5"
50
+
51
+ # Distill the model
52
+ m2v_model = distill(model_name=model_name, pca_dims=256)
53
+
54
+ # Save the model
55
+ m2v_model.save_pretrained("m2v_model")
56
+ ```
57
+
58
+ 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.
59
+
60
+ ## What is Model2Vec?
61
+
62
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Best of all, you don't need _any_ data to distill a model using Model2Vec.
63
+
64
+ 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.
65
+
66
+ Model2vec has 2 modes:
67
+ - **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.
68
+ - **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.
69
+
70
+ ## Main Features
71
+
72
+ Model2Vec is:
73
+
74
+ - **Small**: reduces the size of a Sentence Transformer model by a factor of 15, from 120M params, down to 7.5M (30 MB on disk!).
75
+ - **Static, but better**: smaller than GLoVe, but much more performant, even with the same vocabulary.
76
+ - **Fast distillation**: make your own model in 30 seconds.
77
+ - **Fast inference**: up to 500 times faster on CPU than the original model. Go green or go home.
78
+ - **No data needed**: Distillation happens directly on the token level, so no dataset is needed.
79
+ - **Simple to use**: An easy to use interface for distilling and inferencing.
80
+ - **Bring your own model**: Can be applied to any Sentence Transformer model.
81
+ - **Bring your own vocabulary**: Can be applied to any vocabulary, allowing you to use your own domain-specific vocabulary. Need biomedical? Just get a medical dictionary, a biomedical model, and inference it.
82
+ - **Multi-lingual**: Use any language. Need a French model? [Pick one](https://huggingface.co/models?library=sentence-transformers&language=fr&sort=trending). Need multilingual? [Here you go](https://huggingface.co/sentence-transformers/LaBSE).
83
+ - **Tightly integrated with HuggingFace hub**: easily share and load models from the HuggingFace hub, using the familiar `from_pretrained` and `push_to_hub`. Our own models can be found [here](https://huggingface.co/minishlab). Feel free to share your own.
84
+ - **Easy Evaluation**: evaluate your models on MTEB and some of our own tasks to measure the performance of the distilled model. Model2Vec models work out of the box on [MTEB](https://huggingface.co/spaces/mteb/leaderboard).
85
+
86
+ ## Usage
87
+
88
+ ### Distilling a Model2Vec model
89
+
90
+ Distilling a model from the output embeddings of a Sentence Transformer model. As mentioned above, this leads to really small model that might be less performant.
91
+ ```python
92
+ from model2vec.distill import distill
93
+
94
+ # Choose a Sentence Transformer model
95
+ model_name = "BAAI/bge-base-en-v1.5"
96
+
97
+ # Distill the model
98
+ m2v_model = distill(model_name=model_name, pca_dims=256)
99
+
100
+ # Save the model
101
+ m2v_model.save_pretrained("m2v_model")
102
+
103
+ ```
104
+
105
+ If you pass a vocabulary, you get a set of static word embeddings, together with a custom tokenizer for exactly that vocabulary. This is comparable to how you would use GLoVe or traditional word2vec, but doesn't actually require a corpus or data.
106
+ ```python
107
+ from model2vec.distill import distill
108
+
109
+ # Load a vocabulary as a list of strings
110
+ vocabulary = ["word1", "word2", "word3"]
111
+ # Choose a Sentence Transformer model
112
+ model_name = "BAAI/bge-base-en-v1.5"
113
+
114
+ # Distill the model with the custom vocabulary
115
+ m2v_model = distill(model_name=model_name,
116
+ vocabulary=vocabulary,
117
+ pca_dims=None,
118
+ apply_zipf=True)
119
+
120
+ # Save the model
121
+ m2v_model.save_pretrained("m2v_model")
122
+
123
+ # Or push it to the hub
124
+ m2v_model.push_to_hub("my_organization/my_model", token="<it's a secret to everybody>")
125
+ ```
126
+
127
+ **Important note:** we assume the passed vocabulary is sorted in rank frequency. i.e., we don't care about the actual word frequencies, but do assume that the most frequent word is first, and the least frequent word is last. If you're not sure whether this is case, set `apply_zipf` to `False`. This disables the weighting, but will also make performance a little bit worse.
128
+
129
+ We also provide a command line interface for distillation. Note that `vocab.txt` should be a file with one word per line.
130
+ ```bash
131
+ python3 -m model2vec.distill --model-name BAAI/bge-base-en-v1.5 --vocabulary-path vocab.txt --device mps --save-path model2vec_model
132
+ ```
133
+
134
+ ### Inference with a Model2Vec model
135
+ Inference works as follows. The example shows one of our own models, but you can also just load a local one, or another one from the hub.
136
+ ```python
137
+ from model2vec import StaticModel
138
+
139
+ # Load a model from the HuggingFace hub, or a local one.
140
+ model_name = "minishlab/M2V_base_output"
141
+ # You can optionally pass a token if you're loading a private model
142
+ model = StaticModel.from_pretrained(model_name, token=None)
143
+
144
+ # Make embeddings
145
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
146
+ ```
147
+
148
+ ### Evaluating a Model2Vec model
149
+
150
+ Our models can be evaluated using our [evaluation package](https://github.com/MinishLab/evaluation). To run this, first install the optional evaluation package:
151
+ ```bash
152
+ pip install evaluation@git+https://github.com/MinishLab/evaluation@main
153
+ ```
154
+
155
+ Then, the following code snippet shows how to evaluate a Model2Vec model:
156
+ ```python
157
+ from model2vec import StaticModel
158
+
159
+ from evaluation import CustomMTEB, get_tasks, parse_mteb_results, make_leaderboard, summarize_results
160
+ from mteb import ModelMeta
161
+
162
+ # Get all available tasks
163
+ tasks = get_tasks()
164
+ # Define the CustomMTEB object with the specified tasks
165
+ evaluation = CustomMTEB(tasks=tasks)
166
+
167
+ # Load the model
168
+ model_name = "m2v_model"
169
+ model = StaticModel.from_pretrained(model_name)
170
+
171
+ # Optionally, add model metadata in MTEB format
172
+ model.mteb_model_meta = ModelMeta(
173
+ name=model_name, revision="no_revision_available", release_date=None, languages=None
174
+ )
175
+
176
+ # Run the evaluation
177
+ results = evaluation.run(model, eval_splits=["test"], output_folder=f"results")
178
+
179
+ # Parse the results and summarize them
180
+ parsed_results = parse_mteb_results(mteb_results=results, model_name=model_name)
181
+ task_scores = summarize_results(parsed_results)
182
+
183
+ # Print the results in a leaderboard format
184
+ print(make_leaderboard(task_scores))
185
+ ```
186
+
187
+ ## Model List
188
+
189
+
190
+ | Model | Language | Description | Vocab | Sentence Transformer | Params |
191
+ |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
192
+ | [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 |
193
+ | [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 |
194
+ | [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 |
195
+ ## Results
196
+
197
+ ### Main Results
198
+
199
+ 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.
200
+
201
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
202
+ |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
203
+ | 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 |
204
+ | 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 |
205
+ | 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 |
206
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
207
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
208
+
209
+ <details>
210
+ <summary> Task Abbreviations </summary>
211
+
212
+ For readability, the MTEB task names are abbreviated as follows:
213
+ - Class: Classification
214
+ - Clust: Clustering
215
+ - PairClass: PairClassification
216
+ - Rank: Reranking
217
+ - Ret: Retrieval
218
+ - STS: Semantic Textual Similarity
219
+ - Sum: Summarization
220
+ </details>
221
+
222
+ \
223
+ \* WL256, introduced in the [WordLlama](https://github.com/dleemiller/WordLlama/tree/main) package is included for comparison due to its similarities to Model2Vec. However, we believe it is heavily overfit to the MTEB dataset since it is trained on datasets used in MTEB itself. This can be seen by the fact that the WL256 model performs much worse on the non-MTEB tasks (PEARL and WordSim) than our models and GLoVe. The results shown in the [Classification and Speed Benchmarks](#classification-and-speed-benchmarks) further support this.
224
+
225
+ ### Classification and Speed Benchmarks
226
+
227
+ 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.
228
+
229
+ | model | Average | sst2 | imdb | trec | ag_news |
230
+ |:-----------------|----------:|---------:|-------:|---------:|----------:|
231
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
232
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
233
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
234
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
235
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
236
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
237
+
238
+ 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.
239
+
240
+ 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).
241
+ 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.
242
+
243
+ | ![Description](assets/images/speed_vs_accuracy.png) |
244
+ |:--:|
245
+ |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
246
+
247
+ ## Related work
248
+
249
+ If you are interested in fast small models, also consider looking at these techniques:
250
+ * [BPEmb](https://bpemb.h-its.org/): GLoVE embeddings trained on BPE-encoded Wikipedias. Huge inspiration to this project, multilingual, very fast. If you don't find a sentence transformer in the language you need, check this out.
251
+ * [fast-sentence-transformers](https://github.com/davidberenstein1957/fast-sentence-transformers): distillation using Model2Vec comes at a cost. If that cost is too steep for you, and you have access to a GPU, this package is for you. It automates the quantization and optimization of sentence transformers without loss of performance.
252
+ * [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. As we show above, we think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. It provides an interesting point of comparison to Model2Vec, and, fun fact, was invented at the same time.
253
+
254
+ If you find other related work, please let us know.
255
+
256
+ ## License
257
+
258
+ MIT
259
+
260
+ ## Citing
261
+
262
+ If you use Model2Vec in your research, please cite the following:
263
+ ```bibtex
264
+ @software{minishlab2024word2vec,
265
+ authors = {Stephan Tulkens, Thomas van Dongen},
266
+ title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
267
+ year = {2024},
268
+ url = {https://github.com/MinishLab/model2vec},
269
+ }
270
+ ```
@@ -104,15 +104,19 @@ def distill(
104
104
  tokenizer = create_tokenizer_from_vocab(tokens, unk_token="[UNK]", pad_token="[PAD]")
105
105
 
106
106
  if pca_dims is not None:
107
- if pca_dims < embeddings.shape[1]:
107
+ if pca_dims >= embeddings.shape[1]:
108
+ raise ValueError(
109
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
110
+ )
111
+ if pca_dims >= len(tokens):
112
+ logger.warning(
113
+ f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({len(tokens)}). Not applying PCA."
114
+ )
115
+ elif pca_dims < embeddings.shape[1]:
108
116
  logger.info(f"Applying PCA with n_components {pca_dims}")
109
117
 
110
118
  p = PCA(n_components=pca_dims, whiten=False)
111
119
  embeddings = p.fit_transform(embeddings)
112
- else:
113
- raise ValueError(
114
- f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
115
- )
116
120
 
117
121
  if apply_zipf:
118
122
  logger.info("Applying Zipf weighting")