model2vec 0.9.0__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.
Files changed (115) hide show
  1. {model2vec-0.9.0 → model2vec-0.10.0}/.pre-commit-config.yaml +7 -3
  2. model2vec-0.10.0/CONTRIBUTING.md +79 -0
  3. model2vec-0.10.0/Makefile +50 -0
  4. {model2vec-0.9.0 → model2vec-0.10.0}/PKG-INFO +20 -42
  5. {model2vec-0.9.0 → model2vec-0.10.0}/README.md +13 -39
  6. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/distill/distillation.py +4 -3
  7. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/distill/inference.py +48 -11
  8. model2vec-0.10.0/model2vec/inference/README.md +104 -0
  9. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/inference/evaluation.py +3 -2
  10. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/inference/mlp.py +3 -1
  11. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/inference/model.py +14 -11
  12. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/model.py +223 -148
  13. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/modelcards/modelcards.py +3 -1
  14. model2vec-0.10.0/model2vec/modelcards/onnx_classifier_template.md +58 -0
  15. model2vec-0.10.0/model2vec/modelcards/onnx_model_card_template.md +58 -0
  16. model2vec-0.10.0/model2vec/onnx.py +343 -0
  17. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/persistence/datamodels.py +9 -0
  18. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/persistence/persistence.py +35 -10
  19. model2vec-0.10.0/model2vec/persistence/utils.py +10 -0
  20. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/tokenizer/tokenizer.py +26 -4
  21. model2vec-0.10.0/model2vec/train/README.md +307 -0
  22. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/train/__init__.py +7 -1
  23. model2vec-0.10.0/model2vec/train/base.py +598 -0
  24. model2vec-0.10.0/model2vec/train/classifier.py +520 -0
  25. model2vec-0.10.0/model2vec/train/dataset.py +369 -0
  26. model2vec-0.10.0/model2vec/train/pairs.py +357 -0
  27. model2vec-0.10.0/model2vec/train/similarity.py +265 -0
  28. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/train/trainer.py +28 -16
  29. model2vec-0.10.0/model2vec/train/utils.py +131 -0
  30. model2vec-0.10.0/model2vec/types.py +28 -0
  31. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/version.py +1 -1
  32. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/PKG-INFO +20 -42
  33. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/SOURCES.txt +16 -5
  34. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/requires.txt +6 -2
  35. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/scm_file_list.json +79 -68
  36. model2vec-0.10.0/model2vec.egg-info/scm_version.json +8 -0
  37. {model2vec-0.9.0 → model2vec-0.10.0}/pyproject.toml +4 -3
  38. {model2vec-0.9.0 → model2vec-0.10.0}/results/README.md +52 -48
  39. {model2vec-0.9.0 → model2vec-0.10.0}/tests/conftest.py +35 -4
  40. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/data/Alibaba-NLP___gte-modernbert-base_baseline.json +8 -8
  41. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/data/baai___bge-base-en-v1.5_baseline.json +7 -7
  42. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/data/google___embeddinggemma-300m_baseline.json +10 -10
  43. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/data/intfloat___multilingual-e5-base_baseline.json +11 -11
  44. model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-base-32m_baseline.json +74 -0
  45. model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-base-8m_baseline.json +74 -0
  46. model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-multilingual-128m_baseline.json +178 -0
  47. model2vec-0.10.0/tests/integration/data/pretrained/minishlab___potion-retrieval-32m_baseline.json +74 -0
  48. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/data/sentence-transformers___all-MiniLM-L6-v2_baseline.json +19 -19
  49. model2vec-0.10.0/tests/integration/pretrained_model_metrics.py +102 -0
  50. model2vec-0.10.0/tests/integration/test_onnx_export.py +80 -0
  51. model2vec-0.10.0/tests/integration/test_pretrained_model_regression.py +160 -0
  52. model2vec-0.10.0/tests/integration/update_pretrained_baseline.py +41 -0
  53. {model2vec-0.9.0 → model2vec-0.10.0}/tests/test_distillation.py +4 -0
  54. model2vec-0.10.0/tests/test_export_to_onnx.py +355 -0
  55. {model2vec-0.9.0 → model2vec-0.10.0}/tests/test_inference.py +69 -6
  56. {model2vec-0.9.0 → model2vec-0.10.0}/tests/test_model.py +70 -22
  57. {model2vec-0.9.0 → model2vec-0.10.0}/tests/test_persistence.py +38 -0
  58. model2vec-0.10.0/tests/test_trainable.py +1804 -0
  59. {model2vec-0.9.0 → model2vec-0.10.0}/tests/test_utils.py +1 -1
  60. {model2vec-0.9.0 → model2vec-0.10.0}/uv.lock +156 -13
  61. model2vec-0.9.0/Makefile +0 -29
  62. model2vec-0.9.0/model2vec/inference/README.md +0 -31
  63. model2vec-0.9.0/model2vec/train/README.md +0 -145
  64. model2vec-0.9.0/model2vec/train/base.py +0 -415
  65. model2vec-0.9.0/model2vec/train/classifier.py +0 -296
  66. model2vec-0.9.0/model2vec/train/dataset.py +0 -39
  67. model2vec-0.9.0/model2vec/train/similarity.py +0 -132
  68. model2vec-0.9.0/model2vec/train/utils.py +0 -135
  69. model2vec-0.9.0/model2vec.egg-info/scm_version.json +0 -8
  70. model2vec-0.9.0/scripts/export_to_onnx.py +0 -205
  71. model2vec-0.9.0/tests/test_trainable.py +0 -512
  72. model2vec-0.9.0/tutorials/README.md +0 -16
  73. model2vec-0.9.0/tutorials/recipe_search.ipynb +0 -500
  74. model2vec-0.9.0/tutorials/semantic_chunking.ipynb +0 -268
  75. model2vec-0.9.0/tutorials/train_classifier.ipynb +0 -806
  76. {model2vec-0.9.0 → model2vec-0.10.0}/.github/workflows/ci.yaml +0 -0
  77. {model2vec-0.9.0 → model2vec-0.10.0}/.github/workflows/release.yaml +0 -0
  78. {model2vec-0.9.0 → model2vec-0.10.0}/.gitignore +0 -0
  79. {model2vec-0.9.0 → model2vec-0.10.0}/CITATION.cff +0 -0
  80. {model2vec-0.9.0 → model2vec-0.10.0}/LICENSE +0 -0
  81. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/logo_v2.png +0 -0
  82. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/model2vec_logo.png +0 -0
  83. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/speed_vs_mteb_plot.png +0 -0
  84. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  85. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/training_speed_vs_score.png +0 -0
  86. {model2vec-0.9.0 → model2vec-0.10.0}/assets/images/tutorial_ezlo.png +0 -0
  87. {model2vec-0.9.0 → model2vec-0.10.0}/docs/README.md +0 -0
  88. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/__init__.py +0 -0
  89. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/distill/__init__.py +0 -0
  90. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/distill/utils.py +0 -0
  91. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/inference/__init__.py +0 -0
  92. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/modelcards/__init__.py +0 -0
  93. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/modelcards/classifier_template.md +0 -0
  94. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/modelcards/model_card_template.md +0 -0
  95. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/persistence/__init__.py +0 -0
  96. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/persistence/hf.py +0 -0
  97. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/py.typed +0 -0
  98. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/quantization.py +0 -0
  99. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/tokenizer/__init__.py +0 -0
  100. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/train/regression.py +0 -0
  101. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/utils.py +0 -0
  102. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec/vocabulary_quantization.py +0 -0
  103. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/dependency_links.txt +0 -0
  104. {model2vec-0.9.0 → model2vec-0.10.0}/model2vec.egg-info/top_level.txt +0 -0
  105. {model2vec-0.9.0 → model2vec-0.10.0}/results/make_speed_vs_mteb_plot.py +0 -0
  106. {model2vec-0.9.0 → model2vec-0.10.0}/setup.cfg +0 -0
  107. {model2vec-0.9.0 → model2vec-0.10.0}/tests/__init__.py +0 -0
  108. {model2vec-0.9.0 → model2vec-0.10.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  109. {model2vec-0.9.0 → model2vec-0.10.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
  110. {model2vec-0.9.0 → model2vec-0.10.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  111. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/__init__.py +0 -0
  112. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/distill_metrics.py +0 -0
  113. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/test_distill_regression.py +0 -0
  114. {model2vec-0.9.0 → model2vec-0.10.0}/tests/integration/update_distill_baseline.py +0 -0
  115. {model2vec-0.9.0 → 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: https://github.com/pre-commit/mirrors-mypy
34
- rev: v1.15.0
33
+ - repo: local
35
34
  hooks:
36
35
  - id: mypy
37
- additional_dependencies: []
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.9.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,13 +60,16 @@ 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: scikit-learn; extra == "distill"
63
- Requires-Dist: skeletoken<0.5.0,>=0.4.1; 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"
72
+ Requires-Dist: datasets>=4.0.0; extra == "train"
69
73
  Provides-Extra: quantization
70
74
  Requires-Dist: scikit-learn; extra == "quantization"
71
75
  Provides-Extra: integration
@@ -82,15 +86,6 @@ Requires-Dist: skops; extra == "tests"
82
86
 
83
87
 
84
88
 
85
- <div align="center">
86
- <h2>
87
- <a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
88
- <a href="https://minish.ai/packages/model2vec/introduction"><strong>📖 Docs</strong></a> |
89
- <a href="https://github.com/MinishLab/model2vec/blob/main/results/README.md"><strong>🏆 Results</strong></a> |
90
- <a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
91
- <a href="https://minish.ai/blog"><strong>🌐 Blog</strong></a>
92
- </div>
93
-
94
89
  <div align="center">
95
90
  <h2>
96
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>
@@ -107,24 +102,17 @@ Requires-Dist: skops; extra == "tests"
107
102
  <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE">
108
103
  <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
109
104
  </a>
110
- <a href="https://github.com/MinishLab/model2vec/stargazers">
111
- <img src="https://img.shields.io/github/stars/minishlab/model2vec.svg" alt=Stars">
112
- </a>
113
- </h2>
114
- </div>
105
+ </h2>
106
+
115
107
 
116
108
 
109
+ [Quickstart](#quickstart) • [Main Features](#main-features) • [Model List](#model-list) • [Results](#results)
110
+ </div>
117
111
 
118
112
 
119
113
 
120
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.
121
115
 
122
- <div align="center">
123
- <h3>
124
-
125
- [Quickstart](#quickstart) • [Updates & Announcements](#updates--announcements) • [Main Features](#main-features) • [Model List](#model-list)
126
- </h3>
127
- </div>
128
116
 
129
117
  ## Quickstart
130
118
 
@@ -147,7 +135,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
147
135
  # Make sequences of token embeddings
148
136
  token_embeddings = model.encode_as_sequence(["It's dangerous to go alone!", "It's a secret to everybody."])
149
137
  ```
150
- 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 `distillation` extras with:
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:
151
139
 
152
140
  ```bash
153
141
  pip install model2vec[distill]
@@ -166,7 +154,7 @@ m2v_model = distill(model_name="BAAI/bge-base-en-v1.5")
166
154
  m2v_model.save_pretrained("m2v_model")
167
155
  ```
168
156
 
169
- 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 your own classification models on top of the distilled model, or on a pre-trained model. First, make sure you install the `training` extras with:
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:
170
158
 
171
159
  ```bash
172
160
  pip install model2vec[train]
@@ -175,12 +163,11 @@ pip install model2vec[train]
175
163
  Then, you can fine-tune a model as follows:
176
164
 
177
165
  ```python
178
- import numpy as np
179
166
  from datasets import load_dataset
180
167
  from model2vec.train import StaticModelForClassification
181
168
 
182
169
  # Initialize a classifier from a pre-trained model
183
- classifier = StaticModelForClassification.from_pretrained(model_name="minishlab/potion-base-32M")
170
+ classifier = StaticModelForClassification.from_pretrained(path="minishlab/potion-base-32M")
184
171
 
185
172
  # Load a dataset. Note: both single and multi-label classification datasets are supported
186
173
  ds = load_dataset("setfit/subj")
@@ -194,17 +181,6 @@ classification_report = classifier.evaluate(ds["test"]["text"], ds["test"]["labe
194
181
 
195
182
  For advanced usage, see our [training docs](https://minish.ai/packages/model2vec/training).
196
183
 
197
- ## Updates & Announcements
198
-
199
- - **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.
200
-
201
- - **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.
202
-
203
- - **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).
204
-
205
- - **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
-
207
- - **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
184
 
209
185
  ## Main Features
210
186
 
@@ -213,7 +189,7 @@ For advanced usage, see our [training docs](https://minish.ai/packages/model2vec
213
189
  - **Lightweight Dependencies**: the base package's only major dependency is `numpy`.
214
190
  - **Lightning-fast Inference**: up to 500 times faster on CPU than the original model.
215
191
  - **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset.
216
- - **Fine-tuning**: fine-tune your own classification models on top of Model2Vec models.
192
+ - **Fine-tuning**: fine-tune Model2Vec models for classification, similarity, regression, or pair similarity, and run them without `torch`.
217
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).
218
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).
219
195
 
@@ -240,9 +216,7 @@ We provide a number of models that can be used out of the box. These models are
240
216
  | [potion-multilingual-128M](https://huggingface.co/minishlab/potion-multilingual-128M) | Multilingual | [bge-m3](https://huggingface.co/BAAI/bge-m3) | 128M | General |
241
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 |
242
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 |
243
- | [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 |
244
- | [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 |
245
-
219
+ | [potion-code-16M-v2](https://huggingface.co/minishlab/potion-code-16M-v2) | Code | [CodeRankEmbed](https://huggingface.co/nomic-ai/CodeRankEmbed) | 16.2M | Code |
246
220
 
247
221
 
248
222
 
@@ -255,6 +229,10 @@ We have performed extensive experiments to evaluate the performance of Model2Vec
255
229
  - [Training Results](results/README.md#training-results)
256
230
  - [Ablations](results/README.md#ablations)
257
231
 
232
+ ## Acknowledgements
233
+
234
+ Thanks to [Greptile](https://greptile.com) for providing free access to their AI code review platform.
235
+
258
236
  ## License
259
237
 
260
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
- <a href="https://github.com/MinishLab/model2vec/stargazers">
35
- <img src="https://img.shields.io/github/stars/minishlab/model2vec.svg" alt=Stars">
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 `distillation` extras with:
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 your own classification models on top of the distilled model, or on a pre-trained model. First, make sure you install the `training` extras with:
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(model_name="minishlab/potion-base-32M")
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 your own classification models on top of Model2Vec models.
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-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 |
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: list[str] | None = None,
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
- if pca_dims == "auto":
218
- pca_dims = embeddings.shape[1]
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 = embeddings.shape[1]
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
- p = PCA(n_components=pca_dims, svd_solver="full")
238
- embeddings = np.ascontiguousarray(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