model2vec 0.3.3__py3-none-any.whl → 0.3.5__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 +54 -17
- model2vec/distill/tokenizer.py +4 -2
- model2vec/model.py +58 -19
- model2vec/utils.py +42 -2
- model2vec/version.py +1 -1
- {model2vec-0.3.3.dist-info → model2vec-0.3.5.dist-info}/METADATA +183 -146
- model2vec-0.3.5.dist-info/RECORD +16 -0
- {model2vec-0.3.3.dist-info → model2vec-0.3.5.dist-info}/WHEEL +1 -1
- model2vec-0.3.3.dist-info/RECORD +0 -16
- {model2vec-0.3.3.dist-info → model2vec-0.3.5.dist-info}/LICENSE +0 -0
- {model2vec-0.3.3.dist-info → model2vec-0.3.5.dist-info}/top_level.txt +0 -0
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
4
6
|
from typing import Literal, Union
|
|
5
7
|
|
|
6
8
|
import numpy as np
|
|
7
9
|
from huggingface_hub import model_info
|
|
8
10
|
from sklearn.decomposition import PCA
|
|
11
|
+
from tokenizers import Tokenizer
|
|
9
12
|
from tokenizers.models import BPE, Unigram
|
|
10
13
|
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
11
14
|
|
|
@@ -39,6 +42,7 @@ def distill_from_model(
|
|
|
39
42
|
pca_dims: PCADimType = 256,
|
|
40
43
|
apply_zipf: bool = True,
|
|
41
44
|
use_subword: bool = True,
|
|
45
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
42
46
|
) -> StaticModel:
|
|
43
47
|
"""
|
|
44
48
|
Distill a staticmodel from a sentence transformer.
|
|
@@ -58,8 +62,12 @@ def distill_from_model(
|
|
|
58
62
|
If this is 'auto', we don't reduce dimensionality, but still apply PCA.
|
|
59
63
|
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
60
64
|
: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
|
+
: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
|
+
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.
|
|
61
67
|
:raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
|
|
62
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.
|
|
63
71
|
:return: A StaticModel
|
|
64
72
|
|
|
65
73
|
"""
|
|
@@ -81,17 +89,7 @@ def distill_from_model(
|
|
|
81
89
|
if use_subword:
|
|
82
90
|
# Create the subword embeddings.
|
|
83
91
|
tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
|
|
84
|
-
|
|
85
|
-
# Remove any unused tokens from the tokenizer and embeddings.
|
|
86
|
-
wrong_tokens = [x for x in tokens if x.startswith("[unused")]
|
|
87
|
-
vocab = tokenizer.get_vocab()
|
|
88
|
-
# Get the ids of the unused token.
|
|
89
|
-
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
90
|
-
# Remove the unused tokens from the tokenizer.
|
|
91
|
-
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
|
|
92
|
-
# Remove the embeddings of the unused tokens.
|
|
93
|
-
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
94
|
-
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
92
|
+
new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
|
|
95
93
|
else:
|
|
96
94
|
# We need to keep the unk token in the tokenizer.
|
|
97
95
|
unk_token = tokenizer.backend_tokenizer.model.unk_token
|
|
@@ -136,25 +134,64 @@ def distill_from_model(
|
|
|
136
134
|
model_name = getattr(model, "name_or_path", "")
|
|
137
135
|
|
|
138
136
|
config = {
|
|
137
|
+
"model_type": "model2vec",
|
|
138
|
+
"architectures": ["StaticModel"],
|
|
139
139
|
"tokenizer_name": model_name,
|
|
140
140
|
"apply_pca": pca_dims,
|
|
141
141
|
"apply_zipf": apply_zipf,
|
|
142
142
|
"hidden_dim": embeddings.shape[1],
|
|
143
143
|
"seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
|
|
144
144
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
except RepositoryNotFoundError:
|
|
150
|
-
logger.info("No model info found for model. Setting `language` to None.")
|
|
145
|
+
|
|
146
|
+
if os.path.exists(model_name):
|
|
147
|
+
# Using a local model. Get the model name from the path.
|
|
148
|
+
model_name = os.path.basename(model_name)
|
|
151
149
|
language = None
|
|
150
|
+
else:
|
|
151
|
+
# Get the language from the model card.
|
|
152
|
+
try:
|
|
153
|
+
info = model_info(model_name)
|
|
154
|
+
language = info.cardData.get("language", None)
|
|
155
|
+
except RepositoryNotFoundError:
|
|
156
|
+
logger.info("No model info found for the model. Setting language to None.")
|
|
157
|
+
language = None
|
|
152
158
|
|
|
153
159
|
return StaticModel(
|
|
154
160
|
vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
|
|
155
161
|
)
|
|
156
162
|
|
|
157
163
|
|
|
164
|
+
def _remove_tokens_and_embeddings(
|
|
165
|
+
tokenizer: PreTrainedTokenizerFast, token_remove_pattern: str | None, tokens: list[str], embeddings: np.ndarray
|
|
166
|
+
) -> tuple[Tokenizer, np.ndarray]:
|
|
167
|
+
if not token_remove_pattern:
|
|
168
|
+
return tokenizer.backend_tokenizer, embeddings
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
token_regex = re.compile(token_remove_pattern)
|
|
172
|
+
except re.error as e:
|
|
173
|
+
raise ValueError(f"Invalid regex pattern: {token_remove_pattern}") from e
|
|
174
|
+
# Remove any unused tokens from the tokenizer and embeddings.
|
|
175
|
+
wrong_tokens = [x for x in tokens if token_regex.match(x)]
|
|
176
|
+
vocab = tokenizer.get_vocab()
|
|
177
|
+
# Get the ids of the unused token.
|
|
178
|
+
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
179
|
+
|
|
180
|
+
if len(wrong_token_ids) == len(vocab):
|
|
181
|
+
raise ValueError(
|
|
182
|
+
"All tokens in the vocabulary are unused tokens. This will result in an empty tokenizer. "
|
|
183
|
+
"Please provide a valid token removal pattern. The pattern is now: {token_remove_pattern}"
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# Remove the unused tokens from the tokenizer.
|
|
187
|
+
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
|
|
188
|
+
# Remove the embeddings of the unused tokens.
|
|
189
|
+
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
190
|
+
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
191
|
+
|
|
192
|
+
return new_tokenizer, embeddings
|
|
193
|
+
|
|
194
|
+
|
|
158
195
|
def distill(
|
|
159
196
|
model_name: str,
|
|
160
197
|
vocabulary: list[str] | None = None,
|
model2vec/distill/tokenizer.py
CHANGED
|
@@ -68,10 +68,12 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
|
|
|
68
68
|
tokenizer_data["model"]["vocab"] = reindexed
|
|
69
69
|
|
|
70
70
|
elif model_type == "Unigram":
|
|
71
|
-
|
|
71
|
+
logger.warning("Removing tokens from a unigram tokenizer is not supported.")
|
|
72
|
+
return tokenizer
|
|
72
73
|
|
|
73
74
|
elif model_type == "BPE":
|
|
74
|
-
|
|
75
|
+
logger.warning("Removing tokens from a BPE tokenizer is not supported.")
|
|
76
|
+
return tokenizer
|
|
75
77
|
|
|
76
78
|
else:
|
|
77
79
|
raise ValueError(f"Unknown model type {model_type}")
|
model2vec/model.py
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import math
|
|
4
|
+
import os
|
|
4
5
|
from logging import getLogger
|
|
5
6
|
from pathlib import Path
|
|
6
7
|
from tempfile import TemporaryDirectory
|
|
7
8
|
from typing import Any, Iterator, Union
|
|
8
9
|
|
|
9
10
|
import numpy as np
|
|
11
|
+
from joblib import delayed
|
|
10
12
|
from tokenizers import Encoding, Tokenizer
|
|
11
13
|
from tqdm import tqdm
|
|
12
14
|
|
|
13
|
-
from model2vec.utils import load_local_model
|
|
15
|
+
from model2vec.utils import ProgressParallel, load_local_model
|
|
14
16
|
|
|
15
17
|
PathLike = Union[Path, str]
|
|
16
18
|
|
|
17
|
-
|
|
18
19
|
logger = getLogger(__name__)
|
|
19
20
|
|
|
20
21
|
|
|
@@ -171,6 +172,8 @@ class StaticModel:
|
|
|
171
172
|
max_length: int | None = None,
|
|
172
173
|
batch_size: int = 1024,
|
|
173
174
|
show_progress_bar: bool = False,
|
|
175
|
+
use_multiprocessing: bool = True,
|
|
176
|
+
multiprocessing_threshold: int = 10_000,
|
|
174
177
|
) -> list[np.ndarray] | np.ndarray:
|
|
175
178
|
"""
|
|
176
179
|
Encode a list of sentences as a list of numpy arrays of tokens.
|
|
@@ -186,6 +189,9 @@ class StaticModel:
|
|
|
186
189
|
If this is None, no truncation is done.
|
|
187
190
|
:param batch_size: The batch size to use.
|
|
188
191
|
:param show_progress_bar: Whether to show the progress bar.
|
|
192
|
+
:param use_multiprocessing: Whether to use multiprocessing.
|
|
193
|
+
By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.
|
|
194
|
+
:param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.
|
|
189
195
|
:return: The encoded sentences with an embedding per token.
|
|
190
196
|
"""
|
|
191
197
|
was_single = False
|
|
@@ -193,17 +199,32 @@ class StaticModel:
|
|
|
193
199
|
sentences = [sentences]
|
|
194
200
|
was_single = True
|
|
195
201
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
):
|
|
202
|
-
|
|
202
|
+
# Prepare all batches
|
|
203
|
+
sentence_batches = list(self._batch(sentences, batch_size))
|
|
204
|
+
total_batches = math.ceil(len(sentences) / batch_size)
|
|
205
|
+
|
|
206
|
+
# Use joblib for multiprocessing if requested, and if we have enough sentences
|
|
207
|
+
if use_multiprocessing and len(sentences) > multiprocessing_threshold:
|
|
208
|
+
# Disable parallelism for tokenizers
|
|
209
|
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
210
|
+
|
|
211
|
+
results = ProgressParallel(n_jobs=-1, use_tqdm=show_progress_bar, total=total_batches)(
|
|
212
|
+
delayed(self._encode_batch_as_sequence)(batch, max_length) for batch in sentence_batches
|
|
213
|
+
)
|
|
214
|
+
out_array: list[np.ndarray] = []
|
|
215
|
+
for r in results:
|
|
216
|
+
out_array.extend(r)
|
|
217
|
+
else:
|
|
218
|
+
out_array = []
|
|
219
|
+
for batch in tqdm(
|
|
220
|
+
sentence_batches,
|
|
221
|
+
total=total_batches,
|
|
222
|
+
disable=not show_progress_bar,
|
|
223
|
+
):
|
|
224
|
+
out_array.extend(self._encode_batch_as_sequence(batch, max_length))
|
|
203
225
|
|
|
204
226
|
if was_single:
|
|
205
227
|
return out_array[0]
|
|
206
|
-
|
|
207
228
|
return out_array
|
|
208
229
|
|
|
209
230
|
def _encode_batch_as_sequence(self, sentences: list[str], max_length: int | None) -> list[np.ndarray]:
|
|
@@ -224,6 +245,8 @@ class StaticModel:
|
|
|
224
245
|
show_progress_bar: bool = False,
|
|
225
246
|
max_length: int | None = 512,
|
|
226
247
|
batch_size: int = 1024,
|
|
248
|
+
use_multiprocessing: bool = True,
|
|
249
|
+
multiprocessing_threshold: int = 10_000,
|
|
227
250
|
**kwargs: Any,
|
|
228
251
|
) -> np.ndarray:
|
|
229
252
|
"""
|
|
@@ -237,6 +260,9 @@ class StaticModel:
|
|
|
237
260
|
:param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.
|
|
238
261
|
If this is None, no truncation is done.
|
|
239
262
|
:param batch_size: The batch size to use.
|
|
263
|
+
:param use_multiprocessing: Whether to use multiprocessing.
|
|
264
|
+
By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.
|
|
265
|
+
:param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.
|
|
240
266
|
:param **kwargs: Any additional arguments. These are ignored.
|
|
241
267
|
:return: The encoded sentences. If a single sentence was passed, a vector is returned.
|
|
242
268
|
"""
|
|
@@ -245,19 +271,32 @@ class StaticModel:
|
|
|
245
271
|
sentences = [sentences]
|
|
246
272
|
was_single = True
|
|
247
273
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
total=math.ceil(len(sentences) / batch_size),
|
|
252
|
-
disable=not show_progress_bar,
|
|
253
|
-
):
|
|
254
|
-
out_arrays.append(self._encode_batch(batch, max_length))
|
|
274
|
+
# Prepare all batches
|
|
275
|
+
sentence_batches = list(self._batch(sentences, batch_size))
|
|
276
|
+
total_batches = math.ceil(len(sentences) / batch_size)
|
|
255
277
|
|
|
256
|
-
|
|
278
|
+
# Use joblib for multiprocessing if requested, and if we have enough sentences
|
|
279
|
+
if use_multiprocessing and len(sentences) > multiprocessing_threshold:
|
|
280
|
+
# Disable parallelism for tokenizers
|
|
281
|
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
282
|
+
|
|
283
|
+
results = ProgressParallel(n_jobs=-1, use_tqdm=show_progress_bar, total=total_batches)(
|
|
284
|
+
delayed(self._encode_batch)(batch, max_length) for batch in sentence_batches
|
|
285
|
+
)
|
|
286
|
+
out_array = np.concatenate(results, axis=0)
|
|
287
|
+
else:
|
|
288
|
+
# Don't use multiprocessing
|
|
289
|
+
out_arrays: list[np.ndarray] = []
|
|
290
|
+
for batch in tqdm(
|
|
291
|
+
sentence_batches,
|
|
292
|
+
total=total_batches,
|
|
293
|
+
disable=not show_progress_bar,
|
|
294
|
+
):
|
|
295
|
+
out_arrays.append(self._encode_batch(batch, max_length))
|
|
296
|
+
out_array = np.concatenate(out_arrays, axis=0)
|
|
257
297
|
|
|
258
298
|
if was_single:
|
|
259
299
|
return out_array[0]
|
|
260
|
-
|
|
261
300
|
return out_array
|
|
262
301
|
|
|
263
302
|
def _encode_batch(self, sentences: list[str], max_length: int | None) -> np.ndarray:
|
model2vec/utils.py
CHANGED
|
@@ -1,18 +1,56 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
2
4
|
import json
|
|
3
5
|
import logging
|
|
6
|
+
import re
|
|
4
7
|
from importlib import import_module
|
|
5
8
|
from importlib.metadata import metadata
|
|
6
9
|
from pathlib import Path
|
|
7
|
-
from typing import Iterator, Protocol, cast
|
|
10
|
+
from typing import Any, Iterator, Protocol, cast
|
|
8
11
|
|
|
9
12
|
import numpy as np
|
|
10
13
|
import safetensors
|
|
14
|
+
from joblib import Parallel
|
|
11
15
|
from tokenizers import Tokenizer
|
|
16
|
+
from tqdm import tqdm
|
|
12
17
|
|
|
13
18
|
logger = logging.getLogger(__name__)
|
|
14
19
|
|
|
15
20
|
|
|
21
|
+
class ProgressParallel(Parallel):
|
|
22
|
+
"""A drop-in replacement for joblib.Parallel that shows a tqdm progress bar."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, use_tqdm: bool = True, total: int | None = None, *args: Any, **kwargs: Any) -> None:
|
|
25
|
+
"""
|
|
26
|
+
Initialize the ProgressParallel object.
|
|
27
|
+
|
|
28
|
+
:param use_tqdm: Whether to show the progress bar.
|
|
29
|
+
:param total: Total number of tasks (batches) you expect to process. If None,
|
|
30
|
+
it updates the total dynamically to the number of dispatched tasks.
|
|
31
|
+
:param *args: Additional arguments to pass to `Parallel.__init__`.
|
|
32
|
+
:param **kwargs: Additional keyword arguments to pass to `Parallel.__init__`.
|
|
33
|
+
"""
|
|
34
|
+
self._use_tqdm = use_tqdm
|
|
35
|
+
self._total = total
|
|
36
|
+
super().__init__(*args, **kwargs)
|
|
37
|
+
|
|
38
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
39
|
+
"""Create a tqdm context."""
|
|
40
|
+
with tqdm(disable=not self._use_tqdm, total=self._total) as self._pbar:
|
|
41
|
+
self._pbar = self._pbar
|
|
42
|
+
return super().__call__(*args, **kwargs)
|
|
43
|
+
|
|
44
|
+
def print_progress(self) -> None:
|
|
45
|
+
"""Hook called by joblib as tasks complete. We update the tqdm bar here."""
|
|
46
|
+
if self._total is None:
|
|
47
|
+
# If no fixed total was given, we dynamically set the total
|
|
48
|
+
self._pbar.total = self.n_dispatched_tasks
|
|
49
|
+
# Move the bar to the number of completed tasks
|
|
50
|
+
self._pbar.n = self.n_completed_tasks
|
|
51
|
+
self._pbar.refresh()
|
|
52
|
+
|
|
53
|
+
|
|
16
54
|
class SafeOpenProtocol(Protocol):
|
|
17
55
|
"""Protocol to fix safetensors safe open."""
|
|
18
56
|
|
|
@@ -22,6 +60,7 @@ class SafeOpenProtocol(Protocol):
|
|
|
22
60
|
|
|
23
61
|
|
|
24
62
|
_MODULE_MAP = (("scikit-learn", "sklearn"),)
|
|
63
|
+
_DIVIDERS = re.compile(r"[=<>!]+")
|
|
25
64
|
|
|
26
65
|
|
|
27
66
|
def get_package_extras(package: str, extra: str) -> Iterator[str]:
|
|
@@ -38,7 +77,8 @@ def get_package_extras(package: str, extra: str) -> Iterator[str]:
|
|
|
38
77
|
# Extract and clean the extra requirement
|
|
39
78
|
found_extra = rest[0].split("==")[-1].strip(" \"'")
|
|
40
79
|
if found_extra == extra:
|
|
41
|
-
|
|
80
|
+
prefix, *_ = _DIVIDERS.split(name)
|
|
81
|
+
yield prefix.strip()
|
|
42
82
|
|
|
43
83
|
|
|
44
84
|
def importable(module: str, extra: str) -> None:
|
model2vec/version.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
__version_triple__ = (0, 3,
|
|
1
|
+
__version_triple__ = (0, 3, 5)
|
|
2
2
|
__version__ = ".".join(map(str, __version_triple__))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.5
|
|
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
|
|
@@ -44,27 +44,28 @@ Requires-Python: >=3.9
|
|
|
44
44
|
Description-Content-Type: text/markdown
|
|
45
45
|
License-File: LICENSE
|
|
46
46
|
Requires-Dist: jinja2
|
|
47
|
+
Requires-Dist: joblib
|
|
47
48
|
Requires-Dist: numpy
|
|
48
49
|
Requires-Dist: rich
|
|
49
50
|
Requires-Dist: safetensors
|
|
50
51
|
Requires-Dist: setuptools
|
|
51
|
-
Requires-Dist: tokenizers
|
|
52
|
+
Requires-Dist: tokenizers>=0.20
|
|
52
53
|
Requires-Dist: tqdm
|
|
53
54
|
Provides-Extra: dev
|
|
54
|
-
Requires-Dist: black
|
|
55
|
-
Requires-Dist: ipython
|
|
56
|
-
Requires-Dist: mypy
|
|
57
|
-
Requires-Dist: pre-commit
|
|
58
|
-
Requires-Dist: pytest
|
|
59
|
-
Requires-Dist: pytest-
|
|
60
|
-
Requires-Dist: ruff
|
|
55
|
+
Requires-Dist: black; extra == "dev"
|
|
56
|
+
Requires-Dist: ipython; extra == "dev"
|
|
57
|
+
Requires-Dist: mypy; extra == "dev"
|
|
58
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
59
|
+
Requires-Dist: pytest; extra == "dev"
|
|
60
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
61
|
+
Requires-Dist: ruff; extra == "dev"
|
|
61
62
|
Provides-Extra: distill
|
|
62
|
-
Requires-Dist: torch
|
|
63
|
-
Requires-Dist: transformers
|
|
64
|
-
Requires-Dist: scikit-learn
|
|
63
|
+
Requires-Dist: torch; extra == "distill"
|
|
64
|
+
Requires-Dist: transformers; extra == "distill"
|
|
65
|
+
Requires-Dist: scikit-learn; extra == "distill"
|
|
65
66
|
Provides-Extra: onnx
|
|
66
|
-
Requires-Dist: onnx
|
|
67
|
-
Requires-Dist: torch
|
|
67
|
+
Requires-Dist: onnx; extra == "onnx"
|
|
68
|
+
Requires-Dist: torch; extra == "onnx"
|
|
68
69
|
|
|
69
70
|
|
|
70
71
|
<div align="center">
|
|
@@ -82,7 +83,7 @@ Requires-Dist: torch ; extra == 'onnx'
|
|
|
82
83
|
<h2>
|
|
83
84
|
<a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
|
|
84
85
|
<a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
|
|
85
|
-
<a href="https://
|
|
86
|
+
<a href="https://minishlab.github.io/"><strong>🌐 Website</strong></a> |
|
|
86
87
|
<a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a>
|
|
87
88
|
</h2>
|
|
88
89
|
</div>
|
|
@@ -119,35 +120,33 @@ Model2Vec is a technique to turn any sentence transformer into a really small st
|
|
|
119
120
|
- [Main Features](#main-features)
|
|
120
121
|
- [What is Model2Vec?](#what-is-model2vec)
|
|
121
122
|
- [Usage](#usage)
|
|
122
|
-
- [Distillation](#distillation)
|
|
123
123
|
- [Inference](#inference)
|
|
124
|
+
- [Distillation](#distillation)
|
|
124
125
|
- [Evaluation](#evaluation)
|
|
125
|
-
|
|
126
|
+
- [Integrations](#integrations)
|
|
126
127
|
- [Model List](#model-list)
|
|
127
128
|
- [Results](#results)
|
|
128
|
-
- [Related Work](#related-work)
|
|
129
|
-
- [Citing](#citing)
|
|
130
129
|
|
|
131
130
|
## Quickstart
|
|
132
131
|
|
|
133
|
-
Install the package
|
|
132
|
+
Install the package with:
|
|
133
|
+
|
|
134
134
|
```bash
|
|
135
|
-
pip install model2vec
|
|
135
|
+
pip install model2vec
|
|
136
136
|
```
|
|
137
137
|
|
|
138
|
-
|
|
138
|
+
This will install the base inference package, which only depends on `numpy` and a few other minor dependencies. If you want to distill your own models, you can install the distillation extras with:
|
|
139
139
|
|
|
140
140
|
```bash
|
|
141
|
-
pip install model2vec
|
|
141
|
+
pip install model2vec[distill]
|
|
142
142
|
```
|
|
143
143
|
|
|
144
|
-
The easiest way to get started with Model2Vec is to
|
|
144
|
+
The easiest way to get started with Model2Vec is to load one of our [flagship models from the HuggingFace hub](https://huggingface.co/collections/minishlab/potion-6721e0abd4ea41881417f062). These models are pre-trained and ready to use. The following code snippet shows how to load a model and make embeddings:
|
|
145
145
|
```python
|
|
146
146
|
from model2vec import StaticModel
|
|
147
147
|
|
|
148
148
|
# Load a model from the HuggingFace hub (in this case the potion-base-8M model)
|
|
149
|
-
|
|
150
|
-
model = StaticModel.from_pretrained(model_name)
|
|
149
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
151
150
|
|
|
152
151
|
# Make embeddings
|
|
153
152
|
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
@@ -158,82 +157,89 @@ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It'
|
|
|
158
157
|
|
|
159
158
|
And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
|
|
160
159
|
|
|
161
|
-
Instead of using one of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
|
|
160
|
+
Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
|
|
162
161
|
```python
|
|
163
162
|
from model2vec.distill import distill
|
|
164
163
|
|
|
165
|
-
#
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
# Distill the model
|
|
169
|
-
m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
164
|
+
# Distill a Sentence Transformer model, in this case the BAAI/bge-base-en-v1.5 model
|
|
165
|
+
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)
|
|
170
166
|
|
|
171
167
|
# Save the model
|
|
172
168
|
m2v_model.save_pretrained("m2v_model")
|
|
173
169
|
```
|
|
174
170
|
|
|
175
|
-
Distillation is really fast
|
|
171
|
+
Distillation is really fast and only takes 30 seconds on CPU. Best of all, distillation requires no training data.
|
|
176
172
|
|
|
177
|
-
|
|
178
|
-
```python
|
|
179
|
-
from sentence_transformers import SentenceTransformer
|
|
180
|
-
from sentence_transformers.models import StaticEmbedding
|
|
173
|
+
For advanced usage, such as using Model2Vec in the [Sentence Transformers library](https://github.com/UKPLab/sentence-transformers), please refer to the [Usage](#usage) sections.
|
|
181
174
|
|
|
182
|
-
# Initialize a StaticEmbedding module
|
|
183
|
-
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
184
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
185
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
Or you can distill a model directly into a Sentence Transformer model:
|
|
189
|
-
```python
|
|
190
|
-
from sentence_transformers import SentenceTransformer
|
|
191
|
-
from sentence_transformers.models import StaticEmbedding
|
|
192
|
-
|
|
193
|
-
static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cpu", pca_dims=256)
|
|
194
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
195
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
196
|
-
```
|
|
197
|
-
For more documentation, please refer to the [Sentence Transformers documentation](https://sbert.net/docs/package_reference/sentence_transformer/models.html#sentence_transformers.models.StaticEmbedding).
|
|
198
175
|
|
|
199
176
|
## Main Features
|
|
200
177
|
|
|
201
|
-
Model2Vec
|
|
202
|
-
|
|
203
|
-
- **
|
|
204
|
-
- **
|
|
205
|
-
- **Fast
|
|
206
|
-
- **
|
|
207
|
-
- **No data needed**: Distillation happens directly on the token level, so no dataset is needed.
|
|
208
|
-
- **Simple to use**: An easy to use interface for distilling and inferencing.
|
|
209
|
-
- **Integrated into Sentence Transformers**: Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers).
|
|
210
|
-
- **Bring your own model**: Can be applied to any Sentence Transformer model.
|
|
211
|
-
- **Bring your own vocabulary**: Can be applied to any vocabulary, allowing you to use your own domain-specific vocabulary. Need biomedical? Just get a medical dictionary, a biomedical model, and inference it.
|
|
212
|
-
- **Multi-lingual**: Use any language. Need a French model? [Pick one](https://huggingface.co/models?library=sentence-transformers&language=fr&sort=trending). Need multilingual? [Here you go](https://huggingface.co/sentence-transformers/LaBSE).
|
|
178
|
+
- **State-of-the-Art Performance**: Model2Vec models outperform any other static embeddings (such as GLoVe and BPEmb) by a large margin, as can be seen in our [results](results/README.md).
|
|
179
|
+
- **Small**: Model2Vec reduces the size of a Sentence Transformer model by a factor of 15, from 120M params, down to 7.5M (30 MB on disk, making it the smallest model on [MTEB](https://huggingface.co/spaces/mteb/leaderboard)!).
|
|
180
|
+
- **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
|
|
181
|
+
- **Lightning-fast Inference**: up to 500 times faster on CPU than the original model. Go green or go home.
|
|
182
|
+
- **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset. All you need is a model and (optionally) a custom vocabulary.
|
|
183
|
+
- **Integrated in many popular libraries**: Model2Vec can be used directly in popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers), [LangChain](https://github.com/langchain-ai/langchain), [txtai](https://github.com/neuml/txtai), and [Chonkie](https://github.com/bhavnicksm/chonkie). See the [Integrations](#integrations) section for more information.
|
|
213
184
|
- **Tightly integrated with HuggingFace hub**: easily share and load models from the HuggingFace hub, using the familiar `from_pretrained` and `push_to_hub`. Our own models can be found [here](https://huggingface.co/minishlab). Feel free to share your own.
|
|
214
|
-
- **Easy Evaluation**: evaluate your models on MTEB and some of our own tasks to measure the performance of the distilled model. Model2Vec models work out of the box on [MTEB](https://huggingface.co/spaces/mteb/leaderboard).
|
|
215
185
|
|
|
216
186
|
## What is Model2Vec?
|
|
217
187
|
|
|
218
|
-
Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance.
|
|
188
|
+
Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Distillation doesn't need _any_ data, just a vocabulary and a model.
|
|
219
189
|
|
|
220
|
-
|
|
190
|
+
The base model2vec technique works by passing a vocabulary through a sentence transformer model, then reducing the dimensionality of the resulting embeddings using PCA, and finally weighting the embeddings using zipf weighting. During inference, we simply take the mean of all token embeddings occurring in a sentence.
|
|
221
191
|
|
|
222
|
-
|
|
223
|
-
- **
|
|
224
|
-
- **
|
|
225
|
-
- **
|
|
192
|
+
Our [potion models](https://huggingface.co/collections/minishlab/potion-6721e0abd4ea41881417f062) are pre-trained using [tokenlearn](https://github.com/MinishLab/tokenlearn), a technique to pre-train model2vec distillation models. These models are created with the following steps:
|
|
193
|
+
- **Distillation**: We distill a Model2Vec model from a Sentence Transformer model, using the method described above.
|
|
194
|
+
- **Sentence Transformer inference**: We use the Sentence Transformer model to create mean embeddings for a large number of texts from a corpus.
|
|
195
|
+
- **Training**: We train a model to minimize the cosine distance between the mean embeddings generated by the Sentence Transformer model and the mean embeddings generated by the Model2Vec model.
|
|
196
|
+
- **Post-training re-regularization**: We re-regularize the trained embeddings by first performing PCA, and then weighting the embeddings using `smooth inverse frequency (SIF)` weighting using the following formula: `w = 1e-3 / (1e-3 + proba)`. Here, `proba` is the probability of the token in the corpus we used for training.
|
|
226
197
|
|
|
227
|
-
For a technical deepdive into Model2Vec, please refer to our [blog post](https://huggingface.co/blog/Pringled/model2vec).
|
|
228
198
|
|
|
229
|
-
|
|
199
|
+
For a much more extensive deepdive, please refer to our [Model2Vec blog post](https://huggingface.co/blog/Pringled/model2vec) and our [Tokenlearn blog post](https://minishlab.github.io/tokenlearn_blogpost/).
|
|
230
200
|
|
|
231
|
-
|
|
201
|
+
## Usage
|
|
232
202
|
|
|
203
|
+
### Inference
|
|
233
204
|
|
|
234
|
-
|
|
205
|
+
<details>
|
|
206
|
+
<summary> Inference with a pretrained model </summary>
|
|
207
|
+
<br>
|
|
208
|
+
|
|
209
|
+
Inference works as follows. The example shows one of our own models, but you can also just load a local one, or another one from the hub.
|
|
210
|
+
```python
|
|
211
|
+
from model2vec import StaticModel
|
|
212
|
+
|
|
213
|
+
# Load a model from the Hub. You can optionally pass a token when loading a private model
|
|
214
|
+
model = StaticModel.from_pretrained(model_name="minishlab/potion-base-8M", token=None)
|
|
215
|
+
|
|
216
|
+
# Make embeddings
|
|
217
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
218
|
+
|
|
219
|
+
# Make sequences of token embeddings
|
|
220
|
+
token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
221
|
+
```
|
|
222
|
+
</details>
|
|
235
223
|
|
|
236
224
|
|
|
225
|
+
<details>
|
|
226
|
+
<summary> Inference with the Sentence Transformers library </summary>
|
|
227
|
+
<br>
|
|
228
|
+
|
|
229
|
+
The following code snippet shows how to use a Model2Vec model in the [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) library. This is useful if you want to use the model in a Sentence Transformers pipeline.
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
from sentence_transformers import SentenceTransformer
|
|
233
|
+
from sentence_transformers.models import StaticEmbedding
|
|
234
|
+
|
|
235
|
+
# Initialize a StaticEmbedding module
|
|
236
|
+
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
237
|
+
model = SentenceTransformer(modules=[static_embedding])
|
|
238
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
</details>
|
|
242
|
+
|
|
237
243
|
### Distillation
|
|
238
244
|
|
|
239
245
|
<details>
|
|
@@ -244,11 +250,8 @@ The following code can be used to distill a model from a Sentence Transformer. A
|
|
|
244
250
|
```python
|
|
245
251
|
from model2vec.distill import distill
|
|
246
252
|
|
|
247
|
-
#
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
# Distill the model
|
|
251
|
-
m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
253
|
+
# Distill a Sentence Transformer model
|
|
254
|
+
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)
|
|
252
255
|
|
|
253
256
|
# Save the model
|
|
254
257
|
m2v_model.save_pretrained("m2v_model")
|
|
@@ -308,11 +311,9 @@ from model2vec.distill import distill
|
|
|
308
311
|
|
|
309
312
|
# Load a vocabulary as a list of strings
|
|
310
313
|
vocabulary = ["word1", "word2", "word3"]
|
|
311
|
-
# Choose a Sentence Transformer model
|
|
312
|
-
model_name = "BAAI/bge-base-en-v1.5"
|
|
313
314
|
|
|
314
|
-
# Distill
|
|
315
|
-
m2v_model = distill(model_name=
|
|
315
|
+
# Distill a Sentence Transformer model with the custom vocabulary
|
|
316
|
+
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", vocabulary=vocabulary)
|
|
316
317
|
|
|
317
318
|
# Save the model
|
|
318
319
|
m2v_model.save_pretrained("m2v_model")
|
|
@@ -331,48 +332,6 @@ m2v_model = distill(model_name=model_name, vocabulary=vocabulary, use_subword=Fa
|
|
|
331
332
|
|
|
332
333
|
</details>
|
|
333
334
|
|
|
334
|
-
### Inference
|
|
335
|
-
|
|
336
|
-
<details>
|
|
337
|
-
<summary> Inference using pretrained model </summary>
|
|
338
|
-
<br>
|
|
339
|
-
|
|
340
|
-
Inference works as follows. The example shows one of our own models, but you can also just load a local one, or another one from the hub.
|
|
341
|
-
```python
|
|
342
|
-
from model2vec import StaticModel
|
|
343
|
-
|
|
344
|
-
# Load a model from the HuggingFace hub, or a local one.
|
|
345
|
-
model_name = "minishlab/potion-base-8M"
|
|
346
|
-
# You can optionally pass a token if you're loading a private model
|
|
347
|
-
model = StaticModel.from_pretrained(model_name, token=None)
|
|
348
|
-
|
|
349
|
-
# Make embeddings
|
|
350
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
351
|
-
|
|
352
|
-
# Make sequences of token embeddings
|
|
353
|
-
token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
354
|
-
```
|
|
355
|
-
</details>
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
<details>
|
|
359
|
-
<summary> Inference using the Sentence Transformers library </summary>
|
|
360
|
-
<br>
|
|
361
|
-
|
|
362
|
-
The following code snippet shows how to use a Model2Vec model in the [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) library. This is useful if you want to use the model in a Sentence Transformers pipeline.
|
|
363
|
-
|
|
364
|
-
```python
|
|
365
|
-
from sentence_transformers import SentenceTransformer
|
|
366
|
-
from sentence_transformers.models import StaticEmbedding
|
|
367
|
-
|
|
368
|
-
# Initialize a StaticEmbedding module
|
|
369
|
-
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
370
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
371
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
372
|
-
```
|
|
373
|
-
|
|
374
|
-
</details>
|
|
375
|
-
|
|
376
335
|
|
|
377
336
|
### Evaluation
|
|
378
337
|
|
|
@@ -425,9 +384,10 @@ print(make_leaderboard(task_scores))
|
|
|
425
384
|
```
|
|
426
385
|
</details>
|
|
427
386
|
|
|
428
|
-
|
|
387
|
+
## Integrations
|
|
429
388
|
<details>
|
|
430
389
|
<summary> Sentence Transformers </summary>
|
|
390
|
+
<a name="sentence-transformers"></a>
|
|
431
391
|
<br>
|
|
432
392
|
|
|
433
393
|
Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) using the `StaticEmbedding` module.
|
|
@@ -454,12 +414,97 @@ model = SentenceTransformer(modules=[static_embedding])
|
|
|
454
414
|
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
455
415
|
```
|
|
456
416
|
|
|
417
|
+
For more documentation, please refer to the [Sentence Transformers documentation](https://sbert.net/docs/package_reference/sentence_transformer/models.html#sentence_transformers.models.StaticEmbedding).
|
|
418
|
+
|
|
457
419
|
</details>
|
|
458
420
|
|
|
421
|
+
<details>
|
|
422
|
+
<summary> LangChain </summary>
|
|
423
|
+
<br>
|
|
424
|
+
|
|
425
|
+
Model2Vec can be used in [LangChain](https://github.com/langchain-ai/langchain) using the `langchain-community` package. For more information, see the [LangChain Model2Vec docs](https://python.langchain.com/docs/integrations/text_embedding/model2vec/). The following code snippet shows how to use Model2Vec in LangChain after installing the `langchain-community` package with `pip install langchain-community`:
|
|
426
|
+
|
|
427
|
+
```python
|
|
428
|
+
from langchain_community.embeddings import Model2vecEmbeddings
|
|
429
|
+
from langchain_community.vectorstores import FAISS
|
|
430
|
+
from langchain.schema import Document
|
|
431
|
+
|
|
432
|
+
# Initialize a Model2Vec embedder
|
|
433
|
+
embedder = Model2vecEmbeddings("minishlab/potion-base-8M")
|
|
434
|
+
|
|
435
|
+
# Create some example texts
|
|
436
|
+
texts = [
|
|
437
|
+
"Enduring Stew",
|
|
438
|
+
"Hearty Elixir",
|
|
439
|
+
"Mighty Mushroom Risotto",
|
|
440
|
+
"Spicy Meat Skewer",
|
|
441
|
+
"Fruit Salad",
|
|
442
|
+
]
|
|
443
|
+
|
|
444
|
+
# Embed the texts
|
|
445
|
+
embeddings = embedder.embed_documents(texts)
|
|
446
|
+
|
|
447
|
+
# Or, create a vector store and query it
|
|
448
|
+
documents = [Document(page_content=text) for text in texts]
|
|
449
|
+
vector_store = FAISS.from_documents(documents, embedder)
|
|
450
|
+
query = "Risotto"
|
|
451
|
+
query_vector = embedder.embed_query(query)
|
|
452
|
+
retrieved_docs = vector_store.similarity_search_by_vector(query_vector, k=1)
|
|
453
|
+
```
|
|
454
|
+
</details>
|
|
459
455
|
|
|
460
456
|
<details>
|
|
461
|
-
<summary>
|
|
457
|
+
<summary> Txtai </summary>
|
|
458
|
+
<br>
|
|
459
|
+
|
|
460
|
+
Model2Vec can be used in [txtai](https://github.com/neuml/txtai) for text embeddings, nearest-neighbors search, and any of the other functionalities that txtai offers. The following code snippet shows how to use Model2Vec in txtai after installing the `txtai` package (including the `vectors` dependency) with `pip install txtai[vectors]`:
|
|
461
|
+
|
|
462
|
+
```python
|
|
463
|
+
from txtai import Embeddings
|
|
464
|
+
|
|
465
|
+
# Load a model2vec model
|
|
466
|
+
embeddings = Embeddings(path="minishlab/potion-base-8M", method="model2vec", backend="numpy")
|
|
467
|
+
|
|
468
|
+
# Create some example texts
|
|
469
|
+
texts = ["Enduring Stew", "Hearty Elixir", "Mighty Mushroom Risotto", "Spicy Meat Skewer", "Chilly Fruit Salad"]
|
|
470
|
+
|
|
471
|
+
# Create embeddings for downstream tasks
|
|
472
|
+
vectors = embeddings.batchtransform(texts)
|
|
473
|
+
|
|
474
|
+
# Or create a nearest-neighbors index and search it
|
|
475
|
+
embeddings.index(texts)
|
|
476
|
+
result = embeddings.search("Risotto", 1)
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
</details>
|
|
480
|
+
|
|
481
|
+
<details>
|
|
482
|
+
<summary> Chonkie </summary>
|
|
483
|
+
<br>
|
|
484
|
+
|
|
485
|
+
Model2Vec is the default model for semantic chunking in [Chonkie](https://github.com/bhavnicksm/chonkie). To use Model2Vec for semantic chunking in Chonkie, simply install Chonkie with `pip install chonkie[semantic]` and use one of the `potion` models in the `SemanticChunker` class. The following code snippet shows how to use Model2Vec in Chonkie:
|
|
486
|
+
|
|
487
|
+
```python
|
|
488
|
+
from chonkie import SDPMChunker
|
|
489
|
+
|
|
490
|
+
# Create some example text to chunk
|
|
491
|
+
text = "It's dangerous to go alone! Take this."
|
|
462
492
|
|
|
493
|
+
# Initialize the SemanticChunker with a potion model
|
|
494
|
+
chunker = SDPMChunker(
|
|
495
|
+
embedding_model="minishlab/potion-base-8M",
|
|
496
|
+
similarity_threshold=0.3
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
# Chunk the text
|
|
500
|
+
chunks = chunker.chunk(text)
|
|
501
|
+
```
|
|
502
|
+
|
|
503
|
+
</details>
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
<details>
|
|
507
|
+
<summary> Transformers.js </summary>
|
|
463
508
|
<br>
|
|
464
509
|
|
|
465
510
|
To use a Model2Vec model in [transformers.js](https://github.com/huggingface/transformers.js), the following code snippet can be used as a starting point:
|
|
@@ -513,12 +558,13 @@ python scripts/export_to_onnx.py --model_path <path-to-a-model2vec-model> --save
|
|
|
513
558
|
We provide a number of models that can be used out of the box. These models are available on the [HuggingFace hub](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e) and can be loaded using the `from_pretrained` method. The models are listed below.
|
|
514
559
|
|
|
515
560
|
|
|
516
|
-
| Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn
|
|
517
|
-
|
|
518
|
-
| [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 |
|
|
519
|
-
| [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
|
|
520
|
-
| [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
|
|
521
|
-
| [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M |
|
|
561
|
+
| Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
|
|
562
|
+
|-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|-------------------|
|
|
563
|
+
| [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
|
+
| [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
|
+
| [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> |
|
|
566
|
+
| [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
|
+
|
|
522
568
|
|
|
523
569
|
|
|
524
570
|
## Results
|
|
@@ -527,15 +573,6 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
|
|
|
527
573
|
- [MTEB Results](results/README.md#mteb-results)
|
|
528
574
|
- [Ablations](results/README.md#ablations)
|
|
529
575
|
|
|
530
|
-
## Related work
|
|
531
|
-
|
|
532
|
-
If you are interested in fast small models, also consider looking at these techniques:
|
|
533
|
-
* [BPEmb](https://bpemb.h-its.org/): GLoVE embeddings trained on BPE-encoded Wikipedias. Huge inspiration to this project, multilingual, very fast. If you don't find a sentence transformer in the language you need, check this out.
|
|
534
|
-
* [fast-sentence-transformers](https://github.com/davidberenstein1957/fast-sentence-transformers): distillation using Model2Vec comes at a cost. If that cost is too steep for you, and you have access to a GPU, this package is for you. It automates the quantization and optimization of sentence transformers without loss of performance.
|
|
535
|
-
* [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. We think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. Fun fact: this was invented at the same time as Model2Vec.
|
|
536
|
-
|
|
537
|
-
If you find other related work, please let us know.
|
|
538
|
-
|
|
539
576
|
## License
|
|
540
577
|
|
|
541
578
|
MIT
|
|
@@ -546,7 +583,7 @@ If you use Model2Vec in your research, please cite the following:
|
|
|
546
583
|
```bibtex
|
|
547
584
|
@software{minishlab2024model2vec,
|
|
548
585
|
authors = {Stephan Tulkens, Thomas van Dongen},
|
|
549
|
-
title = {Model2Vec:
|
|
586
|
+
title = {Model2Vec: The Fastest State-of-the-Art Static Embeddings in the World},
|
|
550
587
|
year = {2024},
|
|
551
588
|
url = {https://github.com/MinishLab/model2vec},
|
|
552
589
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
|
|
2
|
+
model2vec/hf_utils.py,sha256=Z-_V2kYagBX7m9_--e2ZAGP4irfRpqIlBQgGwYswpoU,7772
|
|
3
|
+
model2vec/model.py,sha256=hrwcKrDfqgQ1Lia0GVcaXKtw48f1kyR89Fq4uyETClc,14329
|
|
4
|
+
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
5
|
+
model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
|
|
6
|
+
model2vec/version.py,sha256=ZYpHTj-x0fED3Zyiud-IRadvSU8eJO098rh78NyEd_A,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.5.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
+
model2vec-0.3.5.dist-info/METADATA,sha256=Fz9dR7n6kp64g2sqcDuX1kVq4dEn7Code9siNT5y__4,26138
|
|
14
|
+
model2vec-0.3.5.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
15
|
+
model2vec-0.3.5.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
+
model2vec-0.3.5.dist-info/RECORD,,
|
model2vec-0.3.3.dist-info/RECORD
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
|
|
2
|
-
model2vec/hf_utils.py,sha256=Z-_V2kYagBX7m9_--e2ZAGP4irfRpqIlBQgGwYswpoU,7772
|
|
3
|
-
model2vec/model.py,sha256=DuzsHaTBf0fTsp0ovVPzFs3EzDqGnFd5bGC94vumYuU,12031
|
|
4
|
-
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
5
|
-
model2vec/utils.py,sha256=AyKPu7w7XO2DhJEBN8NrO53vZj5rZpbwWJNxjagCKIk,2684
|
|
6
|
-
model2vec/version.py,sha256=azyH_mT8eRQuggt3kh7T7FSoYvfnwcLHjURqaYWVK0Q,84
|
|
7
|
-
model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
|
|
8
|
-
model2vec/distill/distillation.py,sha256=yDdIW4nqR5Vw4cUYL4p7hrJnIzZWO9fV9LiqZHe_z8s,11504
|
|
9
|
-
model2vec/distill/inference.py,sha256=QgHAEkLoeq-jPyKnFTB6p6Ry-ZGZqonkZaEg2S7VTOY,6123
|
|
10
|
-
model2vec/distill/tokenizer.py,sha256=xtVsMTxquqTufoP9z39C4Itg2LLcGViqeguz-M7y-u8,4293
|
|
11
|
-
model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
|
|
12
|
-
model2vec-0.3.3.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
-
model2vec-0.3.3.dist-info/METADATA,sha256=1kDQ4KrbGMom8ZKMx3b0DJ4XpUcJtkQsAmdEfZWPd0o,25800
|
|
14
|
-
model2vec-0.3.3.dist-info/WHEEL,sha256=R06PA3UVYHThwHvxuRWMqaGcr-PuniXahwjmQRFMEkY,91
|
|
15
|
-
model2vec-0.3.3.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
-
model2vec-0.3.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|