model2vec 0.8.2__tar.gz → 0.10.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.8.2 → model2vec-0.10.0}/.github/workflows/ci.yaml +1 -1
- {model2vec-0.8.2 → model2vec-0.10.0}/.pre-commit-config.yaml +7 -3
- model2vec-0.10.0/CONTRIBUTING.md +79 -0
- model2vec-0.10.0/Makefile +50 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/PKG-INFO +25 -48
- {model2vec-0.8.2 → model2vec-0.10.0}/README.md +13 -39
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/distill/distillation.py +4 -3
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/distill/inference.py +48 -11
- model2vec-0.10.0/model2vec/inference/README.md +104 -0
- model2vec-0.10.0/model2vec/inference/__init__.py +4 -0
- model2vec-0.10.0/model2vec/inference/evaluation.py +114 -0
- model2vec-0.10.0/model2vec/inference/mlp.py +81 -0
- model2vec-0.10.0/model2vec/inference/model.py +368 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/model.py +223 -148
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/modelcards/modelcards.py +3 -1
- model2vec-0.10.0/model2vec/modelcards/onnx_classifier_template.md +58 -0
- model2vec-0.10.0/model2vec/modelcards/onnx_model_card_template.md +58 -0
- model2vec-0.10.0/model2vec/onnx.py +343 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/persistence/datamodels.py +9 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/persistence/persistence.py +38 -13
- model2vec-0.10.0/model2vec/persistence/utils.py +10 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/tokenizer/tokenizer.py +30 -4
- model2vec-0.10.0/model2vec/train/README.md +307 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/train/__init__.py +8 -7
- model2vec-0.10.0/model2vec/train/base.py +598 -0
- model2vec-0.10.0/model2vec/train/classifier.py +520 -0
- model2vec-0.10.0/model2vec/train/dataset.py +369 -0
- model2vec-0.10.0/model2vec/train/pairs.py +357 -0
- model2vec-0.10.0/model2vec/train/regression.py +16 -0
- model2vec-0.10.0/model2vec/train/similarity.py +265 -0
- model2vec-0.10.0/model2vec/train/trainer.py +206 -0
- model2vec-0.10.0/model2vec/train/utils.py +131 -0
- model2vec-0.10.0/model2vec/types.py +28 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/version.py +1 -1
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec.egg-info/PKG-INFO +25 -48
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec.egg-info/SOURCES.txt +31 -6
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec.egg-info/requires.txt +12 -8
- model2vec-0.10.0/model2vec.egg-info/scm_file_list.json +95 -0
- model2vec-0.10.0/model2vec.egg-info/scm_version.json +8 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/pyproject.toml +7 -5
- {model2vec-0.8.2 → model2vec-0.10.0}/results/README.md +52 -48
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/conftest.py +58 -4
- model2vec-0.10.0/tests/integration/__init__.py +0 -0
- model2vec-0.10.0/tests/integration/data/Alibaba-NLP___gte-modernbert-base_baseline.json +91 -0
- model2vec-0.10.0/tests/integration/data/baai___bge-base-en-v1.5_baseline.json +91 -0
- model2vec-0.10.0/tests/integration/data/google___embeddinggemma-300m_baseline.json +91 -0
- model2vec-0.10.0/tests/integration/data/intfloat___multilingual-e5-base_baseline.json +91 -0
- model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-base-32m_baseline.json +74 -0
- model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-base-8m_baseline.json +74 -0
- model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-multilingual-128m_baseline.json +178 -0
- model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-retrieval-32m_baseline.json +74 -0
- model2vec-0.10.0/tests/integration/data/sentence-transformers___all-MiniLM-L6-v2_baseline.json +91 -0
- model2vec-0.10.0/tests/integration/distill_metrics.py +123 -0
- model2vec-0.10.0/tests/integration/pretrained_model_metrics.py +102 -0
- model2vec-0.10.0/tests/integration/test_distill_regression.py +145 -0
- model2vec-0.10.0/tests/integration/test_onnx_export.py +80 -0
- model2vec-0.10.0/tests/integration/test_pretrained_model_regression.py +160 -0
- model2vec-0.10.0/tests/integration/update_distill_baseline.py +47 -0
- model2vec-0.10.0/tests/integration/update_pretrained_baseline.py +41 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/test_distillation.py +5 -0
- model2vec-0.10.0/tests/test_export_to_onnx.py +355 -0
- model2vec-0.10.0/tests/test_inference.py +396 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/test_model.py +70 -22
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/test_persistence.py +70 -0
- model2vec-0.10.0/tests/test_trainable.py +1804 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/test_utils.py +1 -1
- {model2vec-0.8.2 → model2vec-0.10.0}/uv.lock +1290 -492
- model2vec-0.8.2/Makefile +0 -23
- model2vec-0.8.2/model2vec/inference/README.md +0 -18
- model2vec-0.8.2/model2vec/inference/__init__.py +0 -10
- model2vec-0.8.2/model2vec/inference/model.py +0 -320
- model2vec-0.8.2/model2vec/train/README.md +0 -151
- model2vec-0.8.2/model2vec/train/base.py +0 -437
- model2vec-0.8.2/model2vec/train/classifier.py +0 -278
- model2vec-0.8.2/model2vec/train/dataset.py +0 -39
- model2vec-0.8.2/model2vec/train/lightning_modules.py +0 -99
- model2vec-0.8.2/model2vec/train/similarity.py +0 -117
- model2vec-0.8.2/model2vec/train/utils.py +0 -118
- model2vec-0.8.2/scripts/export_to_onnx.py +0 -205
- model2vec-0.8.2/tests/test_inference.py +0 -107
- model2vec-0.8.2/tests/test_trainable.py +0 -379
- model2vec-0.8.2/tutorials/README.md +0 -16
- model2vec-0.8.2/tutorials/recipe_search.ipynb +0 -500
- model2vec-0.8.2/tutorials/semantic_chunking.ipynb +0 -268
- model2vec-0.8.2/tutorials/train_classifier.ipynb +0 -806
- {model2vec-0.8.2 → model2vec-0.10.0}/.github/workflows/release.yaml +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/.gitignore +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/CITATION.cff +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/LICENSE +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/logo_v2.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/model2vec_logo.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/speed_vs_mteb_plot.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/docs/README.md +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/distill/utils.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/modelcards/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/modelcards/classifier_template.md +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/modelcards/model_card_template.md +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/persistence/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/persistence/hf.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/py.typed +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/quantization.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/tokenizer/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/utils.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec/vocabulary_quantization.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/results/make_speed_vs_mteb_plot.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/setup.cfg +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/__init__.py +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.8.2 → model2vec-0.10.0}/tests/test_quantization.py +0 -0
|
@@ -30,8 +30,12 @@ repos:
|
|
|
30
30
|
- id: ruff-check
|
|
31
31
|
args: [--fix]
|
|
32
32
|
- id: ruff-format
|
|
33
|
-
- repo:
|
|
34
|
-
rev: v1.15.0
|
|
33
|
+
- repo: local
|
|
35
34
|
hooks:
|
|
36
35
|
- id: mypy
|
|
37
|
-
|
|
36
|
+
name: mypy
|
|
37
|
+
entry: uv run --frozen mypy
|
|
38
|
+
language: system
|
|
39
|
+
types: [python]
|
|
40
|
+
pass_filenames: false
|
|
41
|
+
args: [model2vec/]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Contributing to model2vec
|
|
2
|
+
|
|
3
|
+
Thanks for your interest in model2vec. This document explains how contributions work and what we expect.
|
|
4
|
+
|
|
5
|
+
## tl;dr
|
|
6
|
+
|
|
7
|
+
- **Every PR must link to an existing issue.** Open an issue to discuss before writing code, then link it from your PR (e.g. `Closes #123`).
|
|
8
|
+
- **AI-generated PRs** will be closed without review if they weren't discussed beforehand.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Discuss before building
|
|
13
|
+
|
|
14
|
+
Our libraries are small and focused by design. We care a lot about keeping it that way. Before you invest time writing code, please open an issue describing:
|
|
15
|
+
|
|
16
|
+
- What problem you're solving
|
|
17
|
+
- Why it belongs in model2vec (as opposed to a wrapper or separate tool)
|
|
18
|
+
- What API or behaviour change it would involve, if any
|
|
19
|
+
- A minimal (code) example of how it would work
|
|
20
|
+
|
|
21
|
+
This applies to small PRs (e.g. bug fixes and documentation updates) as well. A quick issue lets us confirm the fix is wanted and aligned with how we'd want to solve it, so you don't waste time on a PR we'd need to reject or rework.
|
|
22
|
+
|
|
23
|
+
**PRs without a linked issue will be closed.**
|
|
24
|
+
|
|
25
|
+
## What we generally welcome
|
|
26
|
+
|
|
27
|
+
- Bug fixes (with a linked issue and a test that reproduces the issue)
|
|
28
|
+
- Documentation improvements and example fixes (with a linked issue)
|
|
29
|
+
|
|
30
|
+
## What we generally won't accept
|
|
31
|
+
|
|
32
|
+
- Large new features that haven't been discussed
|
|
33
|
+
- Features that significantly expand the scope of the library
|
|
34
|
+
- Dependency additions
|
|
35
|
+
- AI-generated code dumps with no context or discussion
|
|
36
|
+
|
|
37
|
+
## Opening a good issue
|
|
38
|
+
|
|
39
|
+
If you found a bug, include:
|
|
40
|
+
- model2vec version
|
|
41
|
+
- Python version
|
|
42
|
+
- A minimal reproducible example
|
|
43
|
+
- What you expected vs. what happened
|
|
44
|
+
|
|
45
|
+
If you want a feature, include the things listed under "Discuss before building" above.
|
|
46
|
+
|
|
47
|
+
## Pull request checklist
|
|
48
|
+
|
|
49
|
+
Before opening a PR:
|
|
50
|
+
|
|
51
|
+
- [ ] Link to an existing issue (e.g. `Closes #123`). PRs without one will be closed
|
|
52
|
+
- [ ] Run `make test` and confirm all tests pass
|
|
53
|
+
- [ ] Run `make lint` and `make typecheck`
|
|
54
|
+
- [ ] Run `make fix` to auto-fix any lint issues
|
|
55
|
+
- [ ] If you added behaviour, add or update tests
|
|
56
|
+
- [ ] If you changed a public API, update the docstrings
|
|
57
|
+
- [ ] Keep the diff focused (one logical change per PR)
|
|
58
|
+
|
|
59
|
+
You can also run `make pre-commit` to run all checks at once.
|
|
60
|
+
|
|
61
|
+
## Code style
|
|
62
|
+
|
|
63
|
+
- We use `ruff` for formatting and linting
|
|
64
|
+
- We use `mypy` for type checking and expect all new code to be fully typed
|
|
65
|
+
- Keep things simple; we prefer readable over clever
|
|
66
|
+
|
|
67
|
+
## A note on AI-assisted contributions
|
|
68
|
+
|
|
69
|
+
We don't have a blanket policy against AI tools (we also use them ourselves). But we do expect:
|
|
70
|
+
|
|
71
|
+
1. **You understand what you're submitting.** If you ran an agent against the repo and opened a PR with the output, you should be able to explain what it does.
|
|
72
|
+
2. **The contribution was discussed first.** An AI generating code for an agreed-on, well-scoped issue is fine. An AI inventing features and opening a PR is not.
|
|
73
|
+
3. **Tests and quality are your responsibility.** "The AI wrote it" is not a substitute for correctness.
|
|
74
|
+
|
|
75
|
+
PRs that appear to be unreviewed AI output (large scope, multiple unrelated files touched, no prior discussion, new deps) will be closed with a pointer to this document.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
Questions? Open an issue.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
.PHONY: help install install-no-pre-commit install-base test test-integration test-integration-update test-integration-pretrained-update lint typecheck fix pre-commit
|
|
2
|
+
|
|
3
|
+
help:
|
|
4
|
+
@echo "Available targets:"
|
|
5
|
+
@echo " install Install all dependencies and pre-commit hooks"
|
|
6
|
+
@echo " install-no-pre-commit Install all dependencies without pre-commit hooks"
|
|
7
|
+
@echo " install-base Install only the dev dependencies"
|
|
8
|
+
@echo " test Run unit tests with coverage (excludes integration tests)"
|
|
9
|
+
@echo " test-integration Run integration tests"
|
|
10
|
+
@echo " test-integration-update Regenerate the distill integration baseline"
|
|
11
|
+
@echo " test-integration-pretrained-update Regenerate the pretrained integration baseline"
|
|
12
|
+
@echo " lint Run ruff and pydoclint"
|
|
13
|
+
@echo " typecheck Run mypy"
|
|
14
|
+
@echo " fix Auto-fix lint issues and format code"
|
|
15
|
+
@echo " pre-commit Run all pre-commit hooks"
|
|
16
|
+
|
|
17
|
+
install: install-no-pre-commit
|
|
18
|
+
uv run pre-commit install
|
|
19
|
+
|
|
20
|
+
install-no-pre-commit:
|
|
21
|
+
uv sync --all-extras
|
|
22
|
+
|
|
23
|
+
install-base:
|
|
24
|
+
uv sync --extra dev
|
|
25
|
+
|
|
26
|
+
lint:
|
|
27
|
+
uv run ruff check model2vec/ tests/
|
|
28
|
+
uv run pydoclint model2vec/
|
|
29
|
+
|
|
30
|
+
typecheck:
|
|
31
|
+
uv run mypy model2vec/
|
|
32
|
+
|
|
33
|
+
fix:
|
|
34
|
+
uv run ruff check --fix model2vec/ tests/
|
|
35
|
+
uv run ruff format model2vec/ tests/
|
|
36
|
+
|
|
37
|
+
pre-commit:
|
|
38
|
+
uv run pre-commit run --all-files
|
|
39
|
+
|
|
40
|
+
test:
|
|
41
|
+
uv run pytest --cov=model2vec --cov-report=term-missing --ignore=tests/integration $(VERBOSITY)
|
|
42
|
+
|
|
43
|
+
test-integration:
|
|
44
|
+
uv run pytest tests/integration $(VERBOSITY)
|
|
45
|
+
|
|
46
|
+
test-integration-update:
|
|
47
|
+
uv run python -m tests.integration.update_distill_baseline
|
|
48
|
+
|
|
49
|
+
test-integration-pretrained-update:
|
|
50
|
+
uv run python -m tests.integration.update_pretrained_baseline
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.10.0
|
|
4
4
|
Summary: Fast State-of-the-Art Static Embeddings
|
|
5
5
|
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomasvdongen@proton.me>
|
|
6
6
|
License: MIT License
|
|
@@ -48,6 +48,7 @@ Requires-Dist: numpy
|
|
|
48
48
|
Requires-Dist: safetensors
|
|
49
49
|
Requires-Dist: tokenizers>=0.20
|
|
50
50
|
Requires-Dist: tqdm
|
|
51
|
+
Requires-Dist: huggingface-hub>=1.0.0
|
|
51
52
|
Provides-Extra: dev
|
|
52
53
|
Requires-Dist: ipython; extra == "dev"
|
|
53
54
|
Requires-Dist: mypy; extra == "dev"
|
|
@@ -59,21 +60,23 @@ Requires-Dist: setuptools; extra == "dev"
|
|
|
59
60
|
Provides-Extra: distill
|
|
60
61
|
Requires-Dist: torch; extra == "distill"
|
|
61
62
|
Requires-Dist: transformers<5.4.0; extra == "distill"
|
|
62
|
-
Requires-Dist:
|
|
63
|
-
Requires-Dist: skeletoken>=0.3.3; extra == "distill"
|
|
63
|
+
Requires-Dist: skeletoken<0.7.0,>=0.6.0; extra == "distill"
|
|
64
64
|
Provides-Extra: onnx
|
|
65
65
|
Requires-Dist: onnx; extra == "onnx"
|
|
66
66
|
Requires-Dist: torch; extra == "onnx"
|
|
67
|
+
Requires-Dist: onnxruntime; extra == "onnx"
|
|
68
|
+
Requires-Dist: onnxscript; extra == "onnx"
|
|
69
|
+
Requires-Dist: skeletoken<0.7.0,>=0.6.0; extra == "onnx"
|
|
67
70
|
Provides-Extra: train
|
|
68
71
|
Requires-Dist: torch; extra == "train"
|
|
69
|
-
Requires-Dist:
|
|
70
|
-
Requires-Dist: scikit-learn; extra == "train"
|
|
71
|
-
Requires-Dist: skops; extra == "train"
|
|
72
|
-
Provides-Extra: inference
|
|
73
|
-
Requires-Dist: scikit-learn; extra == "inference"
|
|
74
|
-
Requires-Dist: skops; extra == "inference"
|
|
72
|
+
Requires-Dist: datasets>=4.0.0; extra == "train"
|
|
75
73
|
Provides-Extra: quantization
|
|
76
74
|
Requires-Dist: scikit-learn; extra == "quantization"
|
|
75
|
+
Provides-Extra: integration
|
|
76
|
+
Requires-Dist: mteb; extra == "integration"
|
|
77
|
+
Provides-Extra: tests
|
|
78
|
+
Requires-Dist: scikit-learn; extra == "tests"
|
|
79
|
+
Requires-Dist: skops; extra == "tests"
|
|
77
80
|
|
|
78
81
|
|
|
79
82
|
<h2 align="center">
|
|
@@ -83,15 +86,6 @@ Requires-Dist: scikit-learn; extra == "quantization"
|
|
|
83
86
|
|
|
84
87
|
|
|
85
88
|
|
|
86
|
-
<div align="center">
|
|
87
|
-
<h2>
|
|
88
|
-
<a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
|
|
89
|
-
<a href="https://minish.ai/packages/model2vec/introduction"><strong>📖 Docs</strong></a> |
|
|
90
|
-
<a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a> |
|
|
91
|
-
<a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
|
|
92
|
-
<a href="https://minish.ai/blog"><strong>🌐 Blog</strong></a>
|
|
93
|
-
</div>
|
|
94
|
-
|
|
95
89
|
<div align="center">
|
|
96
90
|
<h2>
|
|
97
91
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
|
|
@@ -108,24 +102,17 @@ Requires-Dist: scikit-learn; extra == "quantization"
|
|
|
108
102
|
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
|
|
109
103
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
|
|
110
104
|
</a>
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
</a>
|
|
114
|
-
</h2>
|
|
115
|
-
</div>
|
|
105
|
+
</h2>
|
|
106
|
+
|
|
116
107
|
|
|
117
108
|
|
|
109
|
+
[Quickstart](#quickstart) • [Main Features](#main-features) • [Model List](#model-list) • [Results](#results)
|
|
110
|
+
</div>
|
|
118
111
|
|
|
119
112
|
|
|
120
113
|
|
|
121
114
|
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.
|
|
122
115
|
|
|
123
|
-
<div align="center">
|
|
124
|
-
<h3>
|
|
125
|
-
|
|
126
|
-
[Quickstart](#quickstart) • [Updates & Announcements](#updates--announcements) • [Main Features](#main-features) • [Model List](#model-list)
|
|
127
|
-
</h3>
|
|
128
|
-
</div>
|
|
129
116
|
|
|
130
117
|
## Quickstart
|
|
131
118
|
|
|
@@ -148,7 +135,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
|
|
|
148
135
|
# Make sequences of token embeddings
|
|
149
136
|
token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
150
137
|
```
|
|
151
|
-
For advanced usage, see our [inference docs](https://minish.ai/packages/model2vec/inference). Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. First, install the `
|
|
138
|
+
For advanced usage, see our [inference docs](https://minish.ai/packages/model2vec/inference). Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. First, install the `distill` extra with:
|
|
152
139
|
|
|
153
140
|
```bash
|
|
154
141
|
pip install model2vec[distill]
|
|
@@ -167,7 +154,7 @@ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5")
|
|
|
167
154
|
m2v_model.save_pretrained("m2v_model")
|
|
168
155
|
```
|
|
169
156
|
|
|
170
|
-
For advanced usage, see our [distillation docs](https://minish.ai/packages/model2vec/distillation), which includes some [distillation best practices](https://minish.ai/packages/model2vec/distillation#distillation-best-practices). After distillation, you can also fine-tune
|
|
157
|
+
For advanced usage, see our [distillation docs](https://minish.ai/packages/model2vec/distillation), which includes some [distillation best practices](https://minish.ai/packages/model2vec/distillation#distillation-best-practices). After distillation, you can also fine-tune the distilled model, or a pre-trained model, for classification, similarity, regression, or pair similarity (e.g. query-document retrieval). First, make sure you install the `train` extras with:
|
|
171
158
|
|
|
172
159
|
```bash
|
|
173
160
|
pip install model2vec[train]
|
|
@@ -176,12 +163,11 @@ pip install model2vec[train]
|
|
|
176
163
|
Then, you can fine-tune a model as follows:
|
|
177
164
|
|
|
178
165
|
```python
|
|
179
|
-
import numpy as np
|
|
180
166
|
from datasets import load_dataset
|
|
181
167
|
from model2vec.train import StaticModelForClassification
|
|
182
168
|
|
|
183
169
|
# Initialize a classifier from a pre-trained model
|
|
184
|
-
classifier = StaticModelForClassification.from_pretrained(
|
|
170
|
+
classifier = StaticModelForClassification.from_pretrained(path="minishlab/potion-base-32M")
|
|
185
171
|
|
|
186
172
|
# Load a dataset. Note: both single and multi-label classification datasets are supported
|
|
187
173
|
ds = load_dataset("setfit/subj")
|
|
@@ -195,17 +181,6 @@ classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["labe
|
|
|
195
181
|
|
|
196
182
|
For advanced usage, see our [training docs](https://minish.ai/packages/model2vec/training).
|
|
197
183
|
|
|
198
|
-
## Updates & Announcements
|
|
199
|
-
|
|
200
|
-
- **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.
|
|
201
|
-
|
|
202
|
-
- **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 size, and can be quantized to int8 to be 25% of the size, without loss of performance.
|
|
203
|
-
|
|
204
|
-
- **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).
|
|
205
|
-
|
|
206
|
-
- **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.
|
|
207
|
-
|
|
208
|
-
- **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).
|
|
209
184
|
|
|
210
185
|
## Main Features
|
|
211
186
|
|
|
@@ -214,7 +189,7 @@ For advanced usage, see our [training docs](https://minish.ai/packages/model2vec
|
|
|
214
189
|
- **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
|
|
215
190
|
- **Lightning-fast Inference**: up to 500 times faster on CPU than the original model.
|
|
216
191
|
- **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset.
|
|
217
|
-
- **Fine-tuning**: fine-tune
|
|
192
|
+
- **Fine-tuning**: fine-tune Model2Vec models for classification, similarity, regression, or pair similarity, and run them without `torch`.
|
|
218
193
|
- **Integrated in many popular libraries**: Model2Vec is integrated direclty into popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) and [LangChain](https://github.com/langchain-ai/langchain). For more information, see our [integrations documentation](https://minish.ai/packages/model2vec/integrations).
|
|
219
194
|
- **Tightly integrated with HuggingFace hub**: easily share and load models from the HuggingFace hub, using the familiar `from_pretrained` and `push_to_hub`. Our own models can be found [here](https://huggingface.co/minishlab).
|
|
220
195
|
|
|
@@ -241,9 +216,7 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
241
216
|
| [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M) | Multilingual | [bge-m3](https://huggingface.co/BAAI/bge-m3) | 128M | General |
|
|
242
217
|
| [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 |
|
|
243
218
|
| [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 |
|
|
244
|
-
| [potion-
|
|
245
|
-
| [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 |
|
|
246
|
-
|
|
219
|
+
| [potion-code-16M-v2](https://huggingface.co/minishlab/potion-code-16M-v2) | Code | [CodeRankEmbed](https://huggingface.co/nomic-ai/CodeRankEmbed) | 16.2M | Code |
|
|
247
220
|
|
|
248
221
|
|
|
249
222
|
|
|
@@ -256,6 +229,10 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
|
|
|
256
229
|
- [Training Results](results/README.md#training-results)
|
|
257
230
|
- [Ablations](results/README.md#ablations)
|
|
258
231
|
|
|
232
|
+
## Acknowledgements
|
|
233
|
+
|
|
234
|
+
Thanks to [Greptile](https://greptile.com) for providing free access to their AI code review platform.
|
|
235
|
+
|
|
259
236
|
## License
|
|
260
237
|
|
|
261
238
|
MIT
|
|
@@ -6,15 +6,6 @@
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
<div align="center">
|
|
10
|
-
<h2>
|
|
11
|
-
<a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
|
|
12
|
-
<a href="https://minish.ai/packages/model2vec/introduction"><strong>📖 Docs</strong></a> |
|
|
13
|
-
<a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a> |
|
|
14
|
-
<a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
|
|
15
|
-
<a href="https://minish.ai/blog"><strong>🌐 Blog</strong></a>
|
|
16
|
-
</div>
|
|
17
|
-
|
|
18
9
|
<div align="center">
|
|
19
10
|
<h2>
|
|
20
11
|
<a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
|
|
@@ -31,24 +22,17 @@
|
|
|
31
22
|
<a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
|
|
32
23
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
|
|
33
24
|
</a>
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
</a>
|
|
37
|
-
</h2>
|
|
38
|
-
</div>
|
|
25
|
+
</h2>
|
|
26
|
+
|
|
39
27
|
|
|
40
28
|
|
|
29
|
+
[Quickstart](#quickstart) • [Main Features](#main-features) • [Model List](#model-list) • [Results](#results)
|
|
30
|
+
</div>
|
|
41
31
|
|
|
42
32
|
|
|
43
33
|
|
|
44
34
|
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
35
|
|
|
46
|
-
<div align="center">
|
|
47
|
-
<h3>
|
|
48
|
-
|
|
49
|
-
[Quickstart](#quickstart) • [Updates & Announcements](#updates--announcements) • [Main Features](#main-features) • [Model List](#model-list)
|
|
50
|
-
</h3>
|
|
51
|
-
</div>
|
|
52
36
|
|
|
53
37
|
## Quickstart
|
|
54
38
|
|
|
@@ -71,7 +55,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
|
|
|
71
55
|
# Make sequences of token embeddings
|
|
72
56
|
token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
|
|
73
57
|
```
|
|
74
|
-
For advanced usage, see our [inference docs](https://minish.ai/packages/model2vec/inference). Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. First, install the `
|
|
58
|
+
For advanced usage, see our [inference docs](https://minish.ai/packages/model2vec/inference). Instead of using one of our models, you can also distill your own Model2Vec model from a Sentence Transformer model. First, install the `distill` extra with:
|
|
75
59
|
|
|
76
60
|
```bash
|
|
77
61
|
pip install model2vec[distill]
|
|
@@ -90,7 +74,7 @@ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5")
|
|
|
90
74
|
m2v_model.save_pretrained("m2v_model")
|
|
91
75
|
```
|
|
92
76
|
|
|
93
|
-
For advanced usage, see our [distillation docs](https://minish.ai/packages/model2vec/distillation), which includes some [distillation best practices](https://minish.ai/packages/model2vec/distillation#distillation-best-practices). After distillation, you can also fine-tune
|
|
77
|
+
For advanced usage, see our [distillation docs](https://minish.ai/packages/model2vec/distillation), which includes some [distillation best practices](https://minish.ai/packages/model2vec/distillation#distillation-best-practices). After distillation, you can also fine-tune the distilled model, or a pre-trained model, for classification, similarity, regression, or pair similarity (e.g. query-document retrieval). First, make sure you install the `train` extras with:
|
|
94
78
|
|
|
95
79
|
```bash
|
|
96
80
|
pip install model2vec[train]
|
|
@@ -99,12 +83,11 @@ pip install model2vec[train]
|
|
|
99
83
|
Then, you can fine-tune a model as follows:
|
|
100
84
|
|
|
101
85
|
```python
|
|
102
|
-
import numpy as np
|
|
103
86
|
from datasets import load_dataset
|
|
104
87
|
from model2vec.train import StaticModelForClassification
|
|
105
88
|
|
|
106
89
|
# Initialize a classifier from a pre-trained model
|
|
107
|
-
classifier = StaticModelForClassification.from_pretrained(
|
|
90
|
+
classifier = StaticModelForClassification.from_pretrained(path="minishlab/potion-base-32M")
|
|
108
91
|
|
|
109
92
|
# Load a dataset. Note: both single and multi-label classification datasets are supported
|
|
110
93
|
ds = load_dataset("setfit/subj")
|
|
@@ -118,17 +101,6 @@ classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["labe
|
|
|
118
101
|
|
|
119
102
|
For advanced usage, see our [training docs](https://minish.ai/packages/model2vec/training).
|
|
120
103
|
|
|
121
|
-
## Updates & Announcements
|
|
122
|
-
|
|
123
|
-
- **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.
|
|
124
|
-
|
|
125
|
-
- **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 size, and can be quantized to int8 to be 25% of the size, without loss of performance.
|
|
126
|
-
|
|
127
|
-
- **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).
|
|
128
|
-
|
|
129
|
-
- **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.
|
|
130
|
-
|
|
131
|
-
- **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).
|
|
132
104
|
|
|
133
105
|
## Main Features
|
|
134
106
|
|
|
@@ -137,7 +109,7 @@ For advanced usage, see our [training docs](https://minish.ai/packages/model2vec
|
|
|
137
109
|
- **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
|
|
138
110
|
- **Lightning-fast Inference**: up to 500 times faster on CPU than the original model.
|
|
139
111
|
- **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset.
|
|
140
|
-
- **Fine-tuning**: fine-tune
|
|
112
|
+
- **Fine-tuning**: fine-tune Model2Vec models for classification, similarity, regression, or pair similarity, and run them without `torch`.
|
|
141
113
|
- **Integrated in many popular libraries**: Model2Vec is integrated direclty into popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) and [LangChain](https://github.com/langchain-ai/langchain). For more information, see our [integrations documentation](https://minish.ai/packages/model2vec/integrations).
|
|
142
114
|
- **Tightly integrated with HuggingFace hub**: easily share and load models from the HuggingFace hub, using the familiar `from_pretrained` and `push_to_hub`. Our own models can be found [here](https://huggingface.co/minishlab).
|
|
143
115
|
|
|
@@ -164,9 +136,7 @@ We provide a number of models that can be used out of the box. These models are
|
|
|
164
136
|
| [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M) | Multilingual | [bge-m3](https://huggingface.co/BAAI/bge-m3) | 128M | General |
|
|
165
137
|
| [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 |
|
|
166
138
|
| [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 |
|
|
167
|
-
| [potion-
|
|
168
|
-
| [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 |
|
|
169
|
-
|
|
139
|
+
| [potion-code-16M-v2](https://huggingface.co/minishlab/potion-code-16M-v2) | Code | [CodeRankEmbed](https://huggingface.co/nomic-ai/CodeRankEmbed) | 16.2M | Code |
|
|
170
140
|
|
|
171
141
|
|
|
172
142
|
|
|
@@ -179,6 +149,10 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
|
|
|
179
149
|
- [Training Results](results/README.md#training-results)
|
|
180
150
|
- [Ablations](results/README.md#ablations)
|
|
181
151
|
|
|
152
|
+
## Acknowledgements
|
|
153
|
+
|
|
154
|
+
Thanks to [Greptile](https://greptile.com) for providing free access to their AI code review platform.
|
|
155
|
+
|
|
182
156
|
## License
|
|
183
157
|
|
|
184
158
|
MIT
|
|
@@ -3,7 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
import logging
|
|
4
4
|
import os
|
|
5
5
|
import re
|
|
6
|
-
from typing import cast
|
|
6
|
+
from typing import Sequence, cast
|
|
7
7
|
|
|
8
8
|
from huggingface_hub.hf_api import model_info
|
|
9
9
|
from skeletoken import TokenizerModel
|
|
@@ -16,6 +16,7 @@ from model2vec.distill.utils import select_optimal_device
|
|
|
16
16
|
from model2vec.model import StaticModel
|
|
17
17
|
from model2vec.quantization import DType, quantize_embeddings
|
|
18
18
|
from model2vec.tokenizer import clean_and_create_vocabulary, turn_tokens_into_ids
|
|
19
|
+
from model2vec.types import StaticModelConfig
|
|
19
20
|
from model2vec.vocabulary_quantization import quantize_vocabulary
|
|
20
21
|
|
|
21
22
|
logger = logging.getLogger(__name__)
|
|
@@ -24,7 +25,7 @@ logger = logging.getLogger(__name__)
|
|
|
24
25
|
def distill_from_model(
|
|
25
26
|
model: PreTrainedModel,
|
|
26
27
|
tokenizer: PreTrainedTokenizerFast,
|
|
27
|
-
vocabulary:
|
|
28
|
+
vocabulary: Sequence[str] | None = None,
|
|
28
29
|
device: str | None = None,
|
|
29
30
|
pca_dims: PCADimType = 256,
|
|
30
31
|
sif_coefficient: float | None = 1e-4,
|
|
@@ -125,7 +126,7 @@ def distill_from_model(
|
|
|
125
126
|
|
|
126
127
|
model_name = getattr(model, "name_or_path", "")
|
|
127
128
|
|
|
128
|
-
config = {
|
|
129
|
+
config: StaticModelConfig = {
|
|
129
130
|
"model_type": "model2vec",
|
|
130
131
|
"architectures": ["StaticModel"],
|
|
131
132
|
"tokenizer_name": model_name,
|
|
@@ -4,11 +4,10 @@ import inspect
|
|
|
4
4
|
import logging
|
|
5
5
|
from enum import Enum
|
|
6
6
|
from pathlib import Path
|
|
7
|
-
from typing import Literal
|
|
7
|
+
from typing import Literal, cast
|
|
8
8
|
|
|
9
9
|
import numpy as np
|
|
10
10
|
import torch
|
|
11
|
-
from sklearn.decomposition import PCA
|
|
12
11
|
from torch.nn.utils.rnn import pad_sequence
|
|
13
12
|
from tqdm import tqdm
|
|
14
13
|
from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
|
|
@@ -211,18 +210,59 @@ def compute_weights(n_embeddings: int, sif_coefficient: float | None) -> np.ndar
|
|
|
211
210
|
return weight
|
|
212
211
|
|
|
213
212
|
|
|
213
|
+
def _pca_fit_transform(X: np.ndarray, n_components: int | float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
214
|
+
"""Fit a PCA via eigendecomposition of the covariance matrix, and transform X.
|
|
215
|
+
|
|
216
|
+
:param X: The data matrix of shape (n_samples, n_features).
|
|
217
|
+
:param n_components: The number of components to keep, or, if a float between 0 and 1, the minimum
|
|
218
|
+
amount of variance that should be explained by the kept components.
|
|
219
|
+
:return: A tuple of (transformed X, explained_variance, explained_variance_ratio).
|
|
220
|
+
"""
|
|
221
|
+
n_samples = X.shape[0]
|
|
222
|
+
mean = X.mean(axis=0)
|
|
223
|
+
Xc = X - mean
|
|
224
|
+
|
|
225
|
+
cov = (Xc.T @ Xc) / (n_samples - 1)
|
|
226
|
+
|
|
227
|
+
eigvals, eigvecs = np.linalg.eigh(cov)
|
|
228
|
+
eigvals = eigvals[::-1]
|
|
229
|
+
eigvecs = eigvecs[:, ::-1]
|
|
230
|
+
eigvals = np.clip(eigvals, a_min=0, a_max=None)
|
|
231
|
+
|
|
232
|
+
total_variance = eigvals.sum()
|
|
233
|
+
if isinstance(n_components, float):
|
|
234
|
+
explained_variance_ratio_cumsum = np.cumsum(eigvals) / total_variance
|
|
235
|
+
k = int(np.searchsorted(explained_variance_ratio_cumsum, n_components)) + 1
|
|
236
|
+
k = min(k, eigvecs.shape[1])
|
|
237
|
+
else:
|
|
238
|
+
k = n_components
|
|
239
|
+
|
|
240
|
+
components = eigvecs[:, :k].T
|
|
241
|
+
explained_variance = eigvals[:k]
|
|
242
|
+
explained_variance_ratio = explained_variance / total_variance
|
|
243
|
+
|
|
244
|
+
scores = Xc @ components.T
|
|
245
|
+
|
|
246
|
+
max_abs_idx = np.argmax(np.abs(scores), axis=0)
|
|
247
|
+
signs = np.sign(scores[max_abs_idx, range(scores.shape[1])])
|
|
248
|
+
scores = scores * signs
|
|
249
|
+
|
|
250
|
+
return scores, explained_variance, explained_variance_ratio
|
|
251
|
+
|
|
252
|
+
|
|
214
253
|
def apply_pca(embeddings: np.ndarray, pca_dims: PCADimType) -> np.ndarray:
|
|
215
254
|
"""Apply PCA to the embeddings."""
|
|
216
255
|
if pca_dims is not None:
|
|
217
|
-
|
|
218
|
-
|
|
256
|
+
n_features: int = embeddings.shape[1]
|
|
257
|
+
pca_dims = n_features if pca_dims == "auto" else pca_dims
|
|
258
|
+
pca_dims = cast(int | float, pca_dims)
|
|
219
259
|
if pca_dims > embeddings.shape[1]:
|
|
220
260
|
logger.warning(
|
|
221
261
|
f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). "
|
|
222
262
|
"Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. "
|
|
223
263
|
"Applying PCA will probably improve performance, so consider just leaving it."
|
|
224
264
|
)
|
|
225
|
-
pca_dims =
|
|
265
|
+
pca_dims = n_features
|
|
226
266
|
if pca_dims >= embeddings.shape[0]:
|
|
227
267
|
logger.warning(
|
|
228
268
|
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
|
|
@@ -234,14 +274,11 @@ def apply_pca(embeddings: np.ndarray, pca_dims: PCADimType) -> np.ndarray:
|
|
|
234
274
|
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
235
275
|
|
|
236
276
|
orig_dims = embeddings.shape[1]
|
|
237
|
-
|
|
238
|
-
embeddings = p.fit_transform(embeddings)
|
|
277
|
+
embeddings, explained_variance, explained_variance_ratio = _pca_fit_transform(embeddings, pca_dims)
|
|
239
278
|
|
|
240
279
|
if embeddings.shape[1] < orig_dims:
|
|
241
|
-
explained_variance_ratio = np.sum(p.explained_variance_ratio_)
|
|
242
|
-
explained_variance = np.sum(p.explained_variance_)
|
|
243
280
|
logger.info(f"Reduced dimensionality from {orig_dims} to {embeddings.shape[1]}.")
|
|
244
|
-
logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
|
|
245
|
-
logger.info(f"Explained variance: {explained_variance:.3f}.")
|
|
281
|
+
logger.info(f"Explained variance ratio: {np.sum(explained_variance_ratio):.3f}.")
|
|
282
|
+
logger.info(f"Explained variance: {np.sum(explained_variance):.3f}.")
|
|
246
283
|
|
|
247
284
|
return embeddings
|