model2vec 0.2.1__py3-none-any.whl → 0.2.3__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.
@@ -1,3 +1,3 @@
1
- from model2vec.distill.__main__ import distill
1
+ from model2vec.distill.distillation import distill, distill_from_model
2
2
 
3
- __all__ = ["distill"]
3
+ __all__ = ["distill", "distill_from_model"]
@@ -1,8 +1,11 @@
1
1
  import logging
2
+ from typing import Literal
2
3
 
3
4
  import numpy as np
4
5
  from huggingface_hub import model_info
6
+ from huggingface_hub.utils._errors import RepositoryNotFoundError
5
7
  from sklearn.decomposition import PCA
8
+ from tokenizers.models import BPE, Unigram
6
9
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
7
10
 
8
11
  from model2vec.distill.inference import (
@@ -10,16 +13,21 @@ from model2vec.distill.inference import (
10
13
  create_output_embeddings_from_model_name_and_tokens,
11
14
  )
12
15
  from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
16
+ from model2vec.distill.utils import select_optimal_device
13
17
  from model2vec.model import StaticModel
14
18
 
15
19
  logger = logging.getLogger(__name__)
16
20
 
17
21
 
18
- def distill(
19
- model_name: str,
22
+ PCADimType = int | None | Literal["auto"]
23
+
24
+
25
+ def distill_from_model(
26
+ model: PreTrainedModel,
27
+ tokenizer: PreTrainedTokenizerFast,
20
28
  vocabulary: list[str] | None = None,
21
- device: str = "cpu",
22
- pca_dims: int | None = 256,
29
+ device: str | None = None,
30
+ pca_dims: PCADimType = 256,
23
31
  apply_zipf: bool = True,
24
32
  use_subword: bool = True,
25
33
  ) -> StaticModel:
@@ -32,10 +40,13 @@ def distill(
32
40
  If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
33
41
  If you don't pass a vocabulary, we use the model's tokenizer directly.
34
42
 
35
- :param model_name: The model name to use. Any sentencetransformer compatible model works.
43
+ :param model: The model to use.
44
+ :param tokenizer: The tokenizer to use.
36
45
  :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
37
46
  :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.
47
+ :param pca_dims: The number of components to use for PCA.
48
+ If this is None, we don't apply PCA.
49
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
39
50
  :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
40
51
  :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
52
  :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
@@ -43,45 +54,46 @@ def distill(
43
54
  :return: A StaticModel
44
55
 
45
56
  """
57
+ device = select_optimal_device(device)
46
58
  if not use_subword and vocabulary is None:
47
59
  raise ValueError(
48
60
  "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
49
61
  )
50
62
 
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)
63
+ if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
64
+ raise ValueError(
65
+ "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
66
+ "This is not supported yet."
67
+ "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
68
+ )
69
+
54
70
  # Make a base list of tokens.
55
71
  tokens: list[str] = []
56
72
  if use_subword:
57
73
  # Create the subword embeddings.
58
- tokens, embeddings = create_output_embeddings_from_model_name(
59
- model=original_model, tokenizer=original_tokenizer, device=device
60
- )
74
+ tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
61
75
 
62
76
  # Remove any unused tokens from the tokenizer and embeddings.
63
77
  wrong_tokens = [x for x in tokens if x.startswith("[unused")]
64
- vocab = original_tokenizer.get_vocab()
78
+ vocab = tokenizer.get_vocab()
65
79
  # Get the ids of the unused token.
66
80
  wrong_token_ids = [vocab[token] for token in wrong_tokens]
67
81
  # Remove the unused tokens from the tokenizer.
68
- new_tokenizer = remove_tokens(original_tokenizer.backend_tokenizer, wrong_tokens)
82
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
69
83
  # Remove the embeddings of the unused tokens.
70
84
  embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
71
85
  logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
72
86
  else:
73
87
  # We need to keep the unk token in the tokenizer.
74
- unk_token = original_tokenizer.backend_tokenizer.model.unk_token
88
+ unk_token = tokenizer.backend_tokenizer.model.unk_token
75
89
  # 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
- )
90
+ new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, list(set(tokenizer.get_vocab()) - {unk_token}))
79
91
  # We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
80
92
  embeddings = None
81
93
 
82
- if vocabulary is not None:
94
+ if vocabulary:
83
95
  # Preprocess the vocabulary with the original tokenizer.
84
- preprocessed_vocabulary = preprocess_vocabulary(original_tokenizer.backend_tokenizer, vocabulary)
96
+ preprocessed_vocabulary = preprocess_vocabulary(tokenizer.backend_tokenizer, vocabulary)
85
97
  n_tokens_before = len(preprocessed_vocabulary)
86
98
  # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
87
99
  cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
@@ -93,8 +105,8 @@ def distill(
93
105
  if cleaned_vocabulary:
94
106
  # Create the embeddings.
95
107
  _, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
96
- model=original_model,
97
- tokenizer=original_tokenizer,
108
+ model=model,
109
+ tokenizer=tokenizer,
98
110
  tokens=cleaned_vocabulary,
99
111
  device=device,
100
112
  )
@@ -112,28 +124,87 @@ def distill(
112
124
  # Post process the embeddings by applying PCA and Zipf weighting.
113
125
  embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
114
126
 
115
- config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
127
+ model_name = getattr(model, "name_or_path", "")
128
+
129
+ config = {
130
+ "tokenizer_name": model_name,
131
+ "apply_pca": pca_dims,
132
+ "apply_zipf": apply_zipf,
133
+ "hidden_dim": embeddings.shape[1],
134
+ "seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
135
+ }
116
136
  # Get the language from the model card
117
- info = model_info(model_name)
118
- language = info.cardData.get("language")
137
+ try:
138
+ info = model_info(model_name)
139
+ language = info.cardData.get("language")
140
+ except RepositoryNotFoundError:
141
+ logger.info("No model info found for model. Setting `language` to None.")
142
+ language = None
119
143
 
120
144
  return StaticModel(
121
145
  vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
122
146
  )
123
147
 
124
148
 
125
- def _post_process_embeddings(embeddings: np.ndarray, pca_dims: int | None, apply_zipf: bool) -> np.ndarray:
149
+ def distill(
150
+ model_name: str,
151
+ vocabulary: list[str] | None = None,
152
+ device: str | None = None,
153
+ pca_dims: PCADimType = 256,
154
+ apply_zipf: bool = True,
155
+ use_subword: bool = True,
156
+ ) -> StaticModel:
157
+ """
158
+ Distill a staticmodel from a sentence transformer.
159
+
160
+ This function creates a set of embeddings from a sentence transformer. It does this by doing either
161
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
162
+
163
+ If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
164
+ If you don't pass a vocabulary, we use the model's tokenizer directly.
165
+
166
+ :param model_name: The model name to use. Any sentencetransformer compatible model works.
167
+ :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
168
+ :param device: The device to use.
169
+ :param pca_dims: The number of components to use for PCA.
170
+ If this is None, we don't apply PCA.
171
+ If this is 'auto', we don't reduce dimenionality, but still apply PCA.
172
+ :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
173
+ :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.
174
+ :return: A StaticModel
175
+
176
+ """
177
+ model: PreTrainedModel = AutoModel.from_pretrained(model_name)
178
+ tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
179
+
180
+ return distill_from_model(
181
+ model=model,
182
+ tokenizer=tokenizer,
183
+ vocabulary=vocabulary,
184
+ device=device,
185
+ pca_dims=pca_dims,
186
+ apply_zipf=apply_zipf,
187
+ use_subword=use_subword,
188
+ )
189
+
190
+
191
+ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
126
192
  """Post process embeddings by applying PCA and Zipf weighting."""
127
193
  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]})"
194
+ if pca_dims == "auto":
195
+ pca_dims = embeddings.shape[1]
196
+ if pca_dims > embeddings.shape[1]:
197
+ logger.warning(
198
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
199
+ "Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
200
+ "Applying PCA will probably improve performance, so consider just leaving it."
131
201
  )
202
+ pca_dims = embeddings.shape[1]
132
203
  if pca_dims >= embeddings.shape[0]:
133
204
  logger.warning(
134
205
  f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
135
206
  )
136
- elif pca_dims < embeddings.shape[1]:
207
+ elif pca_dims <= embeddings.shape[1]:
137
208
  logger.info(f"Applying PCA with n_components {pca_dims}")
138
209
 
139
210
  p = PCA(n_components=pca_dims, whiten=False)
@@ -67,7 +67,12 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
67
67
  """
68
68
  encodings = tokenizer(tokens, return_tensors="pt", padding=True, truncation=True).to(model.device)
69
69
  encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
70
- out = encoded.last_hidden_state.cpu()
70
+ out: torch.Tensor = encoded.last_hidden_state.cpu()
71
+ # NOTE: If the dtype is bfloat 16, we convert to float32,
72
+ # because numpy does not suport bfloat16
73
+ # See here: https://github.com/numpy/numpy/issues/19808
74
+ if out.dtype == torch.bfloat16:
75
+ out = out.float()
71
76
 
72
77
  mask = encodings["attention_mask"].cpu()
73
78
  # NOTE: evil hack. For any batch, there will be a mask vector
@@ -122,8 +127,19 @@ def create_output_embeddings_from_model_name(
122
127
  for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
123
128
  batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
124
129
  with torch.no_grad():
125
- encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(input_ids=batch.to(device))
130
+ # NOTE: we create these masks because nomic embed requires them.
131
+ # Normally, we could set them to None
132
+ token_type_ids = torch.zeros_like(batch)
133
+ attention_mask = torch.ones_like(batch)
134
+ encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(
135
+ input_ids=batch.to(device), attention_mask=attention_mask, token_type_ids=token_type_ids
136
+ )
126
137
  out: torch.Tensor = encoded.last_hidden_state
138
+ # NOTE: If the dtype is bfloat 16, we convert to float32,
139
+ # because numpy does not suport bfloat16
140
+ # See here: https://github.com/numpy/numpy/issues/19808
141
+ if out.dtype == torch.bfloat16:
142
+ out = out.float()
127
143
  intermediate_weights.append(out[:, 1].cpu().numpy())
128
144
  out_weights = np.concatenate(intermediate_weights)
129
145
 
@@ -23,7 +23,19 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
23
23
  :param tokenizer: The tokenizer to remove tokens from.
24
24
  :param tokens_to_remove: The tokens to remove.
25
25
  :return: The modified tokenizer.
26
+ :raises ValueError: If the tokenizer model type is not supported.
26
27
  """
28
+ model_vocab = set(tokenizer.get_vocab())
29
+ # This triggers when tokens_to_remove is empty or when there is no overlap
30
+ # between the tokens to remove and the model vocabulary.
31
+ if not set(tokens_to_remove).intersection(model_vocab):
32
+ # NOTE: return a copy.
33
+ if tokens_to_remove:
34
+ logger.info("No tokens to remove, none of the tokens were in the vocabulary.")
35
+ else:
36
+ logger.info("No tokens to remove.")
37
+ return Tokenizer.from_str(tokenizer.to_str())
38
+
27
39
  tokenizer_data = json.loads(tokenizer.to_str())
28
40
 
29
41
  # Find all added tokens
@@ -35,20 +47,31 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
35
47
  tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
36
48
 
37
49
  # Load the vocabulary.
38
- vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
39
- n_tokens = len(vocab)
40
-
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.")
45
-
46
- n_removed = n_tokens - len(vocab)
47
- logger.info(f"Removed {n_removed} tokens from the vocabulary.")
48
-
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
50
+ model_type = tokenizer_data["model"]["type"]
51
+
52
+ match model_type:
53
+ case "WordPiece":
54
+ # Vocab is a dictionary.
55
+ vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
56
+ n_tokens = len(vocab)
57
+
58
+ # Remove the tokens.
59
+ for token in tokens_to_remove:
60
+ if vocab.pop(token, None) is None:
61
+ logger.warning(f"Token {token} was not in the vocabulary.")
62
+
63
+ n_removed = n_tokens - len(vocab)
64
+ logger.info(f"Removed {n_removed} tokens from the vocabulary.")
65
+
66
+ # Reindex the vocabulary so that it is contiguous.
67
+ reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
68
+ tokenizer_data["model"]["vocab"] = reindexed
69
+ case "Unigram":
70
+ raise ValueError("Removing tokens from a unigram tokenizer is not supported.")
71
+ case "BPE":
72
+ raise ValueError("Removing tokens from a bpe tokenizer is not supported.")
73
+ case _:
74
+ raise ValueError(f"Unknown model type {model_type}")
52
75
 
53
76
  # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
54
77
  special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
@@ -68,12 +91,24 @@ def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
68
91
  :param tokenizer: The tokenizer to add tokens to.
69
92
  :param tokens_to_add: The tokens to add.
70
93
  :return: The modified tokenizer.
94
+ :raises ValueError: If the tokenizer model type is not supported.
71
95
  """
72
96
  data = json.loads(tokenizer.to_str())
73
97
 
74
- vocab: dict[str, int] = data["model"]["vocab"]
75
- for token in tokens_to_add:
76
- vocab[token] = len(vocab)
98
+ model = data["model"]["type"]
99
+
100
+ match model:
101
+ case "WordPiece":
102
+ wordpiece_vocab: dict[str, int] = data["model"]["vocab"]
103
+ for token in tokens_to_add:
104
+ if token not in wordpiece_vocab:
105
+ wordpiece_vocab[token] = len(wordpiece_vocab)
106
+ case "Unigram":
107
+ raise ValueError("Adding tokens to a unigram tokenizer is not supported.")
108
+ case "BPE":
109
+ raise ValueError("Adding tokens to a bpe tokenizer is not supported.")
110
+ case _:
111
+ raise ValueError(f"Unknown model type {model}")
77
112
 
78
113
  tokenizer = Tokenizer.from_str(json.dumps(data))
79
114
 
@@ -0,0 +1,26 @@
1
+ from logging import getLogger
2
+
3
+ import torch
4
+
5
+ logger = getLogger(__name__)
6
+
7
+
8
+ def select_optimal_device(device: str | None) -> str:
9
+ """
10
+ Guess what your optimal device should be based on backend availability.
11
+
12
+ If you pass a device, we just pass it through.
13
+
14
+ :param device: The device to use. If this is not None you get back what you passed.
15
+ :return: The selected device.
16
+ """
17
+ if device is None:
18
+ if torch.cuda.is_available():
19
+ device = "cuda"
20
+ elif torch.backends.mps.is_available():
21
+ device = "mps"
22
+ else:
23
+ device = "cpu"
24
+ logger.info(f"Automatically selected device: {device}")
25
+
26
+ return device
model2vec/model.py CHANGED
@@ -9,7 +9,7 @@ import numpy as np
9
9
  import torch
10
10
  from tokenizers import Encoding, Tokenizer
11
11
  from torch import nn
12
- from torch.nn import EmbeddingBag
12
+ from torch.nn import Embedding, EmbeddingBag
13
13
  from tqdm import tqdm
14
14
 
15
15
  from model2vec.utils import load_pretrained, push_folder_to_hub, save_pretrained
@@ -25,7 +25,7 @@ class StaticModel(nn.Module):
25
25
  self,
26
26
  vectors: np.ndarray,
27
27
  tokenizer: Tokenizer,
28
- config: dict[str, Any],
28
+ config: dict[str, Any] | None = None,
29
29
  normalize: bool | None = None,
30
30
  base_model_name: str | None = None,
31
31
  language: list[str] | None = None,
@@ -44,7 +44,13 @@ class StaticModel(nn.Module):
44
44
  super().__init__()
45
45
  tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1]))
46
46
  self.tokens = tokens
47
- self.embedding = EmbeddingBag.from_pretrained(torch.from_numpy(vectors))
47
+ tensor = torch.from_numpy(vectors)
48
+
49
+ # NOTE: We make two embedding modules, but since they share the same memory,
50
+ # there's no overhead.
51
+ # Gradients are also integrated into both.
52
+ self.embedding_bag = EmbeddingBag.from_pretrained(tensor, mode="mean")
53
+ self.embedding = Embedding.from_pretrained(tensor)
48
54
 
49
55
  if len(tokens) != vectors.shape[0]:
50
56
  raise ValueError(f"Number of tokens ({len(tokens)}) does not match number of vectors ({vectors.shape[0]})")
@@ -57,14 +63,24 @@ class StaticModel(nn.Module):
57
63
  self.unk_token_id = None
58
64
 
59
65
  self.median_token_length = int(np.median([len(token) for token in self.tokens]))
60
- self.config = config
66
+ self.config = config or {}
61
67
  self.base_model_name = base_model_name
62
68
  self.language = language
63
69
 
64
70
  if normalize is not None:
65
71
  self.normalize = normalize
66
72
  else:
67
- self.normalize = config.get("normalize", False)
73
+ self.normalize = self.config.get("normalize", False)
74
+
75
+ @property
76
+ def dim(self) -> int:
77
+ """Get the dimension of the model."""
78
+ return self.embedding.weight.shape[1]
79
+
80
+ @property
81
+ def device(self) -> torch.device:
82
+ """Get the device of the model."""
83
+ return next(self.parameters()).device
68
84
 
69
85
  @property
70
86
  def normalize(self) -> bool:
@@ -103,7 +119,17 @@ class StaticModel(nn.Module):
103
119
  model_name=model_name,
104
120
  )
105
121
 
106
- def forward(self, ids: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
122
+ def forward(self, X: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
123
+ """
124
+ Helper method to facilitate training.
125
+
126
+ :param X: a tuple of ids and offsets.
127
+ :return: A padded output tensor.
128
+ """
129
+ ids, offsets = X
130
+ return self.embedding_bag(ids, offsets)
131
+
132
+ def forward_mean(self, ids: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
107
133
  """
108
134
  Forward pass of the model.
109
135
 
@@ -111,7 +137,8 @@ class StaticModel(nn.Module):
111
137
  :param offsets: The offsets tensor.
112
138
  :return: The output tensor.
113
139
  """
114
- means = self.embedding(ids, offsets)
140
+ means = self.embedding_bag(ids, offsets)
141
+
115
142
  if self.normalize:
116
143
  return torch.nn.functional.normalize(means)
117
144
  return means
@@ -165,6 +192,49 @@ class StaticModel(nn.Module):
165
192
  embeddings, tokenizer, config, base_model_name=metadata.get("base_model"), language=metadata.get("language")
166
193
  )
167
194
 
195
+ def encode_as_sequence(
196
+ self, sentences: list[str] | str, max_length: int | None = None
197
+ ) -> list[np.ndarray] | np.ndarray:
198
+ """
199
+ Encode a list of sentences as a list of numpy arrays of tokens.
200
+
201
+ This is useful if you want to use the tokens for further processing, or if you want to do sequence
202
+ modeling.
203
+ Note that if you just want the mean, you should use the `encode` method.
204
+ This is about twice as slow.
205
+ Sentences that do not contain any tokens will be turned into an empty array.
206
+
207
+ :param sentences: The list of sentences to encode.
208
+ :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.
209
+ If this is None, no truncation is done.
210
+ :return: The encoded sentences with an embedding per token.
211
+ """
212
+ was_single = False
213
+ if isinstance(sentences, str):
214
+ was_single = True
215
+ sentences = [sentences]
216
+
217
+ ids, offsets = self.tokenize(sentences=sentences, max_length=max_length)
218
+ ids = ids.to(self.device)
219
+ offsets = offsets.to(self.device)
220
+
221
+ out = [tensor.cpu().numpy() for tensor in self._sub_encode_as_sequence(ids, offsets)]
222
+
223
+ if was_single:
224
+ return out[0]
225
+
226
+ return out
227
+
228
+ def _sub_encode_as_sequence(self, ids: torch.Tensor, offsets: torch.Tensor) -> list[torch.Tensor]:
229
+ """Helper function to reduce deduplication."""
230
+ out = []
231
+ for x in range(len(offsets) - 1):
232
+ start, end = offsets[x], offsets[x + 1]
233
+ out.append(self.embedding(ids[start:end]))
234
+ out.append(self.embedding(ids[offsets[-1] :]))
235
+
236
+ return out
237
+
168
238
  def encode(
169
239
  self,
170
240
  sentences: list[str] | str,
@@ -209,7 +279,9 @@ class StaticModel(nn.Module):
209
279
  def _encode_batch(self, sentences: list[str], max_length: int | None) -> np.ndarray:
210
280
  """Encode a batch of sentences."""
211
281
  ids, offsets = self.tokenize(sentences, max_length)
212
- return self.forward(ids, offsets).numpy()
282
+ ids = ids.to(self.device)
283
+ offsets = offsets.to(self.device)
284
+ return self.forward_mean(ids, offsets).cpu().numpy()
213
285
 
214
286
  @staticmethod
215
287
  def _batch(sentences: list[str], batch_size: int) -> Iterator[list[str]]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.2.1
3
+ Version: 0.2.3
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
@@ -133,6 +133,9 @@ model = StaticModel.from_pretrained(model_name)
133
133
 
134
134
  # Make embeddings
135
135
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
136
+
137
+ # Make sequences of token embeddings
138
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
136
139
  ```
137
140
 
138
141
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
@@ -151,17 +154,36 @@ m2v_model = distill(model_name=model_name, pca_dims=256)
151
154
  m2v_model.save_pretrained("m2v_model")
152
155
  ```
153
156
 
154
- Distillation is really fast, and only takes about 30 seconds on a 2024 macbook using the MPS backend. Best of all, distillation requires no training data.
157
+ If you already have a model loaded, or need to load a model in some special way, we also offer an interface to distill models in memory.
158
+
159
+ ```python
160
+ from transformers import AutoModel, AutoTokenizer
161
+
162
+ from model2vec.distill import distill_from_model
163
+
164
+ # Assuming a loaded model and tokenizer
165
+ model_name = "baai/bge-base-en-v1.5"
166
+ model = AutoModel.from_pretrained(model_name)
167
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
168
+
169
+ m2v_model = distill_from_model(model=model, tokenizer=tokenizer, pca_dims=256)
170
+
171
+ m2v_model.save_pretrained("m2v_model")
172
+
173
+ ```
174
+
175
+ Distillation is really fast, and only takes about 5 seconds on a 2024 macbook using the MPS backend, 30 seconds on CPU. Best of all, distillation requires no training data.
155
176
 
156
177
  ## What is Model2Vec?
157
178
 
158
- 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.
179
+ Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Like BPEmb, it can create subword embeddings, but with much better performance. Best of all, you don't need _any_ data to distill a model using Model2Vec.
159
180
 
160
181
  It works by passing a vocabulary through a sentence transformer model, then reducing the dimensionality of the resulting embeddings using PCA, and finally weighting the embeddings using zipf weighting. During inference, we simply take the mean of all token embeddings occurring in a sentence.
161
182
 
162
- Model2vec has 2 modes:
163
- - **Output**: behaves much a like a real sentence transformer, i.e., it uses a subword tokenizer and encodes all wordpieces. This is really quick to create, very small (30 MB), but might be less performant on some tasks.
164
- - **Vocab**: behaves much like GloVe or regular word2vec vectors, albeit with much better performance. These models are a bit bigger, depending on your vocabulary size, but still very fast, and are useful in situations in which you have a bit more RAM, but still need to go fast.
183
+ Model2vec has 3 modes:
184
+ - **Output**: behaves much like a real sentence transformer, i.e., it uses a subword tokenizer and simply encodes all wordpieces in its vocab. This is really quick to create (30 seconds on a CPU), very small (30 MB in float32), but might be less performant on some tasks.
185
+ - **Vocab (word level)**: creates a word-level tokenizer and only encodes words that are in the vocabulary. This is a bit slower to create and creates a larger model, but might be more performant on some tasks. Note that this model can go out-of-vocabulary, which might be beneficial if your domain is very noisy
186
+ - **Vocab (subword)**: a combination of the two methods above. In this mode, you can pass your own vocabulary, but it also uses the subword vocabulary to create representations for words not in the passed vocabulary.
165
187
 
166
188
  ## Main Features
167
189
 
@@ -239,6 +261,9 @@ model = StaticModel.from_pretrained(model_name, token=None)
239
261
 
240
262
  # Make embeddings
241
263
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
264
+
265
+ # Make sequences of token embeddings
266
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
242
267
  ```
243
268
 
244
269
  ### Evaluating a Model2Vec model
@@ -287,6 +312,7 @@ print(make_leaderboard(task_scores))
287
312
  |------------------------|-------------|-----------------------------------------------------------------------|----------------|-----------------------|--------------|
288
313
  | [M2V_base_glove](https://huggingface.co/minishlab/M2V_base_glove) | English | Flagship embedding model based on GloVe vocab. | GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 102M |
289
314
  | [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | English | Flagship embedding model based on bge-base-en-v1.5 vocab. Uses a subword tokenizer. | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M |
315
+ | [M2V_base_glove_subword](https://huggingface.co/minishlab/M2V_base_glove_subword) | English | Flagship embedding model based on bge-base-en-v1.5 + glove vocab. Uses a subword tokenizer. | Output + GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 103M |
290
316
  | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Flagship multilingual embedding model based on LaBSE vocab. Uses a subword tokenizer. | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M |
291
317
  ## Results
292
318
 
@@ -294,13 +320,18 @@ print(make_leaderboard(task_scores))
294
320
 
295
321
  Model2Vec is evaluated on MTEB, as well as two additional tasks: [PEARL](https://github.com/tigerchen52/PEARL) (a phrase representation task) and WordSim (a collection of _word_ similarity tasks). The results are shown in the table below.
296
322
 
297
- | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | PEARL | WordSim |
298
- |------------------|-------------|------------|-------|-------|-----------|-------|-------|-------|-------|-------|---------|
299
- | 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 |
300
- | 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 |
301
- | 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 |
302
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
303
- | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
323
+
324
+
325
+ | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
326
+ |:-----------------------|:---------:|:----------:|:------:|:------:|:---------:|:------:|:------:|:------:|:------:|:------:|:-------:|
327
+ | 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 |
328
+ | M2V_base_glove_subword | 49.06 | 46.69 | 61.27 | 30.03 | 74.71 | 49.15 | 27.16 | 69.09 | 30.08 | 56.82 | 57.99 |
329
+ | 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 |
330
+ | 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 |
331
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
332
+ | BPEmb_50k_300d | 39.34 | 37.78 | 55.76 | 23.35 | 57.86 | 43.21 | 17.50 | 55.10 | 29.74 | 47.56 | 41.28 |
333
+ | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
334
+
304
335
 
305
336
  <details>
306
337
  <summary> Task Abbreviations </summary>
@@ -322,21 +353,25 @@ For readability, the MTEB task names are abbreviated as follows:
322
353
 
323
354
  In addition to the MTEB evaluation, we evaluate Model2Vec on a number of classification datasets. These are used as additional evidence to avoid overfitting to the MTEB dataset and to benchmark the speed of the model. The results are shown in the table below.
324
355
 
325
- | model | Average | sst2 | imdb | trec | ag_news |
326
- |:-----------------|----------:|---------:|-------:|---------:|----------:|
327
- | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
328
- | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
329
- | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
330
- | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
331
- | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
332
- | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
333
356
 
334
- As can be seen, Model2Vec models outperform the GloVe and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
357
+ | Model | Average | SST2 | IMDB | TREC | AG News |
358
+ |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
359
+ | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
360
+ | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
361
+ | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
362
+ | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
363
+ | BPEmb_50k_300d | 81.15 | 80.42 | 84.04 | 71.25 | 88.92 |
364
+ | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
365
+ | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
366
+ | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
367
+
368
+
369
+ As can be seen, Model2Vec models outperform the GloVe, BPEmb, and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
335
370
 
336
371
  The figure below shows the relationship between the number of sentences per second and the average classification score. The circle sizes correspond to the number of parameters in the models (larger = more parameters).
337
372
  This plot shows that the Model2Vec models are much faster than the other models, while still being competitive in terms of classification performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
338
373
 
339
- | ![Description](assets/images/speed_vs_accuracy.png) |
374
+ | ![Description](assets/images/speed_vs_accuracy_v3.png) |
340
375
  |:--:|
341
376
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
342
377
 
@@ -0,0 +1,15 @@
1
+ model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
2
+ model2vec/model.py,sha256=beLes7Nf3tTgBFCvPbeimtyRPDUsCEJNN5RD7MwZrHM,11420
3
+ model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
4
+ model2vec/utils.py,sha256=gS4-_Lno3iDG0k1B1tbcAhqyINZeTOFDJ6gP46YPkTc,8227
5
+ model2vec/distill/__init__.py,sha256=M5kp6RGYBsKQ6tqnoZiguPZomaR093cj-oxkV3Sdp1k,116
6
+ model2vec/distill/__main__.py,sha256=syBzxZz1zQi3UUD7KQAM0wG0W9oqHcKlAT5RX92tn0A,1738
7
+ model2vec/distill/distillation.py,sha256=DBcY2QITNjVGGsjZgdZZfl6Fab9M6Z_9FejlYH82KjE,10789
8
+ model2vec/distill/inference.py,sha256=z8dK546imn_YatB3qLASOjnhSoryV1zk30djIGe0KM0,5475
9
+ model2vec/distill/tokenizer.py,sha256=rUE599Zk1wxBrKqW8D5Oi3Thtgvhyjm3y188GXoI8_g,4405
10
+ model2vec/distill/utils.py,sha256=a7PVyKHYZlowYOTHL1-CoVc76OJ0jukDnRquN_nnwLQ,685
11
+ model2vec-0.2.3.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
12
+ model2vec-0.2.3.dist-info/METADATA,sha256=nzUrcBDi-HL5UXRYcQSQ4INlPeTB5_5VzLUP0VxWy58,21605
13
+ model2vec-0.2.3.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
+ model2vec-0.2.3.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
15
+ model2vec-0.2.3.dist-info/RECORD,,
@@ -1,14 +0,0 @@
1
- model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
2
- model2vec/model.py,sha256=fxqd0_pz4ahWtn4idgG_q61QyzKqqC0QcaOGu6XeHu4,8721
3
- model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
4
- model2vec/utils.py,sha256=gS4-_Lno3iDG0k1B1tbcAhqyINZeTOFDJ6gP46YPkTc,8227
5
- model2vec/distill/__init__.py,sha256=1WLSMhxifoTSpIPb-drmP4sHdroc5jHo1fTISzqP6Hg,70
6
- model2vec/distill/__main__.py,sha256=syBzxZz1zQi3UUD7KQAM0wG0W9oqHcKlAT5RX92tn0A,1738
7
- model2vec/distill/distillation.py,sha256=vQLDbgD4Si5dGK1V2LaGmTVbhHb4ALuzgmkj87-u8HY,7918
8
- model2vec/distill/inference.py,sha256=A-13qdkffeF5S__a0rTHx_O7n0iZQeyOwT3z9zqdQi0,4639
9
- model2vec/distill/tokenizer.py,sha256=-3fWtHp_Fs41uqf3TWGHAxLoyEfSbnXsCeKcz6mQTP4,2751
10
- model2vec-0.2.1.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
11
- model2vec-0.2.1.dist-info/METADATA,sha256=x_y5e33PjybvEGP_7rQ5KwdA4Xoknm0y9w1Ob0oO8tw,19435
12
- model2vec-0.2.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
13
- model2vec-0.2.1.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
14
- model2vec-0.2.1.dist-info/RECORD,,