model2vec 0.2.1__py3-none-any.whl → 0.2.2__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/__init__.py +2 -2
- model2vec/distill/distillation.py +87 -27
- model2vec/distill/inference.py +18 -2
- model2vec/distill/tokenizer.py +52 -17
- model2vec/distill/utils.py +26 -0
- {model2vec-0.2.1.dist-info → model2vec-0.2.2.dist-info}/METADATA +45 -21
- model2vec-0.2.2.dist-info/RECORD +15 -0
- model2vec-0.2.1.dist-info/RECORD +0 -14
- {model2vec-0.2.1.dist-info → model2vec-0.2.2.dist-info}/LICENSE +0 -0
- {model2vec-0.2.1.dist-info → model2vec-0.2.2.dist-info}/WHEEL +0 -0
- {model2vec-0.2.1.dist-info → model2vec-0.2.2.dist-info}/top_level.txt +0 -0
model2vec/distill/__init__.py
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
from model2vec.distill.
|
|
1
|
+
from model2vec.distill.distillation import distill, distill_from_model
|
|
2
2
|
|
|
3
|
-
__all__ = ["distill"]
|
|
3
|
+
__all__ = ["distill", "distill_from_model"]
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import logging
|
|
2
|
+
from typing import Literal
|
|
2
3
|
|
|
3
4
|
import numpy as np
|
|
4
5
|
from huggingface_hub import model_info
|
|
5
6
|
from sklearn.decomposition import PCA
|
|
7
|
+
from tokenizers.models import BPE, Unigram
|
|
6
8
|
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
7
9
|
|
|
8
10
|
from model2vec.distill.inference import (
|
|
@@ -10,16 +12,21 @@ from model2vec.distill.inference import (
|
|
|
10
12
|
create_output_embeddings_from_model_name_and_tokens,
|
|
11
13
|
)
|
|
12
14
|
from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
|
|
15
|
+
from model2vec.distill.utils import select_optimal_device
|
|
13
16
|
from model2vec.model import StaticModel
|
|
14
17
|
|
|
15
18
|
logger = logging.getLogger(__name__)
|
|
16
19
|
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
PCADimType = int | None | Literal["auto"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def distill_from_model(
|
|
25
|
+
model: PreTrainedModel,
|
|
26
|
+
tokenizer: PreTrainedTokenizerFast,
|
|
20
27
|
vocabulary: list[str] | None = None,
|
|
21
|
-
device: str =
|
|
22
|
-
pca_dims:
|
|
28
|
+
device: str | None = None,
|
|
29
|
+
pca_dims: PCADimType = 256,
|
|
23
30
|
apply_zipf: bool = True,
|
|
24
31
|
use_subword: bool = True,
|
|
25
32
|
) -> StaticModel:
|
|
@@ -32,10 +39,13 @@ def distill(
|
|
|
32
39
|
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
33
40
|
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
34
41
|
|
|
35
|
-
:param
|
|
42
|
+
:param model: The model to use.
|
|
43
|
+
:param tokenizer: The tokenizer to use.
|
|
36
44
|
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
37
45
|
:param device: The device to use.
|
|
38
|
-
:param pca_dims: The number of components to use for PCA.
|
|
46
|
+
:param pca_dims: The number of components to use for PCA.
|
|
47
|
+
If this is None, we don't apply PCA.
|
|
48
|
+
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
39
49
|
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
40
50
|
: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.
|
|
41
51
|
:raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
|
|
@@ -43,45 +53,46 @@ def distill(
|
|
|
43
53
|
:return: A StaticModel
|
|
44
54
|
|
|
45
55
|
"""
|
|
56
|
+
device = select_optimal_device(device)
|
|
46
57
|
if not use_subword and vocabulary is None:
|
|
47
58
|
raise ValueError(
|
|
48
59
|
"You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
|
|
49
60
|
)
|
|
50
61
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
|
|
65
|
+
"This is not supported yet."
|
|
66
|
+
"Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
|
|
67
|
+
)
|
|
68
|
+
|
|
54
69
|
# Make a base list of tokens.
|
|
55
70
|
tokens: list[str] = []
|
|
56
71
|
if use_subword:
|
|
57
72
|
# Create the subword embeddings.
|
|
58
|
-
tokens, embeddings = create_output_embeddings_from_model_name(
|
|
59
|
-
model=original_model, tokenizer=original_tokenizer, device=device
|
|
60
|
-
)
|
|
73
|
+
tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
|
|
61
74
|
|
|
62
75
|
# Remove any unused tokens from the tokenizer and embeddings.
|
|
63
76
|
wrong_tokens = [x for x in tokens if x.startswith("[unused")]
|
|
64
|
-
vocab =
|
|
77
|
+
vocab = tokenizer.get_vocab()
|
|
65
78
|
# Get the ids of the unused token.
|
|
66
79
|
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
67
80
|
# Remove the unused tokens from the tokenizer.
|
|
68
|
-
new_tokenizer = remove_tokens(
|
|
81
|
+
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
|
|
69
82
|
# Remove the embeddings of the unused tokens.
|
|
70
83
|
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
71
84
|
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
72
85
|
else:
|
|
73
86
|
# We need to keep the unk token in the tokenizer.
|
|
74
|
-
unk_token =
|
|
87
|
+
unk_token = tokenizer.backend_tokenizer.model.unk_token
|
|
75
88
|
# Remove all tokens except the UNK token.
|
|
76
|
-
new_tokenizer = remove_tokens(
|
|
77
|
-
original_tokenizer.backend_tokenizer, list(set(original_tokenizer.get_vocab()) - {unk_token})
|
|
78
|
-
)
|
|
89
|
+
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, list(set(tokenizer.get_vocab()) - {unk_token}))
|
|
79
90
|
# We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
|
|
80
91
|
embeddings = None
|
|
81
92
|
|
|
82
|
-
if vocabulary
|
|
93
|
+
if vocabulary:
|
|
83
94
|
# Preprocess the vocabulary with the original tokenizer.
|
|
84
|
-
preprocessed_vocabulary = preprocess_vocabulary(
|
|
95
|
+
preprocessed_vocabulary = preprocess_vocabulary(tokenizer.backend_tokenizer, vocabulary)
|
|
85
96
|
n_tokens_before = len(preprocessed_vocabulary)
|
|
86
97
|
# Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
|
|
87
98
|
cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
|
|
@@ -93,8 +104,8 @@ def distill(
|
|
|
93
104
|
if cleaned_vocabulary:
|
|
94
105
|
# Create the embeddings.
|
|
95
106
|
_, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
|
|
96
|
-
model=
|
|
97
|
-
tokenizer=
|
|
107
|
+
model=model,
|
|
108
|
+
tokenizer=tokenizer,
|
|
98
109
|
tokens=cleaned_vocabulary,
|
|
99
110
|
device=device,
|
|
100
111
|
)
|
|
@@ -112,6 +123,8 @@ def distill(
|
|
|
112
123
|
# Post process the embeddings by applying PCA and Zipf weighting.
|
|
113
124
|
embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
|
|
114
125
|
|
|
126
|
+
model_name = getattr(model, "name_or_path", "")
|
|
127
|
+
|
|
115
128
|
config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
|
|
116
129
|
# Get the language from the model card
|
|
117
130
|
info = model_info(model_name)
|
|
@@ -122,18 +135,65 @@ def distill(
|
|
|
122
135
|
)
|
|
123
136
|
|
|
124
137
|
|
|
125
|
-
def
|
|
138
|
+
def distill(
|
|
139
|
+
model_name: str,
|
|
140
|
+
vocabulary: list[str] | None = None,
|
|
141
|
+
device: str | None = None,
|
|
142
|
+
pca_dims: PCADimType = 256,
|
|
143
|
+
apply_zipf: bool = True,
|
|
144
|
+
use_subword: bool = True,
|
|
145
|
+
) -> StaticModel:
|
|
146
|
+
"""
|
|
147
|
+
Distill a staticmodel from a sentence transformer.
|
|
148
|
+
|
|
149
|
+
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
150
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
|
|
151
|
+
|
|
152
|
+
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
153
|
+
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
154
|
+
|
|
155
|
+
:param model_name: The model name to use. Any sentencetransformer compatible model works.
|
|
156
|
+
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
157
|
+
:param device: The device to use.
|
|
158
|
+
:param pca_dims: The number of components to use for PCA.
|
|
159
|
+
If this is None, we don't apply PCA.
|
|
160
|
+
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
161
|
+
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
162
|
+
: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.
|
|
163
|
+
:return: A StaticModel
|
|
164
|
+
|
|
165
|
+
"""
|
|
166
|
+
model: PreTrainedModel = AutoModel.from_pretrained(model_name)
|
|
167
|
+
tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
|
|
168
|
+
|
|
169
|
+
return distill_from_model(
|
|
170
|
+
model=model,
|
|
171
|
+
tokenizer=tokenizer,
|
|
172
|
+
vocabulary=vocabulary,
|
|
173
|
+
device=device,
|
|
174
|
+
pca_dims=pca_dims,
|
|
175
|
+
apply_zipf=apply_zipf,
|
|
176
|
+
use_subword=use_subword,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
|
|
126
181
|
"""Post process embeddings by applying PCA and Zipf weighting."""
|
|
127
182
|
if pca_dims is not None:
|
|
128
|
-
if pca_dims
|
|
129
|
-
|
|
130
|
-
|
|
183
|
+
if pca_dims == "auto":
|
|
184
|
+
pca_dims = embeddings.shape[1]
|
|
185
|
+
if pca_dims > embeddings.shape[1]:
|
|
186
|
+
logger.warning(
|
|
187
|
+
f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
|
|
188
|
+
"Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
|
|
189
|
+
"Applying PCA will probably improve performance, so consider just leaving it."
|
|
131
190
|
)
|
|
191
|
+
pca_dims = embeddings.shape[1]
|
|
132
192
|
if pca_dims >= embeddings.shape[0]:
|
|
133
193
|
logger.warning(
|
|
134
194
|
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
|
|
135
195
|
)
|
|
136
|
-
elif pca_dims
|
|
196
|
+
elif pca_dims <= embeddings.shape[1]:
|
|
137
197
|
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
138
198
|
|
|
139
199
|
p = PCA(n_components=pca_dims, whiten=False)
|
model2vec/distill/inference.py
CHANGED
|
@@ -67,7 +67,12 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
|
|
|
67
67
|
"""
|
|
68
68
|
encodings = tokenizer(tokens, return_tensors="pt", padding=True, truncation=True).to(model.device)
|
|
69
69
|
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
|
|
70
|
-
out = encoded.last_hidden_state.cpu()
|
|
70
|
+
out: torch.Tensor = encoded.last_hidden_state.cpu()
|
|
71
|
+
# NOTE: If the dtype is bfloat 16, we convert to float32,
|
|
72
|
+
# because numpy does not suport bfloat16
|
|
73
|
+
# See here: https://github.com/numpy/numpy/issues/19808
|
|
74
|
+
if out.dtype == torch.bfloat16:
|
|
75
|
+
out = out.float()
|
|
71
76
|
|
|
72
77
|
mask = encodings["attention_mask"].cpu()
|
|
73
78
|
# NOTE: evil hack. For any batch, there will be a mask vector
|
|
@@ -122,8 +127,19 @@ def create_output_embeddings_from_model_name(
|
|
|
122
127
|
for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
|
|
123
128
|
batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
|
|
124
129
|
with torch.no_grad():
|
|
125
|
-
|
|
130
|
+
# NOTE: we create these masks because nomic embed requires them.
|
|
131
|
+
# Normally, we could set them to None
|
|
132
|
+
token_type_ids = torch.zeros_like(batch)
|
|
133
|
+
attention_mask = torch.ones_like(batch)
|
|
134
|
+
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(
|
|
135
|
+
input_ids=batch.to(device), attention_mask=attention_mask, token_type_ids=token_type_ids
|
|
136
|
+
)
|
|
126
137
|
out: torch.Tensor = encoded.last_hidden_state
|
|
138
|
+
# NOTE: If the dtype is bfloat 16, we convert to float32,
|
|
139
|
+
# because numpy does not suport bfloat16
|
|
140
|
+
# See here: https://github.com/numpy/numpy/issues/19808
|
|
141
|
+
if out.dtype == torch.bfloat16:
|
|
142
|
+
out = out.float()
|
|
127
143
|
intermediate_weights.append(out[:, 1].cpu().numpy())
|
|
128
144
|
out_weights = np.concatenate(intermediate_weights)
|
|
129
145
|
|
model2vec/distill/tokenizer.py
CHANGED
|
@@ -23,7 +23,19 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
|
|
|
23
23
|
:param tokenizer: The tokenizer to remove tokens from.
|
|
24
24
|
:param tokens_to_remove: The tokens to remove.
|
|
25
25
|
:return: The modified tokenizer.
|
|
26
|
+
:raises ValueError: If the tokenizer model type is not supported.
|
|
26
27
|
"""
|
|
28
|
+
model_vocab = set(tokenizer.get_vocab())
|
|
29
|
+
# This triggers when tokens_to_remove is empty or when there is no overlap
|
|
30
|
+
# between the tokens to remove and the model vocabulary.
|
|
31
|
+
if not set(tokens_to_remove).intersection(model_vocab):
|
|
32
|
+
# NOTE: return a copy.
|
|
33
|
+
if tokens_to_remove:
|
|
34
|
+
logger.info("No tokens to remove, none of the tokens were in the vocabulary.")
|
|
35
|
+
else:
|
|
36
|
+
logger.info("No tokens to remove.")
|
|
37
|
+
return Tokenizer.from_str(tokenizer.to_str())
|
|
38
|
+
|
|
27
39
|
tokenizer_data = json.loads(tokenizer.to_str())
|
|
28
40
|
|
|
29
41
|
# Find all added tokens
|
|
@@ -35,20 +47,31 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
|
|
|
35
47
|
tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
|
|
36
48
|
|
|
37
49
|
# Load the vocabulary.
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
model_type = tokenizer_data["model"]["type"]
|
|
51
|
+
|
|
52
|
+
match model_type:
|
|
53
|
+
case "WordPiece":
|
|
54
|
+
# Vocab is a dictionary.
|
|
55
|
+
vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
|
|
56
|
+
n_tokens = len(vocab)
|
|
57
|
+
|
|
58
|
+
# Remove the tokens.
|
|
59
|
+
for token in tokens_to_remove:
|
|
60
|
+
if vocab.pop(token, None) is None:
|
|
61
|
+
logger.warning(f"Token {token} was not in the vocabulary.")
|
|
62
|
+
|
|
63
|
+
n_removed = n_tokens - len(vocab)
|
|
64
|
+
logger.info(f"Removed {n_removed} tokens from the vocabulary.")
|
|
65
|
+
|
|
66
|
+
# Reindex the vocabulary so that it is contiguous.
|
|
67
|
+
reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
|
|
68
|
+
tokenizer_data["model"]["vocab"] = reindexed
|
|
69
|
+
case "Unigram":
|
|
70
|
+
raise ValueError("Removing tokens from a unigram tokenizer is not supported.")
|
|
71
|
+
case "BPE":
|
|
72
|
+
raise ValueError("Removing tokens from a bpe tokenizer is not supported.")
|
|
73
|
+
case _:
|
|
74
|
+
raise ValueError(f"Unknown model type {model_type}")
|
|
52
75
|
|
|
53
76
|
# Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
|
|
54
77
|
special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
|
|
@@ -68,12 +91,24 @@ def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
|
|
|
68
91
|
:param tokenizer: The tokenizer to add tokens to.
|
|
69
92
|
:param tokens_to_add: The tokens to add.
|
|
70
93
|
:return: The modified tokenizer.
|
|
94
|
+
:raises ValueError: If the tokenizer model type is not supported.
|
|
71
95
|
"""
|
|
72
96
|
data = json.loads(tokenizer.to_str())
|
|
73
97
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
98
|
+
model = data["model"]["type"]
|
|
99
|
+
|
|
100
|
+
match model:
|
|
101
|
+
case "WordPiece":
|
|
102
|
+
wordpiece_vocab: dict[str, int] = data["model"]["vocab"]
|
|
103
|
+
for token in tokens_to_add:
|
|
104
|
+
if token not in wordpiece_vocab:
|
|
105
|
+
wordpiece_vocab[token] = len(wordpiece_vocab)
|
|
106
|
+
case "Unigram":
|
|
107
|
+
raise ValueError("Adding tokens to a unigram tokenizer is not supported.")
|
|
108
|
+
case "BPE":
|
|
109
|
+
raise ValueError("Adding tokens to a bpe tokenizer is not supported.")
|
|
110
|
+
case _:
|
|
111
|
+
raise ValueError(f"Unknown model type {model}")
|
|
77
112
|
|
|
78
113
|
tokenizer = Tokenizer.from_str(json.dumps(data))
|
|
79
114
|
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from logging import getLogger
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
logger = getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def select_optimal_device(device: str | None) -> str:
|
|
9
|
+
"""
|
|
10
|
+
Guess what your optimal device should be based on backend availability.
|
|
11
|
+
|
|
12
|
+
If you pass a device, we just pass it through.
|
|
13
|
+
|
|
14
|
+
:param device: The device to use. If this is not None you get back what you passed.
|
|
15
|
+
:return: The selected device.
|
|
16
|
+
"""
|
|
17
|
+
if device is None:
|
|
18
|
+
if torch.cuda.is_available():
|
|
19
|
+
device = "cuda"
|
|
20
|
+
elif torch.backends.mps.is_available():
|
|
21
|
+
device = "mps"
|
|
22
|
+
else:
|
|
23
|
+
device = "cpu"
|
|
24
|
+
logger.info(f"Automatically selected device: {device}")
|
|
25
|
+
|
|
26
|
+
return device
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Distill a Small Fast Model from any Sentence Transformer
|
|
5
5
|
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
|
|
6
6
|
License: MIT License
|
|
@@ -151,7 +151,25 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
|
151
151
|
m2v_model.save_pretrained("m2v_model")
|
|
152
152
|
```
|
|
153
153
|
|
|
154
|
-
|
|
154
|
+
If you already have a model loaded, or need to load a model in some special way, we also offer an interface to distill models in memory.
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from transformers import AutoModel, AutoTokenizer
|
|
158
|
+
|
|
159
|
+
from model2vec.distill import distill_from_model
|
|
160
|
+
|
|
161
|
+
# Assuming a loaded model and tokenizer
|
|
162
|
+
model_name = "baai/bge-base-en-v1.5"
|
|
163
|
+
model = AutoModel.from_pretrained(model_name)
|
|
164
|
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
165
|
+
|
|
166
|
+
m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
|
|
167
|
+
|
|
168
|
+
m2v_model.save_pretrained("m2v_model")
|
|
169
|
+
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Distillation is really fast, and only takes about 5 seconds on a 2024 macbook using the MPS backend, 30 seconds on CPU. Best of all, distillation requires no training data.
|
|
155
173
|
|
|
156
174
|
## What is Model2Vec?
|
|
157
175
|
|
|
@@ -159,9 +177,10 @@ Model2vec creates a small, fast, and powerful model that outperforms other stati
|
|
|
159
177
|
|
|
160
178
|
It 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.
|
|
161
179
|
|
|
162
|
-
Model2vec has
|
|
163
|
-
- **Output**: behaves much
|
|
164
|
-
- **Vocab**:
|
|
180
|
+
Model2vec has 3 modes:
|
|
181
|
+
- **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.
|
|
182
|
+
- **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
|
|
183
|
+
- **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.
|
|
165
184
|
|
|
166
185
|
## Main Features
|
|
167
186
|
|
|
@@ -287,6 +306,7 @@ print(make_leaderboard(task_scores))
|
|
|
287
306
|
|------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
|
|
288
307
|
| [M2V_base_glove](https://huggingface.co/minishlab/M2V_base_glove) | English | Flagship embedding model based on GloVe vocab. | GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 102M |
|
|
289
308
|
| [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | English | Flagship embedding model based on bge-base-en-v1.5 vocab. Uses a subword tokenizer. | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M |
|
|
309
|
+
| [M2V_base_glove_subword](https://huggingface.co/minishlab/M2V_base_glove_subword) | English | Flagship embedding model based on bge-base-en-v1.5 + glove vocab. Uses a subword tokenizer. | Output + GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 103M |
|
|
290
310
|
| [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Flagship multilingual embedding model based on LaBSE vocab. Uses a subword tokenizer. | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M |
|
|
291
311
|
## Results
|
|
292
312
|
|
|
@@ -294,13 +314,16 @@ print(make_leaderboard(task_scores))
|
|
|
294
314
|
|
|
295
315
|
Model2Vec is evaluated on MTEB, as well as two additional tasks: [PEARL](https://github.com/tigerchen52/PEARL) (a phrase representation task) and WordSim (a collection of _word_ similarity tasks). The results are shown in the table below.
|
|
296
316
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
|
301
|
-
|
|
|
302
|
-
|
|
|
303
|
-
|
|
|
317
|
+
|
|
318
|
+
| Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
|
|
319
|
+
|------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
|
|
320
|
+
| all-MiniLM-L6-v2 | 56.08 | 56.09 | 62.62 | 41.94 | 82.37 | 58.04 | 41.95 | 78.90 | 30.81 | 60.83 | 49.91 |
|
|
321
|
+
| M2V_base_glove_subword | 49.06 | 46.69 | 61.27 | 30.03 | 74.71 | 49.15 | 27.16 | 69.09 | 30.08 | 56.82 | 57.99 |
|
|
322
|
+
| M2V_base_glove | 48.58 | 47.6 | 61.35 | 30.52 | 75.34 | 48.5 | 29.26 | 70.31 | 31.5 | 50.28 | 54.29 |
|
|
323
|
+
| M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 |
|
|
324
|
+
| GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
|
|
325
|
+
| WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
|
|
326
|
+
|
|
304
327
|
|
|
305
328
|
<details>
|
|
306
329
|
<summary> Task Abbreviations </summary>
|
|
@@ -322,21 +345,22 @@ For readability, the MTEB task names are abbreviated as follows:
|
|
|
322
345
|
|
|
323
346
|
In addition to the MTEB evaluation, we evaluate Model2Vec on a number of classification datasets. These are used as additional evidence to avoid overfitting to the MTEB dataset and to benchmark the speed of the model. The results are shown in the table below.
|
|
324
347
|
|
|
325
|
-
|
|
|
326
|
-
|
|
327
|
-
| bge-base-en-v1.5
|
|
328
|
-
| all-MiniLM-L6-v2
|
|
329
|
-
| M2V_base_output
|
|
330
|
-
|
|
|
331
|
-
|
|
|
332
|
-
|
|
|
348
|
+
| Model | Average | SST2 | IMDB | TREC | AG News |
|
|
349
|
+
|:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
|
|
350
|
+
| bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
|
|
351
|
+
| all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
|
|
352
|
+
| M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
|
|
353
|
+
| M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
|
|
354
|
+
| M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
|
|
355
|
+
| WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
|
|
356
|
+
| GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
|
|
333
357
|
|
|
334
358
|
As can be seen, Model2Vec models outperform the GloVe and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
|
|
335
359
|
|
|
336
360
|
The figure below shows the relationship between the number of sentences per second and the average classification score. The circle sizes correspond to the number of parameters in the models (larger = more parameters).
|
|
337
361
|
This plot shows that the Model2Vec models are much faster than the other models, while still being competitive in terms of classification performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
|
|
338
362
|
|
|
339
|
-
|  |
|
|
340
364
|
|:--:|
|
|
341
365
|
|*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
|
|
342
366
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
|
|
2
|
+
model2vec/model.py,sha256=fxqd0_pz4ahWtn4idgG_q61QyzKqqC0QcaOGu6XeHu4,8721
|
|
3
|
+
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
4
|
+
model2vec/utils.py,sha256=gS4-_Lno3iDG0k1B1tbcAhqyINZeTOFDJ6gP46YPkTc,8227
|
|
5
|
+
model2vec/distill/__init__.py,sha256=M5kp6RGYBsKQ6tqnoZiguPZomaR093cj-oxkV3Sdp1k,116
|
|
6
|
+
model2vec/distill/__main__.py,sha256=syBzxZz1zQi3UUD7KQAM0wG0W9oqHcKlAT5RX92tn0A,1738
|
|
7
|
+
model2vec/distill/distillation.py,sha256=cpK27cB_15AuLMR7nauSNH2R9x7kiRPsUCBHLMvKwdc,10386
|
|
8
|
+
model2vec/distill/inference.py,sha256=z8dK546imn_YatB3qLASOjnhSoryV1zk30djIGe0KM0,5475
|
|
9
|
+
model2vec/distill/tokenizer.py,sha256=rUE599Zk1wxBrKqW8D5Oi3Thtgvhyjm3y188GXoI8_g,4405
|
|
10
|
+
model2vec/distill/utils.py,sha256=a7PVyKHYZlowYOTHL1-CoVc76OJ0jukDnRquN_nnwLQ,685
|
|
11
|
+
model2vec-0.2.2.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
12
|
+
model2vec-0.2.2.dist-info/METADATA,sha256=iHvx07imW0L7XMm5fIxshocf9ZV5gmY9vJ5HmUl-BE0,21010
|
|
13
|
+
model2vec-0.2.2.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
14
|
+
model2vec-0.2.2.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
15
|
+
model2vec-0.2.2.dist-info/RECORD,,
|
model2vec-0.2.1.dist-info/RECORD
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
|
|
2
|
-
model2vec/model.py,sha256=fxqd0_pz4ahWtn4idgG_q61QyzKqqC0QcaOGu6XeHu4,8721
|
|
3
|
-
model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
|
|
4
|
-
model2vec/utils.py,sha256=gS4-_Lno3iDG0k1B1tbcAhqyINZeTOFDJ6gP46YPkTc,8227
|
|
5
|
-
model2vec/distill/__init__.py,sha256=1WLSMhxifoTSpIPb-drmP4sHdroc5jHo1fTISzqP6Hg,70
|
|
6
|
-
model2vec/distill/__main__.py,sha256=syBzxZz1zQi3UUD7KQAM0wG0W9oqHcKlAT5RX92tn0A,1738
|
|
7
|
-
model2vec/distill/distillation.py,sha256=vQLDbgD4Si5dGK1V2LaGmTVbhHb4ALuzgmkj87-u8HY,7918
|
|
8
|
-
model2vec/distill/inference.py,sha256=A-13qdkffeF5S__a0rTHx_O7n0iZQeyOwT3z9zqdQi0,4639
|
|
9
|
-
model2vec/distill/tokenizer.py,sha256=-3fWtHp_Fs41uqf3TWGHAxLoyEfSbnXsCeKcz6mQTP4,2751
|
|
10
|
-
model2vec-0.2.1.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
11
|
-
model2vec-0.2.1.dist-info/METADATA,sha256=x_y5e33PjybvEGP_7rQ5KwdA4Xoknm0y9w1Ob0oO8tw,19435
|
|
12
|
-
model2vec-0.2.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
13
|
-
model2vec-0.2.1.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
14
|
-
model2vec-0.2.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|