model2vec 0.1.2__py3-none-any.whl → 0.2.0__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/__main__.py +16 -96
- model2vec/distill/distillation.py +171 -0
- model2vec/distill/inference.py +59 -53
- model2vec/distill/tokenizer.py +47 -40
- model2vec/model.py +34 -19
- model2vec/model_card_template.md +70 -0
- model2vec/utils.py +119 -18
- {model2vec-0.1.2.dist-info → model2vec-0.2.0.dist-info}/METADATA +38 -9
- model2vec-0.2.0.dist-info/RECORD +14 -0
- model2vec-0.1.2.dist-info/RECORD +0 -12
- {model2vec-0.1.2.dist-info → model2vec-0.2.0.dist-info}/LICENSE +0 -0
- {model2vec-0.1.2.dist-info → model2vec-0.2.0.dist-info}/WHEEL +0 -0
- {model2vec-0.1.2.dist-info → model2vec-0.2.0.dist-info}/top_level.txt +0 -0
model2vec/distill/__main__.py
CHANGED
|
@@ -1,19 +1,10 @@
|
|
|
1
1
|
import logging
|
|
2
|
-
from collections import Counter
|
|
3
2
|
from pathlib import Path
|
|
4
3
|
from typing import Annotated, Optional
|
|
5
4
|
|
|
6
|
-
import numpy as np
|
|
7
5
|
import typer
|
|
8
|
-
from sklearn.decomposition import PCA
|
|
9
|
-
from tokenizers import Tokenizer
|
|
10
6
|
|
|
11
|
-
from model2vec.distill.
|
|
12
|
-
create_output_embeddings_from_model_name,
|
|
13
|
-
create_output_embeddings_from_model_name_and_tokens,
|
|
14
|
-
)
|
|
15
|
-
from model2vec.distill.tokenizer import create_tokenizer_from_vocab, remove_tokens
|
|
16
|
-
from model2vec.model import StaticModel
|
|
7
|
+
from model2vec.distill.distillation import distill
|
|
17
8
|
from model2vec.utils import setup_logging
|
|
18
9
|
|
|
19
10
|
logger = logging.getLogger(__name__)
|
|
@@ -32,6 +23,13 @@ def main(
|
|
|
32
23
|
),
|
|
33
24
|
] = None,
|
|
34
25
|
device: Annotated[str, typer.Option(help="The device to train the model on.")] = "cpu",
|
|
26
|
+
pca_dims: Annotated[
|
|
27
|
+
int | None, typer.Option(help="The PCA dimensionality to use. If this is None, no PCA is applied.")
|
|
28
|
+
] = 256,
|
|
29
|
+
apply_zipf: Annotated[bool, typer.Option(help="Whether to apply Zipf weighting.")] = True,
|
|
30
|
+
use_subword: Annotated[
|
|
31
|
+
bool, typer.Option(help="Whether to use subword tokenization. If this is False, you must pass a vocabulary.")
|
|
32
|
+
] = True,
|
|
35
33
|
) -> None:
|
|
36
34
|
"""Creates output embeddings for a sentencetransformer."""
|
|
37
35
|
if vocabulary_path is not None:
|
|
@@ -39,95 +37,17 @@ def main(
|
|
|
39
37
|
else:
|
|
40
38
|
vocabulary = None
|
|
41
39
|
|
|
42
|
-
model = distill(
|
|
40
|
+
model = distill(
|
|
41
|
+
model_name=model_name,
|
|
42
|
+
vocabulary=vocabulary,
|
|
43
|
+
device=device,
|
|
44
|
+
pca_dims=pca_dims,
|
|
45
|
+
apply_zipf=apply_zipf,
|
|
46
|
+
use_subword=use_subword,
|
|
47
|
+
)
|
|
43
48
|
model.save_pretrained(Path(save_path))
|
|
44
49
|
|
|
45
50
|
|
|
46
|
-
def distill(
|
|
47
|
-
model_name: str,
|
|
48
|
-
vocabulary: list[str] | None = None,
|
|
49
|
-
device: str = "cpu",
|
|
50
|
-
pca_dims: int | None = 256,
|
|
51
|
-
apply_zipf: bool = True,
|
|
52
|
-
) -> StaticModel:
|
|
53
|
-
"""
|
|
54
|
-
Distill down a sentencetransformer to a static model.
|
|
55
|
-
|
|
56
|
-
This function creates a set of embeddings from a sentencetransformer. It does this by doing either
|
|
57
|
-
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
|
|
58
|
-
|
|
59
|
-
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
60
|
-
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
61
|
-
|
|
62
|
-
:param model_name: The model name to use. Any sentencetransformer compatible model works.
|
|
63
|
-
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
64
|
-
:param device: The device to use.
|
|
65
|
-
:param pca_dims: The number of components to use for PCA. If this is None, we don't apply PCA.
|
|
66
|
-
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
67
|
-
:raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
|
|
68
|
-
:raises: ValueError if the vocabulary contains duplicate tokens.
|
|
69
|
-
:return: A StaticModdel
|
|
70
|
-
|
|
71
|
-
"""
|
|
72
|
-
if vocabulary is None:
|
|
73
|
-
tokenizer: Tokenizer = Tokenizer.from_pretrained(model_name)
|
|
74
|
-
tokens, embeddings = create_output_embeddings_from_model_name(model_name, device=device)
|
|
75
|
-
tokenizer_name = model_name
|
|
76
|
-
|
|
77
|
-
wrong_tokens = [x for x in tokens if x.startswith("[unused")]
|
|
78
|
-
vocab = tokenizer.get_vocab()
|
|
79
|
-
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
80
|
-
tokenizer = remove_tokens(tokenizer, wrong_tokens)
|
|
81
|
-
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
82
|
-
logger.info("Removed unused tokens from the tokenizer and embeddings.")
|
|
83
|
-
|
|
84
|
-
else:
|
|
85
|
-
vocabulary_counts = Counter(vocabulary)
|
|
86
|
-
duplicates = [k for k, v in vocabulary_counts.items() if v > 1]
|
|
87
|
-
if duplicates:
|
|
88
|
-
duplicate_str = ", ".join(duplicates)
|
|
89
|
-
raise ValueError(f"Vocabulary contains duplicate tokens: {duplicate_str}")
|
|
90
|
-
|
|
91
|
-
if "[PAD]" not in vocabulary_counts:
|
|
92
|
-
vocabulary = ["[PAD]"] + vocabulary
|
|
93
|
-
if "[UNK]" not in vocabulary_counts:
|
|
94
|
-
vocabulary = ["[UNK]"] + vocabulary
|
|
95
|
-
|
|
96
|
-
tokens, embeddings = create_output_embeddings_from_model_name_and_tokens(
|
|
97
|
-
model_name=model_name,
|
|
98
|
-
tokens=vocabulary,
|
|
99
|
-
device=device,
|
|
100
|
-
output_value="token_embeddings",
|
|
101
|
-
include_eos_bos=False,
|
|
102
|
-
)
|
|
103
|
-
tokenizer_name = "word_level"
|
|
104
|
-
tokenizer = create_tokenizer_from_vocab(tokens, unk_token="[UNK]", pad_token="[PAD]")
|
|
105
|
-
|
|
106
|
-
if pca_dims is not None:
|
|
107
|
-
if pca_dims >= embeddings.shape[1]:
|
|
108
|
-
raise ValueError(
|
|
109
|
-
f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
|
|
110
|
-
)
|
|
111
|
-
if pca_dims >= len(tokens):
|
|
112
|
-
logger.warning(
|
|
113
|
-
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({len(tokens)}). Not applying PCA."
|
|
114
|
-
)
|
|
115
|
-
elif pca_dims < embeddings.shape[1]:
|
|
116
|
-
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
117
|
-
|
|
118
|
-
p = PCA(n_components=pca_dims, whiten=False)
|
|
119
|
-
embeddings = p.fit_transform(embeddings)
|
|
120
|
-
|
|
121
|
-
if apply_zipf:
|
|
122
|
-
logger.info("Applying Zipf weighting")
|
|
123
|
-
w = np.log(np.arange(1, len(embeddings) + 1))
|
|
124
|
-
embeddings *= w[:, None]
|
|
125
|
-
|
|
126
|
-
config = {"tokenizer_name": tokenizer_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
|
|
127
|
-
|
|
128
|
-
return StaticModel(embeddings, tokenizer, config)
|
|
129
|
-
|
|
130
|
-
|
|
131
51
|
if __name__ == "__main__":
|
|
132
52
|
setup_logging()
|
|
133
53
|
typer.run(main)
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from huggingface_hub import model_info
|
|
5
|
+
from sklearn.decomposition import PCA
|
|
6
|
+
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
7
|
+
|
|
8
|
+
from model2vec.distill.inference import (
|
|
9
|
+
create_output_embeddings_from_model_name,
|
|
10
|
+
create_output_embeddings_from_model_name_and_tokens,
|
|
11
|
+
)
|
|
12
|
+
from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
|
|
13
|
+
from model2vec.model import StaticModel
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def distill(
|
|
19
|
+
model_name: str,
|
|
20
|
+
vocabulary: list[str] | None = None,
|
|
21
|
+
device: str = "cpu",
|
|
22
|
+
pca_dims: int | None = 256,
|
|
23
|
+
apply_zipf: bool = True,
|
|
24
|
+
use_subword: bool = True,
|
|
25
|
+
) -> StaticModel:
|
|
26
|
+
"""
|
|
27
|
+
Distill a staticmodel from a sentence transformer.
|
|
28
|
+
|
|
29
|
+
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
30
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
|
|
31
|
+
|
|
32
|
+
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
33
|
+
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
34
|
+
|
|
35
|
+
:param model_name: The model name to use. Any sentencetransformer compatible model works.
|
|
36
|
+
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
37
|
+
:param device: The device to use.
|
|
38
|
+
:param pca_dims: The number of components to use for PCA. If this is None, we don't apply PCA.
|
|
39
|
+
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
40
|
+
: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
|
+
:raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
|
|
42
|
+
:raises: ValueError if the vocabulary contains duplicate tokens.
|
|
43
|
+
:return: A StaticModel
|
|
44
|
+
|
|
45
|
+
"""
|
|
46
|
+
if not use_subword and vocabulary is None:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
"You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Load original tokenizer. We need to keep this to tokenize any tokens in the vocabulary.
|
|
52
|
+
original_tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
|
|
53
|
+
original_model: PreTrainedModel = AutoModel.from_pretrained(model_name)
|
|
54
|
+
# Make a base list of tokens.
|
|
55
|
+
tokens: list[str] = []
|
|
56
|
+
if use_subword:
|
|
57
|
+
# Create the subword embeddings.
|
|
58
|
+
tokens, embeddings = create_output_embeddings_from_model_name(
|
|
59
|
+
model=original_model, tokenizer=original_tokenizer, device=device
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Remove any unused tokens from the tokenizer and embeddings.
|
|
63
|
+
wrong_tokens = [x for x in tokens if x.startswith("[unused")]
|
|
64
|
+
vocab = original_tokenizer.get_vocab()
|
|
65
|
+
# Get the ids of the unused token.
|
|
66
|
+
wrong_token_ids = [vocab[token] for token in wrong_tokens]
|
|
67
|
+
# Remove the unused tokens from the tokenizer.
|
|
68
|
+
new_tokenizer = remove_tokens(original_tokenizer.backend_tokenizer, wrong_tokens)
|
|
69
|
+
# Remove the embeddings of the unused tokens.
|
|
70
|
+
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
71
|
+
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
72
|
+
else:
|
|
73
|
+
# We need to keep the unk token in the tokenizer.
|
|
74
|
+
unk_token = original_tokenizer.backend_tokenizer.model.unk_token
|
|
75
|
+
# 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
|
+
)
|
|
79
|
+
# We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
|
|
80
|
+
embeddings = None
|
|
81
|
+
|
|
82
|
+
if vocabulary is not None:
|
|
83
|
+
# Preprocess the vocabulary with the original tokenizer.
|
|
84
|
+
preprocessed_vocabulary = preprocess_vocabulary(original_tokenizer.backend_tokenizer, vocabulary)
|
|
85
|
+
n_tokens_before = len(preprocessed_vocabulary)
|
|
86
|
+
# Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
|
|
87
|
+
cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
|
|
88
|
+
n_tokens_after = len(cleaned_vocabulary)
|
|
89
|
+
logger.info(
|
|
90
|
+
f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
|
|
91
|
+
)
|
|
92
|
+
# Only create embeddings if we have tokens to add.
|
|
93
|
+
if cleaned_vocabulary:
|
|
94
|
+
# Create the embeddings.
|
|
95
|
+
_, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
|
|
96
|
+
model=original_model,
|
|
97
|
+
tokenizer=original_tokenizer,
|
|
98
|
+
tokens=cleaned_vocabulary,
|
|
99
|
+
device=device,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# If we don't have subword tokens, we still need to create
|
|
103
|
+
# some embeddings for [UNK] and some other special tokens.
|
|
104
|
+
if embeddings is None:
|
|
105
|
+
embeddings = np.zeros((new_tokenizer.get_vocab_size(), token_embeddings.shape[1]))
|
|
106
|
+
embeddings = np.concatenate([embeddings, token_embeddings], axis=0)
|
|
107
|
+
# Add the cleaned vocabulary to the tokenizer.
|
|
108
|
+
new_tokenizer = add_tokens(new_tokenizer, cleaned_vocabulary)
|
|
109
|
+
else:
|
|
110
|
+
logger.warning("Didn't create any token embeddings as all tokens were duplicates or empty.")
|
|
111
|
+
|
|
112
|
+
# Post process the embeddings by applying PCA and Zipf weighting.
|
|
113
|
+
embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
|
|
114
|
+
|
|
115
|
+
config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
|
|
116
|
+
# Get the language from the model card
|
|
117
|
+
info = model_info(model_name)
|
|
118
|
+
language = info.cardData.get("language")
|
|
119
|
+
|
|
120
|
+
return StaticModel(
|
|
121
|
+
vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _post_process_embeddings(embeddings: np.ndarray, pca_dims: int | None, apply_zipf: bool) -> np.ndarray:
|
|
126
|
+
"""Post process embeddings by applying PCA and Zipf weighting."""
|
|
127
|
+
if pca_dims is not None:
|
|
128
|
+
if pca_dims >= embeddings.shape[1]:
|
|
129
|
+
raise ValueError(
|
|
130
|
+
f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
|
|
131
|
+
)
|
|
132
|
+
if pca_dims >= embeddings.shape[0]:
|
|
133
|
+
logger.warning(
|
|
134
|
+
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
|
|
135
|
+
)
|
|
136
|
+
elif pca_dims < embeddings.shape[1]:
|
|
137
|
+
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
138
|
+
|
|
139
|
+
p = PCA(n_components=pca_dims, whiten=False)
|
|
140
|
+
embeddings = p.fit_transform(embeddings)
|
|
141
|
+
|
|
142
|
+
if apply_zipf:
|
|
143
|
+
logger.info("Applying Zipf weighting")
|
|
144
|
+
embeddings *= np.log(1 + np.arange(embeddings.shape[0]))[:, None]
|
|
145
|
+
|
|
146
|
+
return embeddings
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _clean_vocabulary(preprocessed_vocabulary: list[str], added_tokens: list[str]) -> list[str]:
|
|
150
|
+
"""Cleans a vocabulary by removing duplicates and tokens that were already in the vocabulary."""
|
|
151
|
+
added_tokens_set = set(added_tokens)
|
|
152
|
+
seen_tokens = set()
|
|
153
|
+
cleaned_vocabulary = []
|
|
154
|
+
n_empty = 0
|
|
155
|
+
n_duplicates = 0
|
|
156
|
+
for token in preprocessed_vocabulary:
|
|
157
|
+
if not token:
|
|
158
|
+
n_empty += 1
|
|
159
|
+
continue
|
|
160
|
+
if token in seen_tokens or token in added_tokens_set:
|
|
161
|
+
n_duplicates += 1
|
|
162
|
+
continue
|
|
163
|
+
seen_tokens.add(token)
|
|
164
|
+
cleaned_vocabulary.append(token)
|
|
165
|
+
|
|
166
|
+
if n_duplicates:
|
|
167
|
+
logger.warning(f"Removed {n_duplicates} duplicate tokens.")
|
|
168
|
+
if n_empty:
|
|
169
|
+
logger.warning(f"Removed {n_empty} empty tokens.")
|
|
170
|
+
|
|
171
|
+
return cleaned_vocabulary
|
model2vec/distill/inference.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
2
|
import logging
|
|
3
3
|
from pathlib import Path
|
|
4
|
-
from typing import
|
|
4
|
+
from typing import Protocol
|
|
5
5
|
|
|
6
6
|
import numpy as np
|
|
7
7
|
import torch
|
|
8
|
-
from sentence_transformers import SentenceTransformer
|
|
9
8
|
from tqdm import tqdm
|
|
10
|
-
from transformers import
|
|
9
|
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
|
11
10
|
from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
|
|
12
11
|
|
|
13
12
|
logger = logging.getLogger(__name__)
|
|
@@ -17,77 +16,84 @@ PathLike = str | Path
|
|
|
17
16
|
|
|
18
17
|
_DEFAULT_BATCH_SIZE = 1024
|
|
19
18
|
|
|
20
|
-
OutputValue = Literal["sentence_embedding", "token_embeddings"]
|
|
21
|
-
|
|
22
19
|
|
|
23
20
|
class ModulewithWeights(Protocol):
|
|
24
21
|
weight: torch.nn.Parameter
|
|
25
22
|
|
|
26
23
|
|
|
27
24
|
def create_output_embeddings_from_model_name_and_tokens(
|
|
28
|
-
|
|
25
|
+
model: PreTrainedModel,
|
|
26
|
+
tokenizer: PreTrainedTokenizer,
|
|
29
27
|
tokens: list[str],
|
|
30
28
|
device: str,
|
|
31
|
-
output_value: Literal["sentence_embedding", "token_embeddings"],
|
|
32
|
-
include_eos_bos: bool,
|
|
33
29
|
) -> tuple[list[str], np.ndarray]:
|
|
34
30
|
"""
|
|
35
31
|
Create output embeddings for a bunch of tokens from a model name.
|
|
36
32
|
|
|
37
33
|
It does a forward pass for all tokens passed in tokens.
|
|
38
34
|
|
|
39
|
-
:param
|
|
35
|
+
:param model: The model name to use.
|
|
36
|
+
:param tokenizer: The tokenizer to use.
|
|
40
37
|
:param tokens: The tokens to use.
|
|
41
38
|
:param device: The torch device to use.
|
|
42
|
-
:
|
|
43
|
-
:param include_eos_bos: Whether to include the eos and bos tokens in the mean. Only applied if output_value == "token_embeddings".
|
|
44
|
-
:return: The tokens and output emnbeddings.
|
|
39
|
+
:return: The tokens and output embeddings.
|
|
45
40
|
"""
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
embedder_output_dim = _get_embedder_output_dim(output_value, embedder)
|
|
41
|
+
model = model.to(device)
|
|
49
42
|
|
|
50
43
|
out_weights: np.ndarray
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
list[torch.Tensor], embedder.encode(batch, show_progress_bar=False, output_value=output_value)
|
|
59
|
-
)
|
|
60
|
-
for idx, token_vectors in enumerate(out):
|
|
61
|
-
if not include_eos_bos:
|
|
62
|
-
# NOTE: remove BOS/EOS
|
|
63
|
-
token_vectors = token_vectors[1:-1]
|
|
64
|
-
if len(token_vectors) == 0:
|
|
65
|
-
str_repr = batch[idx]
|
|
66
|
-
bytes_repr = str_repr.encode("utf-8")
|
|
67
|
-
logger.warning(f"Got empty token vectors for word `{str_repr}` with bytes `{bytes_repr!r}`")
|
|
68
|
-
mean_vector = np.zeros(embedder_output_dim)
|
|
69
|
-
else:
|
|
70
|
-
mean_vector = cast(np.ndarray, token_vectors.cpu().numpy()).mean(0)
|
|
71
|
-
intermediate_weights.append(mean_vector)
|
|
72
|
-
out_weights = np.stack(intermediate_weights)
|
|
73
|
-
else:
|
|
74
|
-
out_weights = cast(
|
|
75
|
-
np.ndarray,
|
|
76
|
-
embedder.encode(tokens, show_progress_bar=True, output_value=output_value, batch_size=_DEFAULT_BATCH_SIZE),
|
|
77
|
-
)
|
|
44
|
+
intermediate_weights: list[np.ndarray] = []
|
|
45
|
+
|
|
46
|
+
for batch_idx in tqdm(range(0, len(tokens), _DEFAULT_BATCH_SIZE)):
|
|
47
|
+
batch = tokens[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
|
|
48
|
+
out = _encode_mean_using_model(model, tokenizer, batch)
|
|
49
|
+
intermediate_weights.append(out.numpy())
|
|
50
|
+
out_weights = np.concatenate(intermediate_weights)
|
|
78
51
|
|
|
79
52
|
return tokens, out_weights
|
|
80
53
|
|
|
81
54
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
55
|
+
@torch.no_grad()
|
|
56
|
+
def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, tokens: list[str]) -> torch.Tensor:
|
|
57
|
+
"""
|
|
58
|
+
Encode a batch of tokens using a model.
|
|
59
|
+
|
|
60
|
+
Note that if a token in the input batch does not have any embeddings, it will be output as a vector of zeros.
|
|
61
|
+
So detection of these is necessary.
|
|
62
|
+
|
|
63
|
+
:param model: The model to use.
|
|
64
|
+
:param tokenizer: The tokenizer to use.
|
|
65
|
+
:param tokens: The tokens to encode.
|
|
66
|
+
:return: The mean of the output for each token.
|
|
67
|
+
"""
|
|
68
|
+
encodings = tokenizer(tokens, return_tensors="pt", padding=True, truncation=True).to(model.device)
|
|
69
|
+
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
|
|
70
|
+
out = encoded.last_hidden_state.cpu()
|
|
71
|
+
|
|
72
|
+
mask = encodings["attention_mask"].cpu()
|
|
73
|
+
# NOTE: evil hack. For any batch, there will be a mask vector
|
|
74
|
+
# which has all 1s, because we pad to max_length. argmin returns 0
|
|
75
|
+
# in this case, which is wrong. But because we end up subtracting 1
|
|
76
|
+
# from it, we use -1, which is correct.
|
|
77
|
+
last_nonzero_index = mask.argmin(1) - 1
|
|
78
|
+
# NOTE: do not change the order of these calls. If you do, the hack
|
|
79
|
+
# above will no longer be evil (it will turn good), and will no longer work.
|
|
80
|
+
mask[torch.arange(mask.shape[0]), last_nonzero_index] = 0
|
|
81
|
+
mask[:, 0] = 0
|
|
82
|
+
|
|
83
|
+
# We take the mean of embeddings by first summing
|
|
84
|
+
result = torch.bmm(mask[:, None, :].float(), out).squeeze(1)
|
|
85
|
+
|
|
86
|
+
# Divide by the number of non-padding tokens, non-cls, etc. tokens.
|
|
87
|
+
divisor = mask.sum(1)
|
|
88
|
+
# Account for the case where divisor is 0.
|
|
89
|
+
divisor[divisor == 0] = 1
|
|
85
90
|
|
|
86
|
-
return
|
|
91
|
+
return result / divisor[:, None]
|
|
87
92
|
|
|
88
93
|
|
|
89
94
|
def create_output_embeddings_from_model_name(
|
|
90
|
-
|
|
95
|
+
model: PreTrainedModel,
|
|
96
|
+
tokenizer: PreTrainedTokenizer,
|
|
91
97
|
device: str,
|
|
92
98
|
) -> tuple[list[str], np.ndarray]:
|
|
93
99
|
"""
|
|
@@ -95,15 +101,15 @@ def create_output_embeddings_from_model_name(
|
|
|
95
101
|
|
|
96
102
|
It does a forward pass for all ids in the tokenizer.
|
|
97
103
|
|
|
98
|
-
:param
|
|
104
|
+
:param model: The model name to use.
|
|
105
|
+
:param tokenizer: The tokenizer to use.
|
|
99
106
|
:param device: The torch device to use.
|
|
100
|
-
:return: The tokens and output
|
|
107
|
+
:return: The tokens and output embeddings.
|
|
101
108
|
"""
|
|
102
|
-
model
|
|
103
|
-
tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
109
|
+
model = model.to(device)
|
|
104
110
|
ids = torch.arange(tokenizer.vocab_size)
|
|
105
111
|
|
|
106
|
-
# Work-around
|
|
112
|
+
# Work-around to get the eos and bos token ids without having to go into tokenizer internals.
|
|
107
113
|
dummy_encoding = tokenizer.encode("A")
|
|
108
114
|
eos_token_id, bos_token_id = dummy_encoding[0], dummy_encoding[-1]
|
|
109
115
|
|
|
@@ -114,7 +120,7 @@ def create_output_embeddings_from_model_name(
|
|
|
114
120
|
|
|
115
121
|
intermediate_weights: list[np.ndarray] = []
|
|
116
122
|
for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
|
|
117
|
-
batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
|
|
123
|
+
batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
|
|
118
124
|
with torch.no_grad():
|
|
119
125
|
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(input_ids=batch.to(device))
|
|
120
126
|
out: torch.Tensor = encoded.last_hidden_state
|
model2vec/distill/tokenizer.py
CHANGED
|
@@ -2,16 +2,20 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
4
|
import logging
|
|
5
|
-
from tempfile import NamedTemporaryFile
|
|
6
5
|
|
|
7
6
|
from tokenizers import Tokenizer
|
|
8
|
-
from tokenizers.models import WordLevel
|
|
9
|
-
from tokenizers.normalizers import NFKC, Lowercase, Sequence
|
|
10
|
-
from tokenizers.pre_tokenizers import Whitespace
|
|
11
7
|
|
|
12
8
|
logger = logging.getLogger(__name__)
|
|
13
9
|
|
|
14
10
|
|
|
11
|
+
def preprocess_vocabulary(tokenizer: Tokenizer, vocabulary: list[str]) -> list[str]:
|
|
12
|
+
"""Preprocess a vocabulary with a tokenizer by doing a roundtrip encode/decode."""
|
|
13
|
+
encoded_ids: list[list[int]] = [
|
|
14
|
+
encoding.ids for encoding in tokenizer.encode_batch(vocabulary, add_special_tokens=False)
|
|
15
|
+
]
|
|
16
|
+
return tokenizer.decode_batch(encoded_ids)
|
|
17
|
+
|
|
18
|
+
|
|
15
19
|
def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenizer:
|
|
16
20
|
"""
|
|
17
21
|
Remove tokens from a tokenizer.
|
|
@@ -20,54 +24,57 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
|
|
|
20
24
|
:param tokens_to_remove: The tokens to remove.
|
|
21
25
|
:return: The modified tokenizer.
|
|
22
26
|
"""
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
tokenizer_data = json.loads(tokenizer.to_str())
|
|
28
|
+
|
|
29
|
+
# Find all added tokens
|
|
30
|
+
added_tokens = tokenizer_data["added_tokens"]
|
|
31
|
+
added_tokens_str = {token["content"] for token in added_tokens}
|
|
32
|
+
|
|
33
|
+
# Remove all added tokens from the list of tokens to remove.
|
|
34
|
+
# Things will go bad if we keep them.
|
|
35
|
+
tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
|
|
36
|
+
|
|
37
|
+
# Load the vocabulary.
|
|
38
|
+
vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
|
|
39
|
+
n_tokens = len(vocab)
|
|
27
40
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
41
|
+
# Remove the tokens.
|
|
42
|
+
for token in tokens_to_remove:
|
|
43
|
+
if vocab.pop(token, None) is None:
|
|
44
|
+
logger.warning(f"Token {token} was not in the vocabulary.")
|
|
32
45
|
|
|
33
|
-
|
|
34
|
-
|
|
46
|
+
n_removed = n_tokens - len(vocab)
|
|
47
|
+
logger.info(f"Removed {n_removed} tokens from the vocabulary.")
|
|
35
48
|
|
|
36
|
-
|
|
37
|
-
|
|
49
|
+
# Reindex the vocabulary so that it is contiguous.
|
|
50
|
+
reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
|
|
51
|
+
tokenizer_data["model"]["vocab"] = reindexed
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
# Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
|
|
54
|
+
special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
|
|
55
|
+
for token, token_data in special_tokens_post_processor.items():
|
|
56
|
+
token_data["ids"] = [reindexed[token] for token in token_data["tokens"]]
|
|
57
|
+
|
|
58
|
+
# Reinitialize the tokenizer from the json.
|
|
59
|
+
tokenizer = Tokenizer.from_str(json.dumps(tokenizer_data))
|
|
40
60
|
|
|
41
61
|
return tokenizer
|
|
42
62
|
|
|
43
63
|
|
|
44
|
-
def
|
|
64
|
+
def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
|
|
45
65
|
"""
|
|
46
|
-
|
|
66
|
+
Add tokens to a tokenizer.
|
|
47
67
|
|
|
48
|
-
:param
|
|
49
|
-
:param
|
|
50
|
-
:
|
|
51
|
-
:return: A word level tokenizer.
|
|
52
|
-
:raises ValueError: If the unk_token or pad_token is not in the vocabulary.
|
|
68
|
+
:param tokenizer: The tokenizer to add tokens to.
|
|
69
|
+
:param tokens_to_add: The tokens to add.
|
|
70
|
+
:return: The modified tokenizer.
|
|
53
71
|
"""
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if unk_token not in vocabulary_indexed:
|
|
57
|
-
raise ValueError(f"unk token: {unk_token} was not in your vocabulary.")
|
|
58
|
-
if pad_token not in vocabulary_indexed:
|
|
59
|
-
raise ValueError(f"pad token: {pad_token} was not in your vocabulary.")
|
|
60
|
-
|
|
61
|
-
model = WordLevel(vocab=vocabulary_indexed, unk_token=unk_token)
|
|
62
|
-
tokenizer = Tokenizer(model)
|
|
63
|
-
tokenizer.pre_tokenizer = Whitespace()
|
|
72
|
+
data = json.loads(tokenizer.to_str())
|
|
64
73
|
|
|
65
|
-
|
|
66
|
-
|
|
74
|
+
vocab: dict[str, int] = data["model"]["vocab"]
|
|
75
|
+
for token in tokens_to_add:
|
|
76
|
+
vocab[token] = len(vocab)
|
|
67
77
|
|
|
68
|
-
|
|
69
|
-
if not is_cased:
|
|
70
|
-
normalization_steps.append(Lowercase())
|
|
71
|
-
tokenizer.normalizer = Sequence(normalization_steps)
|
|
78
|
+
tokenizer = Tokenizer.from_str(json.dumps(data))
|
|
72
79
|
|
|
73
80
|
return tokenizer
|
model2vec/model.py
CHANGED
|
@@ -22,7 +22,13 @@ logger = getLogger(__name__)
|
|
|
22
22
|
|
|
23
23
|
class StaticModel(nn.Module):
|
|
24
24
|
def __init__(
|
|
25
|
-
self,
|
|
25
|
+
self,
|
|
26
|
+
vectors: np.ndarray,
|
|
27
|
+
tokenizer: Tokenizer,
|
|
28
|
+
config: dict[str, Any],
|
|
29
|
+
normalize: bool | None = None,
|
|
30
|
+
base_model_name: str | None = None,
|
|
31
|
+
language: list[str] | None = None,
|
|
26
32
|
) -> None:
|
|
27
33
|
"""
|
|
28
34
|
Initialize the StaticModel.
|
|
@@ -31,6 +37,8 @@ class StaticModel(nn.Module):
|
|
|
31
37
|
:param tokenizer: The Transformers tokenizer to use.
|
|
32
38
|
:param config: Any metadata config.
|
|
33
39
|
:param normalize: Whether to normalize.
|
|
40
|
+
:param base_model_name: The used base model name. Used for creating a model card.
|
|
41
|
+
:param language: The language of the model. Used for creating a model card.
|
|
34
42
|
:raises: ValueError if the number of tokens does not match the number of vectors.
|
|
35
43
|
"""
|
|
36
44
|
super().__init__()
|
|
@@ -43,12 +51,15 @@ class StaticModel(nn.Module):
|
|
|
43
51
|
|
|
44
52
|
self.tokenizer = tokenizer
|
|
45
53
|
self.unk_token_id: int | None
|
|
46
|
-
if
|
|
54
|
+
if hasattr(self.tokenizer.model, "unk_token") and self.tokenizer.model.unk_token is not None:
|
|
47
55
|
self.unk_token_id = tokenizer.get_vocab()[self.tokenizer.model.unk_token]
|
|
48
56
|
else:
|
|
49
57
|
self.unk_token_id = None
|
|
50
58
|
|
|
51
59
|
self.config = config
|
|
60
|
+
self.base_model_name = base_model_name
|
|
61
|
+
self.language = language
|
|
62
|
+
|
|
52
63
|
if normalize is not None:
|
|
53
64
|
self.normalize = normalize
|
|
54
65
|
else:
|
|
@@ -74,13 +85,22 @@ class StaticModel(nn.Module):
|
|
|
74
85
|
)
|
|
75
86
|
self.config["normalize"] = value
|
|
76
87
|
|
|
77
|
-
def save_pretrained(self, path: PathLike) -> None:
|
|
88
|
+
def save_pretrained(self, path: PathLike, model_name: str | None = None) -> None:
|
|
78
89
|
"""
|
|
79
90
|
Save the pretrained model.
|
|
80
91
|
|
|
81
92
|
:param path: The path to save to.
|
|
82
|
-
|
|
83
|
-
|
|
93
|
+
:param model_name: The model name to use in the Model Card.
|
|
94
|
+
"""
|
|
95
|
+
save_pretrained(
|
|
96
|
+
folder_path=Path(path),
|
|
97
|
+
embeddings=self.embedding.weight.numpy(),
|
|
98
|
+
tokenizer=self.tokenizer,
|
|
99
|
+
config=self.config,
|
|
100
|
+
base_model_name=self.base_model_name,
|
|
101
|
+
language=self.language,
|
|
102
|
+
model_name=model_name,
|
|
103
|
+
)
|
|
84
104
|
|
|
85
105
|
def forward(self, ids: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
|
|
86
106
|
"""
|
|
@@ -134,18 +154,11 @@ class StaticModel(nn.Module):
|
|
|
134
154
|
:param token: The huggingface token to use.
|
|
135
155
|
:return: A StaticEmbedder
|
|
136
156
|
"""
|
|
137
|
-
embeddings, tokenizer, config = load_pretrained(path, token=token)
|
|
138
|
-
|
|
139
|
-
return cls(embeddings, tokenizer, config)
|
|
140
|
-
|
|
141
|
-
@property
|
|
142
|
-
def dim(self) -> int:
|
|
143
|
-
"""
|
|
144
|
-
Get the dimension of the vectors.
|
|
157
|
+
embeddings, tokenizer, config, metadata = load_pretrained(path, token=token)
|
|
145
158
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
159
|
+
return cls(
|
|
160
|
+
embeddings, tokenizer, config, base_model_name=metadata.get("base_model"), language=metadata.get("language")
|
|
161
|
+
)
|
|
149
162
|
|
|
150
163
|
def encode(
|
|
151
164
|
self,
|
|
@@ -198,15 +211,17 @@ class StaticModel(nn.Module):
|
|
|
198
211
|
"""Batch the sentences into equal-sized."""
|
|
199
212
|
return (sentences[i : i + batch_size] for i in range(0, len(sentences), batch_size))
|
|
200
213
|
|
|
201
|
-
def push_to_hub(self, repo_id: str, token: str | None) -> None:
|
|
214
|
+
def push_to_hub(self, repo_id: str, private: bool = False, token: str | None = None) -> None:
|
|
202
215
|
"""
|
|
203
216
|
Push the model to the huggingface hub.
|
|
204
217
|
|
|
205
218
|
NOTE: you need to pass a token if you are pushing a private model.
|
|
206
219
|
|
|
207
220
|
:param repo_id: The repo id to push to.
|
|
221
|
+
:param private: Whether the repo, if created is set to private.
|
|
222
|
+
If the repo already exists, this doesn't change the visibility.
|
|
208
223
|
:param token: The huggingface token to use.
|
|
209
224
|
"""
|
|
210
225
|
with TemporaryDirectory() as temp_dir:
|
|
211
|
-
self.save_pretrained(temp_dir)
|
|
212
|
-
push_folder_to_hub(Path(temp_dir), repo_id, token)
|
|
226
|
+
self.save_pretrained(temp_dir, model_name=repo_id)
|
|
227
|
+
push_folder_to_hub(Path(temp_dir), repo_id, private, token)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
---
|
|
2
|
+
{{ card_data }}
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# {{ model_name }} Model Card
|
|
6
|
+
|
|
7
|
+
This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of {% if base_model %}the [{{ base_model }}](https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical.
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install model2vec using pip:
|
|
13
|
+
```
|
|
14
|
+
pip install model2vec
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
Load this model using the `from_pretrained` method:
|
|
19
|
+
```python
|
|
20
|
+
from model2vec import StaticModel
|
|
21
|
+
|
|
22
|
+
# Load a pretrained Model2Vec model
|
|
23
|
+
model = StaticModel.from_pretrained("{{ model_name }}")
|
|
24
|
+
|
|
25
|
+
# Compute text embeddings
|
|
26
|
+
embeddings = model.encode(["Example sentence"])
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Alternatively, you can distill your own model using the `distill` method:
|
|
30
|
+
```python
|
|
31
|
+
from model2vec.distill import distill
|
|
32
|
+
|
|
33
|
+
# Choose a Sentence Transformer model
|
|
34
|
+
model_name = "BAAI/bge-base-en-v1.5"
|
|
35
|
+
|
|
36
|
+
# Distill the model
|
|
37
|
+
m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
38
|
+
|
|
39
|
+
# Save the model
|
|
40
|
+
m2v_model.save_pretrained("m2v_model")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## How it works
|
|
44
|
+
|
|
45
|
+
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. Best of all, you don't need any data to distill a model using Model2Vec.
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
## Additional Resources
|
|
50
|
+
|
|
51
|
+
- [All Model2Vec models on the hub](https://huggingface.co/models?library=model2vec)
|
|
52
|
+
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
53
|
+
- [Model2Vec Results](https://github.com/MinishLab/model2vec?tab=readme-ov-file#results)
|
|
54
|
+
- [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials)
|
|
55
|
+
|
|
56
|
+
## Library Authors
|
|
57
|
+
|
|
58
|
+
Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team consisting of [Stephan Tulkens](https://github.com/stephantul) and [Thomas van Dongen](https://github.com/Pringled).
|
|
59
|
+
|
|
60
|
+
## Citation
|
|
61
|
+
|
|
62
|
+
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
63
|
+
```
|
|
64
|
+
@software{minishlab2024model2vec,
|
|
65
|
+
authors = {Stephan Tulkens, Thomas van Dongen},
|
|
66
|
+
title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
|
|
67
|
+
year = {2024},
|
|
68
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
69
|
+
}
|
|
70
|
+
```
|
model2vec/utils.py
CHANGED
|
@@ -6,8 +6,10 @@ from typing import Any, Protocol, cast
|
|
|
6
6
|
|
|
7
7
|
import click
|
|
8
8
|
import huggingface_hub
|
|
9
|
+
import huggingface_hub.errors
|
|
9
10
|
import numpy as np
|
|
10
11
|
import safetensors
|
|
12
|
+
from huggingface_hub import ModelCard, ModelCardData
|
|
11
13
|
from rich.logging import RichHandler
|
|
12
14
|
from safetensors.numpy import save_file
|
|
13
15
|
from tokenizers import Tokenizer
|
|
@@ -33,26 +35,74 @@ def setup_logging() -> None:
|
|
|
33
35
|
)
|
|
34
36
|
|
|
35
37
|
|
|
36
|
-
def save_pretrained(
|
|
38
|
+
def save_pretrained(
|
|
39
|
+
folder_path: Path,
|
|
40
|
+
embeddings: np.ndarray,
|
|
41
|
+
tokenizer: Tokenizer,
|
|
42
|
+
config: dict[str, Any],
|
|
43
|
+
create_model_card: bool = True,
|
|
44
|
+
**kwargs: Any,
|
|
45
|
+
) -> None:
|
|
37
46
|
"""
|
|
38
47
|
Save a model to a folder.
|
|
39
48
|
|
|
40
49
|
:param folder_path: The path to the folder.
|
|
41
|
-
:param embeddings: The embeddings
|
|
42
|
-
:param tokenizer: The tokenizer
|
|
43
|
-
:param config: A metadata config
|
|
50
|
+
:param embeddings: The embeddings.
|
|
51
|
+
:param tokenizer: The tokenizer.
|
|
52
|
+
:param config: A metadata config.
|
|
53
|
+
:param create_model_card: Whether to create a model card.
|
|
54
|
+
:param **kwargs: Any additional arguments.
|
|
44
55
|
"""
|
|
45
56
|
folder_path.mkdir(exist_ok=True, parents=True)
|
|
46
|
-
save_file({"embeddings": embeddings}, folder_path / "
|
|
57
|
+
save_file({"embeddings": embeddings}, folder_path / "model.safetensors")
|
|
47
58
|
tokenizer.save(str(folder_path / "tokenizer.json"))
|
|
48
59
|
json.dump(config, open(folder_path / "config.json", "w"))
|
|
49
60
|
|
|
50
61
|
logger.info(f"Saved model to {folder_path}")
|
|
51
62
|
|
|
63
|
+
# Optionally create the model card
|
|
64
|
+
if create_model_card:
|
|
65
|
+
_create_model_card(folder_path, **kwargs)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _create_model_card(
|
|
69
|
+
folder_path: Path,
|
|
70
|
+
base_model_name: str = "unknown",
|
|
71
|
+
license: str = "mit",
|
|
72
|
+
language: list[str] | None = None,
|
|
73
|
+
model_name: str | None = None,
|
|
74
|
+
**kwargs: Any,
|
|
75
|
+
) -> None:
|
|
76
|
+
"""
|
|
77
|
+
Create a model card and store it in the specified path.
|
|
78
|
+
|
|
79
|
+
:param folder_path: The path where the model card will be stored.
|
|
80
|
+
:param base_model_name: The name of the base model.
|
|
81
|
+
:param license: The license to use.
|
|
82
|
+
:param language: The language of the model.
|
|
83
|
+
:param model_name: The name of the model to use in the Model Card.
|
|
84
|
+
:param **kwargs: Additional metadata for the model card (e.g., model_name, base_model, etc.).
|
|
85
|
+
"""
|
|
86
|
+
folder_path = Path(folder_path)
|
|
87
|
+
model_name = model_name or folder_path.name
|
|
88
|
+
template_path = Path(__file__).parent / "model_card_template.md"
|
|
89
|
+
|
|
90
|
+
model_card_data = ModelCardData(
|
|
91
|
+
model_name=model_name,
|
|
92
|
+
base_model=base_model_name,
|
|
93
|
+
license=license,
|
|
94
|
+
language=language,
|
|
95
|
+
tags=["embeddings", "static-embeddings"],
|
|
96
|
+
library_name="model2vec",
|
|
97
|
+
**kwargs,
|
|
98
|
+
)
|
|
99
|
+
model_card = ModelCard.from_template(model_card_data, template_path=template_path)
|
|
100
|
+
model_card.save(folder_path / "README.md")
|
|
101
|
+
|
|
52
102
|
|
|
53
103
|
def load_pretrained(
|
|
54
104
|
folder_or_repo_path: str | Path, token: str | None = None
|
|
55
|
-
) -> tuple[np.ndarray, Tokenizer, dict[str, Any]]:
|
|
105
|
+
) -> tuple[np.ndarray, Tokenizer, dict[str, Any], dict[str, Any]]:
|
|
56
106
|
"""
|
|
57
107
|
Loads a pretrained model from a folder.
|
|
58
108
|
|
|
@@ -61,14 +111,19 @@ def load_pretrained(
|
|
|
61
111
|
- If the local path is not found, we will attempt to load from the huggingface hub.
|
|
62
112
|
:param token: The huggingface token to use.
|
|
63
113
|
:raises: FileNotFoundError if the folder exists, but the file does not exist locally.
|
|
64
|
-
:return: The embeddings, tokenizer, and
|
|
114
|
+
:return: The embeddings, tokenizer, config, and metadata.
|
|
65
115
|
|
|
66
116
|
"""
|
|
67
117
|
folder_or_repo_path = Path(folder_or_repo_path)
|
|
68
118
|
if folder_or_repo_path.exists():
|
|
69
|
-
embeddings_path = folder_or_repo_path / "
|
|
119
|
+
embeddings_path = folder_or_repo_path / "model.safetensors"
|
|
70
120
|
if not embeddings_path.exists():
|
|
71
|
-
|
|
121
|
+
old_embeddings_path = folder_or_repo_path / "embeddings.safetensors"
|
|
122
|
+
if old_embeddings_path.exists():
|
|
123
|
+
logger.warning("Old embeddings file found. Please rename to `model.safetensors` and re-save.")
|
|
124
|
+
embeddings_path = old_embeddings_path
|
|
125
|
+
else:
|
|
126
|
+
raise FileNotFoundError(f"Embeddings file does not exist in {folder_or_repo_path}")
|
|
72
127
|
|
|
73
128
|
config_path = folder_or_repo_path / "config.json"
|
|
74
129
|
if not config_path.exists():
|
|
@@ -78,13 +133,34 @@ def load_pretrained(
|
|
|
78
133
|
if not tokenizer_path.exists():
|
|
79
134
|
raise FileNotFoundError(f"Tokenizer file does not exist in {folder_or_repo_path}")
|
|
80
135
|
|
|
136
|
+
# README is optional, so this is a bit finicky.
|
|
137
|
+
readme_path = folder_or_repo_path / "README.md"
|
|
138
|
+
metadata = _get_metadata_from_readme(readme_path)
|
|
139
|
+
|
|
81
140
|
else:
|
|
82
141
|
logger.info("Folder does not exist locally, attempting to use huggingface hub.")
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
142
|
+
try:
|
|
143
|
+
embeddings_path = huggingface_hub.hf_hub_download(
|
|
144
|
+
folder_or_repo_path.as_posix(), "model.safetensors", token=token
|
|
145
|
+
)
|
|
146
|
+
except huggingface_hub.utils.EntryNotFoundError as e:
|
|
147
|
+
try:
|
|
148
|
+
embeddings_path = huggingface_hub.hf_hub_download(
|
|
149
|
+
folder_or_repo_path.as_posix(), "embeddings.safetensors", token=token
|
|
150
|
+
)
|
|
151
|
+
except huggingface_hub.utils.EntryNotFoundError:
|
|
152
|
+
# Raise original exception.
|
|
153
|
+
raise e
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
readme_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "README.md", token=token)
|
|
157
|
+
metadata = _get_metadata_from_readme(Path(readme_path))
|
|
158
|
+
except huggingface_hub.utils.EntryNotFoundError:
|
|
159
|
+
logger.info("No README found in the model folder. No model card loaded.")
|
|
160
|
+
metadata = {}
|
|
161
|
+
|
|
162
|
+
config_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "config.json", token=token)
|
|
163
|
+
tokenizer_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "tokenizer.json", token=token)
|
|
88
164
|
|
|
89
165
|
opened_tensor_file = cast(SafeOpenProtocol, safetensors.safe_open(embeddings_path, framework="numpy"))
|
|
90
166
|
embeddings = opened_tensor_file.get_tensor("embeddings")
|
|
@@ -97,18 +173,43 @@ def load_pretrained(
|
|
|
97
173
|
f"Number of tokens does not match number of embeddings: `{len(tokenizer.get_vocab())}` vs `{len(embeddings)}`"
|
|
98
174
|
)
|
|
99
175
|
|
|
100
|
-
return embeddings, tokenizer, config
|
|
176
|
+
return embeddings, tokenizer, config, metadata
|
|
177
|
+
|
|
101
178
|
|
|
179
|
+
def _get_metadata_from_readme(readme_path: Path) -> dict[str, Any]:
|
|
180
|
+
"""Get metadata from a README file."""
|
|
181
|
+
if not readme_path.exists():
|
|
182
|
+
logger.info(f"README file not found in {readme_path}. No model card loaded.")
|
|
183
|
+
return {}
|
|
184
|
+
model_card = ModelCard.load(readme_path)
|
|
185
|
+
data: dict[str, Any] = model_card.data.to_dict()
|
|
186
|
+
if not data:
|
|
187
|
+
logger.info("File README.md exists, but was empty. No model card loaded.")
|
|
188
|
+
return data
|
|
102
189
|
|
|
103
|
-
|
|
190
|
+
|
|
191
|
+
def push_folder_to_hub(folder_path: Path, repo_id: str, private: bool, token: str | None) -> None:
|
|
104
192
|
"""
|
|
105
|
-
Push a model folder to the huggingface hub.
|
|
193
|
+
Push a model folder to the huggingface hub, including model card.
|
|
106
194
|
|
|
107
195
|
:param folder_path: The path to the folder.
|
|
108
196
|
:param repo_id: The repo name.
|
|
197
|
+
:param private: Whether the repo is private.
|
|
109
198
|
:param token: The huggingface token.
|
|
110
199
|
"""
|
|
111
200
|
if not huggingface_hub.repo_exists(repo_id=repo_id, token=token):
|
|
112
|
-
huggingface_hub.create_repo(repo_id, token=token)
|
|
201
|
+
huggingface_hub.create_repo(repo_id, token=token, private=private)
|
|
202
|
+
|
|
203
|
+
# Push model card and all model files to the Hugging Face hub
|
|
113
204
|
huggingface_hub.upload_folder(repo_id=repo_id, folder_path=folder_path, token=token)
|
|
205
|
+
|
|
206
|
+
# Check if the model card exists, and push it if available
|
|
207
|
+
model_card_path = folder_path / "README.md"
|
|
208
|
+
if model_card_path.exists():
|
|
209
|
+
card = ModelCard.load(model_card_path)
|
|
210
|
+
card.push_to_hub(repo_id=repo_id, token=token)
|
|
211
|
+
logger.info(f"Pushed model card to {repo_id}")
|
|
212
|
+
else:
|
|
213
|
+
logger.warning(f"Model card README.md not found in {folder_path}. Skipping model card upload.")
|
|
214
|
+
|
|
114
215
|
logger.info(f"Pushed model to {repo_id}")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
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
|
|
@@ -49,9 +49,9 @@ Requires-Dist: tqdm
|
|
|
49
49
|
Requires-Dist: typer
|
|
50
50
|
Requires-Dist: transformers
|
|
51
51
|
Requires-Dist: torch
|
|
52
|
-
Requires-Dist: sentence-transformers
|
|
53
52
|
Requires-Dist: tokenizers
|
|
54
53
|
Requires-Dist: scikit-learn
|
|
54
|
+
Requires-Dist: setuptools
|
|
55
55
|
Provides-Extra: dev
|
|
56
56
|
Requires-Dist: black ; extra == 'dev'
|
|
57
57
|
Requires-Dist: ipython ; extra == 'dev'
|
|
@@ -61,14 +61,43 @@ Requires-Dist: pytest ; extra == 'dev'
|
|
|
61
61
|
Requires-Dist: pytest-coverage ; extra == 'dev'
|
|
62
62
|
Requires-Dist: ruff ; extra == 'dev'
|
|
63
63
|
|
|
64
|
-
# Model2Vec: Distill a Small Fast Model from any Sentence Transformer
|
|
65
64
|
|
|
66
|
-
|
|
65
|
+
<div align="center">
|
|
66
|
+
<picture>
|
|
67
|
+
<img width="50%" alt="Model2Vec logo" src="assets/images/logo.png">
|
|
68
|
+
</picture>
|
|
69
|
+
</a>
|
|
70
|
+
</div>
|
|
67
71
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
<div align="center">
|
|
73
|
+
<h2>Distill a Small Fast Model from any Sentence Transformer</h2>
|
|
74
|
+
</div>
|
|
75
|
+
|
|
76
|
+
<div align="center">
|
|
77
|
+
<h2>
|
|
78
|
+
<a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
|
|
79
|
+
<a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
|
|
80
|
+
<a href="https://github.com/MinishLab"><strong>📖 Website </strong></a>
|
|
81
|
+
</h2>
|
|
82
|
+
</div>
|
|
83
|
+
|
|
84
|
+
<div align="center">
|
|
85
|
+
<h2>
|
|
86
|
+
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
|
|
87
|
+
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
|
|
88
|
+
<a href="https://pepy.tech/project/model2vec">
|
|
89
|
+
<img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
|
|
90
|
+
</a>
|
|
91
|
+
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
|
|
92
|
+
</h2>
|
|
93
|
+
</div>
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
<p align="center">
|
|
97
|
+
<img width="75%", src="assets/images/model2vec_model_diagram.png" alt="Model2Vec">
|
|
98
|
+
</p>
|
|
71
99
|
|
|
100
|
+
Model2Vec is a technique to turn any sentence transformer into a really small fast model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. See our results [here](#classification-and-speed-benchmarks), or dive in to see how it works.
|
|
72
101
|
|
|
73
102
|
## Table of Contents
|
|
74
103
|
- [Quickstart](#quickstart)
|
|
@@ -104,7 +133,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
|
|
|
104
133
|
|
|
105
134
|
And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
|
|
106
135
|
|
|
107
|
-
Instead of using
|
|
136
|
+
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:
|
|
108
137
|
```python
|
|
109
138
|
from model2vec.distill import distill
|
|
110
139
|
|
|
@@ -324,7 +353,7 @@ MIT
|
|
|
324
353
|
|
|
325
354
|
If you use Model2Vec in your research, please cite the following:
|
|
326
355
|
```bibtex
|
|
327
|
-
@software{
|
|
356
|
+
@software{minishlab2024model2vec,
|
|
328
357
|
authors = {Stephan Tulkens, Thomas van Dongen},
|
|
329
358
|
title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
|
|
330
359
|
year = {2024},
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
|
|
2
|
+
model2vec/model.py,sha256=tOiOo6BFo9fmOdzSlhEE2ElGuhT0kWL92X55VnsEKc8,8477
|
|
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.0.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
11
|
+
model2vec-0.2.0.dist-info/METADATA,sha256=MO-_ODvW5C1PtSmxVfu4f8uqw8wEGF1NXsCCJGWjv5M,19251
|
|
12
|
+
model2vec-0.2.0.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
13
|
+
model2vec-0.2.0.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
14
|
+
model2vec-0.2.0.dist-info/RECORD,,
|
model2vec-0.1.2.dist-info/RECORD
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
|
|
2
|
-
model2vec/model.py,sha256=z8QxOVMPMue4TnhbKgN2BcWQl0k9mKFZVGzYISa8uRY,7657
|
|
3
|
-
model2vec/utils.py,sha256=_1BXy782nRpbReJYQ0j9keFWJo1oKcwNtgYKw1t_7aY,4263
|
|
4
|
-
model2vec/distill/__init__.py,sha256=1WLSMhxifoTSpIPb-drmP4sHdroc5jHo1fTISzqP6Hg,70
|
|
5
|
-
model2vec/distill/__main__.py,sha256=Mobljoq8iMTSnb7q3HGIyfzxrFY3NU6-RQd4BgcBQsQ,5263
|
|
6
|
-
model2vec/distill/inference.py,sha256=MqLUpqzVzcXLziw8JBt3jyiQMRN8EtV2j5DZlE5Ba3o,4991
|
|
7
|
-
model2vec/distill/tokenizer.py,sha256=Yko4FdRL1nHdJ402PdhoHcK6oLVS2J4OkItRUagDcsw,2653
|
|
8
|
-
model2vec-0.1.2.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
9
|
-
model2vec-0.1.2.dist-info/METADATA,sha256=hQoodO_r6qPU1GnGie9AcNsK93AUCAS_iA7KF3dW8r4,17985
|
|
10
|
-
model2vec-0.1.2.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
11
|
-
model2vec-0.1.2.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
12
|
-
model2vec-0.1.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|