model2vec 0.2.4__py3-none-any.whl → 0.3.0__py3-none-any.whl

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/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- from model2vec.distill import distill
2
1
  from model2vec.model import StaticModel
2
+ from model2vec.version import __version__
3
3
 
4
- __all__ = ["distill", "StaticModel"]
4
+ __all__ = ["StaticModel", "__version__"]
@@ -1,3 +1,10 @@
1
+ from model2vec.utils import get_package_extras, importable
2
+
3
+ _REQUIRED_EXTRA = "distill"
4
+
5
+ for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA):
6
+ importable(extra_dependency, _REQUIRED_EXTRA)
7
+
1
8
  from model2vec.distill.distillation import distill, distill_from_model
2
9
 
3
10
  __all__ = ["distill", "distill_from_model"]
@@ -1,5 +1,7 @@
1
+ from __future__ import annotations
2
+
1
3
  import logging
2
- from typing import Literal
4
+ from typing import Literal, Union
3
5
 
4
6
  import numpy as np
5
7
  from huggingface_hub import model_info
@@ -26,7 +28,7 @@ except ImportError:
26
28
  logger = logging.getLogger(__name__)
27
29
 
28
30
 
29
- PCADimType = int | None | Literal["auto"]
31
+ PCADimType = Union[int, None, Literal["auto"]]
30
32
 
31
33
 
32
34
  def distill_from_model(
@@ -53,7 +55,7 @@ def distill_from_model(
53
55
  :param device: The device to use.
54
56
  :param pca_dims: The number of components to use for PCA.
55
57
  If this is None, we don't apply PCA.
56
- If this is 'auto', we don't reduce dimenionality, but still apply PCA.
58
+ If this is 'auto', we don't reduce dimensionality, but still apply PCA.
57
59
  :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
58
60
  :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
59
61
  :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
@@ -214,9 +216,17 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
214
216
  elif pca_dims <= embeddings.shape[1]:
215
217
  logger.info(f"Applying PCA with n_components {pca_dims}")
216
218
 
219
+ orig_dims = embeddings.shape[1]
217
220
  p = PCA(n_components=pca_dims, whiten=False)
218
221
  embeddings = p.fit_transform(embeddings)
219
222
 
223
+ if embeddings.shape[1] < orig_dims:
224
+ explained_variance_ratio = np.sum(p.explained_variance_ratio_)
225
+ explained_variance = np.sum(p.explained_variance_)
226
+ logger.info(f"Reduced dimensionality from {orig_dims} to {embeddings.shape[1]}.")
227
+ logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
228
+ logger.info(f"Explained variance: {explained_variance:.3f}.")
229
+
220
230
  if apply_zipf:
221
231
  logger.info("Applying Zipf weighting")
222
232
  embeddings *= np.log(1 + np.arange(embeddings.shape[0]))[:, None]
@@ -1,7 +1,10 @@
1
1
  # -*- coding: utf-8 -*-
2
+ from __future__ import annotations
3
+
4
+ import inspect
2
5
  import logging
3
6
  from pathlib import Path
4
- from typing import Protocol
7
+ from typing import Protocol, Union
5
8
 
6
9
  import numpy as np
7
10
  import torch
@@ -12,7 +15,7 @@ from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAtte
12
15
  logger = logging.getLogger(__name__)
13
16
 
14
17
 
15
- PathLike = str | Path
18
+ PathLike = Union[Path, str]
16
19
 
17
20
  _DEFAULT_BATCH_SIZE = 1024
18
21
 
@@ -116,31 +119,39 @@ def create_output_embeddings_from_model_name(
116
119
 
117
120
  # Work-around to get the eos and bos token ids without having to go into tokenizer internals.
118
121
  dummy_encoding = tokenizer.encode("A")
119
- eos_token_id, bos_token_id = dummy_encoding[0], dummy_encoding[-1]
122
+ bos_token_id, eos_token_id = dummy_encoding[0], dummy_encoding[-1]
120
123
 
121
- eos = torch.full([len(ids)], fill_value=eos_token_id)
122
124
  bos = torch.full([len(ids)], fill_value=bos_token_id)
125
+ eos = torch.full([len(ids)], fill_value=eos_token_id)
123
126
 
124
- stacked = torch.stack([bos, ids, eos], dim=1)
127
+ # NOTE: reversing the bos and eos tokens works better on our benchmarks.
128
+ stacked = torch.stack([eos, ids, bos], dim=1)
125
129
 
126
130
  intermediate_weights: list[np.ndarray] = []
127
131
  for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
128
132
  batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
129
133
  with torch.no_grad():
130
- # NOTE: we create these masks because nomic embed requires them.
131
- # Normally, we could set them to None
132
- token_type_ids = torch.zeros_like(batch)
133
134
  attention_mask = torch.ones_like(batch)
134
- encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(
135
- input_ids=batch.to(device), attention_mask=attention_mask, token_type_ids=token_type_ids
136
- )
137
- out: torch.Tensor = encoded.last_hidden_state
135
+ # Prepare model inputs
136
+ model_inputs = {"input_ids": batch.to(device), "attention_mask": attention_mask}
137
+
138
+ # Add token_type_ids only if the model supports it
139
+ if "token_type_ids" in inspect.getfullargspec(model.forward).args:
140
+ model_inputs["token_type_ids"] = torch.zeros_like(batch)
141
+
142
+ # Perform the forward pass
143
+ encoded_output: BaseModelOutputWithPoolingAndCrossAttentions = model(**model_inputs)
144
+ out: torch.Tensor = encoded_output.last_hidden_state
138
145
  # NOTE: If the dtype is bfloat 16, we convert to float32,
139
146
  # because numpy does not suport bfloat16
140
147
  # See here: https://github.com/numpy/numpy/issues/19808
141
148
  if out.dtype == torch.bfloat16:
142
149
  out = out.float()
143
- intermediate_weights.append(out[:, 1].cpu().numpy())
150
+
151
+ # Add the output to the intermediate weights
152
+ intermediate_weights.append(out[:, 1].detach().cpu().numpy())
153
+
154
+ # Concatenate the intermediate weights
144
155
  out_weights = np.concatenate(intermediate_weights)
145
156
 
146
157
  return tokenizer.convert_ids_to_tokens(ids), out_weights
@@ -49,29 +49,31 @@ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenize
49
49
  # Load the vocabulary.
50
50
  model_type = tokenizer_data["model"]["type"]
51
51
 
52
- match model_type:
53
- case "WordPiece":
54
- # Vocab is a dictionary.
55
- vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
56
- n_tokens = len(vocab)
57
-
58
- # Remove the tokens.
59
- for token in tokens_to_remove:
60
- if vocab.pop(token, None) is None:
61
- logger.warning(f"Token {token} was not in the vocabulary.")
62
-
63
- n_removed = n_tokens - len(vocab)
64
- logger.info(f"Removed {n_removed} tokens from the vocabulary.")
65
-
66
- # Reindex the vocabulary so that it is contiguous.
67
- reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
68
- tokenizer_data["model"]["vocab"] = reindexed
69
- case "Unigram":
70
- raise ValueError("Removing tokens from a unigram tokenizer is not supported.")
71
- case "BPE":
72
- raise ValueError("Removing tokens from a bpe tokenizer is not supported.")
73
- case _:
74
- raise ValueError(f"Unknown model type {model_type}")
52
+ if model_type == "WordPiece":
53
+ # Vocab is a dictionary.
54
+ vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
55
+ n_tokens = len(vocab)
56
+
57
+ # Remove the tokens.
58
+ for token in tokens_to_remove:
59
+ if vocab.pop(token, None) is None:
60
+ logger.warning(f"Token {token} was not in the vocabulary.")
61
+
62
+ n_removed = n_tokens - len(vocab)
63
+ logger.info(f"Removed {n_removed} tokens from the vocabulary.")
64
+
65
+ # Reindex the vocabulary so that it is contiguous.
66
+ reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
67
+ tokenizer_data["model"]["vocab"] = reindexed
68
+
69
+ elif model_type == "Unigram":
70
+ raise ValueError("Removing tokens from a unigram tokenizer is not supported.")
71
+
72
+ elif model_type == "BPE":
73
+ raise ValueError("Removing tokens from a BPE tokenizer is not supported.")
74
+
75
+ else:
76
+ raise ValueError(f"Unknown model type {model_type}")
75
77
 
76
78
  # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
77
79
  special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
@@ -97,18 +99,20 @@ def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
97
99
 
98
100
  model = data["model"]["type"]
99
101
 
100
- match model:
101
- case "WordPiece":
102
- wordpiece_vocab: dict[str, int] = data["model"]["vocab"]
103
- for token in tokens_to_add:
104
- if token not in wordpiece_vocab:
105
- wordpiece_vocab[token] = len(wordpiece_vocab)
106
- case "Unigram":
107
- raise ValueError("Adding tokens to a unigram tokenizer is not supported.")
108
- case "BPE":
109
- raise ValueError("Adding tokens to a bpe tokenizer is not supported.")
110
- case _:
111
- raise ValueError(f"Unknown model type {model}")
102
+ if model == "WordPiece":
103
+ wordpiece_vocab: dict[str, int] = data["model"]["vocab"]
104
+ for token in tokens_to_add:
105
+ if token not in wordpiece_vocab:
106
+ wordpiece_vocab[token] = len(wordpiece_vocab)
107
+
108
+ elif model == "Unigram":
109
+ raise ValueError("Adding tokens to a unigram tokenizer is not supported.")
110
+
111
+ elif model == "BPE":
112
+ raise ValueError("Adding tokens to a BPE tokenizer is not supported.")
113
+
114
+ else:
115
+ raise ValueError(f"Unknown model type {model}")
112
116
 
113
117
  tokenizer = Tokenizer.from_str(json.dumps(data))
114
118
 
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  from logging import getLogger
2
4
 
3
5
  import torch
model2vec/hf_utils.py ADDED
@@ -0,0 +1,198 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any, cast
7
+
8
+ import huggingface_hub
9
+ import huggingface_hub.errors
10
+ import numpy as np
11
+ import safetensors
12
+ from huggingface_hub import ModelCard, ModelCardData
13
+ from safetensors.numpy import save_file
14
+ from tokenizers import Tokenizer
15
+
16
+ from model2vec.utils import SafeOpenProtocol
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def save_pretrained(
22
+ folder_path: Path,
23
+ embeddings: np.ndarray,
24
+ tokenizer: Tokenizer,
25
+ config: dict[str, Any],
26
+ create_model_card: bool = True,
27
+ **kwargs: Any,
28
+ ) -> None:
29
+ """
30
+ Save a model to a folder.
31
+
32
+ :param folder_path: The path to the folder.
33
+ :param embeddings: The embeddings.
34
+ :param tokenizer: The tokenizer.
35
+ :param config: A metadata config.
36
+ :param create_model_card: Whether to create a model card.
37
+ :param **kwargs: Any additional arguments.
38
+ """
39
+ folder_path.mkdir(exist_ok=True, parents=True)
40
+ save_file({"embeddings": embeddings}, folder_path / "model.safetensors")
41
+ tokenizer.save(str(folder_path / "tokenizer.json"))
42
+ json.dump(config, open(folder_path / "config.json", "w"))
43
+
44
+ logger.info(f"Saved model to {folder_path}")
45
+
46
+ # Optionally create the model card
47
+ if create_model_card:
48
+ _create_model_card(folder_path, **kwargs)
49
+
50
+
51
+ def _create_model_card(
52
+ folder_path: Path,
53
+ base_model_name: str = "unknown",
54
+ license: str = "mit",
55
+ language: list[str] | None = None,
56
+ model_name: str | None = None,
57
+ **kwargs: Any,
58
+ ) -> None:
59
+ """
60
+ Create a model card and store it in the specified path.
61
+
62
+ :param folder_path: The path where the model card will be stored.
63
+ :param base_model_name: The name of the base model.
64
+ :param license: The license to use.
65
+ :param language: The language of the model.
66
+ :param model_name: The name of the model to use in the Model Card.
67
+ :param **kwargs: Additional metadata for the model card (e.g., model_name, base_model, etc.).
68
+ """
69
+ folder_path = Path(folder_path)
70
+ model_name = model_name or folder_path.name
71
+ template_path = Path(__file__).parent / "model_card_template.md"
72
+
73
+ model_card_data = ModelCardData(
74
+ model_name=model_name,
75
+ base_model=base_model_name,
76
+ license=license,
77
+ language=language,
78
+ tags=["embeddings", "static-embeddings"],
79
+ library_name="model2vec",
80
+ **kwargs,
81
+ )
82
+ model_card = ModelCard.from_template(model_card_data, template_path=template_path)
83
+ model_card.save(folder_path / "README.md")
84
+
85
+
86
+ def load_pretrained(
87
+ folder_or_repo_path: str | Path, token: str | None = None
88
+ ) -> tuple[np.ndarray, Tokenizer, dict[str, Any], dict[str, Any]]:
89
+ """
90
+ Loads a pretrained model from a folder.
91
+
92
+ :param folder_or_repo_path: The folder or repo path to load from.
93
+ - If this is a local path, we will load from the local path.
94
+ - If the local path is not found, we will attempt to load from the huggingface hub.
95
+ :param token: The huggingface token to use.
96
+ :raises: FileNotFoundError if the folder exists, but the file does not exist locally.
97
+ :return: The embeddings, tokenizer, config, and metadata.
98
+
99
+ """
100
+ folder_or_repo_path = Path(folder_or_repo_path)
101
+ if folder_or_repo_path.exists():
102
+ embeddings_path = folder_or_repo_path / "model.safetensors"
103
+ if not embeddings_path.exists():
104
+ old_embeddings_path = folder_or_repo_path / "embeddings.safetensors"
105
+ if old_embeddings_path.exists():
106
+ logger.warning("Old embeddings file found. Please rename to `model.safetensors` and re-save.")
107
+ embeddings_path = old_embeddings_path
108
+ else:
109
+ raise FileNotFoundError(f"Embeddings file does not exist in {folder_or_repo_path}")
110
+
111
+ config_path = folder_or_repo_path / "config.json"
112
+ if not config_path.exists():
113
+ raise FileNotFoundError(f"Config file does not exist in {folder_or_repo_path}")
114
+
115
+ tokenizer_path = folder_or_repo_path / "tokenizer.json"
116
+ if not tokenizer_path.exists():
117
+ raise FileNotFoundError(f"Tokenizer file does not exist in {folder_or_repo_path}")
118
+
119
+ # README is optional, so this is a bit finicky.
120
+ readme_path = folder_or_repo_path / "README.md"
121
+ metadata = _get_metadata_from_readme(readme_path)
122
+
123
+ else:
124
+ logger.info("Folder does not exist locally, attempting to use huggingface hub.")
125
+ try:
126
+ embeddings_path = huggingface_hub.hf_hub_download(
127
+ folder_or_repo_path.as_posix(), "model.safetensors", token=token
128
+ )
129
+ except huggingface_hub.utils.EntryNotFoundError as e:
130
+ try:
131
+ embeddings_path = huggingface_hub.hf_hub_download(
132
+ folder_or_repo_path.as_posix(), "embeddings.safetensors", token=token
133
+ )
134
+ except huggingface_hub.utils.EntryNotFoundError:
135
+ # Raise original exception.
136
+ raise e
137
+
138
+ try:
139
+ readme_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "README.md", token=token)
140
+ metadata = _get_metadata_from_readme(Path(readme_path))
141
+ except huggingface_hub.utils.EntryNotFoundError:
142
+ logger.info("No README found in the model folder. No model card loaded.")
143
+ metadata = {}
144
+
145
+ config_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "config.json", token=token)
146
+ tokenizer_path = huggingface_hub.hf_hub_download(folder_or_repo_path.as_posix(), "tokenizer.json", token=token)
147
+
148
+ opened_tensor_file = cast(SafeOpenProtocol, safetensors.safe_open(embeddings_path, framework="numpy"))
149
+ embeddings = opened_tensor_file.get_tensor("embeddings")
150
+
151
+ tokenizer: Tokenizer = Tokenizer.from_file(str(tokenizer_path))
152
+ config = json.load(open(config_path))
153
+
154
+ if len(tokenizer.get_vocab()) != len(embeddings):
155
+ logger.warning(
156
+ f"Number of tokens does not match number of embeddings: `{len(tokenizer.get_vocab())}` vs `{len(embeddings)}`"
157
+ )
158
+
159
+ return embeddings, tokenizer, config, metadata
160
+
161
+
162
+ def _get_metadata_from_readme(readme_path: Path) -> dict[str, Any]:
163
+ """Get metadata from a README file."""
164
+ if not readme_path.exists():
165
+ logger.info(f"README file not found in {readme_path}. No model card loaded.")
166
+ return {}
167
+ model_card = ModelCard.load(readme_path)
168
+ data: dict[str, Any] = model_card.data.to_dict()
169
+ if not data:
170
+ logger.info("File README.md exists, but was empty. No model card loaded.")
171
+ return data
172
+
173
+
174
+ def push_folder_to_hub(folder_path: Path, repo_id: str, private: bool, token: str | None) -> None:
175
+ """
176
+ Push a model folder to the huggingface hub, including model card.
177
+
178
+ :param folder_path: The path to the folder.
179
+ :param repo_id: The repo name.
180
+ :param private: Whether the repo is private.
181
+ :param token: The huggingface token.
182
+ """
183
+ if not huggingface_hub.repo_exists(repo_id=repo_id, token=token):
184
+ huggingface_hub.create_repo(repo_id, token=token, private=private)
185
+
186
+ # Push model card and all model files to the Hugging Face hub
187
+ huggingface_hub.upload_folder(repo_id=repo_id, folder_path=folder_path, token=token)
188
+
189
+ # Check if the model card exists, and push it if available
190
+ model_card_path = folder_path / "README.md"
191
+ if model_card_path.exists():
192
+ card = ModelCard.load(model_card_path)
193
+ card.push_to_hub(repo_id=repo_id, token=token)
194
+ logger.info(f"Pushed model card to {repo_id}")
195
+ else:
196
+ logger.warning(f"Model card README.md not found in {folder_path}. Skipping model card upload.")
197
+
198
+ logger.info(f"Pushed model to {repo_id}")