model2vec 0.4.0__tar.gz → 0.4.1__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.4.0 → model2vec-0.4.1}/PKG-INFO +11 -8
- {model2vec-0.4.0 → model2vec-0.4.1}/README.md +10 -7
- model2vec-0.4.1/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/inference/__init__.py +2 -2
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/inference/model.py +111 -6
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/modelcards/classifier_template.md +6 -5
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/modelcards/model_card_template.md +34 -13
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/train/README.md +47 -4
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/train/base.py +3 -3
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/train/classifier.py +159 -54
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/version.py +1 -1
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec.egg-info/PKG-INFO +11 -8
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec.egg-info/SOURCES.txt +1 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/results/README.md +39 -26
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/conftest.py +24 -9
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/test_inference.py +44 -6
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/test_trainable.py +32 -7
- {model2vec-0.4.0 → model2vec-0.4.1}/uv.lock +1 -1
- {model2vec-0.4.0 → model2vec-0.4.1}/.github/workflows/ci.yaml +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/.gitignore +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/.pre-commit-config.yaml +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/LICENSE +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/Makefile +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/logo.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/logo_v2.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/model2vec_model_diagram.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/sentences_per_second_vs_average_score.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_accuracy.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_accuracy_v2.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_accuracy_v3.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_accuracy_v4.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_mteb_score.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_mteb_score_v2.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/docs/README.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/docs/integrations.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/docs/usage.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/docs/what_is_model2vec.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/__init__.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/distill/distillation.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/distill/inference.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/distill/tokenizer.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/distill/utils.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/hf_utils.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/inference/README.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/model.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/train/__init__.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec/utils.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec.egg-info/requires.txt +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/pyproject.toml +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/results/make_speed_vs_mteb_plot.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/scripts/export_to_onnx.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/setup.cfg +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/__init__.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/test_distillation.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/test_model.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tests/test_utils.py +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tutorials/README.md +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tutorials/recipe_search.ipynb +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tutorials/semantic_chunking.ipynb +0 -0
- {model2vec-0.4.0 → model2vec-0.4.1}/tutorials/train_classifier.ipynb +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.1
|
|
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
|
|
@@ -102,20 +102,24 @@ Requires-Dist: skops; extra == "inference"
|
|
|
102
102
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
|
|
103
103
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
|
|
104
104
|
<a href="https://pepy.tech/project/model2vec">
|
|
105
|
-
|
|
105
|
+
<img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
|
|
106
106
|
</a>
|
|
107
107
|
<a href="https://app.codecov.io/gh/MinishLab/model2vec">
|
|
108
|
-
|
|
108
|
+
<img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
|
|
109
109
|
</a>
|
|
110
|
+
<a href="https://discord.gg/4BDPR5nmtK">
|
|
111
|
+
<img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
|
|
112
|
+
</a>
|
|
113
|
+
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
|
|
114
|
+
<img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
|
|
110
115
|
</a>
|
|
111
|
-
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
|
|
112
|
-
|
|
113
116
|
</h2>
|
|
114
117
|
</div>
|
|
115
118
|
|
|
116
119
|
|
|
117
120
|
|
|
118
121
|
|
|
122
|
+
|
|
119
123
|
Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by a factor up to 50 and making the models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is the most performant static embedding model in the world. See our results [here](results/README.md), or dive in to see how it works.
|
|
120
124
|
|
|
121
125
|
<div align="center">
|
|
@@ -182,15 +186,14 @@ from model2vec.train import StaticModelForClassification
|
|
|
182
186
|
# Initialize a classifier from a pre-trained model
|
|
183
187
|
classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
|
|
184
188
|
|
|
185
|
-
# Load a dataset
|
|
189
|
+
# Load a dataset. Note: both single and multi-label classification datasets are supported
|
|
186
190
|
ds = load_dataset("setfit/subj")
|
|
187
191
|
|
|
188
192
|
# Train the classifier on text (X) and labels (y)
|
|
189
193
|
classifier.fit(ds["train"]["text"], ds["train"]["label"])
|
|
190
194
|
|
|
191
195
|
# Evaluate the classifier
|
|
192
|
-
|
|
193
|
-
accuracy = np.mean(np.array(predictions) == np.array(ds["test"]["label"])) * 100
|
|
196
|
+
classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["label"])
|
|
194
197
|
```
|
|
195
198
|
|
|
196
199
|
For advanced usage, please refer to our [usage documentation](https://github.com/MinishLab/model2vec/blob/main/docs/usage.md).
|
|
@@ -25,20 +25,24 @@
|
|
|
25
25
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
|
|
26
26
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
|
|
27
27
|
<a href="https://pepy.tech/project/model2vec">
|
|
28
|
-
|
|
28
|
+
<img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
|
|
29
29
|
</a>
|
|
30
30
|
<a href="https://app.codecov.io/gh/MinishLab/model2vec">
|
|
31
|
-
|
|
31
|
+
<img src="https://codecov.io/gh/MinishLab/model2vec/graph/badge.svg?token=21TWJ6B5ET" alt="Codecov">
|
|
32
32
|
</a>
|
|
33
|
+
<a href="https://discord.gg/4BDPR5nmtK">
|
|
34
|
+
<img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
|
|
35
|
+
</a>
|
|
36
|
+
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
|
|
37
|
+
<img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
|
|
33
38
|
</a>
|
|
34
|
-
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
|
|
35
|
-
|
|
36
39
|
</h2>
|
|
37
40
|
</div>
|
|
38
41
|
|
|
39
42
|
|
|
40
43
|
|
|
41
44
|
|
|
45
|
+
|
|
42
46
|
Model2Vec is a technique to turn any sentence transformer into a really small static model, reducing model size by a factor up to 50 and making the models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is the most performant static embedding model in the world. See our results [here](results/README.md), or dive in to see how it works.
|
|
43
47
|
|
|
44
48
|
<div align="center">
|
|
@@ -105,15 +109,14 @@ from model2vec.train import StaticModelForClassification
|
|
|
105
109
|
# Initialize a classifier from a pre-trained model
|
|
106
110
|
classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
|
|
107
111
|
|
|
108
|
-
# Load a dataset
|
|
112
|
+
# Load a dataset. Note: both single and multi-label classification datasets are supported
|
|
109
113
|
ds = load_dataset("setfit/subj")
|
|
110
114
|
|
|
111
115
|
# Train the classifier on text (X) and labels (y)
|
|
112
116
|
classifier.fit(ds["train"]["text"], ds["train"]["label"])
|
|
113
117
|
|
|
114
118
|
# Evaluate the classifier
|
|
115
|
-
|
|
116
|
-
accuracy = np.mean(np.array(predictions) == np.array(ds["test"]["label"])) * 100
|
|
119
|
+
classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["label"])
|
|
117
120
|
```
|
|
118
121
|
|
|
119
122
|
For advanced usage, please refer to our [usage documentation](https://github.com/MinishLab/model2vec/blob/main/docs/usage.md).
|
|
Binary file
|
|
@@ -5,6 +5,6 @@ _REQUIRED_EXTRA = "inference"
|
|
|
5
5
|
for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA):
|
|
6
6
|
importable(extra_dependency, _REQUIRED_EXTRA)
|
|
7
7
|
|
|
8
|
-
from model2vec.inference.model import StaticModelPipeline
|
|
8
|
+
from model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label
|
|
9
9
|
|
|
10
|
-
__all__ = ["StaticModelPipeline"]
|
|
10
|
+
__all__ = ["StaticModelPipeline", "evaluate_single_or_multi_label"]
|
|
@@ -3,11 +3,15 @@ from __future__ import annotations
|
|
|
3
3
|
import re
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
from tempfile import TemporaryDirectory
|
|
6
|
+
from typing import TypeVar
|
|
6
7
|
|
|
7
8
|
import huggingface_hub
|
|
8
9
|
import numpy as np
|
|
9
10
|
import skops.io
|
|
11
|
+
from sklearn.metrics import classification_report
|
|
12
|
+
from sklearn.neural_network import MLPClassifier
|
|
10
13
|
from sklearn.pipeline import Pipeline
|
|
14
|
+
from sklearn.preprocessing import MultiLabelBinarizer
|
|
11
15
|
|
|
12
16
|
from model2vec.hf_utils import _create_model_card
|
|
13
17
|
from model2vec.model import PathLike, StaticModel
|
|
@@ -15,12 +19,28 @@ from model2vec.model import PathLike, StaticModel
|
|
|
15
19
|
_DEFAULT_TRUST_PATTERN = re.compile(r"sklearn\..+")
|
|
16
20
|
_DEFAULT_MODEL_FILENAME = "pipeline.skops"
|
|
17
21
|
|
|
22
|
+
LabelType = TypeVar("LabelType", list[str], list[list[str]])
|
|
23
|
+
|
|
18
24
|
|
|
19
25
|
class StaticModelPipeline:
|
|
20
26
|
def __init__(self, model: StaticModel, head: Pipeline) -> None:
|
|
21
27
|
"""Create a pipeline with a StaticModel encoder."""
|
|
22
28
|
self.model = model
|
|
23
29
|
self.head = head
|
|
30
|
+
classifier = self.head[-1]
|
|
31
|
+
# Check if the classifier is a multilabel classifier.
|
|
32
|
+
# NOTE: this doesn't look robust, but it is.
|
|
33
|
+
# Different classifiers, such as OVR wrappers, support multilabel output natively, so we
|
|
34
|
+
# can just use predict.
|
|
35
|
+
self.multilabel = False
|
|
36
|
+
if isinstance(classifier, MLPClassifier):
|
|
37
|
+
if classifier.out_activation_ == "logistic":
|
|
38
|
+
self.multilabel = True
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def classes_(self) -> np.ndarray:
|
|
42
|
+
"""The classes of the classifier."""
|
|
43
|
+
return self.head.classes_
|
|
24
44
|
|
|
25
45
|
@classmethod
|
|
26
46
|
def from_pretrained(
|
|
@@ -60,7 +80,7 @@ class StaticModelPipeline:
|
|
|
60
80
|
self.model.save_pretrained(temp_dir)
|
|
61
81
|
push_folder_to_hub(Path(temp_dir), repo_id, private, token)
|
|
62
82
|
|
|
63
|
-
def
|
|
83
|
+
def _encode_and_coerce_to_2d(
|
|
64
84
|
self,
|
|
65
85
|
X: list[str] | str,
|
|
66
86
|
show_progress_bar: bool,
|
|
@@ -69,7 +89,7 @@ class StaticModelPipeline:
|
|
|
69
89
|
use_multiprocessing: bool,
|
|
70
90
|
multiprocessing_threshold: int,
|
|
71
91
|
) -> np.ndarray:
|
|
72
|
-
"""
|
|
92
|
+
"""Encode the instances and coerce the output to a matrix."""
|
|
73
93
|
encoded = self.model.encode(
|
|
74
94
|
X,
|
|
75
95
|
show_progress_bar=show_progress_bar,
|
|
@@ -91,9 +111,21 @@ class StaticModelPipeline:
|
|
|
91
111
|
batch_size: int = 1024,
|
|
92
112
|
use_multiprocessing: bool = True,
|
|
93
113
|
multiprocessing_threshold: int = 10_000,
|
|
114
|
+
threshold: float = 0.5,
|
|
94
115
|
) -> np.ndarray:
|
|
95
|
-
"""
|
|
96
|
-
|
|
116
|
+
"""
|
|
117
|
+
Predict the labels of the input.
|
|
118
|
+
|
|
119
|
+
:param X: The input data to predict. Can be a list of strings or a single string.
|
|
120
|
+
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
|
|
121
|
+
:param max_length: The maximum length of the input sequences. Defaults to 512.
|
|
122
|
+
:param batch_size: The batch size for prediction. Defaults to 1024.
|
|
123
|
+
:param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
|
|
124
|
+
:param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
|
|
125
|
+
:param threshold: The threshold for multilabel classification. Defaults to 0.5. Ignored if not multilabel.
|
|
126
|
+
:return: The predicted labels or probabilities.
|
|
127
|
+
"""
|
|
128
|
+
encoded = self._encode_and_coerce_to_2d(
|
|
97
129
|
X,
|
|
98
130
|
show_progress_bar=show_progress_bar,
|
|
99
131
|
max_length=max_length,
|
|
@@ -102,6 +134,13 @@ class StaticModelPipeline:
|
|
|
102
134
|
multiprocessing_threshold=multiprocessing_threshold,
|
|
103
135
|
)
|
|
104
136
|
|
|
137
|
+
if self.multilabel:
|
|
138
|
+
out_labels = []
|
|
139
|
+
proba = self.head.predict_proba(encoded)
|
|
140
|
+
for vector in proba:
|
|
141
|
+
out_labels.append(self.classes_[vector > threshold])
|
|
142
|
+
return np.asarray(out_labels, dtype=object)
|
|
143
|
+
|
|
105
144
|
return self.head.predict(encoded)
|
|
106
145
|
|
|
107
146
|
def predict_proba(
|
|
@@ -113,8 +152,18 @@ class StaticModelPipeline:
|
|
|
113
152
|
use_multiprocessing: bool = True,
|
|
114
153
|
multiprocessing_threshold: int = 10_000,
|
|
115
154
|
) -> np.ndarray:
|
|
116
|
-
"""
|
|
117
|
-
|
|
155
|
+
"""
|
|
156
|
+
Predict the labels of the input.
|
|
157
|
+
|
|
158
|
+
:param X: The input data to predict. Can be a list of strings or a single string.
|
|
159
|
+
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
|
|
160
|
+
:param max_length: The maximum length of the input sequences. Defaults to 512.
|
|
161
|
+
:param batch_size: The batch size for prediction. Defaults to 1024.
|
|
162
|
+
:param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
|
|
163
|
+
:param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
|
|
164
|
+
:return: The predicted labels or probabilities.
|
|
165
|
+
"""
|
|
166
|
+
encoded = self._encode_and_coerce_to_2d(
|
|
118
167
|
X,
|
|
119
168
|
show_progress_bar=show_progress_bar,
|
|
120
169
|
max_length=max_length,
|
|
@@ -125,6 +174,24 @@ class StaticModelPipeline:
|
|
|
125
174
|
|
|
126
175
|
return self.head.predict_proba(encoded)
|
|
127
176
|
|
|
177
|
+
def evaluate(
|
|
178
|
+
self, X: list[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5, output_dict: bool = False
|
|
179
|
+
) -> str | dict[str, dict[str, float]]:
|
|
180
|
+
"""
|
|
181
|
+
Evaluate the classifier on a given dataset using scikit-learn's classification report.
|
|
182
|
+
|
|
183
|
+
:param X: The texts to predict on.
|
|
184
|
+
:param y: The ground truth labels.
|
|
185
|
+
:param batch_size: The batch size.
|
|
186
|
+
:param threshold: The threshold for multilabel classification.
|
|
187
|
+
:param output_dict: Whether to output the classification report as a dictionary.
|
|
188
|
+
:return: A classification report.
|
|
189
|
+
"""
|
|
190
|
+
predictions = self.predict(X, show_progress_bar=True, batch_size=batch_size, threshold=threshold)
|
|
191
|
+
report = evaluate_single_or_multi_label(predictions=predictions, y=y, output_dict=output_dict)
|
|
192
|
+
|
|
193
|
+
return report
|
|
194
|
+
|
|
128
195
|
|
|
129
196
|
def _load_pipeline(
|
|
130
197
|
folder_or_repo_path: PathLike, token: str | None = None, trust_remote_code: bool = False
|
|
@@ -200,3 +267,41 @@ def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> Non
|
|
|
200
267
|
language=pipeline.model.language,
|
|
201
268
|
template_path="modelcards/classifier_template.md",
|
|
202
269
|
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _is_multi_label_shaped(y: LabelType) -> bool:
|
|
273
|
+
"""Check if the labels are in a multi-label shape."""
|
|
274
|
+
return isinstance(y, (list, tuple)) and len(y) > 0 and isinstance(y[0], (list, tuple, set))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def evaluate_single_or_multi_label(
|
|
278
|
+
predictions: np.ndarray,
|
|
279
|
+
y: LabelType,
|
|
280
|
+
output_dict: bool = False,
|
|
281
|
+
) -> str | dict[str, dict[str, float]]:
|
|
282
|
+
"""
|
|
283
|
+
Evaluate the classifier on a given dataset using scikit-learn's classification report.
|
|
284
|
+
|
|
285
|
+
:param predictions: The predictions.
|
|
286
|
+
:param y: The ground truth labels.
|
|
287
|
+
:param output_dict: Whether to output the classification report as a dictionary.
|
|
288
|
+
:return: A classification report.
|
|
289
|
+
"""
|
|
290
|
+
if _is_multi_label_shaped(y):
|
|
291
|
+
classes = sorted(set([label for labels in y for label in labels]))
|
|
292
|
+
mlb = MultiLabelBinarizer(classes=classes)
|
|
293
|
+
y = mlb.fit_transform(y)
|
|
294
|
+
predictions = mlb.transform(predictions)
|
|
295
|
+
elif isinstance(y[0], (str, int)):
|
|
296
|
+
classes = sorted(set(y))
|
|
297
|
+
|
|
298
|
+
report = classification_report(
|
|
299
|
+
y,
|
|
300
|
+
predictions,
|
|
301
|
+
labels=np.arange(len(classes)),
|
|
302
|
+
target_names=[str(c) for c in classes],
|
|
303
|
+
output_dict=output_dict,
|
|
304
|
+
zero_division=0,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
return report
|
|
@@ -27,10 +27,11 @@ predicted = model.predict(["Example sentence"])
|
|
|
27
27
|
|
|
28
28
|
## Additional Resources
|
|
29
29
|
|
|
30
|
-
- [All Model2Vec models on the hub](https://huggingface.co/models?library=model2vec)
|
|
31
30
|
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
32
|
-
- [Model2Vec
|
|
31
|
+
- [Model2Vec Base Models](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e)
|
|
32
|
+
- [Model2Vec Results](https://github.com/MinishLab/model2vec/tree/main/results)
|
|
33
33
|
- [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials)
|
|
34
|
+
- [Website](https://minishlab.github.io/)
|
|
34
35
|
|
|
35
36
|
## Library Authors
|
|
36
37
|
|
|
@@ -41,9 +42,9 @@ Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team c
|
|
|
41
42
|
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
42
43
|
```
|
|
43
44
|
@software{minishlab2024model2vec,
|
|
44
|
-
authors = {Stephan Tulkens
|
|
45
|
-
title = {Model2Vec:
|
|
45
|
+
authors = {Stephan Tulkens and Thomas van Dongen},
|
|
46
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
46
47
|
year = {2024},
|
|
47
|
-
url = {https://github.com/MinishLab/model2vec}
|
|
48
|
+
url = {https://github.com/MinishLab/model2vec}
|
|
48
49
|
}
|
|
49
50
|
```
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# {{ model_name }} Model Card
|
|
6
6
|
|
|
7
|
-
This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of {% if base_model %}the {{ base_model }}(https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical.
|
|
7
|
+
This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of {% if base_model %}the {{ base_model }}(https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical. Model2Vec models are the smallest, fastest, and most performant static embedders available. The distilled models are up to 50 times smaller and 500 times faster than traditional Sentence Transformers.
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
## Installation
|
|
@@ -15,6 +15,11 @@ pip install model2vec
|
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
## Usage
|
|
18
|
+
|
|
19
|
+
### Using Model2Vec
|
|
20
|
+
|
|
21
|
+
The [Model2Vec library](https://github.com/MinishLab/model2vec) is the fastest and most lightweight way to run Model2Vec models.
|
|
22
|
+
|
|
18
23
|
Load this model using the `from_pretrained` method:
|
|
19
24
|
```python
|
|
20
25
|
from model2vec import StaticModel
|
|
@@ -26,15 +31,29 @@ model = StaticModel.from_pretrained("{{ model_name }}")
|
|
|
26
31
|
embeddings = model.encode(["Example sentence"])
|
|
27
32
|
```
|
|
28
33
|
|
|
29
|
-
|
|
34
|
+
### Using Sentence Transformers
|
|
35
|
+
|
|
36
|
+
You can also use the [Sentence Transformers library](https://github.com/UKPLab/sentence-transformers) to load and use the model:
|
|
37
|
+
|
|
30
38
|
```python
|
|
31
|
-
from
|
|
39
|
+
from sentence_transformers import SentenceTransformer
|
|
40
|
+
|
|
41
|
+
# Load a pretrained Sentence Transformer model
|
|
42
|
+
model = SentenceTransformer("{{ model_name }}")
|
|
43
|
+
|
|
44
|
+
# Compute text embeddings
|
|
45
|
+
embeddings = model.encode(["Example sentence"])
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Distilling a Model2Vec model
|
|
32
49
|
|
|
33
|
-
|
|
34
|
-
model_name = "BAAI/bge-base-en-v1.5"
|
|
50
|
+
You can distill a Model2Vec model from a Sentence Transformer model using the `distill` method. First, install the `distill` extra with `pip install model2vec[distill]`. Then, run the following code:
|
|
35
51
|
|
|
36
|
-
|
|
37
|
-
|
|
52
|
+
```python
|
|
53
|
+
from model2vec.distill import distill
|
|
54
|
+
|
|
55
|
+
# Distill a Sentence Transformer model, in this case the BAAI/bge-base-en-v1.5 model
|
|
56
|
+
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)
|
|
38
57
|
|
|
39
58
|
# Save the model
|
|
40
59
|
m2v_model.save_pretrained("m2v_model")
|
|
@@ -44,14 +63,16 @@ m2v_model.save_pretrained("m2v_model")
|
|
|
44
63
|
|
|
45
64
|
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.
|
|
46
65
|
|
|
47
|
-
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
|
|
66
|
+
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 [SIF weighting](https://openreview.net/pdf?id=SyK00v5xx). During inference, we simply take the mean of all token embeddings occurring in a sentence.
|
|
48
67
|
|
|
49
68
|
## Additional Resources
|
|
50
69
|
|
|
51
|
-
- [All Model2Vec models on the hub](https://huggingface.co/models?library=model2vec)
|
|
52
70
|
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
53
|
-
- [Model2Vec
|
|
71
|
+
- [Model2Vec Base Models](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e)
|
|
72
|
+
- [Model2Vec Results](https://github.com/MinishLab/model2vec/tree/main/results)
|
|
54
73
|
- [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials)
|
|
74
|
+
- [Website](https://minishlab.github.io/)
|
|
75
|
+
|
|
55
76
|
|
|
56
77
|
## Library Authors
|
|
57
78
|
|
|
@@ -62,9 +83,9 @@ Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team c
|
|
|
62
83
|
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
63
84
|
```
|
|
64
85
|
@software{minishlab2024model2vec,
|
|
65
|
-
authors = {Stephan Tulkens
|
|
66
|
-
title = {Model2Vec:
|
|
86
|
+
authors = {Stephan Tulkens and Thomas van Dongen},
|
|
87
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
67
88
|
year = {2024},
|
|
68
|
-
url = {https://github.com/MinishLab/model2vec}
|
|
89
|
+
url = {https://github.com/MinishLab/model2vec}
|
|
69
90
|
}
|
|
70
91
|
```
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Aside from [distillation](../../README.md#distillation), `model2vec` also supports training simple classifiers on top of static models, using [pytorch](https://pytorch.org/), [lightning](https://lightning.ai/) and [scikit-learn](https://scikit-learn.org/stable/index.html).
|
|
4
4
|
|
|
5
|
+
We support both single and multi-label classification, which work seamlessly based on the labels you provide.
|
|
6
|
+
|
|
5
7
|
# Installation
|
|
6
8
|
|
|
7
9
|
To train, make sure you install the training extra:
|
|
@@ -20,7 +22,7 @@ from model2vec.train import StaticModelForClassification
|
|
|
20
22
|
|
|
21
23
|
# From a distilled model
|
|
22
24
|
distilled_model = distill("baai/bge-base-en-v1.5")
|
|
23
|
-
classifier = StaticModelForClassification.from_static_model(distilled_model)
|
|
25
|
+
classifier = StaticModelForClassification.from_static_model(model=distilled_model)
|
|
24
26
|
|
|
25
27
|
# From a pre-trained model: potion is the default
|
|
26
28
|
classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32m")
|
|
@@ -42,11 +44,10 @@ test = ds["test"]
|
|
|
42
44
|
s = perf_counter()
|
|
43
45
|
classifier = classifier.fit(train["text"], train["label"])
|
|
44
46
|
|
|
45
|
-
predicted = classifier.predict(test["text"])
|
|
46
47
|
print(f"Training took {int(perf_counter() - s)} seconds.")
|
|
47
48
|
# Training took 81 seconds
|
|
48
|
-
|
|
49
|
-
print(
|
|
49
|
+
classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["label"])
|
|
50
|
+
print(classification_report)
|
|
50
51
|
# Achieved 91.0 test accuracy
|
|
51
52
|
```
|
|
52
53
|
|
|
@@ -65,6 +66,44 @@ print(f"Took {int((perf_counter() - s) * 1000)} milliseconds for {len(test)} ins
|
|
|
65
66
|
# Took 67 milliseconds for 2000 instances on CPU.
|
|
66
67
|
```
|
|
67
68
|
|
|
69
|
+
## Multi-label classification
|
|
70
|
+
|
|
71
|
+
Multi-label classification is supported out of the box. Just pass a list of lists to the `fit` function (e.g. `[[label1, label2], [label1, label3]]`), and a multi-label classifier will be trained. For example, the following code trains a multi-label classifier on the [go_emotions](https://huggingface.co/datasets/google-research-datasets/go_emotions) dataset:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from datasets import load_dataset
|
|
75
|
+
from model2vec.train import StaticModelForClassification
|
|
76
|
+
|
|
77
|
+
# Initialize a classifier from a pre-trained model
|
|
78
|
+
classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
|
|
79
|
+
|
|
80
|
+
# Load a multi-label dataset
|
|
81
|
+
ds = load_dataset("google-research-datasets/go_emotions")
|
|
82
|
+
|
|
83
|
+
# Inspect some of the labels
|
|
84
|
+
print(ds["train"]["labels"][40:50])
|
|
85
|
+
# [[0, 15], [15, 18], [16, 27], [27], [7, 13], [10], [20], [27], [27], [27]]
|
|
86
|
+
|
|
87
|
+
# Train the classifier on text (X) and labels (y)
|
|
88
|
+
classifier.fit(ds["train"]["text"], ds["train"]["labels"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then, we can evaluate the classifier:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from sklearn import metrics
|
|
95
|
+
from sklearn.preprocessing import MultiLabelBinarizer
|
|
96
|
+
|
|
97
|
+
classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["labels"], threshold=0.3)
|
|
98
|
+
print(classification_report)
|
|
99
|
+
# Accuracy: 0.410
|
|
100
|
+
# Precision: 0.527
|
|
101
|
+
# Recall: 0.410
|
|
102
|
+
# F1: 0.439
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The scores are competitive with the popular [roberta-base-go_emotions](https://huggingface.co/SamLowe/roberta-base-go_emotions) model, while our model is orders of magnitude faster.
|
|
106
|
+
|
|
68
107
|
# Persistence
|
|
69
108
|
|
|
70
109
|
You can turn a classifier into a scikit-learn compatible pipeline, as follows:
|
|
@@ -106,3 +145,7 @@ The core functionality of the `StaticModelForClassification` is contained in a c
|
|
|
106
145
|
* `fit`: contains all the lightning-related fitting logic.
|
|
107
146
|
|
|
108
147
|
The training of the model is done in a `lighting.LightningModule`, which can be modified but is very basic.
|
|
148
|
+
|
|
149
|
+
# Results
|
|
150
|
+
|
|
151
|
+
We ran extensive benchmarks where we compared our model to several well known architectures. The results can be found in the [training results](https://github.com/MinishLab/model2vec/tree/main/results#training-results) documentation.
|
|
@@ -45,14 +45,14 @@ class FinetunableStaticModel(nn.Module):
|
|
|
45
45
|
|
|
46
46
|
@classmethod
|
|
47
47
|
def from_pretrained(
|
|
48
|
-
cls: type[ModelType], out_dim: int = 2, model_name: str = "minishlab/potion-base-32m", **kwargs: Any
|
|
48
|
+
cls: type[ModelType], *, out_dim: int = 2, model_name: str = "minishlab/potion-base-32m", **kwargs: Any
|
|
49
49
|
) -> ModelType:
|
|
50
50
|
"""Load the model from a pretrained model2vec model."""
|
|
51
51
|
model = StaticModel.from_pretrained(model_name)
|
|
52
|
-
return cls.from_static_model(model, out_dim, **kwargs)
|
|
52
|
+
return cls.from_static_model(model=model, out_dim=out_dim, **kwargs)
|
|
53
53
|
|
|
54
54
|
@classmethod
|
|
55
|
-
def from_static_model(cls: type[ModelType], model: StaticModel, out_dim: int = 2, **kwargs: Any) -> ModelType:
|
|
55
|
+
def from_static_model(cls: type[ModelType], *, model: StaticModel, out_dim: int = 2, **kwargs: Any) -> ModelType:
|
|
56
56
|
"""Load the model from a static model."""
|
|
57
57
|
model.embedding = np.nan_to_num(model.embedding)
|
|
58
58
|
embeddings_converted = torch.from_numpy(model.embedding)
|