model2vec 0.3.8__py3-none-any.whl → 0.4.0__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.
@@ -40,7 +40,8 @@ def distill_from_model(
40
40
  vocabulary: list[str] | None = None,
41
41
  device: str | None = None,
42
42
  pca_dims: PCADimType = 256,
43
- apply_zipf: bool = True,
43
+ apply_zipf: bool | None = None,
44
+ sif_coefficient: float | None = 1e-4,
44
45
  use_subword: bool = True,
45
46
  token_remove_pattern: str | None = r"\[unused\d+\]",
46
47
  ) -> StaticModel:
@@ -60,30 +61,19 @@ def distill_from_model(
60
61
  :param pca_dims: The number of components to use for PCA.
61
62
  If this is None, we don't apply PCA.
62
63
  If this is 'auto', we don't reduce dimensionality, but still apply PCA.
63
- :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
64
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
65
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
66
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
67
+ Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
64
68
  :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
65
69
  :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
66
70
  If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled into a valid regex, we also throw an error.
67
- :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
68
- :raises: ValueError if the vocabulary contains duplicate tokens.
69
- :raises: ValueError if the regex can't be compiled.
70
- :raises: ValueError if the vocabulary is empty after token removal.
71
71
  :return: A StaticModel
72
72
 
73
73
  """
74
- device = select_optimal_device(device)
75
- if not use_subword and vocabulary is None:
76
- raise ValueError(
77
- "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
78
- )
79
-
80
- if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
81
- raise ValueError(
82
- "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
83
- "This is not supported yet."
84
- "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
85
- )
74
+ sif_coefficient = _validate_parameters(tokenizer, vocabulary, apply_zipf, sif_coefficient, use_subword)
86
75
 
76
+ device = select_optimal_device(device)
87
77
  # Make a base list of tokens.
88
78
  tokens: list[str] = []
89
79
  if use_subword:
@@ -129,7 +119,7 @@ def distill_from_model(
129
119
  logger.warning("Didn't create any token embeddings as all tokens were duplicates or empty.")
130
120
 
131
121
  # Post process the embeddings by applying PCA and Zipf weighting.
132
- embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
122
+ embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
133
123
 
134
124
  model_name = getattr(model, "name_or_path", "")
135
125
 
@@ -139,8 +129,10 @@ def distill_from_model(
139
129
  "tokenizer_name": model_name,
140
130
  "apply_pca": pca_dims,
141
131
  "apply_zipf": apply_zipf,
132
+ "sif_coefficient": sif_coefficient,
142
133
  "hidden_dim": embeddings.shape[1],
143
134
  "seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
135
+ "normalize": True,
144
136
  }
145
137
 
146
138
  if os.path.exists(model_name):
@@ -157,10 +149,71 @@ def distill_from_model(
157
149
  language = None
158
150
 
159
151
  return StaticModel(
160
- vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
152
+ vectors=embeddings,
153
+ tokenizer=new_tokenizer,
154
+ config=config,
155
+ base_model_name=model_name,
156
+ language=language,
157
+ normalize=True,
161
158
  )
162
159
 
163
160
 
161
+ def _validate_parameters(
162
+ tokenizer: PreTrainedTokenizerFast,
163
+ vocabulary: list[str] | None,
164
+ apply_zipf: bool | None,
165
+ sif_coefficient: float | None,
166
+ use_subword: bool,
167
+ ) -> float | None:
168
+ """
169
+ Validate the parameters passed to the distillation function.
170
+
171
+ :param tokenizer: The tokenizer to use.
172
+ :param vocabulary: The vocabulary to use.
173
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
174
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
175
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
176
+ Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
177
+ :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
178
+ :return: The SIF coefficient to use.
179
+ :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
180
+ :raises: ValueError if the vocabulary contains duplicate tokens.
181
+ :raises: ValueError if the regex can't be compiled.
182
+ :raises: ValueError if the vocabulary is empty after token removal.
183
+
184
+ """
185
+ if apply_zipf is not None:
186
+ logger.warning(
187
+ "The `apply_zipf` parameter is deprecated and will be removed in the next release. "
188
+ "Zipf weighting is applied based on the sif_coefficient parameter. If this is set to None, "
189
+ "no weighting is applied."
190
+ )
191
+ if apply_zipf and sif_coefficient is None:
192
+ logger.warning("You set apply_zipf to True, but sif_coefficient is None. Setting sif_coefficient to 1e-4.")
193
+ sif_coefficient = 1e-4
194
+ elif not apply_zipf:
195
+ logger.warning("Because you set apply_zipf to False, we ignore the sif_coefficient parameter.")
196
+ sif_coefficient = None
197
+
198
+ if sif_coefficient is not None:
199
+ if not 0 < sif_coefficient < 1.0:
200
+ raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
201
+
202
+ if not use_subword and vocabulary is None:
203
+ raise ValueError(
204
+ "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
205
+ )
206
+
207
+ if vocabulary and isinstance(tokenizer.backend_tokenizer.model, (BPE, Unigram)):
208
+ raise ValueError(
209
+ "You passed a vocabulary, but the model you are using does not use a WordPiece tokenizer. "
210
+ "This is not supported yet."
211
+ "Feel free to open an issue if this is a blocker: https://github.com/MinishLab/model2vec/issues"
212
+ )
213
+
214
+ return sif_coefficient
215
+
216
+
164
217
  def _remove_tokens_and_embeddings(
165
218
  tokenizer: PreTrainedTokenizerFast, token_remove_pattern: str | None, tokens: list[str], embeddings: np.ndarray
166
219
  ) -> tuple[Tokenizer, np.ndarray]:
@@ -201,9 +254,11 @@ def distill(
201
254
  vocabulary: list[str] | None = None,
202
255
  device: str | None = None,
203
256
  pca_dims: PCADimType = 256,
204
- apply_zipf: bool = True,
257
+ apply_zipf: bool | None = None,
258
+ sif_coefficient: float | None = 1e-4,
205
259
  use_subword: bool = True,
206
260
  token_remove_pattern: str | None = r"\[unused\d+\]",
261
+ trust_remote_code: bool = False,
207
262
  ) -> StaticModel:
208
263
  """
209
264
  Distill a staticmodel from a sentence transformer.
@@ -220,14 +275,18 @@ def distill(
220
275
  :param pca_dims: The number of components to use for PCA.
221
276
  If this is None, we don't apply PCA.
222
277
  If this is 'auto', we don't reduce dimenionality, but still apply PCA.
223
- :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
278
+ :param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
279
+ Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
280
+ :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
281
+ Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
224
282
  :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
225
283
  :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
284
+ :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `transformers`. If this is True, we will load all components.
226
285
  :return: A StaticModel
227
286
 
228
287
  """
229
- model: PreTrainedModel = AutoModel.from_pretrained(model_name)
230
- tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
288
+ model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)
289
+ tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code)
231
290
 
232
291
  return distill_from_model(
233
292
  model=model,
@@ -238,11 +297,14 @@ def distill(
238
297
  apply_zipf=apply_zipf,
239
298
  use_subword=use_subword,
240
299
  token_remove_pattern=token_remove_pattern,
300
+ sif_coefficient=sif_coefficient,
241
301
  )
242
302
 
243
303
 
244
- def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply_zipf: bool) -> np.ndarray:
245
- """Post process embeddings by applying PCA and Zipf weighting."""
304
+ def _post_process_embeddings(
305
+ embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4
306
+ ) -> np.ndarray:
307
+ """Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law."""
246
308
  if pca_dims is not None:
247
309
  if pca_dims == "auto":
248
310
  pca_dims = embeddings.shape[1]
@@ -274,9 +336,11 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
274
336
  logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
275
337
  logger.info(f"Explained variance: {explained_variance:.3f}.")
276
338
 
277
- if apply_zipf:
278
- logger.info("Applying Zipf weighting")
279
- embeddings *= np.log(1 + np.arange(embeddings.shape[0]))[:, None]
339
+ if sif_coefficient is not None:
340
+ logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
341
+ inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
342
+ proba = inv_rank / np.sum(inv_rank)
343
+ embeddings *= (sif_coefficient / (sif_coefficient + proba))[:, None]
280
344
 
281
345
  return embeddings
282
346
 
model2vec/hf_utils.py CHANGED
@@ -60,6 +60,7 @@ def _create_model_card(
60
60
  license: str = "mit",
61
61
  language: list[str] | None = None,
62
62
  model_name: str | None = None,
63
+ template_path: str = "modelcards/model_card_template.md",
63
64
  **kwargs: Any,
64
65
  ) -> None:
65
66
  """
@@ -70,11 +71,12 @@ def _create_model_card(
70
71
  :param license: The license to use.
71
72
  :param language: The language of the model.
72
73
  :param model_name: The name of the model to use in the Model Card.
74
+ :param template_path: The path to the template.
73
75
  :param **kwargs: Additional metadata for the model card (e.g., model_name, base_model, etc.).
74
76
  """
75
77
  folder_path = Path(folder_path)
76
78
  model_name = model_name or folder_path.name
77
- template_path = Path(__file__).parent / "model_card_template.md"
79
+ full_path = Path(__file__).parent / template_path
78
80
 
79
81
  model_card_data = ModelCardData(
80
82
  model_name=model_name,
@@ -85,7 +87,7 @@ def _create_model_card(
85
87
  library_name="model2vec",
86
88
  **kwargs,
87
89
  )
88
- model_card = ModelCard.from_template(model_card_data, template_path=template_path)
90
+ model_card = ModelCard.from_template(model_card_data, template_path=full_path)
89
91
  model_card.save(folder_path / "README.md")
90
92
 
91
93
 
@@ -0,0 +1,18 @@
1
+ # Inference
2
+
3
+ This subpackage mainly contains helper functions for inference with trained models that have been exported to `scikit-learn` compatible pipelines.
4
+
5
+ If you're looking for information on how to train a model, see [here](../train/README.md).
6
+
7
+ # Usage
8
+
9
+ Let's assume you're using our [potion-edu classifier](https://huggingface.co/minishlab/potion-8m-edu-classifier).
10
+
11
+ ```python
12
+ from model2vec.inference import StaticModelPipeline
13
+
14
+ classifier = StaticModelPipeline.from_pretrained("minishlab/potion-8m-edu-classifier")
15
+ label = classifier.predict("Attitudes towards cattle in the Alps: a study in letting go.")
16
+ ```
17
+
18
+ This should just work.
@@ -0,0 +1,10 @@
1
+ from model2vec.utils import get_package_extras, importable
2
+
3
+ _REQUIRED_EXTRA = "inference"
4
+
5
+ for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA):
6
+ importable(extra_dependency, _REQUIRED_EXTRA)
7
+
8
+ from model2vec.inference.model import StaticModelPipeline
9
+
10
+ __all__ = ["StaticModelPipeline"]
@@ -0,0 +1,202 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+
7
+ import huggingface_hub
8
+ import numpy as np
9
+ import skops.io
10
+ from sklearn.pipeline import Pipeline
11
+
12
+ from model2vec.hf_utils import _create_model_card
13
+ from model2vec.model import PathLike, StaticModel
14
+
15
+ _DEFAULT_TRUST_PATTERN = re.compile(r"sklearn\..+")
16
+ _DEFAULT_MODEL_FILENAME = "pipeline.skops"
17
+
18
+
19
+ class StaticModelPipeline:
20
+ def __init__(self, model: StaticModel, head: Pipeline) -> None:
21
+ """Create a pipeline with a StaticModel encoder."""
22
+ self.model = model
23
+ self.head = head
24
+
25
+ @classmethod
26
+ def from_pretrained(
27
+ cls: type[StaticModelPipeline], path: PathLike, token: str | None = None, trust_remote_code: bool = False
28
+ ) -> StaticModelPipeline:
29
+ """
30
+ Load a StaticModel from a local path or huggingface hub path.
31
+
32
+ NOTE: if you load a private model from the huggingface hub, you need to pass a token.
33
+
34
+ :param path: The path to the folder containing the pipeline, or a repository on the Hugging Face Hub
35
+ :param token: The token to use to download the pipeline from the hub.
36
+ :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `sklearn`.
37
+ :return: The loaded pipeline.
38
+ """
39
+ model, head = _load_pipeline(path, token, trust_remote_code)
40
+ model.embedding = np.nan_to_num(model.embedding)
41
+
42
+ return cls(model, head)
43
+
44
+ def save_pretrained(self, path: str) -> None:
45
+ """Save the model to a folder."""
46
+ save_pipeline(self, path)
47
+
48
+ def push_to_hub(self, repo_id: str, token: str | None = None, private: bool = False) -> None:
49
+ """
50
+ Save a model to a folder, and then push that folder to the hf hub.
51
+
52
+ :param repo_id: The id of the repository to push to.
53
+ :param token: The token to use to push to the hub.
54
+ :param private: Whether the repository should be private.
55
+ """
56
+ from model2vec.hf_utils import push_folder_to_hub
57
+
58
+ with TemporaryDirectory() as temp_dir:
59
+ save_pipeline(self, temp_dir)
60
+ self.model.save_pretrained(temp_dir)
61
+ push_folder_to_hub(Path(temp_dir), repo_id, private, token)
62
+
63
+ def _predict_and_coerce_to_2d(
64
+ self,
65
+ X: list[str] | str,
66
+ show_progress_bar: bool,
67
+ max_length: int | None,
68
+ batch_size: int,
69
+ use_multiprocessing: bool,
70
+ multiprocessing_threshold: int,
71
+ ) -> np.ndarray:
72
+ """Predict the labels of the input and coerce the output to a matrix."""
73
+ encoded = self.model.encode(
74
+ X,
75
+ show_progress_bar=show_progress_bar,
76
+ max_length=max_length,
77
+ batch_size=batch_size,
78
+ use_multiprocessing=use_multiprocessing,
79
+ multiprocessing_threshold=multiprocessing_threshold,
80
+ )
81
+ if np.ndim(encoded) == 1:
82
+ encoded = encoded[None, :]
83
+
84
+ return encoded
85
+
86
+ def predict(
87
+ self,
88
+ X: list[str] | str,
89
+ show_progress_bar: bool = False,
90
+ max_length: int | None = 512,
91
+ batch_size: int = 1024,
92
+ use_multiprocessing: bool = True,
93
+ multiprocessing_threshold: int = 10_000,
94
+ ) -> np.ndarray:
95
+ """Predict the labels of the input."""
96
+ encoded = self._predict_and_coerce_to_2d(
97
+ X,
98
+ show_progress_bar=show_progress_bar,
99
+ max_length=max_length,
100
+ batch_size=batch_size,
101
+ use_multiprocessing=use_multiprocessing,
102
+ multiprocessing_threshold=multiprocessing_threshold,
103
+ )
104
+
105
+ return self.head.predict(encoded)
106
+
107
+ def predict_proba(
108
+ self,
109
+ X: list[str] | str,
110
+ show_progress_bar: bool = False,
111
+ max_length: int | None = 512,
112
+ batch_size: int = 1024,
113
+ use_multiprocessing: bool = True,
114
+ multiprocessing_threshold: int = 10_000,
115
+ ) -> np.ndarray:
116
+ """Predict the probabilities of the labels of the input."""
117
+ encoded = self._predict_and_coerce_to_2d(
118
+ X,
119
+ show_progress_bar=show_progress_bar,
120
+ max_length=max_length,
121
+ batch_size=batch_size,
122
+ use_multiprocessing=use_multiprocessing,
123
+ multiprocessing_threshold=multiprocessing_threshold,
124
+ )
125
+
126
+ return self.head.predict_proba(encoded)
127
+
128
+
129
+ def _load_pipeline(
130
+ folder_or_repo_path: PathLike, token: str | None = None, trust_remote_code: bool = False
131
+ ) -> tuple[StaticModel, Pipeline]:
132
+ """
133
+ Load a model and an sklearn pipeline.
134
+
135
+ This assumes the following files are present in the repo:
136
+ - `pipeline.skops`: The head of the pipeline.
137
+ - `config.json`: The configuration of the model.
138
+ - `model.safetensors`: The weights of the model.
139
+ - `tokenizer.json`: The tokenizer of the model.
140
+
141
+ :param folder_or_repo_path: The path to the folder containing the pipeline.
142
+ :param token: The token to use to download the pipeline from the hub. If this is None, you will only
143
+ be able to load the pipeline from a local folder, public repository, or a repository that you have access to
144
+ because you are logged in.
145
+ :param trust_remote_code: Whether to trust the remote code. If this is False,
146
+ we will only load components coming from `sklearn`. If this is True, we will load all components.
147
+ If you set this to True, you are responsible for whatever happens.
148
+ :return: The encoder model and the loaded head
149
+ :raises FileNotFoundError: If the pipeline file does not exist in the folder.
150
+ :raises ValueError: If an untrusted type is found in the pipeline, and `trust_remote_code` is False.
151
+ """
152
+ folder_or_repo_path = Path(folder_or_repo_path)
153
+ model_filename = _DEFAULT_MODEL_FILENAME
154
+ if folder_or_repo_path.exists():
155
+ head_pipeline_path = folder_or_repo_path / model_filename
156
+ if not head_pipeline_path.exists():
157
+ raise FileNotFoundError(f"Pipeline file does not exist in {folder_or_repo_path}")
158
+ else:
159
+ head_pipeline_path = huggingface_hub.hf_hub_download(
160
+ folder_or_repo_path.as_posix(), model_filename, token=token
161
+ )
162
+
163
+ model = StaticModel.from_pretrained(folder_or_repo_path)
164
+
165
+ unknown_types = skops.io.get_untrusted_types(file=head_pipeline_path)
166
+ # If the user does not trust remote code, we should check that the unknown types are trusted.
167
+ # By default, we trust everything coming from scikit-learn.
168
+ if not trust_remote_code:
169
+ for t in unknown_types:
170
+ if not _DEFAULT_TRUST_PATTERN.match(t):
171
+ raise ValueError(f"Untrusted type {t}.")
172
+ head = skops.io.load(head_pipeline_path, trusted=unknown_types)
173
+
174
+ return model, head
175
+
176
+
177
+ def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> None:
178
+ """
179
+ Save a pipeline to a folder.
180
+
181
+ :param pipeline: The pipeline to save.
182
+ :param folder_path: The path to the folder to save the pipeline to.
183
+ """
184
+ folder_path = Path(folder_path)
185
+ folder_path.mkdir(parents=True, exist_ok=True)
186
+ model_filename = _DEFAULT_MODEL_FILENAME
187
+ head_pipeline_path = folder_path / model_filename
188
+ skops.io.dump(pipeline.head, head_pipeline_path)
189
+ pipeline.model.save_pretrained(folder_path)
190
+ base_model_name = pipeline.model.base_model_name
191
+ if isinstance(base_model_name, list) and base_model_name:
192
+ name = base_model_name[0]
193
+ elif isinstance(base_model_name, str):
194
+ name = base_model_name
195
+ else:
196
+ name = "unknown"
197
+ _create_model_card(
198
+ folder_path,
199
+ base_model_name=name,
200
+ language=pipeline.model.language,
201
+ template_path="modelcards/classifier_template.md",
202
+ )
model2vec/model.py CHANGED
@@ -87,7 +87,7 @@ class StaticModel:
87
87
  @normalize.setter
88
88
  def normalize(self, value: bool) -> None:
89
89
  """Update the config if the value of normalize changes."""
90
- config_normalize = self.config.get("normalize", False)
90
+ config_normalize = self.config.get("normalize")
91
91
  self._normalize = value
92
92
  if config_normalize is not None and value != config_normalize:
93
93
  logger.warning(
@@ -0,0 +1,49 @@
1
+ ---
2
+ {{ card_data }}
3
+ ---
4
+
5
+ # {{ model_name }} Model Card
6
+
7
+ This [Model2Vec](https://github.com/MinishLab/model2vec) model is a fine-tuned version of {% if base_model %}the [{{ base_model }}](https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Model2Vec model. It also includes a classifier head on top.
8
+
9
+ ## Installation
10
+
11
+ Install model2vec using pip:
12
+ ```
13
+ pip install model2vec[inference]
14
+ ```
15
+
16
+ ## Usage
17
+ Load this model using the `from_pretrained` method:
18
+ ```python
19
+ from model2vec.inference import StaticModelPipeline
20
+
21
+ # Load a pretrained Model2Vec model
22
+ model = StaticModelPipeline.from_pretrained("{{ model_name }}")
23
+
24
+ # Predict labels
25
+ predicted = model.predict(["Example sentence"])
26
+ ```
27
+
28
+ ## Additional Resources
29
+
30
+ - [All Model2Vec models on the hub](https://huggingface.co/models?library=model2vec)
31
+ - [Model2Vec Repo](https://github.com/MinishLab/model2vec)
32
+ - [Model2Vec Results](https://github.com/MinishLab/model2vec?tab=readme-ov-file#results)
33
+ - [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials)
34
+
35
+ ## Library Authors
36
+
37
+ Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team consisting of [Stephan Tulkens](https://github.com/stephantul) and [Thomas van Dongen](https://github.com/Pringled).
38
+
39
+ ## Citation
40
+
41
+ Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
42
+ ```
43
+ @software{minishlab2024model2vec,
44
+ authors = {Stephan Tulkens, Thomas van Dongen},
45
+ title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
46
+ year = {2024},
47
+ url = {https://github.com/MinishLab/model2vec},
48
+ }
49
+ ```
@@ -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.
8
8
 
9
9
 
10
10
  ## Installation
@@ -0,0 +1,108 @@
1
+ # Training
2
+
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
+
5
+ # Installation
6
+
7
+ To train, make sure you install the training extra:
8
+
9
+ ```
10
+ pip install model2vec[training]
11
+ ```
12
+
13
+ # Quickstart
14
+
15
+ To train a model, simply initialize it using a `StaticModel`, or from a pre-trained model, as follows:
16
+
17
+ ```python
18
+ from model2vec.distill import distill
19
+ from model2vec.train import StaticModelForClassification
20
+
21
+ # From a distilled model
22
+ distilled_model = distill("baai/bge-base-en-v1.5")
23
+ classifier = StaticModelForClassification.from_static_model(distilled_model)
24
+
25
+ # From a pre-trained model: potion is the default
26
+ classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32m")
27
+ ```
28
+
29
+ This creates a very simple classifier: a StaticModel with a single 512-unit hidden layer on top. You can adjust the number of hidden layers and the number units through some parameters on both functions. Note that the default for `from_pretrained` is [potion-base-32m](https://huggingface.co/minishlab/potion-base-32M), our best model to date. This is our recommended path if you're working with general English data.
30
+
31
+ Now that you have created the classifier, let's just train a model. The example below assumes you have the [`datasets`](https://github.com/huggingface/datasets) library installed.
32
+
33
+ ```python
34
+ import numpy as np
35
+ from datasets import load_dataset
36
+
37
+ # Load the subj dataset
38
+ ds = load_dataset("setfit/subj")
39
+ train = ds["train"]
40
+ test = ds["test"]
41
+
42
+ s = perf_counter()
43
+ classifier = classifier.fit(train["text"], train["label"])
44
+
45
+ predicted = classifier.predict(test["text"])
46
+ print(f"Training took {int(perf_counter() - s)} seconds.")
47
+ # Training took 81 seconds
48
+ accuracy = np.mean([x == y for x, y in zip(predicted, test["label"])]) * 100
49
+ print(f"Achieved {accuracy} test accuracy")
50
+ # Achieved 91.0 test accuracy
51
+ ```
52
+
53
+ As you can see, we got a pretty nice 91% accuracy, with only 81 seconds of training.
54
+
55
+ The training loop is handled by [`lightning`](https://pypi.org/project/lightning/). By default the training loop splits the data into a train and validation split, with 90% of the data being used for training and 10% for validation. By default, it runs with early stopping on the validation set accuracy, with a patience of 5.
56
+
57
+ Note that this model is as fast as you're used to from us:
58
+
59
+ ```python
60
+ from time import perf_counter
61
+
62
+ s = perf_counter()
63
+ classifier.predict(test["text"])
64
+ print(f"Took {int((perf_counter() - s) * 1000)} milliseconds for {len(test)} instances on CPU.")
65
+ # Took 67 milliseconds for 2000 instances on CPU.
66
+ ```
67
+
68
+ # Persistence
69
+
70
+ You can turn a classifier into a scikit-learn compatible pipeline, as follows:
71
+
72
+ ```python
73
+ pipeline = classifier.to_pipeline()
74
+ ```
75
+
76
+ This pipeline object can be persisted using standard pickle-based methods, such as [joblib](https://joblib.readthedocs.io/en/stable/). This makes it easy to use your model in inferene pipelines (no installing torch!), although `joblib` and `pickle` should not be used to share models outside of your organization.
77
+
78
+ If you want to persist your pipeline to the Hugging Face hub, you can use our built-in functions:
79
+
80
+ ```python
81
+ pipeline.save_pretrained(path)
82
+ pipeline.push_to_hub("my_cool/project")
83
+ ```
84
+
85
+ Later, you can load these as follows:
86
+
87
+ ```python
88
+ from model2vec.inference import StaticModelPipeline
89
+
90
+ pipeline = StaticModelPipeline.from_pretrained("my_cool/project")
91
+ ```
92
+
93
+ Loading pipelines in this way is _extremely_ fast. It takes only 30ms to load a pipeline from disk.
94
+
95
+
96
+ # Bring your own architecture
97
+
98
+ Our training architecture is set up to be extensible, with each task having a specific class. Right now, we only offer `StaticModelForClassification`, but in the future we'll also offer regression, etc.
99
+
100
+ The core functionality of the `StaticModelForClassification` is contained in a couple of functions:
101
+
102
+ * `construct_head`: This function constructs the classifier on top of the staticmodel. For example, if you want to create a model that has LayerNorm, just subclass, and replace this function. This should be the main function to update if you want to change model behavior.
103
+ * `train_test_split`: governs the train test split before classification.
104
+ * `prepare_dataset`: Selects the `torch.Dataset` that will be used in the `Dataloader` during training.
105
+ * `_encode`: The encoding function used in the model.
106
+ * `fit`: contains all the lightning-related fitting logic.
107
+
108
+ The training of the model is done in a `lighting.LightningModule`, which can be modified but is very basic.
@@ -0,0 +1,10 @@
1
+ from model2vec.utils import get_package_extras, importable
2
+
3
+ _REQUIRED_EXTRA = "train"
4
+
5
+ for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA):
6
+ importable(extra_dependency, _REQUIRED_EXTRA)
7
+
8
+ from model2vec.train.classifier import StaticModelForClassification
9
+
10
+ __all__ = ["StaticModelForClassification"]