model2vec 0.4.0__tar.gz → 0.5.0__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 (77) hide show
  1. {model2vec-0.4.0 → model2vec-0.5.0}/PKG-INFO +17 -11
  2. {model2vec-0.4.0 → model2vec-0.5.0}/README.md +14 -9
  3. model2vec-0.5.0/assets/images/training_speed_vs_score.png +0 -0
  4. {model2vec-0.4.0 → model2vec-0.5.0}/docs/usage.md +48 -0
  5. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/distill/distillation.py +90 -116
  6. model2vec-0.5.0/model2vec/distill/inference.py +149 -0
  7. model2vec-0.5.0/model2vec/distill/tokenizer.py +197 -0
  8. model2vec-0.5.0/model2vec/distill/utils.py +58 -0
  9. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/hf_utils.py +46 -25
  10. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/inference/__init__.py +2 -2
  11. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/inference/model.py +115 -11
  12. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/model.py +93 -14
  13. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/modelcards/classifier_template.md +7 -6
  14. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/modelcards/model_card_template.md +35 -14
  15. model2vec-0.5.0/model2vec/quantization.py +63 -0
  16. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/train/README.md +47 -4
  17. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/train/base.py +15 -5
  18. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/train/classifier.py +159 -54
  19. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/version.py +1 -1
  20. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec.egg-info/PKG-INFO +17 -11
  21. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec.egg-info/SOURCES.txt +4 -0
  22. {model2vec-0.4.0 → model2vec-0.5.0}/pyproject.toml +5 -1
  23. {model2vec-0.4.0 → model2vec-0.5.0}/results/README.md +39 -26
  24. {model2vec-0.4.0 → model2vec-0.5.0}/scripts/export_to_onnx.py +3 -1
  25. model2vec-0.5.0/tests/__init__.py +0 -0
  26. {model2vec-0.4.0 → model2vec-0.5.0}/tests/conftest.py +43 -13
  27. {model2vec-0.4.0 → model2vec-0.5.0}/tests/test_distillation.py +51 -94
  28. {model2vec-0.4.0 → model2vec-0.5.0}/tests/test_inference.py +44 -6
  29. {model2vec-0.4.0 → model2vec-0.5.0}/tests/test_model.py +59 -0
  30. model2vec-0.5.0/tests/test_quantization.py +30 -0
  31. {model2vec-0.4.0 → model2vec-0.5.0}/tests/test_trainable.py +32 -7
  32. model2vec-0.5.0/tutorials/semantic_chunking.ipynb +268 -0
  33. {model2vec-0.4.0 → model2vec-0.5.0}/uv.lock +1 -1
  34. model2vec-0.4.0/model2vec/distill/inference.py +0 -167
  35. model2vec-0.4.0/model2vec/distill/tokenizer.py +0 -122
  36. model2vec-0.4.0/model2vec/distill/utils.py +0 -28
  37. model2vec-0.4.0/tutorials/semantic_chunking.ipynb +0 -261
  38. {model2vec-0.4.0 → model2vec-0.5.0}/.github/workflows/ci.yaml +0 -0
  39. {model2vec-0.4.0 → model2vec-0.5.0}/.gitignore +0 -0
  40. {model2vec-0.4.0 → model2vec-0.5.0}/.pre-commit-config.yaml +0 -0
  41. {model2vec-0.4.0 → model2vec-0.5.0}/LICENSE +0 -0
  42. {model2vec-0.4.0 → model2vec-0.5.0}/Makefile +0 -0
  43. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/logo.png +0 -0
  44. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/logo_v2.png +0 -0
  45. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/model2vec_model_diagram.png +0 -0
  46. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
  47. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
  48. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  49. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_accuracy.png +0 -0
  50. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v2.png +0 -0
  51. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v3.png +0 -0
  52. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v4.png +0 -0
  53. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score.png +0 -0
  54. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score_v2.png +0 -0
  55. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  56. {model2vec-0.4.0 → model2vec-0.5.0}/assets/images/tutorial_ezlo.png +0 -0
  57. {model2vec-0.4.0 → model2vec-0.5.0}/docs/README.md +0 -0
  58. {model2vec-0.4.0 → model2vec-0.5.0}/docs/integrations.md +0 -0
  59. {model2vec-0.4.0 → model2vec-0.5.0}/docs/what_is_model2vec.md +0 -0
  60. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/__init__.py +0 -0
  61. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/distill/__init__.py +0 -0
  62. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/inference/README.md +0 -0
  63. /model2vec-0.4.0/tests/__init__.py → /model2vec-0.5.0/model2vec/py.typed +0 -0
  64. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/train/__init__.py +0 -0
  65. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec/utils.py +0 -0
  66. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec.egg-info/dependency_links.txt +0 -0
  67. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec.egg-info/requires.txt +0 -0
  68. {model2vec-0.4.0 → model2vec-0.5.0}/model2vec.egg-info/top_level.txt +0 -0
  69. {model2vec-0.4.0 → model2vec-0.5.0}/results/make_speed_vs_mteb_plot.py +0 -0
  70. {model2vec-0.4.0 → model2vec-0.5.0}/setup.cfg +0 -0
  71. {model2vec-0.4.0 → model2vec-0.5.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  72. {model2vec-0.4.0 → model2vec-0.5.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
  73. {model2vec-0.4.0 → model2vec-0.5.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  74. {model2vec-0.4.0 → model2vec-0.5.0}/tests/test_utils.py +0 -0
  75. {model2vec-0.4.0 → model2vec-0.5.0}/tutorials/README.md +0 -0
  76. {model2vec-0.4.0 → model2vec-0.5.0}/tutorials/recipe_search.ipynb +0 -0
  77. {model2vec-0.4.0 → model2vec-0.5.0}/tutorials/train_classifier.ipynb +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: model2vec
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Fast State-of-the-Art Static Embeddings
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
@@ -74,6 +74,7 @@ Requires-Dist: skops; extra == "train"
74
74
  Provides-Extra: inference
75
75
  Requires-Dist: scikit-learn; extra == "inference"
76
76
  Requires-Dist: skops; extra == "inference"
77
+ Dynamic: license-file
77
78
 
78
79
 
79
80
  <div align="center">
@@ -102,20 +103,24 @@ Requires-Dist: skops; extra == "inference"
102
103
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
103
104
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
104
105
  <a href="https://pepy.tech/project/model2vec">
105
- <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
106
+ <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
106
107
  </a>
107
108
  <a href="https://app.codecov.io/gh/MinishLab/model2vec">
108
- <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
109
+ <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
109
110
  </a>
111
+ <a href="https://discord.gg/4BDPR5nmtK">
112
+ <img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
113
+ </a>
114
+ <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
115
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
110
116
  </a>
111
- <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
112
-
113
117
  </h2>
114
118
  </div>
115
119
 
116
120
 
117
121
 
118
122
 
123
+
119
124
  Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by a factor up to 50 and making the models up to 500 times 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.
120
125
 
121
126
  <div align="center">
@@ -182,21 +187,22 @@ from model2vec.train import StaticModelForClassification
182
187
  # Initialize a classifier from a pre-trained model
183
188
  classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
184
189
 
185
- # Load a dataset
190
+ # Load a dataset. Note: both single and multi-label classification datasets are supported
186
191
  ds = load_dataset("setfit/subj")
187
192
 
188
193
  # Train the classifier on text (X) and labels (y)
189
194
  classifier.fit(ds["train"]["text"], ds["train"]["label"])
190
195
 
191
196
  # Evaluate the classifier
192
- predictions = classifier.predict(ds["test"]["text"])
193
- accuracy = np.mean(np.array(predictions) == np.array(ds["test"]["label"])) * 100
197
+ classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["label"])
194
198
  ```
195
199
 
196
200
  For advanced usage, please refer to our [usage documentation](https://github.com/MinishLab/model2vec/blob/main/docs/usage.md).
197
201
 
198
202
  ## Updates & Announcements
199
203
 
204
+ - **01/05/2024**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
205
+
200
206
  - **12/02/2024**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
201
207
 
202
208
  - **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.
@@ -262,8 +268,8 @@ MIT
262
268
 
263
269
  If you use Model2Vec in your research, please cite the following:
264
270
  ```bibtex
265
- @software{minishlab2024model2vec,
266
- authors = {Stephan Tulkens and Thomas van Dongen},
271
+ @article{minishlab2024model2vec,
272
+ author = {Tulkens, Stephan and {van Dongen}, Thomas},
267
273
  title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
268
274
  year = {2024},
269
275
  url = {https://github.com/MinishLab/model2vec}
@@ -25,20 +25,24 @@
25
25
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
26
26
  <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
27
27
  <a href="https://pepy.tech/project/model2vec">
28
- <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
28
+ <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
29
29
  </a>
30
30
  <a href="https://app.codecov.io/gh/MinishLab/model2vec">
31
- <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
31
+ <img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
32
32
  </a>
33
+ <a href="https://discord.gg/4BDPR5nmtK">
34
+ <img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
35
+ </a>
36
+ <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
37
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
33
38
  </a>
34
- <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
35
-
36
39
  </h2>
37
40
  </div>
38
41
 
39
42
 
40
43
 
41
44
 
45
+
42
46
  Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by a factor up to 50 and making the models up to 500 times 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.
43
47
 
44
48
  <div align="center">
@@ -105,21 +109,22 @@ from model2vec.train import StaticModelForClassification
105
109
  # Initialize a classifier from a pre-trained model
106
110
  classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
107
111
 
108
- # Load a dataset
112
+ # Load a dataset. Note: both single and multi-label classification datasets are supported
109
113
  ds = load_dataset("setfit/subj")
110
114
 
111
115
  # Train the classifier on text (X) and labels (y)
112
116
  classifier.fit(ds["train"]["text"], ds["train"]["label"])
113
117
 
114
118
  # Evaluate the classifier
115
- predictions = classifier.predict(ds["test"]["text"])
116
- accuracy = np.mean(np.array(predictions) == np.array(ds["test"]["label"])) * 100
119
+ classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["label"])
117
120
  ```
118
121
 
119
122
  For advanced usage, please refer to our [usage documentation](https://github.com/MinishLab/model2vec/blob/main/docs/usage.md).
120
123
 
121
124
  ## Updates & Announcements
122
125
 
126
+ - **01/05/2024**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
127
+
123
128
  - **12/02/2024**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
124
129
 
125
130
  - **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.
@@ -185,8 +190,8 @@ MIT
185
190
 
186
191
  If you use Model2Vec in your research, please cite the following:
187
192
  ```bibtex
188
- @software{minishlab2024model2vec,
189
- authors = {Stephan Tulkens and Thomas van Dongen},
193
+ @article{minishlab2024model2vec,
194
+ author = {Tulkens, Stephan and {van Dongen}, Thomas},
190
195
  title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
191
196
  year = {2024},
192
197
  url = {https://github.com/MinishLab/model2vec}
@@ -126,6 +126,54 @@ m2v_model = distill(model_name=model_name, vocabulary=vocabulary, use_subword=Fa
126
126
 
127
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
128
 
129
+ ### Quantization
130
+
131
+ Models can be quantized to `float16` (default) or `int8` during distillation, or when loading from disk.
132
+
133
+ ```python
134
+ from model2vec.distill import distill
135
+
136
+ # Distill a Sentence Transformer model and quantize is to int8
137
+ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", quantize_to="int8")
138
+
139
+ # Save the model. This model is now 25% of the size of a normal model.
140
+ m2v_model.save_pretrained("m2v_model")
141
+ ```
142
+
143
+ You can also quantize during loading.
144
+
145
+ ```python
146
+ from model2vec import StaticModel
147
+
148
+ model = StaticModel.from_pretrained("minishlab/potion-base-8m", quantize_to="int8")
149
+ ```
150
+
151
+ ### Dimensionality reduction
152
+
153
+ Because almost all Model2Vec models have been distilled using PCA, and because PCA explicitly orders dimensions from most informative to least informative, we can perform dimensionality reduction during loading. This is very similar to how matryoshka embeddings work.
154
+
155
+ ```python
156
+ from model2vec import StaticModel
157
+
158
+ model = StaticModel.from_pretrained("minishlab/potion-base-8m", dimensionality=32)
159
+
160
+ print(model.embedding.shape)
161
+ # (29528, 32)
162
+ ```
163
+
164
+ ### Combining quantization and dimensionality reduction
165
+
166
+ Combining these tricks can lead to extremely small models. For example, using this, we can reduce the size of `potion-base-8m`, which is now 30MB, to only 1MB:
167
+
168
+ ```python
169
+ model = StaticModel.from_pretrained("minishlab/potion-base-8m",
170
+ dimensionality=32,
171
+ quantize_to="int8")
172
+ print(model.embedding.nbytes)
173
+ # 944896 bytes = 944kb
174
+ ```
175
+
176
+ This should be enough to satisfy even the strongest hardware constraints.
129
177
 
130
178
  ## Training
131
179
 
@@ -9,16 +9,13 @@ import numpy as np
9
9
  from huggingface_hub import model_info
10
10
  from sklearn.decomposition import PCA
11
11
  from tokenizers import Tokenizer
12
- from tokenizers.models import BPE, Unigram
13
12
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
14
13
 
15
- from model2vec.distill.inference import (
16
- create_output_embeddings_from_model,
17
- create_output_embeddings_from_model_and_tokens,
18
- )
19
- from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
20
- from model2vec.distill.utils import select_optimal_device
14
+ from model2vec.distill.inference import create_embeddings
15
+ from model2vec.distill.tokenizer import replace_vocabulary
16
+ from model2vec.distill.utils import Token, select_optimal_device
21
17
  from model2vec.model import StaticModel
18
+ from model2vec.quantization import DType, quantize_embeddings
22
19
 
23
20
  try:
24
21
  # For huggingface_hub>=0.25.0
@@ -42,8 +39,9 @@ def distill_from_model(
42
39
  pca_dims: PCADimType = 256,
43
40
  apply_zipf: bool | None = None,
44
41
  sif_coefficient: float | None = 1e-4,
45
- use_subword: bool = True,
46
42
  token_remove_pattern: str | None = r"\[unused\d+\]",
43
+ quantize_to: DType | str = DType.Float16,
44
+ use_subword: bool | None = None,
47
45
  ) -> StaticModel:
48
46
  """
49
47
  Distill a staticmodel from a sentence transformer.
@@ -65,62 +63,57 @@ def distill_from_model(
65
63
  Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
66
64
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
67
65
  Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
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.
69
66
  :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.
70
67
  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.
68
+ :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
69
+ :param use_subword: DEPRECATED: If this is not set to None, we show a warning. It doesn't do anything.
71
70
  :return: A StaticModel
72
71
 
73
72
  """
74
- sif_coefficient = _validate_parameters(tokenizer, vocabulary, apply_zipf, sif_coefficient, use_subword)
73
+ if use_subword is not None:
74
+ logger.warning(
75
+ "The `use_subword` parameter is deprecated and will be removed in the next release. It doesn't do anything."
76
+ )
77
+ quantize_to = DType(quantize_to)
78
+ backend_tokenizer = tokenizer.backend_tokenizer
79
+ sif_coefficient, token_remove_regex = _validate_parameters(apply_zipf, sif_coefficient, token_remove_pattern)
80
+
81
+ if vocabulary is None:
82
+ vocabulary = []
75
83
 
76
84
  device = select_optimal_device(device)
77
85
  # Make a base list of tokens.
78
- tokens: list[str] = []
79
- if use_subword:
80
- # Create the subword embeddings.
81
- tokens, embeddings = create_output_embeddings_from_model(model=model, tokenizer=tokenizer, device=device)
82
- new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
83
- else:
84
- # We need to keep the unk token in the tokenizer.
85
- unk_token = tokenizer.backend_tokenizer.model.unk_token
86
- # Remove all tokens except the UNK token.
87
- new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, list(set(tokenizer.get_vocab()) - {unk_token}))
88
- # We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
89
- embeddings = None
90
-
91
- if vocabulary:
92
- # Preprocess the vocabulary with the original tokenizer.
93
- preprocessed_vocabulary = preprocess_vocabulary(tokenizer.backend_tokenizer, vocabulary)
94
- n_tokens_before = len(preprocessed_vocabulary)
95
- # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
96
- cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
97
- n_tokens_after = len(cleaned_vocabulary)
98
- logger.info(
99
- f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
100
- )
101
- # Only create embeddings if we have tokens to add.
102
- if cleaned_vocabulary:
103
- # Create the embeddings.
104
- _, token_embeddings = create_output_embeddings_from_model_and_tokens(
105
- model=model,
106
- tokenizer=tokenizer,
107
- tokens=cleaned_vocabulary,
108
- device=device,
109
- )
86
+ subword_vocab: dict[str, int] = tokenizer.get_vocab()
87
+ subword_tokens: list[str] = [k for k, _ in sorted(subword_vocab.items(), key=lambda x: x[1])]
88
+
89
+ n_tokens_before = len(vocabulary)
90
+ # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
91
+ cleaned_vocabulary = _clean_vocabulary(tokenizer.backend_tokenizer, vocabulary, subword_tokens)
92
+ n_tokens_after = len(cleaned_vocabulary)
93
+ logger.info(
94
+ f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
95
+ )
110
96
 
111
- # If we don't have subword tokens, we still need to create
112
- # some embeddings for [UNK] and some other special tokens.
113
- if embeddings is None:
114
- embeddings = np.zeros((new_tokenizer.get_vocab_size(), token_embeddings.shape[1]))
115
- embeddings = np.concatenate([embeddings, token_embeddings], axis=0)
116
- # Add the cleaned vocabulary to the tokenizer.
117
- new_tokenizer = add_tokens(new_tokenizer, cleaned_vocabulary)
118
- else:
119
- logger.warning("Didn't create any token embeddings as all tokens were duplicates or empty.")
97
+ # Create the embeddings.
98
+ all_tokens, embeddings = create_embeddings(
99
+ model=model,
100
+ tokenizer=tokenizer,
101
+ tokens=cleaned_vocabulary,
102
+ device=device,
103
+ token_remove_regex=token_remove_regex,
104
+ )
105
+
106
+ unk_token = tokenizer.special_tokens_map.get("unk_token")
107
+ pad_token = tokenizer.special_tokens_map.get("pad_token")
108
+ # Add the cleaned vocabulary to the tokenizer.
109
+ backend_tokenizer = replace_vocabulary(backend_tokenizer, all_tokens, unk_token=unk_token, pad_token=pad_token)
120
110
 
121
111
  # Post process the embeddings by applying PCA and Zipf weighting.
122
112
  embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
123
113
 
114
+ # Quantize the embeddings.
115
+ embeddings = quantize_embeddings(embeddings, quantize_to)
116
+
124
117
  model_name = getattr(model, "name_or_path", "")
125
118
 
126
119
  config = {
@@ -150,7 +143,7 @@ def distill_from_model(
150
143
 
151
144
  return StaticModel(
152
145
  vectors=embeddings,
153
- tokenizer=new_tokenizer,
146
+ tokenizer=backend_tokenizer,
154
147
  config=config,
155
148
  base_model_name=model_name,
156
149
  language=language,
@@ -159,27 +152,20 @@ def distill_from_model(
159
152
 
160
153
 
161
154
  def _validate_parameters(
162
- tokenizer: PreTrainedTokenizerFast,
163
- vocabulary: list[str] | None,
164
155
  apply_zipf: bool | None,
165
156
  sif_coefficient: float | None,
166
- use_subword: bool,
167
- ) -> float | None:
157
+ token_remove_pattern: str | None,
158
+ ) -> tuple[float | None, re.Pattern | None]:
168
159
  """
169
160
  Validate the parameters passed to the distillation function.
170
161
 
171
- :param tokenizer: The tokenizer to use.
172
- :param vocabulary: The vocabulary to use.
173
162
  :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
174
163
  Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
175
164
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
176
165
  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.
166
+ :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.
178
167
  :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
168
  :raises: ValueError if the regex can't be compiled.
182
- :raises: ValueError if the vocabulary is empty after token removal.
183
169
 
184
170
  """
185
171
  if apply_zipf is not None:
@@ -199,54 +185,14 @@ def _validate_parameters(
199
185
  if not 0 < sif_coefficient < 1.0:
200
186
  raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
201
187
 
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
-
217
- def _remove_tokens_and_embeddings(
218
- tokenizer: PreTrainedTokenizerFast, token_remove_pattern: str | None, tokens: list[str], embeddings: np.ndarray
219
- ) -> tuple[Tokenizer, np.ndarray]:
220
- if not token_remove_pattern:
221
- return tokenizer.backend_tokenizer, embeddings
222
-
223
- try:
224
- token_regex = re.compile(token_remove_pattern)
225
- except re.error as e:
226
- raise ValueError(f"Invalid regex pattern: {token_remove_pattern}") from e
227
- # Remove any unused tokens from the tokenizer and embeddings.
228
- wrong_tokens = [x for x in tokens if token_regex.match(x)]
229
- vocab = tokenizer.get_vocab()
230
- # Get the ids of the unused token.
231
- wrong_token_ids = [vocab[token] for token in wrong_tokens]
232
-
233
- if len(wrong_token_ids) == len(vocab):
234
- raise ValueError(
235
- "All tokens in the vocabulary are unused tokens. This will result in an empty tokenizer. "
236
- "Please provide a valid token removal pattern. The pattern is now: {token_remove_pattern}"
237
- )
238
-
239
- # Remove the unused tokens from the tokenizer.
240
- new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
241
- if new_tokenizer.get_vocab_size() == tokenizer.backend_tokenizer.get_vocab_size():
242
- # This happens if we didn't remove any tokens.
243
- return new_tokenizer, embeddings
244
-
245
- # Remove the embeddings of the unused tokens.
246
- embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
247
- logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
188
+ token_remove_regex: re.Pattern | None = None
189
+ if token_remove_pattern is not None:
190
+ try:
191
+ token_remove_regex = re.compile(token_remove_pattern)
192
+ except re.error as e:
193
+ raise ValueError(f"Couldn't compile the regex pattern: {e}")
248
194
 
249
- return new_tokenizer, embeddings
195
+ return sif_coefficient, token_remove_regex
250
196
 
251
197
 
252
198
  def distill(
@@ -256,9 +202,10 @@ def distill(
256
202
  pca_dims: PCADimType = 256,
257
203
  apply_zipf: bool | None = None,
258
204
  sif_coefficient: float | None = 1e-4,
259
- use_subword: bool = True,
260
205
  token_remove_pattern: str | None = r"\[unused\d+\]",
261
206
  trust_remote_code: bool = False,
207
+ quantize_to: DType | str = DType.Float16,
208
+ use_subword: bool | None = None,
262
209
  ) -> StaticModel:
263
210
  """
264
211
  Distill a staticmodel from a sentence transformer.
@@ -279,9 +226,10 @@ def distill(
279
226
  Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
280
227
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
281
228
  Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
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.
283
229
  :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
230
  :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.
231
+ :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
232
+ :param use_subword: DEPRECATED: If this is not set to None, we show a warning. It doesn't do anything.
285
233
  :return: A StaticModel
286
234
 
287
235
  """
@@ -295,9 +243,10 @@ def distill(
295
243
  device=device,
296
244
  pca_dims=pca_dims,
297
245
  apply_zipf=apply_zipf,
298
- use_subword=use_subword,
299
246
  token_remove_pattern=token_remove_pattern,
300
247
  sif_coefficient=sif_coefficient,
248
+ quantize_to=quantize_to,
249
+ use_subword=use_subword,
301
250
  )
302
251
 
303
252
 
@@ -345,26 +294,51 @@ def _post_process_embeddings(
345
294
  return embeddings
346
295
 
347
296
 
348
- def _clean_vocabulary(preprocessed_vocabulary: list[str], added_tokens: list[str]) -> list[str]:
297
+ def _clean_vocabulary(tokenizer: Tokenizer, vocabulary: list[str], added_tokens: list[str]) -> list[str]:
349
298
  """Cleans a vocabulary by removing duplicates and tokens that were already in the vocabulary."""
350
299
  added_tokens_set = set(added_tokens)
351
300
  seen_tokens = set()
352
301
  cleaned_vocabulary = []
353
302
  n_empty = 0
354
303
  n_duplicates = 0
355
- for token in preprocessed_vocabulary:
304
+ n_multiword = 0
305
+ for token in vocabulary:
306
+ normalizer = tokenizer.normalizer
307
+ if normalizer is not None:
308
+ token = normalizer.normalize_str(token)
309
+
356
310
  if not token:
357
311
  n_empty += 1
358
312
  continue
359
- if token in seen_tokens or token in added_tokens_set:
313
+
314
+ pre_tokenizer = tokenizer.pre_tokenizer
315
+ # We need to check whether the pretokenized token is a single word or not.
316
+ if pre_tokenizer is not None:
317
+ pretokenized_tokens = pre_tokenizer.pre_tokenize_str(token)
318
+ if len(pretokenized_tokens) != 1:
319
+ n_multiword += 1
320
+ continue
321
+ new_token = pretokenized_tokens[-1][0]
322
+ else:
323
+ new_token = token
324
+
325
+ # We need to check whether the pretokenized token is in the vocabulary.
326
+ # But we need to return the original token, because that will be tokenized
327
+ # again by the tokenizer during featurization.
328
+ if new_token in seen_tokens or new_token in added_tokens_set:
360
329
  n_duplicates += 1
361
330
  continue
362
- seen_tokens.add(token)
331
+
332
+ # Add the possibly pretokenized token to _seen_
333
+ seen_tokens.add(new_token)
334
+ # Add the original string to the vocabulary.
363
335
  cleaned_vocabulary.append(token)
364
336
 
365
337
  if n_duplicates:
366
338
  logger.warning(f"Removed {n_duplicates} duplicate tokens.")
367
339
  if n_empty:
368
340
  logger.warning(f"Removed {n_empty} empty tokens.")
341
+ if n_multiword:
342
+ logger.warning(f"Removed {n_multiword} multiword tokens.")
369
343
 
370
344
  return cleaned_vocabulary