Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@



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.
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 30000 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.


## Quickstart
Expand Down Expand Up @@ -107,7 +107,7 @@ For advanced usage, see our [training docs](https://minish.ai/packages/model2vec
- **State-of-the-Art Performance**: Model2Vec models outperform any other static embeddings (such as GLoVe and BPEmb) by a large margin, as can be seen in our [results](results/README.md).
- **Small**: Model2Vec reduces the size of a Sentence Transformer model by a factor of up to 50. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is just ~30 MB on disk, and our smallest model just ~8 MB (making it the smallest model on [MTEB](https://huggingface.co/spaces/mteb/leaderboard)!).
- **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
- **Lightning-fast Inference**: up to 500 times faster on CPU than the original model.
- **Lightning-fast Inference**: up to 30000 times faster on CPU than the original model.
- **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset.
- **Fine-tuning**: fine-tune Model2Vec models for classification, similarity, regression, or pair similarity, and run them without `torch`.
- **Integrated in many popular libraries**: Model2Vec is integrated direclty into popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) and [LangChain](https://github.com/langchain-ai/langchain). For more information, see our [integrations documentation](https://minish.ai/packages/model2vec/integrations).
Expand Down
2 changes: 1 addition & 1 deletion model2vec/inference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ The report has the same format as the dictionary returned by scikit-learn's `cla

`predict_proba` and `evaluate` raise an error for pipelines that predict vectors.

`predict` and `predict_proba` take the same encoding options as `StaticModel.encode`: `batch_size`, `max_length`, `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold`. If `max_length` is not passed, the model's own `max_length` is used. Pass `max_length=None` to disable truncation.
`predict` and `predict_proba` take `max_length`, like `StaticModel.encode`. If `max_length` is not passed, the model's own `max_length` is used. Pass `max_length=None` to disable truncation.

The underlying `StaticModel` is available as `pipeline.model`, and the head as `pipeline.head`.

Expand Down
73 changes: 18 additions & 55 deletions model2vec/inference/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from collections.abc import Sequence
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TypeVar, cast
from typing import Any, TypeVar, cast

import huggingface_hub
import numpy as np
Expand Down Expand Up @@ -71,59 +71,33 @@ def push_to_hub(
_save_pipeline(self, temp_dir)
push_folder_to_hub(Path(temp_dir), subfolder, repo_id, private, token)

def _encode_and_coerce_to_2d(
self,
X: Sequence[str],
show_progress_bar: bool,
max_length: int | None | _UnsetType,
batch_size: int,
use_multiprocessing: bool,
multiprocessing_threshold: int,
) -> np.ndarray:
def _encode_and_coerce_to_2d(self, X: str | Sequence[str], max_length: int | None | _UnsetType) -> np.ndarray:
"""Encode the instances and coerce the output to a matrix."""
encoded = self.model.encode(
X,
show_progress_bar=show_progress_bar,
max_length=max_length,
batch_size=batch_size,
use_multiprocessing=use_multiprocessing,
multiprocessing_threshold=multiprocessing_threshold,
)
encoded = self.model.encode(X, max_length=max_length)
if np.ndim(encoded) == 1:
encoded = encoded[None, :]

return encoded

def predict(
self,
X: Sequence[str],
show_progress_bar: bool = False,
X: str | Sequence[str],
*,
max_length: int | None | _UnsetType = _UNSET,
batch_size: int = 1024,
use_multiprocessing: bool = True,
multiprocessing_threshold: int = 10_000,
threshold: float = 0.5,
**kwargs: Any,
) -> np.ndarray:
"""Predict the labels of the input.

:param X: The input data to predict. Can be a list of strings or a single string.
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
:param max_length: The maximum length of the input sequences. If not passed, the encoder model's
`max_length` is used. Pass `max_length=None` to disable truncation.
:param batch_size: The batch size for prediction. Defaults to 1024.
:param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
:param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
:param threshold: The threshold for multilabel classification. Defaults to 0.5. Ignored if not multilabel.
:param **kwargs: Any additional arguments, such as the removed `show_progress_bar`, `batch_size` and
`use_multiprocessing`. These are ignored.
:return: The predicted labels or probabilities.
"""
encoded = self._encode_and_coerce_to_2d(
X,
show_progress_bar=show_progress_bar,
max_length=max_length,
batch_size=batch_size,
use_multiprocessing=use_multiprocessing,
multiprocessing_threshold=multiprocessing_threshold,
)
encoded = self._encode_and_coerce_to_2d(X, max_length=max_length)

if self.head.activation == Activation.IDENTITY:
return self.head.predict_regression(encoded)
Expand All @@ -139,53 +113,42 @@ def predict(

def predict_proba(
self,
X: Sequence[str],
show_progress_bar: bool = False,
X: str | Sequence[str],
*,
max_length: int | None | _UnsetType = _UNSET,
batch_size: int = 1024,
use_multiprocessing: bool = True,
multiprocessing_threshold: int = 10_000,
**kwargs: Any,
) -> np.ndarray:
"""Predict the labels of the input.

:param X: The input data to predict. Can be a list of strings or a single string.
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
:param max_length: The maximum length of the input sequences. If not passed, the encoder model's
`max_length` is used. Pass `max_length=None` to disable truncation.
:param batch_size: The batch size for prediction. Defaults to 1024.
:param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
:param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
:param **kwargs: Any additional arguments, such as the removed `show_progress_bar`, `batch_size` and
`use_multiprocessing`. These are ignored.
:return: The predicted labels or probabilities.
:raises ValueError: If the classifier type is projector.
"""
if self.head.activation == Activation.IDENTITY:
raise ValueError("You are using predict_proba on a projector model. This is not supported.")
encoded = self._encode_and_coerce_to_2d(
X,
show_progress_bar=show_progress_bar,
max_length=max_length,
batch_size=batch_size,
use_multiprocessing=use_multiprocessing,
multiprocessing_threshold=multiprocessing_threshold,
)
encoded = self._encode_and_coerce_to_2d(X, max_length=max_length)

return self.head.predict_proba(encoded)

def evaluate(
self, X: Sequence[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5
self, X: Sequence[str], y: LabelType, *, threshold: float = 0.5, **kwargs: Any
) -> dict[str, dict[str, float]]:
"""Evaluate the classifier on a given dataset using a classification report.

:param X: The texts to predict on.
:param y: The ground truth labels.
:param batch_size: The batch size.
:param threshold: The threshold for multilabel classification.
:param **kwargs: Any additional arguments, such as the removed `batch_size`. These are ignored.
:return: A classification report, as a dictionary.
:raises ValueError: If the classifier type is projector.
"""
if self.head.activation == Activation.IDENTITY:
raise ValueError("You are using evaluate on a projector model. This is not supported.")
predictions = self.predict(X, show_progress_bar=True, batch_size=batch_size, threshold=threshold)
predictions = self.predict(X, threshold=threshold)
return evaluate_single_or_multi_label(predictions=predictions, y=y)


Expand Down
Loading
Loading