model2vec 0.7.0__tar.gz → 0.8.0__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.
- {model2vec-0.7.0 → model2vec-0.8.0}/.github/workflows/ci.yaml +5 -2
- model2vec-0.8.0/CITATION.cff +27 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/PKG-INFO +17 -11
- {model2vec-0.7.0 → model2vec-0.8.0}/README.md +14 -8
- model2vec-0.8.0/assets/images/model2vec_logo.png +0 -0
- model2vec-0.8.0/assets/images/speed_vs_mteb_plot.png +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/distill/distillation.py +53 -50
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/distill/inference.py +3 -4
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/inference/model.py +9 -8
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/model.py +13 -30
- model2vec-0.8.0/model2vec/modelcards/__init__.py +3 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/modelcards/classifier_template.md +9 -7
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/modelcards/model_card_template.md +9 -7
- model2vec-0.8.0/model2vec/modelcards/modelcards.py +56 -0
- model2vec-0.8.0/model2vec/persistence/__init__.py +4 -0
- model2vec-0.8.0/model2vec/persistence/datamodels.py +50 -0
- model2vec-0.8.0/model2vec/persistence/hf.py +57 -0
- model2vec-0.8.0/model2vec/persistence/persistence.py +162 -0
- model2vec-0.8.0/model2vec/tokenizer/__init__.py +10 -0
- model2vec-0.8.0/model2vec/tokenizer/tokenizer.py +98 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/train/base.py +7 -2
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/train/classifier.py +30 -20
- model2vec-0.8.0/model2vec/train/utils.py +21 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/utils.py +2 -2
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/version.py +1 -1
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec.egg-info/PKG-INFO +17 -11
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec.egg-info/SOURCES.txt +11 -6
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec.egg-info/requires.txt +1 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/pyproject.toml +2 -3
- {model2vec-0.7.0 → model2vec-0.8.0}/results/README.md +22 -26
- {model2vec-0.7.0 → model2vec-0.8.0}/results/make_speed_vs_mteb_plot.py +49 -47
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/conftest.py +52 -3
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_distillation.py +69 -22
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_model.py +0 -2
- model2vec-0.8.0/tests/test_persistence.py +88 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_trainable.py +50 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_utils.py +5 -5
- {model2vec-0.7.0 → model2vec-0.8.0}/uv.lock +212 -469
- model2vec-0.7.0/model2vec/hf_utils.py +0 -277
- model2vec-0.7.0/model2vec/tokenizer/__init__.py +0 -12
- model2vec-0.7.0/model2vec/tokenizer/datamodels.py +0 -14
- model2vec-0.7.0/model2vec/tokenizer/model.py +0 -43
- model2vec-0.7.0/model2vec/tokenizer/normalizer.py +0 -42
- model2vec-0.7.0/model2vec/tokenizer/pretokenizer.py +0 -57
- model2vec-0.7.0/model2vec/tokenizer/tokenizer.py +0 -398
- model2vec-0.7.0/tests/test_tokenizer.py +0 -123
- {model2vec-0.7.0 → model2vec-0.8.0}/.gitignore +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/.pre-commit-config.yaml +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/LICENSE +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/Makefile +0 -0
- /model2vec-0.7.0/assets/images/model2vec_logo.png → /model2vec-0.8.0/assets/images/logo_v2.png +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/docs/README.md +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/__init__.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/distill/utils.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/inference/README.md +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/inference/__init__.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/py.typed +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/quantization.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/train/README.md +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/train/__init__.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec/vocabulary_quantization.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/scripts/export_to_onnx.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/setup.cfg +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/__init__.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_inference.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tests/test_quantization.py +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tutorials/README.md +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tutorials/recipe_search.ipynb +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tutorials/semantic_chunking.ipynb +0 -0
- {model2vec-0.7.0 → model2vec-0.8.0}/tutorials/train_classifier.ipynb +0 -0
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
name: Run tests and upload coverage
|
|
2
2
|
|
|
3
3
|
on:
|
|
4
|
-
push
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
pull_request:
|
|
5
8
|
|
|
6
9
|
jobs:
|
|
7
10
|
test:
|
|
@@ -10,7 +13,7 @@ jobs:
|
|
|
10
13
|
strategy:
|
|
11
14
|
matrix:
|
|
12
15
|
os: ["ubuntu-latest"]
|
|
13
|
-
python-version: ["3.
|
|
16
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
14
17
|
fail-fast: false
|
|
15
18
|
|
|
16
19
|
steps:
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use Model2Vec in your research, please cite it as below."
|
|
3
|
+
title: "Model2Vec: Fast State-of-the-Art Static Embeddings"
|
|
4
|
+
authors:
|
|
5
|
+
- family-names: "Tulkens"
|
|
6
|
+
given-names: "Stephan"
|
|
7
|
+
- family-names: "van Dongen"
|
|
8
|
+
given-names: "Thomas"
|
|
9
|
+
doi: 10.5281/zenodo.17270888
|
|
10
|
+
license: MIT
|
|
11
|
+
url: "https://github.com/MinishLab/model2vec"
|
|
12
|
+
repository-code: "https://github.com/MinishLab/model2vec"
|
|
13
|
+
date-released: "2024-09-20"
|
|
14
|
+
|
|
15
|
+
preferred-citation:
|
|
16
|
+
type: software
|
|
17
|
+
title: "Model2Vec: Fast State-of-the-Art Static Embeddings"
|
|
18
|
+
authors:
|
|
19
|
+
- family-names: "Tulkens"
|
|
20
|
+
given-names: "Stephan"
|
|
21
|
+
- family-names: "van Dongen"
|
|
22
|
+
given-names: "Thomas"
|
|
23
|
+
year: 2024
|
|
24
|
+
publisher: Zenodo
|
|
25
|
+
doi: 10.5281/zenodo.17270888
|
|
26
|
+
url: "https://github.com/MinishLab/model2vec"
|
|
27
|
+
license: MIT
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.0
|
|
4
4
|
Summary: Fast State-of-the-Art Static Embeddings
|
|
5
5
|
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
|
|
6
6
|
License: MIT License
|
|
@@ -35,13 +35,12 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
35
35
|
Classifier: Topic :: Software Development :: Libraries
|
|
36
36
|
Classifier: License :: OSI Approved :: MIT License
|
|
37
37
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
38
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
39
38
|
Classifier: Programming Language :: Python :: 3.10
|
|
40
39
|
Classifier: Programming Language :: Python :: 3.11
|
|
41
40
|
Classifier: Programming Language :: Python :: 3.12
|
|
42
41
|
Classifier: Programming Language :: Python :: 3.13
|
|
43
42
|
Classifier: Natural Language :: English
|
|
44
|
-
Requires-Python: >=3.
|
|
43
|
+
Requires-Python: >=3.10
|
|
45
44
|
Description-Content-Type: text/markdown
|
|
46
45
|
Requires-Dist: jinja2
|
|
47
46
|
Requires-Dist: joblib
|
|
@@ -63,6 +62,7 @@ Provides-Extra: distill
|
|
|
63
62
|
Requires-Dist: torch; extra == "distill"
|
|
64
63
|
Requires-Dist: transformers; extra == "distill"
|
|
65
64
|
Requires-Dist: scikit-learn; extra == "distill"
|
|
65
|
+
Requires-Dist: skeletoken>=0.3.2; extra == "distill"
|
|
66
66
|
Provides-Extra: onnx
|
|
67
67
|
Requires-Dist: onnx; extra == "onnx"
|
|
68
68
|
Requires-Dist: torch; extra == "onnx"
|
|
@@ -122,7 +122,7 @@ Requires-Dist: scikit-learn; extra == "quantization"
|
|
|
122
122
|
|
|
123
123
|
|
|
124
124
|
|
|
125
|
-
Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-
|
|
125
|
+
Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
|
|
126
126
|
|
|
127
127
|
<div align="center">
|
|
128
128
|
<h3>
|
|
@@ -143,8 +143,8 @@ You can start using Model2Vec by loading one of our [flagship models from the Hu
|
|
|
143
143
|
```python
|
|
144
144
|
from model2vec import StaticModel
|
|
145
145
|
|
|
146
|
-
# Load a model from the HuggingFace hub (in this case the potion-base-
|
|
147
|
-
model = StaticModel.from_pretrained("minishlab/potion-base-
|
|
146
|
+
# Load a model from the HuggingFace hub (in this case the potion-base-32M model)
|
|
147
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-32M")
|
|
148
148
|
|
|
149
149
|
# Make embeddings
|
|
150
150
|
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
@@ -255,6 +255,8 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
255
255
|
|
|
256
256
|
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:
|
|
257
257
|
- [MTEB Results](results/README.md#mteb-results)
|
|
258
|
+
- [MMTEB Results](results/README.md#mmteb-results)
|
|
259
|
+
- [Retrieval Results](results/README.md#retrieval-results)
|
|
258
260
|
- [Training Results](results/README.md#training-results)
|
|
259
261
|
- [Ablations](results/README.md#ablations)
|
|
260
262
|
|
|
@@ -265,11 +267,15 @@ MIT
|
|
|
265
267
|
## Citing
|
|
266
268
|
|
|
267
269
|
If you use Model2Vec in your research, please cite the following:
|
|
270
|
+
|
|
268
271
|
```bibtex
|
|
269
|
-
@
|
|
270
|
-
author
|
|
271
|
-
title
|
|
272
|
-
year
|
|
273
|
-
|
|
272
|
+
@software{minishlab2024model2vec,
|
|
273
|
+
author = {Stephan Tulkens and {van Dongen}, Thomas},
|
|
274
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
275
|
+
year = {2024},
|
|
276
|
+
publisher = {Zenodo},
|
|
277
|
+
doi = {10.5281/zenodo.17270888},
|
|
278
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
279
|
+
license = {MIT}
|
|
274
280
|
}
|
|
275
281
|
```
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
|
|
42
42
|
|
|
43
43
|
|
|
44
|
-
Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-
|
|
44
|
+
Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
|
|
45
45
|
|
|
46
46
|
<div align="center">
|
|
47
47
|
<h3>
|
|
@@ -62,8 +62,8 @@ You can start using Model2Vec by loading one of our [flagship models from the Hu
|
|
|
62
62
|
```python
|
|
63
63
|
from model2vec import StaticModel
|
|
64
64
|
|
|
65
|
-
# Load a model from the HuggingFace hub (in this case the potion-base-
|
|
66
|
-
model = StaticModel.from_pretrained("minishlab/potion-base-
|
|
65
|
+
# Load a model from the HuggingFace hub (in this case the potion-base-32M model)
|
|
66
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-32M")
|
|
67
67
|
|
|
68
68
|
# Make embeddings
|
|
69
69
|
embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
@@ -174,6 +174,8 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
174
174
|
|
|
175
175
|
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:
|
|
176
176
|
- [MTEB Results](results/README.md#mteb-results)
|
|
177
|
+
- [MMTEB Results](results/README.md#mmteb-results)
|
|
178
|
+
- [Retrieval Results](results/README.md#retrieval-results)
|
|
177
179
|
- [Training Results](results/README.md#training-results)
|
|
178
180
|
- [Ablations](results/README.md#ablations)
|
|
179
181
|
|
|
@@ -184,11 +186,15 @@ MIT
|
|
|
184
186
|
## Citing
|
|
185
187
|
|
|
186
188
|
If you use Model2Vec in your research, please cite the following:
|
|
189
|
+
|
|
187
190
|
```bibtex
|
|
188
|
-
@
|
|
189
|
-
author
|
|
190
|
-
title
|
|
191
|
-
year
|
|
192
|
-
|
|
191
|
+
@software{minishlab2024model2vec,
|
|
192
|
+
author = {Stephan Tulkens and {van Dongen}, Thomas},
|
|
193
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
194
|
+
year = {2024},
|
|
195
|
+
publisher = {Zenodo},
|
|
196
|
+
doi = {10.5281/zenodo.17270888},
|
|
197
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
198
|
+
license = {MIT}
|
|
193
199
|
}
|
|
194
200
|
```
|
|
Binary file
|
|
Binary file
|
|
@@ -3,10 +3,12 @@ from __future__ import annotations
|
|
|
3
3
|
import logging
|
|
4
4
|
import os
|
|
5
5
|
import re
|
|
6
|
-
from typing import
|
|
6
|
+
from typing import cast
|
|
7
7
|
|
|
8
8
|
import numpy as np
|
|
9
9
|
from huggingface_hub.hf_api import model_info
|
|
10
|
+
from skeletoken import TokenizerModel
|
|
11
|
+
from skeletoken.external.transformers import reshape_embeddings
|
|
10
12
|
from transformers import AutoModel, AutoTokenizer
|
|
11
13
|
from transformers.modeling_utils import PreTrainedModel
|
|
12
14
|
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
|
@@ -15,7 +17,7 @@ from model2vec.distill.inference import PCADimType, PoolingMode, create_embeddin
|
|
|
15
17
|
from model2vec.distill.utils import select_optimal_device
|
|
16
18
|
from model2vec.model import StaticModel
|
|
17
19
|
from model2vec.quantization import DType, quantize_embeddings
|
|
18
|
-
from model2vec.tokenizer import clean_and_create_vocabulary,
|
|
20
|
+
from model2vec.tokenizer import clean_and_create_vocabulary, turn_tokens_into_ids
|
|
19
21
|
from model2vec.vocabulary_quantization import quantize_vocabulary
|
|
20
22
|
|
|
21
23
|
logger = logging.getLogger(__name__)
|
|
@@ -37,7 +39,8 @@ def distill_from_model(
|
|
|
37
39
|
Distill a staticmodel from a sentence transformer.
|
|
38
40
|
|
|
39
41
|
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
40
|
-
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
42
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
43
|
+
vocabulary.
|
|
41
44
|
|
|
42
45
|
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
43
46
|
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
@@ -51,10 +54,13 @@ def distill_from_model(
|
|
|
51
54
|
If this is 'auto', we don't reduce dimensionality, but still apply PCA.
|
|
52
55
|
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
53
56
|
Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
|
|
54
|
-
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
55
|
-
|
|
57
|
+
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
58
|
+
this regex pattern will be removed from the vocabulary.
|
|
59
|
+
If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled
|
|
60
|
+
into a valid regex, we also throw an error.
|
|
56
61
|
:param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
|
|
57
|
-
:param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
|
|
62
|
+
:param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
|
|
63
|
+
quantization is performed.
|
|
58
64
|
:param pooling: The pooling mode to use for creating embeddings. Can be one of:
|
|
59
65
|
'mean' (default): mean over all tokens. Robust and works well in most cases.
|
|
60
66
|
'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
|
|
@@ -65,59 +71,51 @@ def distill_from_model(
|
|
|
65
71
|
|
|
66
72
|
"""
|
|
67
73
|
quantize_to = DType(quantize_to)
|
|
68
|
-
backend_tokenizer = tokenizer.backend_tokenizer
|
|
69
74
|
sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)
|
|
70
75
|
|
|
71
76
|
if vocabulary is None:
|
|
72
77
|
vocabulary = []
|
|
73
78
|
|
|
74
79
|
device = select_optimal_device(device)
|
|
80
|
+
original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)
|
|
81
|
+
original_tokenizer_model = original_tokenizer_model.prune_added_tokens()
|
|
75
82
|
|
|
76
|
-
n_tokens_before = len(vocabulary)
|
|
77
83
|
# Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
84
|
+
# Copy the original tokenizer model.
|
|
85
|
+
tokenizer_model = original_tokenizer_model.deep_copy()
|
|
86
|
+
if tokenizer_model.adds_prefix_space is not None:
|
|
87
|
+
tokenizer_model.adds_prefix_space = True
|
|
88
|
+
|
|
89
|
+
# Create the vocabulary in the new tokenizer.
|
|
90
|
+
tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)
|
|
91
|
+
# Remove the post processor, this is not necessary.
|
|
92
|
+
tokenizer_model.post_processor = None
|
|
93
|
+
# Prune again now that the post processor is gone.
|
|
94
|
+
# We can't do this before because we need the post processor and associated
|
|
95
|
+
# tokens before to add eos/bos.
|
|
96
|
+
tokenizer_model = tokenizer_model.prune_added_tokens()
|
|
97
|
+
|
|
98
|
+
# All tokens in a single list.
|
|
99
|
+
all_tokens = tokenizer_model.sorted_vocabulary
|
|
87
100
|
if not all_tokens:
|
|
88
101
|
raise ValueError("The vocabulary is empty after preprocessing. Please check your token_remove_pattern.")
|
|
89
102
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
#
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
logger.warning(
|
|
98
|
-
"The pad token is not set. Setting it to the unk token. This is a workaround for models that don't have a pad token."
|
|
99
|
-
)
|
|
100
|
-
else:
|
|
101
|
-
pad_token = unk_token or all_tokens[0].form
|
|
102
|
-
logger.warning(
|
|
103
|
-
"The pad token is not set. Setting it to the first token in the vocabulary. This is a workaround for models that don't have a pad token."
|
|
104
|
-
)
|
|
105
|
-
|
|
106
|
-
# Replace the vocabulary in the tokenizer with the new vocabulary.
|
|
107
|
-
backend_tokenizer = replace_vocabulary(backend_tokenizer, all_tokens, unk_token=unk_token, pad_token=pad_token)
|
|
108
|
-
logger.info(f"Creating embeddings for {len(all_tokens)} tokens")
|
|
109
|
-
# Convert tokens to IDs
|
|
110
|
-
token_ids = turn_tokens_into_ids(all_tokens, tokenizer, unk_token)
|
|
111
|
-
|
|
112
|
-
# Create the embeddings
|
|
103
|
+
# Turn all _new_ tokens into ids using the original tokenizer
|
|
104
|
+
token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)
|
|
105
|
+
|
|
106
|
+
# Reshape the transformer
|
|
107
|
+
model = reshape_embeddings(model, original_tokenizer_model)
|
|
108
|
+
|
|
109
|
+
# Create the embeddings using the ids from the original tokenizer.
|
|
113
110
|
embeddings = create_embeddings(
|
|
114
111
|
tokenized=token_ids,
|
|
115
112
|
model=model,
|
|
116
113
|
device=device,
|
|
117
|
-
pad_token_id=
|
|
114
|
+
pad_token_id=original_tokenizer_model.pad_token_id or 0,
|
|
118
115
|
pooling=pooling,
|
|
119
116
|
)
|
|
120
117
|
|
|
118
|
+
# Maybe apply quantization
|
|
121
119
|
if vocabulary_quantization is not None:
|
|
122
120
|
_, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)
|
|
123
121
|
embeddings, token_mapping, weights = quantize_vocabulary(
|
|
@@ -163,7 +161,7 @@ def distill_from_model(
|
|
|
163
161
|
vectors=embeddings,
|
|
164
162
|
weights=weights,
|
|
165
163
|
token_mapping=token_mapping,
|
|
166
|
-
tokenizer=
|
|
164
|
+
tokenizer=tokenizer_model.to_tokenizer(),
|
|
167
165
|
config=config,
|
|
168
166
|
base_model_name=model_name,
|
|
169
167
|
language=language,
|
|
@@ -174,13 +172,14 @@ def distill_from_model(
|
|
|
174
172
|
def _validate_parameters(
|
|
175
173
|
sif_coefficient: float | None,
|
|
176
174
|
token_remove_pattern: str | None,
|
|
177
|
-
) -> tuple[float | None, re.Pattern | None]:
|
|
175
|
+
) -> tuple[float | None, re.Pattern[str] | None]:
|
|
178
176
|
"""
|
|
179
177
|
Validate the parameters passed to the distillation function.
|
|
180
178
|
|
|
181
179
|
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
182
180
|
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
|
|
183
|
-
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
181
|
+
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
182
|
+
this regex pattern will be removed from the vocabulary.
|
|
184
183
|
:return: The SIF coefficient to use.
|
|
185
184
|
:raises: ValueError if the regex can't be compiled.
|
|
186
185
|
|
|
@@ -189,12 +188,12 @@ def _validate_parameters(
|
|
|
189
188
|
if not 0 < sif_coefficient < 1.0:
|
|
190
189
|
raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
|
|
191
190
|
|
|
192
|
-
token_remove_regex: re.Pattern | None = None
|
|
191
|
+
token_remove_regex: re.Pattern[str] | None = None
|
|
193
192
|
if token_remove_pattern is not None:
|
|
194
193
|
try:
|
|
195
194
|
token_remove_regex = re.compile(token_remove_pattern)
|
|
196
195
|
except re.error as e:
|
|
197
|
-
raise ValueError(f"Couldn't compile the regex pattern: {e}")
|
|
196
|
+
raise ValueError(f"Couldn't compile the regex pattern: {e}") from e
|
|
198
197
|
|
|
199
198
|
return sif_coefficient, token_remove_regex
|
|
200
199
|
|
|
@@ -215,7 +214,8 @@ def distill(
|
|
|
215
214
|
Distill a staticmodel from a sentence transformer.
|
|
216
215
|
|
|
217
216
|
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
218
|
-
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
217
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
218
|
+
vocabulary.
|
|
219
219
|
|
|
220
220
|
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
221
221
|
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
@@ -228,10 +228,13 @@ def distill(
|
|
|
228
228
|
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
229
229
|
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
230
230
|
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
|
|
231
|
-
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
232
|
-
|
|
231
|
+
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
232
|
+
this regex pattern will be removed from the vocabulary.
|
|
233
|
+
:param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming
|
|
234
|
+
from `transformers`. If this is True, we will load all components.
|
|
233
235
|
:param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
|
|
234
|
-
:param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
|
|
236
|
+
:param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
|
|
237
|
+
quantization is performed.
|
|
235
238
|
:param pooling: The pooling mode to use for creating embeddings. Can be one of:
|
|
236
239
|
'mean' (default): mean over all tokens. Robust and works well in most cases.
|
|
237
240
|
'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
1
|
from __future__ import annotations
|
|
3
2
|
|
|
4
3
|
import inspect
|
|
5
4
|
import logging
|
|
6
5
|
from enum import Enum
|
|
7
6
|
from pathlib import Path
|
|
8
|
-
from typing import Literal
|
|
7
|
+
from typing import Literal
|
|
9
8
|
|
|
10
9
|
import numpy as np
|
|
11
10
|
import torch
|
|
@@ -17,8 +16,8 @@ from transformers.modeling_utils import PreTrainedModel
|
|
|
17
16
|
|
|
18
17
|
logger = logging.getLogger(__name__)
|
|
19
18
|
|
|
20
|
-
PathLike =
|
|
21
|
-
PCADimType =
|
|
19
|
+
PathLike = Path | str
|
|
20
|
+
PCADimType = int | None | float | Literal["auto"]
|
|
22
21
|
|
|
23
22
|
_DEFAULT_BATCH_SIZE = 256
|
|
24
23
|
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import re
|
|
4
|
+
from collections.abc import Sequence
|
|
4
5
|
from pathlib import Path
|
|
5
6
|
from tempfile import TemporaryDirectory
|
|
6
|
-
from typing import
|
|
7
|
+
from typing import TypeVar, cast
|
|
7
8
|
|
|
8
9
|
import huggingface_hub
|
|
9
10
|
import numpy as np
|
|
@@ -13,8 +14,8 @@ from sklearn.neural_network import MLPClassifier
|
|
|
13
14
|
from sklearn.pipeline import Pipeline
|
|
14
15
|
from sklearn.preprocessing import MultiLabelBinarizer
|
|
15
16
|
|
|
16
|
-
from model2vec.hf_utils import _create_model_card
|
|
17
17
|
from model2vec.model import PathLike, StaticModel
|
|
18
|
+
from model2vec.modelcards import create_model_card
|
|
18
19
|
|
|
19
20
|
_DEFAULT_TRUST_PATTERN = re.compile(r"sklearn\..+")
|
|
20
21
|
_DEFAULT_MODEL_FILENAME = "pipeline.skops"
|
|
@@ -76,7 +77,7 @@ class StaticModelPipeline:
|
|
|
76
77
|
:param token: The token to use to push to the hub.
|
|
77
78
|
:param private: Whether the repository should be private.
|
|
78
79
|
"""
|
|
79
|
-
from model2vec.
|
|
80
|
+
from model2vec.persistence import push_folder_to_hub
|
|
80
81
|
|
|
81
82
|
with TemporaryDirectory() as temp_dir:
|
|
82
83
|
save_pipeline(self, temp_dir)
|
|
@@ -265,11 +266,11 @@ def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> Non
|
|
|
265
266
|
name = base_model_name
|
|
266
267
|
else:
|
|
267
268
|
name = "unknown"
|
|
268
|
-
|
|
269
|
+
create_model_card(
|
|
269
270
|
folder_path,
|
|
270
271
|
base_model_name=name,
|
|
271
272
|
language=pipeline.model.language,
|
|
272
|
-
template_path="
|
|
273
|
+
template_path="classifier_template.md",
|
|
273
274
|
)
|
|
274
275
|
|
|
275
276
|
|
|
@@ -293,14 +294,14 @@ def evaluate_single_or_multi_label(
|
|
|
293
294
|
"""
|
|
294
295
|
if _is_multi_label_shaped(y):
|
|
295
296
|
# Cast because the type checker doesn't understand that y is a list of lists.
|
|
296
|
-
y = cast(
|
|
297
|
+
y = cast(list[list[str]] | list[list[int]], y)
|
|
297
298
|
classes = sorted(set([label for labels in y for label in labels]))
|
|
298
299
|
mlb = MultiLabelBinarizer(classes=classes)
|
|
299
300
|
y_transformed = mlb.fit_transform(y)
|
|
300
301
|
predictions_transformed = mlb.transform(predictions)
|
|
301
302
|
else:
|
|
302
303
|
if all(isinstance(label, (str, int)) for label in y):
|
|
303
|
-
y = cast(
|
|
304
|
+
y = cast(list[str] | list[int], y)
|
|
304
305
|
classes = sorted(set(y))
|
|
305
306
|
y_transformed = np.array(y)
|
|
306
307
|
predictions_transformed = np.array(predictions)
|
|
@@ -309,7 +310,7 @@ def evaluate_single_or_multi_label(
|
|
|
309
310
|
y_transformed,
|
|
310
311
|
predictions_transformed,
|
|
311
312
|
output_dict=output_dict,
|
|
312
|
-
zero_division=0,
|
|
313
|
+
zero_division=0, # type: ignore # incorrect type in sklearn.
|
|
313
314
|
)
|
|
314
315
|
|
|
315
316
|
return report
|
|
@@ -2,10 +2,12 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import math
|
|
4
4
|
import os
|
|
5
|
+
import warnings
|
|
6
|
+
from collections.abc import Iterator, Sequence
|
|
5
7
|
from logging import getLogger
|
|
6
8
|
from pathlib import Path
|
|
7
9
|
from tempfile import TemporaryDirectory
|
|
8
|
-
from typing import Any,
|
|
10
|
+
from typing import Any, overload
|
|
9
11
|
|
|
10
12
|
import numpy as np
|
|
11
13
|
from joblib import delayed
|
|
@@ -15,7 +17,7 @@ from tqdm import tqdm
|
|
|
15
17
|
from model2vec.quantization import DType, quantize_and_reduce_dim
|
|
16
18
|
from model2vec.utils import ProgressParallel
|
|
17
19
|
|
|
18
|
-
PathLike =
|
|
20
|
+
PathLike = Path | str
|
|
19
21
|
|
|
20
22
|
logger = getLogger(__name__)
|
|
21
23
|
|
|
@@ -130,7 +132,7 @@ class StaticModel:
|
|
|
130
132
|
:param model_name: The model name to use in the Model Card.
|
|
131
133
|
:param subfolder: The subfolder to save to.
|
|
132
134
|
"""
|
|
133
|
-
from model2vec.
|
|
135
|
+
from model2vec.persistence import save_pretrained
|
|
134
136
|
|
|
135
137
|
save_pretrained(
|
|
136
138
|
folder_path=Path(path),
|
|
@@ -213,7 +215,6 @@ class StaticModel:
|
|
|
213
215
|
vocabulary_quantization=vocabulary_quantization,
|
|
214
216
|
quantize_to=quantize_to,
|
|
215
217
|
dimensionality=dimensionality,
|
|
216
|
-
from_sentence_transformers=False,
|
|
217
218
|
normalize=normalize,
|
|
218
219
|
subfolder=subfolder,
|
|
219
220
|
force_download=force_download,
|
|
@@ -230,24 +231,12 @@ class StaticModel:
|
|
|
230
231
|
vocabulary_quantization: int | None = None,
|
|
231
232
|
force_download: bool = True,
|
|
232
233
|
) -> StaticModel:
|
|
233
|
-
"""
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
:param token: The huggingface token to use.
|
|
240
|
-
:param normalize: Whether to normalize the embeddings.
|
|
241
|
-
:param quantize_to: The dtype to quantize the model to. If None, no quantization is done.
|
|
242
|
-
If a string is passed, it is converted to a DType.
|
|
243
|
-
:param dimensionality: The dimensionality of the model. If this is None, use the dimensionality of the model.
|
|
244
|
-
This is useful if you want to load a model with a lower dimensionality.
|
|
245
|
-
Note that this only applies if you have trained your model using mrl or PCA.
|
|
246
|
-
:param vocabulary_quantization: The number of clusters to use for vocabulary quantization.
|
|
247
|
-
:param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not
|
|
248
|
-
already present in the cache.
|
|
249
|
-
:return: A StaticModel.
|
|
250
|
-
"""
|
|
234
|
+
"""Deprecated: use from_pretrained."""
|
|
235
|
+
warnings.warn(
|
|
236
|
+
"StaticModel.from_sentence_transformers() is deprecated; use from_pretrained() instead.",
|
|
237
|
+
DeprecationWarning,
|
|
238
|
+
stacklevel=2,
|
|
239
|
+
)
|
|
251
240
|
return _loading_helper(
|
|
252
241
|
cls=cls,
|
|
253
242
|
path=path,
|
|
@@ -255,7 +244,6 @@ class StaticModel:
|
|
|
255
244
|
vocabulary_quantization=vocabulary_quantization,
|
|
256
245
|
quantize_to=quantize_to,
|
|
257
246
|
dimensionality=dimensionality,
|
|
258
|
-
from_sentence_transformers=True,
|
|
259
247
|
normalize=normalize,
|
|
260
248
|
subfolder=None,
|
|
261
249
|
force_download=force_download,
|
|
@@ -480,7 +468,7 @@ class StaticModel:
|
|
|
480
468
|
:param token: The huggingface token to use.
|
|
481
469
|
:param subfolder: The subfolder to push to.
|
|
482
470
|
"""
|
|
483
|
-
from model2vec.
|
|
471
|
+
from model2vec.persistence import push_folder_to_hub
|
|
484
472
|
|
|
485
473
|
with TemporaryDirectory() as temp_dir:
|
|
486
474
|
self.save_pretrained(temp_dir, model_name=repo_id)
|
|
@@ -545,21 +533,16 @@ def _loading_helper(
|
|
|
545
533
|
vocabulary_quantization: int | None,
|
|
546
534
|
quantize_to: str | DType | None,
|
|
547
535
|
dimensionality: int | None,
|
|
548
|
-
from_sentence_transformers: bool,
|
|
549
536
|
normalize: bool | None,
|
|
550
537
|
subfolder: str | None,
|
|
551
538
|
force_download: bool,
|
|
552
539
|
) -> StaticModel:
|
|
553
540
|
"""Helper function to load a model from a directory."""
|
|
554
|
-
from model2vec.
|
|
555
|
-
|
|
556
|
-
if from_sentence_transformers and subfolder is not None:
|
|
557
|
-
raise ValueError("Subfolder is not supported for sentence transformers models.")
|
|
541
|
+
from model2vec.persistence import load_pretrained
|
|
558
542
|
|
|
559
543
|
embeddings, tokenizer, config, metadata, weights, mapping = load_pretrained(
|
|
560
544
|
folder_or_repo_path=path,
|
|
561
545
|
token=token,
|
|
562
|
-
from_sentence_transformers=from_sentence_transformers,
|
|
563
546
|
subfolder=subfolder,
|
|
564
547
|
force_download=force_download,
|
|
565
548
|
)
|
|
@@ -30,8 +30,7 @@ predicted = model.predict(["Example sentence"])
|
|
|
30
30
|
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
31
31
|
- [Model2Vec Base Models](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e)
|
|
32
32
|
- [Model2Vec Results](https://github.com/MinishLab/model2vec/tree/main/results)
|
|
33
|
-
- [Model2Vec
|
|
34
|
-
- [Website](https://minishlab.github.io/)
|
|
33
|
+
- [Model2Vec Docs](https://minish.ai/packages/model2vec/introduction)
|
|
35
34
|
|
|
36
35
|
## Library Authors
|
|
37
36
|
|
|
@@ -41,10 +40,13 @@ Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team c
|
|
|
41
40
|
|
|
42
41
|
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
43
42
|
```
|
|
44
|
-
@
|
|
45
|
-
author
|
|
46
|
-
title
|
|
47
|
-
year
|
|
48
|
-
|
|
43
|
+
@software{minishlab2024model2vec,
|
|
44
|
+
author = {Stephan Tulkens and {van Dongen}, Thomas},
|
|
45
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
46
|
+
year = {2024},
|
|
47
|
+
publisher = {Zenodo},
|
|
48
|
+
doi = {10.5281/zenodo.17270888},
|
|
49
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
50
|
+
license = {MIT}
|
|
49
51
|
}
|
|
50
52
|
```
|
|
@@ -70,8 +70,7 @@ It works by passing a vocabulary through a sentence transformer model, then redu
|
|
|
70
70
|
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
71
71
|
- [Model2Vec Base Models](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e)
|
|
72
72
|
- [Model2Vec Results](https://github.com/MinishLab/model2vec/tree/main/results)
|
|
73
|
-
- [Model2Vec
|
|
74
|
-
- [Website](https://minishlab.github.io/)
|
|
73
|
+
- [Model2Vec Docs](https://minish.ai/packages/model2vec/introduction)
|
|
75
74
|
|
|
76
75
|
|
|
77
76
|
## Library Authors
|
|
@@ -82,10 +81,13 @@ Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team c
|
|
|
82
81
|
|
|
83
82
|
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
84
83
|
```
|
|
85
|
-
@
|
|
86
|
-
author
|
|
87
|
-
title
|
|
88
|
-
year
|
|
89
|
-
|
|
84
|
+
@software{minishlab2024model2vec,
|
|
85
|
+
author = {Stephan Tulkens and {van Dongen}, Thomas},
|
|
86
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
87
|
+
year = {2024},
|
|
88
|
+
publisher = {Zenodo},
|
|
89
|
+
doi = {10.5281/zenodo.17270888},
|
|
90
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
91
|
+
license = {MIT}
|
|
90
92
|
}
|
|
91
93
|
```
|