model2vec 0.3.2__py3-none-any.whl → 0.3.4__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 +41 -11
- model2vec/distill/tokenizer.py +4 -2
- model2vec/model.py +58 -19
- model2vec/utils.py +42 -2
- model2vec/version.py +1 -1
- {model2vec-0.3.2.dist-info → model2vec-0.3.4.dist-info}/METADATA +269 -144
- model2vec-0.3.4.dist-info/RECORD +16 -0
- {model2vec-0.3.2.dist-info → model2vec-0.3.4.dist-info}/WHEEL +1 -1
- model2vec-0.3.2.dist-info/RECORD +0 -16
- {model2vec-0.3.2.dist-info → model2vec-0.3.4.dist-info}/LICENSE +0 -0
- {model2vec-0.3.2.dist-info → model2vec-0.3.4.dist-info}/top_level.txt +0 -0
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
+
import re
|
|
4
5
|
from typing import Literal, Union
|
|
5
6
|
|
|
6
7
|
import numpy as np
|
|
7
8
|
from huggingface_hub import model_info
|
|
8
9
|
from sklearn.decomposition import PCA
|
|
10
|
+
from tokenizers import Tokenizer
|
|
9
11
|
from tokenizers.models import BPE, Unigram
|
|
10
12
|
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
11
13
|
|
|
@@ -39,6 +41,7 @@ def distill_from_model(
|
|
|
39
41
|
pca_dims: PCADimType = 256,
|
|
40
42
|
apply_zipf: bool = True,
|
|
41
43
|
use_subword: bool = True,
|
|
44
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
42
45
|
) -> StaticModel:
|
|
43
46
|
"""
|
|
44
47
|
Distill a staticmodel from a sentence transformer.
|
|
@@ -58,8 +61,12 @@ def distill_from_model(
|
|
|
58
61
|
If this is 'auto', we don't reduce dimensionality, but still apply PCA.
|
|
59
62
|
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
60
63
|
: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.
|
|
64
|
+
: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.
|
|
65
|
+
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
66
|
:raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
|
|
62
67
|
:raises: ValueError if the vocabulary contains duplicate tokens.
|
|
68
|
+
:raises: ValueError if the regex can't be compiled.
|
|
69
|
+
:raises: ValueError if the vocabulary is empty after token removal.
|
|
63
70
|
:return: A StaticModel
|
|
64
71
|
|
|
65
72
|
"""
|
|
@@ -81,17 +88,7 @@ def distill_from_model(
|
|
|
81
88
|
if use_subword:
|
|
82
89
|
# Create the subword embeddings.
|
|
83
90
|
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.")
|
|
91
|
+
new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
|
|
95
92
|
else:
|
|
96
93
|
# We need to keep the unk token in the tokenizer.
|
|
97
94
|
unk_token = tokenizer.backend_tokenizer.model.unk_token
|
|
@@ -136,6 +133,8 @@ def distill_from_model(
|
|
|
136
133
|
model_name = getattr(model, "name_or_path", "")
|
|
137
134
|
|
|
138
135
|
config = {
|
|
136
|
+
"model_type": "model2vec",
|
|
137
|
+
"architectures": ["StaticModel"],
|
|
139
138
|
"tokenizer_name": model_name,
|
|
140
139
|
"apply_pca": pca_dims,
|
|
141
140
|
"apply_zipf": apply_zipf,
|
|
@@ -155,6 +154,37 @@ def distill_from_model(
|
|
|
155
154
|
)
|
|
156
155
|
|
|
157
156
|
|
|
157
|
+
def _remove_tokens_and_embeddings(
|
|
158
|
+
tokenizer: PreTrainedTokenizerFast, token_remove_pattern: str | None, tokens: list[str], embeddings: np.ndarray
|
|
159
|
+
) -> tuple[Tokenizer, np.ndarray]:
|
|
160
|
+
if not token_remove_pattern:
|
|
161
|
+
return tokenizer.backend_tokenizer, embeddings
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
token_regex = re.compile(token_remove_pattern)
|
|
165
|
+
except re.error as e:
|
|
166
|
+
raise ValueError(f"Invalid regex pattern: {token_remove_pattern}") from e
|
|
167
|
+
# Remove any unused tokens from the tokenizer and embeddings.
|
|
168
|
+
wrong_tokens = [x for x in tokens if token_regex.match(x)]
|
|
169
|
+
vocab = tokenizer.get_vocab()
|
|
170
|
+
# Get the ids of the unused token.
|
|
171
|
+
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
172
|
+
|
|
173
|
+
if len(wrong_token_ids) == len(vocab):
|
|
174
|
+
raise ValueError(
|
|
175
|
+
"All tokens in the vocabulary are unused tokens. This will result in an empty tokenizer. "
|
|
176
|
+
"Please provide a valid token removal pattern. The pattern is now: {token_remove_pattern}"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# Remove the unused tokens from the tokenizer.
|
|
180
|
+
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
|
|
181
|
+
# Remove the embeddings of the unused tokens.
|
|
182
|
+
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
183
|
+
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
184
|
+
|
|
185
|
+
return new_tokenizer, embeddings
|
|
186
|
+
|
|
187
|
+
|
|
158
188
|
def distill(
|
|
159
189
|
model_name: str,
|
|
160
190
|
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, 4)
|
|
2
2
|
__version__ = ".".join(map(str, __version_triple__))
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.3.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.3.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
|
|
7
7
|
|
|
@@ -43,24 +43,29 @@ Classifier: Natural Language :: English
|
|
|
43
43
|
Requires-Python: >=3.9
|
|
44
44
|
Description-Content-Type: text/markdown
|
|
45
45
|
License-File: LICENSE
|
|
46
|
+
Requires-Dist: jinja2
|
|
47
|
+
Requires-Dist: joblib
|
|
46
48
|
Requires-Dist: numpy
|
|
47
49
|
Requires-Dist: rich
|
|
48
|
-
Requires-Dist: tqdm
|
|
49
|
-
Requires-Dist: tokenizers >=0.20
|
|
50
50
|
Requires-Dist: safetensors
|
|
51
51
|
Requires-Dist: setuptools
|
|
52
|
+
Requires-Dist: tokenizers>=0.20
|
|
53
|
+
Requires-Dist: tqdm
|
|
52
54
|
Provides-Extra: dev
|
|
53
|
-
Requires-Dist: black
|
|
54
|
-
Requires-Dist: ipython
|
|
55
|
-
Requires-Dist: mypy
|
|
56
|
-
Requires-Dist: pre-commit
|
|
57
|
-
Requires-Dist: pytest
|
|
58
|
-
Requires-Dist: pytest-
|
|
59
|
-
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"
|
|
60
62
|
Provides-Extra: distill
|
|
61
|
-
Requires-Dist: torch
|
|
62
|
-
Requires-Dist: transformers
|
|
63
|
-
Requires-Dist: scikit-learn
|
|
63
|
+
Requires-Dist: torch; extra == "distill"
|
|
64
|
+
Requires-Dist: transformers; extra == "distill"
|
|
65
|
+
Requires-Dist: scikit-learn; extra == "distill"
|
|
66
|
+
Provides-Extra: onnx
|
|
67
|
+
Requires-Dist: onnx; extra == "onnx"
|
|
68
|
+
Requires-Dist: torch; extra == "onnx"
|
|
64
69
|
|
|
65
70
|
|
|
66
71
|
<div align="center">
|
|
@@ -71,14 +76,14 @@ Requires-Dist: scikit-learn ; extra == 'distill'
|
|
|
71
76
|
</div>
|
|
72
77
|
|
|
73
78
|
<div align="center">
|
|
74
|
-
<h2>
|
|
79
|
+
<h2>The Fastest State-of-the-Art Static Embeddings in the World</h2>
|
|
75
80
|
</div>
|
|
76
81
|
|
|
77
82
|
<div align="center">
|
|
78
83
|
<h2>
|
|
79
84
|
<a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
|
|
80
85
|
<a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
|
|
81
|
-
<a href="https://
|
|
86
|
+
<a href="https://minishlab.github.io/"><strong>🌐 Website</strong></a> |
|
|
82
87
|
<a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a>
|
|
83
88
|
</h2>
|
|
84
89
|
</div>
|
|
@@ -103,7 +108,7 @@ Requires-Dist: scikit-learn ; extra == 'distill'
|
|
|
103
108
|
<img src="assets/images/model2vec_model_diagram_transparant_light.png#gh-light-mode-only" width="90%">
|
|
104
109
|
</div>
|
|
105
110
|
|
|
106
|
-
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. See our results [here](results/README.md), or dive in to see how it works.
|
|
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-8M) is the most performant static embedding model in the world. See our results [here](results/README.md), or dive in to see how it works.
|
|
107
112
|
|
|
108
113
|
|
|
109
114
|
## Updates & Announcements
|
|
@@ -115,34 +120,33 @@ Model2Vec is a technique to turn any sentence transformer into a really small st
|
|
|
115
120
|
- [Main Features](#main-features)
|
|
116
121
|
- [What is Model2Vec?](#what-is-model2vec)
|
|
117
122
|
- [Usage](#usage)
|
|
118
|
-
- [Distillation](#distillation)
|
|
119
123
|
- [Inference](#inference)
|
|
124
|
+
- [Distillation](#distillation)
|
|
120
125
|
- [Evaluation](#evaluation)
|
|
126
|
+
- [Integrations](#integrations)
|
|
121
127
|
- [Model List](#model-list)
|
|
122
128
|
- [Results](#results)
|
|
123
|
-
- [Related Work](#related-work)
|
|
124
|
-
- [Citing](#citing)
|
|
125
129
|
|
|
126
130
|
## Quickstart
|
|
127
131
|
|
|
128
|
-
Install the package
|
|
132
|
+
Install the package with:
|
|
133
|
+
|
|
129
134
|
```bash
|
|
130
|
-
pip install model2vec
|
|
135
|
+
pip install model2vec
|
|
131
136
|
```
|
|
132
137
|
|
|
133
|
-
|
|
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:
|
|
134
139
|
|
|
135
140
|
```bash
|
|
136
|
-
pip install model2vec
|
|
141
|
+
pip install model2vec[distill]
|
|
137
142
|
```
|
|
138
143
|
|
|
139
|
-
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:
|
|
140
145
|
```python
|
|
141
146
|
from model2vec import StaticModel
|
|
142
147
|
|
|
143
148
|
# Load a model from the HuggingFace hub (in this case the potion-base-8M model)
|
|
144
|
-
|
|
145
|
-
model = StaticModel.from_pretrained(model_name)
|
|
149
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
146
150
|
|
|
147
151
|
# Make embeddings
|
|
148
152
|
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
@@ -153,82 +157,89 @@ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It'
|
|
|
153
157
|
|
|
154
158
|
And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
|
|
155
159
|
|
|
156
|
-
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:
|
|
157
161
|
```python
|
|
158
162
|
from model2vec.distill import distill
|
|
159
163
|
|
|
160
|
-
#
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
# Distill the model
|
|
164
|
-
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)
|
|
165
166
|
|
|
166
167
|
# Save the model
|
|
167
168
|
m2v_model.save_pretrained("m2v_model")
|
|
168
169
|
```
|
|
169
170
|
|
|
170
|
-
Distillation is really fast
|
|
171
|
-
|
|
172
|
-
You can also directly use Model2Vec in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) using the [StaticEmbedding](https://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/models/StaticEmbedding.py) module. You can either load a Model2Vec model into a Sentence Transformer with the following code snippet:
|
|
173
|
-
```python
|
|
174
|
-
from sentence_transformers import SentenceTransformer
|
|
175
|
-
from sentence_transformers.models import StaticEmbedding
|
|
176
|
-
|
|
177
|
-
# Initialize a StaticEmbedding module
|
|
178
|
-
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
179
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
180
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
181
|
-
```
|
|
171
|
+
Distillation is really fast and only takes 30 seconds on CPU. Best of all, distillation requires no training data.
|
|
182
172
|
|
|
183
|
-
|
|
184
|
-
```python
|
|
185
|
-
from sentence_transformers import SentenceTransformer
|
|
186
|
-
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.
|
|
187
174
|
|
|
188
|
-
static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cpu", pca_dims=256)
|
|
189
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
190
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
191
|
-
```
|
|
192
|
-
For more documentation, please refer to the [Sentence Transformers documentation](https://sbert.net/docs/package_reference/sentence_transformer/models.html#sentence_transformers.models.StaticEmbedding).
|
|
193
175
|
|
|
194
176
|
## Main Features
|
|
195
177
|
|
|
196
|
-
Model2Vec
|
|
197
|
-
|
|
198
|
-
- **
|
|
199
|
-
- **
|
|
200
|
-
- **Fast
|
|
201
|
-
- **
|
|
202
|
-
- **No data needed**: Distillation happens directly on the token level, so no dataset is needed.
|
|
203
|
-
- **Simple to use**: An easy to use interface for distilling and inferencing.
|
|
204
|
-
- **Integrated into Sentence Transformers**: Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers).
|
|
205
|
-
- **Bring your own model**: Can be applied to any Sentence Transformer model.
|
|
206
|
-
- **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.
|
|
207
|
-
- **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.
|
|
208
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.
|
|
209
|
-
- **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).
|
|
210
185
|
|
|
211
186
|
## What is Model2Vec?
|
|
212
187
|
|
|
213
|
-
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.
|
|
189
|
+
|
|
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.
|
|
214
191
|
|
|
215
|
-
|
|
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.
|
|
216
197
|
|
|
217
|
-
Model2vec has 3 modes:
|
|
218
|
-
- **Output**: behaves much like a real sentence transformer, i.e., it uses a subword tokenizer and simply encodes all wordpieces in its vocab. This is really quick to create (30 seconds on a CPU), very small (30 MB in float32), but might be less performant on some tasks.
|
|
219
|
-
- **Vocab (word level)**: creates a word-level tokenizer and only encodes words that are in the vocabulary. This is a bit slower to create and creates a larger model, but might be more performant on some tasks. Note that this model can go out-of-vocabulary, which might be beneficial if your domain is very noisy
|
|
220
|
-
- **Vocab (subword)**: a combination of the two methods above. In this mode, you can pass your own vocabulary, but it also uses the subword vocabulary to create representations for words not in the passed vocabulary.
|
|
221
198
|
|
|
222
|
-
For a
|
|
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/).
|
|
223
200
|
|
|
224
|
-
|
|
201
|
+
## Usage
|
|
225
202
|
|
|
226
|
-
|
|
203
|
+
### Inference
|
|
227
204
|
|
|
205
|
+
<details>
|
|
206
|
+
<summary> Inference with a pretrained model </summary>
|
|
207
|
+
<br>
|
|
228
208
|
|
|
229
|
-
|
|
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>
|
|
230
223
|
|
|
231
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
|
+
|
|
232
243
|
### Distillation
|
|
233
244
|
|
|
234
245
|
<details>
|
|
@@ -239,11 +250,8 @@ The following code can be used to distill a model from a Sentence Transformer. A
|
|
|
239
250
|
```python
|
|
240
251
|
from model2vec.distill import distill
|
|
241
252
|
|
|
242
|
-
#
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
# Distill the model
|
|
246
|
-
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)
|
|
247
255
|
|
|
248
256
|
# Save the model
|
|
249
257
|
m2v_model.save_pretrained("m2v_model")
|
|
@@ -303,11 +311,9 @@ from model2vec.distill import distill
|
|
|
303
311
|
|
|
304
312
|
# Load a vocabulary as a list of strings
|
|
305
313
|
vocabulary = ["word1", "word2", "word3"]
|
|
306
|
-
# Choose a Sentence Transformer model
|
|
307
|
-
model_name = "BAAI/bge-base-en-v1.5"
|
|
308
314
|
|
|
309
|
-
# Distill
|
|
310
|
-
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)
|
|
311
317
|
|
|
312
318
|
# Save the model
|
|
313
319
|
m2v_model.save_pretrained("m2v_model")
|
|
@@ -326,48 +332,6 @@ m2v_model = distill(model_name=model_name, vocabulary=vocabulary, use_subword=Fa
|
|
|
326
332
|
|
|
327
333
|
</details>
|
|
328
334
|
|
|
329
|
-
### Inference
|
|
330
|
-
|
|
331
|
-
<details>
|
|
332
|
-
<summary> Inference using pretrained model </summary>
|
|
333
|
-
<br>
|
|
334
|
-
|
|
335
|
-
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.
|
|
336
|
-
```python
|
|
337
|
-
from model2vec import StaticModel
|
|
338
|
-
|
|
339
|
-
# Load a model from the HuggingFace hub, or a local one.
|
|
340
|
-
model_name = "minishlab/potion-base-8M"
|
|
341
|
-
# You can optionally pass a token if you're loading a private model
|
|
342
|
-
model = StaticModel.from_pretrained(model_name, token=None)
|
|
343
|
-
|
|
344
|
-
# Make embeddings
|
|
345
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
346
|
-
|
|
347
|
-
# Make sequences of token embeddings
|
|
348
|
-
token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
349
|
-
```
|
|
350
|
-
</details>
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
<details>
|
|
354
|
-
<summary> Inference using the Sentence Transformers library </summary>
|
|
355
|
-
<br>
|
|
356
|
-
|
|
357
|
-
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.
|
|
358
|
-
|
|
359
|
-
```python
|
|
360
|
-
from sentence_transformers import SentenceTransformer
|
|
361
|
-
from sentence_transformers.models import StaticEmbedding
|
|
362
|
-
|
|
363
|
-
# Initialize a StaticEmbedding module
|
|
364
|
-
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
365
|
-
model = SentenceTransformer(modules=[static_embedding])
|
|
366
|
-
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
367
|
-
```
|
|
368
|
-
|
|
369
|
-
</details>
|
|
370
|
-
|
|
371
335
|
|
|
372
336
|
### Evaluation
|
|
373
337
|
|
|
@@ -420,17 +384,187 @@ print(make_leaderboard(task_scores))
|
|
|
420
384
|
```
|
|
421
385
|
</details>
|
|
422
386
|
|
|
387
|
+
## Integrations
|
|
388
|
+
<details>
|
|
389
|
+
<summary> Sentence Transformers </summary>
|
|
390
|
+
<a name="sentence-transformers"></a>
|
|
391
|
+
<br>
|
|
392
|
+
|
|
393
|
+
Model2Vec can be used directly in [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) using the `StaticEmbedding` module.
|
|
394
|
+
|
|
395
|
+
The following code snippet shows how to load a Model2Vec model into a Sentence Transformer model:
|
|
396
|
+
```python
|
|
397
|
+
from sentence_transformers import SentenceTransformer
|
|
398
|
+
from sentence_transformers.models import StaticEmbedding
|
|
399
|
+
|
|
400
|
+
# Initialize a StaticEmbedding module
|
|
401
|
+
static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
|
|
402
|
+
model = SentenceTransformer(modules=[static_embedding])
|
|
403
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
The following code snippet shows how to distill a model directly into a Sentence Transformer model:
|
|
407
|
+
|
|
408
|
+
```python
|
|
409
|
+
from sentence_transformers import SentenceTransformer
|
|
410
|
+
from sentence_transformers.models import StaticEmbedding
|
|
411
|
+
|
|
412
|
+
static_embedding = StaticEmbedding.from_distillation("BAAI/bge-base-en-v1.5", device="cpu", pca_dims=256)
|
|
413
|
+
model = SentenceTransformer(modules=[static_embedding])
|
|
414
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
415
|
+
```
|
|
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
|
+
|
|
419
|
+
</details>
|
|
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>
|
|
455
|
+
|
|
456
|
+
<details>
|
|
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."
|
|
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>
|
|
508
|
+
<br>
|
|
509
|
+
|
|
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:
|
|
511
|
+
|
|
512
|
+
```javascript
|
|
513
|
+
import { AutoModel, AutoTokenizer, Tensor } from '@huggingface/transformers';
|
|
514
|
+
|
|
515
|
+
const modelName = 'minishlab/potion-base-8M';
|
|
516
|
+
|
|
517
|
+
const modelConfig = {
|
|
518
|
+
config: { model_type: 'model2vec' },
|
|
519
|
+
dtype: 'fp32',
|
|
520
|
+
revision: 'refs/pr/1'
|
|
521
|
+
};
|
|
522
|
+
const tokenizerConfig = {
|
|
523
|
+
revision: 'refs/pr/2'
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
const model = await AutoModel.from_pretrained(modelName, modelConfig);
|
|
527
|
+
const tokenizer = await AutoTokenizer.from_pretrained(modelName, tokenizerConfig);
|
|
528
|
+
|
|
529
|
+
const texts = ['hello', 'hello world'];
|
|
530
|
+
const { input_ids } = await tokenizer(texts, { add_special_tokens: false, return_tensor: false });
|
|
531
|
+
|
|
532
|
+
const cumsum = arr => arr.reduce((acc, num, i) => [...acc, num + (acc[i - 1] || 0)], []);
|
|
533
|
+
const offsets = [0, ...cumsum(input_ids.slice(0, -1).map(x => x.length))];
|
|
534
|
+
|
|
535
|
+
const flattened_input_ids = input_ids.flat();
|
|
536
|
+
const modelInputs = {
|
|
537
|
+
input_ids: new Tensor('int64', flattened_input_ids, [flattened_input_ids.length]),
|
|
538
|
+
offsets: new Tensor('int64', offsets, [offsets.length])
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const { embeddings } = await model(modelInputs);
|
|
542
|
+
console.log(embeddings.tolist()); // output matches python version
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
Note that this requires that the Model2Vec has a `model.onnx` file and several required tokenizers file. To generate these for a model that does not have them yet, the following code snippet can be used:
|
|
546
|
+
|
|
547
|
+
```bash
|
|
548
|
+
python scripts/export_to_onnx.py --model_path <path-to-a-model2vec-model> --save_path "<path-to-save-the-onnx-model>"
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
<br>
|
|
553
|
+
</details>
|
|
554
|
+
|
|
555
|
+
|
|
423
556
|
## Model List
|
|
424
557
|
|
|
425
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.
|
|
426
559
|
|
|
427
560
|
|
|
428
|
-
| Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn
|
|
429
|
-
|
|
430
|
-
| [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 |
|
|
431
|
-
| [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
|
|
432
|
-
| [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
|
|
433
|
-
| [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
|
+
|
|
434
568
|
|
|
435
569
|
|
|
436
570
|
## Results
|
|
@@ -439,15 +573,6 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
|
|
|
439
573
|
- [MTEB Results](results/README.md#mteb-results)
|
|
440
574
|
- [Ablations](results/README.md#ablations)
|
|
441
575
|
|
|
442
|
-
## Related work
|
|
443
|
-
|
|
444
|
-
If you are interested in fast small models, also consider looking at these techniques:
|
|
445
|
-
* [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.
|
|
446
|
-
* [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.
|
|
447
|
-
* [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.
|
|
448
|
-
|
|
449
|
-
If you find other related work, please let us know.
|
|
450
|
-
|
|
451
576
|
## License
|
|
452
577
|
|
|
453
578
|
MIT
|
|
@@ -458,7 +583,7 @@ If you use Model2Vec in your research, please cite the following:
|
|
|
458
583
|
```bibtex
|
|
459
584
|
@software{minishlab2024model2vec,
|
|
460
585
|
authors = {Stephan Tulkens, Thomas van Dongen},
|
|
461
|
-
title = {Model2Vec:
|
|
586
|
+
title = {Model2Vec: The Fastest State-of-the-Art Static Embeddings in the World},
|
|
462
587
|
year = {2024},
|
|
463
588
|
url = {https://github.com/MinishLab/model2vec},
|
|
464
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=ZB6JPUJBX9JjQe38as-mWtqpIbHFqsGv8vGE1TxfnZ0,84
|
|
7
|
+
model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
|
|
8
|
+
model2vec/distill/distillation.py,sha256=g51y-h7S6BgXHfZ-q841D5mbuiCzRwwRaPJjf6hpCoU,13001
|
|
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.4.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
+
model2vec-0.3.4.dist-info/METADATA,sha256=WbAWLb53Fyl5qIgx-KUiTrCfQNCPuH9m0yBIqVjusvU,26138
|
|
14
|
+
model2vec-0.3.4.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
|
15
|
+
model2vec-0.3.4.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
+
model2vec-0.3.4.dist-info/RECORD,,
|
model2vec-0.3.2.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=YUIpQDxUrCbh0vtQtU7z3qcWjcuAHAhcRI706SxPcGw,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.2.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
13
|
-
model2vec-0.3.2.dist-info/METADATA,sha256=mMDSZ9I2XhHGnXZhzO0TUtwuerJL3zD_yeVtjRp4clc,22641
|
|
14
|
-
model2vec-0.3.2.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
|
15
|
-
model2vec-0.3.2.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
16
|
-
model2vec-0.3.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|