model2vec 0.3.8__py3-none-any.whl → 0.3.9__py3-none-any.whl
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.
- model2vec/distill/distillation.py +93 -29
- model2vec/version.py +1 -1
- {model2vec-0.3.8.dist-info → model2vec-0.3.9.dist-info}/METADATA +5 -2
- {model2vec-0.3.8.dist-info → model2vec-0.3.9.dist-info}/RECORD +7 -7
- {model2vec-0.3.8.dist-info → model2vec-0.3.9.dist-info}/LICENSE +0 -0
- {model2vec-0.3.8.dist-info → model2vec-0.3.9.dist-info}/WHEEL +0 -0
- {model2vec-0.3.8.dist-info → model2vec-0.3.9.dist-info}/top_level.txt +0 -0
|
@@ -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 =
|
|
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:
|
|
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
|
-
|
|
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,
|
|
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,
|
|
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 =
|
|
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:
|
|
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(
|
|
245
|
-
|
|
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
|
|
278
|
-
logger.info("
|
|
279
|
-
|
|
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
|
|
model2vec/version.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
__version_triple__ = (0, 3,
|
|
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.
|
|
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-
|
|
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
|
|
|
@@ -3,14 +3,14 @@ model2vec/hf_utils.py,sha256=dVPM1mIWH66YbR276nkSbC3zQgWxUQJ0CovIQFAkxNc,8048
|
|
|
3
3
|
model2vec/model.py,sha256=ZYEw0Ha5pHp2hsmLVksJCK5tQdfnmpl6bjrmMmvwiXE,15575
|
|
4
4
|
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
5
5
|
model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
|
|
6
|
-
model2vec/version.py,sha256=
|
|
6
|
+
model2vec/version.py,sha256=TUfzqSdyYoDw7zGUu2Ddrc3WpuwLtvnD_UQOIM3FMiE,84
|
|
7
7
|
model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
|
|
8
|
-
model2vec/distill/distillation.py,sha256=
|
|
8
|
+
model2vec/distill/distillation.py,sha256=jl6mG_hXd4YqyRDQP5EV8Bu5tFqA8UH2vcwvGJ5M51k,17266
|
|
9
9
|
model2vec/distill/inference.py,sha256=peUpPvt6S_pmmp0Xzu0Ty1TGrW7NKP0dd6qqVyVjNDw,6232
|
|
10
10
|
model2vec/distill/tokenizer.py,sha256=QSSH3qKqP19_DUu2JamRXOv_2_I-bL2Sty0A8q4pCPw,4339
|
|
11
11
|
model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
|
|
12
|
-
model2vec-0.3.
|
|
13
|
-
model2vec-0.3.
|
|
14
|
-
model2vec-0.3.
|
|
15
|
-
model2vec-0.3.
|
|
16
|
-
model2vec-0.3.
|
|
12
|
+
model2vec-0.3.9.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
+
model2vec-0.3.9.dist-info/METADATA,sha256=nJ23zbHRR6gKlUIuRmJR2biZNMn9S0WMBsMmgT4VnWY,27286
|
|
14
|
+
model2vec-0.3.9.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
15
|
+
model2vec-0.3.9.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
+
model2vec-0.3.9.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|