model2vec 0.2.2__py3-none-any.whl → 0.2.4__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.
@@ -15,6 +15,14 @@ from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remov
15
15
  from model2vec.distill.utils import select_optimal_device
16
16
  from model2vec.model import StaticModel
17
17
 
18
+ try:
19
+ # For huggingface_hub>=0.25.0
20
+ from huggingface_hub.errors import RepositoryNotFoundError
21
+ except ImportError:
22
+ # For huggingface_hub<0.25.0
23
+ from huggingface_hub.utils._errors import RepositoryNotFoundError
24
+
25
+
18
26
  logger = logging.getLogger(__name__)
19
27
 
20
28
 
@@ -125,10 +133,20 @@ def distill_from_model(
125
133
 
126
134
  model_name = getattr(model, "name_or_path", "")
127
135
 
128
- config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
136
+ config = {
137
+ "tokenizer_name": model_name,
138
+ "apply_pca": pca_dims,
139
+ "apply_zipf": apply_zipf,
140
+ "hidden_dim": embeddings.shape[1],
141
+ "seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
142
+ }
129
143
  # Get the language from the model card
130
- info = model_info(model_name)
131
- language = info.cardData.get("language")
144
+ try:
145
+ info = model_info(model_name)
146
+ language = info.cardData.get("language")
147
+ except RepositoryNotFoundError:
148
+ logger.info("No model info found for model. Setting `language` to None.")
149
+ language = None
132
150
 
133
151
  return StaticModel(
134
152
  vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
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.2
3
+ Version: 0.2.4
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.
@@ -173,7 +176,7 @@ Distillation is really fast, and only takes about 5 seconds on a 2024 macbook us
173
176
 
174
177
  ## What is Model2Vec?
175
178
 
176
- 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.
177
180
 
178
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.
179
182
 
@@ -258,6 +261,9 @@ model = StaticModel.from_pretrained(model_name, token=None)
258
261
 
259
262
  # Make embeddings
260
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."])
261
267
  ```
262
268
 
263
269
  ### Evaluating a Model2Vec model
@@ -315,13 +321,15 @@ print(make_leaderboard(task_scores))
315
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.
316
322
 
317
323
 
324
+
318
325
  | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
319
- |------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
326
+ |:-----------------------|:---------:|:----------:|:------:|:------:|:---------:|:------:|:------:|:------:|:------:|:------:|:-------:|
320
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 |
321
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 |
322
- | M2V_base_glove | 48.58 | 47.6 | 61.35 | 30.52 | 75.34 | 48.5 | 29.26 | 70.31 | 31.5 | 50.28 | 54.29 |
323
- | M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 |
324
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
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 |
325
333
  | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
326
334
 
327
335
 
@@ -345,22 +353,25 @@ For readability, the MTEB task names are abbreviated as follows:
345
353
 
346
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.
347
355
 
356
+
348
357
  | Model | Average | SST2 | IMDB | TREC | AG News |
349
358
  |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
350
359
  | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
351
360
  | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
352
361
  | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
353
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 |
354
364
  | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
355
365
  | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
356
366
  | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
357
367
 
358
- As can be seen, Model2Vec models outperform the GloVe and WL256 models on all classification tasks, and are competitive with the all-MiniLM-L6-v2 model, while being much faster.
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.
359
370
 
360
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).
361
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.
362
373
 
363
- | ![Description](assets/images/speed_vs_accuracy_v2.png) |
374
+ | ![Description](assets/images/speed_vs_accuracy_v3.png) |
364
375
  |:--:|
365
376
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
366
377
 
@@ -1,15 +1,15 @@
1
1
  model2vec/__init__.py,sha256=H2Tjvc5jvBNMNKsk4nYdrvDZeeLL__nog7bcM6r5ppw,116
2
- model2vec/model.py,sha256=fxqd0_pz4ahWtn4idgG_q61QyzKqqC0QcaOGu6XeHu4,8721
2
+ model2vec/model.py,sha256=beLes7Nf3tTgBFCvPbeimtyRPDUsCEJNN5RD7MwZrHM,11420
3
3
  model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
4
4
  model2vec/utils.py,sha256=gS4-_Lno3iDG0k1B1tbcAhqyINZeTOFDJ6gP46YPkTc,8227
5
5
  model2vec/distill/__init__.py,sha256=M5kp6RGYBsKQ6tqnoZiguPZomaR093cj-oxkV3Sdp1k,116
6
6
  model2vec/distill/__main__.py,sha256=syBzxZz1zQi3UUD7KQAM0wG0W9oqHcKlAT5RX92tn0A,1738
7
- model2vec/distill/distillation.py,sha256=cpK27cB_15AuLMR7nauSNH2R9x7kiRPsUCBHLMvKwdc,10386
7
+ model2vec/distill/distillation.py,sha256=iTApiheYzN6rPSvAVTehhN3P8HORhTrRyjksp4qqI1M,10950
8
8
  model2vec/distill/inference.py,sha256=z8dK546imn_YatB3qLASOjnhSoryV1zk30djIGe0KM0,5475
9
9
  model2vec/distill/tokenizer.py,sha256=rUE599Zk1wxBrKqW8D5Oi3Thtgvhyjm3y188GXoI8_g,4405
10
10
  model2vec/distill/utils.py,sha256=a7PVyKHYZlowYOTHL1-CoVc76OJ0jukDnRquN_nnwLQ,685
11
- model2vec-0.2.2.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
12
- model2vec-0.2.2.dist-info/METADATA,sha256=iHvx07imW0L7XMm5fIxshocf9ZV5gmY9vJ5HmUl-BE0,21010
13
- model2vec-0.2.2.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
- model2vec-0.2.2.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
15
- model2vec-0.2.2.dist-info/RECORD,,
11
+ model2vec-0.2.4.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
12
+ model2vec-0.2.4.dist-info/METADATA,sha256=MvlUOjHfr1EwLuqBLiXitAP_iib4EWKW4QGdi5ivkss,21605
13
+ model2vec-0.2.4.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
+ model2vec-0.2.4.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
15
+ model2vec-0.2.4.dist-info/RECORD,,