model2vec 0.11.0__tar.gz → 0.12.0__tar.gz
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.
- {model2vec-0.11.0 → model2vec-0.12.0}/PKG-INFO +4 -2
- model2vec-0.12.0/model2vec/base.py +184 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/inference/model.py +1 -1
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/model.py +45 -158
- model2vec-0.12.0/model2vec/modelcards/sparse_model_card_template.md +72 -0
- model2vec-0.12.0/model2vec/persistence/__init__.py +4 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/persistence/persistence.py +105 -28
- model2vec-0.12.0/model2vec/sentence-transformers/sparse_encoder.py +139 -0
- model2vec-0.12.0/model2vec/sparse.py +483 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/base.py +34 -15
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/types.py +16 -3
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/utils.py +8 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/version.py +1 -1
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/PKG-INFO +4 -2
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/SOURCES.txt +6 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/requires.txt +4 -1
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/scm_file_list.json +6 -0
- model2vec-0.12.0/model2vec.egg-info/scm_version.json +8 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/pyproject.toml +3 -1
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_model.py +62 -12
- model2vec-0.12.0/tests/test_sparse.py +593 -0
- model2vec-0.12.0/tests/test_sparse_encoder.py +203 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_trainable.py +37 -12
- {model2vec-0.11.0 → model2vec-0.12.0}/uv.lock +6 -1
- model2vec-0.11.0/model2vec/persistence/__init__.py +0 -4
- model2vec-0.11.0/model2vec.egg-info/scm_version.json +0 -8
- {model2vec-0.11.0 → model2vec-0.12.0}/.github/workflows/ci.yaml +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/.github/workflows/release.yaml +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/.gitignore +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/.pre-commit-config.yaml +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/CITATION.cff +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/CONTRIBUTING.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/LICENSE +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/Makefile +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/README.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/logo_v2.png +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/model2vec_logo.png +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/speed_vs_mteb_plot.svg +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/docs/README.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/docs/internals.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/distill/distillation.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/distill/inference.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/distill/utils.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/inference/README.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/inference/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/inference/evaluation.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/inference/mlp.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/classifier_template.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/model_card_template.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/modelcards.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/onnx_classifier_template.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/modelcards/onnx_model_card_template.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/onnx.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/persistence/datamodels.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/persistence/hf.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/persistence/utils.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/py.typed +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/quantization.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/tokenizer/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/tokenizer/tokenizer.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/README.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/classifier.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/dataset.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/pairs.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/regression.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/similarity.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/trainer.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/train/utils.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec/vocabulary_quantization.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/results/README.md +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/results/make_speed_vs_mteb_plot.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/setup.cfg +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/conftest.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/__init__.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/Alibaba-NLP___gte-modernbert-base_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/baai___bge-base-en-v1.5_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/google___embeddinggemma-300m_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/intfloat___multilingual-e5-base_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/pretrained/minishlab___potion-base-32m_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/pretrained/minishlab___potion-base-8m_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/pretrained/minishlab___potion-multilingual-128m_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/pretrained/minishlab___potion-retrieval-32m_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/data/sentence-transformers___all-MiniLM-L6-v2_baseline.json +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/distill_metrics.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/pretrained_model_metrics.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/test_distill_regression.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/test_onnx_export.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/test_pretrained_model_regression.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/update_distill_baseline.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/integration/update_pretrained_baseline.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_distillation.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_export_to_onnx.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_inference.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_persistence.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_quantization.py +0 -0
- {model2vec-0.11.0 → model2vec-0.12.0}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.12.0
|
|
4
4
|
Summary: Fast State-of-the-Art Static Embeddings
|
|
5
5
|
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomasvdongen@proton.me>
|
|
6
6
|
License: MIT License
|
|
@@ -48,7 +48,7 @@ Requires-Dist: safetensors
|
|
|
48
48
|
Requires-Dist: tokenizers<1.0.0,>=0.22
|
|
49
49
|
Requires-Dist: tqdm
|
|
50
50
|
Requires-Dist: huggingface-hub>=1.0.0
|
|
51
|
-
Requires-Dist: model2vec-rs<0.
|
|
51
|
+
Requires-Dist: model2vec-rs<0.7.0,>=0.6.0
|
|
52
52
|
Provides-Extra: dev
|
|
53
53
|
Requires-Dist: ipython; extra == "dev"
|
|
54
54
|
Requires-Dist: mypy; extra == "dev"
|
|
@@ -72,6 +72,8 @@ Requires-Dist: torch; extra == "train"
|
|
|
72
72
|
Requires-Dist: datasets>=4.0.0; extra == "train"
|
|
73
73
|
Provides-Extra: quantization
|
|
74
74
|
Requires-Dist: scikit-learn; extra == "quantization"
|
|
75
|
+
Provides-Extra: sparse
|
|
76
|
+
Requires-Dist: scipy; extra == "sparse"
|
|
75
77
|
Provides-Extra: integration
|
|
76
78
|
Requires-Dist: mteb; extra == "integration"
|
|
77
79
|
Provides-Extra: tests
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from logging import getLogger
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from tempfile import TemporaryDirectory
|
|
9
|
+
from typing import Any, ClassVar, Generic, TypeVar, cast
|
|
10
|
+
|
|
11
|
+
import model2vec_rs
|
|
12
|
+
import numpy as np
|
|
13
|
+
from tokenizers import Tokenizer
|
|
14
|
+
|
|
15
|
+
from model2vec.types import BaseStaticModelConfig
|
|
16
|
+
|
|
17
|
+
PathLike = Path | str
|
|
18
|
+
|
|
19
|
+
logger = getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
DEFAULT_MAX_LENGTH = 512
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
ConfigT = TypeVar("ConfigT", bound=BaseStaticModelConfig)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class BaseStaticModel(ABC, Generic[ConfigT]):
|
|
28
|
+
_RUST_CACHES: ClassVar[tuple[str, ...]] = ("_rust_tokenizer",)
|
|
29
|
+
_rust_tokenizer: model2vec_rs.Tokenizer | None
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
tokenizer: Tokenizer,
|
|
34
|
+
config: ConfigT | None = None,
|
|
35
|
+
base_model_name: str | None = None,
|
|
36
|
+
language: list[str] | None = None,
|
|
37
|
+
max_length: int | None = DEFAULT_MAX_LENGTH,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Initialize the tokenizer, config and settings shared by dense and sparse static models.
|
|
40
|
+
|
|
41
|
+
:param tokenizer: The tokenizer to use. Stored as a copy. If you change `model.tokenizer`
|
|
42
|
+
in place, assign it again (`model.tokenizer = model.tokenizer`) for `encode` to use the changes.
|
|
43
|
+
:param config: Any metadata config. Stored as a copy, so mutating it afterwards does not affect
|
|
44
|
+
the model, and vice versa.
|
|
45
|
+
:param base_model_name: The used base model name. Used for creating a model card.
|
|
46
|
+
:param language: The language of the model. Used for creating a model card.
|
|
47
|
+
:param max_length: The default maximum sequence length (in tokens) used by `encode` when its own
|
|
48
|
+
`max_length` argument is not passed. Defaults to 512; pass None to disable truncation. This value
|
|
49
|
+
is authoritative: it is written to `config["max_length"]`, and any conflicting value already in
|
|
50
|
+
`config` is overridden.
|
|
51
|
+
"""
|
|
52
|
+
super().__init__()
|
|
53
|
+
tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1]))
|
|
54
|
+
self.tokens = tokens
|
|
55
|
+
|
|
56
|
+
self.tokenizer = copy.deepcopy(tokenizer)
|
|
57
|
+
self.config: ConfigT = cast(ConfigT, {**config} if config is not None else {})
|
|
58
|
+
self.base_model_name = base_model_name
|
|
59
|
+
self.language = language
|
|
60
|
+
self.max_length = max_length
|
|
61
|
+
|
|
62
|
+
def __getstate__(self) -> dict[str, Any]:
|
|
63
|
+
"""Get the state for pickling, without the Rust objects."""
|
|
64
|
+
state = vars(self).copy()
|
|
65
|
+
for name in self._RUST_CACHES:
|
|
66
|
+
state[name] = None
|
|
67
|
+
return state
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def tokenizer(self) -> Tokenizer:
|
|
71
|
+
"""The tokenizer. Assign it again after changing it in place, so that encoding uses the changes."""
|
|
72
|
+
return self._tokenizer
|
|
73
|
+
|
|
74
|
+
@tokenizer.setter
|
|
75
|
+
def tokenizer(self, value: Tokenizer) -> None:
|
|
76
|
+
self._tokenizer = value
|
|
77
|
+
for name in self._RUST_CACHES:
|
|
78
|
+
setattr(self, name, None)
|
|
79
|
+
|
|
80
|
+
def _tokenizer_to_save(self) -> Tokenizer:
|
|
81
|
+
"""Get a copy of the tokenizer that truncates to `max_length` tokens and does not pad."""
|
|
82
|
+
tokenizer = copy.deepcopy(self.tokenizer)
|
|
83
|
+
_disable_padding(tokenizer)
|
|
84
|
+
if self.max_length is None:
|
|
85
|
+
tokenizer.no_truncation()
|
|
86
|
+
else:
|
|
87
|
+
tokenizer.enable_truncation(self.max_length)
|
|
88
|
+
return tokenizer
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def rust_tokenizer(self) -> model2vec_rs.Tokenizer:
|
|
92
|
+
"""The Rust tokenizer used for encoding, built from `tokenizer` and rebuilt when it is assigned."""
|
|
93
|
+
if self._rust_tokenizer is None:
|
|
94
|
+
self._rust_tokenizer = model2vec_rs.Tokenizer.from_str(self.tokenizer.to_str())
|
|
95
|
+
return self._rust_tokenizer
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def median_token_length(self) -> int:
|
|
99
|
+
"""The median character length of the tokens in the vocabulary."""
|
|
100
|
+
return self.rust_tokenizer.median_token_length
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def unk_token_id(self) -> int | None:
|
|
104
|
+
"""The id of the unk token, which is left out of tokenized sentences, or None if there is none."""
|
|
105
|
+
return self.rust_tokenizer.unk_token_id
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def max_length(self) -> int | None:
|
|
109
|
+
"""Get the max_length value.
|
|
110
|
+
|
|
111
|
+
:return: The max_length value.
|
|
112
|
+
"""
|
|
113
|
+
return self._max_length
|
|
114
|
+
|
|
115
|
+
@max_length.setter
|
|
116
|
+
def max_length(self, value: int | None) -> None:
|
|
117
|
+
"""Update the config."""
|
|
118
|
+
self._max_length = value
|
|
119
|
+
self._update_config("max_length", value)
|
|
120
|
+
|
|
121
|
+
def _update_config(self, key: str, value: Any) -> None:
|
|
122
|
+
"""Write a value to the config, warning if it conflicts with the value already there."""
|
|
123
|
+
config = cast(dict[str, Any], self.config)
|
|
124
|
+
config_value = config.get(key)
|
|
125
|
+
if config_value is not None and value != config_value:
|
|
126
|
+
logger.warning(
|
|
127
|
+
f"Set {key} to `{value}`, which does not match config value `{config_value}`. Updating config."
|
|
128
|
+
)
|
|
129
|
+
config[key] = value
|
|
130
|
+
|
|
131
|
+
@abstractmethod
|
|
132
|
+
def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None:
|
|
133
|
+
"""Save the pretrained model.
|
|
134
|
+
|
|
135
|
+
:param path: The path to save to.
|
|
136
|
+
:param model_name: The model name to use in the Model Card.
|
|
137
|
+
:param subfolder: The subfolder to save to.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def tokenize(self, sentences: Sequence[str]) -> list[list[int]]:
|
|
141
|
+
"""Tokenize a list of sentences into the token ids that `encode` uses, truncated to the model's `max_length`.
|
|
142
|
+
|
|
143
|
+
:param sentences: The sentences to tokenize.
|
|
144
|
+
:return: A list of list of tokens.
|
|
145
|
+
"""
|
|
146
|
+
ids, offsets = self._tokenize_flat(sentences, max_length=self.max_length)
|
|
147
|
+
return [ids[start:end].tolist() for start, end in zip(offsets[:-1].tolist(), offsets[1:].tolist())]
|
|
148
|
+
|
|
149
|
+
def _tokenize_flat(self, sentences: Sequence[str], max_length: int | None) -> tuple[np.ndarray, np.ndarray]:
|
|
150
|
+
"""Tokenize sentences into flat token ids and offsets, as `model2vec_rs.Tokenizer.tokenize` does.
|
|
151
|
+
|
|
152
|
+
:param sentences: The sentences to tokenize.
|
|
153
|
+
:param max_length: The maximum number of tokens per sentence, or None to not truncate.
|
|
154
|
+
:return: The token ids, and the offsets of each sentence's ids.
|
|
155
|
+
"""
|
|
156
|
+
return self.rust_tokenizer.tokenize(list(sentences), max_length=max_length)
|
|
157
|
+
|
|
158
|
+
def push_to_hub(
|
|
159
|
+
self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None
|
|
160
|
+
) -> None:
|
|
161
|
+
"""Push the model to the huggingface hub.
|
|
162
|
+
|
|
163
|
+
NOTE: you need to pass a token if you are pushing a private model.
|
|
164
|
+
|
|
165
|
+
:param repo_id: The repo id to push to.
|
|
166
|
+
:param private: Whether the repo, if created is set to private.
|
|
167
|
+
If the repo already exists, this doesn't change the visibility.
|
|
168
|
+
:param token: The huggingface token to use.
|
|
169
|
+
:param subfolder: The subfolder to push to.
|
|
170
|
+
"""
|
|
171
|
+
from model2vec.persistence import push_folder_to_hub
|
|
172
|
+
|
|
173
|
+
with TemporaryDirectory() as temp_dir:
|
|
174
|
+
self.save_pretrained(temp_dir, model_name=repo_id)
|
|
175
|
+
push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _disable_padding(tokenizer: Tokenizer) -> None:
|
|
179
|
+
"""Stop the tokenizer from padding, while keeping its pad token."""
|
|
180
|
+
padding = tokenizer.padding
|
|
181
|
+
if padding is not None:
|
|
182
|
+
tokenizer.enable_padding(
|
|
183
|
+
pad_id=padding["pad_id"], pad_token=padding["pad_token"], pad_type_id=padding["pad_type_id"], length=0
|
|
184
|
+
)
|
|
@@ -325,7 +325,7 @@ def _save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> No
|
|
|
325
325
|
save_pretrained(
|
|
326
326
|
folder_path=folder_path,
|
|
327
327
|
embeddings=model.embedding,
|
|
328
|
-
tokenizer=model.
|
|
328
|
+
tokenizer=model._tokenizer_to_save(),
|
|
329
329
|
config=config,
|
|
330
330
|
base_model_name=name,
|
|
331
331
|
language=model.language,
|
|
@@ -1,31 +1,29 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
import copy
|
|
4
|
-
import json
|
|
5
3
|
import warnings
|
|
6
4
|
from collections.abc import Sequence
|
|
7
5
|
from logging import getLogger
|
|
8
6
|
from pathlib import Path
|
|
9
|
-
from tempfile import TemporaryDirectory
|
|
10
7
|
from typing import Any, Mapping, TypeVar, cast, overload
|
|
11
8
|
|
|
12
9
|
import model2vec_rs
|
|
13
10
|
import numpy as np
|
|
14
11
|
import numpy.typing as npt
|
|
15
|
-
from tokenizers import
|
|
12
|
+
from tokenizers import Tokenizer
|
|
16
13
|
|
|
14
|
+
from model2vec.base import DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike
|
|
17
15
|
from model2vec.quantization import DType, quantize_and_reduce_dim
|
|
18
16
|
from model2vec.types import _UNSET, StaticModelConfig, _UnsetType
|
|
19
17
|
|
|
20
|
-
PathLike = Path | str
|
|
21
|
-
|
|
22
18
|
logger = getLogger(__name__)
|
|
23
19
|
|
|
24
|
-
DEFAULT_MAX_LENGTH = 512
|
|
25
20
|
_DEFAULT_NORMALIZE = False
|
|
26
21
|
|
|
27
22
|
|
|
28
|
-
class StaticModel:
|
|
23
|
+
class StaticModel(BaseStaticModel[StaticModelConfig]):
|
|
24
|
+
_RUST_CACHES = ("_rust_backend",)
|
|
25
|
+
_rust_backend: tuple[tuple[np.ndarray, np.ndarray | None, np.ndarray | None], model2vec_rs.StaticModel] | None
|
|
26
|
+
|
|
29
27
|
def __init__(
|
|
30
28
|
self,
|
|
31
29
|
vectors: np.ndarray,
|
|
@@ -62,13 +60,18 @@ class StaticModel:
|
|
|
62
60
|
`config` is overridden.
|
|
63
61
|
:raises ValueError: if the number of tokens does not match the number of vectors.
|
|
64
62
|
"""
|
|
65
|
-
super().__init__(
|
|
66
|
-
|
|
67
|
-
|
|
63
|
+
super().__init__(
|
|
64
|
+
tokenizer=tokenizer,
|
|
65
|
+
config=cast(StaticModelConfig, config),
|
|
66
|
+
base_model_name=base_model_name,
|
|
67
|
+
language=language,
|
|
68
|
+
max_length=max_length,
|
|
69
|
+
)
|
|
70
|
+
self.normalize = normalize
|
|
68
71
|
|
|
69
|
-
if token_mapping is None and len(vectors) != len(tokens):
|
|
72
|
+
if token_mapping is None and len(vectors) != len(self.tokens):
|
|
70
73
|
raise ValueError(
|
|
71
|
-
f"Number of tokens ({len(tokens)}) does not match number of vectors ({len(vectors)}). "
|
|
74
|
+
f"Number of tokens ({len(self.tokens)}) does not match number of vectors ({len(vectors)}). "
|
|
72
75
|
"Please provide a token mapping or ensure the number of tokens matches the number of vectors."
|
|
73
76
|
)
|
|
74
77
|
|
|
@@ -76,39 +79,29 @@ class StaticModel:
|
|
|
76
79
|
self.weights = weights
|
|
77
80
|
self.token_mapping = token_mapping
|
|
78
81
|
|
|
79
|
-
self.tokenizer = copy.deepcopy(tokenizer)
|
|
80
|
-
_disable_padding(self.tokenizer)
|
|
81
|
-
self.unk_token_id = _get_unk_token_id(self.tokenizer)
|
|
82
|
-
|
|
83
|
-
self.median_token_length = int(np.median([len(token) for token in self.tokens]))
|
|
84
|
-
self.config: StaticModelConfig = cast(StaticModelConfig, {**config}) if config is not None else {}
|
|
85
|
-
self.base_model_name = base_model_name
|
|
86
|
-
self.language = language
|
|
87
|
-
self.max_length = max_length
|
|
88
|
-
self.normalize = normalize
|
|
89
|
-
|
|
90
|
-
def __getstate__(self) -> dict[str, Any]:
|
|
91
|
-
"""Get the state for pickling, without the Rust backend."""
|
|
92
|
-
state = self.__dict__.copy()
|
|
93
|
-
state.pop("_rust_backend", None)
|
|
94
|
-
return state
|
|
95
|
-
|
|
96
82
|
def __setstate__(self, state: dict[str, Any]) -> None:
|
|
97
83
|
"""Restore the state from pickling, keeping the arrays read-only."""
|
|
98
84
|
for name in ("embedding", "weights", "token_mapping"):
|
|
99
85
|
state[f"_{name}"] = _read_only(state.pop(f"_{name}", state.pop(name, None)))
|
|
100
86
|
state["_tokenizer"] = state.pop("_tokenizer", state.pop("tokenizer", None))
|
|
101
|
-
|
|
87
|
+
for name in ("median_token_length", "unk_token_id"):
|
|
88
|
+
state.pop(name, None)
|
|
89
|
+
state.setdefault("_rust_backend", None)
|
|
90
|
+
vars(self).update(state)
|
|
102
91
|
|
|
103
92
|
@property
|
|
104
|
-
def
|
|
105
|
-
"""
|
|
106
|
-
|
|
93
|
+
def normalize(self) -> bool:
|
|
94
|
+
"""Get the normalize value.
|
|
95
|
+
|
|
96
|
+
:return: The normalize value.
|
|
97
|
+
"""
|
|
98
|
+
return self._normalize
|
|
107
99
|
|
|
108
|
-
@
|
|
109
|
-
def
|
|
110
|
-
|
|
111
|
-
self.
|
|
100
|
+
@normalize.setter
|
|
101
|
+
def normalize(self, value: bool) -> None:
|
|
102
|
+
"""Update the config."""
|
|
103
|
+
self._normalize = value
|
|
104
|
+
self._update_config("normalize", value)
|
|
112
105
|
|
|
113
106
|
@property
|
|
114
107
|
def embedding(self) -> np.ndarray:
|
|
@@ -146,7 +139,7 @@ class StaticModel:
|
|
|
146
139
|
:return: The Rust backend.
|
|
147
140
|
"""
|
|
148
141
|
key = (self.embedding, self.weights, self.token_mapping)
|
|
149
|
-
cached = self.
|
|
142
|
+
cached = self._rust_backend
|
|
150
143
|
if cached is not None and all(old is new for old, new in zip(cached[0], key)):
|
|
151
144
|
return cached[1]
|
|
152
145
|
embedding: npt.NDArray[np.float32] | npt.NDArray[np.int8]
|
|
@@ -171,50 +164,16 @@ class StaticModel:
|
|
|
171
164
|
self._rust_backend = ((self.embedding, self.weights, self.token_mapping), backend)
|
|
172
165
|
return backend
|
|
173
166
|
|
|
167
|
+
@property
|
|
168
|
+
def rust_tokenizer(self) -> model2vec_rs.Tokenizer:
|
|
169
|
+
"""The tokenizer of the Rust backend, which shares its state with the backend."""
|
|
170
|
+
return self._get_rust_backend().tokenizer
|
|
171
|
+
|
|
174
172
|
@property
|
|
175
173
|
def dim(self) -> int:
|
|
176
174
|
"""Get the dimension of the model."""
|
|
177
175
|
return self.embedding.shape[1]
|
|
178
176
|
|
|
179
|
-
@property
|
|
180
|
-
def normalize(self) -> bool:
|
|
181
|
-
"""Get the normalize value.
|
|
182
|
-
|
|
183
|
-
:return: The normalize value.
|
|
184
|
-
"""
|
|
185
|
-
return self._normalize
|
|
186
|
-
|
|
187
|
-
@normalize.setter
|
|
188
|
-
def normalize(self, value: bool) -> None:
|
|
189
|
-
"""Update the config."""
|
|
190
|
-
config_normalize = self.config.get("normalize")
|
|
191
|
-
self._normalize = value
|
|
192
|
-
if config_normalize is not None and value != config_normalize:
|
|
193
|
-
logger.warning(
|
|
194
|
-
f"Set normalization to `{value}`, which does not match config value `{config_normalize}`. Updating config."
|
|
195
|
-
)
|
|
196
|
-
self.config["normalize"] = value
|
|
197
|
-
|
|
198
|
-
@property
|
|
199
|
-
def max_length(self) -> int | None:
|
|
200
|
-
"""Get the max_length value.
|
|
201
|
-
|
|
202
|
-
:return: The max_length value.
|
|
203
|
-
"""
|
|
204
|
-
return self._max_length
|
|
205
|
-
|
|
206
|
-
@max_length.setter
|
|
207
|
-
def max_length(self, value: int | None) -> None:
|
|
208
|
-
"""Update the config."""
|
|
209
|
-
config_max_length = self.config.get("max_length")
|
|
210
|
-
self._max_length = value
|
|
211
|
-
if config_max_length is not None and value != config_max_length:
|
|
212
|
-
logger.warning(
|
|
213
|
-
f"Set max_length to `{value}`, which does not match config value `{config_max_length}`. Updating config."
|
|
214
|
-
)
|
|
215
|
-
self.config["max_length"] = value
|
|
216
|
-
self._set_max_length_in_tokenizer(value)
|
|
217
|
-
|
|
218
177
|
@property
|
|
219
178
|
def embedding_dtype(self) -> str:
|
|
220
179
|
"""Get the dtype (precision) of the embedding matrix."""
|
|
@@ -238,7 +197,7 @@ class StaticModel:
|
|
|
238
197
|
save_pretrained(
|
|
239
198
|
folder_path=Path(path),
|
|
240
199
|
embeddings=self.embedding,
|
|
241
|
-
tokenizer=self.
|
|
200
|
+
tokenizer=self._tokenizer_to_save(),
|
|
242
201
|
config=self.config,
|
|
243
202
|
base_model_name=self.base_model_name,
|
|
244
203
|
language=self.language,
|
|
@@ -248,24 +207,6 @@ class StaticModel:
|
|
|
248
207
|
mapping=self.token_mapping,
|
|
249
208
|
)
|
|
250
209
|
|
|
251
|
-
def tokenize(self, sentences: Sequence[str]) -> list[list[int]]:
|
|
252
|
-
"""Tokenize a list of sentences.
|
|
253
|
-
|
|
254
|
-
:param sentences: The sentences to tokenize.
|
|
255
|
-
:return: A list of list of tokens.
|
|
256
|
-
"""
|
|
257
|
-
encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False)
|
|
258
|
-
|
|
259
|
-
encodings_ids = [encoding.ids for encoding in encodings]
|
|
260
|
-
|
|
261
|
-
if self.unk_token_id is not None:
|
|
262
|
-
# NOTE: Remove the unknown token: necessary for word-level models.
|
|
263
|
-
encodings_ids = [
|
|
264
|
-
[token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids
|
|
265
|
-
]
|
|
266
|
-
|
|
267
|
-
return encodings_ids
|
|
268
|
-
|
|
269
210
|
@classmethod
|
|
270
211
|
def from_pretrained(
|
|
271
212
|
cls: type[T],
|
|
@@ -314,13 +255,6 @@ class StaticModel:
|
|
|
314
255
|
force_download=force_download,
|
|
315
256
|
)
|
|
316
257
|
|
|
317
|
-
def _set_max_length_in_tokenizer(self, max_length: int | None) -> None:
|
|
318
|
-
"""Sets the max length in the tokenizer."""
|
|
319
|
-
if max_length is None:
|
|
320
|
-
self.tokenizer.no_truncation()
|
|
321
|
-
else:
|
|
322
|
-
self.tokenizer.enable_truncation(max_length)
|
|
323
|
-
|
|
324
258
|
@overload
|
|
325
259
|
def encode_as_sequence(self, sentences: str, *, max_length: int | None = None, **kwargs: Any) -> np.ndarray: ...
|
|
326
260
|
|
|
@@ -354,17 +288,11 @@ class StaticModel:
|
|
|
354
288
|
_warn_removed_arguments(kwargs)
|
|
355
289
|
was_single = isinstance(sentences, str)
|
|
356
290
|
sentence_list: list[str] = [sentences] if isinstance(sentences, str) else list(sentences)
|
|
357
|
-
if
|
|
358
|
-
|
|
359
|
-
|
|
291
|
+
if not sentence_list:
|
|
292
|
+
return []
|
|
293
|
+
ids, offsets = self._tokenize_flat(sentence_list, max_length)
|
|
360
294
|
|
|
361
|
-
self.
|
|
362
|
-
try:
|
|
363
|
-
ids = self.tokenize(sentence_list)
|
|
364
|
-
finally:
|
|
365
|
-
self._set_max_length_in_tokenizer(self.max_length)
|
|
366
|
-
|
|
367
|
-
out = [self._encode_helper(id_list) if id_list else np.zeros((0, self.dim)) for id_list in ids]
|
|
295
|
+
out = np.split(self._encode_helper(ids), offsets[1:-1])
|
|
368
296
|
if was_single:
|
|
369
297
|
return out[0]
|
|
370
298
|
return out
|
|
@@ -404,15 +332,15 @@ class StaticModel:
|
|
|
404
332
|
out = out.astype(self.embedding.dtype, copy=False)
|
|
405
333
|
return out
|
|
406
334
|
|
|
407
|
-
def _encode_helper(self, id_list:
|
|
335
|
+
def _encode_helper(self, id_list: np.ndarray) -> np.ndarray:
|
|
408
336
|
"""Helper function to encode a list of ids.
|
|
409
337
|
|
|
410
338
|
It retrieves the embeddings for the given list of ids, applying weights if available.
|
|
411
339
|
|
|
412
|
-
:param id_list:
|
|
340
|
+
:param id_list: An array of token ids.
|
|
413
341
|
:return: The embeddings for the given ids, as a sequence of vectors.
|
|
414
342
|
"""
|
|
415
|
-
id_list_remapped:
|
|
343
|
+
id_list_remapped: np.ndarray
|
|
416
344
|
if self.token_mapping is None:
|
|
417
345
|
id_list_remapped = id_list
|
|
418
346
|
else:
|
|
@@ -423,25 +351,6 @@ class StaticModel:
|
|
|
423
351
|
|
|
424
352
|
return emb
|
|
425
353
|
|
|
426
|
-
def push_to_hub(
|
|
427
|
-
self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None
|
|
428
|
-
) -> None:
|
|
429
|
-
"""Push the model to the huggingface hub.
|
|
430
|
-
|
|
431
|
-
NOTE: you need to pass a token if you are pushing a private model.
|
|
432
|
-
|
|
433
|
-
:param repo_id: The repo id to push to.
|
|
434
|
-
:param private: Whether the repo, if created is set to private.
|
|
435
|
-
If the repo already exists, this doesn't change the visibility.
|
|
436
|
-
:param token: The huggingface token to use.
|
|
437
|
-
:param subfolder: The subfolder to push to.
|
|
438
|
-
"""
|
|
439
|
-
from model2vec.persistence import push_folder_to_hub
|
|
440
|
-
|
|
441
|
-
with TemporaryDirectory() as temp_dir:
|
|
442
|
-
self.save_pretrained(temp_dir, model_name=repo_id)
|
|
443
|
-
push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token)
|
|
444
|
-
|
|
445
354
|
|
|
446
355
|
def quantize_model(
|
|
447
356
|
model: T,
|
|
@@ -546,28 +455,6 @@ def _loading_helper(
|
|
|
546
455
|
)
|
|
547
456
|
|
|
548
457
|
|
|
549
|
-
def _disable_padding(tokenizer: Tokenizer) -> None:
|
|
550
|
-
"""Stop the tokenizer from padding, while keeping its pad token."""
|
|
551
|
-
padding = tokenizer.padding
|
|
552
|
-
if padding is not None:
|
|
553
|
-
tokenizer.enable_padding(
|
|
554
|
-
pad_id=padding["pad_id"], pad_token=padding["pad_token"], pad_type_id=padding["pad_type_id"], length=0
|
|
555
|
-
)
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
def _get_unk_token_id(tokenizer: Tokenizer) -> int | None:
|
|
559
|
-
"""Get the unk token id."""
|
|
560
|
-
model = tokenizer.model
|
|
561
|
-
# Wordpiece + BPE + Word level
|
|
562
|
-
if hasattr(model, "unk_token"):
|
|
563
|
-
token = model.unk_token
|
|
564
|
-
if token is None:
|
|
565
|
-
return None
|
|
566
|
-
return tokenizer.token_to_id(token)
|
|
567
|
-
# Unigram
|
|
568
|
-
return json.loads(tokenizer.to_str())["model"].get("unk_id")
|
|
569
|
-
|
|
570
|
-
|
|
571
458
|
_REMOVED_ARGUMENTS = ("batch_size", "show_progress_bar", "use_multiprocessing", "multiprocessing_threshold")
|
|
572
459
|
|
|
573
460
|
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
{{ card_data }}
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# {{ model_name }} Model Card
|
|
6
|
+
|
|
7
|
+
This is a sparse [Model2Vec](https://github.com/MinishLab/model2vec) model{% if base_model %} based on [{{ base_model }}](https://huggingface.co/{{ base_model }}){% endif %}. Each token has a static sparse code over the vocabulary, so sparse document and query vectors are computed with lookups alone, without running a neural network.
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install model2vec with the `sparse` extra using pip:
|
|
13
|
+
```
|
|
14
|
+
pip install model2vec[sparse]
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Load this model using the `from_pretrained` method of `SparseStaticModel`:
|
|
20
|
+
```python
|
|
21
|
+
from model2vec.sparse import SparseStaticModel
|
|
22
|
+
|
|
23
|
+
# Load a pretrained sparse Model2Vec model
|
|
24
|
+
model = SparseStaticModel.from_pretrained("{{ model_name }}")
|
|
25
|
+
|
|
26
|
+
# Compute sparse query and document vectors
|
|
27
|
+
queries = model.encode_query(["Example query"])
|
|
28
|
+
documents = model.encode_document(["Example document"])
|
|
29
|
+
|
|
30
|
+
# Score queries against documents
|
|
31
|
+
scores = queries @ documents.T
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
This model can also be loaded as a [Sentence Transformers](https://github.com/huggingface/sentence-transformers) `SparseEncoder`. This requires Sentence Transformers in addition to `model2vec[sparse]`:
|
|
35
|
+
```
|
|
36
|
+
pip install model2vec[sparse] sentence-transformers
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from sentence_transformers import SparseEncoder
|
|
41
|
+
|
|
42
|
+
model = SparseEncoder("{{ model_name }}", trust_remote_code=True)
|
|
43
|
+
|
|
44
|
+
queries = model.encode_query(["Example query"])
|
|
45
|
+
documents = model.encode_document(["Example document"])
|
|
46
|
+
scores = model.similarity(queries, documents)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Additional Resources
|
|
50
|
+
|
|
51
|
+
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
|
|
52
|
+
- [Model2Vec Docs](https://minish.ai/packages/model2vec/introduction)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
## Library Authors
|
|
56
|
+
|
|
57
|
+
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).
|
|
58
|
+
|
|
59
|
+
## Citation
|
|
60
|
+
|
|
61
|
+
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
|
|
62
|
+
```
|
|
63
|
+
@software{minishlab2024model2vec,
|
|
64
|
+
author = {Stephan Tulkens and {van Dongen}, Thomas},
|
|
65
|
+
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
66
|
+
year = {2024},
|
|
67
|
+
publisher = {Zenodo},
|
|
68
|
+
doi = {10.5281/zenodo.17270888},
|
|
69
|
+
url = {https://github.com/MinishLab/model2vec},
|
|
70
|
+
license = {MIT}
|
|
71
|
+
}
|
|
72
|
+
```
|