model2vec 0.3.8__tar.gz → 0.3.9__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.8 → model2vec-0.3.9}/PKG-INFO +5 -2
  2. {model2vec-0.3.8 → model2vec-0.3.9}/README.md +4 -1
  3. model2vec-0.3.9/assets/images/speed_vs_mteb_score_v3.png +0 -0
  4. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/distill/distillation.py +93 -29
  5. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/version.py +1 -1
  6. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec.egg-info/PKG-INFO +5 -2
  7. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec.egg-info/SOURCES.txt +2 -0
  8. {model2vec-0.3.8 → model2vec-0.3.9}/results/README.md +30 -9
  9. model2vec-0.3.9/results/make_speed_vs_mteb_plot.py +184 -0
  10. {model2vec-0.3.8 → model2vec-0.3.9}/tests/test_distillation.py +49 -19
  11. {model2vec-0.3.8 → model2vec-0.3.9}/.github/workflows/ci.yaml +0 -0
  12. {model2vec-0.3.8 → model2vec-0.3.9}/.gitignore +0 -0
  13. {model2vec-0.3.8 → model2vec-0.3.9}/.pre-commit-config.yaml +0 -0
  14. {model2vec-0.3.8 → model2vec-0.3.9}/LICENSE +0 -0
  15. {model2vec-0.3.8 → model2vec-0.3.9}/Makefile +0 -0
  16. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/logo.png +0 -0
  17. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/logo_v2.png +0 -0
  18. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/model2vec_model_diagram.png +0 -0
  19. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
  20. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
  21. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  22. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_accuracy.png +0 -0
  23. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_accuracy_v2.png +0 -0
  24. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_accuracy_v3.png +0 -0
  25. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_accuracy_v4.png +0 -0
  26. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_mteb_score.png +0 -0
  27. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/speed_vs_mteb_score_v2.png +0 -0
  28. {model2vec-0.3.8 → model2vec-0.3.9}/assets/images/tutorial_ezlo.png +0 -0
  29. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/__init__.py +0 -0
  30. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/distill/__init__.py +0 -0
  31. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/distill/inference.py +0 -0
  32. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/distill/tokenizer.py +0 -0
  33. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/distill/utils.py +0 -0
  34. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/hf_utils.py +0 -0
  35. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/model.py +0 -0
  36. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/model_card_template.md +0 -0
  37. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec/utils.py +0 -0
  38. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec.egg-info/dependency_links.txt +0 -0
  39. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec.egg-info/requires.txt +0 -0
  40. {model2vec-0.3.8 → model2vec-0.3.9}/model2vec.egg-info/top_level.txt +0 -0
  41. {model2vec-0.3.8 → model2vec-0.3.9}/pyproject.toml +0 -0
  42. {model2vec-0.3.8 → model2vec-0.3.9}/scripts/export_to_onnx.py +0 -0
  43. {model2vec-0.3.8 → model2vec-0.3.9}/setup.cfg +0 -0
  44. {model2vec-0.3.8 → model2vec-0.3.9}/tests/__init__.py +0 -0
  45. {model2vec-0.3.8 → model2vec-0.3.9}/tests/conftest.py +0 -0
  46. {model2vec-0.3.8 → model2vec-0.3.9}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  47. {model2vec-0.3.8 → model2vec-0.3.9}/tests/data/test_tokenizer/tokenizer.json +0 -0
  48. {model2vec-0.3.8 → model2vec-0.3.9}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  49. {model2vec-0.3.8 → model2vec-0.3.9}/tests/test_model.py +0 -0
  50. {model2vec-0.3.8 → model2vec-0.3.9}/tests/test_utils.py +0 -0
  51. {model2vec-0.3.8 → model2vec-0.3.9}/tutorials/README.md +0 -0
  52. {model2vec-0.3.8 → model2vec-0.3.9}/tutorials/recipe_search.ipynb +0 -0
  53. {model2vec-0.3.8 → model2vec-0.3.9}/tutorials/semantic_chunking.ipynb +0 -0
  54. {model2vec-0.3.8 → model2vec-0.3.9}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: model2vec
3
- Version: 0.3.8
3
+ Version: 0.3.9
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
@@ -108,11 +108,12 @@ Requires-Dist: torch; extra == "onnx"
108
108
  <img src="assets/images/model2vec_model_diagram_transparant_light.png#gh-light-mode-only" width="90%">
109
109
  </div>
110
110
 
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.
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-32M) 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.
112
112
 
113
113
 
114
114
  ## Updates & Announcements
115
115
 
116
+ - **30/01/2024**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
116
117
  - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
117
118
 
118
119
  ## Table of Contents
@@ -560,9 +561,11 @@ We provide a number of models that can be used out of the box. These models are
560
561
 
561
562
  | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
562
563
  |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|-------------------|
564
+ | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
563
565
  | [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
566
  | [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
567
  | [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> |
568
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
566
569
  | [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
570
 
568
571
 
@@ -39,11 +39,12 @@
39
39
  <img src="assets/images/model2vec_model_diagram_transparant_light.png#gh-light-mode-only" width="90%">
40
40
  </div>
41
41
 
42
- 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.
42
+ 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-32M) 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.
43
43
 
44
44
 
45
45
  ## Updates & Announcements
46
46
 
47
+ - **30/01/2024**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
47
48
  - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
48
49
 
49
50
  ## Table of Contents
@@ -491,9 +492,11 @@ We provide a number of models that can be used out of the box. These models are
491
492
 
492
493
  | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
493
494
  |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|-------------------|
495
+ | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
494
496
  | [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> |
495
497
  | [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> |
496
498
  | [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> |
499
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
497
500
  | [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> |
498
501
 
499
502
 
@@ -40,7 +40,8 @@ def distill_from_model(
40
40
  vocabulary: list[str] | None = None,
41
41
  device: str | None = None,
42
42
  pca_dims: PCADimType = 256,
43
- apply_zipf: bool = True,
43
+ apply_zipf: bool | None = None,
44
+ sif_coefficient: float | None = 1e-4,
44
45
  use_subword: bool = True,
45
46
  token_remove_pattern: str | None = r"\[unused\d+\]",
46
47
  ) -> StaticModel:
@@ -60,30 +61,19 @@ def distill_from_model(
60
61
  :param pca_dims: The number of components to use for PCA.
61
62
  If this is None, we don't apply PCA.
62
63
  If this is 'auto', we don't reduce dimensionality, but still apply PCA.
63
- :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
64
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
65
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
66
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
67
+ Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
64
68
  :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.
65
69
  :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
66
70
  If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled into a valid regex, we also throw an error.
67
- :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
68
- :raises: ValueError if the vocabulary contains duplicate tokens.
69
- :raises: ValueError if the regex can't be compiled.
70
- :raises: ValueError if the vocabulary is empty after token removal.
71
71
  :return: A StaticModel
72
72
 
73
73
  """
74
- device = select_optimal_device(device)
75
- if not use_subword and vocabulary is None:
76
- raise ValueError(
77
- "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
78
- )
79
-
80
- if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
81
- raise ValueError(
82
- "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
83
- "This is not supported yet."
84
- "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
85
- )
74
+ sif_coefficient = _validate_parameters(tokenizer, vocabulary, apply_zipf, sif_coefficient, use_subword)
86
75
 
76
+ device = select_optimal_device(device)
87
77
  # Make a base list of tokens.
88
78
  tokens: list[str] = []
89
79
  if use_subword:
@@ -129,7 +119,7 @@ def distill_from_model(
129
119
  logger.warning("Didn't create any token embeddings as all tokens were duplicates or empty.")
130
120
 
131
121
  # Post process the embeddings by applying PCA and Zipf weighting.
132
- embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
122
+ embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
133
123
 
134
124
  model_name = getattr(model, "name_or_path", "")
135
125
 
@@ -139,8 +129,10 @@ def distill_from_model(
139
129
  "tokenizer_name": model_name,
140
130
  "apply_pca": pca_dims,
141
131
  "apply_zipf": apply_zipf,
132
+ "sif_coefficient": sif_coefficient,
142
133
  "hidden_dim": embeddings.shape[1],
143
134
  "seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
135
+ "normalize": True,
144
136
  }
145
137
 
146
138
  if os.path.exists(model_name):
@@ -157,10 +149,71 @@ def distill_from_model(
157
149
  language = None
158
150
 
159
151
  return StaticModel(
160
- vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
152
+ vectors=embeddings,
153
+ tokenizer=new_tokenizer,
154
+ config=config,
155
+ base_model_name=model_name,
156
+ language=language,
157
+ normalize=True,
161
158
  )
162
159
 
163
160
 
161
+ def _validate_parameters(
162
+ tokenizer: PreTrainedTokenizerFast,
163
+ vocabulary: list[str] | None,
164
+ apply_zipf: bool | None,
165
+ sif_coefficient: float | None,
166
+ use_subword: bool,
167
+ ) -> float | None:
168
+ """
169
+ Validate the parameters passed to the distillation function.
170
+
171
+ :param tokenizer: The tokenizer to use.
172
+ :param vocabulary: The vocabulary to use.
173
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
174
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
175
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
176
+ Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
177
+ :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.
178
+ :return: The SIF coefficient to use.
179
+ :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
180
+ :raises: ValueError if the vocabulary contains duplicate tokens.
181
+ :raises: ValueError if the regex can't be compiled.
182
+ :raises: ValueError if the vocabulary is empty after token removal.
183
+
184
+ """
185
+ if apply_zipf is not None:
186
+ logger.warning(
187
+ "The `apply_zipf` parameter is deprecated and will be removed in the next release. "
188
+ "Zipf weighting is applied based on the sif_coefficient parameter. If this is set to None, "
189
+ "no weighting is applied."
190
+ )
191
+ if apply_zipf and sif_coefficient is None:
192
+ logger.warning("You set apply_zipf to True, but sif_coefficient is None. Setting sif_coefficient to 1e-4.")
193
+ sif_coefficient = 1e-4
194
+ elif not apply_zipf:
195
+ logger.warning("Because you set apply_zipf to False, we ignore the sif_coefficient parameter.")
196
+ sif_coefficient = None
197
+
198
+ if sif_coefficient is not None:
199
+ if not 0 < sif_coefficient < 1.0:
200
+ raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
201
+
202
+ if not use_subword and vocabulary is None:
203
+ raise ValueError(
204
+ "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
205
+ )
206
+
207
+ if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
208
+ raise ValueError(
209
+ "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
210
+ "This is not supported yet."
211
+ "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
212
+ )
213
+
214
+ return sif_coefficient
215
+
216
+
164
217
  def _remove_tokens_and_embeddings(
165
218
  tokenizer: PreTrainedTokenizerFast, token_remove_pattern: str | None, tokens: list[str], embeddings: np.ndarray
166
219
  ) -> tuple[Tokenizer, np.ndarray]:
@@ -201,9 +254,11 @@ def distill(
201
254
  vocabulary: list[str] | None = None,
202
255
  device: str | None = None,
203
256
  pca_dims: PCADimType = 256,
204
- apply_zipf: bool = True,
257
+ apply_zipf: bool | None = None,
258
+ sif_coefficient: float | None = 1e-4,
205
259
  use_subword: bool = True,
206
260
  token_remove_pattern: str | None = r"\[unused\d+\]",
261
+ trust_remote_code: bool = False,
207
262
  ) -> StaticModel:
208
263
  """
209
264
  Distill a staticmodel from a sentence transformer.
@@ -220,14 +275,18 @@ def distill(
220
275
  :param pca_dims: The number of components to use for PCA.
221
276
  If this is None, we don't apply PCA.
222
277
  If this is 'auto', we don't reduce dimenionality, but still apply PCA.
223
- :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
278
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
279
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
280
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
281
+ Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
224
282
  :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.
225
283
  :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
284
+ :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `transformers`. If this is True, we will load all components.
226
285
  :return: A StaticModel
227
286
 
228
287
  """
229
- model: PreTrainedModel = AutoModel.from_pretrained(model_name)
230
- tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
288
+ model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)
289
+ tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code)
231
290
 
232
291
  return distill_from_model(
233
292
  model=model,
@@ -238,11 +297,14 @@ def distill(
238
297
  apply_zipf=apply_zipf,
239
298
  use_subword=use_subword,
240
299
  token_remove_pattern=token_remove_pattern,
300
+ sif_coefficient=sif_coefficient,
241
301
  )
242
302
 
243
303
 
244
- def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
245
- """Post process embeddings by applying PCA and Zipf weighting."""
304
+ def _post_process_embeddings(
305
+ embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4
306
+ ) -> np.ndarray:
307
+ """Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law."""
246
308
  if pca_dims is not None:
247
309
  if pca_dims == "auto":
248
310
  pca_dims = embeddings.shape[1]
@@ -274,9 +336,11 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
274
336
  logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
275
337
  logger.info(f"Explained variance: {explained_variance:.3f}.")
276
338
 
277
- if apply_zipf:
278
- logger.info("Applying Zipf weighting")
279
- embeddings *= np.log(1 + np.arange(embeddings.shape[0]))[:, None]
339
+ if sif_coefficient is not None:
340
+ logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
341
+ inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
342
+ proba = inv_rank / np.sum(inv_rank)
343
+ embeddings *= (sif_coefficient / (sif_coefficient + proba))[:, None]
280
344
 
281
345
  return embeddings
282
346
 
@@ -1,2 +1,2 @@
1
- __version_triple__ = (0, 3, 8)
1
+ __version_triple__ = (0, 3, 9)
2
2
  __version__ = ".".join(map(str, __version_triple__))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: model2vec
3
- Version: 0.3.8
3
+ Version: 0.3.9
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
@@ -108,11 +108,12 @@ Requires-Dist: torch; extra == "onnx"
108
108
  <img src="assets/images/model2vec_model_diagram_transparant_light.png#gh-light-mode-only" width="90%">
109
109
  </div>
110
110
 
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.
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-32M) 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.
112
112
 
113
113
 
114
114
  ## Updates & Announcements
115
115
 
116
+ - **30/01/2024**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
116
117
  - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
117
118
 
118
119
  ## Table of Contents
@@ -560,9 +561,11 @@ We provide a number of models that can be used out of the box. These models are
560
561
 
561
562
  | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
562
563
  |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|-------------------|
564
+ | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
563
565
  | [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
566
  | [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
567
  | [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> |
568
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | Output + Frequent C4 tokens | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 32.3M | <div align="center">✅</div> |
566
569
  | [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
570
 
568
571
 
@@ -18,6 +18,7 @@ assets/images/speed_vs_accuracy_v3.png
18
18
  assets/images/speed_vs_accuracy_v4.png
19
19
  assets/images/speed_vs_mteb_score.png
20
20
  assets/images/speed_vs_mteb_score_v2.png
21
+ assets/images/speed_vs_mteb_score_v3.png
21
22
  assets/images/tutorial_ezlo.png
22
23
  model2vec/__init__.py
23
24
  model2vec/hf_utils.py
@@ -36,6 +37,7 @@ model2vec/distill/inference.py
36
37
  model2vec/distill/tokenizer.py
37
38
  model2vec/distill/utils.py
38
39
  results/README.md
40
+ results/make_speed_vs_mteb_plot.py
39
41
  scripts/export_to_onnx.py
40
42
  tests/__init__.py
41
43
  tests/conftest.py
@@ -13,14 +13,16 @@ Note: The `potion` and `M2V` models are our static models.
13
13
  | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
14
14
  |:-----------------------|------------:|-------------:|--------:|--------:|------------:|-------:|-------:|-------:|-------:|--------:|----------:|
15
15
  | [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/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 |
16
- | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | 50.54 | 50.03 | 64.44 | 32.93 | 76.62 | 49.73 | 31.71 | 73.24 | 29.28 | 53.54 | 50.75 |
17
- | [M2V_base_glove_subword](https://huggingface.co/minishlab/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 |
18
- | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | 48.87 | 48.23 | 62.19 | 31.47 | 75.37 | 48.75 | 29.11 | 72.19 | 28.89 | 52.55 | 49.21 |
19
- | [M2V_base_glove](https://huggingface.co/minishlab/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 |
20
- | [M2V_base_output](https://huggingface.co/minishlab/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 |
21
- | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | 45.52 | 44.77 | 58.45 | 27.5 | 73.72 | 46.82 | 24.13 | 70.14 | 31.51 | 50.82 | 44.72 |
22
- | [GloVe_300d](https://huggingface.co/sentence-transformers/average_word_embeddings_glove.6B.300d) | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
23
- | [BPEmb_50k_300d](https://github.com/bheinzerling/bpemb) | 39.34 | 37.78 | 55.76 | 23.35 | 57.86 | 43.21 | 17.5 | 55.1 | 29.74 | 47.56 | 41.28 |
16
+ | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | 52.46 | 51.66 | 65.97 | 35.29 | 78.17 | 50.92 | 33.52 | 74.22 | 29.78 | 55.37 | 55.15 |
17
+ | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | 50.54 | 50.03 | 64.44 | 32.93 | 76.62 | 49.73 | 31.71 | 73.24 | 29.28 | 53.54 | 50.75 |
18
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | 49.73 | 49.76 | 59.56 | 30.55 | 76.38 | 50.05 | 36.35 | 73.22 | 28.85 | 49.31 | 50.02 |
19
+ | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | 48.87 | 48.23 | 62.19 | 31.47 | 75.37 | 48.75 | 29.11 | 72.19 | 28.89 | 52.55 | 49.21 |
20
+ | [static-retrieval-mrl-en-v1](https://huggingface.co/minishlab/static-retrieval-mrl-en-v1) | 48.18 | 48.36 | 57.39 | 28.32 | 75.63 | 49.16 | 35.61 | 72.18 | 28.64 | 49.68 | 44.76 |
21
+ | [static-similarity-mrl-multilingual-v1](https://huggingface.co/minishlab/static-similarity-mrl-multilingual-v1) | 48.15 | 47.15 | 59.96 | 24.40 | 79.02 | 48.25 | 29.54 | 74.88 | 30.28 | 51.66 | 51.66 |
22
+ | [M2V_base_output](https://huggingface.co/minishlab/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 |
23
+ | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | 45.52 | 44.77 | 58.45 | 27.5 | 73.72 | 46.82 | 24.13 | 70.14 | 31.51 | 50.82 | 44.72 |
24
+ | [GloVe_300d](https://huggingface.co/sentence-transformers/average_word_embeddings_glove.6B.300d) | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
25
+ | [BPEmb_50k_300d](https://github.com/bheinzerling/bpemb) | 39.34 | 37.78 | 55.76 | 23.35 | 57.86 | 43.21 | 17.5 | 55.1 | 29.74 | 47.56 | 41.28 |
24
26
 
25
27
 
26
28
  <details>
@@ -36,14 +38,33 @@ For readability, the MTEB task names are abbreviated as follows:
36
38
  - Sum: Summarization
37
39
  </details>
38
40
 
41
+ The results show that [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model. It reaches 92.11% of the performance of [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) with an average MTEB score of 51.66 while being orders of magnitude faster.
42
+
43
+ Note: the [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M), [static-retrieval-mrl-en-v1](https://huggingface.co/minishlab/static-retrieval-mrl-en-v1), and [static-similarity-mrl-multilingual-v1](https://huggingface.co/minishlab/static-similarity-mrl-multilingual-v1) models are task-specific models. We've included them for completeness, but they should not be compared directly to the other models for tasks that they are not designed for.
44
+
39
45
  The figure below shows the relationship between the number of sentences per second and the average MTEB score. The circle sizes correspond to the number of parameters in the models (larger = more parameters).
40
46
  This plot shows that the potion and M2V models are much faster than the other models, while still being competitive in terms of performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
47
+ NOTE: for fairness of comparison, we disabled multiprocessing for Model2Vec for this benchmark. All sentence-transformers models are run with the [sentence-transformers](https://github.com/UKPLab/sentence-transformers) library's default settings for `encode`.
41
48
 
42
- | ![Description](../assets/images/speed_vs_mteb_score_v2.png) |
49
+ | ![Description](../assets/images/speed_vs_mteb_score_v3.png) |
43
50
  |:--:|
44
51
  |*Figure: The average MTEB score plotted against sentences per second. The circle size indicates model size.*|
45
52
 
46
53
 
54
+ ## Retrieval Results
55
+
56
+ A subset of models we created and compare against are specifically designed for retrieval tasks. The results are shown in the table below, including two general-purpose models for comparison and a transformer.
57
+
58
+ | Model | Retrieval Score |
59
+ |:-----------------------|------------------:|
60
+ | [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) | 41.95 |
61
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | 36.35 |
62
+ | [static-retrieval-mrl-en-v1](https://huggingface.co/minishlab/static-retrieval-mrl-en-v1) | 35.61 |
63
+ | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | 33.52 |
64
+ | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | 31.71 |
65
+
66
+ As can be seen, [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) model is the most performant static retrieval model, reaching 86.65%% of the performance of [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) with a retrieval score of 36.35.
67
+
47
68
  ## Ablations
48
69
 
49
70
  To better understand the factors contributing to the performance of Model2Vec, we conducted a comprehensive set of ablation studies, covering various aspects of the model's architecture and preprocessing methods. In these studies, we examined the impact of key elements such as PCA, Zipf weighting, and the use of Sentence Transformers versus regular transformer models. We also compared the performance of input embeddings versus output embeddings, since it would seem plausible that these should also work well. The results are shown in the table below.
@@ -0,0 +1,184 @@
1
+ """Script to benchmark the speed of various text embedding models and generate a plot of the MTEB score vs samples per second."""
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ from pathlib import Path
7
+ from time import perf_counter
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from bpemb import BPEmb
13
+ from datasets import load_dataset
14
+ from plotnine import (
15
+ aes,
16
+ element_line,
17
+ geom_point,
18
+ geom_text,
19
+ ggplot,
20
+ guides,
21
+ labs,
22
+ scale_size,
23
+ scale_y_continuous,
24
+ theme,
25
+ theme_classic,
26
+ xlim,
27
+ ylim,
28
+ )
29
+ from sentence_transformers import SentenceTransformer
30
+
31
+ from model2vec import StaticModel
32
+
33
+ logging.basicConfig(level=logging.INFO)
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class BPEmbEmbedder:
39
+ def __init__(self, vs: int = 50_000, dim: int = 300) -> None:
40
+ """Initialize the BPEmbEmbedder."""
41
+ self.bpemb_en = BPEmb(lang="en", vs=vs, dim=dim)
42
+
43
+ def mean_sentence_embedding(self, sentence: str) -> np.ndarray:
44
+ """Encode a sentence to a mean embedding."""
45
+ encoded_ids = self.bpemb_en.encode_ids(sentence)
46
+ embeddings = self.bpemb_en.vectors[encoded_ids]
47
+ if embeddings.size == 0:
48
+ return np.zeros(self.bpemb_en.dim) # Return a zero vector if no tokens are found
49
+ return embeddings.mean(axis=0)
50
+
51
+ def encode(self, sentences: list[str], **kwargs: Any) -> np.ndarray:
52
+ """Encode a list of sentences to embeddings."""
53
+ return np.array([self.mean_sentence_embedding(sentence.lower()) for sentence in sentences])
54
+
55
+
56
+ def make_plot(df: pd.DataFrame) -> ggplot:
57
+ """Create a plot of the MTEB score vs samples per second."""
58
+ df["label_y"] = (
59
+ df["Average score"]
60
+ + 0.5 # a constant "base" offset for all bubbles
61
+ + 0.08 * np.sqrt(df["Params (Million)"])
62
+ )
63
+ plot = (
64
+ ggplot(df, aes(x="Samples per second", y="Average score"))
65
+ + geom_point(aes(size="Params (Million)", color="Model"))
66
+ + geom_text(aes(y="label_y", label="Model"), color="black", size=7)
67
+ + scale_size(range=(2, 30))
68
+ + theme_classic()
69
+ + labs(title="Average MTEB Score vs Samples per Second")
70
+ + ylim(df["Average score"].min(), df["Average score"].max() + 3)
71
+ + scale_y_continuous(breaks=range(30, 70, 5))
72
+ + theme(
73
+ panel_grid_major=element_line(color="lightgrey", size=0.5),
74
+ panel_grid_minor=element_line(color="lightgrey", size=0.25),
75
+ figure_size=(10, 6),
76
+ )
77
+ + xlim(0, df["Samples per second"].max() + 100)
78
+ + guides(None)
79
+ )
80
+ return plot
81
+
82
+
83
+ def benchmark_model(name: str, info: list[str], texts: list[str]) -> dict[str, float | str]:
84
+ """Benchmark a single model."""
85
+ logger.info("Starting", name)
86
+ if info[1] == "BPEmb":
87
+ model = BPEmbEmbedder(vs=50_000, dim=300) # type: ignore
88
+ elif info[1] == "ST":
89
+ model = SentenceTransformer(info[0], device="cpu") # type: ignore
90
+ else:
91
+ model = StaticModel.from_pretrained(info[0]) # type: ignore
92
+
93
+ start = perf_counter()
94
+ if info[1] == "M2V":
95
+ # If the model is a model2vec model, disable multiprocessing for a fair comparison
96
+ model.encode(texts, use_multiprocessing=False)
97
+ else:
98
+ model.encode(texts)
99
+
100
+ total_time = perf_counter() - start
101
+ docs_per_second = len(texts) / total_time
102
+
103
+ logger.info(f"{name}: {docs_per_second} docs per second")
104
+ logger.info(f"Total time: {total_time}")
105
+
106
+ return {"docs_per_second": docs_per_second, "total_time": total_time}
107
+
108
+
109
+ def main(save_path: str, n_texts: int) -> None:
110
+ """Benchmark text embedding models and generate a plot."""
111
+ # Define the models to benchmark
112
+ models: dict[str, list[str]] = {
113
+ "BPEmb-50k-300d": ["", "BPEmb"],
114
+ "all-MiniLM-L6-v2": ["sentence-transformers/all-MiniLM-L6-v2", "ST"],
115
+ "bge-base-en-v1.5": ["BAAI/bge-base-en-v1.5", "ST"],
116
+ "GloVe 6B 300d": ["sentence-transformers/average_word_embeddings_glove.6B.300d", "ST"],
117
+ "potion-base-8M": ["minishlab/potion-base-8M", "M2V"],
118
+ }
119
+
120
+ # Load the dataset
121
+ ds = load_dataset("wikimedia/wikipedia", data_files="20231101.en/train-00000-of-00041.parquet")["train"]
122
+ texts = ds["text"][:n_texts]
123
+
124
+ summarized_results = [
125
+ {"Model": "potion-base-2M", "Average score": 44.77, "Samples per second": None, "Params (Million)": 1.875},
126
+ {"Model": "GloVe 6B 300d", "Average score": 42.36, "Samples per second": None, "Params (Million)": 120.000},
127
+ {"Model": "potion-base-4M", "Average score": 48.23, "Samples per second": None, "Params (Million)": 3.750},
128
+ {"Model": "all-MiniLM-L6-v2", "Average score": 56.09, "Samples per second": None, "Params (Million)": 23.000},
129
+ {"Model": "potion-base-8M", "Average score": 50.03, "Samples per second": None, "Params (Million)": 7.500},
130
+ {"Model": "bge-base-en-v1.5", "Average score": 63.56, "Samples per second": None, "Params (Million)": 109.000},
131
+ {"Model": "M2V_base_output", "Average score": 45.34, "Samples per second": None, "Params (Million)": 7.500},
132
+ {"Model": "BPEmb-50k-300d", "Average score": 37.78, "Samples per second": None, "Params (Million)": 15.000},
133
+ {"Model": "potion-base-32M", "Average score": 51.66, "Samples per second": None, "Params (Million)": 32.300},
134
+ ]
135
+
136
+ timings = {}
137
+
138
+ for name, info in models.items():
139
+ timing = benchmark_model(name, info, texts)
140
+ timings[name] = timing
141
+ # Update summarized results
142
+ for result in summarized_results:
143
+ if result["Model"] == name:
144
+ result["Samples per second"] = timing["docs_per_second"]
145
+
146
+ # Set potion-base-8M as the reference speed for the other potion models
147
+ potion_base_8m_speed = next(
148
+ result["Samples per second"] for result in summarized_results if result["Model"] == "potion-base-8M"
149
+ )
150
+ for model_name in ["M2V_base_output", "potion-base-2M", "potion-base-4M", "potion-base-32M"]:
151
+ for result in summarized_results:
152
+ if result["Model"] == model_name:
153
+ result["Samples per second"] = potion_base_8m_speed
154
+
155
+ # Ensure save_path is a directory
156
+ save_dir = Path(save_path)
157
+ save_dir.mkdir(parents=True, exist_ok=True)
158
+
159
+ # Save timings to JSON
160
+ json_path = save_dir / "speed_benchmark_results.json"
161
+ with open(json_path, "w") as file:
162
+ json.dump(timings, file, indent=4)
163
+
164
+ # Create and save the plot
165
+ df = pd.DataFrame(summarized_results)
166
+ plot = make_plot(df)
167
+ plot_path = save_dir / "speed_vs_mteb_plot.png"
168
+ plot.save(plot_path, width=12, height=10)
169
+
170
+ logger.info(f"Timings saved to {json_path}")
171
+ logger.info(f"Plot saved to {plot_path}")
172
+
173
+
174
+ if __name__ == "__main__":
175
+ parser = argparse.ArgumentParser(description="Benchmark text embedding models and generate a plot.")
176
+ parser.add_argument(
177
+ "--save-path", type=str, required=True, help="Directory to save the benchmark results and plot."
178
+ )
179
+ parser.add_argument(
180
+ "--n-texts", type=int, default=100_000, help="Number of texts to use from the dataset for benchmarking."
181
+ )
182
+ args = parser.parse_args()
183
+
184
+ main(save_path=args.save_path, n_texts=args.n_texts)
@@ -160,22 +160,29 @@ def test_distill_removal_pattern(
160
160
 
161
161
 
162
162
  @pytest.mark.parametrize(
163
- "vocabulary, use_subword, pca_dims, apply_zipf, expected_shape",
163
+ "vocabulary, use_subword, pca_dims, apply_zipf, sif_coefficient, expected_shape",
164
164
  [
165
- (None, True, 256, True, (29528, 256)), # Output vocab with subwords, PCA applied
165
+ (None, True, 256, True, None, (29528, 256)), # Output vocab with subwords, PCA applied
166
166
  (
167
167
  ["wordA", "wordB"],
168
168
  False,
169
169
  4,
170
170
  False,
171
+ None,
171
172
  (7, 4),
172
173
  ), # Custom vocab without subword , PCA applied
173
- (None, True, "auto", False, (29528, 768)), # Subword, PCA set to 'auto'
174
- (None, True, 1024, False, (29528, 768)), # Subword, PCA set to high number.
175
- (["wordA", "wordB"], True, 4, False, (29530, 4)), # Custom vocab with subword, PCA applied
176
- (None, True, None, True, (29528, 768)), # No PCA applied
177
- (["wordA", "wordB"], False, 4, True, (7, 4)), # Custom vocab without subwords PCA and Zipf applied
178
- (None, False, 256, True, None), # use_subword = False without passing a vocabulary should raise an error
174
+ (None, True, "auto", False, None, (29528, 768)), # Subword, PCA set to 'auto'
175
+ (None, True, "auto", True, 1e-4, (29528, 768)), # Subword, PCA set to 'auto'
176
+ (None, True, "auto", False, 1e-4, (29528, 768)), # Subword, PCA set to 'auto'
177
+ (None, True, "auto", True, 0, None), # Sif too low
178
+ (None, True, "auto", True, 1, None), # Sif too high
179
+ (None, True, "auto", False, 0, (29528, 768)), # Sif too low, but apply_zipf is False
180
+ (None, True, "auto", False, 1, (29528, 768)), # Sif too high, but apply_zipf is False
181
+ (None, True, 1024, False, None, (29528, 768)), # Subword, PCA set to high number.
182
+ (["wordA", "wordB"], True, 4, False, None, (29530, 4)), # Custom vocab with subword, PCA applied
183
+ (None, True, None, True, None, (29528, 768)), # No PCA applied
184
+ (["wordA", "wordB"], False, 4, True, None, (7, 4)), # Custom vocab without subwords PCA and Zipf applied
185
+ (None, False, 256, True, None, None), # use_subword = False without passing a vocabulary should raise an error
179
186
  ],
180
187
  )
181
188
  @patch.object(import_module("model2vec.distill.distillation"), "model_info")
@@ -188,6 +195,7 @@ def test_distill(
188
195
  use_subword: bool,
189
196
  pca_dims: int | None,
190
197
  apply_zipf: bool,
198
+ sif_coefficient: float | None,
191
199
  expected_shape: tuple[int, int],
192
200
  ) -> None:
193
201
  """Test distill function with different parameters."""
@@ -208,7 +216,25 @@ def test_distill(
208
216
  pca_dims=pca_dims,
209
217
  apply_zipf=apply_zipf,
210
218
  use_subword=use_subword,
219
+ sif_coefficient=sif_coefficient,
211
220
  )
221
+ elif (
222
+ apply_zipf is not None
223
+ and apply_zipf
224
+ and sif_coefficient is not None
225
+ and (sif_coefficient <= 0 or sif_coefficient >= 1)
226
+ ):
227
+ with pytest.raises(ValueError):
228
+ static_model = distill(
229
+ model_name=model_name,
230
+ vocabulary=vocabulary,
231
+ device="cpu",
232
+ pca_dims=pca_dims,
233
+ apply_zipf=apply_zipf,
234
+ use_subword=use_subword,
235
+ sif_coefficient=sif_coefficient,
236
+ )
237
+
212
238
  else:
213
239
  # Call the distill function with the parametrized inputs
214
240
  static_model = distill(
@@ -218,6 +244,7 @@ def test_distill(
218
244
  pca_dims=pca_dims,
219
245
  apply_zipf=apply_zipf,
220
246
  use_subword=use_subword,
247
+ sif_coefficient=sif_coefficient,
221
248
  )
222
249
 
223
250
  # Assert the model is correctly generated
@@ -240,16 +267,16 @@ def test_missing_modelinfo(
240
267
 
241
268
 
242
269
  @pytest.mark.parametrize(
243
- "embeddings, pca_dims, apply_zipf, expected_shape",
270
+ "embeddings, pca_dims, sif_coefficient, expected_shape",
244
271
  [
245
- (rng.random((1000, 768)), 256, False, (1000, 256)), # PCA applied correctly
246
- (rng.random((1000, 768)), None, False, (1000, 768)), # No PCA applied, dimensions remain unchanged
247
- (rng.random((1000, 768)), 256, True, (1000, 256)), # PCA and Zipf applied
248
- (rng.random((10, 768)), 256, False, (10, 768)), # PCA dims higher than vocab size, no PCA applied
272
+ (rng.random((1000, 768)), 256, None, (1000, 256)), # PCA applied correctly
273
+ (rng.random((1000, 768)), None, None, (1000, 768)), # No PCA applied, dimensions remain unchanged
274
+ (rng.random((1000, 768)), 256, 1e-4, (1000, 256)), # PCA and Zipf applied
275
+ (rng.random((10, 768)), 256, 1e-4, (10, 768)), # PCA dims higher than vocab size, no PCA applied
249
276
  ],
250
277
  )
251
278
  def test__post_process_embeddings(
252
- embeddings: np.ndarray, pca_dims: int, apply_zipf: bool, expected_shape: tuple[int, int]
279
+ embeddings: np.ndarray, pca_dims: int, sif_coefficient: float | None, expected_shape: tuple[int, int]
253
280
  ) -> None:
254
281
  """Test the _post_process_embeddings function."""
255
282
  original_embeddings = embeddings.copy() # Copy embeddings to compare later
@@ -257,18 +284,21 @@ def test__post_process_embeddings(
257
284
  # Test that the function raises an error if the PCA dims are larger than the number of dimensions
258
285
  if pca_dims and pca_dims > embeddings.shape[1]:
259
286
  with pytest.raises(ValueError):
260
- _post_process_embeddings(embeddings, pca_dims, False)
287
+ _post_process_embeddings(embeddings, pca_dims, None)
261
288
 
262
- processed_embeddings = _post_process_embeddings(embeddings, pca_dims, apply_zipf)
289
+ processed_embeddings = _post_process_embeddings(embeddings, pca_dims, sif_coefficient)
263
290
 
264
291
  # Assert the shape is correct
265
292
  assert processed_embeddings.shape == expected_shape
266
293
 
267
294
  # If Zipf weighting is applied compare the original and processed embeddings
268
295
  # and check the weights are applied correctly
269
- if apply_zipf and pca_dims is None:
270
- zipf_weights = np.log(1 + np.arange(embeddings.shape[0]))[:, None]
271
- expected_zipf_embeddings = original_embeddings * zipf_weights
296
+ if sif_coefficient and pca_dims is None:
297
+ inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
298
+ proba = inv_rank / np.sum(inv_rank)
299
+ sif_weights = (sif_coefficient / (sif_coefficient + proba))[:, None]
300
+
301
+ expected_zipf_embeddings = original_embeddings * sif_weights
272
302
  assert np.allclose(
273
303
  processed_embeddings, expected_zipf_embeddings, rtol=1e-5
274
304
  ), "Zipf weighting not applied correctly"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes