-
Notifications
You must be signed in to change notification settings - Fork 92
Add fittable #140
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add fittable #140
Changes from all commits
Commits
Show all changes
64 commits
Select commit
Hold shift + click to select a range
4078a3b
Fix tokenizer issue
stephantul 09f888d
fix issue with warning
stephantul 2167a4e
regenerate lock file
stephantul c95dca5
fix lock file
stephantul b5d8bb7
Try to not select 2.5.1
stephantul 3e68669
fix: issue with dividers in utils
stephantul 1ae4d61
Try to not select 2.5.0
stephantul 1349b0c
fix: do not up version
stephantul 4b83d59
Attempt special fix
stephantul 9515b83
merge
stephantul dfd865b
feat: add training
stephantul c4ba272
merge with old
stephantul 4713bfa
fix: no grad
stephantul e8058bb
use numpy
stephantul a59127e
Add train_test_split
stephantul 310fbb5
fix: issue with fit not resetting
stephantul b1899d1
feat: add lightning
stephantul e27f9dc
merge
stephantul 8df3aaf
Fix bugs
stephantul 839d88a
fix: reviewer comments
stephantul 8457357
fix train issue
stephantul a750709
fix issue with trainer
stephantul e83c54e
fix: truncate during training
stephantul 803565d
feat: tokenize maximum length truncation
stephantul 9052806
fixes
stephantul 2f9fbf4
typo
stephantul f1e08c3
Add progressbar
stephantul bb54a76
small code changes, add docs
stephantul 69ee4ee
fix training comments
stephantul 9962be7
Merge branch 'main' into add-fittable
stephantul ffec235
Add pipeline saving
stephantul 0af84fc
fix bug
stephantul c829745
fix issue with normalize test
stephantul 9ce65a1
change default batch size
stephantul e1169fb
feat: add sklearn skops pipeline
stephantul f096824
Device handling and automatic batch size
stephantul ff3ebdf
Add docstrings, defaults
stephantul b4e966a
docs
stephantul 8f65bfd
fix: rename
stephantul 8cdb668
fix: rename
stephantul e96a72a
fix installation
stephantul 3e76083
rename
stephantul 9f1cb5a
Add training tutorial
stephantul e2d92b9
Add tutorial link
stephantul 657cef0
Merge branch 'main' into add-fittable
stephantul 773009f
test: add tests
stephantul 7015341
fix tests
stephantul 8ab8456
tests: fix tests
stephantul e21e61f
Address comments
stephantul ff75af9
Add inference reqs to train reqs
stephantul 87de7c4
fix normalize
stephantul 1fb33f1
update lock file
stephantul 59f0076
Merge branch 'main' into add-fittable
stephantul 009342b
Merge branch 'main' into add-fittable
stephantul 261a9b4
fix: move modelcards
stephantul e1d53ac
fix: batch size
stephantul 6b5f991
update lock file
stephantul 759b96c
Update model2vec/inference/README.md
stephantul 7caf9bc
Update model2vec/inference/README.md
stephantul c7b68b6
Update model2vec/inference/README.md
stephantul be7baa1
Update model2vec/train/classifier.py
stephantul cc74618
fix: encode args
stephantul a4d8d6c
fix: trust_remote_code
stephantul a0d56d5
fix notebook
stephantul File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Inference | ||
|
||
This subpackage mainly contains helper functions for inference with trained models that have been exported to `scikit-learn` compatible pipelines. | ||
|
||
If you're looking for information on how to train a model, see [here](../train/README.md). | ||
|
||
# Usage | ||
|
||
Let's assume you're using our [potion-edu classifier](https://huggingface.co/minishlab/potion-8m-edu-classifier). | ||
|
||
```python | ||
from model2vec.inference import StaticModelPipeline | ||
|
||
classifier = StaticModelPipeline.from_pretrained("minishlab/potion-8m-edu-classifier") | ||
label = classifier.predict("Attitudes towards cattle in the Alps: a study in letting go.") | ||
``` | ||
|
||
This should just work. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
from model2vec.utils import get_package_extras, importable | ||
|
||
_REQUIRED_EXTRA = "inference" | ||
|
||
for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA): | ||
importable(extra_dependency, _REQUIRED_EXTRA) | ||
|
||
from model2vec.inference.model import StaticModelPipeline | ||
|
||
__all__ = ["StaticModelPipeline"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
from __future__ import annotations | ||
|
||
import re | ||
from pathlib import Path | ||
from tempfile import TemporaryDirectory | ||
|
||
import huggingface_hub | ||
import numpy as np | ||
import skops.io | ||
from sklearn.pipeline import Pipeline | ||
|
||
from model2vec.hf_utils import _create_model_card | ||
from model2vec.model import PathLike, StaticModel | ||
|
||
_DEFAULT_TRUST_PATTERN = re.compile(r"sklearn\..+") | ||
_DEFAULT_MODEL_FILENAME = "pipeline.skops" | ||
|
||
|
||
class StaticModelPipeline: | ||
def __init__(self, model: StaticModel, head: Pipeline) -> None: | ||
"""Create a pipeline with a StaticModel encoder.""" | ||
self.model = model | ||
self.head = head | ||
|
||
@classmethod | ||
def from_pretrained( | ||
cls: type[StaticModelPipeline], path: PathLike, token: str | None = None, trust_remote_code: bool = False | ||
) -> StaticModelPipeline: | ||
""" | ||
Load a StaticModel from a local path or huggingface hub path. | ||
|
||
NOTE: if you load a private model from the huggingface hub, you need to pass a token. | ||
|
||
:param path: The path to the folder containing the pipeline, or a repository on the Hugging Face Hub | ||
:param token: The token to use to download the pipeline from the hub. | ||
:param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `sklearn`. | ||
:return: The loaded pipeline. | ||
""" | ||
model, head = _load_pipeline(path, token, trust_remote_code) | ||
model.embedding = np.nan_to_num(model.embedding) | ||
|
||
return cls(model, head) | ||
|
||
def save_pretrained(self, path: str) -> None: | ||
"""Save the model to a folder.""" | ||
save_pipeline(self, path) | ||
|
||
def push_to_hub(self, repo_id: str, token: str | None = None, private: bool = False) -> None: | ||
stephantul marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Save a model to a folder, and then push that folder to the hf hub. | ||
|
||
:param repo_id: The id of the repository to push to. | ||
:param token: The token to use to push to the hub. | ||
:param private: Whether the repository should be private. | ||
""" | ||
from model2vec.hf_utils import push_folder_to_hub | ||
|
||
with TemporaryDirectory() as temp_dir: | ||
save_pipeline(self, temp_dir) | ||
self.model.save_pretrained(temp_dir) | ||
push_folder_to_hub(Path(temp_dir), repo_id, private, token) | ||
|
||
def _predict_and_coerce_to_2d( | ||
self, | ||
X: list[str] | str, | ||
show_progress_bar: bool, | ||
max_length: int | None, | ||
batch_size: int, | ||
use_multiprocessing: bool, | ||
multiprocessing_threshold: int, | ||
) -> np.ndarray: | ||
"""Predict the labels of the input 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, | ||
) | ||
if np.ndim(encoded) == 1: | ||
encoded = encoded[None, :] | ||
|
||
return encoded | ||
|
||
def predict( | ||
self, | ||
X: list[str] | str, | ||
show_progress_bar: bool = False, | ||
max_length: int | None = 512, | ||
batch_size: int = 1024, | ||
use_multiprocessing: bool = True, | ||
multiprocessing_threshold: int = 10_000, | ||
) -> np.ndarray: | ||
"""Predict the labels of the input.""" | ||
encoded = self._predict_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, | ||
) | ||
|
||
return self.head.predict(encoded) | ||
|
||
def predict_proba( | ||
self, | ||
X: list[str] | str, | ||
show_progress_bar: bool = False, | ||
max_length: int | None = 512, | ||
batch_size: int = 1024, | ||
use_multiprocessing: bool = True, | ||
multiprocessing_threshold: int = 10_000, | ||
) -> np.ndarray: | ||
"""Predict the probabilities of the labels of the input.""" | ||
encoded = self._predict_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, | ||
) | ||
|
||
return self.head.predict_proba(encoded) | ||
|
||
|
||
def _load_pipeline( | ||
folder_or_repo_path: PathLike, token: str | None = None, trust_remote_code: bool = False | ||
) -> tuple[StaticModel, Pipeline]: | ||
""" | ||
Load a model and an sklearn pipeline. | ||
|
||
This assumes the following files are present in the repo: | ||
- `pipeline.skops`: The head of the pipeline. | ||
- `config.json`: The configuration of the model. | ||
- `model.safetensors`: The weights of the model. | ||
- `tokenizer.json`: The tokenizer of the model. | ||
|
||
:param folder_or_repo_path: The path to the folder containing the pipeline. | ||
:param token: The token to use to download the pipeline from the hub. If this is None, you will only | ||
be able to load the pipeline from a local folder, public repository, or a repository that you have access to | ||
because you are logged in. | ||
:param trust_remote_code: Whether to trust the remote code. If this is False, | ||
we will only load components coming from `sklearn`. If this is True, we will load all components. | ||
If you set this to True, you are responsible for whatever happens. | ||
:return: The encoder model and the loaded head | ||
:raises FileNotFoundError: If the pipeline file does not exist in the folder. | ||
:raises ValueError: If an untrusted type is found in the pipeline, and `trust_remote_code` is False. | ||
""" | ||
folder_or_repo_path = Path(folder_or_repo_path) | ||
model_filename = _DEFAULT_MODEL_FILENAME | ||
if folder_or_repo_path.exists(): | ||
head_pipeline_path = folder_or_repo_path / model_filename | ||
if not head_pipeline_path.exists(): | ||
raise FileNotFoundError(f"Pipeline file does not exist in {folder_or_repo_path}") | ||
else: | ||
head_pipeline_path = huggingface_hub.hf_hub_download( | ||
folder_or_repo_path.as_posix(), model_filename, token=token | ||
) | ||
|
||
model = StaticModel.from_pretrained(folder_or_repo_path) | ||
|
||
unknown_types = skops.io.get_untrusted_types(file=head_pipeline_path) | ||
# If the user does not trust remote code, we should check that the unknown types are trusted. | ||
# By default, we trust everything coming from scikit-learn. | ||
if not trust_remote_code: | ||
for t in unknown_types: | ||
if not _DEFAULT_TRUST_PATTERN.match(t): | ||
raise ValueError(f"Untrusted type {t}.") | ||
head = skops.io.load(head_pipeline_path, trusted=unknown_types) | ||
|
||
return model, head | ||
|
||
|
||
def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> None: | ||
""" | ||
Save a pipeline to a folder. | ||
|
||
:param pipeline: The pipeline to save. | ||
:param folder_path: The path to the folder to save the pipeline to. | ||
""" | ||
folder_path = Path(folder_path) | ||
folder_path.mkdir(parents=True, exist_ok=True) | ||
model_filename = _DEFAULT_MODEL_FILENAME | ||
head_pipeline_path = folder_path / model_filename | ||
skops.io.dump(pipeline.head, head_pipeline_path) | ||
pipeline.model.save_pretrained(folder_path) | ||
base_model_name = pipeline.model.base_model_name | ||
if isinstance(base_model_name, list) and base_model_name: | ||
name = base_model_name[0] | ||
elif isinstance(base_model_name, str): | ||
name = base_model_name | ||
else: | ||
name = "unknown" | ||
_create_model_card( | ||
folder_path, | ||
base_model_name=name, | ||
language=pipeline.model.language, | ||
template_path="modelcards/classifier_template.md", | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
--- | ||
{{ card_data }} | ||
--- | ||
|
||
# {{ model_name }} Model Card | ||
|
||
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. | ||
|
||
## Installation | ||
|
||
Install model2vec using pip: | ||
``` | ||
pip install model2vec[inference] | ||
``` | ||
|
||
## Usage | ||
Load this model using the `from_pretrained` method: | ||
```python | ||
from model2vec.inference import StaticModelPipeline | ||
|
||
# Load a pretrained Model2Vec model | ||
model = StaticModelPipeline.from_pretrained("{{ model_name }}") | ||
|
||
# Predict labels | ||
predicted = model.predict(["Example sentence"]) | ||
``` | ||
|
||
## Additional Resources | ||
|
||
- [All Model2Vec models on the hub](https://huggingface.co/models?library=model2vec) | ||
- [Model2Vec Repo](https://github.com/MinishLab/model2vec) | ||
- [Model2Vec Results](https://github.com/MinishLab/model2vec?tab=readme-ov-file#results) | ||
- [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials) | ||
|
||
## Library Authors | ||
|
||
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). | ||
|
||
## Citation | ||
|
||
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work. | ||
``` | ||
@software{minishlab2024model2vec, | ||
authors = {Stephan Tulkens, Thomas van Dongen}, | ||
title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model}, | ||
year = {2024}, | ||
url = {https://github.com/MinishLab/model2vec}, | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.