Skip to content

Commit dfb8247

Browse files
authored
chore: typing on loading should return a T, not a StaticModel (#357)
* fix: loading * everything to 'T' for naming consistency
1 parent 26373f1 commit dfb8247

3 files changed

Lines changed: 21 additions & 18 deletions

File tree

‎model2vec/model.py‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
import json
44
import math
55
import os
6-
from collections.abc import Iterator, Mapping, Sequence
6+
from collections.abc import Iterator, Sequence
77
from logging import getLogger
88
from pathlib import Path
99
from tempfile import TemporaryDirectory
10-
from typing import Any, cast, overload
10+
from typing import Any, Mapping, TypeVar, cast, overload
1111

1212
import numpy as np
1313
from joblib import delayed
@@ -191,7 +191,7 @@ def tokenize(self, sentences: Sequence[str], max_length: int | None = None) -> l
191191

192192
@classmethod
193193
def from_pretrained(
194-
cls: type[StaticModel],
194+
cls: type[T],
195195
path: PathLike,
196196
token: str | None = None,
197197
normalize: bool | None = None,
@@ -201,7 +201,7 @@ def from_pretrained(
201201
vocabulary_quantization: int | None = None,
202202
max_length: int | None | _UnsetType = _UNSET,
203203
force_download: bool = True,
204-
) -> StaticModel:
204+
) -> T:
205205
"""Load a StaticModel from a local path or huggingface hub path.
206206
207207
NOTE: if you load a private model from the huggingface hub, you need to pass a token.
@@ -226,6 +226,7 @@ def from_pretrained(
226226
"""
227227
return _loading_helper(
228228
cls=cls,
229+
max_length=max_length,
229230
path=path,
230231
token=token,
231232
vocabulary_quantization=vocabulary_quantization,
@@ -234,7 +235,6 @@ def from_pretrained(
234235
normalize=normalize,
235236
subfolder=subfolder,
236237
force_download=force_download,
237-
max_length=max_length,
238238
)
239239

240240
@overload
@@ -468,11 +468,11 @@ def push_to_hub(
468468

469469

470470
def quantize_model(
471-
model: StaticModel,
471+
model: T,
472472
vocabulary_quantization: int | None = None,
473473
quantize_to: str | DType | None = None,
474474
dimensionality: int | None = None,
475-
) -> StaticModel:
475+
) -> T:
476476
"""Quantize the model to a lower precision and possibly lower dimensionality.
477477
478478
:param model: The model to quantize.
@@ -505,7 +505,7 @@ def quantize_model(
505505
dimensionality=dimensionality,
506506
)
507507

508-
return StaticModel(
508+
return type(model)(
509509
vectors=embeddings,
510510
tokenizer=model.tokenizer,
511511
config=model.config,
@@ -519,7 +519,7 @@ def quantize_model(
519519

520520

521521
def _loading_helper(
522-
cls: type[StaticModel],
522+
cls: type[T],
523523
path: PathLike,
524524
token: str | None,
525525
vocabulary_quantization: int | None,
@@ -529,7 +529,7 @@ def _loading_helper(
529529
subfolder: str | None,
530530
force_download: bool,
531531
max_length: int | None | _UnsetType,
532-
) -> StaticModel:
532+
) -> T:
533533
"""Helper function to load a model from a directory."""
534534
from model2vec.persistence import load_pretrained
535535

@@ -581,3 +581,6 @@ def _get_unk_token_id(tokenizer: Tokenizer) -> int | None:
581581
return tokenizer.token_to_id(token)
582582
# Unigram
583583
return json.loads(tokenizer.to_str())["model"].get("unk_id")
584+
585+
586+
T = TypeVar("T", bound=StaticModel)

‎model2vec/train/base.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -139,12 +139,12 @@ def _initialize(self) -> None:
139139

140140
@classmethod
141141
def from_pretrained(
142-
cls: type[ModelType],
142+
cls: type[T],
143143
path: PathLike = "minishlab/potion-base-32m",
144144
*,
145145
token: str | None = None,
146146
**kwargs: Any,
147-
) -> ModelType:
147+
) -> T:
148148
"""Load the model from a pretrained model2vec model."""
149149
if model_name := kwargs.pop("model_name", None):
150150
logger.warning("The 'model_name' argument is deprecated. Use 'path' instead.")
@@ -154,13 +154,13 @@ def from_pretrained(
154154

155155
@classmethod
156156
def from_static_model(
157-
cls: type[ModelType],
157+
cls: type[T],
158158
*,
159159
model: StaticModel,
160160
pad_token: str | None = None,
161161
max_length: int | None = None,
162162
**kwargs: Any,
163-
) -> ModelType:
163+
) -> T:
164164
"""Load the model from a static model.
165165
166166
:param model: The static model to load from.
@@ -430,4 +430,4 @@ def _create_datasets(
430430
return train_dataset, val_dataset
431431

432432

433-
ModelType = TypeVar("ModelType", bound=BaseFinetuneable)
433+
T = TypeVar("T", bound=BaseFinetuneable)

‎model2vec/train/similarity.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def __init__(
6464
)
6565

6666
def fit(
67-
self: _T,
67+
self: T,
6868
X: list[str],
6969
y: torch.Tensor,
7070
learning_rate: float = 1e-3,
@@ -78,7 +78,7 @@ def fit(
7878
y_val: torch.Tensor | None = None,
7979
validation_steps: int | None = None,
8080
random_seed: int = DEFAULT_RANDOM_SEED,
81-
) -> _T:
81+
) -> T:
8282
"""Fit a model.
8383
8484
This function trains the model with a plain torch training loop.
@@ -132,4 +132,4 @@ def fit(
132132
return self
133133

134134

135-
_T = TypeVar("_T", bound=StaticModelForSimilarity)
135+
T = TypeVar("T", bound=StaticModelForSimilarity)

0 commit comments

Comments
 (0)