model2vec 0.2.2__tar.gz → 0.2.4__tar.gz

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.
Files changed (42) hide show
  1. {model2vec-0.2.2 → model2vec-0.2.4}/PKG-INFO +19 -8
  2. {model2vec-0.2.2 → model2vec-0.2.4}/README.md +18 -7
  3. model2vec-0.2.4/assets/images/speed_vs_accuracy_v3.png +0 -0
  4. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/distillation.py +21 -3
  5. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/model.py +80 -8
  6. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec.egg-info/PKG-INFO +19 -8
  7. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec.egg-info/SOURCES.txt +1 -0
  8. {model2vec-0.2.2 → model2vec-0.2.4}/pyproject.toml +1 -1
  9. {model2vec-0.2.2 → model2vec-0.2.4}/tests/test_distillation.py +19 -0
  10. {model2vec-0.2.2 → model2vec-0.2.4}/tests/test_model.py +45 -2
  11. {model2vec-0.2.2 → model2vec-0.2.4}/uv.lock +1 -1
  12. {model2vec-0.2.2 → model2vec-0.2.4}/.github/workflows/ci.yaml +0 -0
  13. {model2vec-0.2.2 → model2vec-0.2.4}/.gitignore +0 -0
  14. {model2vec-0.2.2 → model2vec-0.2.4}/.pre-commit-config.yaml +0 -0
  15. {model2vec-0.2.2 → model2vec-0.2.4}/LICENSE +0 -0
  16. {model2vec-0.2.2 → model2vec-0.2.4}/Makefile +0 -0
  17. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/logo.png +0 -0
  18. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/model2vec_model_diagram.png +0 -0
  19. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  20. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/speed_vs_accuracy.png +0 -0
  21. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/speed_vs_accuracy_v2.png +0 -0
  22. {model2vec-0.2.2 → model2vec-0.2.4}/assets/images/tutorial_ezlo.png +0 -0
  23. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/__init__.py +0 -0
  24. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/__init__.py +0 -0
  25. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/__main__.py +0 -0
  26. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/inference.py +0 -0
  27. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/tokenizer.py +0 -0
  28. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/distill/utils.py +0 -0
  29. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/model_card_template.md +0 -0
  30. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec/utils.py +0 -0
  31. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec.egg-info/dependency_links.txt +0 -0
  32. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec.egg-info/requires.txt +0 -0
  33. {model2vec-0.2.2 → model2vec-0.2.4}/model2vec.egg-info/top_level.txt +0 -0
  34. {model2vec-0.2.2 → model2vec-0.2.4}/setup.cfg +0 -0
  35. {model2vec-0.2.2 → model2vec-0.2.4}/tests/__init__.py +0 -0
  36. {model2vec-0.2.2 → model2vec-0.2.4}/tests/conftest.py +0 -0
  37. {model2vec-0.2.2 → model2vec-0.2.4}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  38. {model2vec-0.2.2 → model2vec-0.2.4}/tests/data/test_tokenizer/tokenizer.json +0 -0
  39. {model2vec-0.2.2 → model2vec-0.2.4}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  40. {model2vec-0.2.2 → model2vec-0.2.4}/tests/test_utils.py +0 -0
  41. {model2vec-0.2.2 → model2vec-0.2.4}/tutorials/README.md +0 -0
  42. {model2vec-0.2.2 → model2vec-0.2.4}/tutorials/recipe_search.ipynb +0 -0
@@ -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
 
@@ -70,6 +70,9 @@ model = StaticModel.from_pretrained(model_name)
70
70
 
71
71
  # Make embeddings
72
72
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
73
+
74
+ # Make sequences of token embeddings
75
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
73
76
  ```
74
77
 
75
78
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
@@ -110,7 +113,7 @@ Distillation is really fast, and only takes about 5 seconds on a 2024 macbook us
110
113
 
111
114
  ## What is Model2Vec?
112
115
 
113
- 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.
116
+ 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.
114
117
 
115
118
  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.
116
119
 
@@ -195,6 +198,9 @@ model = StaticModel.from_pretrained(model_name, token=None)
195
198
 
196
199
  # Make embeddings
197
200
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
201
+
202
+ # Make sequences of token embeddings
203
+ token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
198
204
  ```
199
205
 
200
206
  ### Evaluating a Model2Vec model
@@ -252,13 +258,15 @@ print(make_leaderboard(task_scores))
252
258
  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.
253
259
 
254
260
 
261
+
255
262
  | Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim |
256
- |------------------------|-----------|------------|--------|--------|-----------|--------|--------|--------|--------|--------|---------|
263
+ |:-----------------------|:---------:|:----------:|:------:|:------:|:---------:|:------:|:------:|:------:|:------:|:------:|:-------:|
257
264
  | 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 |
258
265
  | 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 |
259
- | 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 |
260
- | 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 |
261
- | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.3 | 22.78 | 61.9 | 28.81 | 45.65 | 43.05 |
266
+ | 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 |
267
+ | 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 |
268
+ | GloVe_300d | 42.84 | 42.36 | 57.31 | 27.66 | 72.48 | 43.30 | 22.78 | 61.90 | 28.81 | 45.65 | 43.05 |
269
+ | 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 |
262
270
  | WL256* | 48.88 | 49.36 | 58.98 | 33.34 | 74.00 | 52.03 | 33.12 | 73.34 | 29.05 | 48.81 | 45.16 |
263
271
 
264
272
 
@@ -282,22 +290,25 @@ For readability, the MTEB task names are abbreviated as follows:
282
290
 
283
291
  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.
284
292
 
293
+
285
294
  | Model | Average | SST2 | IMDB | TREC | AG News |
286
295
  |:-----------------------|:-------:|:------:|:-----:|:------:|:-------:|
287
296
  | bge-base-en-v1.5 | 90.00 | 91.54 | 91.88 | 85.16 | 91.45 |
288
297
  | all-MiniLM-L6-v2 | 84.10 | 83.95 | 81.36 | 81.31 | 89.77 |
289
298
  | M2V_base_output | 82.23 | 80.92 | 84.56 | 75.27 | 88.17 |
290
299
  | M2V_base_glove_subword | 81.95 | 82.84 | 85.96 | 70.51 | 88.49 |
300
+ | BPEmb_50k_300d | 81.15 | 80.42 | 84.04 | 71.25 | 88.92 |
291
301
  | M2V_base_glove | 80.76 | 83.07 | 85.24 | 66.12 | 88.61 |
292
302
  | WL256 | 78.48 | 76.88 | 80.12 | 69.23 | 87.68 |
293
303
  | GloVe_300d | 77.77 | 81.68 | 84.00 | 55.67 | 89.71 |
294
304
 
295
- 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.
305
+
306
+ 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.
296
307
 
297
308
  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).
298
309
  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.
299
310
 
300
- | ![Description](assets/images/speed_vs_accuracy_v2.png) |
311
+ | ![Description](assets/images/speed_vs_accuracy_v3.png) |
301
312
  |:--:|
302
313
  |*Figure: The average accuracy over all classification datasets plotted against sentence per second. The circle size indicates model size.*|
303
314
 
@@ -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
@@ -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
 
@@ -11,6 +11,7 @@ assets/images/model2vec_model_diagram.png
11
11
  assets/images/sentences_per_second_vs_average_score.png
12
12
  assets/images/speed_vs_accuracy.png
13
13
  assets/images/speed_vs_accuracy_v2.png
14
+ assets/images/speed_vs_accuracy_v3.png
14
15
  assets/images/tutorial_ezlo.png
15
16
  model2vec/__init__.py
16
17
  model2vec/model.py
@@ -3,7 +3,7 @@ name = "model2vec"
3
3
  description = "Distill a Small Fast Model from any Sentence Transformer"
4
4
  readme = { file = "README.md", content-type = "text/markdown" }
5
5
  license = { file = "LICENSE" }
6
- version = "0.2.2"
6
+ version = "0.2.4"
7
7
  requires-python = ">=3.10"
8
8
  authors = [{ name = "Stéphan Tulkens", email = "stephantul@gmail.com"}, {name = "Thomas van Dongen", email = "thomas123@live.nl"}]
9
9
 
@@ -10,6 +10,13 @@ from transformers import AutoModel, BertTokenizerFast
10
10
  from model2vec.distill.distillation import _clean_vocabulary, _post_process_embeddings, distill, distill_from_model
11
11
  from model2vec.model import StaticModel
12
12
 
13
+ try:
14
+ # For huggingface_hub>=0.25.0
15
+ from huggingface_hub.errors import RepositoryNotFoundError
16
+ except ImportError:
17
+ # For huggingface_hub<0.25.0
18
+ from huggingface_hub.utils._errors import RepositoryNotFoundError
19
+
13
20
  rng = np.random.default_rng()
14
21
 
15
22
 
@@ -157,6 +164,18 @@ def test_distill(
157
164
  assert static_model.tokenizer is not None
158
165
 
159
166
 
167
+ @patch.object(import_module("model2vec.distill.distillation"), "model_info")
168
+ def test_missing_modelinfo(
169
+ mock_model_info: MagicMock,
170
+ mock_transformer: AutoModel,
171
+ mock_berttokenizer: BertTokenizerFast,
172
+ ) -> None:
173
+ """Test that missing model info does not crash."""
174
+ mock_model_info.side_effect = RepositoryNotFoundError("Model not found")
175
+ static_model = distill_from_model(model=mock_transformer, tokenizer=mock_berttokenizer, device="cpu")
176
+ assert static_model.language is None
177
+
178
+
160
179
  @pytest.mark.parametrize(
161
180
  "embeddings, pca_dims, apply_zipf, expected_shape",
162
181
  [
@@ -28,7 +28,7 @@ def test_encode_single_sentence(
28
28
  ) -> None:
29
29
  """Test encoding of a single sentence."""
30
30
  model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
31
- encoded = model.encode("test sentence")
31
+ encoded = model.encode("word1 word2")
32
32
  assert encoded.shape == (2,)
33
33
 
34
34
 
@@ -37,10 +37,46 @@ def test_encode_multiple_sentences(
37
37
  ) -> None:
38
38
  """Test encoding of multiple sentences."""
39
39
  model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
40
- encoded = model.encode(["sentence 1", "sentence 2"])
40
+ encoded = model.encode(["word1 word2", "word1 word3"])
41
41
  assert encoded.shape == (2, 2)
42
42
 
43
43
 
44
+ def test_encode_as_tokens(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]) -> None:
45
+ """Test encoding of sentences as tokens."""
46
+ sentences = ["word1 word2", "word1 word3"]
47
+ model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
48
+ encoded_sequence = model.encode_as_sequence(sentences)
49
+ encoded = model.encode(sentences)
50
+
51
+ assert len(encoded_sequence) == 2
52
+
53
+ means = [np.mean(sequence, axis=0) for sequence in encoded_sequence]
54
+ assert np.allclose(means, encoded)
55
+
56
+
57
+ def test_encode_as_tokens_empty(
58
+ mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]
59
+ ) -> None:
60
+ """Test encoding of an empty list of sentences."""
61
+ model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
62
+ encoded = model.encode_as_sequence("")
63
+ assert np.array_equal(encoded, np.zeros(shape=(0, 2), dtype=model.embedding.weight.numpy().dtype))
64
+
65
+ encoded = model.encode_as_sequence(["", ""])
66
+ out = [np.zeros(shape=(0, 2), dtype=model.embedding.weight.numpy().dtype) for _ in range(2)]
67
+ assert np.array_equal(encoded, out)
68
+
69
+
70
+ def test_forward(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]) -> None:
71
+ """Test forward pass of the model."""
72
+ model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
73
+ encoded = model.forward(model.tokenize(["word1 word2"]))
74
+ assert encoded.shape == (1, model.embedding.weight.shape[1])
75
+
76
+ encoded = model.forward(model.tokenize(["word1", "word1 word2 word1"]))
77
+ assert encoded.shape == (2, model.embedding.weight.shape[1])
78
+
79
+
44
80
  def test_encode_empty_sentence(
45
81
  mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]
46
82
  ) -> None:
@@ -124,3 +160,10 @@ def test_set_normalize(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> N
124
160
  assert model.config == {"normalize": False}
125
161
  model.normalize = True
126
162
  assert model.config == {"normalize": True}
163
+
164
+
165
+ def test_dim(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]) -> None:
166
+ """Tests the dimensionality of the model."""
167
+ model = StaticModel(mock_vectors, mock_tokenizer, mock_config)
168
+ assert model.dim == 2
169
+ assert model.dim == model.embedding.weight.shape[1]
@@ -433,7 +433,7 @@ wheels = [
433
433
 
434
434
  [[package]]
435
435
  name = "model2vec"
436
- version = "0.2.1"
436
+ version = "0.2.2"
437
437
  source = { editable = "." }
438
438
  dependencies = [
439
439
  { name = "click" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes