model2vec 0.3.0__py3-none-any.whl → 0.3.2__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.
@@ -115,7 +115,15 @@ def create_output_embeddings_from_model_name(
115
115
  :return: The tokens and output embeddings.
116
116
  """
117
117
  model = model.to(device)
118
- ids = torch.arange(tokenizer.vocab_size)
118
+
119
+ # Quick check to see if the tokenizer is consistent.
120
+ vocab_length = len(tokenizer.get_vocab())
121
+ if vocab_length != tokenizer.vocab_size:
122
+ logger.warning(
123
+ f"Reported vocab size {tokenizer.vocab_size} is inconsistent with the vocab size {vocab_length}."
124
+ )
125
+
126
+ ids = torch.arange(vocab_length)
119
127
 
120
128
  # Work-around to get the eos and bos token ids without having to go into tokenizer internals.
121
129
  dummy_encoding = tokenizer.encode("A")
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import logging
5
+ from typing import Any
5
6
 
6
7
  from tokenizers import Tokenizer
7
8
 
@@ -36,11 +37,11 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
36
37
  logger.info("No tokens to remove.")
37
38
  return Tokenizer.from_str(tokenizer.to_str())
38
39
 
39
- tokenizer_data = json.loads(tokenizer.to_str())
40
+ tokenizer_data: dict[str, Any] = json.loads(tokenizer.to_str())
40
41
 
41
42
  # Find all added tokens
42
- added_tokens = tokenizer_data["added_tokens"]
43
- added_tokens_str = {token["content"] for token in added_tokens}
43
+ added_tokens: list[dict[str, Any]] = tokenizer_data.get("added_tokens", [])
44
+ added_tokens_str: set[str] = {token["content"] for token in added_tokens}
44
45
 
45
46
  # Remove all added tokens from the list of tokens to remove.
46
47
  # Things will go bad if we keep them.
@@ -76,9 +77,9 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
76
77
  raise ValueError(f"Unknown model type {model_type}")
77
78
 
78
79
  # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
79
- special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
80
- for token, token_data in special_tokens_post_processor.items():
81
- token_data["ids"] = [reindexed[token] for token in token_data["tokens"]]
80
+ added_tokens = tokenizer_data.get("added_tokens", [])
81
+ for token_data in added_tokens:
82
+ token_data["id"] = reindexed[token_data["content"]]
82
83
 
83
84
  # Reinitialize the tokenizer from the json.
84
85
  tokenizer = Tokenizer.from_str(json.dumps(tokenizer_data))
model2vec/model.py CHANGED
@@ -59,6 +59,10 @@ class StaticModel:
59
59
  self.config = config or {}
60
60
  self.base_model_name = base_model_name
61
61
  self.language = language
62
+ if hasattr(self.tokenizer, "encode_batch_fast"):
63
+ self._can_encode_fast = True
64
+ else:
65
+ self._can_encode_fast = False
62
66
 
63
67
  if normalize is not None:
64
68
  self.normalize = normalize
@@ -121,7 +125,11 @@ class StaticModel:
121
125
  m = max_length * self.median_token_length
122
126
  sentences = [sentence[:m] for sentence in sentences]
123
127
 
124
- encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False)
128
+ if self._can_encode_fast:
129
+ encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False)
130
+ else:
131
+ encodings = self.tokenizer.encode_batch(sentences, add_special_tokens=False)
132
+
125
133
  encodings_ids = [encoding.ids for encoding in encodings]
126
134
 
127
135
  if self.unk_token_id is not None:
@@ -264,7 +272,8 @@ class StaticModel:
264
272
 
265
273
  out_array = np.stack(out)
266
274
  if self.normalize:
267
- out_array = out_array / np.linalg.norm(out_array, axis=1, keepdims=True)
275
+ norm = np.linalg.norm(out_array, axis=1, keepdims=True) + 1e-32
276
+ out_array = out_array / norm
268
277
 
269
278
  return out_array
270
279
 
model2vec/utils.py CHANGED
@@ -26,17 +26,19 @@ _MODULE_MAP = (("scikit-learn", "sklearn"),)
26
26
 
27
27
  def get_package_extras(package: str, extra: str) -> Iterator[str]:
28
28
  """Get the extras of the package."""
29
- message = metadata(package)
29
+ try:
30
+ message = metadata(package)
31
+ except Exception as e:
32
+ raise ImportError(f"Could not retrieve metadata for package '{package}': {e}")
33
+
30
34
  all_packages = message.get_all("Requires-Dist") or []
31
35
  for package in all_packages:
32
36
  name, *rest = package.split(";", maxsplit=1)
33
- if not rest:
34
- continue
35
- _, found_extra = rest[0].split("==", maxsplit=1)
36
- # Strip off quotes
37
- found_extra = found_extra.strip(' "')
38
- if found_extra == extra:
39
- yield name
37
+ if rest:
38
+ # Extract and clean the extra requirement
39
+ found_extra = rest[0].split("==")[-1].strip(" \"'")
40
+ if found_extra == extra:
41
+ yield name.strip()
40
42
 
41
43
 
42
44
  def importable(module: str, extra: str) -> None:
model2vec/version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version_triple__ = (0, 3, 0)
1
+ __version_triple__ = (0, 3, 2)
2
2
  __version__ = ".".join(map(str, __version_triple__))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Distill a Small Static 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
@@ -47,6 +47,7 @@ Requires-Dist: numpy
47
47
  Requires-Dist: rich
48
48
  Requires-Dist: tqdm
49
49
  Requires-Dist: tokenizers >=0.20
50
+ Requires-Dist: safetensors
50
51
  Requires-Dist: setuptools
51
52
  Provides-Extra: dev
52
53
  Requires-Dist: black ; extra == 'dev'
@@ -104,14 +105,19 @@ Requires-Dist: scikit-learn ; extra == 'distill'
104
105
 
105
106
  Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. See our results [here](results/README.md), or dive in to see how it works.
106
107
 
108
+
109
+ ## Updates & Announcements
110
+
111
+ - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
112
+
107
113
  ## Table of Contents
108
114
  - [Quickstart](#quickstart)
109
115
  - [Main Features](#main-features)
110
116
  - [What is Model2Vec?](#what-is-model2vec)
111
117
  - [Usage](#usage)
112
- - [Distilling a Model2Vec model](#distilling-a-model2vec-model)
113
- - [Inferencing a Model2Vec model](#inference-with-a-model2vec-model)
114
- - [Evaluating a Model2Vec model](#evaluating-a-model2vec-model)
118
+ - [Distillation](#distillation)
119
+ - [Inference](#inference)
120
+ - [Evaluation](#evaluation)
115
121
  - [Model List](#model-list)
116
122
  - [Results](#results)
117
123
  - [Related Work](#related-work)
@@ -134,8 +140,8 @@ The easiest way to get started with Model2Vec is to download one of our [flagshi
134
140
  ```python
135
141
  from model2vec import StaticModel
136
142
 
137
- # Load a model from the HuggingFace hub (in this case the M2V_base_output model)
138
- model_name = "minishlab/M2V_base_output"
143
+ # Load a model from the HuggingFace hub (in this case the potion-base-8M model)
144
+ model_name = "minishlab/potion-base-8M"
139
145
  model = StaticModel.from_pretrained(model_name)
140
146
 
141
147
  # Make embeddings
@@ -169,7 +175,7 @@ from sentence_transformers import SentenceTransformer
169
175
  from sentence_transformers.models import StaticEmbedding
170
176
 
171
177
  # Initialize a StaticEmbedding module
172
- static_embedding = StaticEmbedding.from_model2vec("minishlab/M2V_base_output")
178
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
173
179
  model = SentenceTransformer(modules=[static_embedding])
174
180
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
175
181
  ```
@@ -215,6 +221,9 @@ Model2vec has 3 modes:
215
221
 
216
222
  For a technical deepdive into Model2Vec, please refer to our [blog post](https://huggingface.co/blog/Pringled/model2vec).
217
223
 
224
+ ### Tokenlearn
225
+
226
+ Our flagship POTION models are pre-trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). This method is described in our [Tokenlearn blogpost](https://minishlab.github.io/tokenlearn_blogpost/).
218
227
 
219
228
 
220
229
  ## Usage
@@ -328,7 +337,7 @@ Inference works as follows. The example shows one of our own models, but you can
328
337
  from model2vec import StaticModel
329
338
 
330
339
  # Load a model from the HuggingFace hub, or a local one.
331
- model_name = "minishlab/M2V_base_output"
340
+ model_name = "minishlab/potion-base-8M"
332
341
  # You can optionally pass a token if you're loading a private model
333
342
  model = StaticModel.from_pretrained(model_name, token=None)
334
343
 
@@ -352,7 +361,7 @@ from sentence_transformers import SentenceTransformer
352
361
  from sentence_transformers.models import StaticEmbedding
353
362
 
354
363
  # Initialize a StaticEmbedding module
355
- static_embedding = StaticEmbedding.from_model2vec("minishlab/M2V_base_output")
364
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
356
365
  model = SentenceTransformer(modules=[static_embedding])
357
366
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
358
367
  ```
@@ -370,7 +379,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
370
379
  Our models can be evaluated using our [evaluation package](https://github.com/MinishLab/evaluation). Install the evaluation package with:
371
380
 
372
381
  ```bash
373
- pip install evaluation@git+https://github.com MinishLab/evaluation@main
382
+ pip install git+https://github.com/MinishLab/evaluation.git@main
374
383
  ```
375
384
  </details>
376
385
 
@@ -415,19 +424,19 @@ print(make_leaderboard(task_scores))
415
424
 
416
425
  We provide a number of models that can be used out of the box. These models are available on the [HuggingFace hub](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e) and can be loaded using the `from_pretrained` method. The models are listed below.
417
426
 
418
- | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params |
419
- |------------------------|-------------|------------------|----------------------|----------------|--------------|
420
- | [M2V_base_glove](https://huggingface.co/minishlab/M2V_base_glove) | English | GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Word-level | 102M |
421
- | [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 7.5M |
422
- | [M2V_base_glove_subword](https://huggingface.co/minishlab/M2V_base_glove_subword) | English | Output + GloVe | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 103M |
423
- | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M |
427
+
428
+ | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
429
+ |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|------------|
430
+ | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 7.5M | True |
431
+ | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 3.7M | True |
432
+ | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | English | Output | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | Subword | 1.8M | True |
433
+ | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M | False |
424
434
 
425
435
 
426
436
  ## Results
427
437
 
428
438
  We have performed extensive experiments to evaluate the performance of Model2Vec models. The results are documented in the [results](results/README.md) folder. The results are presented in the following sections:
429
439
  - [MTEB Results](results/README.md#mteb-results)
430
- - [Classification and Speed Benchmarks](results/README.md#classification-and-speed-benchmarks)
431
440
  - [Ablations](results/README.md#ablations)
432
441
 
433
442
  ## Related work
@@ -435,7 +444,7 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
435
444
  If you are interested in fast small models, also consider looking at these techniques:
436
445
  * [BPEmb](https://bpemb.h-its.org/): GLoVE embeddings trained on BPE-encoded Wikipedias. Huge inspiration to this project, multilingual, very fast. If you don't find a sentence transformer in the language you need, check this out.
437
446
  * [fast-sentence-transformers](https://github.com/davidberenstein1957/fast-sentence-transformers): distillation using Model2Vec comes at a cost. If that cost is too steep for you, and you have access to a GPU, this package is for you. It automates the quantization and optimization of sentence transformers without loss of performance.
438
- * [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. As we show above, we think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. It provides an interesting point of comparison to Model2Vec, and, fun fact, was invented at the same time.
447
+ * [wordllama](https://github.com/dleemiller/WordLlama): Uses the _input_ embeddings of a LLama2 model and then performs contrastive learning on these embeddings. We think this is a bit overfit on MTEB, as the model is trained on MTEB datasets, and only evaluated on MTEB. Fun fact: this was invented at the same time as Model2Vec.
439
448
 
440
449
  If you find other related work, please let us know.
441
450
 
@@ -0,0 +1,16 @@
1
+ model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
2
+ model2vec/hf_utils.py,sha256=Z-_V2kYagBX7m9_--e2ZAGP4irfRpqIlBQgGwYswpoU,7772
3
+ model2vec/model.py,sha256=DuzsHaTBf0fTsp0ovVPzFs3EzDqGnFd5bGC94vumYuU,12031
4
+ model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
5
+ model2vec/utils.py,sha256=AyKPu7w7XO2DhJEBN8NrO53vZj5rZpbwWJNxjagCKIk,2684
6
+ model2vec/version.py,sha256=YUIpQDxUrCbh0vtQtU7z3qcWjcuAHAhcRI706SxPcGw,84
7
+ model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
8
+ model2vec/distill/distillation.py,sha256=yDdIW4nqR5Vw4cUYL4p7hrJnIzZWO9fV9LiqZHe_z8s,11504
9
+ model2vec/distill/inference.py,sha256=QgHAEkLoeq-jPyKnFTB6p6Ry-ZGZqonkZaEg2S7VTOY,6123
10
+ model2vec/distill/tokenizer.py,sha256=xtVsMTxquqTufoP9z39C4Itg2LLcGViqeguz-M7y-u8,4293
11
+ model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
12
+ model2vec-0.3.2.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
13
+ model2vec-0.3.2.dist-info/METADATA,sha256=mMDSZ9I2XhHGnXZhzO0TUtwuerJL3zD_yeVtjRp4clc,22641
14
+ model2vec-0.3.2.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
15
+ model2vec-0.3.2.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
16
+ model2vec-0.3.2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.2.0)
2
+ Generator: setuptools (75.3.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,16 +0,0 @@
1
- model2vec/__init__.py,sha256=osue7o8CuO_1T9opJAWfnbg4SspGKx0cHuyWv8Tedfs,124
2
- model2vec/hf_utils.py,sha256=Z-_V2kYagBX7m9_--e2ZAGP4irfRpqIlBQgGwYswpoU,7772
3
- model2vec/model.py,sha256=--34uG0aNirxFSNXj-XyoVQ66j6a96X9InWXmtau7HI,11703
4
- model2vec/model_card_template.md,sha256=rQo4bE3VPXH3XB9OUCe7FCenhBc4wv6L1sNURVT4Sro,2747
5
- model2vec/utils.py,sha256=ID5TYV9dvcQccfqBbeVVAK66qfKm0tYf6O9xbISlcOQ,2577
6
- model2vec/version.py,sha256=5g_ckoZK9Wyod0SYRBZRZIWpdFk9UDYODHHFYHSmE4k,84
7
- model2vec/distill/__init__.py,sha256=KpFRhafXVceM1xhorJhXbd8OnX8dwOGcWMbXglZxd4U,330
8
- model2vec/distill/distillation.py,sha256=yDdIW4nqR5Vw4cUYL4p7hrJnIzZWO9fV9LiqZHe_z8s,11504
9
- model2vec/distill/inference.py,sha256=MO-IaG6JVM4hm1L_BYO0rTI8qE8Usn4tJx0Cs81LPT4,5837
10
- model2vec/distill/tokenizer.py,sha256=rpjrVAYOCcG1VSiFwZKv5s-zb92xrcop1tKslN_6qMw,4313
11
- model2vec/distill/utils.py,sha256=lzGyvFUO8mUcz63wnTRimGhQCsXzqnQfG5vRRKDGxic,721
12
- model2vec-0.3.0.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
13
- model2vec-0.3.0.dist-info/METADATA,sha256=1obeltEmrxBMTKmU-MrR4A0DYjbl1jeJO5W70D_XHKA,21848
14
- model2vec-0.3.0.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
15
- model2vec-0.3.0.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
16
- model2vec-0.3.0.dist-info/RECORD,,