model2vec 0.3.0__py3-none-any.whl → 0.3.1__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/version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version_triple__ = (0, 3, 0)
1
+ __version_triple__ = (0, 3, 1)
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.1
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
@@ -104,14 +104,19 @@ Requires-Dist: scikit-learn ; extra == 'distill'
104
104
 
105
105
  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
106
 
107
+
108
+ ## Updates & Announcements
109
+
110
+ - **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).
111
+
107
112
  ## Table of Contents
108
113
  - [Quickstart](#quickstart)
109
114
  - [Main Features](#main-features)
110
115
  - [What is Model2Vec?](#what-is-model2vec)
111
116
  - [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)
117
+ - [Distillation](#distillation)
118
+ - [Inference](#inference)
119
+ - [Evaluation](#evaluation)
115
120
  - [Model List](#model-list)
116
121
  - [Results](#results)
117
122
  - [Related Work](#related-work)
@@ -134,8 +139,8 @@ The easiest way to get started with Model2Vec is to download one of our [flagshi
134
139
  ```python
135
140
  from model2vec import StaticModel
136
141
 
137
- # Load a model from the HuggingFace hub (in this case the M2V_base_output model)
138
- model_name = "minishlab/M2V_base_output"
142
+ # Load a model from the HuggingFace hub (in this case the potion-base-8M model)
143
+ model_name = "minishlab/potion-base-8M"
139
144
  model = StaticModel.from_pretrained(model_name)
140
145
 
141
146
  # Make embeddings
@@ -169,7 +174,7 @@ from sentence_transformers import SentenceTransformer
169
174
  from sentence_transformers.models import StaticEmbedding
170
175
 
171
176
  # Initialize a StaticEmbedding module
172
- static_embedding = StaticEmbedding.from_model2vec("minishlab/M2V_base_output")
177
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
173
178
  model = SentenceTransformer(modules=[static_embedding])
174
179
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
175
180
  ```
@@ -215,6 +220,9 @@ Model2vec has 3 modes:
215
220
 
216
221
  For a technical deepdive into Model2Vec, please refer to our [blog post](https://huggingface.co/blog/Pringled/model2vec).
217
222
 
223
+ ### Tokenlearn
224
+
225
+ 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
226
 
219
227
 
220
228
  ## Usage
@@ -328,7 +336,7 @@ Inference works as follows. The example shows one of our own models, but you can
328
336
  from model2vec import StaticModel
329
337
 
330
338
  # Load a model from the HuggingFace hub, or a local one.
331
- model_name = "minishlab/M2V_base_output"
339
+ model_name = "minishlab/potion-base-8M"
332
340
  # You can optionally pass a token if you're loading a private model
333
341
  model = StaticModel.from_pretrained(model_name, token=None)
334
342
 
@@ -352,7 +360,7 @@ from sentence_transformers import SentenceTransformer
352
360
  from sentence_transformers.models import StaticEmbedding
353
361
 
354
362
  # Initialize a StaticEmbedding module
355
- static_embedding = StaticEmbedding.from_model2vec("minishlab/M2V_base_output")
363
+ static_embedding = StaticEmbedding.from_model2vec("minishlab/potion-base-8M")
356
364
  model = SentenceTransformer(modules=[static_embedding])
357
365
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
358
366
  ```
@@ -370,7 +378,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
370
378
  Our models can be evaluated using our [evaluation package](https://github.com/MinishLab/evaluation). Install the evaluation package with:
371
379
 
372
380
  ```bash
373
- pip install evaluation@git+https://github.com MinishLab/evaluation@main
381
+ pip install git+https://github.com/MinishLab/evaluation.git@main
374
382
  ```
375
383
  </details>
376
384
 
@@ -415,19 +423,19 @@ print(make_leaderboard(task_scores))
415
423
 
416
424
  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
425
 
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 |
426
+
427
+ | Model | Language | Vocab | Sentence Transformer | Tokenizer Type | Params | Tokenlearn |
428
+ |-----------------------------------------------------------------------|-------------|------------------|-----------------------------------------------------------------|----------------|---------|------------|
429
+ | [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 |
430
+ | [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 |
431
+ | [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 |
432
+ | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | Output | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | Subword | 471M | False |
424
433
 
425
434
 
426
435
  ## Results
427
436
 
428
437
  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
438
  - [MTEB Results](results/README.md#mteb-results)
430
- - [Classification and Speed Benchmarks](results/README.md#classification-and-speed-benchmarks)
431
439
  - [Ablations](results/README.md#ablations)
432
440
 
433
441
  ## Related work
@@ -435,7 +443,7 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
435
443
  If you are interested in fast small models, also consider looking at these techniques:
436
444
  * [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
445
  * [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.
446
+ * [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
447
 
440
448
  If you find other related work, please let us know.
441
449
 
@@ -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=ID5TYV9dvcQccfqBbeVVAK66qfKm0tYf6O9xbISlcOQ,2577
6
+ model2vec/version.py,sha256=fgJbJS8ResifrwglA284jEeq3crjuclMKhZfSCctVnQ,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.1.dist-info/LICENSE,sha256=sCFPFI7OrnOfkWIJ54z-FXEsS4EMi8nUS2wtHRYWqrY,1074
13
+ model2vec-0.3.1.dist-info/METADATA,sha256=sSDg_zBOB90cmsCzw3KFz785oWC1jlgGbMddWkDQWh8,22614
14
+ model2vec-0.3.1.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
15
+ model2vec-0.3.1.dist-info/top_level.txt,sha256=cprhxJcbtkFiydp0BGvdCVNupTWg07-3p93jFStc78g,10
16
+ model2vec-0.3.1.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,,