model2vec 0.3.7__py3-none-any.whl → 0.3.8__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.
@@ -13,8 +13,8 @@ from tokenizers.models import BPE, Unigram
13
13
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
14
14
 
15
15
  from model2vec.distill.inference import (
16
- create_output_embeddings_from_model_name,
17
- create_output_embeddings_from_model_name_and_tokens,
16
+ create_output_embeddings_from_model,
17
+ create_output_embeddings_from_model_and_tokens,
18
18
  )
19
19
  from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
20
20
  from model2vec.distill.utils import select_optimal_device
@@ -31,7 +31,7 @@ except ImportError:
31
31
  logger = logging.getLogger(__name__)
32
32
 
33
33
 
34
- PCADimType = Union[int, None, Literal["auto"]]
34
+ PCADimType = Union[int, None, float, Literal["auto"]]
35
35
 
36
36
 
37
37
  def distill_from_model(
@@ -88,7 +88,7 @@ def distill_from_model(
88
88
  tokens: list[str] = []
89
89
  if use_subword:
90
90
  # Create the subword embeddings.
91
- tokens, embeddings = create_output_embeddings_from_model_name(model=model, tokenizer=tokenizer, device=device)
91
+ tokens, embeddings = create_output_embeddings_from_model(model=model, tokenizer=tokenizer, device=device)
92
92
  new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
93
93
  else:
94
94
  # We need to keep the unk token in the tokenizer.
@@ -111,7 +111,7 @@ def distill_from_model(
111
111
  # Only create embeddings if we have tokens to add.
112
112
  if cleaned_vocabulary:
113
113
  # Create the embeddings.
114
- _, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
114
+ _, token_embeddings = create_output_embeddings_from_model_and_tokens(
115
115
  model=model,
116
116
  tokenizer=tokenizer,
117
117
  tokens=cleaned_vocabulary,
@@ -185,6 +185,10 @@ def _remove_tokens_and_embeddings(
185
185
 
186
186
  # Remove the unused tokens from the tokenizer.
187
187
  new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
188
+ if new_tokenizer.get_vocab_size() == tokenizer.backend_tokenizer.get_vocab_size():
189
+ # This happens if we didn't remove any tokens.
190
+ return new_tokenizer, embeddings
191
+
188
192
  # Remove the embeddings of the unused tokens.
189
193
  embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
190
194
  logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
@@ -199,6 +203,7 @@ def distill(
199
203
  pca_dims: PCADimType = 256,
200
204
  apply_zipf: bool = True,
201
205
  use_subword: bool = True,
206
+ token_remove_pattern: str | None = r"\[unused\d+\]",
202
207
  ) -> StaticModel:
203
208
  """
204
209
  Distill a staticmodel from a sentence transformer.
@@ -217,6 +222,7 @@ def distill(
217
222
  If this is 'auto', we don't reduce dimenionality, but still apply PCA.
218
223
  :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
219
224
  :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.
225
+ :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
220
226
  :return: A StaticModel
221
227
 
222
228
  """
@@ -231,6 +237,7 @@ def distill(
231
237
  pca_dims=pca_dims,
232
238
  apply_zipf=apply_zipf,
233
239
  use_subword=use_subword,
240
+ token_remove_pattern=token_remove_pattern,
234
241
  )
235
242
 
236
243
 
@@ -251,10 +258,13 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
251
258
  f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
252
259
  )
253
260
  elif pca_dims <= embeddings.shape[1]:
254
- logger.info(f"Applying PCA with n_components {pca_dims}")
261
+ if isinstance(pca_dims, float):
262
+ logger.info(f"Applying PCA with {pca_dims} explained variance.")
263
+ else:
264
+ logger.info(f"Applying PCA with n_components {pca_dims}")
255
265
 
256
266
  orig_dims = embeddings.shape[1]
257
- p = PCA(n_components=pca_dims, whiten=False)
267
+ p = PCA(n_components=pca_dims, svd_solver="full")
258
268
  embeddings = p.fit_transform(embeddings)
259
269
 
260
270
  if embeddings.shape[1] < orig_dims:
@@ -24,18 +24,19 @@ class ModulewithWeights(Protocol):
24
24
  weight: torch.nn.Parameter
25
25
 
26
26
 
27
- def create_output_embeddings_from_model_name_and_tokens(
27
+ def create_output_embeddings_from_model_and_tokens(
28
28
  model: PreTrainedModel,
29
29
  tokenizer: PreTrainedTokenizer,
30
30
  tokens: list[str],
31
31
  device: str,
32
32
  ) -> tuple[list[str], np.ndarray]:
33
33
  """
34
- Create output embeddings for a bunch of tokens from a model name.
34
+ Create output embeddings for a bunch of tokens using a pretrained model.
35
35
 
36
- It does a forward pass for all tokens passed in tokens.
36
+ It does a forward pass for all tokens passed in `tokens`.
37
37
 
38
- :param model: The model name to use.
38
+ :param model: The model to use.
39
+ This should be a transformers model.
39
40
  :param tokenizer: The tokenizer to use.
40
41
  :param tokens: The tokens to use.
41
42
  :param device: The torch device to use.
@@ -99,17 +100,18 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
99
100
  return result / divisor[:, None]
100
101
 
101
102
 
102
- def create_output_embeddings_from_model_name(
103
+ def create_output_embeddings_from_model(
103
104
  model: PreTrainedModel,
104
105
  tokenizer: PreTrainedTokenizer,
105
106
  device: str,
106
107
  ) -> tuple[list[str], np.ndarray]:
107
108
  """
108
- Create output embeddings for a bunch of tokens from a model name.
109
+ Create output embeddings for a bunch of tokens using a pretrained model.
109
110
 
110
- It does a forward pass for all ids in the tokenizer.
111
+ It does a forward pass for all tokens passed in the tokenizer vocabulary.
111
112
 
112
- :param model: The model name to use.
113
+ :param model: The model to use.
114
+ This should be a transformers model.
113
115
  :param tokenizer: The tokenizer to use.
114
116
  :param device: The torch device to use.
115
117
  :return: The tokens and output embeddings.
@@ -157,7 +159,7 @@ def create_output_embeddings_from_model_name(
157
159
  out = out.float()
158
160
 
159
161
  # Add the output to the intermediate weights
160
- intermediate_weights.append(out[:, 1].detach().cpu().numpy())
162
+ intermediate_weights.append(out.mean(1).detach().cpu().numpy())
161
163
 
162
164
  # Concatenate the intermediate weights
163
165
  out_weights = np.concatenate(intermediate_weights)
model2vec/hf_utils.py CHANGED
@@ -6,7 +6,6 @@ from pathlib import Path
6
6
  from typing import Any, cast
7
7
 
8
8
  import huggingface_hub
9
- import huggingface_hub.errors
10
9
  import numpy as np
11
10
  import safetensors
12
11
  from huggingface_hub import ModelCard, ModelCardData
model2vec/model.py CHANGED
@@ -35,7 +35,7 @@ class StaticModel:
35
35
  :param vectors: The vectors to use.
36
36
  :param tokenizer: The Transformers tokenizer to use.
37
37
  :param config: Any metadata config.
38
- :param normalize: Whether to normalize.
38
+ :param normalize: Whether to normalize the embeddings.
39
39
  :param base_model_name: The used base model name. Used for creating a model card.
40
40
  :param language: The language of the model. Used for creating a model card.
41
41
  :raises: ValueError if the number of tokens does not match the number of vectors.
@@ -114,13 +114,14 @@ class StaticModel:
114
114
  model_name=model_name,
115
115
  )
116
116
 
117
- def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[int]:
117
+ def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[list[int]]:
118
118
  """
119
- Tokenize a sentence.
119
+ Tokenize a list of sentences.
120
120
 
121
- :param sentences: The sentence to tokenize.
122
- :param max_length: The maximum length of the sentence.
123
- :return: The tokens.
121
+ :param sentences: The sentences to tokenize.
122
+ :param max_length: The maximum length of the sentences in tokens. If this is None, sequences
123
+ are not truncated.
124
+ :return: A list of list of tokens.
124
125
  """
125
126
  if max_length is not None:
126
127
  m = max_length * self.median_token_length
@@ -148,6 +149,7 @@ class StaticModel:
148
149
  cls: type[StaticModel],
149
150
  path: PathLike,
150
151
  token: str | None = None,
152
+ normalize: bool | None = None,
151
153
  ) -> StaticModel:
152
154
  """
153
155
  Load a StaticModel from a local path or huggingface hub path.
@@ -156,6 +158,7 @@ class StaticModel:
156
158
 
157
159
  :param path: The path to load your static model from.
158
160
  :param token: The huggingface token to use.
161
+ :param normalize: Whether to normalize the embeddings.
159
162
  :return: A StaticModel
160
163
  """
161
164
  from model2vec.hf_utils import load_pretrained
@@ -163,7 +166,12 @@ class StaticModel:
163
166
  embeddings, tokenizer, config, metadata = load_pretrained(path, token=token, from_sentence_transformers=False)
164
167
 
165
168
  return cls(
166
- embeddings, tokenizer, config, base_model_name=metadata.get("base_model"), language=metadata.get("language")
169
+ embeddings,
170
+ tokenizer,
171
+ config,
172
+ normalize=normalize,
173
+ base_model_name=metadata.get("base_model"),
174
+ language=metadata.get("language"),
167
175
  )
168
176
 
169
177
  @classmethod
@@ -171,6 +179,7 @@ class StaticModel:
171
179
  cls: type[StaticModel],
172
180
  path: PathLike,
173
181
  token: str | None = None,
182
+ normalize: bool | None = None,
174
183
  ) -> StaticModel:
175
184
  """
176
185
  Load a StaticModel trained with sentence transformers from a local path or huggingface hub path.
@@ -179,13 +188,14 @@ class StaticModel:
179
188
 
180
189
  :param path: The path to load your static model from.
181
190
  :param token: The huggingface token to use.
191
+ :param normalize: Whether to normalize the embeddings.
182
192
  :return: A StaticModel
183
193
  """
184
194
  from model2vec.hf_utils import load_pretrained
185
195
 
186
196
  embeddings, tokenizer, config, _ = load_pretrained(path, token=token, from_sentence_transformers=True)
187
197
 
188
- return cls(embeddings, tokenizer, config, base_model_name=None, language=None)
198
+ return cls(embeddings, tokenizer, config, normalize=normalize, base_model_name=None, language=None)
189
199
 
190
200
  def encode_as_sequence(
191
201
  self,
model2vec/version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version_triple__ = (0, 3, 7)
1
+ __version_triple__ = (0, 3, 8)
2
2
  __version__ = ".".join(map(str, __version_triple__))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: model2vec
3
- Version: 0.3.7
3
+ Version: 0.3.8
4
4
  Summary: The Fastest State-of-the-Art Static Embeddings in the World
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
@@ -0,0 +1,16 @@
1
+ model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
2
+ model2vec/hf_utils.py,sha256=dVPM1mIWH66YbR276nkSbC3zQgWxUQJ0CovIQFAkxNc,8048
3
+ model2vec/model.py,sha256=ZYEw0Ha5pHp2hsmLVksJCK5tQdfnmpl6bjrmMmvwiXE,15575
4
+ model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
5
+ model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
6
+ model2vec/version.py,sha256=Zs4ODyWXIJNcomKz9kvL2EwEcCyHneVYB-hkWBBp_Rc,84
7
+ model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
8
+ model2vec/distill/distillation.py,sha256=tryRpxcJ2Itho06vl4K1V8MExSgT1NVKAswWg315e64,13838
9
+ model2vec/distill/inference.py,sha256=peUpPvt6S_pmmp0Xzu0Ty1TGrW7NKP0dd6qqVyVjNDw,6232
10
+ model2vec/distill/tokenizer.py,sha256=QSSH3qKqP19_DUu2JamRXOv_2_I-bL2Sty0A8q4pCPw,4339
11
+ model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
12
+ model2vec-0.3.8.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
13
+ model2vec-0.3.8.dist-info/METADATA,sha256=HsSpgiItwCzqURnLLvzhZdpw2Mm5UeFZ5A6BG4qHQsY,26138
14
+ model2vec-0.3.8.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
15
+ model2vec-0.3.8.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
16
+ model2vec-0.3.8.dist-info/RECORD,,
@@ -1,16 +0,0 @@
1
- model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
2
- model2vec/hf_utils.py,sha256=LDhGOeZ0qnzqTKM5SiciD8vdHRNgZWurWZpOjHunXqA,8078
3
- model2vec/model.py,sha256=wdP7Otk2DmUt4I1ntC9hRX8ION3sfeTfxVKUYRXYHDg,15154
4
- model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
5
- model2vec/utils.py,sha256=ixAAtgKCxoPNn1FgUs6_KrUVV0UnwfAiAtz8DzdZmyc,4351
6
- model2vec/version.py,sha256=0VIUsE13cvKVSjrf_LfnHuniEHsv2yQKzJP1_yibN70,84
7
- model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
8
- model2vec/distill/distillation.py,sha256=xAEFJZAFdLJLySes2WozIgePvgti6LNgIOr5CD7YCmc,13233
9
- model2vec/distill/inference.py,sha256=QgHAEkLoeq-jPyKnFTB6p6Ry-ZGZqonkZaEg2S7VTOY,6123
10
- model2vec/distill/tokenizer.py,sha256=QSSH3qKqP19_DUu2JamRXOv_2_I-bL2Sty0A8q4pCPw,4339
11
- model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
12
- model2vec-0.3.7.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
13
- model2vec-0.3.7.dist-info/METADATA,sha256=1r0pwe8crS9hugMp28muLyiY30-18bxTZgRNUDglre4,26138
14
- model2vec-0.3.7.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
15
- model2vec-0.3.7.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
16
- model2vec-0.3.7.dist-info/RECORD,,