model2vec 0.3.7__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 +110 -36
- model2vec/distill/inference.py +11 -9
- model2vec/hf_utils.py +0 -1
- model2vec/model.py +18 -8
- model2vec/version.py +1 -1
- {model2vec-0.3.7.dist-info → model2vec-0.3.9.dist-info}/METADATA +5 -2
- model2vec-0.3.9.dist-info/RECORD +16 -0
- model2vec-0.3.7.dist-info/RECORD +0 -16
- {model2vec-0.3.7.dist-info → model2vec-0.3.9.dist-info}/LICENSE +0 -0
- {model2vec-0.3.7.dist-info → model2vec-0.3.9.dist-info}/WHEEL +0 -0
- {model2vec-0.3.7.dist-info → model2vec-0.3.9.dist-info}/top_level.txt +0 -0
|
@@ -13,8 +13,8 @@ from tokenizers.models import BPE, Unigram
|
|
|
13
13
|
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
14
14
|
|
|
15
15
|
from model2vec.distill.inference import (
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
create_output_embeddings_from_model,
|
|
17
|
+
create_output_embeddings_from_model_and_tokens,
|
|
18
18
|
)
|
|
19
19
|
from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
|
|
20
20
|
from model2vec.distill.utils import select_optimal_device
|
|
@@ -31,7 +31,7 @@ except ImportError:
|
|
|
31
31
|
logger = logging.getLogger(__name__)
|
|
32
32
|
|
|
33
33
|
|
|
34
|
-
PCADimType = Union[int, None, Literal["auto"]]
|
|
34
|
+
PCADimType = Union[int, None, float, Literal["auto"]]
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
def distill_from_model(
|
|
@@ -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,35 +61,24 @@ 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:
|
|
90
80
|
# Create the subword embeddings.
|
|
91
|
-
tokens, embeddings =
|
|
81
|
+
tokens, embeddings = create_output_embeddings_from_model(model=model, tokenizer=tokenizer, device=device)
|
|
92
82
|
new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
|
|
93
83
|
else:
|
|
94
84
|
# We need to keep the unk token in the tokenizer.
|
|
@@ -111,7 +101,7 @@ def distill_from_model(
|
|
|
111
101
|
# Only create embeddings if we have tokens to add.
|
|
112
102
|
if cleaned_vocabulary:
|
|
113
103
|
# Create the embeddings.
|
|
114
|
-
_, token_embeddings =
|
|
104
|
+
_, token_embeddings = create_output_embeddings_from_model_and_tokens(
|
|
115
105
|
model=model,
|
|
116
106
|
tokenizer=tokenizer,
|
|
117
107
|
tokens=cleaned_vocabulary,
|
|
@@ -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]:
|
|
@@ -185,6 +238,10 @@ def _remove_tokens_and_embeddings(
|
|
|
185
238
|
|
|
186
239
|
# Remove the unused tokens from the tokenizer.
|
|
187
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
|
+
|
|
188
245
|
# Remove the embeddings of the unused tokens.
|
|
189
246
|
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
190
247
|
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
@@ -197,8 +254,11 @@ def distill(
|
|
|
197
254
|
vocabulary: list[str] | None = None,
|
|
198
255
|
device: str | None = None,
|
|
199
256
|
pca_dims: PCADimType = 256,
|
|
200
|
-
apply_zipf: bool =
|
|
257
|
+
apply_zipf: bool | None = None,
|
|
258
|
+
sif_coefficient: float | None = 1e-4,
|
|
201
259
|
use_subword: bool = True,
|
|
260
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
261
|
+
trust_remote_code: bool = False,
|
|
202
262
|
) -> StaticModel:
|
|
203
263
|
"""
|
|
204
264
|
Distill a staticmodel from a sentence transformer.
|
|
@@ -215,13 +275,18 @@ def distill(
|
|
|
215
275
|
:param pca_dims: The number of components to use for PCA.
|
|
216
276
|
If this is None, we don't apply PCA.
|
|
217
277
|
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
218
|
-
: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.
|
|
219
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
|
+
: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.
|
|
220
285
|
:return: A StaticModel
|
|
221
286
|
|
|
222
287
|
"""
|
|
223
|
-
model: PreTrainedModel = AutoModel.from_pretrained(model_name)
|
|
224
|
-
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)
|
|
225
290
|
|
|
226
291
|
return distill_from_model(
|
|
227
292
|
model=model,
|
|
@@ -231,11 +296,15 @@ def distill(
|
|
|
231
296
|
pca_dims=pca_dims,
|
|
232
297
|
apply_zipf=apply_zipf,
|
|
233
298
|
use_subword=use_subword,
|
|
299
|
+
token_remove_pattern=token_remove_pattern,
|
|
300
|
+
sif_coefficient=sif_coefficient,
|
|
234
301
|
)
|
|
235
302
|
|
|
236
303
|
|
|
237
|
-
def _post_process_embeddings(
|
|
238
|
-
|
|
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."""
|
|
239
308
|
if pca_dims is not None:
|
|
240
309
|
if pca_dims == "auto":
|
|
241
310
|
pca_dims = embeddings.shape[1]
|
|
@@ -251,10 +320,13 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
|
|
|
251
320
|
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
|
|
252
321
|
)
|
|
253
322
|
elif pca_dims <= embeddings.shape[1]:
|
|
254
|
-
|
|
323
|
+
if isinstance(pca_dims, float):
|
|
324
|
+
logger.info(f"Applying PCA with {pca_dims} explained variance.")
|
|
325
|
+
else:
|
|
326
|
+
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
255
327
|
|
|
256
328
|
orig_dims = embeddings.shape[1]
|
|
257
|
-
p = PCA(n_components=pca_dims,
|
|
329
|
+
p = PCA(n_components=pca_dims, svd_solver="full")
|
|
258
330
|
embeddings = p.fit_transform(embeddings)
|
|
259
331
|
|
|
260
332
|
if embeddings.shape[1] < orig_dims:
|
|
@@ -264,9 +336,11 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
|
|
|
264
336
|
logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
|
|
265
337
|
logger.info(f"Explained variance: {explained_variance:.3f}.")
|
|
266
338
|
|
|
267
|
-
if
|
|
268
|
-
logger.info("
|
|
269
|
-
|
|
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]
|
|
270
344
|
|
|
271
345
|
return embeddings
|
|
272
346
|
|
model2vec/distill/inference.py
CHANGED
|
@@ -24,18 +24,19 @@ class ModulewithWeights(Protocol):
|
|
|
24
24
|
weight: torch.nn.Parameter
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
def
|
|
27
|
+
def create_output_embeddings_from_model_and_tokens(
|
|
28
28
|
model: PreTrainedModel,
|
|
29
29
|
tokenizer: PreTrainedTokenizer,
|
|
30
30
|
tokens: list[str],
|
|
31
31
|
device: str,
|
|
32
32
|
) -> tuple[list[str], np.ndarray]:
|
|
33
33
|
"""
|
|
34
|
-
Create output embeddings for a bunch of tokens
|
|
34
|
+
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
35
35
|
|
|
36
|
-
It does a forward pass for all tokens passed in tokens
|
|
36
|
+
It does a forward pass for all tokens passed in `tokens`.
|
|
37
37
|
|
|
38
|
-
:param model: The model
|
|
38
|
+
:param model: The model to use.
|
|
39
|
+
This should be a transformers model.
|
|
39
40
|
:param tokenizer: The tokenizer to use.
|
|
40
41
|
:param tokens: The tokens to use.
|
|
41
42
|
:param device: The torch device to use.
|
|
@@ -99,17 +100,18 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
|
|
|
99
100
|
return result / divisor[:, None]
|
|
100
101
|
|
|
101
102
|
|
|
102
|
-
def
|
|
103
|
+
def create_output_embeddings_from_model(
|
|
103
104
|
model: PreTrainedModel,
|
|
104
105
|
tokenizer: PreTrainedTokenizer,
|
|
105
106
|
device: str,
|
|
106
107
|
) -> tuple[list[str], np.ndarray]:
|
|
107
108
|
"""
|
|
108
|
-
Create output embeddings for a bunch of tokens
|
|
109
|
+
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
109
110
|
|
|
110
|
-
It does a forward pass for all
|
|
111
|
+
It does a forward pass for all tokens passed in the tokenizer vocabulary.
|
|
111
112
|
|
|
112
|
-
:param model: The model
|
|
113
|
+
:param model: The model to use.
|
|
114
|
+
This should be a transformers model.
|
|
113
115
|
:param tokenizer: The tokenizer to use.
|
|
114
116
|
:param device: The torch device to use.
|
|
115
117
|
:return: The tokens and output embeddings.
|
|
@@ -157,7 +159,7 @@ def create_output_embeddings_from_model_name(
|
|
|
157
159
|
out = out.float()
|
|
158
160
|
|
|
159
161
|
# Add the output to the intermediate weights
|
|
160
|
-
intermediate_weights.append(out
|
|
162
|
+
intermediate_weights.append(out.mean(1).detach().cpu().numpy())
|
|
161
163
|
|
|
162
164
|
# Concatenate the intermediate weights
|
|
163
165
|
out_weights = np.concatenate(intermediate_weights)
|
model2vec/hf_utils.py
CHANGED
model2vec/model.py
CHANGED
|
@@ -35,7 +35,7 @@ class StaticModel:
|
|
|
35
35
|
:param vectors: The vectors to use.
|
|
36
36
|
:param tokenizer: The Transformers tokenizer to use.
|
|
37
37
|
:param config: Any metadata config.
|
|
38
|
-
:param normalize: Whether to normalize.
|
|
38
|
+
:param normalize: Whether to normalize the embeddings.
|
|
39
39
|
:param base_model_name: The used base model name. Used for creating a model card.
|
|
40
40
|
:param language: The language of the model. Used for creating a model card.
|
|
41
41
|
:raises: ValueError if the number of tokens does not match the number of vectors.
|
|
@@ -114,13 +114,14 @@ class StaticModel:
|
|
|
114
114
|
model_name=model_name,
|
|
115
115
|
)
|
|
116
116
|
|
|
117
|
-
def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[int]:
|
|
117
|
+
def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[list[int]]:
|
|
118
118
|
"""
|
|
119
|
-
Tokenize a
|
|
119
|
+
Tokenize a list of sentences.
|
|
120
120
|
|
|
121
|
-
:param sentences: The
|
|
122
|
-
:param max_length: The maximum length of the
|
|
123
|
-
|
|
121
|
+
:param sentences: The sentences to tokenize.
|
|
122
|
+
:param max_length: The maximum length of the sentences in tokens. If this is None, sequences
|
|
123
|
+
are not truncated.
|
|
124
|
+
:return: A list of list of tokens.
|
|
124
125
|
"""
|
|
125
126
|
if max_length is not None:
|
|
126
127
|
m = max_length * self.median_token_length
|
|
@@ -148,6 +149,7 @@ class StaticModel:
|
|
|
148
149
|
cls: type[StaticModel],
|
|
149
150
|
path: PathLike,
|
|
150
151
|
token: str | None = None,
|
|
152
|
+
normalize: bool | None = None,
|
|
151
153
|
) -> StaticModel:
|
|
152
154
|
"""
|
|
153
155
|
Load a StaticModel from a local path or huggingface hub path.
|
|
@@ -156,6 +158,7 @@ class StaticModel:
|
|
|
156
158
|
|
|
157
159
|
:param path: The path to load your static model from.
|
|
158
160
|
:param token: The huggingface token to use.
|
|
161
|
+
:param normalize: Whether to normalize the embeddings.
|
|
159
162
|
:return: A StaticModel
|
|
160
163
|
"""
|
|
161
164
|
from model2vec.hf_utils import load_pretrained
|
|
@@ -163,7 +166,12 @@ class StaticModel:
|
|
|
163
166
|
embeddings, tokenizer, config, metadata = load_pretrained(path, token=token, from_sentence_transformers=False)
|
|
164
167
|
|
|
165
168
|
return cls(
|
|
166
|
-
embeddings,
|
|
169
|
+
embeddings,
|
|
170
|
+
tokenizer,
|
|
171
|
+
config,
|
|
172
|
+
normalize=normalize,
|
|
173
|
+
base_model_name=metadata.get("base_model"),
|
|
174
|
+
language=metadata.get("language"),
|
|
167
175
|
)
|
|
168
176
|
|
|
169
177
|
@classmethod
|
|
@@ -171,6 +179,7 @@ class StaticModel:
|
|
|
171
179
|
cls: type[StaticModel],
|
|
172
180
|
path: PathLike,
|
|
173
181
|
token: str | None = None,
|
|
182
|
+
normalize: bool | None = None,
|
|
174
183
|
) -> StaticModel:
|
|
175
184
|
"""
|
|
176
185
|
Load a StaticModel trained with sentence transformers from a local path or huggingface hub path.
|
|
@@ -179,13 +188,14 @@ class StaticModel:
|
|
|
179
188
|
|
|
180
189
|
:param path: The path to load your static model from.
|
|
181
190
|
:param token: The huggingface token to use.
|
|
191
|
+
:param normalize: Whether to normalize the embeddings.
|
|
182
192
|
:return: A StaticModel
|
|
183
193
|
"""
|
|
184
194
|
from model2vec.hf_utils import load_pretrained
|
|
185
195
|
|
|
186
196
|
embeddings, tokenizer, config, _ = load_pretrained(path, token=token, from_sentence_transformers=True)
|
|
187
197
|
|
|
188
|
-
return cls(embeddings, tokenizer, config, base_model_name=None, language=None)
|
|
198
|
+
return cls(embeddings, tokenizer, config, normalize=normalize, base_model_name=None, language=None)
|
|
189
199
|
|
|
190
200
|
def encode_as_sequence(
|
|
191
201
|
self,
|
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
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
|
|
2
|
+
model2vec/hf_utils.py,sha256=dVPM1mIWH66YbR276nkSbC3zQgWxUQJ0CovIQFAkxNc,8048
|
|
3
|
+
model2vec/model.py,sha256=ZYEw0Ha5pHp2hsmLVksJCK5tQdfnmpl6bjrmMmvwiXE,15575
|
|
4
|
+
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
5
|
+
model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
|
|
6
|
+
model2vec/version.py,sha256=TUfzqSdyYoDw7zGUu2Ddrc3WpuwLtvnD_UQOIM3FMiE,84
|
|
7
|
+
model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
|
|
8
|
+
model2vec/distill/distillation.py,sha256=jl6mG_hXd4YqyRDQP5EV8Bu5tFqA8UH2vcwvGJ5M51k,17266
|
|
9
|
+
model2vec/distill/inference.py,sha256=peUpPvt6S_pmmp0Xzu0Ty1TGrW7NKP0dd6qqVyVjNDw,6232
|
|
10
|
+
model2vec/distill/tokenizer.py,sha256=QSSH3qKqP19_DUu2JamRXOv_2_I-bL2Sty0A8q4pCPw,4339
|
|
11
|
+
model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
|
|
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,,
|
model2vec-0.3.7.dist-info/RECORD
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
|
|
2
|
-
model2vec/hf_utils.py,sha256=LDhGOeZ0qnzqTKM5SiciD8vdHRNgZWurWZpOjHunXqA,8078
|
|
3
|
-
model2vec/model.py,sha256=wdP7Otk2DmUt4I1ntC9hRX8ION3sfeTfxVKUYRXYHDg,15154
|
|
4
|
-
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
5
|
-
model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
|
|
6
|
-
model2vec/version.py,sha256=0VIUsE13cvKVSjrf_LfnHuniEHsv2yQKzJP1_yibN70,84
|
|
7
|
-
model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
|
|
8
|
-
model2vec/distill/distillation.py,sha256=xAEFJZAFdLJLySes2WozIgePvgti6LNgIOr5CD7YCmc,13233
|
|
9
|
-
model2vec/distill/inference.py,sha256=QgHAEkLoeq-jPyKnFTB6p6Ry-ZGZqonkZaEg2S7VTOY,6123
|
|
10
|
-
model2vec/distill/tokenizer.py,sha256=QSSH3qKqP19_DUu2JamRXOv_2_I-bL2Sty0A8q4pCPw,4339
|
|
11
|
-
model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
|
|
12
|
-
model2vec-0.3.7.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
-
model2vec-0.3.7.dist-info/METADATA,sha256=1r0pwe8crS9hugMp28muLyiY30-18bxTZgRNUDglre4,26138
|
|
14
|
-
model2vec-0.3.7.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
15
|
-
model2vec-0.3.7.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
-
model2vec-0.3.7.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|