Skip to content

Commit 986af59

Browse files
authored
chore: fix pre-commit (#326)
1 parent 810d25e commit 986af59

20 files changed

Lines changed: 89 additions & 156 deletions

.pre-commit-config.yaml

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,37 @@
1-
# See https://pre-commit.com for more information
2-
# See https://pre-commit.com/hooks.html for more hooks
1+
minimum_pre_commit_version: "3.2.0"
2+
3+
default_language_version:
4+
python: python3
5+
36
repos:
47
- repo: https://github.com/pre-commit/pre-commit-hooks
5-
rev: v4.4.0
8+
rev: v6.0.0
69
hooks:
10+
- id: no-commit-to-branch
11+
args: [--branch, main]
712
- id: check-ast
8-
description: Simply check whether files parse as valid python.
13+
- id: check-yaml
14+
- id: check-toml
15+
- id: check-json
16+
- id: check-merge-conflict
17+
- id: debug-statements
918
- id: trailing-whitespace
10-
description: Trims trailing whitespace
1119
- id: end-of-file-fixer
12-
description: Makes sure files end in a newline and only a newline.
1320
- id: check-added-large-files
14-
args: ['--maxkb=5000']
15-
description: Prevent giant files from being committed.
21+
args: ["--maxkb=5000"]
1622
- id: check-case-conflict
17-
description: Check for files with names that would conflict on case-insensitive filesystems like MacOS/Windows.
18-
- id: check-yaml
19-
description: Check yaml files for syntax errors.
2023
- repo: https://github.com/jsh9/pydoclint
21-
rev: 0.5.3
24+
rev: 0.8.3
2225
hooks:
2326
- id: pydoclint
2427
- repo: https://github.com/astral-sh/ruff-pre-commit
25-
rev: v0.13.0
28+
rev: v0.15.12
2629
hooks:
27-
- id: ruff
28-
args: [ --fix ]
30+
- id: ruff-check
31+
args: [--fix]
2932
- id: ruff-format
30-
- repo: local
33+
- repo: https://github.com/pre-commit/mirrors-mypy
34+
rev: v1.15.0
3135
hooks:
3236
- id: mypy
33-
name: mypy
34-
entry: mypy
35-
language: python
36-
types: [python]
37+
additional_dependencies: []

Makefile

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
clean:
2-
1+
VERBOSITY=
32

43
venv:
54
uv venv
@@ -9,7 +8,7 @@ install:
98
uv run pre-commit install
109

1110
install-no-pre-commit:
12-
uv pip install ".[dev,distill,inference,train]"
11+
uv pip install ".[dev,distill,inference,train,onnx,quantization]"
1312

1413
install-base:
1514
uv sync --extra dev
@@ -18,4 +17,7 @@ fix:
1817
uv run pre-commit run --all-files
1918

2019
test:
21-
uv run pytest --cov=model2vec --cov-report=term-missing
20+
uv run pytest --cov=model2vec --cov-report=term-missing $(VERBOSITY)
21+
22+
test-verbose:
23+
make test VERBOSITY="-vvv"

model2vec/distill/distillation.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ def distill_from_model(
3333
vocabulary_quantization: int | None = None,
3434
pooling: PoolingMode | str = PoolingMode.MEAN,
3535
) -> StaticModel:
36-
"""
37-
Distill a staticmodel from a sentence transformer.
36+
"""Distill a staticmodel from a sentence transformer.
3837
3938
This function creates a set of embeddings from a sentence transformer. It does this by doing either
4039
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
@@ -65,7 +64,7 @@ def distill_from_model(
6564
'first': use the first token's hidden state ([CLS] token in BERT-style models).
6665
'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.
6766
:return: A StaticModel.
68-
:raises: ValueError if the vocabulary is empty after preprocessing.
67+
:raises ValueError: if the vocabulary is empty after preprocessing.
6968
7069
"""
7170
quantize_to = DType(quantize_to)
@@ -168,15 +167,14 @@ def _validate_parameters(
168167
sif_coefficient: float | None,
169168
token_remove_pattern: str | None,
170169
) -> tuple[float | None, re.Pattern[str] | None]:
171-
"""
172-
Validate the parameters passed to the distillation function.
170+
"""Validate the parameters passed to the distillation function.
173171
174172
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
175173
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
176174
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
177175
this regex pattern will be removed from the vocabulary.
178176
:return: The SIF coefficient to use.
179-
:raises: ValueError if the regex can't be compiled.
177+
:raises ValueError: if the regex can't be compiled.
180178
181179
"""
182180
if sif_coefficient is not None:
@@ -205,8 +203,7 @@ def distill(
205203
vocabulary_quantization: int | None = None,
206204
pooling: PoolingMode | str = PoolingMode.MEAN,
207205
) -> StaticModel:
208-
"""
209-
Distill a staticmodel from a sentence transformer.
206+
"""Distill a staticmodel from a sentence transformer.
210207
211208
This function creates a set of embeddings from a sentence transformer. It does this by doing either
212209
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed

model2vec/distill/inference.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323

2424

2525
class PoolingMode(str, Enum):
26-
"""
27-
Pooling modes for embedding creation.
26+
"""Pooling modes for embedding creation.
2827
2928
- MEAN: masked mean over all tokens.
3029
- LAST: last non-padding token (often EOS, common in decoder-style models).
@@ -48,8 +47,7 @@ def create_embeddings(
4847
pad_token_id: int,
4948
pooling: PoolingMode | str = PoolingMode.MEAN,
5049
) -> np.ndarray:
51-
"""
52-
Create output embeddings for a bunch of tokens using a pretrained model.
50+
"""Create output embeddings for a bunch of tokens using a pretrained model.
5351
5452
It does a forward pass for all tokens passed in `tokens`.
5553
@@ -121,8 +119,7 @@ def create_embeddings(
121119
def _encode_with_model(
122120
model: PreTrainedModel, encodings: dict[str, torch.Tensor]
123121
) -> tuple[torch.Tensor, torch.Tensor | None, dict[str, torch.Tensor]]:
124-
"""
125-
Move inputs to the model device, run a forward pass, and standardize dtypes.
122+
"""Move inputs to the model device, run a forward pass, and standardize dtypes.
126123
127124
:param model: The model to use.
128125
:param encodings: The encoded tokens to turn into features.
@@ -146,8 +143,7 @@ def _encode_with_model(
146143

147144
@torch.inference_mode()
148145
def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
149-
"""
150-
Encode a batch of tokens using mean pooling.
146+
"""Encode a batch of tokens using mean pooling.
151147
152148
:param model: The model to use.
153149
:param encodings: The encoded tokens to turn into features.
@@ -163,8 +159,7 @@ def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
163159

164160
@torch.inference_mode()
165161
def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
166-
"""
167-
Encode a batch of tokens using last token pooling.
162+
"""Encode a batch of tokens using last token pooling.
168163
169164
:param model: The model to use.
170165
:param encodings: The encoded tokens to turn into features.
@@ -179,8 +174,7 @@ def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
179174

180175
@torch.inference_mode()
181176
def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
182-
"""
183-
Encode a batch of tokens using first token (CLS) pooling.
177+
"""Encode a batch of tokens using first token (CLS) pooling.
184178
185179
:param model: The model to use.
186180
:param encodings: The encoded tokens to turn into features.
@@ -192,8 +186,7 @@ def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.
192186

193187
@torch.inference_mode()
194188
def _encode_pooler_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
195-
"""
196-
Encode a batch of tokens using pooler output.
189+
"""Encode a batch of tokens using pooler output.
197190
198191
:param model: The model to use.
199192
:param encodings: The encoded tokens to turn into features.

model2vec/distill/utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99

1010

1111
def select_optimal_device(device: str | None) -> str:
12-
"""
13-
Get the optimal device to use based on backend availability.
12+
"""Get the optimal device to use based on backend availability.
1413
1514
For Torch versions >= 2.8.0, MPS is disabled due to known performance regressions.
1615

model2vec/inference/model.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ def __init__(self, model: StaticModel, head: Pipeline) -> None:
5252
def from_pretrained(
5353
cls: type[StaticModelPipeline], path: PathLike, token: str | None = None, trust_remote_code: bool = False
5454
) -> StaticModelPipeline:
55-
"""
56-
Load a StaticModel from a local path or huggingface hub path.
55+
"""Load a StaticModel from a local path or huggingface hub path.
5756
5857
NOTE: if you load a private model from the huggingface hub, you need to pass a token.
5958
@@ -74,8 +73,7 @@ def save_pretrained(self, path: str) -> None:
7473
def push_to_hub(
7574
self, repo_id: str, subfolder: str | None = None, token: str | None = None, private: bool = False
7675
) -> None:
77-
"""
78-
Save a model to a folder, and then push that folder to the hf hub.
76+
"""Save a model to a folder, and then push that folder to the hf hub.
7977
8078
:param repo_id: The id of the repository to push to.
8179
:param subfolder: The subfolder to push to.
@@ -122,8 +120,7 @@ def predict(
122120
multiprocessing_threshold: int = 10_000,
123121
threshold: float = 0.5,
124122
) -> np.ndarray:
125-
"""
126-
Predict the labels of the input.
123+
"""Predict the labels of the input.
127124
128125
:param X: The input data to predict. Can be a list of strings or a single string.
129126
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
@@ -162,8 +159,7 @@ def predict_proba(
162159
use_multiprocessing: bool = True,
163160
multiprocessing_threshold: int = 10_000,
164161
) -> np.ndarray:
165-
"""
166-
Predict the labels of the input.
162+
"""Predict the labels of the input.
167163
168164
:param X: The input data to predict. Can be a list of strings or a single string.
169165
:param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
@@ -190,8 +186,7 @@ def predict_proba(
190186
def evaluate(
191187
self, X: Sequence[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5, output_dict: bool = False
192188
) -> str | dict[str, dict[str, float]]:
193-
"""
194-
Evaluate the classifier on a given dataset using scikit-learn's classification report.
189+
"""Evaluate the classifier on a given dataset using scikit-learn's classification report.
195190
196191
:param X: The texts to predict on.
197192
:param y: The ground truth labels.
@@ -212,8 +207,7 @@ def evaluate(
212207
def _load_pipeline(
213208
folder_or_repo_path: PathLike, token: str | None = None, trust_remote_code: bool = False
214209
) -> tuple[StaticModel, Pipeline]:
215-
"""
216-
Load a model and an sklearn pipeline.
210+
"""Load a model and an sklearn pipeline.
217211
218212
This assumes the following files are present in the repo:
219213
- `pipeline.skops`: The head of the pipeline.
@@ -259,8 +253,7 @@ def _load_pipeline(
259253

260254

261255
def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> None:
262-
"""
263-
Save a pipeline to a folder.
256+
"""Save a pipeline to a folder.
264257
265258
:param pipeline: The pipeline to save.
266259
:param folder_path: The path to the folder to save the pipeline to.
@@ -296,8 +289,7 @@ def evaluate_single_or_multi_label(
296289
y: list[int] | list[str] | list[list[int]] | list[list[str]],
297290
output_dict: bool = False,
298291
) -> str | dict[str, dict[str, float]]:
299-
"""
300-
Evaluate the classifier on a given dataset using scikit-learn's classification report.
292+
"""Evaluate the classifier on a given dataset using scikit-learn's classification report.
301293
302294
:param predictions: The predictions.
303295
:param y: The ground truth labels.

0 commit comments

Comments
 (0)