model2vec 0.4.1__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.1 → model2vec-0.5.0}/PKG-INFO +7 -4
  2. {model2vec-0.4.1 → model2vec-0.5.0}/README.md +4 -2
  3. {model2vec-0.4.1 → model2vec-0.5.0}/docs/usage.md +48 -0
  4. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/distill/distillation.py +90 -116
  5. model2vec-0.5.0/model2vec/distill/inference.py +149 -0
  6. model2vec-0.5.0/model2vec/distill/tokenizer.py +197 -0
  7. model2vec-0.5.0/model2vec/distill/utils.py +58 -0
  8. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/hf_utils.py +46 -25
  9. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/inference/model.py +8 -9
  10. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/model.py +93 -14
  11. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/modelcards/classifier_template.md +2 -2
  12. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/modelcards/model_card_template.md +2 -2
  13. model2vec-0.5.0/model2vec/quantization.py +63 -0
  14. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/train/base.py +12 -2
  15. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/version.py +1 -1
  16. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec.egg-info/PKG-INFO +7 -4
  17. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec.egg-info/SOURCES.txt +3 -0
  18. {model2vec-0.4.1 → model2vec-0.5.0}/pyproject.toml +5 -1
  19. {model2vec-0.4.1 → model2vec-0.5.0}/scripts/export_to_onnx.py +3 -1
  20. model2vec-0.5.0/tests/__init__.py +0 -0
  21. {model2vec-0.4.1 → model2vec-0.5.0}/tests/conftest.py +19 -4
  22. {model2vec-0.4.1 → model2vec-0.5.0}/tests/test_distillation.py +51 -94
  23. {model2vec-0.4.1 → model2vec-0.5.0}/tests/test_model.py +59 -0
  24. model2vec-0.5.0/tests/test_quantization.py +30 -0
  25. model2vec-0.5.0/tutorials/semantic_chunking.ipynb +268 -0
  26. {model2vec-0.4.1 → model2vec-0.5.0}/uv.lock +1 -1
  27. model2vec-0.4.1/model2vec/distill/inference.py +0 -167
  28. model2vec-0.4.1/model2vec/distill/tokenizer.py +0 -122
  29. model2vec-0.4.1/model2vec/distill/utils.py +0 -28
  30. model2vec-0.4.1/tutorials/semantic_chunking.ipynb +0 -261
  31. {model2vec-0.4.1 → model2vec-0.5.0}/.github/workflows/ci.yaml +0 -0
  32. {model2vec-0.4.1 → model2vec-0.5.0}/.gitignore +0 -0
  33. {model2vec-0.4.1 → model2vec-0.5.0}/.pre-commit-config.yaml +0 -0
  34. {model2vec-0.4.1 → model2vec-0.5.0}/LICENSE +0 -0
  35. {model2vec-0.4.1 → model2vec-0.5.0}/Makefile +0 -0
  36. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/logo.png +0 -0
  37. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/logo_v2.png +0 -0
  38. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/model2vec_model_diagram.png +0 -0
  39. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
  40. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
  41. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  42. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_accuracy.png +0 -0
  43. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v2.png +0 -0
  44. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v3.png +0 -0
  45. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_accuracy_v4.png +0 -0
  46. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score.png +0 -0
  47. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score_v2.png +0 -0
  48. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  49. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/training_speed_vs_score.png +0 -0
  50. {model2vec-0.4.1 → model2vec-0.5.0}/assets/images/tutorial_ezlo.png +0 -0
  51. {model2vec-0.4.1 → model2vec-0.5.0}/docs/README.md +0 -0
  52. {model2vec-0.4.1 → model2vec-0.5.0}/docs/integrations.md +0 -0
  53. {model2vec-0.4.1 → model2vec-0.5.0}/docs/what_is_model2vec.md +0 -0
  54. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/__init__.py +0 -0
  55. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/distill/__init__.py +0 -0
  56. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/inference/README.md +0 -0
  57. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/inference/__init__.py +0 -0
  58. /model2vec-0.4.1/tests/__init__.py → /model2vec-0.5.0/model2vec/py.typed +0 -0
  59. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/train/README.md +0 -0
  60. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/train/__init__.py +0 -0
  61. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/train/classifier.py +0 -0
  62. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec/utils.py +0 -0
  63. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec.egg-info/dependency_links.txt +0 -0
  64. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec.egg-info/requires.txt +0 -0
  65. {model2vec-0.4.1 → model2vec-0.5.0}/model2vec.egg-info/top_level.txt +0 -0
  66. {model2vec-0.4.1 → model2vec-0.5.0}/results/README.md +0 -0
  67. {model2vec-0.4.1 → model2vec-0.5.0}/results/make_speed_vs_mteb_plot.py +0 -0
  68. {model2vec-0.4.1 → model2vec-0.5.0}/setup.cfg +0 -0
  69. {model2vec-0.4.1 → model2vec-0.5.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  70. {model2vec-0.4.1 → model2vec-0.5.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
  71. {model2vec-0.4.1 → model2vec-0.5.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  72. {model2vec-0.4.1 → model2vec-0.5.0}/tests/test_inference.py +0 -0
  73. {model2vec-0.4.1 → model2vec-0.5.0}/tests/test_trainable.py +0 -0
  74. {model2vec-0.4.1 → model2vec-0.5.0}/tests/test_utils.py +0 -0
  75. {model2vec-0.4.1 → model2vec-0.5.0}/tutorials/README.md +0 -0
  76. {model2vec-0.4.1 → model2vec-0.5.0}/tutorials/recipe_search.ipynb +0 -0
  77. {model2vec-0.4.1 → 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.1
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">
@@ -200,6 +201,8 @@ For advanced usage, please refer to our [usage documentation](https://github.com
200
201
 
201
202
  ## Updates & Announcements
202
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
+
203
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).
204
207
 
205
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.
@@ -265,8 +268,8 @@ MIT
265
268
 
266
269
  If you use Model2Vec in your research, please cite the following:
267
270
  ```bibtex
268
- @software{minishlab2024model2vec,
269
- authors = {Stephan Tulkens and Thomas van Dongen},
271
+ @article{minishlab2024model2vec,
272
+ author = {Tulkens, Stephan and {van Dongen}, Thomas},
270
273
  title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
271
274
  year = {2024},
272
275
  url = {https://github.com/MinishLab/model2vec}
@@ -123,6 +123,8 @@ For advanced usage, please refer to our [usage documentation](https://github.com
123
123
 
124
124
  ## Updates & Announcements
125
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
+
126
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).
127
129
 
128
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.
@@ -188,8 +190,8 @@ MIT
188
190
 
189
191
  If you use Model2Vec in your research, please cite the following:
190
192
  ```bibtex
191
- @software{minishlab2024model2vec,
192
- authors = {Stephan Tulkens and Thomas van Dongen},
193
+ @article{minishlab2024model2vec,
194
+ author = {Tulkens, Stephan and {van Dongen}, Thomas},
193
195
  title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
194
196
  year = {2024},
195
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
@@ -0,0 +1,149 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ import logging
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Protocol, Union
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch.nn.utils.rnn import pad_sequence
13
+ from tqdm import tqdm
14
+ from transformers import PreTrainedModel, PreTrainedTokenizerFast
15
+ from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
16
+
17
+ from model2vec.distill.utils import Token, filter_vocabulary_by_regex
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ PathLike = Union[Path, str]
23
+
24
+ _DEFAULT_BATCH_SIZE = 256
25
+
26
+
27
+ class ModulewithWeights(Protocol):
28
+ weight: torch.nn.Parameter
29
+
30
+
31
+ def create_embeddings(
32
+ model: PreTrainedModel,
33
+ tokenizer: PreTrainedTokenizerFast,
34
+ tokens: list[str],
35
+ device: str,
36
+ token_remove_regex: re.Pattern | None,
37
+ ) -> tuple[list[Token], np.ndarray]:
38
+ """
39
+ Create output embeddings for a bunch of tokens using a pretrained model.
40
+
41
+ It does a forward pass for all tokens passed in `tokens`.
42
+
43
+ :param model: The model to use.
44
+ This should be a transformers model.
45
+ :param tokenizer: The tokenizer to use.
46
+ :param tokens: The tokens to use.
47
+ :param device: The torch device to use.
48
+ :param token_remove_regex: A regex pattern to remove tokens from the vocabulary.
49
+ :return: The tokens and output embeddings.
50
+ """
51
+ model = model.to(device)
52
+
53
+ out_weights: np.ndarray
54
+ intermediate_weights: list[np.ndarray] = []
55
+
56
+ out_tokens: list[Token] = []
57
+ tokenized: list[torch.Tensor] = []
58
+ pad_token = tokenizer.special_tokens_map.get("pad_token")
59
+ # We need to use the pad token id for padding below.
60
+ pad_token_id = tokenizer.convert_tokens_to_ids(pad_token)
61
+ unk_token = tokenizer.special_tokens_map.get("unk_token")
62
+
63
+ # Empty set if no pad or unk token is set.
64
+ tokens_to_keep = {pad_token, unk_token} - {None}
65
+
66
+ if token_remove_regex is not None:
67
+ # Sort the vocabulary by id, important for zipf.
68
+ sorted_vocab = sorted(tokenizer.get_vocab().items(), key=lambda x: x[1])
69
+ id_list = filter_vocabulary_by_regex(token_remove_regex, sorted_vocab)
70
+ else:
71
+ # If the token remove regex is None, just use all tokens.
72
+ id_list = list(range(len(tokenizer.get_vocab())))
73
+
74
+ added_tokens_ids = [id for token, id in tokenizer.added_tokens_encoder.items() if token not in tokens_to_keep]
75
+ ids = torch.Tensor(sorted(set(id_list) - set(added_tokens_ids))).long()
76
+
77
+ if ids is not None:
78
+ dummy_encoding = tokenizer.encode("A")
79
+ bos_token_id, eos_token_id = dummy_encoding[0], dummy_encoding[-1]
80
+
81
+ bos = torch.full([len(ids)], fill_value=bos_token_id)
82
+ eos = torch.full([len(ids)], fill_value=eos_token_id)
83
+
84
+ tokenized.extend(torch.stack([bos, ids, eos], dim=1))
85
+ subword_tokens = [Token(x, True) for x in tokenizer.convert_ids_to_tokens(ids.tolist())]
86
+ out_tokens.extend(subword_tokens)
87
+
88
+ tokenized.extend([tokenizer.encode_plus(token, return_tensors="pt")["input_ids"][0] for token in tokens])
89
+
90
+ # Add token_type_ids only if the model supports it
91
+ add_token_type_ids = "token_type_ids" in inspect.getfullargspec(model.forward).args
92
+
93
+ lengths = np.asarray([len(sequence) for sequence in tokenized])
94
+ sort_order = np.argsort(lengths)
95
+
96
+ sorted_tokenized = [tokenized[i] for i in sort_order]
97
+
98
+ pbar = tqdm(total=len(sorted_tokenized), desc="Encoding tokens", unit=" tokens")
99
+
100
+ for batch_idx in range(0, len(sorted_tokenized), _DEFAULT_BATCH_SIZE):
101
+ batch = sorted_tokenized[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
102
+
103
+ encoded = {}
104
+ encoded["input_ids"] = pad_sequence(batch, batch_first=True, padding_value=pad_token_id)
105
+ encoded["attention_mask"] = encoded["input_ids"] != pad_token_id
106
+
107
+ if add_token_type_ids:
108
+ encoded["token_type_ids"] = torch.zeros_like(encoded["input_ids"])
109
+
110
+ out = _encode_mean_using_model(model, encoded)
111
+ intermediate_weights.extend(out.numpy())
112
+ pbar.update(len(batch))
113
+
114
+ # Sort the output back to the original order
115
+ intermediate_weights = [intermediate_weights[i] for i in np.argsort(sort_order)]
116
+ out_tokens.extend([Token(x, False) for x in tokens])
117
+ out_weights = np.stack(intermediate_weights)
118
+
119
+ return out_tokens, out_weights
120
+
121
+
122
+ @torch.no_grad()
123
+ def _encode_mean_using_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
124
+ """
125
+ Encode a batch of tokens using a model.
126
+
127
+ Note that if a token in the input batch does not have any embeddings, it will be output as a vector of zeros.
128
+ So detection of these is necessary.
129
+
130
+ :param model: The model to use.
131
+ :param encodings: The encoded tokens to turn into features.
132
+ :return: The mean of the output for each token.
133
+ """
134
+ encodings = {k: v.to(model.device) for k, v in encodings.items()}
135
+ encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
136
+ out: torch.Tensor = encoded.last_hidden_state.cpu()
137
+ # NOTE: If the dtype is bfloat 16, we convert to float32,
138
+ # because numpy does not suport bfloat16
139
+ # See here: https://github.com/numpy/numpy/issues/19808
140
+ if out.dtype == torch.bfloat16:
141
+ out = out.float()
142
+
143
+ # Take the mean by averaging over the attention mask.
144
+ mask = encodings["attention_mask"].cpu().float()
145
+ mask /= mask.sum(1)[:, None]
146
+
147
+ result = torch.bmm(mask[:, None, :].float(), out).squeeze(1)
148
+
149
+ return result