model2vec 0.7.0__tar.gz → 0.8.1__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.7.0 → model2vec-0.8.1}/.github/workflows/ci.yaml +23 -10
  2. model2vec-0.8.1/CITATION.cff +27 -0
  3. {model2vec-0.7.0 → model2vec-0.8.1}/PKG-INFO +18 -14
  4. {model2vec-0.7.0 → model2vec-0.8.1}/README.md +14 -8
  5. model2vec-0.8.1/assets/images/model2vec_logo.png +0 -0
  6. model2vec-0.8.1/assets/images/speed_vs_mteb_plot.png +0 -0
  7. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/distill/distillation.py +53 -50
  8. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/distill/inference.py +3 -4
  9. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/inference/model.py +9 -8
  10. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/model.py +13 -30
  11. model2vec-0.8.1/model2vec/modelcards/__init__.py +3 -0
  12. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/modelcards/classifier_template.md +9 -7
  13. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/modelcards/model_card_template.md +9 -7
  14. model2vec-0.8.1/model2vec/modelcards/modelcards.py +56 -0
  15. model2vec-0.8.1/model2vec/persistence/__init__.py +4 -0
  16. model2vec-0.8.1/model2vec/persistence/datamodels.py +50 -0
  17. model2vec-0.8.1/model2vec/persistence/hf.py +57 -0
  18. model2vec-0.8.1/model2vec/persistence/persistence.py +164 -0
  19. model2vec-0.8.1/model2vec/tokenizer/__init__.py +10 -0
  20. model2vec-0.8.1/model2vec/tokenizer/tokenizer.py +98 -0
  21. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/train/base.py +7 -2
  22. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/train/classifier.py +30 -20
  23. model2vec-0.8.1/model2vec/train/utils.py +21 -0
  24. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/utils.py +2 -2
  25. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/version.py +1 -1
  26. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec.egg-info/PKG-INFO +18 -14
  27. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec.egg-info/SOURCES.txt +11 -6
  28. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec.egg-info/requires.txt +2 -4
  29. {model2vec-0.7.0 → model2vec-0.8.1}/pyproject.toml +2 -4
  30. {model2vec-0.7.0 → model2vec-0.8.1}/results/README.md +22 -26
  31. {model2vec-0.7.0 → model2vec-0.8.1}/results/make_speed_vs_mteb_plot.py +49 -47
  32. {model2vec-0.7.0 → model2vec-0.8.1}/tests/conftest.py +52 -3
  33. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_distillation.py +69 -22
  34. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_model.py +0 -2
  35. model2vec-0.8.1/tests/test_persistence.py +89 -0
  36. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_trainable.py +50 -0
  37. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_utils.py +12 -14
  38. model2vec-0.8.1/uv.lock +3275 -0
  39. model2vec-0.7.0/model2vec/hf_utils.py +0 -277
  40. model2vec-0.7.0/model2vec/tokenizer/__init__.py +0 -12
  41. model2vec-0.7.0/model2vec/tokenizer/datamodels.py +0 -14
  42. model2vec-0.7.0/model2vec/tokenizer/model.py +0 -43
  43. model2vec-0.7.0/model2vec/tokenizer/normalizer.py +0 -42
  44. model2vec-0.7.0/model2vec/tokenizer/pretokenizer.py +0 -57
  45. model2vec-0.7.0/model2vec/tokenizer/tokenizer.py +0 -398
  46. model2vec-0.7.0/tests/test_tokenizer.py +0 -123
  47. model2vec-0.7.0/uv.lock +0 -2931
  48. {model2vec-0.7.0 → model2vec-0.8.1}/.gitignore +0 -0
  49. {model2vec-0.7.0 → model2vec-0.8.1}/.pre-commit-config.yaml +0 -0
  50. {model2vec-0.7.0 → model2vec-0.8.1}/LICENSE +0 -0
  51. {model2vec-0.7.0 → model2vec-0.8.1}/Makefile +0 -0
  52. /model2vec-0.7.0/assets/images/model2vec_logo.png → /model2vec-0.8.1/assets/images/logo_v2.png +0 -0
  53. {model2vec-0.7.0 → model2vec-0.8.1}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  54. {model2vec-0.7.0 → model2vec-0.8.1}/assets/images/training_speed_vs_score.png +0 -0
  55. {model2vec-0.7.0 → model2vec-0.8.1}/assets/images/tutorial_ezlo.png +0 -0
  56. {model2vec-0.7.0 → model2vec-0.8.1}/docs/README.md +0 -0
  57. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/__init__.py +0 -0
  58. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/distill/__init__.py +0 -0
  59. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/distill/utils.py +0 -0
  60. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/inference/README.md +0 -0
  61. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/inference/__init__.py +0 -0
  62. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/py.typed +0 -0
  63. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/quantization.py +0 -0
  64. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/train/README.md +0 -0
  65. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/train/__init__.py +0 -0
  66. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec/vocabulary_quantization.py +0 -0
  67. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec.egg-info/dependency_links.txt +0 -0
  68. {model2vec-0.7.0 → model2vec-0.8.1}/model2vec.egg-info/top_level.txt +0 -0
  69. {model2vec-0.7.0 → model2vec-0.8.1}/scripts/export_to_onnx.py +0 -0
  70. {model2vec-0.7.0 → model2vec-0.8.1}/setup.cfg +0 -0
  71. {model2vec-0.7.0 → model2vec-0.8.1}/tests/__init__.py +0 -0
  72. {model2vec-0.7.0 → model2vec-0.8.1}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  73. {model2vec-0.7.0 → model2vec-0.8.1}/tests/data/test_tokenizer/tokenizer.json +0 -0
  74. {model2vec-0.7.0 → model2vec-0.8.1}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  75. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_inference.py +0 -0
  76. {model2vec-0.7.0 → model2vec-0.8.1}/tests/test_quantization.py +0 -0
  77. {model2vec-0.7.0 → model2vec-0.8.1}/tutorials/README.md +0 -0
  78. {model2vec-0.7.0 → model2vec-0.8.1}/tutorials/recipe_search.ipynb +0 -0
  79. {model2vec-0.7.0 → model2vec-0.8.1}/tutorials/semantic_chunking.ipynb +0 -0
  80. {model2vec-0.7.0 → model2vec-0.8.1}/tutorials/train_classifier.ipynb +0 -0
@@ -1,17 +1,20 @@
1
1
  name: Run tests and upload coverage
2
2
 
3
3
  on:
4
- push
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
5
8
 
6
9
  jobs:
7
10
  test:
8
11
  name: Run tests with pytest
9
12
  runs-on: ${{ matrix.os }}
10
13
  strategy:
11
- matrix:
12
- os: ["ubuntu-latest"]
13
- python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
14
14
  fail-fast: false
15
+ matrix:
16
+ os: ["ubuntu-latest", "windows-latest"]
17
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
15
18
 
16
19
  steps:
17
20
  - uses: actions/checkout@v4
@@ -22,24 +25,34 @@ jobs:
22
25
  python-version: ${{ matrix.python-version }}
23
26
  allow-prereleases: true
24
27
 
25
- - name: Create and activate a virtual environment (Unix)
28
+ - name: Install uv
29
+ uses: astral-sh/setup-uv@v6
30
+
31
+ - name: Create virtual environment
32
+ run: uv venv .venv
33
+
34
+ - name: Add venv to PATH (Linux/macOS)
35
+ if: runner.os != 'Windows'
26
36
  run: |
27
- curl -LsSf https://astral.sh/uv/install.sh | sh
28
- uv venv .venv
29
37
  echo "VIRTUAL_ENV=.venv" >> $GITHUB_ENV
30
38
  echo "$PWD/.venv/bin" >> $GITHUB_PATH
31
39
 
32
- # Install dependencies using uv pip
40
+ - name: Add venv to PATH (Windows)
41
+ if: runner.os == 'Windows'
42
+ shell: pwsh
43
+ run: |
44
+ "VIRTUAL_ENV=.venv" >> $env:GITHUB_ENV
45
+ "$pwd\.venv\Scripts" >> $env:GITHUB_PATH
46
+
33
47
  - name: Install dependencies
34
48
  run: make install-no-pre-commit
35
49
 
36
- # Run tests with coverage
37
50
  - name: Run tests under coverage
51
+ shell: bash
38
52
  run: |
39
53
  coverage run --source=model2vec -m pytest
40
54
  coverage report
41
55
 
42
- # Upload results to Codecov
43
56
  - name: Upload results to Codecov
44
57
  uses: codecov/codecov-action@v4
45
58
  with:
@@ -0,0 +1,27 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use Model2Vec in your research, please cite it as below."
3
+ title: "Model2Vec: Fast State-of-the-Art Static Embeddings"
4
+ authors:
5
+ - family-names: "Tulkens"
6
+ given-names: "Stephan"
7
+ - family-names: "van Dongen"
8
+ given-names: "Thomas"
9
+ doi: 10.5281/zenodo.17270888
10
+ license: MIT
11
+ url: "https://github.com/MinishLab/model2vec"
12
+ repository-code: "https://github.com/MinishLab/model2vec"
13
+ date-released: "2024-09-20"
14
+
15
+ preferred-citation:
16
+ type: software
17
+ title: "Model2Vec: Fast State-of-the-Art Static Embeddings"
18
+ authors:
19
+ - family-names: "Tulkens"
20
+ given-names: "Stephan"
21
+ - family-names: "van Dongen"
22
+ given-names: "Thomas"
23
+ year: 2024
24
+ publisher: Zenodo
25
+ doi: 10.5281/zenodo.17270888
26
+ url: "https://github.com/MinishLab/model2vec"
27
+ license: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: model2vec
3
- Version: 0.7.0
3
+ Version: 0.8.1
4
4
  Summary: Fast State-of-the-Art Static Embeddings
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
@@ -35,13 +35,12 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
35
35
  Classifier: Topic :: Software Development :: Libraries
36
36
  Classifier: License :: OSI Approved :: MIT License
37
37
  Classifier: Programming Language :: Python :: 3 :: Only
38
- Classifier: Programming Language :: Python :: 3.9
39
38
  Classifier: Programming Language :: Python :: 3.10
40
39
  Classifier: Programming Language :: Python :: 3.11
41
40
  Classifier: Programming Language :: Python :: 3.12
42
41
  Classifier: Programming Language :: Python :: 3.13
43
42
  Classifier: Natural Language :: English
44
- Requires-Python: >=3.9
43
+ Requires-Python: >=3.10
45
44
  Description-Content-Type: text/markdown
46
45
  Requires-Dist: jinja2
47
46
  Requires-Dist: joblib
@@ -61,8 +60,9 @@ Requires-Dist: pytest-cov; extra == "dev"
61
60
  Requires-Dist: ruff; extra == "dev"
62
61
  Provides-Extra: distill
63
62
  Requires-Dist: torch; extra == "distill"
64
- Requires-Dist: transformers; extra == "distill"
63
+ Requires-Dist: transformers<5.4.0; extra == "distill"
65
64
  Requires-Dist: scikit-learn; extra == "distill"
65
+ Requires-Dist: skeletoken>=0.3.2; extra == "distill"
66
66
  Provides-Extra: onnx
67
67
  Requires-Dist: onnx; extra == "onnx"
68
68
  Requires-Dist: torch; extra == "onnx"
@@ -74,8 +74,6 @@ Requires-Dist: skops; extra == "train"
74
74
  Provides-Extra: inference
75
75
  Requires-Dist: scikit-learn; extra == "inference"
76
76
  Requires-Dist: skops; extra == "inference"
77
- Provides-Extra: tokenizer
78
- Requires-Dist: transformers; extra == "tokenizer"
79
77
  Provides-Extra: quantization
80
78
  Requires-Dist: scikit-learn; extra == "quantization"
81
79
 
@@ -122,7 +120,7 @@ Requires-Dist: scikit-learn; extra == "quantization"
122
120
 
123
121
 
124
122
 
125
- Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
123
+ Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
126
124
 
127
125
  <div align="center">
128
126
  <h3>
@@ -143,8 +141,8 @@ You can start using Model2Vec by loading one of our [flagship models from the Hu
143
141
  ```python
144
142
  from model2vec import StaticModel
145
143
 
146
- # Load a model from the HuggingFace hub (in this case the potion-base-8M model)
147
- model = StaticModel.from_pretrained("minishlab/potion-base-8M")
144
+ # Load a model from the HuggingFace hub (in this case the potion-base-32M model)
145
+ model = StaticModel.from_pretrained("minishlab/potion-base-32M")
148
146
 
149
147
  # Make embeddings
150
148
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
@@ -255,6 +253,8 @@ We provide a number of models that can be used out of the box. These models are
255
253
 
256
254
  We have performed extensive experiments to evaluate the performance of Model2Vec models. The results are documented in the [results](results/README.md) folder. The results are presented in the following sections:
257
255
  - [MTEB Results](results/README.md#mteb-results)
256
+ - [MMTEB Results](results/README.md#mmteb-results)
257
+ - [Retrieval Results](results/README.md#retrieval-results)
258
258
  - [Training Results](results/README.md#training-results)
259
259
  - [Ablations](results/README.md#ablations)
260
260
 
@@ -265,11 +265,15 @@ MIT
265
265
  ## Citing
266
266
 
267
267
  If you use Model2Vec in your research, please cite the following:
268
+
268
269
  ```bibtex
269
- @article{minishlab2024model2vec,
270
- author = {Tulkens, Stephan and {van Dongen}, Thomas},
271
- title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
272
- year = {2024},
273
- url = {https://github.com/MinishLab/model2vec}
270
+ @software{minishlab2024model2vec,
271
+ author = {Stephan Tulkens and {van Dongen}, Thomas},
272
+ title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
273
+ year = {2024},
274
+ publisher = {Zenodo},
275
+ doi = {10.5281/zenodo.17270888},
276
+ url = {https://github.com/MinishLab/model2vec},
277
+ license = {MIT}
274
278
  }
275
279
  ```
@@ -41,7 +41,7 @@
41
41
 
42
42
 
43
43
 
44
- Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
44
+ Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works.
45
45
 
46
46
  <div align="center">
47
47
  <h3>
@@ -62,8 +62,8 @@ You can start using Model2Vec by loading one of our [flagship models from the Hu
62
62
  ```python
63
63
  from model2vec import StaticModel
64
64
 
65
- # Load a model from the HuggingFace hub (in this case the potion-base-8M model)
66
- model = StaticModel.from_pretrained("minishlab/potion-base-8M")
65
+ # Load a model from the HuggingFace hub (in this case the potion-base-32M model)
66
+ model = StaticModel.from_pretrained("minishlab/potion-base-32M")
67
67
 
68
68
  # Make embeddings
69
69
  embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])
@@ -174,6 +174,8 @@ We provide a number of models that can be used out of the box. These models are
174
174
 
175
175
  We have performed extensive experiments to evaluate the performance of Model2Vec models. The results are documented in the [results](results/README.md) folder. The results are presented in the following sections:
176
176
  - [MTEB Results](results/README.md#mteb-results)
177
+ - [MMTEB Results](results/README.md#mmteb-results)
178
+ - [Retrieval Results](results/README.md#retrieval-results)
177
179
  - [Training Results](results/README.md#training-results)
178
180
  - [Ablations](results/README.md#ablations)
179
181
 
@@ -184,11 +186,15 @@ MIT
184
186
  ## Citing
185
187
 
186
188
  If you use Model2Vec in your research, please cite the following:
189
+
187
190
  ```bibtex
188
- @article{minishlab2024model2vec,
189
- author = {Tulkens, Stephan and {van Dongen}, Thomas},
190
- title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
191
- year = {2024},
192
- url = {https://github.com/MinishLab/model2vec}
191
+ @software{minishlab2024model2vec,
192
+ author = {Stephan Tulkens and {van Dongen}, Thomas},
193
+ title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
194
+ year = {2024},
195
+ publisher = {Zenodo},
196
+ doi = {10.5281/zenodo.17270888},
197
+ url = {https://github.com/MinishLab/model2vec},
198
+ license = {MIT}
193
199
  }
194
200
  ```
@@ -3,10 +3,12 @@ from __future__ import annotations
3
3
  import logging
4
4
  import os
5
5
  import re
6
- from typing import Optional, cast
6
+ from typing import cast
7
7
 
8
8
  import numpy as np
9
9
  from huggingface_hub.hf_api import model_info
10
+ from skeletoken import TokenizerModel
11
+ from skeletoken.external.transformers import reshape_embeddings
10
12
  from transformers import AutoModel, AutoTokenizer
11
13
  from transformers.modeling_utils import PreTrainedModel
12
14
  from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
@@ -15,7 +17,7 @@ from model2vec.distill.inference import PCADimType, PoolingMode, create_embeddin
15
17
  from model2vec.distill.utils import select_optimal_device
16
18
  from model2vec.model import StaticModel
17
19
  from model2vec.quantization import DType, quantize_embeddings
18
- from model2vec.tokenizer import clean_and_create_vocabulary, replace_vocabulary, turn_tokens_into_ids
20
+ from model2vec.tokenizer import clean_and_create_vocabulary, turn_tokens_into_ids
19
21
  from model2vec.vocabulary_quantization import quantize_vocabulary
20
22
 
21
23
  logger = logging.getLogger(__name__)
@@ -37,7 +39,8 @@ def distill_from_model(
37
39
  Distill a staticmodel from a sentence transformer.
38
40
 
39
41
  This function creates a set of embeddings from a sentence transformer. It does this by doing either
40
- a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
42
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
43
+ vocabulary.
41
44
 
42
45
  If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
43
46
  If you don't pass a vocabulary, we use the model's tokenizer directly.
@@ -51,10 +54,13 @@ def distill_from_model(
51
54
  If this is 'auto', we don't reduce dimensionality, but still apply PCA.
52
55
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
53
56
  Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
54
- :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
55
- If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled into a valid regex, we also throw an error.
57
+ :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
58
+ this regex pattern will be removed from the vocabulary.
59
+ If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled
60
+ into a valid regex, we also throw an error.
56
61
  :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
57
- :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no quantization is performed.
62
+ :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
63
+ quantization is performed.
58
64
  :param pooling: The pooling mode to use for creating embeddings. Can be one of:
59
65
  'mean' (default): mean over all tokens. Robust and works well in most cases.
60
66
  'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
@@ -65,59 +71,51 @@ def distill_from_model(
65
71
 
66
72
  """
67
73
  quantize_to = DType(quantize_to)
68
- backend_tokenizer = tokenizer.backend_tokenizer
69
74
  sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)
70
75
 
71
76
  if vocabulary is None:
72
77
  vocabulary = []
73
78
 
74
79
  device = select_optimal_device(device)
80
+ original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)
81
+ original_tokenizer_model = original_tokenizer_model.prune_added_tokens()
75
82
 
76
- n_tokens_before = len(vocabulary)
77
83
  # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.
78
- all_tokens, backend_tokenizer = clean_and_create_vocabulary(
79
- tokenizer, vocabulary, token_remove_regex=token_remove_regex
80
- )
81
- n_tokens_after = len([token for token in all_tokens if not token.is_internal])
82
- if n_tokens_before:
83
- logger.info(
84
- f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
85
- )
86
-
84
+ # Copy the original tokenizer model.
85
+ tokenizer_model = original_tokenizer_model.deep_copy()
86
+ if tokenizer_model.adds_prefix_space is not None:
87
+ tokenizer_model.adds_prefix_space = True
88
+
89
+ # Create the vocabulary in the new tokenizer.
90
+ 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
+
98
+ # All tokens in a single list.
99
+ all_tokens = tokenizer_model.sorted_vocabulary
87
100
  if not all_tokens:
88
101
  raise ValueError("The vocabulary is empty after preprocessing. Please check your token_remove_pattern.")
89
102
 
90
- unk_token = cast(Optional[str], tokenizer.special_tokens_map.get("unk_token"))
91
- pad_token = cast(Optional[str], tokenizer.special_tokens_map.get("pad_token"))
92
-
93
- # Weird if to satsify mypy
94
- if pad_token is None:
95
- if unk_token is not None:
96
- pad_token = unk_token
97
- logger.warning(
98
- "The pad token is not set. Setting it to the unk token. This is a workaround for models that don't have a pad token."
99
- )
100
- else:
101
- pad_token = unk_token or all_tokens[0].form
102
- logger.warning(
103
- "The pad token is not set. Setting it to the first token in the vocabulary. This is a workaround for models that don't have a pad token."
104
- )
105
-
106
- # Replace the vocabulary in the tokenizer with the new vocabulary.
107
- backend_tokenizer = replace_vocabulary(backend_tokenizer, all_tokens, unk_token=unk_token, pad_token=pad_token)
108
- logger.info(f"Creating embeddings for {len(all_tokens)} tokens")
109
- # Convert tokens to IDs
110
- token_ids = turn_tokens_into_ids(all_tokens, tokenizer, unk_token)
111
-
112
- # Create the embeddings
103
+ # Turn all _new_ tokens into ids using the original tokenizer
104
+ token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)
105
+
106
+ # Reshape the transformer
107
+ model = reshape_embeddings(model, original_tokenizer_model)
108
+
109
+ # Create the embeddings using the ids from the original tokenizer.
113
110
  embeddings = create_embeddings(
114
111
  tokenized=token_ids,
115
112
  model=model,
116
113
  device=device,
117
- pad_token_id=tokenizer.get_vocab()[pad_token],
114
+ pad_token_id=original_tokenizer_model.pad_token_id or 0,
118
115
  pooling=pooling,
119
116
  )
120
117
 
118
+ # Maybe apply quantization
121
119
  if vocabulary_quantization is not None:
122
120
  _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)
123
121
  embeddings, token_mapping, weights = quantize_vocabulary(
@@ -163,7 +161,7 @@ def distill_from_model(
163
161
  vectors=embeddings,
164
162
  weights=weights,
165
163
  token_mapping=token_mapping,
166
- tokenizer=backend_tokenizer,
164
+ tokenizer=tokenizer_model.to_tokenizer(),
167
165
  config=config,
168
166
  base_model_name=model_name,
169
167
  language=language,
@@ -174,13 +172,14 @@ def distill_from_model(
174
172
  def _validate_parameters(
175
173
  sif_coefficient: float | None,
176
174
  token_remove_pattern: str | None,
177
- ) -> tuple[float | None, re.Pattern | None]:
175
+ ) -> tuple[float | None, re.Pattern[str] | None]:
178
176
  """
179
177
  Validate the parameters passed to the distillation function.
180
178
 
181
179
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
182
180
  Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
183
- :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
181
+ :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
182
+ this regex pattern will be removed from the vocabulary.
184
183
  :return: The SIF coefficient to use.
185
184
  :raises: ValueError if the regex can't be compiled.
186
185
 
@@ -189,12 +188,12 @@ def _validate_parameters(
189
188
  if not 0 < sif_coefficient < 1.0:
190
189
  raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
191
190
 
192
- token_remove_regex: re.Pattern | None = None
191
+ token_remove_regex: re.Pattern[str] | None = None
193
192
  if token_remove_pattern is not None:
194
193
  try:
195
194
  token_remove_regex = re.compile(token_remove_pattern)
196
195
  except re.error as e:
197
- raise ValueError(f"Couldn't compile the regex pattern: {e}")
196
+ raise ValueError(f"Couldn't compile the regex pattern: {e}") from e
198
197
 
199
198
  return sif_coefficient, token_remove_regex
200
199
 
@@ -215,7 +214,8 @@ def distill(
215
214
  Distill a staticmodel from a sentence transformer.
216
215
 
217
216
  This function creates a set of embeddings from a sentence transformer. It does this by doing either
218
- a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
217
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
218
+ vocabulary.
219
219
 
220
220
  If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
221
221
  If you don't pass a vocabulary, we use the model's tokenizer directly.
@@ -228,10 +228,13 @@ def distill(
228
228
  If this is 'auto', we don't reduce dimenionality, but still apply PCA.
229
229
  :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
230
230
  Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
231
- :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
232
- :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `transformers`. If this is True, we will load all components.
231
+ :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
232
+ this regex pattern will be removed from the vocabulary.
233
+ :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming
234
+ from `transformers`. If this is True, we will load all components.
233
235
  :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
234
- :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no quantization is performed.
236
+ :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no
237
+ quantization is performed.
235
238
  :param pooling: The pooling mode to use for creating embeddings. Can be one of:
236
239
  'mean' (default): mean over all tokens. Robust and works well in most cases.
237
240
  'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.
@@ -1,11 +1,10 @@
1
- # -*- coding: utf-8 -*-
2
1
  from __future__ import annotations
3
2
 
4
3
  import inspect
5
4
  import logging
6
5
  from enum import Enum
7
6
  from pathlib import Path
8
- from typing import Literal, Union
7
+ from typing import Literal
9
8
 
10
9
  import numpy as np
11
10
  import torch
@@ -17,8 +16,8 @@ from transformers.modeling_utils import PreTrainedModel
17
16
 
18
17
  logger = logging.getLogger(__name__)
19
18
 
20
- PathLike = Union[Path, str]
21
- PCADimType = Union[int, None, float, Literal["auto"]]
19
+ PathLike = Path | str
20
+ PCADimType = int | None | float | Literal["auto"]
22
21
 
23
22
  _DEFAULT_BATCH_SIZE = 256
24
23
 
@@ -1,9 +1,10 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
+ from collections.abc import Sequence
4
5
  from pathlib import Path
5
6
  from tempfile import TemporaryDirectory
6
- from typing import Sequence, TypeVar, Union, cast
7
+ from typing import TypeVar, cast
7
8
 
8
9
  import huggingface_hub
9
10
  import numpy as np
@@ -13,8 +14,8 @@ from sklearn.neural_network import MLPClassifier
13
14
  from sklearn.pipeline import Pipeline
14
15
  from sklearn.preprocessing import MultiLabelBinarizer
15
16
 
16
- from model2vec.hf_utils import _create_model_card
17
17
  from model2vec.model import PathLike, StaticModel
18
+ from model2vec.modelcards import create_model_card
18
19
 
19
20
  _DEFAULT_TRUST_PATTERN = re.compile(r"sklearn\..+")
20
21
  _DEFAULT_MODEL_FILENAME = "pipeline.skops"
@@ -76,7 +77,7 @@ class StaticModelPipeline:
76
77
  :param token: The token to use to push to the hub.
77
78
  :param private: Whether the repository should be private.
78
79
  """
79
- from model2vec.hf_utils import push_folder_to_hub
80
+ from model2vec.persistence import push_folder_to_hub
80
81
 
81
82
  with TemporaryDirectory() as temp_dir:
82
83
  save_pipeline(self, temp_dir)
@@ -265,11 +266,11 @@ def save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> Non
265
266
  name = base_model_name
266
267
  else:
267
268
  name = "unknown"
268
- _create_model_card(
269
+ create_model_card(
269
270
  folder_path,
270
271
  base_model_name=name,
271
272
  language=pipeline.model.language,
272
- template_path="modelcards/classifier_template.md",
273
+ template_path="classifier_template.md",
273
274
  )
274
275
 
275
276
 
@@ -293,14 +294,14 @@ def evaluate_single_or_multi_label(
293
294
  """
294
295
  if _is_multi_label_shaped(y):
295
296
  # Cast because the type checker doesn't understand that y is a list of lists.
296
- y = cast(Union[list[list[str]], list[list[int]]], y)
297
+ y = cast(list[list[str]] | list[list[int]], y)
297
298
  classes = sorted(set([label for labels in y for label in labels]))
298
299
  mlb = MultiLabelBinarizer(classes=classes)
299
300
  y_transformed = mlb.fit_transform(y)
300
301
  predictions_transformed = mlb.transform(predictions)
301
302
  else:
302
303
  if all(isinstance(label, (str, int)) for label in y):
303
- y = cast(Union[list[str], list[int]], y)
304
+ y = cast(list[str] | list[int], y)
304
305
  classes = sorted(set(y))
305
306
  y_transformed = np.array(y)
306
307
  predictions_transformed = np.array(predictions)
@@ -309,7 +310,7 @@ def evaluate_single_or_multi_label(
309
310
  y_transformed,
310
311
  predictions_transformed,
311
312
  output_dict=output_dict,
312
- zero_division=0,
313
+ zero_division=0, # type: ignore # incorrect type in sklearn.
313
314
  )
314
315
 
315
316
  return report
@@ -2,10 +2,12 @@ from __future__ import annotations
2
2
 
3
3
  import math
4
4
  import os
5
+ import warnings
6
+ from collections.abc import Iterator, Sequence
5
7
  from logging import getLogger
6
8
  from pathlib import Path
7
9
  from tempfile import TemporaryDirectory
8
- from typing import Any, Iterator, Sequence, Union, overload
10
+ from typing import Any, overload
9
11
 
10
12
  import numpy as np
11
13
  from joblib import delayed
@@ -15,7 +17,7 @@ from tqdm import tqdm
15
17
  from model2vec.quantization import DType, quantize_and_reduce_dim
16
18
  from model2vec.utils import ProgressParallel
17
19
 
18
- PathLike = Union[Path, str]
20
+ PathLike = Path | str
19
21
 
20
22
  logger = getLogger(__name__)
21
23
 
@@ -130,7 +132,7 @@ class StaticModel:
130
132
  :param model_name: The model name to use in the Model Card.
131
133
  :param subfolder: The subfolder to save to.
132
134
  """
133
- from model2vec.hf_utils import save_pretrained
135
+ from model2vec.persistence import save_pretrained
134
136
 
135
137
  save_pretrained(
136
138
  folder_path=Path(path),
@@ -213,7 +215,6 @@ class StaticModel:
213
215
  vocabulary_quantization=vocabulary_quantization,
214
216
  quantize_to=quantize_to,
215
217
  dimensionality=dimensionality,
216
- from_sentence_transformers=False,
217
218
  normalize=normalize,
218
219
  subfolder=subfolder,
219
220
  force_download=force_download,
@@ -230,24 +231,12 @@ class StaticModel:
230
231
  vocabulary_quantization: int | None = None,
231
232
  force_download: bool = True,
232
233
  ) -> StaticModel:
233
- """
234
- Load a StaticModel trained with sentence transformers from a local path or huggingface hub path.
235
-
236
- NOTE: if you load a private model from the huggingface hub, you need to pass a token.
237
-
238
- :param path: The path to load your static model from.
239
- :param token: The huggingface token to use.
240
- :param normalize: Whether to normalize the embeddings.
241
- :param quantize_to: The dtype to quantize the model to. If None, no quantization is done.
242
- If a string is passed, it is converted to a DType.
243
- :param dimensionality: The dimensionality of the model. If this is None, use the dimensionality of the model.
244
- This is useful if you want to load a model with a lower dimensionality.
245
- Note that this only applies if you have trained your model using mrl or PCA.
246
- :param vocabulary_quantization: The number of clusters to use for vocabulary quantization.
247
- :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not
248
- already present in the cache.
249
- :return: A StaticModel.
250
- """
234
+ """Deprecated: use from_pretrained."""
235
+ warnings.warn(
236
+ "StaticModel.from_sentence_transformers() is deprecated; use from_pretrained() instead.",
237
+ DeprecationWarning,
238
+ stacklevel=2,
239
+ )
251
240
  return _loading_helper(
252
241
  cls=cls,
253
242
  path=path,
@@ -255,7 +244,6 @@ class StaticModel:
255
244
  vocabulary_quantization=vocabulary_quantization,
256
245
  quantize_to=quantize_to,
257
246
  dimensionality=dimensionality,
258
- from_sentence_transformers=True,
259
247
  normalize=normalize,
260
248
  subfolder=None,
261
249
  force_download=force_download,
@@ -480,7 +468,7 @@ class StaticModel:
480
468
  :param token: The huggingface token to use.
481
469
  :param subfolder: The subfolder to push to.
482
470
  """
483
- from model2vec.hf_utils import push_folder_to_hub
471
+ from model2vec.persistence import push_folder_to_hub
484
472
 
485
473
  with TemporaryDirectory() as temp_dir:
486
474
  self.save_pretrained(temp_dir, model_name=repo_id)
@@ -545,21 +533,16 @@ def _loading_helper(
545
533
  vocabulary_quantization: int | None,
546
534
  quantize_to: str | DType | None,
547
535
  dimensionality: int | None,
548
- from_sentence_transformers: bool,
549
536
  normalize: bool | None,
550
537
  subfolder: str | None,
551
538
  force_download: bool,
552
539
  ) -> StaticModel:
553
540
  """Helper function to load a model from a directory."""
554
- from model2vec.hf_utils import load_pretrained
555
-
556
- if from_sentence_transformers and subfolder is not None:
557
- raise ValueError("Subfolder is not supported for sentence transformers models.")
541
+ from model2vec.persistence import load_pretrained
558
542
 
559
543
  embeddings, tokenizer, config, metadata, weights, mapping = load_pretrained(
560
544
  folder_or_repo_path=path,
561
545
  token=token,
562
- from_sentence_transformers=from_sentence_transformers,
563
546
  subfolder=subfolder,
564
547
  force_download=force_download,
565
548
  )
@@ -0,0 +1,3 @@
1
+ from model2vec.modelcards.modelcards import create_model_card, get_metadata_from_readme
2
+
3
+ __all__ = ["create_model_card", "get_metadata_from_readme"]