model2vec 0.3.2__tar.gz → 0.3.4__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 (54) hide show
  1. {model2vec-0.3.2 → model2vec-0.3.4}/.github/workflows/ci.yaml +1 -0
  2. {model2vec-0.3.2 → model2vec-0.3.4}/Makefile +1 -0
  3. {model2vec-0.3.2 → model2vec-0.3.4}/PKG-INFO +260 -135
  4. {model2vec-0.3.2 → model2vec-0.3.4}/README.md +250 -130
  5. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/distill/distillation.py +41 -11
  6. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/distill/tokenizer.py +4 -2
  7. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/model.py +58 -19
  8. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/utils.py +42 -2
  9. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/version.py +1 -1
  10. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec.egg-info/PKG-INFO +260 -135
  11. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec.egg-info/SOURCES.txt +2 -0
  12. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec.egg-info/requires.txt +9 -3
  13. {model2vec-0.3.2 → model2vec-0.3.4}/pyproject.toml +7 -4
  14. {model2vec-0.3.2 → model2vec-0.3.4}/results/README.md +11 -10
  15. model2vec-0.3.4/scripts/export_to_onnx.py +208 -0
  16. {model2vec-0.3.2 → model2vec-0.3.4}/tests/test_distillation.py +60 -0
  17. {model2vec-0.3.2 → model2vec-0.3.4}/tests/test_model.py +23 -1
  18. model2vec-0.3.4/tutorials/README.md +16 -0
  19. model2vec-0.3.4/tutorials/semantic_chunking.ipynb +261 -0
  20. {model2vec-0.3.2 → model2vec-0.3.4}/uv.lock +623 -453
  21. model2vec-0.3.2/tutorials/README.md +0 -15
  22. {model2vec-0.3.2 → model2vec-0.3.4}/.gitignore +0 -0
  23. {model2vec-0.3.2 → model2vec-0.3.4}/.pre-commit-config.yaml +0 -0
  24. {model2vec-0.3.2 → model2vec-0.3.4}/LICENSE +0 -0
  25. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/logo.png +0 -0
  26. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/logo_v2.png +0 -0
  27. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/model2vec_model_diagram.png +0 -0
  28. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
  29. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
  30. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  31. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_accuracy.png +0 -0
  32. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_accuracy_v2.png +0 -0
  33. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_accuracy_v3.png +0 -0
  34. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_accuracy_v4.png +0 -0
  35. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_mteb_score.png +0 -0
  36. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/speed_vs_mteb_score_v2.png +0 -0
  37. {model2vec-0.3.2 → model2vec-0.3.4}/assets/images/tutorial_ezlo.png +0 -0
  38. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/__init__.py +0 -0
  39. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/distill/__init__.py +0 -0
  40. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/distill/inference.py +0 -0
  41. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/distill/utils.py +0 -0
  42. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/hf_utils.py +0 -0
  43. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec/model_card_template.md +0 -0
  44. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec.egg-info/dependency_links.txt +0 -0
  45. {model2vec-0.3.2 → model2vec-0.3.4}/model2vec.egg-info/top_level.txt +0 -0
  46. {model2vec-0.3.2 → model2vec-0.3.4}/setup.cfg +0 -0
  47. {model2vec-0.3.2 → model2vec-0.3.4}/tests/__init__.py +0 -0
  48. {model2vec-0.3.2 → model2vec-0.3.4}/tests/conftest.py +0 -0
  49. {model2vec-0.3.2 → model2vec-0.3.4}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  50. {model2vec-0.3.2 → model2vec-0.3.4}/tests/data/test_tokenizer/tokenizer.json +0 -0
  51. {model2vec-0.3.2 → model2vec-0.3.4}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  52. {model2vec-0.3.2 → model2vec-0.3.4}/tests/test_utils.py +0 -0
  53. {model2vec-0.3.2 → model2vec-0.3.4}/tutorials/recipe_search.ipynb +0 -0
  54. {model2vec-0.3.2 → model2vec-0.3.4}/tutorials/semantic_deduplication.ipynb +0 -0
@@ -34,6 +34,7 @@ jobs:
34
34
  if: ${{ runner.os == 'Windows' }}
35
35
  run: |
36
36
  irm https://astral.sh/uv/install.ps1 | iex
37
+ $env:Path = "C:\Users\runneradmin\.local\bin;$env:Path"
37
38
  uv venv .venv
38
39
  "VIRTUAL_ENV=.venv" | Out-File -FilePath $env:GITHUB_ENV -Append
39
40
  "$PWD/.venv/Scripts" | Out-File -FilePath $env:GITHUB_PATH -Append
@@ -10,6 +10,7 @@ install:
10
10
 
11
11
  install-no-pre-commit:
12
12
  uv pip install ".[dev,distill]"
13
+ uv pip install "torch<2.5.0"
13
14
 
14
15
  install-base:
15
16
  uv sync --extra dev
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.3.2
4
- Summary: Distill a Small Static Model from any Sentence Transformer
3
+ Version: 0.3.4
4
+ Summary: The Fastest State-of-the-Art Static Embeddings in the World
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
7
7
 
@@ -43,24 +43,29 @@ Classifier: Natural Language :: English
43
43
  Requires-Python: >=3.9
44
44
  Description-Content-Type: text/markdown
45
45
  License-File: LICENSE
46
+ Requires-Dist: jinja2
47
+ Requires-Dist: joblib
46
48
  Requires-Dist: numpy
47
49
  Requires-Dist: rich
48
- Requires-Dist: tqdm
49
- Requires-Dist: tokenizers>=0.20
50
50
  Requires-Dist: safetensors
51
51
  Requires-Dist: setuptools
52
+ Requires-Dist: tokenizers>=0.20
53
+ Requires-Dist: tqdm
52
54
  Provides-Extra: dev
53
55
  Requires-Dist: black; extra == "dev"
54
56
  Requires-Dist: ipython; extra == "dev"
55
57
  Requires-Dist: mypy; extra == "dev"
56
58
  Requires-Dist: pre-commit; extra == "dev"
57
59
  Requires-Dist: pytest; extra == "dev"
58
- Requires-Dist: pytest-coverage; extra == "dev"
60
+ Requires-Dist: pytest-cov; extra == "dev"
59
61
  Requires-Dist: ruff; extra == "dev"
60
62
  Provides-Extra: distill
61
63
  Requires-Dist: torch; extra == "distill"
62
64
  Requires-Dist: transformers; extra == "distill"
63
65
  Requires-Dist: scikit-learn; extra == "distill"
66
+ Provides-Extra: onnx
67
+ Requires-Dist: onnx; extra == "onnx"
68
+ Requires-Dist: torch; extra == "onnx"
64
69
 
65
70
 
66
71
  <div align="center">
@@ -71,14 +76,14 @@ Requires-Dist: scikit-learn; extra == "distill"
71
76
  </div>
72
77
 
73
78
  <div align="center">
74
- <h2>Distill a Small Static Model from any Sentence Transformer</h2>
79
+ <h2>The Fastest State-of-the-Art Static Embeddings in the World</h2>
75
80
  </div>
76
81
 
77
82
  <div align="center">
78
83
  <h2>
79
84
  <a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
80
85
  <a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
81
- <a href="https://huggingface.co/blog/Pringled/model2vec"><strong>📖 Blog</strong></a> |
86
+ <a href="https://minishlab.github.io/"><strong>🌐 Website</strong></a> |
82
87
  <a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a>
83
88
  </h2>
84
89
  </div>
@@ -103,7 +108,7 @@ Requires-Dist: scikit-learn; extra == "distill"
103
108
  <img src="assets/images/model2vec_model_diagram_transparant_light.png#gh-light-mode-only" width="90%">
104
109
  </div>
105
110
 
106
- Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. See our results [here](results/README.md), or dive in to see how it works.
111
+ Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is the most performant static embedding model in the world. See our results [here](results/README.md), or dive in to see how it works.
107
112
 
108
113
 
109
114
  ## Updates & Announcements
@@ -115,34 +120,33 @@ Model2Vec is a technique to turn any sentence transformer into a really small st
115
120
  - [Main Features](#main-features)
116
121
  - [What is Model2Vec?](#what-is-model2vec)
117
122
  - [Usage](#usage)
118
- - [Distillation](#distillation)
119
123
  - [Inference](#inference)
124
+ - [Distillation](#distillation)
120
125
  - [Evaluation](#evaluation)
126
+ - [Integrations](#integrations)
121
127
  - [Model List](#model-list)
122
128
  - [Results](#results)
123
- - [Related Work](#related-work)
124
- - [Citing](#citing)
125
129
 
126
130
  ## Quickstart
127
131
 
128
- Install the package and all required extras with:
132
+ Install the package with:
133
+
129
134
  ```bash
130
- pip install model2vec[distill]
135
+ pip install model2vec
131
136
  ```
132
137
 
133
- If you want a light-weight version of the package which only requires `numpy`, omit the `distill` extra. This means you can't distill your own models, but you can use pre-trained models. This is useful for inference pipelines.
138
+ This will install the base inference package, which only depends on `numpy` and a few other minor dependencies. If you want to distill your own models, you can install the distillation extras with:
134
139
 
135
140
  ```bash
136
- pip install model2vec
141
+ pip install model2vec[distill]
137
142
  ```
138
143
 
139
- 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:
144
+ The easiest way to get started with Model2Vec is to load one of our [flagship models from the HuggingFace hub](https://huggingface.co/collections/minishlab/potion-6721e0abd4ea41881417f062). These models are pre-trained and ready to use. The following code snippet shows how to load a model and make embeddings:
140
145
  ```python
141
146
  from model2vec import StaticModel
142
147
 
143
148
  # Load a model from the HuggingFace hub (in this case the potion-base-8M model)
144
- model_name = "minishlab/potion-base-8M"
145
- model = StaticModel.from_pretrained(model_name)
149
+ model = StaticModel.from_pretrained("minishlab/potion-base-8M")
146
150
 
147
151
  # Make embeddings
148
152
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
@@ -153,81 +157,88 @@ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It'
153
157
 
154
158
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
155
159
 
156
- Instead of using one 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:
160
+ Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
157
161
  ```python
158
162
  from model2vec.distill import distill
159
163
 
160
- # Choose a Sentence Transformer model
161
- model_name = "BAAI/bge-base-en-v1.5"
162
-
163
- # Distill the model
164
- m2v_model = distill(model_name=model_name, pca_dims=256)
164
+ # Distill a Sentence Transformer model, in this case the BAAI/bge-base-en-v1.5 model
165
+ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)
165
166
 
166
167
  # Save the model
167
168
  m2v_model.save_pretrained("m2v_model")
168
169
  ```
169
170
 
170
- 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.
171
-
172
- You can also directly use Model2Vec in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) using the [StaticEmbedding](https://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/models/StaticEmbedding.py) module. You can either load a Model2Vec model into a Sentence Transformer with the following code snippet:
173
- ```python
174
- from sentence_transformers import SentenceTransformer
175
- from sentence_transformers.models import StaticEmbedding
176
-
177
- # Initialize a StaticEmbedding module
178
- static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
179
- model = SentenceTransformer(modules=[static_embedding])
180
- embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
181
- ```
171
+ Distillation is really fast and only takes 30 seconds on CPU. Best of all, distillation requires no training data.
182
172
 
183
- Or you can distill a model directly into a Sentence Transformer model:
184
- ```python
185
- from sentence_transformers import SentenceTransformer
186
- from sentence_transformers.models import StaticEmbedding
173
+ For advanced usage, such as using Model2Vec in the [Sentence Transformers library](https://github.com/UKPLab/sentence-transformers), please refer to the [Usage](#usage) sections.
187
174
 
188
- static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cpu", pca_dims=256)
189
- model = SentenceTransformer(modules=[static_embedding])
190
- embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
191
- ```
192
- For more documentation, please refer to the [Sentence Transformers documentation](https://sbert.net/docs/package_reference/sentence_transformer/models.html#sentence_transformers.models.StaticEmbedding).
193
175
 
194
176
  ## Main Features
195
177
 
196
- Model2Vec has the following features:
197
-
198
- - **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, making it the smallest model on [MTEB](https://huggingface.co/spaces/mteb/leaderboard)!).
199
- - **Static, but better**: smaller than GLoVe and BPEmb, but [much more performant](results/README.md), even with the same vocabulary.
200
- - **Fast distillation**: make your own model in 30 seconds.
201
- - **Fast inference**: up to 500 times faster on CPU than the original model. Go green or go home.
202
- - **No data needed**: Distillation happens directly on the token level, so no dataset is needed.
203
- - **Simple to use**: An easy to use interface for distilling and inferencing.
204
- - **Integrated into Sentence Transformers**: Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers).
205
- - **Bring your own model**: Can be applied to any Sentence Transformer model.
206
- - **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.
207
- - **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).
178
+ - **State-of-the-Art Performance**: Model2Vec models outperform any other static embeddings (such as GLoVe and BPEmb) by a large margin, as can be seen in our [results](results/README.md).
179
+ - **Small**: Model2Vec reduces the size of a Sentence Transformer model by a factor of 15, from 120M params, down to 7.5M (30 MB on disk, making it the smallest model on [MTEB](https://huggingface.co/spaces/mteb/leaderboard)!).
180
+ - **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
181
+ - **Lightning-fast Inference**: up to 500 times faster on CPU than the original model. Go green or go home.
182
+ - **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset. All you need is a model and (optionally) a custom vocabulary.
183
+ - **Integrated in many popular libraries**: Model2Vec can be used directly in popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers), [LangChain](https://github.com/langchain-ai/langchain), [txtai](https://github.com/neuml/txtai), and [Chonkie](https://github.com/bhavnicksm/chonkie). See the [Integrations](#integrations) section for more information.
208
184
  - **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.
209
- - **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).
210
185
 
211
186
  ## What is Model2Vec?
212
187
 
213
- Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Best of all, you don't need _any_ data to distill a model using Model2Vec.
188
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Distillation doesn't need _any_ data, just a vocabulary and a model.
214
189
 
215
- 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.
190
+ The base model2vec technique 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.
216
191
 
217
- Model2vec has 3 modes:
218
- - **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.
219
- - **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
220
- - **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.
192
+ Our [potion models](https://huggingface.co/collections/minishlab/potion-6721e0abd4ea41881417f062) are pre-trained using [tokenlearn](https://github.com/MinishLab/tokenlearn), a technique to pre-train model2vec distillation models. These models are created with the following steps:
193
+ - **Distillation**: We distill a Model2Vec model from a Sentence Transformer model, using the method described above.
194
+ - **Sentence Transformer inference**: We use the Sentence Transformer model to create mean embeddings for a large number of texts from a corpus.
195
+ - **Training**: We train a model to minimize the cosine distance between the mean embeddings generated by the Sentence Transformer model and the mean embeddings generated by the Model2Vec model.
196
+ - **Post-training re-regularization**: We re-regularize the trained embeddings by first performing PCA, and then weighting the embeddings using `smooth inverse frequency (SIF)` weighting using the following formula: `w = 1e-3 / (1e-3 + proba)`. Here, `proba` is the probability of the token in the corpus we used for training.
221
197
 
222
- For a technical deepdive into Model2Vec, please refer to our [blog post](https://huggingface.co/blog/Pringled/model2vec).
223
198
 
224
- ### Tokenlearn
199
+ For a much more extensive deepdive, please refer to our [Model2Vec blog post](https://huggingface.co/blog/Pringled/model2vec) and our [Tokenlearn blog post](https://minishlab.github.io/tokenlearn_blogpost/).
225
200
 
226
- Our flagship POTION models are pre-trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). This method is described in our [Tokenlearn blogpost](https://minishlab.github.io/tokenlearn_blogpost/).
201
+ ## Usage
227
202
 
203
+ ### Inference
228
204
 
229
- ## Usage
205
+ <details>
206
+ <summary> Inference with a pretrained model </summary>
207
+ <br>
208
+
209
+ 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.
210
+ ```python
211
+ from model2vec import StaticModel
212
+
213
+ # Load a model from the Hub. You can optionally pass a token when loading a private model
214
+ model = StaticModel.from_pretrained(model_name="minishlab/potion-base-8M", token=None)
215
+
216
+ # Make embeddings
217
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
218
+
219
+ # Make sequences of token embeddings
220
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
221
+ ```
222
+ </details>
223
+
224
+
225
+ <details>
226
+ <summary> Inference with the Sentence Transformers library </summary>
227
+ <br>
228
+
229
+ The following code snippet shows how to use a Model2Vec model in the [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) library. This is useful if you want to use the model in a Sentence Transformers pipeline.
230
+
231
+ ```python
232
+ from sentence_transformers import SentenceTransformer
233
+ from sentence_transformers.models import StaticEmbedding
234
+
235
+ # Initialize a StaticEmbedding module
236
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
237
+ model = SentenceTransformer(modules=[static_embedding])
238
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
239
+ ```
230
240
 
241
+ </details>
231
242
 
232
243
  ### Distillation
233
244
 
@@ -239,11 +250,8 @@ The following code can be used to distill a model from a Sentence Transformer. A
239
250
  ```python
240
251
  from model2vec.distill import distill
241
252
 
242
- # Choose a Sentence Transformer model
243
- model_name = "BAAI/bge-base-en-v1.5"
244
-
245
- # Distill the model
246
- m2v_model = distill(model_name=model_name, pca_dims=256)
253
+ # Distill a Sentence Transformer model
254
+ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)
247
255
 
248
256
  # Save the model
249
257
  m2v_model.save_pretrained("m2v_model")
@@ -303,11 +311,9 @@ from model2vec.distill import distill
303
311
 
304
312
  # Load a vocabulary as a list of strings
305
313
  vocabulary = ["word1", "word2", "word3"]
306
- # Choose a Sentence Transformer model
307
- model_name = "BAAI/bge-base-en-v1.5"
308
314
 
309
- # Distill the model with the custom vocabulary
310
- m2v_model = distill(model_name=model_name, vocabulary=vocabulary)
315
+ # Distill a Sentence Transformer model with the custom vocabulary
316
+ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", vocabulary=vocabulary)
311
317
 
312
318
  # Save the model
313
319
  m2v_model.save_pretrained("m2v_model")
@@ -326,48 +332,6 @@ m2v_model = distill(model_name=model_name, vocabulary=vocabulary, use_subword=Fa
326
332
 
327
333
  </details>
328
334
 
329
- ### Inference
330
-
331
- <details>
332
- <summary> Inference using pretrained model </summary>
333
- <br>
334
-
335
- 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.
336
- ```python
337
- from model2vec import StaticModel
338
-
339
- # Load a model from the HuggingFace hub, or a local one.
340
- model_name = "minishlab/potion-base-8M"
341
- # You can optionally pass a token if you're loading a private model
342
- model = StaticModel.from_pretrained(model_name, token=None)
343
-
344
- # Make embeddings
345
- embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
346
-
347
- # Make sequences of token embeddings
348
- token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
349
- ```
350
- </details>
351
-
352
-
353
- <details>
354
- <summary> Inference using the Sentence Transformers library </summary>
355
- <br>
356
-
357
- The following code snippet shows how to use a Model2Vec model in the [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) library. This is useful if you want to use the model in a Sentence Transformers pipeline.
358
-
359
- ```python
360
- from sentence_transformers import SentenceTransformer
361
- from sentence_transformers.models import StaticEmbedding
362
-
363
- # Initialize a StaticEmbedding module
364
- static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
365
- model = SentenceTransformer(modules=[static_embedding])
366
- embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
367
- ```
368
-
369
- </details>
370
-
371
335
 
372
336
  ### Evaluation
373
337
 
@@ -420,17 +384,187 @@ print(make_leaderboard(task_scores))
420
384
  ```
421
385
  </details>
422
386
 
387
+ ## Integrations
388
+ <details>
389
+ <summary> Sentence Transformers </summary>
390
+ <a name="sentence-transformers"></a>
391
+ <br>
392
+
393
+ Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) using the `StaticEmbedding` module.
394
+
395
+ The following code snippet shows how to load a Model2Vec model into a Sentence Transformer model:
396
+ ```python
397
+ from sentence_transformers import SentenceTransformer
398
+ from sentence_transformers.models import StaticEmbedding
399
+
400
+ # Initialize a StaticEmbedding module
401
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
402
+ model = SentenceTransformer(modules=[static_embedding])
403
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
404
+ ```
405
+
406
+ The following code snippet shows how to distill a model directly into a Sentence Transformer model:
407
+
408
+ ```python
409
+ from sentence_transformers import SentenceTransformer
410
+ from sentence_transformers.models import StaticEmbedding
411
+
412
+ static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cpu", pca_dims=256)
413
+ model = SentenceTransformer(modules=[static_embedding])
414
+ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
415
+ ```
416
+
417
+ For more documentation, please refer to the [Sentence Transformers documentation](https://sbert.net/docs/package_reference/sentence_transformer/models.html#sentence_transformers.models.StaticEmbedding).
418
+
419
+ </details>
420
+
421
+ <details>
422
+ <summary> LangChain </summary>
423
+ <br>
424
+
425
+ Model2Vec can be used in [LangChain](https://github.com/langchain-ai/langchain) using the `langchain-community` package. For more information, see the [LangChain Model2Vec docs](https://python.langchain.com/docs/integrations/text_embedding/model2vec/). The following code snippet shows how to use Model2Vec in LangChain after installing the `langchain-community` package with `pip install langchain-community`:
426
+
427
+ ```python
428
+ from langchain_community.embeddings import Model2vecEmbeddings
429
+ from langchain_community.vectorstores import FAISS
430
+ from langchain.schema import Document
431
+
432
+ # Initialize a Model2Vec embedder
433
+ embedder = Model2vecEmbeddings("minishlab/potion-base-8M")
434
+
435
+ # Create some example texts
436
+ texts = [
437
+ "Enduring Stew",
438
+ "Hearty Elixir",
439
+ "Mighty Mushroom Risotto",
440
+ "Spicy Meat Skewer",
441
+ "Fruit Salad",
442
+ ]
443
+
444
+ # Embed the texts
445
+ embeddings = embedder.embed_documents(texts)
446
+
447
+ # Or, create a vector store and query it
448
+ documents = [Document(page_content=text) for text in texts]
449
+ vector_store = FAISS.from_documents(documents, embedder)
450
+ query = "Risotto"
451
+ query_vector = embedder.embed_query(query)
452
+ retrieved_docs = vector_store.similarity_search_by_vector(query_vector, k=1)
453
+ ```
454
+ </details>
455
+
456
+ <details>
457
+ <summary> Txtai </summary>
458
+ <br>
459
+
460
+ Model2Vec can be used in [txtai](https://github.com/neuml/txtai) for text embeddings, nearest-neighbors search, and any of the other functionalities that txtai offers. The following code snippet shows how to use Model2Vec in txtai after installing the `txtai` package (including the `vectors` dependency) with `pip install txtai[vectors]`:
461
+
462
+ ```python
463
+ from txtai import Embeddings
464
+
465
+ # Load a model2vec model
466
+ embeddings = Embeddings(path="minishlab/potion-base-8M", method="model2vec", backend="numpy")
467
+
468
+ # Create some example texts
469
+ texts = ["Enduring Stew", "Hearty Elixir", "Mighty Mushroom Risotto", "Spicy Meat Skewer", "Chilly Fruit Salad"]
470
+
471
+ # Create embeddings for downstream tasks
472
+ vectors = embeddings.batchtransform(texts)
473
+
474
+ # Or create a nearest-neighbors index and search it
475
+ embeddings.index(texts)
476
+ result = embeddings.search("Risotto", 1)
477
+ ```
478
+
479
+ </details>
480
+
481
+ <details>
482
+ <summary> Chonkie </summary>
483
+ <br>
484
+
485
+ Model2Vec is the default model for semantic chunking in [Chonkie](https://github.com/bhavnicksm/chonkie). To use Model2Vec for semantic chunking in Chonkie, simply install Chonkie with `pip install chonkie[semantic]` and use one of the `potion` models in the `SemanticChunker` class. The following code snippet shows how to use Model2Vec in Chonkie:
486
+
487
+ ```python
488
+ from chonkie import SDPMChunker
489
+
490
+ # Create some example text to chunk
491
+ text = "It's dangerous to go alone! Take this."
492
+
493
+ # Initialize the SemanticChunker with a potion model
494
+ chunker = SDPMChunker(
495
+ embedding_model="minishlab/potion-base-8M",
496
+ similarity_threshold=0.3
497
+ )
498
+
499
+ # Chunk the text
500
+ chunks = chunker.chunk(text)
501
+ ```
502
+
503
+ </details>
504
+
505
+
506
+ <details>
507
+ <summary> Transformers.js </summary>
508
+ <br>
509
+
510
+ To use a Model2Vec model in [transformers.js](https://github.com/huggingface/transformers.js), the following code snippet can be used as a starting point:
511
+
512
+ ```javascript
513
+ import { AutoModel, AutoTokenizer, Tensor } from '@huggingface/transformers';
514
+
515
+ const modelName = 'minishlab/potion-base-8M';
516
+
517
+ const modelConfig = {
518
+ config: { model_type: 'model2vec' },
519
+ dtype: 'fp32',
520
+ revision: 'refs/pr/1'
521
+ };
522
+ const tokenizerConfig = {
523
+ revision: 'refs/pr/2'
524
+ };
525
+
526
+ const model = await AutoModel.from_pretrained(modelName, modelConfig);
527
+ const tokenizer = await AutoTokenizer.from_pretrained(modelName, tokenizerConfig);
528
+
529
+ const texts = ['hello', 'hello world'];
530
+ const { input_ids } = await tokenizer(texts, { add_special_tokens: false, return_tensor: false });
531
+
532
+ const cumsum = arr => arr.reduce((acc, num, i) => [...acc, num + (acc[i - 1] || 0)], []);
533
+ const offsets = [0, ...cumsum(input_ids.slice(0, -1).map(x => x.length))];
534
+
535
+ const flattened_input_ids = input_ids.flat();
536
+ const modelInputs = {
537
+ input_ids: new Tensor('int64', flattened_input_ids, [flattened_input_ids.length]),
538
+ offsets: new Tensor('int64', offsets, [offsets.length])
539
+ };
540
+
541
+ const { embeddings } = await model(modelInputs);
542
+ console.log(embeddings.tolist()); // output matches python version
543
+ ```
544
+
545
+ Note that this requires that the Model2Vec has a `model.onnx` file and several required tokenizers file. To generate these for a model that does not have them yet, the following code snippet can be used:
546
+
547
+ ```bash
548
+ python scripts/export_to_onnx.py --model_path <path-to-a-model2vec-model> --save_path "<path-to-save-the-onnx-model>"
549
+ ```
550
+
551
+
552
+ <br>
553
+ </details>
554
+
555
+
423
556
  ## Model List
424
557
 
425
558
  We provide a number of models that can be used out of the box. These models are available on the [HuggingFace hub](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e) and can be loaded using the `from_pretrained` method. The models are listed below.
426
559
 
427
560
 
428
- | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
429
- |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|------------|
430
- | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 7.5M | True |
431
- | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 3.7M | True |
432
- | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 1.8M | True |
433
- | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M | False |
561
+ | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
562
+ |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|-------------------|
563
+ | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 7.5M | <div align="center">✅</div> |
564
+ | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 3.7M | <div align="center">✅</div> |
565
+ | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 1.8M | <div align="center">✅</div> |
566
+ | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M | <div align="center">❌</div> |
567
+
434
568
 
435
569
 
436
570
  ## Results
@@ -439,15 +573,6 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
439
573
  - [MTEB Results](results/README.md#mteb-results)
440
574
  - [Ablations](results/README.md#ablations)
441
575
 
442
- ## Related work
443
-
444
- If you are interested in fast small models, also consider looking at these techniques:
445
- * [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.
446
- * [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.
447
- * [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. We think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. Fun fact: this was invented at the same time as Model2Vec.
448
-
449
- If you find other related work, please let us know.
450
-
451
576
  ## License
452
577
 
453
578
  MIT
@@ -458,7 +583,7 @@ If you use Model2Vec in your research, please cite the following:
458
583
  ```bibtex
459
584
  @software{minishlab2024model2vec,
460
585
  authors = {Stephan Tulkens, Thomas van Dongen},
461
- title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
586
+ title = {Model2Vec: The Fastest State-of-the-Art Static Embeddings in the World},
462
587
  year = {2024},
463
588
  url = {https://github.com/MinishLab/model2vec},
464
589
  }