model2vec 0.8.1__tar.gz → 0.8.2__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.
Files changed (80) hide show
  1. {model2vec-0.8.1 → model2vec-0.8.2}/.github/workflows/ci.yaml +5 -5
  2. model2vec-0.8.2/.github/workflows/release.yaml +40 -0
  3. model2vec-0.8.2/.pre-commit-config.yaml +37 -0
  4. model2vec-0.8.2/Makefile +23 -0
  5. {model2vec-0.8.1 → model2vec-0.8.2}/PKG-INFO +4 -6
  6. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/distill/distillation.py +15 -23
  7. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/distill/inference.py +24 -30
  8. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/distill/utils.py +1 -2
  9. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/inference/model.py +36 -32
  10. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/model.py +12 -22
  11. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/modelcards/modelcards.py +1 -2
  12. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/persistence/hf.py +2 -4
  13. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/persistence/persistence.py +2 -4
  14. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/quantization.py +2 -4
  15. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/tokenizer/tokenizer.py +20 -4
  16. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/train/__init__.py +8 -1
  17. model2vec-0.8.2/model2vec/train/base.py +437 -0
  18. model2vec-0.8.2/model2vec/train/classifier.py +278 -0
  19. model2vec-0.8.2/model2vec/train/dataset.py +39 -0
  20. model2vec-0.8.2/model2vec/train/lightning_modules.py +99 -0
  21. model2vec-0.8.2/model2vec/train/similarity.py +117 -0
  22. model2vec-0.8.2/model2vec/train/utils.py +118 -0
  23. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/utils.py +1 -14
  24. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/version.py +1 -1
  25. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec.egg-info/PKG-INFO +4 -6
  26. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec.egg-info/SOURCES.txt +4 -0
  27. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec.egg-info/requires.txt +2 -4
  28. {model2vec-0.8.1 → model2vec-0.8.2}/pyproject.toml +8 -7
  29. {model2vec-0.8.1 → model2vec-0.8.2}/scripts/export_to_onnx.py +4 -9
  30. {model2vec-0.8.1 → model2vec-0.8.2}/tests/conftest.py +24 -1
  31. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_distillation.py +45 -5
  32. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_inference.py +23 -4
  33. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_trainable.py +104 -8
  34. {model2vec-0.8.1 → model2vec-0.8.2}/uv.lock +10 -93
  35. model2vec-0.8.1/.pre-commit-config.yaml +0 -36
  36. model2vec-0.8.1/Makefile +0 -21
  37. model2vec-0.8.1/model2vec/train/base.py +0 -207
  38. model2vec-0.8.1/model2vec/train/classifier.py +0 -463
  39. model2vec-0.8.1/model2vec/train/utils.py +0 -21
  40. {model2vec-0.8.1 → model2vec-0.8.2}/.gitignore +0 -0
  41. {model2vec-0.8.1 → model2vec-0.8.2}/CITATION.cff +0 -0
  42. {model2vec-0.8.1 → model2vec-0.8.2}/LICENSE +0 -0
  43. {model2vec-0.8.1 → model2vec-0.8.2}/README.md +0 -0
  44. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/logo_v2.png +0 -0
  45. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/model2vec_logo.png +0 -0
  46. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/speed_vs_mteb_plot.png +0 -0
  47. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  48. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/training_speed_vs_score.png +0 -0
  49. {model2vec-0.8.1 → model2vec-0.8.2}/assets/images/tutorial_ezlo.png +0 -0
  50. {model2vec-0.8.1 → model2vec-0.8.2}/docs/README.md +0 -0
  51. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/__init__.py +0 -0
  52. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/distill/__init__.py +0 -0
  53. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/inference/README.md +0 -0
  54. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/inference/__init__.py +0 -0
  55. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/modelcards/__init__.py +0 -0
  56. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/modelcards/classifier_template.md +0 -0
  57. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/modelcards/model_card_template.md +0 -0
  58. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/persistence/__init__.py +0 -0
  59. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/persistence/datamodels.py +0 -0
  60. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/py.typed +0 -0
  61. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/tokenizer/__init__.py +0 -0
  62. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/train/README.md +0 -0
  63. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec/vocabulary_quantization.py +0 -0
  64. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec.egg-info/dependency_links.txt +0 -0
  65. {model2vec-0.8.1 → model2vec-0.8.2}/model2vec.egg-info/top_level.txt +0 -0
  66. {model2vec-0.8.1 → model2vec-0.8.2}/results/README.md +0 -0
  67. {model2vec-0.8.1 → model2vec-0.8.2}/results/make_speed_vs_mteb_plot.py +0 -0
  68. {model2vec-0.8.1 → model2vec-0.8.2}/setup.cfg +0 -0
  69. {model2vec-0.8.1 → model2vec-0.8.2}/tests/__init__.py +0 -0
  70. {model2vec-0.8.1 → model2vec-0.8.2}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  71. {model2vec-0.8.1 → model2vec-0.8.2}/tests/data/test_tokenizer/tokenizer.json +0 -0
  72. {model2vec-0.8.1 → model2vec-0.8.2}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  73. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_model.py +0 -0
  74. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_persistence.py +0 -0
  75. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_quantization.py +0 -0
  76. {model2vec-0.8.1 → model2vec-0.8.2}/tests/test_utils.py +0 -0
  77. {model2vec-0.8.1 → model2vec-0.8.2}/tutorials/README.md +0 -0
  78. {model2vec-0.8.1 → model2vec-0.8.2}/tutorials/recipe_search.ipynb +0 -0
  79. {model2vec-0.8.1 → model2vec-0.8.2}/tutorials/semantic_chunking.ipynb +0 -0
  80. {model2vec-0.8.1 → model2vec-0.8.2}/tutorials/train_classifier.ipynb +0 -0
@@ -14,19 +14,19 @@ jobs:
14
14
  fail-fast: false
15
15
  matrix:
16
16
  os: ["ubuntu-latest", "windows-latest"]
17
- python-version: ["3.10", "3.11", "3.12", "3.13"]
17
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
18
18
 
19
19
  steps:
20
- - uses: actions/checkout@v4
20
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
21
21
 
22
22
  - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
23
- uses: actions/setup-python@v5
23
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
24
24
  with:
25
25
  python-version: ${{ matrix.python-version }}
26
26
  allow-prereleases: true
27
27
 
28
28
  - name: Install uv
29
- uses: astral-sh/setup-uv@v6
29
+ uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff
30
30
 
31
31
  - name: Create virtual environment
32
32
  run: uv venv .venv
@@ -54,6 +54,6 @@ jobs:
54
54
  coverage report
55
55
 
56
56
  - name: Upload results to Codecov
57
- uses: codecov/codecov-action@v4
57
+ uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238
58
58
  with:
59
59
  token: ${{ secrets.CODECOV_TOKEN }}
@@ -0,0 +1,40 @@
1
+ name: Release to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ jobs:
7
+ build:
8
+ name: Build distribution
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
12
+
13
+ - name: Install uv
14
+ uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff
15
+
16
+ - name: Build package
17
+ run: uv build
18
+
19
+ - name: Upload dist
20
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
21
+ with:
22
+ name: dist
23
+ path: dist/
24
+
25
+ publish:
26
+ name: Publish to PyPI
27
+ needs: build
28
+ runs-on: ubuntu-latest
29
+ environment: release
30
+ permissions:
31
+ id-token: write
32
+ steps:
33
+ - name: Download dist
34
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
35
+ with:
36
+ name: dist
37
+ path: dist/
38
+
39
+ - name: Publish to PyPI
40
+ uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b
@@ -0,0 +1,37 @@
1
+ minimum_pre_commit_version: "3.2.0"
2
+
3
+ default_language_version:
4
+ python: python3
5
+
6
+ repos:
7
+ - repo: https://github.com/pre-commit/pre-commit-hooks
8
+ rev: v6.0.0
9
+ hooks:
10
+ - id: no-commit-to-branch
11
+ args: [--branch, main]
12
+ - id: check-ast
13
+ - id: check-yaml
14
+ - id: check-toml
15
+ - id: check-json
16
+ - id: check-merge-conflict
17
+ - id: debug-statements
18
+ - id: trailing-whitespace
19
+ - id: end-of-file-fixer
20
+ - id: check-added-large-files
21
+ args: ["--maxkb=5000"]
22
+ - id: check-case-conflict
23
+ - repo: https://github.com/jsh9/pydoclint
24
+ rev: 0.8.3
25
+ hooks:
26
+ - id: pydoclint
27
+ - repo: https://github.com/astral-sh/ruff-pre-commit
28
+ rev: v0.15.12
29
+ hooks:
30
+ - id: ruff-check
31
+ args: [--fix]
32
+ - id: ruff-format
33
+ - repo: https://github.com/pre-commit/mirrors-mypy
34
+ rev: v1.15.0
35
+ hooks:
36
+ - id: mypy
37
+ additional_dependencies: []
@@ -0,0 +1,23 @@
1
+ VERBOSITY=
2
+
3
+ venv:
4
+ uv venv
5
+
6
+ install:
7
+ uv sync --all-extras
8
+ uv run pre-commit install
9
+
10
+ install-no-pre-commit:
11
+ uv pip install ".[dev,distill,inference,train,onnx,quantization]"
12
+
13
+ install-base:
14
+ uv sync --extra dev
15
+
16
+ fix:
17
+ uv run pre-commit run --all-files
18
+
19
+ test:
20
+ uv run pytest --cov=model2vec --cov-report=term-missing $(VERBOSITY)
21
+
22
+ test-verbose:
23
+ make test VERBOSITY="-vvv"
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: model2vec
3
- Version: 0.8.1
3
+ Version: 0.8.2
4
4
  Summary: Fast State-of-the-Art Static Embeddings
5
- Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
5
+ Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomasvdongen@proton.me>
6
6
  License: MIT License
7
7
 
8
8
  Copyright (c) 2024 Thomas van Dongen
@@ -45,24 +45,22 @@ Description-Content-Type: text/markdown
45
45
  Requires-Dist: jinja2
46
46
  Requires-Dist: joblib
47
47
  Requires-Dist: numpy
48
- Requires-Dist: rich
49
48
  Requires-Dist: safetensors
50
- Requires-Dist: setuptools
51
49
  Requires-Dist: tokenizers>=0.20
52
50
  Requires-Dist: tqdm
53
51
  Provides-Extra: dev
54
- Requires-Dist: black; extra == "dev"
55
52
  Requires-Dist: ipython; extra == "dev"
56
53
  Requires-Dist: mypy; extra == "dev"
57
54
  Requires-Dist: pre-commit; extra == "dev"
58
55
  Requires-Dist: pytest; extra == "dev"
59
56
  Requires-Dist: pytest-cov; extra == "dev"
60
57
  Requires-Dist: ruff; extra == "dev"
58
+ Requires-Dist: setuptools; extra == "dev"
61
59
  Provides-Extra: distill
62
60
  Requires-Dist: torch; extra == "distill"
63
61
  Requires-Dist: transformers<5.4.0; extra == "distill"
64
62
  Requires-Dist: scikit-learn; extra == "distill"
65
- Requires-Dist: skeletoken>=0.3.2; extra == "distill"
63
+ Requires-Dist: skeletoken>=0.3.3; extra == "distill"
66
64
  Provides-Extra: onnx
67
65
  Requires-Dist: onnx; extra == "onnx"
68
66
  Requires-Dist: torch; extra == "onnx"
@@ -5,15 +5,13 @@ import os
5
5
  import re
6
6
  from typing import cast
7
7
 
8
- import numpy as np
9
8
  from huggingface_hub.hf_api import model_info
10
9
  from skeletoken import TokenizerModel
11
10
  from skeletoken.external.transformers import reshape_embeddings
12
- from transformers import AutoModel, AutoTokenizer
11
+ from transformers import AutoModel, AutoTokenizer, PreTrainedTokenizerFast
13
12
  from transformers.modeling_utils import PreTrainedModel
14
- from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
15
13
 
16
- from model2vec.distill.inference import PCADimType, PoolingMode, create_embeddings, post_process_embeddings
14
+ from model2vec.distill.inference import PCADimType, PoolingMode, apply_pca, compute_weights, create_embeddings
17
15
  from model2vec.distill.utils import select_optimal_device
18
16
  from model2vec.model import StaticModel
19
17
  from model2vec.quantization import DType, quantize_embeddings
@@ -35,8 +33,7 @@ def distill_from_model(
35
33
  vocabulary_quantization: int | None = None,
36
34
  pooling: PoolingMode | str = PoolingMode.MEAN,
37
35
  ) -> StaticModel:
38
- """
39
- Distill a staticmodel from a sentence transformer.
36
+ """Distill a staticmodel from a sentence transformer.
40
37
 
41
38
  This function creates a set of embeddings from a sentence transformer. It does this by doing either
42
39
  a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
@@ -67,7 +64,7 @@ def distill_from_model(
67
64
  'first': use the first token's hidden state ([CLS] token in BERT-style models).
68
65
  'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.
69
66
  :return: A StaticModel.
70
- :raises: ValueError if the vocabulary is empty after preprocessing.
67
+ :raises ValueError: if the vocabulary is empty after preprocessing.
71
68
 
72
69
  """
73
70
  quantize_to = DType(quantize_to)
@@ -88,12 +85,6 @@ def distill_from_model(
88
85
 
89
86
  # Create the vocabulary in the new tokenizer.
90
87
  tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)
91
- # Remove the post processor, this is not necessary.
92
- tokenizer_model.post_processor = None
93
- # Prune again now that the post processor is gone.
94
- # We can't do this before because we need the post processor and associated
95
- # tokens before to add eos/bos.
96
- tokenizer_model = tokenizer_model.prune_added_tokens()
97
88
 
98
89
  # All tokens in a single list.
99
90
  all_tokens = tokenizer_model.sorted_vocabulary
@@ -115,16 +106,19 @@ def distill_from_model(
115
106
  pooling=pooling,
116
107
  )
117
108
 
118
- # Maybe apply quantization
109
+ # Apply quantization
119
110
  if vocabulary_quantization is not None:
120
- _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)
111
+ weights = compute_weights(len(embeddings), sif_coefficient=sif_coefficient)
121
112
  embeddings, token_mapping, weights = quantize_vocabulary(
122
- n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)
113
+ n_clusters=vocabulary_quantization, weights=weights, embeddings=embeddings
123
114
  )
124
- embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)
115
+ embeddings = apply_pca(embeddings, pca_dims)
125
116
  else:
126
117
  # Post-process the embeddings.
127
- embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
118
+ weights = compute_weights(len(embeddings), sif_coefficient=sif_coefficient)
119
+ embeddings = apply_pca(embeddings, pca_dims)
120
+ embeddings = embeddings * weights[:, None]
121
+ weights = None
128
122
  token_mapping = None
129
123
  # Quantize the embeddings.
130
124
  embeddings = quantize_embeddings(embeddings, quantize_to)
@@ -173,15 +167,14 @@ def _validate_parameters(
173
167
  sif_coefficient: float | None,
174
168
  token_remove_pattern: str | None,
175
169
  ) -> tuple[float | None, re.Pattern[str] | None]:
176
- """
177
- Validate the parameters passed to the distillation function.
170
+ """Validate the parameters passed to the distillation function.
178
171
 
179
172
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
180
173
  Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
181
174
  :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
182
175
  this regex pattern will be removed from the vocabulary.
183
176
  :return: The SIF coefficient to use.
184
- :raises: ValueError if the regex can't be compiled.
177
+ :raises ValueError: if the regex can't be compiled.
185
178
 
186
179
  """
187
180
  if sif_coefficient is not None:
@@ -210,8 +203,7 @@ def distill(
210
203
  vocabulary_quantization: int | None = None,
211
204
  pooling: PoolingMode | str = PoolingMode.MEAN,
212
205
  ) -> StaticModel:
213
- """
214
- Distill a staticmodel from a sentence transformer.
206
+ """Distill a staticmodel from a sentence transformer.
215
207
 
216
208
  This function creates a set of embeddings from a sentence transformer. It does this by doing either
217
209
  a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
@@ -23,8 +23,7 @@ _DEFAULT_BATCH_SIZE = 256
23
23
 
24
24
 
25
25
  class PoolingMode(str, Enum):
26
- """
27
- Pooling modes for embedding creation.
26
+ """Pooling modes for embedding creation.
28
27
 
29
28
  - MEAN: masked mean over all tokens.
30
29
  - LAST: last non-padding token (often EOS, common in decoder-style models).
@@ -48,8 +47,7 @@ def create_embeddings(
48
47
  pad_token_id: int,
49
48
  pooling: PoolingMode | str = PoolingMode.MEAN,
50
49
  ) -> 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.
53
51
 
54
52
  It does a forward pass for all tokens passed in `tokens`.
55
53
 
@@ -121,8 +119,7 @@ def create_embeddings(
121
119
  def _encode_with_model(
122
120
  model: PreTrainedModel, encodings: dict[str, torch.Tensor]
123
121
  ) -> 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.
126
123
 
127
124
  :param model: The model to use.
128
125
  :param encodings: The encoded tokens to turn into features.
@@ -137,18 +134,16 @@ def _encode_with_model(
137
134
  # NOTE: If the dtype is bfloat 16, we convert to float32,
138
135
  # because numpy does not suport bfloat16
139
136
  # See here: https://github.com/numpy/numpy/issues/19808
140
- if hidden.dtype == torch.bfloat16:
141
- hidden = hidden.float()
137
+ hidden = hidden.float()
142
138
  pooler = getattr(outputs, "pooler_output", None)
143
- if pooler is not None and pooler.dtype == torch.bfloat16:
139
+ if pooler is not None:
144
140
  pooler = pooler.float()
145
141
  return hidden, pooler, encodings_on_device
146
142
 
147
143
 
148
144
  @torch.inference_mode()
149
145
  def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
150
- """
151
- Encode a batch of tokens using mean pooling.
146
+ """Encode a batch of tokens using mean pooling.
152
147
 
153
148
  :param model: The model to use.
154
149
  :param encodings: The encoded tokens to turn into features.
@@ -164,8 +159,7 @@ def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
164
159
 
165
160
  @torch.inference_mode()
166
161
  def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
167
- """
168
- Encode a batch of tokens using last token pooling.
162
+ """Encode a batch of tokens using last token pooling.
169
163
 
170
164
  :param model: The model to use.
171
165
  :param encodings: The encoded tokens to turn into features.
@@ -180,8 +174,7 @@ def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
180
174
 
181
175
  @torch.inference_mode()
182
176
  def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
183
- """
184
- Encode a batch of tokens using first token (CLS) pooling.
177
+ """Encode a batch of tokens using first token (CLS) pooling.
185
178
 
186
179
  :param model: The model to use.
187
180
  :param encodings: The encoded tokens to turn into features.
@@ -193,8 +186,7 @@ def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.
193
186
 
194
187
  @torch.inference_mode()
195
188
  def _encode_pooler_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
196
- """
197
- Encode a batch of tokens using pooler output.
189
+ """Encode a batch of tokens using pooler output.
198
190
 
199
191
  :param model: The model to use.
200
192
  :param encodings: The encoded tokens to turn into features.
@@ -207,10 +199,20 @@ def _encode_pooler_with_model(model: PreTrainedModel, encodings: dict[str, torch
207
199
  return pooler.cpu()
208
200
 
209
201
 
210
- def post_process_embeddings(
211
- embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4
212
- ) -> tuple[np.ndarray, np.ndarray]:
213
- """Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law."""
202
+ def compute_weights(n_embeddings: int, sif_coefficient: float | None) -> np.ndarray:
203
+ """Compute the weights based on Zipf's law and a SIF coefficient."""
204
+ if sif_coefficient is None:
205
+ return np.ones(n_embeddings)
206
+ logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
207
+ inv_rank = 1 / (np.arange(2, n_embeddings + 2))
208
+ proba = inv_rank / np.sum(inv_rank)
209
+ weight = sif_coefficient / (sif_coefficient + proba)
210
+
211
+ return weight
212
+
213
+
214
+ def apply_pca(embeddings: np.ndarray, pca_dims: PCADimType) -> np.ndarray:
215
+ """Apply PCA to the embeddings."""
214
216
  if pca_dims is not None:
215
217
  if pca_dims == "auto":
216
218
  pca_dims = embeddings.shape[1]
@@ -242,12 +244,4 @@ def post_process_embeddings(
242
244
  logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
243
245
  logger.info(f"Explained variance: {explained_variance:.3f}.")
244
246
 
245
- if sif_coefficient is not None:
246
- logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
247
- inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
248
- proba = inv_rank / np.sum(inv_rank)
249
- weight = sif_coefficient / (sif_coefficient + proba)
250
- else:
251
- weight = np.ones(embeddings.shape[0])
252
-
253
- return embeddings, weight
247
+ return embeddings
@@ -9,8 +9,7 @@ logger = getLogger(__name__)
9
9
 
10
10
 
11
11
  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.
14
13
 
15
14
  For Torch versions >= 2.8.0, MPS is disabled due to known performance regressions.
16
15
 
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import re
4
4
  from collections.abc import Sequence
5
+ from enum import Enum
5
6
  from pathlib import Path
6
7
  from tempfile import TemporaryDirectory
7
8
  from typing import TypeVar, cast
@@ -10,7 +11,7 @@ import huggingface_hub
10
11
  import numpy as np
11
12
  import skops.io
12
13
  from sklearn.metrics import classification_report
13
- from sklearn.neural_network import MLPClassifier
14
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
14
15
  from sklearn.pipeline import Pipeline
15
16
  from sklearn.preprocessing import MultiLabelBinarizer
16
17
 
@@ -23,32 +24,35 @@ _DEFAULT_MODEL_FILENAME = "pipeline.skops"
23
24
  LabelType = TypeVar("LabelType", list[str], list[list[str]])
24
25
 
25
26
 
27
+ class HeadType(str, Enum):
28
+ CLASSIFIER = "classifier"
29
+ PROJECTOR = "projector"
30
+ MULTILABEL = "multilabel"
31
+
32
+
26
33
  class StaticModelPipeline:
27
34
  def __init__(self, model: StaticModel, head: Pipeline) -> None:
28
35
  """Create a pipeline with a StaticModel encoder."""
29
36
  self.model = model
30
37
  self.head = head
31
- classifier = self.head[-1]
32
- # Check if the classifier is a multilabel classifier.
33
- # NOTE: this doesn't look robust, but it is.
34
- # Different classifiers, such as OVR wrappers, support multilabel output natively, so we
35
- # can just use predict.
36
- self.multilabel = False
37
- if isinstance(classifier, MLPClassifier):
38
- if classifier.out_activation_ == "logistic":
39
- self.multilabel = True
40
-
41
- @property
42
- def classes_(self) -> np.ndarray:
43
- """The classes of the classifier."""
44
- return self.head.classes_
38
+
39
+ last_head = self.head[-1]
40
+ self.classes_: None | np.ndarray = None
41
+ if isinstance(last_head, MLPRegressor):
42
+ self.classifier_type = HeadType.PROJECTOR
43
+ elif isinstance(last_head, MLPClassifier):
44
+ activation = last_head.out_activation_
45
+ self.classifier_type = HeadType.MULTILABEL if activation == "logistic" else HeadType.CLASSIFIER
46
+ self.classes_ = self.head.classes_
47
+ else:
48
+ # Default to classifier: the assumption is the user is unlikely to use multilabel here.
49
+ self.classifier_type = HeadType.CLASSIFIER
45
50
 
46
51
  @classmethod
47
52
  def from_pretrained(
48
53
  cls: type[StaticModelPipeline], path: PathLike, token: str | None = None, trust_remote_code: bool = False
49
54
  ) -> StaticModelPipeline:
50
- """
51
- Load a StaticModel from a local path or huggingface hub path.
55
+ """Load a StaticModel from a local path or huggingface hub path.
52
56
 
53
57
  NOTE: if you load a private model from the huggingface hub, you need to pass a token.
54
58
 
@@ -69,8 +73,7 @@ class StaticModelPipeline:
69
73
  def push_to_hub(
70
74
  self, repo_id: str, subfolder: str | None = None, token: str | None = None, private: bool = False
71
75
  ) -> None:
72
- """
73
- 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.
74
77
 
75
78
  :param repo_id: The id of the repository to push to.
76
79
  :param subfolder: The subfolder to push to.
@@ -117,8 +120,7 @@ class StaticModelPipeline:
117
120
  multiprocessing_threshold: int = 10_000,
118
121
  threshold: float = 0.5,
119
122
  ) -> np.ndarray:
120
- """
121
- Predict the labels of the input.
123
+ """Predict the labels of the input.
122
124
 
123
125
  :param X: The input data to predict. Can be a list of strings or a single string.
124
126
  :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
@@ -138,7 +140,8 @@ class StaticModelPipeline:
138
140
  multiprocessing_threshold=multiprocessing_threshold,
139
141
  )
140
142
 
141
- if self.multilabel:
143
+ if self.classifier_type == HeadType.MULTILABEL:
144
+ assert self.classes_ is not None
142
145
  out_labels = []
143
146
  proba = self.head.predict_proba(encoded)
144
147
  for vector in proba:
@@ -156,8 +159,7 @@ class StaticModelPipeline:
156
159
  use_multiprocessing: bool = True,
157
160
  multiprocessing_threshold: int = 10_000,
158
161
  ) -> np.ndarray:
159
- """
160
- Predict the labels of the input.
162
+ """Predict the labels of the input.
161
163
 
162
164
  :param X: The input data to predict. Can be a list of strings or a single string.
163
165
  :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
@@ -166,7 +168,10 @@ class StaticModelPipeline:
166
168
  :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
167
169
  :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
168
170
  :return: The predicted labels or probabilities.
171
+ :raises ValueError: If the classifier type is projector.
169
172
  """
173
+ if self.classifier_type == HeadType.PROJECTOR:
174
+ raise ValueError("You are using evaluate on a projector model. This is not supported.")
170
175
  encoded = self._encode_and_coerce_to_2d(
171
176
  X,
172
177
  show_progress_bar=show_progress_bar,
@@ -181,8 +186,7 @@ class StaticModelPipeline:
181
186
  def evaluate(
182
187
  self, X: Sequence[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5, output_dict: bool = False
183
188
  ) -> str | dict[str, dict[str, float]]:
184
- """
185
- 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.
186
190
 
187
191
  :param X: The texts to predict on.
188
192
  :param y: The ground truth labels.
@@ -190,7 +194,10 @@ class StaticModelPipeline:
190
194
  :param threshold: The threshold for multilabel classification.
191
195
  :param output_dict: Whether to output the classification report as a dictionary.
192
196
  :return: A classification report.
197
+ :raises ValueError: If the classifier type is projector.
193
198
  """
199
+ if self.classifier_type == HeadType.PROJECTOR:
200
+ raise ValueError("You are using evaluate on a projector model. This is not supported.")
194
201
  predictions = self.predict(X, show_progress_bar=True, batch_size=batch_size, threshold=threshold)
195
202
  report = evaluate_single_or_multi_label(predictions=predictions, y=y, output_dict=output_dict)
196
203
 
@@ -200,8 +207,7 @@ class StaticModelPipeline:
200
207
  def _load_pipeline(
201
208
  folder_or_repo_path: PathLike, token: str | None = None, trust_remote_code: bool = False
202
209
  ) -> tuple[StaticModel, Pipeline]:
203
- """
204
- Load a model and an sklearn pipeline.
210
+ """Load a model and an sklearn pipeline.
205
211
 
206
212
  This assumes the following files are present in the repo:
207
213
  - `pipeline.skops`: The head of the pipeline.
@@ -247,8 +253,7 @@ def _load_pipeline(
247
253
 
248
254
 
249
255
  def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> None:
250
- """
251
- Save a pipeline to a folder.
256
+ """Save a pipeline to a folder.
252
257
 
253
258
  :param pipeline: The pipeline to save.
254
259
  :param folder_path: The path to the folder to save the pipeline to.
@@ -284,8 +289,7 @@ def evaluate_single_or_multi_label(
284
289
  y: list[int] | list[str] | list[list[int]] | list[list[str]],
285
290
  output_dict: bool = False,
286
291
  ) -> str | dict[str, dict[str, float]]:
287
- """
288
- 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.
289
293
 
290
294
  :param predictions: The predictions.
291
295
  :param y: The ground truth labels.