model2vec 0.5.0__tar.gz → 0.6.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.
Files changed (83) hide show
  1. {model2vec-0.5.0 → model2vec-0.6.0}/PKG-INFO +18 -16
  2. {model2vec-0.5.0 → model2vec-0.6.0}/README.md +14 -14
  3. model2vec-0.6.0/assets/images/model2vec_logo.png +0 -0
  4. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/distill/distillation.py +50 -136
  5. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/distill/inference.py +59 -50
  6. model2vec-0.6.0/model2vec/distill/utils.py +28 -0
  7. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/hf_utils.py +4 -3
  8. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/inference/model.py +4 -1
  9. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/model.py +1 -1
  10. model2vec-0.6.0/model2vec/tokenizer/__init__.py +12 -0
  11. model2vec-0.6.0/model2vec/tokenizer/datamodels.py +14 -0
  12. model2vec-0.6.0/model2vec/tokenizer/model.py +43 -0
  13. model2vec-0.6.0/model2vec/tokenizer/normalizer.py +42 -0
  14. model2vec-0.6.0/model2vec/tokenizer/pretokenizer.py +57 -0
  15. model2vec-0.6.0/model2vec/tokenizer/tokenizer.py +395 -0
  16. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/train/classifier.py +26 -5
  17. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/version.py +1 -1
  18. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec.egg-info/PKG-INFO +18 -16
  19. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec.egg-info/SOURCES.txt +8 -1
  20. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec.egg-info/requires.txt +4 -1
  21. {model2vec-0.5.0 → model2vec-0.6.0}/pyproject.toml +2 -1
  22. {model2vec-0.5.0 → model2vec-0.6.0}/results/README.md +31 -1
  23. {model2vec-0.5.0 → model2vec-0.6.0}/tests/conftest.py +11 -7
  24. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_distillation.py +28 -35
  25. model2vec-0.6.0/tests/test_tokenizer.py +123 -0
  26. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_trainable.py +45 -0
  27. {model2vec-0.5.0 → model2vec-0.6.0}/tutorials/README.md +1 -1
  28. model2vec-0.6.0/uv.lock +2553 -0
  29. model2vec-0.5.0/model2vec/distill/tokenizer.py +0 -197
  30. model2vec-0.5.0/model2vec/distill/utils.py +0 -58
  31. model2vec-0.5.0/uv.lock +0 -2360
  32. {model2vec-0.5.0 → model2vec-0.6.0}/.github/workflows/ci.yaml +0 -0
  33. {model2vec-0.5.0 → model2vec-0.6.0}/.gitignore +0 -0
  34. {model2vec-0.5.0 → model2vec-0.6.0}/.pre-commit-config.yaml +0 -0
  35. {model2vec-0.5.0 → model2vec-0.6.0}/LICENSE +0 -0
  36. {model2vec-0.5.0 → model2vec-0.6.0}/Makefile +0 -0
  37. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/logo.png +0 -0
  38. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/logo_v2.png +0 -0
  39. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/model2vec_model_diagram.png +0 -0
  40. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
  41. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
  42. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  43. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_accuracy.png +0 -0
  44. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v2.png +0 -0
  45. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v3.png +0 -0
  46. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v4.png +0 -0
  47. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score.png +0 -0
  48. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score_v2.png +0 -0
  49. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  50. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/training_speed_vs_score.png +0 -0
  51. {model2vec-0.5.0 → model2vec-0.6.0}/assets/images/tutorial_ezlo.png +0 -0
  52. {model2vec-0.5.0 → model2vec-0.6.0}/docs/README.md +0 -0
  53. {model2vec-0.5.0 → model2vec-0.6.0}/docs/integrations.md +0 -0
  54. {model2vec-0.5.0 → model2vec-0.6.0}/docs/usage.md +0 -0
  55. {model2vec-0.5.0 → model2vec-0.6.0}/docs/what_is_model2vec.md +0 -0
  56. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/__init__.py +0 -0
  57. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/distill/__init__.py +0 -0
  58. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/inference/README.md +0 -0
  59. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/inference/__init__.py +0 -0
  60. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/modelcards/classifier_template.md +0 -0
  61. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/modelcards/model_card_template.md +0 -0
  62. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/py.typed +0 -0
  63. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/quantization.py +0 -0
  64. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/train/README.md +0 -0
  65. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/train/__init__.py +0 -0
  66. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/train/base.py +0 -0
  67. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec/utils.py +0 -0
  68. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec.egg-info/dependency_links.txt +0 -0
  69. {model2vec-0.5.0 → model2vec-0.6.0}/model2vec.egg-info/top_level.txt +0 -0
  70. {model2vec-0.5.0 → model2vec-0.6.0}/results/make_speed_vs_mteb_plot.py +0 -0
  71. {model2vec-0.5.0 → model2vec-0.6.0}/scripts/export_to_onnx.py +0 -0
  72. {model2vec-0.5.0 → model2vec-0.6.0}/setup.cfg +0 -0
  73. {model2vec-0.5.0 → model2vec-0.6.0}/tests/__init__.py +0 -0
  74. {model2vec-0.5.0 → model2vec-0.6.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  75. {model2vec-0.5.0 → model2vec-0.6.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
  76. {model2vec-0.5.0 → model2vec-0.6.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  77. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_inference.py +0 -0
  78. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_model.py +0 -0
  79. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_quantization.py +0 -0
  80. {model2vec-0.5.0 → model2vec-0.6.0}/tests/test_utils.py +0 -0
  81. {model2vec-0.5.0 → model2vec-0.6.0}/tutorials/recipe_search.ipynb +0 -0
  82. {model2vec-0.5.0 → model2vec-0.6.0}/tutorials/semantic_chunking.ipynb +0 -0
  83. {model2vec-0.5.0 → model2vec-0.6.0}/tutorials/train_classifier.ipynb +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: model2vec
3
- Version: 0.5.0
3
+ Version: 0.6.0
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
@@ -61,7 +61,7 @@ Requires-Dist: pytest-cov; extra == "dev"
61
61
  Requires-Dist: ruff; extra == "dev"
62
62
  Provides-Extra: distill
63
63
  Requires-Dist: torch; extra == "distill"
64
- Requires-Dist: transformers; extra == "distill"
64
+ Requires-Dist: transformers<=4.52.1; extra == "distill"
65
65
  Requires-Dist: scikit-learn; extra == "distill"
66
66
  Provides-Extra: onnx
67
67
  Requires-Dist: onnx; extra == "onnx"
@@ -74,19 +74,17 @@ 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"
77
79
  Dynamic: license-file
78
80
 
79
81
 
80
- <div align="center">
81
- <picture>
82
- <img width="35%" alt="Model2Vec logo" src="assets/images/logo_v2.png">
83
- </picture>
84
- </a>
85
- </div>
82
+ <h2 align="center">
83
+ <img width="35%" alt="Model2Vec logo" src="assets/images/model2vec_logo.png"><br/>
84
+ Fast State-of-the-Art Static Embeddings
85
+ </h2>
86
+
86
87
 
87
- <div align="center">
88
- <h2>Fast State-of-the-Art Static Embeddings</h2>
89
- </div>
90
88
 
91
89
  <div align="center">
92
90
  <h2>
@@ -201,11 +199,13 @@ For advanced usage, please refer to our [usage documentation](https://github.com
201
199
 
202
200
  ## Updates & Announcements
203
201
 
204
- - **01/05/2024**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
202
+ - **23/05/2025**: We released [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M), a multilingual model trained on 101 languages. It is the best performing static embedding model for multilingual tasks, and is capable of generating embeddings for any text in any language. The results can be found in our [results](results/README.md#mmteb-results-multilingual) section.
205
203
 
206
- - **12/02/2024**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
204
+ - **01/05/2025**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
207
205
 
208
- - **30/01/2024**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
206
+ - **12/02/2025**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
207
+
208
+ - **30/01/2025**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
209
209
 
210
210
  - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
211
211
 
@@ -246,11 +246,13 @@ We provide a number of models that can be used out of the box. These models are
246
246
  | Model | Language | Sentence Transformer | Params | Task |
247
247
  |-----------------------------------------------------------------------|------------|-----------------------------------------------------------------|---------|-----------|
248
248
  | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | General |
249
+ | [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M) | Multilingual | [bge-m3](https://huggingface.co/BAAI/bge-m3) | 128M | General |
250
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | Retrieval |
249
251
  | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M | General |
250
252
  | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 3.7M | General |
251
253
  | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 1.8M | General |
252
- | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | Retrieval |
253
- | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M | General |
254
+
255
+
254
256
 
255
257
 
256
258
  ## Results
@@ -1,14 +1,10 @@
1
1
 
2
- <div align="center">
3
- <picture>
4
- <img width="35%" alt="Model2Vec logo" src="assets/images/logo_v2.png">
5
- </picture>
6
- </a>
7
- </div>
2
+ <h2 align="center">
3
+ <img width="35%" alt="Model2Vec logo" src="assets/images/model2vec_logo.png"><br/>
4
+ Fast State-of-the-Art Static Embeddings
5
+ </h2>
6
+
8
7
 
9
- <div align="center">
10
- <h2>Fast State-of-the-Art Static Embeddings</h2>
11
- </div>
12
8
 
13
9
  <div align="center">
14
10
  <h2>
@@ -123,11 +119,13 @@ For advanced usage, please refer to our [usage documentation](https://github.com
123
119
 
124
120
  ## Updates & Announcements
125
121
 
126
- - **01/05/2024**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
122
+ - **23/05/2025**: We released [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M), a multilingual model trained on 101 languages. It is the best performing static embedding model for multilingual tasks, and is capable of generating embeddings for any text in any language. The results can be found in our [results](results/README.md#mmteb-results-multilingual) section.
127
123
 
128
- - **12/02/2024**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
124
+ - **01/05/2025**: We released backend support for `BPE` and `Unigram` tokenizers, along with quantization and dimensionality reduction. New Model2Vec models are now 50% of the original models, and can be quantized to int8 to be 25% of the size, without loss of performance.
129
125
 
130
- - **30/01/2024**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
126
+ - **12/02/2025**: We released **Model2Vec training**, allowing you to fine-tune your own classification models on top of Model2Vec models. Find out more in our [training documentation](https://github.com/MinishLab/model2vec/blob/main/model2vec/train/README.md) and [results](results/README.md#training-results).
127
+
128
+ - **30/01/2025**: We released two new models: [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) and [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M). [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is our most performant model to date, using a larger vocabulary and higher dimensions. [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) is a finetune of [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) that is optimized for retrieval tasks, and is the best performing static retrieval model currently available.
131
129
 
132
130
  - **30/10/2024**: We released three new models: [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M), [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M), and [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M). These models are trained using [Tokenlearn](https://github.com/MinishLab/tokenlearn). Find out more in our [blog post](https://minishlab.github.io/tokenlearn_blogpost/). NOTE: for users of any of our old English M2V models, we recommend switching to these new models as they [perform better on all tasks](https://github.com/MinishLab/model2vec/tree/main/results).
133
131
 
@@ -168,11 +166,13 @@ We provide a number of models that can be used out of the box. These models are
168
166
  | Model | Language | Sentence Transformer | Params | Task |
169
167
  |-----------------------------------------------------------------------|------------|-----------------------------------------------------------------|---------|-----------|
170
168
  | [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | General |
169
+ | [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M) | Multilingual | [bge-m3](https://huggingface.co/BAAI/bge-m3) | 128M | General |
170
+ | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | Retrieval |
171
171
  | [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 7.5M | General |
172
172
  | [potion-base-4M](https://huggingface.co/minishlab/potion-base-4M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 3.7M | General |
173
173
  | [potion-base-2M](https://huggingface.co/minishlab/potion-base-2M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 1.8M | General |
174
- | [potion-retrieval-32M](https://huggingface.co/minishlab/potion-retrieval-32M) | English | [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 32.3M | Retrieval |
175
- | [M2V_multilingual_output](https://huggingface.co/minishlab/M2V_multilingual_output) | Multilingual | [LaBSE](https://huggingface.co/sentence-transformers/LaBSE) | 471M | General |
174
+
175
+
176
176
 
177
177
 
178
178
  ## Results
@@ -3,34 +3,21 @@ from __future__ import annotations
3
3
  import logging
4
4
  import os
5
5
  import re
6
- from typing import Literal, Union
6
+ from typing import Optional, cast
7
7
 
8
8
  import numpy as np
9
9
  from huggingface_hub import model_info
10
- from sklearn.decomposition import PCA
11
- from tokenizers import Tokenizer
12
10
  from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
13
11
 
14
- from model2vec.distill.inference import create_embeddings
15
- from model2vec.distill.tokenizer import replace_vocabulary
16
- from model2vec.distill.utils import Token, select_optimal_device
12
+ from model2vec.distill.inference import PCADimType, create_embeddings, post_process_embeddings
13
+ from model2vec.distill.utils import select_optimal_device
17
14
  from model2vec.model import StaticModel
18
15
  from model2vec.quantization import DType, quantize_embeddings
19
-
20
- try:
21
- # For huggingface_hub>=0.25.0
22
- from huggingface_hub.errors import RepositoryNotFoundError
23
- except ImportError:
24
- # For huggingface_hub<0.25.0
25
- from huggingface_hub.utils._errors import RepositoryNotFoundError
26
-
16
+ from model2vec.tokenizer import clean_and_create_vocabulary, replace_vocabulary, turn_tokens_into_ids
27
17
 
28
18
  logger = logging.getLogger(__name__)
29
19
 
30
20
 
31
- PCADimType = Union[int, None, float, Literal["auto"]]
32
-
33
-
34
21
  def distill_from_model(
35
22
  model: PreTrainedModel,
36
23
  tokenizer: PreTrainedTokenizerFast,
@@ -68,6 +55,7 @@ def distill_from_model(
68
55
  :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
69
56
  :param use_subword: DEPRECATED: If this is not set to None, we show a warning. It doesn't do anything.
70
57
  :return: A StaticModel
58
+ :raises: ValueError if the vocabulary is empty after preprocessing.
71
59
 
72
60
  """
73
61
  if use_subword is not None:
@@ -82,35 +70,51 @@ def distill_from_model(
82
70
  vocabulary = []
83
71
 
84
72
  device = select_optimal_device(device)
85
- # Make a base list of tokens.
86
- subword_vocab: dict[str, int] = tokenizer.get_vocab()
87
- subword_tokens: list[str] = [k for k, _ in sorted(subword_vocab.items(), key=lambda x: x[1])]
88
73
 
89
74
  n_tokens_before = len(vocabulary)
90
- # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
91
- cleaned_vocabulary = _clean_vocabulary(tokenizer.backend_tokenizer, vocabulary, subword_tokens)
92
- n_tokens_after = len(cleaned_vocabulary)
93
- logger.info(
94
- f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
75
+ # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.
76
+ all_tokens, backend_tokenizer = clean_and_create_vocabulary(
77
+ tokenizer, vocabulary, token_remove_regex=token_remove_regex
95
78
  )
79
+ n_tokens_after = len([token for token in all_tokens if not token.is_internal])
80
+ if n_tokens_before:
81
+ logger.info(
82
+ f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
83
+ )
96
84
 
97
- # Create the embeddings.
98
- all_tokens, embeddings = create_embeddings(
99
- model=model,
100
- tokenizer=tokenizer,
101
- tokens=cleaned_vocabulary,
102
- device=device,
103
- token_remove_regex=token_remove_regex,
104
- )
85
+ if not all_tokens:
86
+ raise ValueError("The vocabulary is empty after preprocessing. Please check your token_remove_pattern.")
87
+
88
+ unk_token = cast(Optional[str], tokenizer.special_tokens_map.get("unk_token"))
89
+ pad_token = cast(Optional[str], tokenizer.special_tokens_map.get("pad_token"))
90
+
91
+ # Weird if to satsify mypy
92
+ if pad_token is None:
93
+ if unk_token is not None:
94
+ pad_token = unk_token
95
+ logger.warning(
96
+ "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."
97
+ )
98
+ else:
99
+ pad_token = unk_token or all_tokens[0].form
100
+ logger.warning(
101
+ "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."
102
+ )
105
103
 
106
- unk_token = tokenizer.special_tokens_map.get("unk_token")
107
- pad_token = tokenizer.special_tokens_map.get("pad_token")
108
- # Add the cleaned vocabulary to the tokenizer.
104
+ # Replace the vocabulary in the tokenizer with the new vocabulary.
109
105
  backend_tokenizer = replace_vocabulary(backend_tokenizer, all_tokens, unk_token=unk_token, pad_token=pad_token)
110
106
 
111
- # Post process the embeddings by applying PCA and Zipf weighting.
112
- embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
107
+ logger.info(f"Creating embeddings for {len(all_tokens)} tokens")
108
+ # Convert tokens to IDs
109
+ token_ids = turn_tokens_into_ids(all_tokens, tokenizer, unk_token)
110
+
111
+ # Create the embeddings
112
+ embeddings = create_embeddings(
113
+ tokenized=token_ids, model=model, device=device, pad_token_id=tokenizer.get_vocab()[pad_token]
114
+ )
113
115
 
116
+ # Post process the embeddings by applying PCA and Zipf weighting.
117
+ embeddings = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)
114
118
  # Quantize the embeddings.
115
119
  embeddings = quantize_embeddings(embeddings, quantize_to)
116
120
 
@@ -136,9 +140,10 @@ def distill_from_model(
136
140
  # Get the language from the model card.
137
141
  try:
138
142
  info = model_info(model_name)
139
- language = info.cardData.get("language", None)
140
- except RepositoryNotFoundError:
141
- logger.info("No model info found for the model. Setting language to None.")
143
+ language = info.cardData.get("language", None) if info.cardData is not None else None
144
+ except Exception as e:
145
+ # NOTE: bare except because there's many reasons this can fail.
146
+ logger.warning(f"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.")
142
147
  language = None
143
148
 
144
149
  return StaticModel(
@@ -234,7 +239,10 @@ def distill(
234
239
 
235
240
  """
236
241
  model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)
237
- tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code)
242
+ tokenizer = cast(
243
+ PreTrainedTokenizerFast,
244
+ AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),
245
+ )
238
246
 
239
247
  return distill_from_model(
240
248
  model=model,
@@ -248,97 +256,3 @@ def distill(
248
256
  quantize_to=quantize_to,
249
257
  use_subword=use_subword,
250
258
  )
251
-
252
-
253
- def _post_process_embeddings(
254
- embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4
255
- ) -> np.ndarray:
256
- """Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law."""
257
- if pca_dims is not None:
258
- if pca_dims == "auto":
259
- pca_dims = embeddings.shape[1]
260
- if pca_dims > embeddings.shape[1]:
261
- logger.warning(
262
- f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
263
- "Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
264
- "Applying PCA will probably improve performance, so consider just leaving it."
265
- )
266
- pca_dims = embeddings.shape[1]
267
- if pca_dims >= embeddings.shape[0]:
268
- logger.warning(
269
- f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
270
- )
271
- elif pca_dims <= embeddings.shape[1]:
272
- if isinstance(pca_dims, float):
273
- logger.info(f"Applying PCA with {pca_dims} explained variance.")
274
- else:
275
- logger.info(f"Applying PCA with n_components {pca_dims}")
276
-
277
- orig_dims = embeddings.shape[1]
278
- p = PCA(n_components=pca_dims, svd_solver="full")
279
- embeddings = p.fit_transform(embeddings)
280
-
281
- if embeddings.shape[1] < orig_dims:
282
- explained_variance_ratio = np.sum(p.explained_variance_ratio_)
283
- explained_variance = np.sum(p.explained_variance_)
284
- logger.info(f"Reduced dimensionality from {orig_dims} to {embeddings.shape[1]}.")
285
- logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
286
- logger.info(f"Explained variance: {explained_variance:.3f}.")
287
-
288
- if sif_coefficient is not None:
289
- logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
290
- inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
291
- proba = inv_rank / np.sum(inv_rank)
292
- embeddings *= (sif_coefficient / (sif_coefficient + proba))[:, None]
293
-
294
- return embeddings
295
-
296
-
297
- def _clean_vocabulary(tokenizer: Tokenizer, vocabulary: list[str], added_tokens: list[str]) -> list[str]:
298
- """Cleans a vocabulary by removing duplicates and tokens that were already in the vocabulary."""
299
- added_tokens_set = set(added_tokens)
300
- seen_tokens = set()
301
- cleaned_vocabulary = []
302
- n_empty = 0
303
- n_duplicates = 0
304
- n_multiword = 0
305
- for token in vocabulary:
306
- normalizer = tokenizer.normalizer
307
- if normalizer is not None:
308
- token = normalizer.normalize_str(token)
309
-
310
- if not token:
311
- n_empty += 1
312
- continue
313
-
314
- pre_tokenizer = tokenizer.pre_tokenizer
315
- # We need to check whether the pretokenized token is a single word or not.
316
- if pre_tokenizer is not None:
317
- pretokenized_tokens = pre_tokenizer.pre_tokenize_str(token)
318
- if len(pretokenized_tokens) != 1:
319
- n_multiword += 1
320
- continue
321
- new_token = pretokenized_tokens[-1][0]
322
- else:
323
- new_token = token
324
-
325
- # We need to check whether the pretokenized token is in the vocabulary.
326
- # But we need to return the original token, because that will be tokenized
327
- # again by the tokenizer during featurization.
328
- if new_token in seen_tokens or new_token in added_tokens_set:
329
- n_duplicates += 1
330
- continue
331
-
332
- # Add the possibly pretokenized token to _seen_
333
- seen_tokens.add(new_token)
334
- # Add the original string to the vocabulary.
335
- cleaned_vocabulary.append(token)
336
-
337
- if n_duplicates:
338
- logger.warning(f"Removed {n_duplicates} duplicate tokens.")
339
- if n_empty:
340
- logger.warning(f"Removed {n_empty} empty tokens.")
341
- if n_multiword:
342
- logger.warning(f"Removed {n_multiword} multiword tokens.")
343
-
344
- return cleaned_vocabulary
@@ -3,23 +3,23 @@ from __future__ import annotations
3
3
 
4
4
  import inspect
5
5
  import logging
6
- import re
7
6
  from pathlib import Path
8
- from typing import Protocol, Union
7
+ from typing import Literal, Protocol, Union
9
8
 
10
9
  import numpy as np
11
10
  import torch
11
+ from sklearn.decomposition import PCA
12
12
  from torch.nn.utils.rnn import pad_sequence
13
13
  from tqdm import tqdm
14
- from transformers import PreTrainedModel, PreTrainedTokenizerFast
14
+ from transformers import PreTrainedModel
15
15
  from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
16
16
 
17
- from model2vec.distill.utils import Token, filter_vocabulary_by_regex
18
-
19
17
  logger = logging.getLogger(__name__)
20
18
 
21
19
 
22
20
  PathLike = Union[Path, str]
21
+ PCADimType = Union[int, None, float, Literal["auto"]]
22
+
23
23
 
24
24
  _DEFAULT_BATCH_SIZE = 256
25
25
 
@@ -30,11 +30,10 @@ class ModulewithWeights(Protocol):
30
30
 
31
31
  def create_embeddings(
32
32
  model: PreTrainedModel,
33
- tokenizer: PreTrainedTokenizerFast,
34
- tokens: list[str],
33
+ tokenized: list[list[int]],
35
34
  device: str,
36
- token_remove_regex: re.Pattern | None,
37
- ) -> tuple[list[Token], np.ndarray]:
35
+ pad_token_id: int,
36
+ ) -> np.ndarray:
38
37
  """
39
38
  Create output embeddings for a bunch of tokens using a pretrained model.
40
39
 
@@ -42,51 +41,16 @@ def create_embeddings(
42
41
 
43
42
  :param model: The model to use.
44
43
  This should be a transformers model.
45
- :param tokenizer: The tokenizer to use.
46
- :param tokens: The tokens to use.
44
+ :param tokenized: All tokenized tokens.
47
45
  :param device: The torch device to use.
48
- :param token_remove_regex: A regex pattern to remove tokens from the vocabulary.
49
- :return: The tokens and output embeddings.
46
+ :param pad_token_id: The pad token id. Used to pad sequences.
47
+ :return: The output embeddings.
50
48
  """
51
49
  model = model.to(device)
52
50
 
53
51
  out_weights: np.ndarray
54
52
  intermediate_weights: list[np.ndarray] = []
55
53
 
56
- out_tokens: list[Token] = []
57
- tokenized: list[torch.Tensor] = []
58
- pad_token = tokenizer.special_tokens_map.get("pad_token")
59
- # We need to use the pad token id for padding below.
60
- pad_token_id = tokenizer.convert_tokens_to_ids(pad_token)
61
- unk_token = tokenizer.special_tokens_map.get("unk_token")
62
-
63
- # Empty set if no pad or unk token is set.
64
- tokens_to_keep = {pad_token, unk_token} - {None}
65
-
66
- if token_remove_regex is not None:
67
- # Sort the vocabulary by id, important for zipf.
68
- sorted_vocab = sorted(tokenizer.get_vocab().items(), key=lambda x: x[1])
69
- id_list = filter_vocabulary_by_regex(token_remove_regex, sorted_vocab)
70
- else:
71
- # If the token remove regex is None, just use all tokens.
72
- id_list = list(range(len(tokenizer.get_vocab())))
73
-
74
- added_tokens_ids = [id for token, id in tokenizer.added_tokens_encoder.items() if token not in tokens_to_keep]
75
- ids = torch.Tensor(sorted(set(id_list) - set(added_tokens_ids))).long()
76
-
77
- if ids is not None:
78
- dummy_encoding = tokenizer.encode("A")
79
- bos_token_id, eos_token_id = dummy_encoding[0], dummy_encoding[-1]
80
-
81
- bos = torch.full([len(ids)], fill_value=bos_token_id)
82
- eos = torch.full([len(ids)], fill_value=eos_token_id)
83
-
84
- tokenized.extend(torch.stack([bos, ids, eos], dim=1))
85
- subword_tokens = [Token(x, True) for x in tokenizer.convert_ids_to_tokens(ids.tolist())]
86
- out_tokens.extend(subword_tokens)
87
-
88
- tokenized.extend([tokenizer.encode_plus(token, return_tensors="pt")["input_ids"][0] for token in tokens])
89
-
90
54
  # Add token_type_ids only if the model supports it
91
55
  add_token_type_ids = "token_type_ids" in inspect.getfullargspec(model.forward).args
92
56
 
@@ -98,7 +62,7 @@ def create_embeddings(
98
62
  pbar = tqdm(total=len(sorted_tokenized), desc="Encoding tokens", unit=" tokens")
99
63
 
100
64
  for batch_idx in range(0, len(sorted_tokenized), _DEFAULT_BATCH_SIZE):
101
- batch = sorted_tokenized[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
65
+ batch = [torch.Tensor(x).long() for x in sorted_tokenized[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]]
102
66
 
103
67
  encoded = {}
104
68
  encoded["input_ids"] = pad_sequence(batch, batch_first=True, padding_value=pad_token_id)
@@ -113,10 +77,11 @@ def create_embeddings(
113
77
 
114
78
  # Sort the output back to the original order
115
79
  intermediate_weights = [intermediate_weights[i] for i in np.argsort(sort_order)]
116
- out_tokens.extend([Token(x, False) for x in tokens])
117
80
  out_weights = np.stack(intermediate_weights)
118
81
 
119
- return out_tokens, out_weights
82
+ out_weights = np.nan_to_num(out_weights)
83
+
84
+ return out_weights
120
85
 
121
86
 
122
87
  @torch.no_grad()
@@ -147,3 +112,47 @@ def _encode_mean_using_model(model: PreTrainedModel, encodings: dict[str, torch.
147
112
  result = torch.bmm(mask[:, None, :].float(), out).squeeze(1)
148
113
 
149
114
  return result
115
+
116
+
117
+ def post_process_embeddings(
118
+ embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4
119
+ ) -> np.ndarray:
120
+ """Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law."""
121
+ if pca_dims is not None:
122
+ if pca_dims == "auto":
123
+ pca_dims = embeddings.shape[1]
124
+ if pca_dims > embeddings.shape[1]:
125
+ logger.warning(
126
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
127
+ "Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
128
+ "Applying PCA will probably improve performance, so consider just leaving it."
129
+ )
130
+ pca_dims = embeddings.shape[1]
131
+ if pca_dims >= embeddings.shape[0]:
132
+ logger.warning(
133
+ f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
134
+ )
135
+ elif pca_dims <= embeddings.shape[1]:
136
+ if isinstance(pca_dims, float):
137
+ logger.info(f"Applying PCA with {pca_dims} explained variance.")
138
+ else:
139
+ logger.info(f"Applying PCA with n_components {pca_dims}")
140
+
141
+ orig_dims = embeddings.shape[1]
142
+ p = PCA(n_components=pca_dims, svd_solver="full")
143
+ embeddings = p.fit_transform(embeddings)
144
+
145
+ if embeddings.shape[1] < orig_dims:
146
+ explained_variance_ratio = np.sum(p.explained_variance_ratio_)
147
+ explained_variance = np.sum(p.explained_variance_)
148
+ logger.info(f"Reduced dimensionality from {orig_dims} to {embeddings.shape[1]}.")
149
+ logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
150
+ logger.info(f"Explained variance: {explained_variance:.3f}.")
151
+
152
+ if sif_coefficient is not None:
153
+ logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
154
+ inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
155
+ proba = inv_rank / np.sum(inv_rank)
156
+ embeddings *= (sif_coefficient / (sif_coefficient + proba))[:, None]
157
+
158
+ return embeddings
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from logging import getLogger
4
+
5
+ import torch
6
+
7
+ logger = getLogger(__name__)
8
+
9
+
10
+ def select_optimal_device(device: str | None) -> str:
11
+ """
12
+ Guess what your optimal device should be based on backend availability.
13
+
14
+ If you pass a device, we just pass it through.
15
+
16
+ :param device: The device to use. If this is not None you get back what you passed.
17
+ :return: The selected device.
18
+ """
19
+ if device is None:
20
+ if torch.cuda.is_available():
21
+ device = "cuda"
22
+ elif torch.backends.mps.is_available():
23
+ device = "mps"
24
+ else:
25
+ device = "cpu"
26
+ logger.info(f"Automatically selected device: {device}")
27
+
28
+ return device
@@ -40,7 +40,7 @@ def save_pretrained(
40
40
  folder_path = folder_path / subfolder if subfolder else folder_path
41
41
  folder_path.mkdir(exist_ok=True, parents=True)
42
42
  save_file({"embeddings": embeddings}, folder_path / "model.safetensors")
43
- tokenizer.save(str(folder_path / "tokenizer.json"))
43
+ tokenizer.save(str(folder_path / "tokenizer.json"), pretty=False)
44
44
  json.dump(config, open(folder_path / "config.json", "w"), indent=4)
45
45
 
46
46
  # Create modules.json
@@ -158,8 +158,9 @@ def load_pretrained(
158
158
  )
159
159
  )
160
160
  metadata = _get_metadata_from_readme(Path(readme_path))
161
- except huggingface_hub.utils.EntryNotFoundError:
162
- logger.info("No README found in the model folder. No model card loaded.")
161
+ except Exception as e:
162
+ # NOTE: we don't want to raise an error here, since the README is optional.
163
+ logger.info(f"No README found in the model folder: {e} No model card loaded.")
163
164
  metadata = {}
164
165
 
165
166
  config_path = Path(
@@ -65,7 +65,9 @@ class StaticModelPipeline:
65
65
  """Save the model to a folder."""
66
66
  save_pipeline(self, path)
67
67
 
68
- def push_to_hub(self, repo_id: str, subfolder: str, token: str | None = None, private: bool = False) -> None:
68
+ def push_to_hub(
69
+ self, repo_id: str, subfolder: str | None = None, token: str | None = None, private: bool = False
70
+ ) -> None:
69
71
  """
70
72
  Save a model to a folder, and then push that folder to the hf hub.
71
73
 
@@ -219,6 +221,7 @@ def _load_pipeline(
219
221
  """
220
222
  folder_or_repo_path = Path(folder_or_repo_path)
221
223
  model_filename = _DEFAULT_MODEL_FILENAME
224
+ head_pipeline_path: str | Path
222
225
  if folder_or_repo_path.exists():
223
226
  head_pipeline_path = folder_or_repo_path / model_filename
224
227
  if not head_pipeline_path.exists():
@@ -331,7 +331,7 @@ class StaticModel:
331
331
  return out_array[0]
332
332
  return out_array
333
333
 
334
- def _encode_batch_as_sequence(self, sentences: list[str], max_length: int | None) -> list[np.ndarray]:
334
+ def _encode_batch_as_sequence(self, sentences: Sequence[str], max_length: int | None) -> list[np.ndarray]:
335
335
  """Encode a batch of sentences as a sequence."""
336
336
  ids = self.tokenize(sentences=sentences, max_length=max_length)
337
337
  out: list[np.ndarray] = []
@@ -0,0 +1,12 @@
1
+ from model2vec.utils import importable
2
+
3
+ importable("transformers", "tokenizer")
4
+
5
+ from model2vec.tokenizer.tokenizer import (
6
+ clean_and_create_vocabulary,
7
+ create_tokenizer,
8
+ replace_vocabulary,
9
+ turn_tokens_into_ids,
10
+ )
11
+
12
+ __all__ = ["clean_and_create_vocabulary", "create_tokenizer", "turn_tokens_into_ids", "replace_vocabulary"]