model2vec 0.8.1__tar.gz → 0.9.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.1 → model2vec-0.9.0}/.github/workflows/ci.yaml +6 -6
- model2vec-0.9.0/.github/workflows/release.yaml +40 -0
- model2vec-0.9.0/.pre-commit-config.yaml +37 -0
- model2vec-0.9.0/Makefile +29 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/PKG-INFO +9 -12
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/distill/distillation.py +15 -23
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/distill/inference.py +25 -31
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/distill/utils.py +1 -2
- model2vec-0.9.0/model2vec/inference/README.md +31 -0
- model2vec-0.9.0/model2vec/inference/__init__.py +4 -0
- model2vec-0.9.0/model2vec/inference/evaluation.py +113 -0
- model2vec-0.9.0/model2vec/inference/mlp.py +79 -0
- model2vec-0.9.0/model2vec/inference/model.py +365 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/model.py +12 -22
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/modelcards/modelcards.py +1 -2
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/persistence/hf.py +2 -4
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/persistence/persistence.py +5 -7
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/quantization.py +2 -4
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/tokenizer/tokenizer.py +26 -6
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/train/README.md +7 -13
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/train/__init__.py +3 -1
- model2vec-0.9.0/model2vec/train/base.py +415 -0
- model2vec-0.9.0/model2vec/train/classifier.py +296 -0
- model2vec-0.9.0/model2vec/train/dataset.py +39 -0
- model2vec-0.9.0/model2vec/train/regression.py +16 -0
- model2vec-0.9.0/model2vec/train/similarity.py +132 -0
- model2vec-0.9.0/model2vec/train/trainer.py +194 -0
- model2vec-0.9.0/model2vec/train/utils.py +135 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/utils.py +1 -14
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/version.py +1 -1
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec.egg-info/PKG-INFO +9 -12
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec.egg-info/SOURCES.txt +18 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec.egg-info/requires.txt +8 -10
- model2vec-0.9.0/model2vec.egg-info/scm_file_list.json +84 -0
- model2vec-0.9.0/model2vec.egg-info/scm_version.json +8 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/pyproject.toml +12 -10
- {model2vec-0.8.1 → model2vec-0.9.0}/scripts/export_to_onnx.py +4 -9
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/conftest.py +49 -3
- model2vec-0.9.0/tests/integration/__init__.py +0 -0
- model2vec-0.9.0/tests/integration/data/Alibaba-NLP___gte-modernbert-base_baseline.json +91 -0
- model2vec-0.9.0/tests/integration/data/baai___bge-base-en-v1.5_baseline.json +91 -0
- model2vec-0.9.0/tests/integration/data/google___embeddinggemma-300m_baseline.json +91 -0
- model2vec-0.9.0/tests/integration/data/intfloat___multilingual-e5-base_baseline.json +91 -0
- model2vec-0.9.0/tests/integration/data/sentence-transformers___all-MiniLM-L6-v2_baseline.json +91 -0
- model2vec-0.9.0/tests/integration/distill_metrics.py +123 -0
- model2vec-0.9.0/tests/integration/test_distill_regression.py +145 -0
- model2vec-0.9.0/tests/integration/update_distill_baseline.py +47 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_distillation.py +46 -5
- model2vec-0.9.0/tests/test_inference.py +333 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_persistence.py +32 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_trainable.py +238 -9
- {model2vec-0.8.1 → model2vec-0.9.0}/uv.lock +1154 -582
- model2vec-0.8.1/.pre-commit-config.yaml +0 -36
- model2vec-0.8.1/Makefile +0 -21
- model2vec-0.8.1/model2vec/inference/README.md +0 -18
- model2vec-0.8.1/model2vec/inference/__init__.py +0 -10
- model2vec-0.8.1/model2vec/inference/model.py +0 -316
- model2vec-0.8.1/model2vec/train/base.py +0 -207
- model2vec-0.8.1/model2vec/train/classifier.py +0 -463
- model2vec-0.8.1/model2vec/train/utils.py +0 -21
- model2vec-0.8.1/tests/test_inference.py +0 -88
- {model2vec-0.8.1 → model2vec-0.9.0}/.gitignore +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/CITATION.cff +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/LICENSE +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/README.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/logo_v2.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/model2vec_logo.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/speed_vs_mteb_plot.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/training_speed_vs_score.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/docs/README.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/modelcards/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/modelcards/classifier_template.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/modelcards/model_card_template.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/persistence/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/persistence/datamodels.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/py.typed +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/tokenizer/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec/vocabulary_quantization.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/results/README.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/results/make_speed_vs_mteb_plot.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/setup.cfg +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/__init__.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_model.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_quantization.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tests/test_utils.py +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tutorials/README.md +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tutorials/recipe_search.ipynb +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tutorials/semantic_chunking.ipynb +0 -0
- {model2vec-0.8.1 → model2vec-0.9.0}/tutorials/train_classifier.ipynb +0 -0
|
@@ -14,19 +14,19 @@ jobs:
|
|
|
14
14
|
fail-fast: false
|
|
15
15
|
matrix:
|
|
16
16
|
os: ["ubuntu-latest", "windows-latest"]
|
|
17
|
-
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
17
|
+
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
|
|
18
18
|
|
|
19
19
|
steps:
|
|
20
|
-
- uses: actions/checkout@
|
|
20
|
+
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
|
|
21
21
|
|
|
22
22
|
- name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
|
|
23
|
-
uses: actions/setup-python@
|
|
23
|
+
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
|
|
24
24
|
with:
|
|
25
25
|
python-version: ${{ matrix.python-version }}
|
|
26
26
|
allow-prereleases: true
|
|
27
27
|
|
|
28
28
|
- name: Install uv
|
|
29
|
-
uses: astral-sh/setup-uv@
|
|
29
|
+
uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff
|
|
30
30
|
|
|
31
31
|
- name: Create virtual environment
|
|
32
32
|
run: uv venv .venv
|
|
@@ -50,10 +50,10 @@ jobs:
|
|
|
50
50
|
- name: Run tests under coverage
|
|
51
51
|
shell: bash
|
|
52
52
|
run: |
|
|
53
|
-
coverage run --source=model2vec -m pytest
|
|
53
|
+
coverage run --source=model2vec -m pytest --ignore=tests/integration
|
|
54
54
|
coverage report
|
|
55
55
|
|
|
56
56
|
- name: Upload results to Codecov
|
|
57
|
-
uses: codecov/codecov-action@
|
|
57
|
+
uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238
|
|
58
58
|
with:
|
|
59
59
|
token: ${{ secrets.CODECOV_TOKEN }}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
name: Release to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
workflow_dispatch:
|
|
5
|
+
|
|
6
|
+
jobs:
|
|
7
|
+
build:
|
|
8
|
+
name: Build distribution
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
|
|
12
|
+
|
|
13
|
+
- name: Install uv
|
|
14
|
+
uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff
|
|
15
|
+
|
|
16
|
+
- name: Build package
|
|
17
|
+
run: uv build
|
|
18
|
+
|
|
19
|
+
- name: Upload dist
|
|
20
|
+
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
|
|
21
|
+
with:
|
|
22
|
+
name: dist
|
|
23
|
+
path: dist/
|
|
24
|
+
|
|
25
|
+
publish:
|
|
26
|
+
name: Publish to PyPI
|
|
27
|
+
needs: build
|
|
28
|
+
runs-on: ubuntu-latest
|
|
29
|
+
environment: release
|
|
30
|
+
permissions:
|
|
31
|
+
id-token: write
|
|
32
|
+
steps:
|
|
33
|
+
- name: Download dist
|
|
34
|
+
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
|
|
35
|
+
with:
|
|
36
|
+
name: dist
|
|
37
|
+
path: dist/
|
|
38
|
+
|
|
39
|
+
- name: Publish to PyPI
|
|
40
|
+
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
minimum_pre_commit_version: "3.2.0"
|
|
2
|
+
|
|
3
|
+
default_language_version:
|
|
4
|
+
python: python3
|
|
5
|
+
|
|
6
|
+
repos:
|
|
7
|
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
8
|
+
rev: v6.0.0
|
|
9
|
+
hooks:
|
|
10
|
+
- id: no-commit-to-branch
|
|
11
|
+
args: [--branch, main]
|
|
12
|
+
- id: check-ast
|
|
13
|
+
- id: check-yaml
|
|
14
|
+
- id: check-toml
|
|
15
|
+
- id: check-json
|
|
16
|
+
- id: check-merge-conflict
|
|
17
|
+
- id: debug-statements
|
|
18
|
+
- id: trailing-whitespace
|
|
19
|
+
- id: end-of-file-fixer
|
|
20
|
+
- id: check-added-large-files
|
|
21
|
+
args: ["--maxkb=5000"]
|
|
22
|
+
- id: check-case-conflict
|
|
23
|
+
- repo: https://github.com/jsh9/pydoclint
|
|
24
|
+
rev: 0.8.3
|
|
25
|
+
hooks:
|
|
26
|
+
- id: pydoclint
|
|
27
|
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
|
28
|
+
rev: v0.15.12
|
|
29
|
+
hooks:
|
|
30
|
+
- id: ruff-check
|
|
31
|
+
args: [--fix]
|
|
32
|
+
- id: ruff-format
|
|
33
|
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
|
34
|
+
rev: v1.15.0
|
|
35
|
+
hooks:
|
|
36
|
+
- id: mypy
|
|
37
|
+
additional_dependencies: []
|
model2vec-0.9.0/Makefile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
VERBOSITY=
|
|
2
|
+
|
|
3
|
+
venv:
|
|
4
|
+
uv venv
|
|
5
|
+
|
|
6
|
+
install:
|
|
7
|
+
uv sync --all-extras
|
|
8
|
+
uv run pre-commit install
|
|
9
|
+
|
|
10
|
+
install-no-pre-commit:
|
|
11
|
+
uv pip install ".[dev,distill,train,onnx,quantization,integration,tests]"
|
|
12
|
+
|
|
13
|
+
install-base:
|
|
14
|
+
uv sync --extra dev
|
|
15
|
+
|
|
16
|
+
fix:
|
|
17
|
+
uv run pre-commit run --all-files
|
|
18
|
+
|
|
19
|
+
test:
|
|
20
|
+
uv run pytest --cov=model2vec --cov-report=term-missing --ignore=tests/integration $(VERBOSITY)
|
|
21
|
+
|
|
22
|
+
test-verbose:
|
|
23
|
+
make test VERBOSITY="-vvv"
|
|
24
|
+
|
|
25
|
+
test-integration:
|
|
26
|
+
uv run pytest tests/integration $(VERBOSITY)
|
|
27
|
+
|
|
28
|
+
test-integration-update:
|
|
29
|
+
uv run python -m tests.integration.update_distill_baseline
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: model2vec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: Fast State-of-the-Art Static Embeddings
|
|
5
|
-
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <
|
|
5
|
+
Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomasvdongen@proton.me>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
8
8
|
Copyright (c) 2024 Thomas van Dongen
|
|
@@ -45,37 +45,34 @@ Description-Content-Type: text/markdown
|
|
|
45
45
|
Requires-Dist: jinja2
|
|
46
46
|
Requires-Dist: joblib
|
|
47
47
|
Requires-Dist: numpy
|
|
48
|
-
Requires-Dist: rich
|
|
49
48
|
Requires-Dist: safetensors
|
|
50
|
-
Requires-Dist: setuptools
|
|
51
49
|
Requires-Dist: tokenizers>=0.20
|
|
52
50
|
Requires-Dist: tqdm
|
|
53
51
|
Provides-Extra: dev
|
|
54
|
-
Requires-Dist: black; extra == "dev"
|
|
55
52
|
Requires-Dist: ipython; extra == "dev"
|
|
56
53
|
Requires-Dist: mypy; extra == "dev"
|
|
57
54
|
Requires-Dist: pre-commit; extra == "dev"
|
|
58
55
|
Requires-Dist: pytest; extra == "dev"
|
|
59
56
|
Requires-Dist: pytest-cov; extra == "dev"
|
|
60
57
|
Requires-Dist: ruff; extra == "dev"
|
|
58
|
+
Requires-Dist: setuptools; extra == "dev"
|
|
61
59
|
Provides-Extra: distill
|
|
62
60
|
Requires-Dist: torch; extra == "distill"
|
|
63
61
|
Requires-Dist: transformers<5.4.0; extra == "distill"
|
|
64
62
|
Requires-Dist: scikit-learn; extra == "distill"
|
|
65
|
-
Requires-Dist: skeletoken
|
|
63
|
+
Requires-Dist: skeletoken<0.5.0,>=0.4.1; extra == "distill"
|
|
66
64
|
Provides-Extra: onnx
|
|
67
65
|
Requires-Dist: onnx; extra == "onnx"
|
|
68
66
|
Requires-Dist: torch; extra == "onnx"
|
|
69
67
|
Provides-Extra: train
|
|
70
68
|
Requires-Dist: torch; extra == "train"
|
|
71
|
-
Requires-Dist: lightning; extra == "train"
|
|
72
|
-
Requires-Dist: scikit-learn; extra == "train"
|
|
73
|
-
Requires-Dist: skops; extra == "train"
|
|
74
|
-
Provides-Extra: inference
|
|
75
|
-
Requires-Dist: scikit-learn; extra == "inference"
|
|
76
|
-
Requires-Dist: skops; extra == "inference"
|
|
77
69
|
Provides-Extra: quantization
|
|
78
70
|
Requires-Dist: scikit-learn; extra == "quantization"
|
|
71
|
+
Provides-Extra: integration
|
|
72
|
+
Requires-Dist: mteb; extra == "integration"
|
|
73
|
+
Provides-Extra: tests
|
|
74
|
+
Requires-Dist: scikit-learn; extra == "tests"
|
|
75
|
+
Requires-Dist: skops; extra == "tests"
|
|
79
76
|
|
|
80
77
|
|
|
81
78
|
<h2 align="center">
|
|
@@ -5,15 +5,13 @@ import os
|
|
|
5
5
|
import re
|
|
6
6
|
from typing import cast
|
|
7
7
|
|
|
8
|
-
import numpy as np
|
|
9
8
|
from huggingface_hub.hf_api import model_info
|
|
10
9
|
from skeletoken import TokenizerModel
|
|
11
10
|
from skeletoken.external.transformers import reshape_embeddings
|
|
12
|
-
from transformers import AutoModel, AutoTokenizer
|
|
11
|
+
from transformers import AutoModel, AutoTokenizer, PreTrainedTokenizerFast
|
|
13
12
|
from transformers.modeling_utils import PreTrainedModel
|
|
14
|
-
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
|
15
13
|
|
|
16
|
-
from model2vec.distill.inference import PCADimType, PoolingMode,
|
|
14
|
+
from model2vec.distill.inference import PCADimType, PoolingMode, apply_pca, compute_weights, create_embeddings
|
|
17
15
|
from model2vec.distill.utils import select_optimal_device
|
|
18
16
|
from model2vec.model import StaticModel
|
|
19
17
|
from model2vec.quantization import DType, quantize_embeddings
|
|
@@ -35,8 +33,7 @@ def distill_from_model(
|
|
|
35
33
|
vocabulary_quantization: int | None = None,
|
|
36
34
|
pooling: PoolingMode | str = PoolingMode.MEAN,
|
|
37
35
|
) -> StaticModel:
|
|
38
|
-
"""
|
|
39
|
-
Distill a staticmodel from a sentence transformer.
|
|
36
|
+
"""Distill a staticmodel from a sentence transformer.
|
|
40
37
|
|
|
41
38
|
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
42
39
|
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
@@ -67,7 +64,7 @@ def distill_from_model(
|
|
|
67
64
|
'first': use the first token's hidden state ([CLS] token in BERT-style models).
|
|
68
65
|
'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.
|
|
69
66
|
:return: A StaticModel.
|
|
70
|
-
:raises
|
|
67
|
+
:raises ValueError: if the vocabulary is empty after preprocessing.
|
|
71
68
|
|
|
72
69
|
"""
|
|
73
70
|
quantize_to = DType(quantize_to)
|
|
@@ -88,12 +85,6 @@ def distill_from_model(
|
|
|
88
85
|
|
|
89
86
|
# Create the vocabulary in the new tokenizer.
|
|
90
87
|
tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)
|
|
91
|
-
# Remove the post processor, this is not necessary.
|
|
92
|
-
tokenizer_model.post_processor = None
|
|
93
|
-
# Prune again now that the post processor is gone.
|
|
94
|
-
# We can't do this before because we need the post processor and associated
|
|
95
|
-
# tokens before to add eos/bos.
|
|
96
|
-
tokenizer_model = tokenizer_model.prune_added_tokens()
|
|
97
88
|
|
|
98
89
|
# All tokens in a single list.
|
|
99
90
|
all_tokens = tokenizer_model.sorted_vocabulary
|
|
@@ -115,16 +106,19 @@ def distill_from_model(
|
|
|
115
106
|
pooling=pooling,
|
|
116
107
|
)
|
|
117
108
|
|
|
118
|
-
#
|
|
109
|
+
# Apply quantization
|
|
119
110
|
if vocabulary_quantization is not None:
|
|
120
|
-
|
|
111
|
+
weights = compute_weights(len(embeddings), sif_coefficient=sif_coefficient)
|
|
121
112
|
embeddings, token_mapping, weights = quantize_vocabulary(
|
|
122
|
-
n_clusters=vocabulary_quantization, weights=weights, embeddings=
|
|
113
|
+
n_clusters=vocabulary_quantization, weights=weights, embeddings=embeddings
|
|
123
114
|
)
|
|
124
|
-
embeddings
|
|
115
|
+
embeddings = apply_pca(embeddings, pca_dims)
|
|
125
116
|
else:
|
|
126
117
|
# Post-process the embeddings.
|
|
127
|
-
|
|
118
|
+
weights = compute_weights(len(embeddings), sif_coefficient=sif_coefficient)
|
|
119
|
+
embeddings = apply_pca(embeddings, pca_dims)
|
|
120
|
+
embeddings = embeddings * weights[:, None]
|
|
121
|
+
weights = None
|
|
128
122
|
token_mapping = None
|
|
129
123
|
# Quantize the embeddings.
|
|
130
124
|
embeddings = quantize_embeddings(embeddings, quantize_to)
|
|
@@ -173,15 +167,14 @@ def _validate_parameters(
|
|
|
173
167
|
sif_coefficient: float | None,
|
|
174
168
|
token_remove_pattern: str | None,
|
|
175
169
|
) -> tuple[float | None, re.Pattern[str] | None]:
|
|
176
|
-
"""
|
|
177
|
-
Validate the parameters passed to the distillation function.
|
|
170
|
+
"""Validate the parameters passed to the distillation function.
|
|
178
171
|
|
|
179
172
|
:param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.
|
|
180
173
|
Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.
|
|
181
174
|
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to
|
|
182
175
|
this regex pattern will be removed from the vocabulary.
|
|
183
176
|
:return: The SIF coefficient to use.
|
|
184
|
-
:raises
|
|
177
|
+
:raises ValueError: if the regex can't be compiled.
|
|
185
178
|
|
|
186
179
|
"""
|
|
187
180
|
if sif_coefficient is not None:
|
|
@@ -210,8 +203,7 @@ def distill(
|
|
|
210
203
|
vocabulary_quantization: int | None = None,
|
|
211
204
|
pooling: PoolingMode | str = PoolingMode.MEAN,
|
|
212
205
|
) -> StaticModel:
|
|
213
|
-
"""
|
|
214
|
-
Distill a staticmodel from a sentence transformer.
|
|
206
|
+
"""Distill a staticmodel from a sentence transformer.
|
|
215
207
|
|
|
216
208
|
This function creates a set of embeddings from a sentence transformer. It does this by doing either
|
|
217
209
|
a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed
|
|
@@ -23,8 +23,7 @@ _DEFAULT_BATCH_SIZE = 256
|
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
class PoolingMode(str, Enum):
|
|
26
|
-
"""
|
|
27
|
-
Pooling modes for embedding creation.
|
|
26
|
+
"""Pooling modes for embedding creation.
|
|
28
27
|
|
|
29
28
|
- MEAN: masked mean over all tokens.
|
|
30
29
|
- LAST: last non-padding token (often EOS, common in decoder-style models).
|
|
@@ -48,8 +47,7 @@ def create_embeddings(
|
|
|
48
47
|
pad_token_id: int,
|
|
49
48
|
pooling: PoolingMode | str = PoolingMode.MEAN,
|
|
50
49
|
) -> np.ndarray:
|
|
51
|
-
"""
|
|
52
|
-
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
50
|
+
"""Create output embeddings for a bunch of tokens using a pretrained model.
|
|
53
51
|
|
|
54
52
|
It does a forward pass for all tokens passed in `tokens`.
|
|
55
53
|
|
|
@@ -121,8 +119,7 @@ def create_embeddings(
|
|
|
121
119
|
def _encode_with_model(
|
|
122
120
|
model: PreTrainedModel, encodings: dict[str, torch.Tensor]
|
|
123
121
|
) -> tuple[torch.Tensor, torch.Tensor | None, dict[str, torch.Tensor]]:
|
|
124
|
-
"""
|
|
125
|
-
Move inputs to the model device, run a forward pass, and standardize dtypes.
|
|
122
|
+
"""Move inputs to the model device, run a forward pass, and standardize dtypes.
|
|
126
123
|
|
|
127
124
|
:param model: The model to use.
|
|
128
125
|
:param encodings: The encoded tokens to turn into features.
|
|
@@ -137,18 +134,16 @@ def _encode_with_model(
|
|
|
137
134
|
# NOTE: If the dtype is bfloat 16, we convert to float32,
|
|
138
135
|
# because numpy does not suport bfloat16
|
|
139
136
|
# See here: https://github.com/numpy/numpy/issues/19808
|
|
140
|
-
|
|
141
|
-
hidden = hidden.float()
|
|
137
|
+
hidden = hidden.float()
|
|
142
138
|
pooler = getattr(outputs, "pooler_output", None)
|
|
143
|
-
if pooler is not None
|
|
139
|
+
if pooler is not None:
|
|
144
140
|
pooler = pooler.float()
|
|
145
141
|
return hidden, pooler, encodings_on_device
|
|
146
142
|
|
|
147
143
|
|
|
148
144
|
@torch.inference_mode()
|
|
149
145
|
def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
|
|
150
|
-
"""
|
|
151
|
-
Encode a batch of tokens using mean pooling.
|
|
146
|
+
"""Encode a batch of tokens using mean pooling.
|
|
152
147
|
|
|
153
148
|
:param model: The model to use.
|
|
154
149
|
:param encodings: The encoded tokens to turn into features.
|
|
@@ -164,8 +159,7 @@ def _encode_mean_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
|
|
|
164
159
|
|
|
165
160
|
@torch.inference_mode()
|
|
166
161
|
def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
|
|
167
|
-
"""
|
|
168
|
-
Encode a batch of tokens using last token pooling.
|
|
162
|
+
"""Encode a batch of tokens using last token pooling.
|
|
169
163
|
|
|
170
164
|
:param model: The model to use.
|
|
171
165
|
:param encodings: The encoded tokens to turn into features.
|
|
@@ -180,8 +174,7 @@ def _encode_last_with_model(model: PreTrainedModel, encodings: dict[str, torch.T
|
|
|
180
174
|
|
|
181
175
|
@torch.inference_mode()
|
|
182
176
|
def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
|
|
183
|
-
"""
|
|
184
|
-
Encode a batch of tokens using first token (CLS) pooling.
|
|
177
|
+
"""Encode a batch of tokens using first token (CLS) pooling.
|
|
185
178
|
|
|
186
179
|
:param model: The model to use.
|
|
187
180
|
:param encodings: The encoded tokens to turn into features.
|
|
@@ -193,8 +186,7 @@ def _encode_first_with_model(model: PreTrainedModel, encodings: dict[str, torch.
|
|
|
193
186
|
|
|
194
187
|
@torch.inference_mode()
|
|
195
188
|
def _encode_pooler_with_model(model: PreTrainedModel, encodings: dict[str, torch.Tensor]) -> torch.Tensor:
|
|
196
|
-
"""
|
|
197
|
-
Encode a batch of tokens using pooler output.
|
|
189
|
+
"""Encode a batch of tokens using pooler output.
|
|
198
190
|
|
|
199
191
|
:param model: The model to use.
|
|
200
192
|
:param encodings: The encoded tokens to turn into features.
|
|
@@ -207,10 +199,20 @@ def _encode_pooler_with_model(model: PreTrainedModel, encodings: dict[str, torch
|
|
|
207
199
|
return pooler.cpu()
|
|
208
200
|
|
|
209
201
|
|
|
210
|
-
def
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
202
|
+
def compute_weights(n_embeddings: int, sif_coefficient: float | None) -> np.ndarray:
|
|
203
|
+
"""Compute the weights based on Zipf's law and a SIF coefficient."""
|
|
204
|
+
if sif_coefficient is None:
|
|
205
|
+
return np.ones(n_embeddings)
|
|
206
|
+
logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
|
|
207
|
+
inv_rank = 1 / (np.arange(2, n_embeddings + 2))
|
|
208
|
+
proba = inv_rank / np.sum(inv_rank)
|
|
209
|
+
weight = sif_coefficient / (sif_coefficient + proba)
|
|
210
|
+
|
|
211
|
+
return weight
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def apply_pca(embeddings: np.ndarray, pca_dims: PCADimType) -> np.ndarray:
|
|
215
|
+
"""Apply PCA to the embeddings."""
|
|
214
216
|
if pca_dims is not None:
|
|
215
217
|
if pca_dims == "auto":
|
|
216
218
|
pca_dims = embeddings.shape[1]
|
|
@@ -233,7 +235,7 @@ def post_process_embeddings(
|
|
|
233
235
|
|
|
234
236
|
orig_dims = embeddings.shape[1]
|
|
235
237
|
p = PCA(n_components=pca_dims, svd_solver="full")
|
|
236
|
-
embeddings = p.fit_transform(embeddings)
|
|
238
|
+
embeddings = np.ascontiguousarray(p.fit_transform(embeddings))
|
|
237
239
|
|
|
238
240
|
if embeddings.shape[1] < orig_dims:
|
|
239
241
|
explained_variance_ratio = np.sum(p.explained_variance_ratio_)
|
|
@@ -242,12 +244,4 @@ def post_process_embeddings(
|
|
|
242
244
|
logger.info(f"Explained variance ratio: {explained_variance_ratio:.3f}.")
|
|
243
245
|
logger.info(f"Explained variance: {explained_variance:.3f}.")
|
|
244
246
|
|
|
245
|
-
|
|
246
|
-
logger.info("Estimating word frequencies using Zipf's law, and then applying SIF.")
|
|
247
|
-
inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))
|
|
248
|
-
proba = inv_rank / np.sum(inv_rank)
|
|
249
|
-
weight = sif_coefficient / (sif_coefficient + proba)
|
|
250
|
-
else:
|
|
251
|
-
weight = np.ones(embeddings.shape[0])
|
|
252
|
-
|
|
253
|
-
return embeddings, weight
|
|
247
|
+
return embeddings
|
|
@@ -9,8 +9,7 @@ logger = getLogger(__name__)
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
def select_optimal_device(device: str | None) -> str:
|
|
12
|
-
"""
|
|
13
|
-
Get the optimal device to use based on backend availability.
|
|
12
|
+
"""Get the optimal device to use based on backend availability.
|
|
14
13
|
|
|
15
14
|
For Torch versions >= 2.8.0, MPS is disabled due to known performance regressions.
|
|
16
15
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Inference
|
|
2
|
+
|
|
3
|
+
This subpackage mainly contains helper functions for inference with trained classifier/projector heads, persisted as a `safetensors` file and `config.json` metadata.
|
|
4
|
+
|
|
5
|
+
If you're looking for information on how to train a model, see [here](../train/README.md).
|
|
6
|
+
|
|
7
|
+
# Usage
|
|
8
|
+
|
|
9
|
+
Let's assume you're using our [potion-edu classifier](https://huggingface.co/minishlab/potion-8m-edu-classifier).
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from model2vec.inference import StaticModelPipeline
|
|
13
|
+
|
|
14
|
+
classifier = StaticModelPipeline.from_pretrained("minishlab/potion-8m-edu-classifier")
|
|
15
|
+
label = classifier.predict("Attitudes towards cattle in the Alps: a study in letting go.")
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
This should just work.
|
|
19
|
+
|
|
20
|
+
# Migrating a legacy pipeline
|
|
21
|
+
|
|
22
|
+
Pipelines saved by older versions of model2vec store the head as a `scikit-learn`/`skops` `pipeline.skops` file instead of `head.safetensors`. `from_pretrained` still loads these automatically, falling back to the legacy format and emitting a warning. This requires `scikit-learn` and `skops` to be installed.
|
|
23
|
+
|
|
24
|
+
To upgrade a pipeline to the current format (and silence the warning), convert it with `convert_legacy_pipeline` and save the result:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from model2vec.inference import convert_legacy_pipeline
|
|
28
|
+
|
|
29
|
+
pipeline = convert_legacy_pipeline("path/or/repo-id/of/legacy/pipeline")
|
|
30
|
+
pipeline.save_pretrained("path/to/save")
|
|
31
|
+
```
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Sequence
|
|
4
|
+
from typing import Any, cast
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _is_multi_label_shaped(y: list[int] | list[str] | list[list[int]] | list[list[str]]) -> bool:
|
|
10
|
+
"""Check if the labels are in a multi-label shape."""
|
|
11
|
+
return isinstance(y, (list, tuple)) and len(y) > 0 and isinstance(y[0], (list, tuple, set))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _one_hot(labels: Sequence[Any], classes: Sequence[Any]) -> np.ndarray:
|
|
15
|
+
"""One-hot encode a flat sequence of labels against a fixed set of classes."""
|
|
16
|
+
index = {label: position for position, label in enumerate(classes)}
|
|
17
|
+
encoded = np.zeros((len(labels), len(classes)), dtype=int)
|
|
18
|
+
for row, label in enumerate(labels):
|
|
19
|
+
encoded[row, index[label]] = 1
|
|
20
|
+
return encoded
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _multi_hot(label_lists: Iterable[Iterable[Any]], classes: Sequence[Any]) -> np.ndarray:
|
|
24
|
+
"""Multi-hot encode a sequence of label lists against a fixed set of classes."""
|
|
25
|
+
index = {label: position for position, label in enumerate(classes)}
|
|
26
|
+
label_lists = list(label_lists)
|
|
27
|
+
encoded = np.zeros((len(label_lists), len(classes)), dtype=int)
|
|
28
|
+
for row, labels in enumerate(label_lists):
|
|
29
|
+
for label in labels:
|
|
30
|
+
encoded[row, index[label]] = 1
|
|
31
|
+
return encoded
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _precision_recall_f1_support(
|
|
35
|
+
y_true: np.ndarray, y_pred: np.ndarray
|
|
36
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
37
|
+
"""Compute per-class precision, recall, f1, and support from one-hot / multi-hot encoded labels."""
|
|
38
|
+
true_positive = ((y_true == 1) & (y_pred == 1)).sum(axis=0).astype(float)
|
|
39
|
+
false_positive = ((y_true == 0) & (y_pred == 1)).sum(axis=0).astype(float)
|
|
40
|
+
false_negative = ((y_true == 1) & (y_pred == 0)).sum(axis=0).astype(float)
|
|
41
|
+
support = y_true.sum(axis=0)
|
|
42
|
+
|
|
43
|
+
predicted_positive = true_positive + false_positive
|
|
44
|
+
actual_positive = true_positive + false_negative
|
|
45
|
+
precision = np.divide(
|
|
46
|
+
true_positive, predicted_positive, out=np.zeros_like(true_positive), where=predicted_positive > 0
|
|
47
|
+
)
|
|
48
|
+
recall = np.divide(true_positive, actual_positive, out=np.zeros_like(true_positive), where=actual_positive > 0)
|
|
49
|
+
precision_plus_recall = precision + recall
|
|
50
|
+
f1 = np.divide(
|
|
51
|
+
2 * precision * recall, precision_plus_recall, out=np.zeros_like(precision), where=precision_plus_recall > 0
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return precision, recall, f1, support
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def evaluate_single_or_multi_label(
|
|
58
|
+
predictions: np.ndarray,
|
|
59
|
+
y: list[int] | list[str] | list[list[int]] | list[list[str]],
|
|
60
|
+
) -> dict[str, dict[str, float]]:
|
|
61
|
+
"""Evaluate the classifier on a given dataset using a classification report.
|
|
62
|
+
|
|
63
|
+
This function computes per-class precision, recall and f1-score (via one-vs-rest / multi-hot encoding), plus
|
|
64
|
+
overall accuracy, macro average, and weighted average.
|
|
65
|
+
|
|
66
|
+
:param predictions: The predictions.
|
|
67
|
+
:param y: The ground truth labels.
|
|
68
|
+
:return: A classification report, as a dictionary.
|
|
69
|
+
"""
|
|
70
|
+
if _is_multi_label_shaped(y):
|
|
71
|
+
y = cast(list[list[str]] | list[list[int]], y)
|
|
72
|
+
predictions = cast(np.ndarray, predictions)
|
|
73
|
+
y_labels = {label for labels in y for label in labels}
|
|
74
|
+
predicted_labels = {label for labels in predictions for label in labels}
|
|
75
|
+
classes = sorted(y_labels | predicted_labels)
|
|
76
|
+
y_transformed = _multi_hot(y, classes)
|
|
77
|
+
predictions_transformed = _multi_hot(predictions, classes)
|
|
78
|
+
else:
|
|
79
|
+
y = cast(list[str] | list[int], y)
|
|
80
|
+
classes = sorted(set(y) | set(predictions.tolist()))
|
|
81
|
+
y_transformed = _one_hot(y, classes)
|
|
82
|
+
predictions_transformed = _one_hot(predictions.tolist(), classes)
|
|
83
|
+
|
|
84
|
+
target_names = [str(c) for c in classes]
|
|
85
|
+
precision, recall, f1, support = _precision_recall_f1_support(y_transformed, predictions_transformed)
|
|
86
|
+
total_support = float(support.sum())
|
|
87
|
+
accuracy = float(np.all(y_transformed == predictions_transformed, axis=1).mean())
|
|
88
|
+
|
|
89
|
+
report: dict[str, Any] = {
|
|
90
|
+
name: {
|
|
91
|
+
"precision": float(precision[idx]),
|
|
92
|
+
"recall": float(recall[idx]),
|
|
93
|
+
"f1-score": float(f1[idx]),
|
|
94
|
+
"support": float(support[idx]),
|
|
95
|
+
}
|
|
96
|
+
for idx, name in enumerate(target_names)
|
|
97
|
+
}
|
|
98
|
+
report["accuracy"] = accuracy
|
|
99
|
+
report["macro avg"] = {
|
|
100
|
+
"precision": float(precision.mean()),
|
|
101
|
+
"recall": float(recall.mean()),
|
|
102
|
+
"f1-score": float(f1.mean()),
|
|
103
|
+
"support": total_support,
|
|
104
|
+
}
|
|
105
|
+
weights = support / total_support if total_support > 0 else np.zeros_like(support, dtype=float)
|
|
106
|
+
report["weighted avg"] = {
|
|
107
|
+
"precision": float((precision * weights).sum()),
|
|
108
|
+
"recall": float((recall * weights).sum()),
|
|
109
|
+
"f1-score": float((f1 * weights).sum()),
|
|
110
|
+
"support": total_support,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return report
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import Enum
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Activation(str, Enum):
|
|
10
|
+
SOFTMAX = "softmax"
|
|
11
|
+
SIGMOID = "sigmoid"
|
|
12
|
+
IDENTITY = "identity"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _softmax(x: np.ndarray) -> np.ndarray:
|
|
16
|
+
"""Numerically stable softmax over the last axis."""
|
|
17
|
+
shifted = x - x.max(axis=-1, keepdims=True)
|
|
18
|
+
exponentiated = np.exp(shifted)
|
|
19
|
+
return exponentiated / exponentiated.sum(axis=-1, keepdims=True)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _sigmoid(x: np.ndarray) -> np.ndarray:
|
|
23
|
+
"""Numerically stable sigmoid."""
|
|
24
|
+
return np.where(x >= 0, 1 / (1 + np.exp(-x)), np.exp(x) / (1 + np.exp(x)))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Layer:
|
|
29
|
+
weight: np.ndarray
|
|
30
|
+
bias: np.ndarray
|
|
31
|
+
|
|
32
|
+
def __call__(self, x: np.ndarray) -> np.ndarray:
|
|
33
|
+
"""Apply the linear transformation."""
|
|
34
|
+
return x @ self.weight.T + self.bias
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MLPHead:
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
layers: list[Layer],
|
|
41
|
+
activation: Activation,
|
|
42
|
+
classes: np.ndarray | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""An MLP with ReLU activation.
|
|
45
|
+
|
|
46
|
+
:param layers: The linear layers, in order.
|
|
47
|
+
:param activation: The output activation.
|
|
48
|
+
:param classes: The classes, if the task is a classification task.
|
|
49
|
+
"""
|
|
50
|
+
self.layers = layers
|
|
51
|
+
self.activation = activation
|
|
52
|
+
self.classes_ = classes
|
|
53
|
+
|
|
54
|
+
def _logits(self, X: np.ndarray) -> np.ndarray:
|
|
55
|
+
"""Run the forward through the layers."""
|
|
56
|
+
out = X
|
|
57
|
+
*hidden_layers, last_layer = self.layers
|
|
58
|
+
for layer in hidden_layers:
|
|
59
|
+
out = np.maximum(layer(out), 0.0)
|
|
60
|
+
return last_layer(out)
|
|
61
|
+
|
|
62
|
+
def predict_proba(self, X: np.ndarray) -> np.ndarray:
|
|
63
|
+
"""Predict probabilities, applying the output activation to the raw logits."""
|
|
64
|
+
logits = self._logits(X)
|
|
65
|
+
match self.activation:
|
|
66
|
+
case Activation.SOFTMAX:
|
|
67
|
+
return _softmax(logits)
|
|
68
|
+
case Activation.SIGMOID:
|
|
69
|
+
return _sigmoid(logits)
|
|
70
|
+
case Activation.IDENTITY:
|
|
71
|
+
return logits
|
|
72
|
+
|
|
73
|
+
def predict_index(self, X: np.ndarray) -> np.ndarray:
|
|
74
|
+
"""Predict the index of the most likely class."""
|
|
75
|
+
return self._logits(X).argmax(axis=1)
|
|
76
|
+
|
|
77
|
+
def predict_regression(self, X: np.ndarray) -> np.ndarray:
|
|
78
|
+
"""Predict the raw (identity-activation) output, e.g. for a projector head."""
|
|
79
|
+
return self._logits(X)
|