model2vec 0.4.1__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.
- {model2vec-0.4.1 → model2vec-0.6.0}/PKG-INFO +23 -18
- {model2vec-0.4.1 → model2vec-0.6.0}/README.md +17 -15
- model2vec-0.6.0/assets/images/model2vec_logo.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/docs/usage.md +48 -0
- model2vec-0.6.0/model2vec/distill/distillation.py +258 -0
- model2vec-0.6.0/model2vec/distill/inference.py +158 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/hf_utils.py +50 -28
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/inference/model.py +11 -9
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/model.py +94 -15
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/modelcards/classifier_template.md +2 -2
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/modelcards/model_card_template.md +2 -2
- model2vec-0.6.0/model2vec/quantization.py +63 -0
- model2vec-0.6.0/model2vec/tokenizer/__init__.py +12 -0
- model2vec-0.6.0/model2vec/tokenizer/datamodels.py +14 -0
- model2vec-0.6.0/model2vec/tokenizer/model.py +43 -0
- model2vec-0.6.0/model2vec/tokenizer/normalizer.py +42 -0
- model2vec-0.6.0/model2vec/tokenizer/pretokenizer.py +57 -0
- model2vec-0.6.0/model2vec/tokenizer/tokenizer.py +395 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/train/base.py +12 -2
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/train/classifier.py +26 -5
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/version.py +1 -1
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec.egg-info/PKG-INFO +23 -18
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec.egg-info/SOURCES.txt +11 -1
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec.egg-info/requires.txt +4 -1
- {model2vec-0.4.1 → model2vec-0.6.0}/pyproject.toml +7 -2
- {model2vec-0.4.1 → model2vec-0.6.0}/results/README.md +31 -1
- {model2vec-0.4.1 → model2vec-0.6.0}/scripts/export_to_onnx.py +3 -1
- model2vec-0.6.0/tests/__init__.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/conftest.py +28 -9
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/test_distillation.py +65 -115
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/test_model.py +59 -0
- model2vec-0.6.0/tests/test_quantization.py +30 -0
- model2vec-0.6.0/tests/test_tokenizer.py +123 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/test_trainable.py +45 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tutorials/README.md +1 -1
- model2vec-0.6.0/tutorials/semantic_chunking.ipynb +268 -0
- model2vec-0.6.0/uv.lock +2553 -0
- model2vec-0.4.1/model2vec/distill/distillation.py +0 -370
- model2vec-0.4.1/model2vec/distill/inference.py +0 -167
- model2vec-0.4.1/model2vec/distill/tokenizer.py +0 -122
- model2vec-0.4.1/tutorials/semantic_chunking.ipynb +0 -261
- model2vec-0.4.1/uv.lock +0 -2360
- {model2vec-0.4.1 → model2vec-0.6.0}/.github/workflows/ci.yaml +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/.gitignore +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/.pre-commit-config.yaml +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/LICENSE +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/Makefile +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/logo.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/logo_v2.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/model2vec_model_diagram.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/sentences_per_second_vs_average_score.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_accuracy.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v2.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v3.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_accuracy_v4.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score_v2.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/docs/README.md +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/docs/integrations.md +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/docs/what_is_model2vec.md +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/__init__.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/distill/utils.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/inference/README.md +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/inference/__init__.py +0 -0
- /model2vec-0.4.1/tests/__init__.py → /model2vec-0.6.0/model2vec/py.typed +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/train/README.md +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/train/__init__.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec/utils.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/results/make_speed_vs_mteb_plot.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/setup.cfg +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/test_inference.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tests/test_utils.py +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tutorials/recipe_search.ipynb +0 -0
- {model2vec-0.4.1 → model2vec-0.6.0}/tutorials/train_classifier.ipynb +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 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,18 +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"
|
|
79
|
+
Dynamic: license-file
|
|
77
80
|
|
|
78
81
|
|
|
79
|
-
<
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
</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
|
+
|
|
85
87
|
|
|
86
|
-
<div align="center">
|
|
87
|
-
<h2>Fast State-of-the-Art Static Embeddings</h2>
|
|
88
|
-
</div>
|
|
89
88
|
|
|
90
89
|
<div align="center">
|
|
91
90
|
<h2>
|
|
@@ -200,9 +199,13 @@ For advanced usage, please refer to our [usage documentation](https://github.com
|
|
|
200
199
|
|
|
201
200
|
## Updates & Announcements
|
|
202
201
|
|
|
203
|
-
- **
|
|
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.
|
|
203
|
+
|
|
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.
|
|
204
205
|
|
|
205
|
-
- **
|
|
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.
|
|
206
209
|
|
|
207
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).
|
|
208
211
|
|
|
@@ -243,11 +246,13 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
243
246
|
| Model | Language | Sentence Transformer | Params | Task |
|
|
244
247
|
|-----------------------------------------------------------------------|------------|-----------------------------------------------------------------|---------|-----------|
|
|
245
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 |
|
|
246
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 |
|
|
247
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 |
|
|
248
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 |
|
|
249
|
-
|
|
250
|
-
|
|
254
|
+
|
|
255
|
+
|
|
251
256
|
|
|
252
257
|
|
|
253
258
|
## Results
|
|
@@ -265,8 +270,8 @@ MIT
|
|
|
265
270
|
|
|
266
271
|
If you use Model2Vec in your research, please cite the following:
|
|
267
272
|
```bibtex
|
|
268
|
-
@
|
|
269
|
-
|
|
273
|
+
@article{minishlab2024model2vec,
|
|
274
|
+
author = {Tulkens, Stephan and {van Dongen}, Thomas},
|
|
270
275
|
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
271
276
|
year = {2024},
|
|
272
277
|
url = {https://github.com/MinishLab/model2vec}
|
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
|
|
2
|
-
<
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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,9 +119,13 @@ For advanced usage, please refer to our [usage documentation](https://github.com
|
|
|
123
119
|
|
|
124
120
|
## Updates & Announcements
|
|
125
121
|
|
|
126
|
-
- **
|
|
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.
|
|
123
|
+
|
|
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.
|
|
127
125
|
|
|
128
|
-
- **
|
|
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.
|
|
129
129
|
|
|
130
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).
|
|
131
131
|
|
|
@@ -166,11 +166,13 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
166
166
|
| Model | Language | Sentence Transformer | Params | Task |
|
|
167
167
|
|-----------------------------------------------------------------------|------------|-----------------------------------------------------------------|---------|-----------|
|
|
168
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 |
|
|
169
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 |
|
|
170
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 |
|
|
171
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 |
|
|
172
|
-
|
|
173
|
-
|
|
174
|
+
|
|
175
|
+
|
|
174
176
|
|
|
175
177
|
|
|
176
178
|
## Results
|
|
@@ -188,8 +190,8 @@ MIT
|
|
|
188
190
|
|
|
189
191
|
If you use Model2Vec in your research, please cite the following:
|
|
190
192
|
```bibtex
|
|
191
|
-
@
|
|
192
|
-
|
|
193
|
+
@article{minishlab2024model2vec,
|
|
194
|
+
author = {Tulkens, Stephan and {van Dongen}, Thomas},
|
|
193
195
|
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
|
|
194
196
|
year = {2024},
|
|
195
197
|
url = {https://github.com/MinishLab/model2vec}
|
|
Binary file
|
|
@@ -126,6 +126,54 @@ m2v_model = distill(model_name=model_name, vocabulary=vocabulary, use_subword=Fa
|
|
|
126
126
|
|
|
127
127
|
**Important note:** we assume the passed vocabulary is sorted in rank frequency. i.e., we don't care about the actual word frequencies, but do assume that the most frequent word is first, and the least frequent word is last. If you're not sure whether this is case, set `apply_zipf` to `False`. This disables the weighting, but will also make performance a little bit worse.
|
|
128
128
|
|
|
129
|
+
### Quantization
|
|
130
|
+
|
|
131
|
+
Models can be quantized to `float16` (default) or `int8` during distillation, or when loading from disk.
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from model2vec.distill import distill
|
|
135
|
+
|
|
136
|
+
# Distill a Sentence Transformer model and quantize is to int8
|
|
137
|
+
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", quantize_to="int8")
|
|
138
|
+
|
|
139
|
+
# Save the model. This model is now 25% of the size of a normal model.
|
|
140
|
+
m2v_model.save_pretrained("m2v_model")
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
You can also quantize during loading.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from model2vec import StaticModel
|
|
147
|
+
|
|
148
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8m", quantize_to="int8")
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Dimensionality reduction
|
|
152
|
+
|
|
153
|
+
Because almost all Model2Vec models have been distilled using PCA, and because PCA explicitly orders dimensions from most informative to least informative, we can perform dimensionality reduction during loading. This is very similar to how matryoshka embeddings work.
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from model2vec import StaticModel
|
|
157
|
+
|
|
158
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8m", dimensionality=32)
|
|
159
|
+
|
|
160
|
+
print(model.embedding.shape)
|
|
161
|
+
# (29528, 32)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Combining quantization and dimensionality reduction
|
|
165
|
+
|
|
166
|
+
Combining these tricks can lead to extremely small models. For example, using this, we can reduce the size of `potion-base-8m`, which is now 30MB, to only 1MB:
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8m",
|
|
170
|
+
dimensionality=32,
|
|
171
|
+
quantize_to="int8")
|
|
172
|
+
print(model.embedding.nbytes)
|
|
173
|
+
# 944896 bytes = 944kb
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
This should be enough to satisfy even the strongest hardware constraints.
|
|
129
177
|
|
|
130
178
|
## Training
|
|
131
179
|
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from typing import Optional, cast
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from huggingface_hub import model_info
|
|
10
|
+
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
11
|
+
|
|
12
|
+
from model2vec.distill.inference import PCADimType, create_embeddings, post_process_embeddings
|
|
13
|
+
from model2vec.distill.utils import select_optimal_device
|
|
14
|
+
from model2vec.model import StaticModel
|
|
15
|
+
from model2vec.quantization import DType, quantize_embeddings
|
|
16
|
+
from model2vec.tokenizer import clean_and_create_vocabulary, replace_vocabulary, turn_tokens_into_ids
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def distill_from_model(
|
|
22
|
+
model: PreTrainedModel,
|
|
23
|
+
tokenizer: PreTrainedTokenizerFast,
|
|
24
|
+
vocabulary: list[str] | None = None,
|
|
25
|
+
device: str | None = None,
|
|
26
|
+
pca_dims: PCADimType = 256,
|
|
27
|
+
apply_zipf: bool | None = None,
|
|
28
|
+
sif_coefficient: float | None = 1e-4,
|
|
29
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
30
|
+
quantize_to: DType | str = DType.Float16,
|
|
31
|
+
use_subword: bool | None = None,
|
|
32
|
+
) -> StaticModel:
|
|
33
|
+
"""
|
|
34
|
+
Distill a staticmodel from a sentence transformer.
|
|
35
|
+
|
|
36
|
+
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
37
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
|
|
38
|
+
|
|
39
|
+
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
40
|
+
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
41
|
+
|
|
42
|
+
:param model: The model to use.
|
|
43
|
+
:param tokenizer: The tokenizer to use.
|
|
44
|
+
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
45
|
+
:param device: The device to use.
|
|
46
|
+
:param pca_dims: The number of components to use for PCA.
|
|
47
|
+
If this is None, we don't apply PCA.
|
|
48
|
+
If this is 'auto', we don't reduce dimensionality, but still apply PCA.
|
|
49
|
+
:param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
|
|
50
|
+
Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
|
|
51
|
+
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
52
|
+
Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.
|
|
53
|
+
: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.
|
|
54
|
+
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.
|
|
55
|
+
:param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
|
|
56
|
+
:param use_subword: DEPRECATED: If this is not set to None, we show a warning. It doesn't do anything.
|
|
57
|
+
:return: A StaticModel
|
|
58
|
+
:raises: ValueError if the vocabulary is empty after preprocessing.
|
|
59
|
+
|
|
60
|
+
"""
|
|
61
|
+
if use_subword is not None:
|
|
62
|
+
logger.warning(
|
|
63
|
+
"The `use_subword` parameter is deprecated and will be removed in the next release. It doesn't do anything."
|
|
64
|
+
)
|
|
65
|
+
quantize_to = DType(quantize_to)
|
|
66
|
+
backend_tokenizer = tokenizer.backend_tokenizer
|
|
67
|
+
sif_coefficient, token_remove_regex = _validate_parameters(apply_zipf, sif_coefficient, token_remove_pattern)
|
|
68
|
+
|
|
69
|
+
if vocabulary is None:
|
|
70
|
+
vocabulary = []
|
|
71
|
+
|
|
72
|
+
device = select_optimal_device(device)
|
|
73
|
+
|
|
74
|
+
n_tokens_before = len(vocabulary)
|
|
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
|
|
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
|
+
)
|
|
84
|
+
|
|
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
|
+
)
|
|
103
|
+
|
|
104
|
+
# Replace the vocabulary in the tokenizer with the new vocabulary.
|
|
105
|
+
backend_tokenizer = replace_vocabulary(backend_tokenizer, all_tokens, unk_token=unk_token, pad_token=pad_token)
|
|
106
|
+
|
|
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
|
+
)
|
|
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)
|
|
118
|
+
# Quantize the embeddings.
|
|
119
|
+
embeddings = quantize_embeddings(embeddings, quantize_to)
|
|
120
|
+
|
|
121
|
+
model_name = getattr(model, "name_or_path", "")
|
|
122
|
+
|
|
123
|
+
config = {
|
|
124
|
+
"model_type": "model2vec",
|
|
125
|
+
"architectures": ["StaticModel"],
|
|
126
|
+
"tokenizer_name": model_name,
|
|
127
|
+
"apply_pca": pca_dims,
|
|
128
|
+
"apply_zipf": apply_zipf,
|
|
129
|
+
"sif_coefficient": sif_coefficient,
|
|
130
|
+
"hidden_dim": embeddings.shape[1],
|
|
131
|
+
"seq_length": 1000000, # Set this to a high value since we don't have a sequence length limit.
|
|
132
|
+
"normalize": True,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if os.path.exists(model_name):
|
|
136
|
+
# Using a local model. Get the model name from the path.
|
|
137
|
+
model_name = os.path.basename(model_name)
|
|
138
|
+
language = None
|
|
139
|
+
else:
|
|
140
|
+
# Get the language from the model card.
|
|
141
|
+
try:
|
|
142
|
+
info = model_info(model_name)
|
|
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.")
|
|
147
|
+
language = None
|
|
148
|
+
|
|
149
|
+
return StaticModel(
|
|
150
|
+
vectors=embeddings,
|
|
151
|
+
tokenizer=backend_tokenizer,
|
|
152
|
+
config=config,
|
|
153
|
+
base_model_name=model_name,
|
|
154
|
+
language=language,
|
|
155
|
+
normalize=True,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _validate_parameters(
|
|
160
|
+
apply_zipf: bool | None,
|
|
161
|
+
sif_coefficient: float | None,
|
|
162
|
+
token_remove_pattern: str | None,
|
|
163
|
+
) -> tuple[float | None, re.Pattern | None]:
|
|
164
|
+
"""
|
|
165
|
+
Validate the parameters passed to the distillation function.
|
|
166
|
+
|
|
167
|
+
:param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
|
|
168
|
+
Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
|
|
169
|
+
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
170
|
+
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
|
|
171
|
+
: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.
|
|
172
|
+
:return: The SIF coefficient to use.
|
|
173
|
+
:raises: ValueError if the regex can't be compiled.
|
|
174
|
+
|
|
175
|
+
"""
|
|
176
|
+
if apply_zipf is not None:
|
|
177
|
+
logger.warning(
|
|
178
|
+
"The `apply_zipf` parameter is deprecated and will be removed in the next release. "
|
|
179
|
+
"Zipf weighting is applied based on the sif_coefficient parameter. If this is set to None, "
|
|
180
|
+
"no weighting is applied."
|
|
181
|
+
)
|
|
182
|
+
if apply_zipf and sif_coefficient is None:
|
|
183
|
+
logger.warning("You set apply_zipf to True, but sif_coefficient is None. Setting sif_coefficient to 1e-4.")
|
|
184
|
+
sif_coefficient = 1e-4
|
|
185
|
+
elif not apply_zipf:
|
|
186
|
+
logger.warning("Because you set apply_zipf to False, we ignore the sif_coefficient parameter.")
|
|
187
|
+
sif_coefficient = None
|
|
188
|
+
|
|
189
|
+
if sif_coefficient is not None:
|
|
190
|
+
if not 0 < sif_coefficient < 1.0:
|
|
191
|
+
raise ValueError("SIF coefficient must be a value > 0 and < 1.0.")
|
|
192
|
+
|
|
193
|
+
token_remove_regex: re.Pattern | None = None
|
|
194
|
+
if token_remove_pattern is not None:
|
|
195
|
+
try:
|
|
196
|
+
token_remove_regex = re.compile(token_remove_pattern)
|
|
197
|
+
except re.error as e:
|
|
198
|
+
raise ValueError(f"Couldn't compile the regex pattern: {e}")
|
|
199
|
+
|
|
200
|
+
return sif_coefficient, token_remove_regex
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def distill(
|
|
204
|
+
model_name: str,
|
|
205
|
+
vocabulary: list[str] | None = None,
|
|
206
|
+
device: str | None = None,
|
|
207
|
+
pca_dims: PCADimType = 256,
|
|
208
|
+
apply_zipf: bool | None = None,
|
|
209
|
+
sif_coefficient: float | None = 1e-4,
|
|
210
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
211
|
+
trust_remote_code: bool = False,
|
|
212
|
+
quantize_to: DType | str = DType.Float16,
|
|
213
|
+
use_subword: bool | None = None,
|
|
214
|
+
) -> StaticModel:
|
|
215
|
+
"""
|
|
216
|
+
Distill a staticmodel from a sentence transformer.
|
|
217
|
+
|
|
218
|
+
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
219
|
+
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
|
|
220
|
+
|
|
221
|
+
If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
|
|
222
|
+
If you don't pass a vocabulary, we use the model's tokenizer directly.
|
|
223
|
+
|
|
224
|
+
:param model_name: The model name to use. Any sentencetransformer compatible model works.
|
|
225
|
+
:param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
|
|
226
|
+
:param device: The device to use.
|
|
227
|
+
:param pca_dims: The number of components to use for PCA.
|
|
228
|
+
If this is None, we don't apply PCA.
|
|
229
|
+
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
230
|
+
:param apply_zipf: DEPRECATED: This parameter used to control whether Zipf is applied.
|
|
231
|
+
Zipf weighting is now controlled by the sif_coefficient parameter. If this is set to None, no weighting is applied.
|
|
232
|
+
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
233
|
+
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
|
|
234
|
+
: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.
|
|
235
|
+
: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.
|
|
236
|
+
:param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.
|
|
237
|
+
:param use_subword: DEPRECATED: If this is not set to None, we show a warning. It doesn't do anything.
|
|
238
|
+
:return: A StaticModel
|
|
239
|
+
|
|
240
|
+
"""
|
|
241
|
+
model: PreTrainedModel = AutoModel.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
|
+
)
|
|
246
|
+
|
|
247
|
+
return distill_from_model(
|
|
248
|
+
model=model,
|
|
249
|
+
tokenizer=tokenizer,
|
|
250
|
+
vocabulary=vocabulary,
|
|
251
|
+
device=device,
|
|
252
|
+
pca_dims=pca_dims,
|
|
253
|
+
apply_zipf=apply_zipf,
|
|
254
|
+
token_remove_pattern=token_remove_pattern,
|
|
255
|
+
sif_coefficient=sif_coefficient,
|
|
256
|
+
quantize_to=quantize_to,
|
|
257
|
+
use_subword=use_subword,
|
|
258
|
+
)
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import inspect
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal, Protocol, Union
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import torch
|
|
11
|
+
from sklearn.decomposition import PCA
|
|
12
|
+
from torch.nn.utils.rnn import pad_sequence
|
|
13
|
+
from tqdm import tqdm
|
|
14
|
+
from transformers import PreTrainedModel
|
|
15
|
+
from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
PathLike = Union[Path, str]
|
|
21
|
+
PCADimType = Union[int, None, float, Literal["auto"]]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_DEFAULT_BATCH_SIZE = 256
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ModulewithWeights(Protocol):
|
|
28
|
+
weight: torch.nn.Parameter
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_embeddings(
|
|
32
|
+
model: PreTrainedModel,
|
|
33
|
+
tokenized: list[list[int]],
|
|
34
|
+
device: str,
|
|
35
|
+
pad_token_id: int,
|
|
36
|
+
) -> np.ndarray:
|
|
37
|
+
"""
|
|
38
|
+
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
39
|
+
|
|
40
|
+
It does a forward pass for all tokens passed in `tokens`.
|
|
41
|
+
|
|
42
|
+
:param model: The model to use.
|
|
43
|
+
This should be a transformers model.
|
|
44
|
+
:param tokenized: All tokenized tokens.
|
|
45
|
+
:param device: The torch device to use.
|
|
46
|
+
:param pad_token_id: The pad token id. Used to pad sequences.
|
|
47
|
+
:return: The output embeddings.
|
|
48
|
+
"""
|
|
49
|
+
model = model.to(device)
|
|
50
|
+
|
|
51
|
+
out_weights: np.ndarray
|
|
52
|
+
intermediate_weights: list[np.ndarray] = []
|
|
53
|
+
|
|
54
|
+
# Add token_type_ids only if the model supports it
|
|
55
|
+
add_token_type_ids = "token_type_ids" in inspect.getfullargspec(model.forward).args
|
|
56
|
+
|
|
57
|
+
lengths = np.asarray([len(sequence) for sequence in tokenized])
|
|
58
|
+
sort_order = np.argsort(lengths)
|
|
59
|
+
|
|
60
|
+
sorted_tokenized = [tokenized[i] for i in sort_order]
|
|
61
|
+
|
|
62
|
+
pbar = tqdm(total=len(sorted_tokenized), desc="Encoding tokens", unit=" tokens")
|
|
63
|
+
|
|
64
|
+
for batch_idx in range(0, len(sorted_tokenized), _DEFAULT_BATCH_SIZE):
|
|
65
|
+
batch = [torch.Tensor(x).long() for x in sorted_tokenized[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]]
|
|
66
|
+
|
|
67
|
+
encoded = {}
|
|
68
|
+
encoded["input_ids"] = pad_sequence(batch, batch_first=True, padding_value=pad_token_id)
|
|
69
|
+
encoded["attention_mask"] = encoded["input_ids"] != pad_token_id
|
|
70
|
+
|
|
71
|
+
if add_token_type_ids:
|
|
72
|
+
encoded["token_type_ids"] = torch.zeros_like(encoded["input_ids"])
|
|
73
|
+
|
|
74
|
+
out = _encode_mean_using_model(model, encoded)
|
|
75
|
+
intermediate_weights.extend(out.numpy())
|
|
76
|
+
pbar.update(len(batch))
|
|
77
|
+
|
|
78
|
+
# Sort the output back to the original order
|
|
79
|
+
intermediate_weights = [intermediate_weights[i] for i in np.argsort(sort_order)]
|
|
80
|
+
out_weights = np.stack(intermediate_weights)
|
|
81
|
+
|
|
82
|
+
out_weights = np.nan_to_num(out_weights)
|
|
83
|
+
|
|
84
|
+
return out_weights
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@torch.no_grad()
|
|
88
|
+
def _encode_mean_using_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
|
|
89
|
+
"""
|
|
90
|
+
Encode a batch of tokens using a model.
|
|
91
|
+
|
|
92
|
+
Note that if a token in the input batch does not have any embeddings, it will be output as a vector of zeros.
|
|
93
|
+
So detection of these is necessary.
|
|
94
|
+
|
|
95
|
+
:param model: The model to use.
|
|
96
|
+
:param encodings: The encoded tokens to turn into features.
|
|
97
|
+
:return: The mean of the output for each token.
|
|
98
|
+
"""
|
|
99
|
+
encodings = {k: v.to(model.device) for k, v in encodings.items()}
|
|
100
|
+
encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
|
|
101
|
+
out: torch.Tensor = encoded.last_hidden_state.cpu()
|
|
102
|
+
# NOTE: If the dtype is bfloat 16, we convert to float32,
|
|
103
|
+
# because numpy does not suport bfloat16
|
|
104
|
+
# See here: https://github.com/numpy/numpy/issues/19808
|
|
105
|
+
if out.dtype == torch.bfloat16:
|
|
106
|
+
out = out.float()
|
|
107
|
+
|
|
108
|
+
# Take the mean by averaging over the attention mask.
|
|
109
|
+
mask = encodings["attention_mask"].cpu().float()
|
|
110
|
+
mask /= mask.sum(1)[:, None]
|
|
111
|
+
|
|
112
|
+
result = torch.bmm(mask[:, None, :].float(), out).squeeze(1)
|
|
113
|
+
|
|
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
|