model2vec 0.1.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/__init__.py +4 -0
- model2vec/distill/__init__.py +3 -0
- model2vec/distill/__main__.py +129 -0
- model2vec/distill/inference.py +124 -0
- model2vec/distill/tokenizer.py +73 -0
- model2vec/model.py +168 -0
- model2vec/utils.py +116 -0
- model2vec-0.1.0.dist-info/LICENSE +21 -0
- model2vec-0.1.0.dist-info/METADATA +307 -0
- model2vec-0.1.0.dist-info/RECORD +12 -0
- model2vec-0.1.0.dist-info/WHEEL +5 -0
- model2vec-0.1.0.dist-info/top_level.txt +1 -0
model2vec/__init__.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from collections import Counter
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated, Optional
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import typer
|
|
8
|
+
from sklearn.decomposition import PCA
|
|
9
|
+
from tokenizers import Tokenizer
|
|
10
|
+
|
|
11
|
+
from model2vec.distill.inference import (
|
|
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
|
|
17
|
+
from model2vec.utils import setup_logging
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
app = typer.Typer()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@app.command()
|
|
25
|
+
def main(
|
|
26
|
+
model_name: Annotated[str, typer.Option(help="The model name to initialize the embedder model with.")],
|
|
27
|
+
save_path: Annotated[str, typer.Option(help="The folder to save the model to.")],
|
|
28
|
+
vocabulary_path: Annotated[
|
|
29
|
+
Optional[str],
|
|
30
|
+
typer.Option(
|
|
31
|
+
help="The path to the vocabulary file, which is a .txt file with one word per line. If this is not passed, we use the model's vocabulary."
|
|
32
|
+
),
|
|
33
|
+
] = None,
|
|
34
|
+
device: Annotated[str, typer.Option(help="The device to train the model on.")] = "cpu",
|
|
35
|
+
) -> None:
|
|
36
|
+
"""Creates output embeddings for a sentencetransformer."""
|
|
37
|
+
if vocabulary_path is not None:
|
|
38
|
+
vocabulary = open(vocabulary_path).read().splitlines()
|
|
39
|
+
else:
|
|
40
|
+
vocabulary = None
|
|
41
|
+
|
|
42
|
+
model = distill(model_name, vocabulary, device)
|
|
43
|
+
model.save_pretrained(Path(save_path))
|
|
44
|
+
|
|
45
|
+
|
|
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
|
+
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
109
|
+
|
|
110
|
+
p = PCA(n_components=pca_dims, whiten=False)
|
|
111
|
+
embeddings = p.fit_transform(embeddings)
|
|
112
|
+
else:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
if apply_zipf:
|
|
118
|
+
logger.info("Applying Zipf weighting")
|
|
119
|
+
w = np.log(np.arange(1, len(embeddings) + 1))
|
|
120
|
+
embeddings *= w[:, None]
|
|
121
|
+
|
|
122
|
+
config = {"tokenizer_name": tokenizer_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
|
|
123
|
+
|
|
124
|
+
return StaticModel(embeddings, tokenizer, config)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
setup_logging()
|
|
129
|
+
typer.run(main)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
import logging
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal, Protocol, cast
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import torch
|
|
8
|
+
from sentence_transformers import SentenceTransformer
|
|
9
|
+
from tqdm import tqdm
|
|
10
|
+
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizer
|
|
11
|
+
from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
PathLike = str | Path
|
|
17
|
+
|
|
18
|
+
_DEFAULT_BATCH_SIZE = 1024
|
|
19
|
+
|
|
20
|
+
OutputValue = Literal["sentence_embedding", "token_embeddings"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ModulewithWeights(Protocol):
|
|
24
|
+
weight: torch.nn.Parameter
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def create_output_embeddings_from_model_name_and_tokens(
|
|
28
|
+
model_name: PathLike,
|
|
29
|
+
tokens: list[str],
|
|
30
|
+
device: str,
|
|
31
|
+
output_value: Literal["sentence_embedding", "token_embeddings"],
|
|
32
|
+
include_eos_bos: bool,
|
|
33
|
+
) -> tuple[list[str], np.ndarray]:
|
|
34
|
+
"""
|
|
35
|
+
Create output embeddings for a bunch of tokens from a model name.
|
|
36
|
+
|
|
37
|
+
It does a forward pass for all tokens passed in tokens.
|
|
38
|
+
|
|
39
|
+
:param model_name: The model name to use.
|
|
40
|
+
:param tokens: The tokens to use.
|
|
41
|
+
:param device: The torch device to use.
|
|
42
|
+
:param output_value: The output value to pass to sentence transformers. If this is 'sentence_embedding', get pooled output, if this is 'token_embedding', get token means.
|
|
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.
|
|
45
|
+
"""
|
|
46
|
+
embedder = SentenceTransformer(str(model_name), device=device)
|
|
47
|
+
|
|
48
|
+
embedder_output_dim = _get_embedder_output_dim(output_value, embedder)
|
|
49
|
+
|
|
50
|
+
out_weights: np.ndarray
|
|
51
|
+
if output_value == "token_embeddings":
|
|
52
|
+
intermediate_weights: list[np.ndarray] = []
|
|
53
|
+
# NOTE: because tokens might be really long, and we want to take the mean anyway, we need to batch.
|
|
54
|
+
# otherwise we could go OOM.
|
|
55
|
+
for batch_idx in tqdm(range(0, len(tokens), _DEFAULT_BATCH_SIZE)):
|
|
56
|
+
batch = tokens[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
|
|
57
|
+
out: list[torch.Tensor] = cast(
|
|
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
|
+
)
|
|
78
|
+
|
|
79
|
+
return tokens, out_weights
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _get_embedder_output_dim(output_value: OutputValue, embedder: SentenceTransformer) -> int:
|
|
83
|
+
"""Get the embeddings dimension of a sentence transformer, given an output value."""
|
|
84
|
+
embedder_output_dim = embedder.encode(["a"], show_progress_bar=False, output_value=output_value)[0].shape[0]
|
|
85
|
+
|
|
86
|
+
return embedder_output_dim
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def create_output_embeddings_from_model_name(
|
|
90
|
+
model_name: PathLike,
|
|
91
|
+
device: str,
|
|
92
|
+
) -> tuple[list[str], np.ndarray]:
|
|
93
|
+
"""
|
|
94
|
+
Create output embeddings for a bunch of tokens from a model name.
|
|
95
|
+
|
|
96
|
+
It does a forward pass for all ids in the tokenizer.
|
|
97
|
+
|
|
98
|
+
:param model_name: The model name to use.
|
|
99
|
+
:param device: The torch device to use.
|
|
100
|
+
:return: The tokens and output emnbeddings.
|
|
101
|
+
"""
|
|
102
|
+
model: PreTrainedModel = AutoModel.from_pretrained(model_name).to(device)
|
|
103
|
+
tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
104
|
+
ids = torch.arange(tokenizer.vocab_size)
|
|
105
|
+
|
|
106
|
+
# Work-around
|
|
107
|
+
dummy_encoding = tokenizer.encode("A")
|
|
108
|
+
eos_token_id, bos_token_id = dummy_encoding[0], dummy_encoding[-1]
|
|
109
|
+
|
|
110
|
+
eos = torch.full([len(ids)], fill_value=eos_token_id)
|
|
111
|
+
bos = torch.full([len(ids)], fill_value=bos_token_id)
|
|
112
|
+
|
|
113
|
+
stacked = torch.stack([bos, ids, eos], dim=1)
|
|
114
|
+
|
|
115
|
+
intermediate_weights: list[np.ndarray] = []
|
|
116
|
+
for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
|
|
117
|
+
batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
|
|
118
|
+
with torch.no_grad():
|
|
119
|
+
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(input_ids=batch.to(device))
|
|
120
|
+
out: torch.Tensor = encoded.last_hidden_state
|
|
121
|
+
intermediate_weights.append(out[:, 1].cpu().numpy())
|
|
122
|
+
out_weights = np.concatenate(intermediate_weights)
|
|
123
|
+
|
|
124
|
+
return tokenizer.convert_ids_to_tokens(ids), out_weights
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from tempfile import NamedTemporaryFile
|
|
6
|
+
|
|
7
|
+
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
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenizer:
|
|
16
|
+
"""
|
|
17
|
+
Remove tokens from a tokenizer.
|
|
18
|
+
|
|
19
|
+
:param tokenizer: The tokenizer to remove tokens from.
|
|
20
|
+
:param tokens_to_remove: The tokens to remove.
|
|
21
|
+
:return: The modified tokenizer.
|
|
22
|
+
"""
|
|
23
|
+
with NamedTemporaryFile(mode="w+") as temp_file:
|
|
24
|
+
tokenizer.save(temp_file.name)
|
|
25
|
+
data = json.load(open(temp_file.name))
|
|
26
|
+
vocab: dict[str, int] = data["model"]["vocab"]
|
|
27
|
+
|
|
28
|
+
n_tokens = len(vocab)
|
|
29
|
+
for token in tokens_to_remove:
|
|
30
|
+
if vocab.pop(token, None) is None:
|
|
31
|
+
logger.warning(f"Token {token} was not in the vocabulary.")
|
|
32
|
+
|
|
33
|
+
n_removed = n_tokens - len(vocab)
|
|
34
|
+
logger.info(f"Removed {n_removed} tokens from the vocabulary.")
|
|
35
|
+
|
|
36
|
+
reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
|
|
37
|
+
data["model"]["vocab"] = reindexed
|
|
38
|
+
|
|
39
|
+
tokenizer = Tokenizer.from_str(json.dumps(data))
|
|
40
|
+
|
|
41
|
+
return tokenizer
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def create_tokenizer_from_vocab(vocabulary: list[str], unk_token: str, pad_token: str) -> Tokenizer:
|
|
45
|
+
"""
|
|
46
|
+
Create a word level tokenizer from a vocabulary.
|
|
47
|
+
|
|
48
|
+
:param vocabulary: The vocabulary mapping from strings to integers.
|
|
49
|
+
:param unk_token: The string representing the unk token.
|
|
50
|
+
:param pad_token: The string representing the pad token.
|
|
51
|
+
:return: A word level tokenizer.
|
|
52
|
+
:raises ValueError: If the unk_token or pad_token is not in the vocabulary.
|
|
53
|
+
"""
|
|
54
|
+
vocabulary_indexed = {token: idx for idx, token in enumerate(vocabulary)}
|
|
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()
|
|
64
|
+
|
|
65
|
+
# NOTE: unk and pad token can be cased, doesn't matter.
|
|
66
|
+
is_cased = any(token != token.lower() for token in vocabulary if token not in {unk_token, pad_token})
|
|
67
|
+
|
|
68
|
+
normalization_steps = [NFKC()]
|
|
69
|
+
if not is_cased:
|
|
70
|
+
normalization_steps.append(Lowercase())
|
|
71
|
+
tokenizer.normalizer = Sequence(normalization_steps)
|
|
72
|
+
|
|
73
|
+
return tokenizer
|
model2vec/model.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from logging import getLogger
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from tempfile import TemporaryDirectory
|
|
6
|
+
from typing import Any, Iterator
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
from tokenizers import Encoding, Tokenizer
|
|
11
|
+
from torch.nn import EmbeddingBag
|
|
12
|
+
from tqdm import tqdm
|
|
13
|
+
|
|
14
|
+
from model2vec.utils import load_pretrained, push_folder_to_hub, save_pretrained
|
|
15
|
+
|
|
16
|
+
PathLike = Path | str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
logger = getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class StaticModel:
|
|
23
|
+
def __init__(self, vectors: np.ndarray, tokenizer: Tokenizer, config: dict[str, Any]) -> None:
|
|
24
|
+
"""
|
|
25
|
+
Initialize the StaticModel.
|
|
26
|
+
|
|
27
|
+
:param vectors: The vectors to use.
|
|
28
|
+
:param tokenizer: The Transformers tokenizer to use.
|
|
29
|
+
:param config: Any metadata config.
|
|
30
|
+
:raises: ValueError if the number of tokens does not match the number of vectors.
|
|
31
|
+
"""
|
|
32
|
+
tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1]))
|
|
33
|
+
self.vectors = vectors
|
|
34
|
+
self.tokens = tokens
|
|
35
|
+
self.embedding = EmbeddingBag.from_pretrained(torch.from_numpy(vectors))
|
|
36
|
+
|
|
37
|
+
if len(tokens) != vectors.shape[0]:
|
|
38
|
+
raise ValueError(f"Number of tokens ({len(tokens)}) does not match number of vectors ({vectors.shape[0]})")
|
|
39
|
+
|
|
40
|
+
self.tokenizer = tokenizer
|
|
41
|
+
self.unk_token_id: int | None
|
|
42
|
+
if getattr(self.tokenizer.model, "unk_token") and self.tokenizer.model.unk_token is not None:
|
|
43
|
+
self.unk_token_id = tokenizer.get_vocab()[self.tokenizer.model.unk_token]
|
|
44
|
+
else:
|
|
45
|
+
self.unk_token_id = None
|
|
46
|
+
|
|
47
|
+
self.config = config
|
|
48
|
+
|
|
49
|
+
def save_pretrained(self, path: PathLike) -> None:
|
|
50
|
+
"""
|
|
51
|
+
Save the pretrained model.
|
|
52
|
+
|
|
53
|
+
:param path: The path to save to.
|
|
54
|
+
"""
|
|
55
|
+
save_pretrained(Path(path), self.vectors, self.tokenizer, self.config)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_pretrained(
|
|
59
|
+
cls: type[StaticModel],
|
|
60
|
+
path: PathLike,
|
|
61
|
+
huggingface_token: str | None = None,
|
|
62
|
+
) -> StaticModel:
|
|
63
|
+
"""
|
|
64
|
+
Create a static embeddder by creating a word-level tokenizer.
|
|
65
|
+
|
|
66
|
+
:param path: The path to load your static model from.
|
|
67
|
+
:param huggingface_token: The huggingface token to use.
|
|
68
|
+
:return: A StaticEmbedder
|
|
69
|
+
"""
|
|
70
|
+
embeddings, tokenizer, config = load_pretrained(path, huggingface_token=huggingface_token)
|
|
71
|
+
|
|
72
|
+
return cls(embeddings, tokenizer, config)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def dim(self) -> int:
|
|
76
|
+
"""
|
|
77
|
+
Get the dimension of the vectors.
|
|
78
|
+
|
|
79
|
+
:return: The dimension of the vectors.
|
|
80
|
+
"""
|
|
81
|
+
return self.vectors.shape[1]
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def normalize(X: np.ndarray) -> np.ndarray:
|
|
85
|
+
"""Normalize an array to unit length."""
|
|
86
|
+
norms = np.linalg.norm(X, axis=1, keepdims=True)
|
|
87
|
+
norms[norms == 0] = 1
|
|
88
|
+
|
|
89
|
+
return X / norms
|
|
90
|
+
|
|
91
|
+
def encode(
|
|
92
|
+
self,
|
|
93
|
+
sentences: list[str] | str,
|
|
94
|
+
show_progressbar: bool = False,
|
|
95
|
+
max_length: int | None = 512,
|
|
96
|
+
norm: bool = False,
|
|
97
|
+
batch_size: int = 1024,
|
|
98
|
+
**kwargs: Any,
|
|
99
|
+
) -> np.ndarray:
|
|
100
|
+
"""
|
|
101
|
+
Encode a list of sentences.
|
|
102
|
+
|
|
103
|
+
This function encodes a list of sentences by averaging the word embeddings of the tokens in the sentence.
|
|
104
|
+
For ease of use, we don't batch sentences together.
|
|
105
|
+
|
|
106
|
+
:param sentences: The list of sentences to encode. You can also pass a single sentence.
|
|
107
|
+
:param show_progressbar: Whether to show the progress bar.
|
|
108
|
+
:param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.
|
|
109
|
+
If this is None, no truncation is done.
|
|
110
|
+
:param norm: Whether to normalize the embeddings to unit length.
|
|
111
|
+
:param batch_size: The batch size to use.
|
|
112
|
+
:param **kwargs: Any additional arguments. These are ignored.
|
|
113
|
+
:return: The encoded sentences. If a single sentence was passed, a vector is returned.
|
|
114
|
+
"""
|
|
115
|
+
was_single = False
|
|
116
|
+
if isinstance(sentences, str):
|
|
117
|
+
sentences = [sentences]
|
|
118
|
+
was_single = True
|
|
119
|
+
|
|
120
|
+
out_arrays: list[np.ndarray] = []
|
|
121
|
+
for batch in tqdm(
|
|
122
|
+
self._batch(sentences, batch_size), total=(len(sentences) // batch_size) + 1, disable=not show_progressbar
|
|
123
|
+
):
|
|
124
|
+
out_arrays.append(self._encode_batch(batch, max_length))
|
|
125
|
+
|
|
126
|
+
out_array = np.concatenate(out_arrays, axis=0)
|
|
127
|
+
|
|
128
|
+
if norm:
|
|
129
|
+
out_array = self.normalize(out_array)
|
|
130
|
+
|
|
131
|
+
if was_single:
|
|
132
|
+
return out_array[0]
|
|
133
|
+
|
|
134
|
+
return out_array
|
|
135
|
+
|
|
136
|
+
def _encode_batch(self, sentences: list[str], max_length: int | None) -> np.ndarray:
|
|
137
|
+
"""Encode a batch of sentences."""
|
|
138
|
+
encodings: list[Encoding] = self.tokenizer.encode_batch(sentences, add_special_tokens=False)
|
|
139
|
+
encodings_ids = [encoding.ids for encoding in encodings]
|
|
140
|
+
|
|
141
|
+
if self.unk_token_id is not None:
|
|
142
|
+
# NOTE: Remove the unknown token: necessary for word-level models.
|
|
143
|
+
encodings_ids = [
|
|
144
|
+
[token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids
|
|
145
|
+
]
|
|
146
|
+
if max_length is not None:
|
|
147
|
+
encodings_ids = [token_ids[:max_length] for token_ids in encodings_ids]
|
|
148
|
+
|
|
149
|
+
offsets = np.cumsum([0] + [len(token_ids) for token_ids in encodings_ids[:-1]])
|
|
150
|
+
ids = torch.tensor([token_id for token_ids in encodings_ids for token_id in token_ids], dtype=torch.long)
|
|
151
|
+
|
|
152
|
+
return self.embedding(ids, torch.tensor(offsets, dtype=torch.long)).detach().numpy()
|
|
153
|
+
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _batch(sentences: list[str], batch_size: int) -> Iterator[list[str]]:
|
|
156
|
+
"""Batch the sentences into equal-sized."""
|
|
157
|
+
return (sentences[i : i + batch_size] for i in range(0, len(sentences), batch_size))
|
|
158
|
+
|
|
159
|
+
def push_to_hub(self, repo_id: str, token: str | None) -> None:
|
|
160
|
+
"""
|
|
161
|
+
Push the model to the huggingface hub.
|
|
162
|
+
|
|
163
|
+
:param repo_id: The repo id to push to.
|
|
164
|
+
:param token: The huggingface token to use.
|
|
165
|
+
"""
|
|
166
|
+
with TemporaryDirectory() as temp_dir:
|
|
167
|
+
self.save_pretrained(temp_dir)
|
|
168
|
+
push_folder_to_hub(Path(temp_dir), repo_id, token)
|
model2vec/utils.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Protocol, cast
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
import huggingface_hub
|
|
9
|
+
import numpy as np
|
|
10
|
+
import safetensors
|
|
11
|
+
from rich.logging import RichHandler
|
|
12
|
+
from safetensors.numpy import save_file
|
|
13
|
+
from tokenizers import Tokenizer
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SafeOpenProtocol(Protocol):
|
|
19
|
+
"""Protocol to fix safetensors safe open."""
|
|
20
|
+
|
|
21
|
+
def get_tensor(self, key: str) -> np.ndarray:
|
|
22
|
+
"""Get a tensor."""
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def setup_logging() -> None:
|
|
27
|
+
"""Simple logging setup."""
|
|
28
|
+
logging.basicConfig(
|
|
29
|
+
level="INFO",
|
|
30
|
+
format="%(name)s - %(message)s",
|
|
31
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
32
|
+
handlers=[RichHandler(rich_tracebacks=True, tracebacks_suppress=[click])],
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def save_pretrained(folder_path: Path, embeddings: np.ndarray, tokenizer: Tokenizer, config: dict[str, Any]) -> None:
|
|
37
|
+
"""
|
|
38
|
+
Save a model to a folder.
|
|
39
|
+
|
|
40
|
+
:param folder_path: The path to the folder.
|
|
41
|
+
:param embeddings: The embeddings
|
|
42
|
+
:param tokenizer: The tokenizer
|
|
43
|
+
:param config: A metadata config
|
|
44
|
+
"""
|
|
45
|
+
folder_path.mkdir(exist_ok=True, parents=True)
|
|
46
|
+
save_file({"embeddings": embeddings}, folder_path / "embeddings.safetensors")
|
|
47
|
+
tokenizer.save(str(folder_path / "tokenizer.json"))
|
|
48
|
+
json.dump(config, open(folder_path / "config.json", "w"))
|
|
49
|
+
|
|
50
|
+
logger.info(f"Saved model to {folder_path}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load_pretrained(
|
|
54
|
+
folder_or_repo_path: str | Path, huggingface_token: str | None = None
|
|
55
|
+
) -> tuple[np.ndarray, Tokenizer, dict[str, Any]]:
|
|
56
|
+
"""
|
|
57
|
+
Loads a pretrained model from a folder.
|
|
58
|
+
|
|
59
|
+
:param folder_or_repo_path: The folder or repo path to load from.
|
|
60
|
+
- If this is a local path, we will load from the local path.
|
|
61
|
+
- If the local path is not found, we will attempt to load from the huggingface hub.
|
|
62
|
+
:param huggingface_token: The huggingface token to use.
|
|
63
|
+
:raises: FileNotFoundError if the folder exists, but the file does not exist locally.
|
|
64
|
+
:return: The embeddings, tokenizer, and config.
|
|
65
|
+
|
|
66
|
+
"""
|
|
67
|
+
folder_or_repo_path = Path(folder_or_repo_path)
|
|
68
|
+
if folder_or_repo_path.exists():
|
|
69
|
+
embeddings_path = folder_or_repo_path / "embeddings.safetensors"
|
|
70
|
+
if not embeddings_path.exists():
|
|
71
|
+
raise FileNotFoundError(f"Embeddings file does not exist in {folder_or_repo_path}")
|
|
72
|
+
|
|
73
|
+
config_path = folder_or_repo_path / "config.json"
|
|
74
|
+
if not config_path.exists():
|
|
75
|
+
raise FileNotFoundError(f"Config file does not exist in {folder_or_repo_path}")
|
|
76
|
+
|
|
77
|
+
tokenizer_path = folder_or_repo_path / "tokenizer.json"
|
|
78
|
+
if not tokenizer_path.exists():
|
|
79
|
+
raise FileNotFoundError(f"Tokenizer file does not exist in {folder_or_repo_path}")
|
|
80
|
+
|
|
81
|
+
else:
|
|
82
|
+
logger.info("Folder does not exist locally, attempting to use huggingface hub.")
|
|
83
|
+
embeddings_path = huggingface_hub.hf_hub_download(
|
|
84
|
+
str(folder_or_repo_path), "embeddings.safetensors", token=huggingface_token
|
|
85
|
+
)
|
|
86
|
+
config_path = huggingface_hub.hf_hub_download(str(folder_or_repo_path), "config.json", token=huggingface_token)
|
|
87
|
+
tokenizer_path = huggingface_hub.hf_hub_download(
|
|
88
|
+
str(folder_or_repo_path), "tokenizer.json", token=huggingface_token
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
opened_tensor_file = cast(SafeOpenProtocol, safetensors.safe_open(embeddings_path, framework="numpy"))
|
|
92
|
+
embeddings = opened_tensor_file.get_tensor("embeddings")
|
|
93
|
+
|
|
94
|
+
tokenizer: Tokenizer = Tokenizer.from_file(str(tokenizer_path))
|
|
95
|
+
config = json.load(open(config_path))
|
|
96
|
+
|
|
97
|
+
if len(tokenizer.get_vocab()) != len(embeddings):
|
|
98
|
+
logger.warning(
|
|
99
|
+
f"Number of tokens does not match number of embeddings: `{len(tokenizer.get_vocab())}` vs `{len(embeddings)}`"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
return embeddings, tokenizer, config
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def push_folder_to_hub(folder_path: Path, repo_id: str, huggingface_token: str | None) -> None:
|
|
106
|
+
"""
|
|
107
|
+
Push a model folder to the huggingface hub.
|
|
108
|
+
|
|
109
|
+
:param folder_path: The path to the folder.
|
|
110
|
+
:param repo_id: The repo name.
|
|
111
|
+
:param huggingface_token: The huggingface token.
|
|
112
|
+
"""
|
|
113
|
+
if not huggingface_hub.repo_exists(repo_id=repo_id, token=huggingface_token):
|
|
114
|
+
huggingface_hub.create_repo(repo_id, token=huggingface_token)
|
|
115
|
+
huggingface_hub.upload_folder(repo_id=repo_id, folder_path=folder_path, token=huggingface_token)
|
|
116
|
+
logger.info(f"Pushed model to {repo_id}")
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Thomas van Dongen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: model2vec
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Distill a Small Fast Model from any Sentence Transformer
|
|
5
|
+
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2024 Thomas van Dongen
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/MinishLab
|
|
29
|
+
Project-URL: Bug Reports, https://github.com/MinishLab/model2vec/issues
|
|
30
|
+
Project-URL: Source, https://github.com/MinishLab/model2vec
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: Intended Audience :: Science/Research
|
|
34
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
35
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
36
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
37
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
41
|
+
Classifier: Natural Language :: English
|
|
42
|
+
Requires-Python: >=3.10
|
|
43
|
+
Description-Content-Type: text/markdown
|
|
44
|
+
License-File: LICENSE
|
|
45
|
+
Requires-Dist: click
|
|
46
|
+
Requires-Dist: numpy
|
|
47
|
+
Requires-Dist: rich
|
|
48
|
+
Requires-Dist: tqdm
|
|
49
|
+
Requires-Dist: typer
|
|
50
|
+
Requires-Dist: transformers
|
|
51
|
+
Requires-Dist: torch
|
|
52
|
+
Requires-Dist: sentence-transformers
|
|
53
|
+
Requires-Dist: tokenizers
|
|
54
|
+
Requires-Dist: scikit-learn
|
|
55
|
+
Provides-Extra: dev
|
|
56
|
+
Requires-Dist: black ; extra == 'dev'
|
|
57
|
+
Requires-Dist: ipython ; extra == 'dev'
|
|
58
|
+
Requires-Dist: mypy ; extra == 'dev'
|
|
59
|
+
Requires-Dist: pre-commit ; extra == 'dev'
|
|
60
|
+
Requires-Dist: pytest ; extra == 'dev'
|
|
61
|
+
Requires-Dist: pytest-coverage ; extra == 'dev'
|
|
62
|
+
Requires-Dist: ruff ; extra == 'dev'
|
|
63
|
+
|
|
64
|
+
# Model2Vec: Distill a Small Fast Model from any Sentence Transformer
|
|
65
|
+
|
|
66
|
+
**Model2Vec** is a method to distill a small, fast model from any Sentence Transformer model.
|
|
67
|
+
|
|
68
|
+
## Table of Contents
|
|
69
|
+
- [Main Features](#main-features)
|
|
70
|
+
- [Quickstart](#quickstart)
|
|
71
|
+
- [What is Model2Vec?](#what-is-model2vec)
|
|
72
|
+
- [Who is this for?](#who-is-this-for)
|
|
73
|
+
- [Usage](#usage)
|
|
74
|
+
- [Distilling a Model2Vec model](#distilling-a-model2vec-model)
|
|
75
|
+
- [Inferencing a Model2Vec model](#inferencing-a-model2vec-model)
|
|
76
|
+
- [Evaluating a Model2Vec model](#evaluating-a-model2vec-model)
|
|
77
|
+
- [Results](#results)
|
|
78
|
+
- [Citing](#citing)
|
|
79
|
+
|
|
80
|
+
## Main Features
|
|
81
|
+
- **Small**: Model2Vec can reduce the size of a Sentence Transformer model by a factor of 15 *.
|
|
82
|
+
- **Fast distillation**: Model2Vec can distill a Sentence Transformer model in ~5 minutes on CPU *.
|
|
83
|
+
- **Fast inference**: Model2Vec creates static embeddings that are up to 500 times * faster than the original model.
|
|
84
|
+
- **State-of-the-art static embedding performance**: Model2Vec outperforms traditional static embeddings by a large margin on a number of benchmarks.
|
|
85
|
+
- **No data needed**: Distillation happens directly on a token leven, so no dataset is needed.
|
|
86
|
+
- **Simple to use**: Model2Vec provides an easy to use interface for distilling and inferencing Model2Vec models.
|
|
87
|
+
- **Bring your own model**: Model2Vec can be applied to any Sentence Transformer model.
|
|
88
|
+
- **Bring your own vocabulary**: Model2Vec can be applied to any vocabulary, allowing you to use your own domain-specific vocabulary.
|
|
89
|
+
- **Multi-lingual**: Model2Vec can easily be applied to any language.
|
|
90
|
+
- **Tightly integrated with HuggingFace hub**: Model2Vec models can be easily shared and loaded from the HuggingFace hub. Our models can be found [here](https://huggingface.co/minishlab).
|
|
91
|
+
- **Easy Evaluation**: Model2Vec comes with a set of evaluation tasks to measure the performance of the distilled model.
|
|
92
|
+
|
|
93
|
+
\* Based on the [bge-base-en-v1.5 model](https://huggingface.co/BAAI/bge-base-en-v1.5).
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
## Quickstart
|
|
97
|
+
|
|
98
|
+
Install the package with:
|
|
99
|
+
```bash
|
|
100
|
+
pip install model2vec
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The easiest way to get started with Model2Vec is to download one of our [flagship models from the HuggingFace hub](https://huggingface.co/minishlab). These models are pre-trained and ready to use. The following code snippet shows how to load a model and make embeddings:
|
|
104
|
+
```python
|
|
105
|
+
from model2vec import StaticModel
|
|
106
|
+
|
|
107
|
+
# Load a model from the HuggingFace hub (in this case the M2V_base_output model)
|
|
108
|
+
model_name = "minishlab/M2V_base_output"
|
|
109
|
+
model = StaticModel.from_pretrained(model_name)
|
|
110
|
+
|
|
111
|
+
# Make embeddings
|
|
112
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everyone."])
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Alternatively, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
|
|
116
|
+
```python
|
|
117
|
+
from model2vec.distill import distill
|
|
118
|
+
|
|
119
|
+
# Choose a Sentence Transformer model
|
|
120
|
+
model_name = "BAAI/bge-base-en-v1.5"
|
|
121
|
+
|
|
122
|
+
# Distill the model
|
|
123
|
+
m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
124
|
+
|
|
125
|
+
# Save the model
|
|
126
|
+
m2v_model.save_pretrained("m2v_model")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## What is Model2Vec?
|
|
130
|
+
Model2Vec is a simple and effective method to distill any sentence transformer into static embeddings. It works by inferencing a vocabulary with the specified Sentence Transformer model, reducing the dimensionality of the embeddings using PCA, weighting the embeddings using zipf weighting, and storing the embeddings in a static format.
|
|
131
|
+
|
|
132
|
+
This technique creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on a a number of relevent tasks, while being much faster to create than traditional static embedding models such as GloVe, without need for a dataset.
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
## Who is this for?
|
|
136
|
+
Model2Vec allows anyone to create their own static embeddings from any Sentence Transformer model in minutes. It can easily be applied to other languages by using a language-specific Sentence Transformer model and vocab. Similarly, it can be applied to specific domains by using a domain specific model, vocab, or both. This makes it an ideal tool for fast prototyping, research, and production use cases where speed and size are more important than performance.
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
## Usage
|
|
142
|
+
|
|
143
|
+
### Distilling a Model2Vec model
|
|
144
|
+
|
|
145
|
+
Distilling a model from the output embeddings of a Sentence Transformer model:
|
|
146
|
+
```python
|
|
147
|
+
from model2vec.distill import distill
|
|
148
|
+
|
|
149
|
+
# Choose a Sentence Transformer model
|
|
150
|
+
model_name = "BAAI/bge-base-en-v1.5"
|
|
151
|
+
|
|
152
|
+
# Distill the model
|
|
153
|
+
m2v_model = distill(model_name=model_name, pca_dims=256)
|
|
154
|
+
|
|
155
|
+
# Save the model
|
|
156
|
+
m2v_model.save_pretrained("m2v_model")
|
|
157
|
+
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Distilling with a custom vocabulary:
|
|
161
|
+
```python
|
|
162
|
+
from model2vec.distill import distill
|
|
163
|
+
|
|
164
|
+
# Load a vocabulary as a list of strings
|
|
165
|
+
vocabulary = ["word1", "word2", "word3"]
|
|
166
|
+
# Choose a Sentence Transformer model
|
|
167
|
+
model_name = "BAAI/bge-base-en-v1.5"
|
|
168
|
+
|
|
169
|
+
# Distill the model with the custom vocabulary
|
|
170
|
+
m2v_model = distill(model_name=model_name, vocabulary=vocabulary, pca_dims=256)
|
|
171
|
+
|
|
172
|
+
# Save the model
|
|
173
|
+
m2v_model.save_pretrained("m2v_model")
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Alternatively, the command line interface can be used to distill a model:
|
|
177
|
+
```bash
|
|
178
|
+
python3 -m model2vec.distill --model-name BAAI/bge-base-en-v1.5 --vocabulary-path vocab.txt --device mps --save-path model2vec_model
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Inferencing a Model2Vec model
|
|
182
|
+
Inferencing with one of our flagship Model2Vec models:
|
|
183
|
+
```python
|
|
184
|
+
from model2vec import StaticModel
|
|
185
|
+
|
|
186
|
+
# Load a model from the HuggingFace hub
|
|
187
|
+
model_name = "minishlab/M2V_base_output"
|
|
188
|
+
model = StaticModel.from_pretrained(model_name)
|
|
189
|
+
|
|
190
|
+
# Make embeddings
|
|
191
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everyone."])
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
Inferencing with a saved Model2Vec model:
|
|
196
|
+
```python
|
|
197
|
+
from model2vec import StaticModel
|
|
198
|
+
|
|
199
|
+
# Load a saved model
|
|
200
|
+
model_name = "m2v_model"
|
|
201
|
+
model = StaticModel.from_pretrained(model_name)
|
|
202
|
+
|
|
203
|
+
# Make embeddings
|
|
204
|
+
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everyone."])
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Evaluating a Model2Vec model
|
|
208
|
+
|
|
209
|
+
Model2Vec models can be evaluated using our [evaluation package](https://github.com/MinishLab/evaluation). To run this, first install the optionall evaluation package:
|
|
210
|
+
```bash
|
|
211
|
+
pip install evaluation@git+https://github.com/MinishLab/evaluation@main
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Then, the following code snippet shows how to evaluate a Model2Vec model:
|
|
215
|
+
```python
|
|
216
|
+
from model2vec import StaticModel
|
|
217
|
+
|
|
218
|
+
from evaluation import CustomMTEB, get_tasks, parse_mteb_results, make_leaderboard, summarize_results
|
|
219
|
+
from mteb import ModelMeta
|
|
220
|
+
|
|
221
|
+
# Get all available tasks
|
|
222
|
+
tasks = get_tasks()
|
|
223
|
+
# Define the CustomMTEB object with the specified tasks
|
|
224
|
+
evaluation = CustomMTEB(tasks=tasks)
|
|
225
|
+
|
|
226
|
+
# Load the model
|
|
227
|
+
model_name = "m2v_model"
|
|
228
|
+
model = StaticModel.from_pretrained(model_name)
|
|
229
|
+
|
|
230
|
+
# Optionally, add model metadata in MTEB format
|
|
231
|
+
model.mteb_model_meta = ModelMeta(
|
|
232
|
+
name=model_name, revision="no_revision_available", release_date=None, languages=None
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Run the evaluation
|
|
236
|
+
results = evaluation.run(model, eval_splits=["test"], output_folder=f"results/{model_name}")
|
|
237
|
+
|
|
238
|
+
# Parse the results and summarize them
|
|
239
|
+
parsed_results = parse_mteb_results(mteb_results=results, model_name=model_name)
|
|
240
|
+
task_scores = summarize_results(parsed_results)
|
|
241
|
+
# Print the results in a leaderboard format
|
|
242
|
+
print(make_leaderboard(task_scores))
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## Results
|
|
246
|
+
|
|
247
|
+
### Main Results
|
|
248
|
+
|
|
249
|
+
Model2Vec is evaluated on MTEB, as well as two additional tasks: PEARL (a phrase representation task) and WordSim (a word similarity task). The results are shown in the table below.
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
| Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
|
|
255
|
+
|------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
|
|
256
|
+
| 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 |
|
|
257
|
+
| M2V_base_glove | 48.58 | 47.60 | 61.35 | 30.52 | 75.34 | 48.50 | 29.26 | 70.31 | 31.50 | 50.28 | 54.29 |
|
|
258
|
+
| M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.90 | 47.63 | 26.14 | 68.58 | 29.20 | 54.02 | 49.18 |
|
|
259
|
+
| GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
|
|
260
|
+
| WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
|
|
261
|
+
|
|
262
|
+
<details>
|
|
263
|
+
<summary> Task Abbreviations </summary>
|
|
264
|
+
|
|
265
|
+
For readability, the MTEB task names are abbreviated as follows:
|
|
266
|
+
- Class: Classification
|
|
267
|
+
- Clust: Clustering
|
|
268
|
+
- PairClass: PairClassification
|
|
269
|
+
- Rank: Reranking
|
|
270
|
+
- Ret: Retrieval
|
|
271
|
+
- STS: Semantic Textual Similarity
|
|
272
|
+
- Sum: Summarization
|
|
273
|
+
</details>
|
|
274
|
+
|
|
275
|
+
\
|
|
276
|
+
\* WL256, introduced in the [WordLlama](https://github.com/dleemiller/WordLlama/tree/main) package is included for comparison due to its similarities to Model2Vec. However, we believe it is heavily overfit to the MTEB dataset since it is trained on datasets used in MTEB itself. This can be seen by the fact that the WL256 model performs much worse on the non-MTEB tasks (PEARL and WordSim) than our models. The results shown in the [Classification and Speed Benchmarks](#classification-and-speed-benchmarks) further support this.
|
|
277
|
+
|
|
278
|
+
### Classification and Speed Benchmarks
|
|
279
|
+
|
|
280
|
+
In addition to the MTEB evaluation, Model2Vec is evaluated on a number of classification datasets. These are used as additional analysis to avoid overfitting to the MTEB dataset and to benchmark the speed of the model. The results are shown in the table below.
|
|
281
|
+
|
|
282
|
+
| model | Average | sst2 | imdb | trec | ag_news |
|
|
283
|
+
|:-----------------|----------:|---------:|-------:|---------:|----------:|
|
|
284
|
+
| bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
|
|
285
|
+
| all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
|
|
286
|
+
| M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
|
|
287
|
+
| M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
|
|
288
|
+
| WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
|
|
289
|
+
| GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
|
|
290
|
+
|
|
291
|
+
As can be seen, the Model2Vec models outperforms the GloVe and WL256 models on all classification tasks, and is competitive with the all-MiniLM-L6-v2 model while being much faster.
|
|
292
|
+
|
|
293
|
+
The scatterplot below shows the relationship between the number of sentences per second and the average classification score. The bubble sizes correspond to the number of parameters in the models (larger = more parameters), and the colors correspond to the sentences per second (greener = more sentences per second). 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 model.
|
|
294
|
+
|
|
295
|
+

|
|
296
|
+
|
|
297
|
+
## Citing
|
|
298
|
+
|
|
299
|
+
If you use Model2Vec in your research, please cite the following:
|
|
300
|
+
```bibtex
|
|
301
|
+
@software{minishlab2024word2vec,
|
|
302
|
+
authors = {Stephan Tulkens, Thomas van Dongen},
|
|
303
|
+
title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
|
|
304
|
+
year = {2024},
|
|
305
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
306
|
+
}
|
|
307
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
|
|
2
|
+
model2vec/model.py,sha256=ERW-Yazx6A8xTGMBTfrSVRW6lys3Oze9kKBRRMdwCoY,6157
|
|
3
|
+
model2vec/utils.py,sha256=hpydNokx7YnQMO9dNdMPUZMzOwQtdb1sLKhD2pwb6Cw,4405
|
|
4
|
+
model2vec/distill/__init__.py,sha256=1WLSMhxifoTSpIPb-drmP4sHdroc5jHo1fTISzqP6Hg,70
|
|
5
|
+
model2vec/distill/__main__.py,sha256=4Hq69AI4tlbBsUqezhG5wToCwA5Jxk0F-lBKQgF9FrY,5018
|
|
6
|
+
model2vec/distill/inference.py,sha256=B5jlh-xt_Z0cdPe3omZlwwSFVoamOKkiCVt5kXA6vXI,4991
|
|
7
|
+
model2vec/distill/tokenizer.py,sha256=Yko4FdRL1nHdJ402PdhoHcK6oLVS2J4OkItRUagDcsw,2653
|
|
8
|
+
model2vec-0.1.0.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
|
|
9
|
+
model2vec-0.1.0.dist-info/METADATA,sha256=uMdiaaEAIpfH0uZknFKIkS1i3vxebRV2L0u7-AhNUnQ,13920
|
|
10
|
+
model2vec-0.1.0.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
11
|
+
model2vec-0.1.0.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
|
|
12
|
+
model2vec-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
model2vec
|