model2vec 0.8.2__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.
Files changed (96) hide show
  1. {model2vec-0.8.2 → model2vec-0.9.0}/.github/workflows/ci.yaml +1 -1
  2. model2vec-0.9.0/Makefile +29 -0
  3. {model2vec-0.8.2 → model2vec-0.9.0}/PKG-INFO +7 -8
  4. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/distill/inference.py +1 -1
  5. model2vec-0.9.0/model2vec/inference/README.md +31 -0
  6. model2vec-0.9.0/model2vec/inference/__init__.py +4 -0
  7. model2vec-0.9.0/model2vec/inference/evaluation.py +113 -0
  8. model2vec-0.9.0/model2vec/inference/mlp.py +79 -0
  9. model2vec-0.9.0/model2vec/inference/model.py +365 -0
  10. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/persistence/persistence.py +3 -3
  11. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/tokenizer/tokenizer.py +6 -2
  12. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/README.md +7 -13
  13. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/__init__.py +2 -7
  14. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/base.py +24 -46
  15. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/classifier.py +38 -20
  16. model2vec-0.9.0/model2vec/train/regression.py +16 -0
  17. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/similarity.py +26 -11
  18. model2vec-0.9.0/model2vec/train/trainer.py +194 -0
  19. model2vec-0.9.0/model2vec/train/utils.py +135 -0
  20. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/version.py +1 -1
  21. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec.egg-info/PKG-INFO +7 -8
  22. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec.egg-info/SOURCES.txt +15 -1
  23. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec.egg-info/requires.txt +7 -7
  24. model2vec-0.9.0/model2vec.egg-info/scm_file_list.json +84 -0
  25. model2vec-0.9.0/model2vec.egg-info/scm_version.json +8 -0
  26. {model2vec-0.8.2 → model2vec-0.9.0}/pyproject.toml +5 -4
  27. {model2vec-0.8.2 → model2vec-0.9.0}/tests/conftest.py +26 -3
  28. model2vec-0.9.0/tests/integration/__init__.py +0 -0
  29. model2vec-0.9.0/tests/integration/data/Alibaba-NLP___gte-modernbert-base_baseline.json +91 -0
  30. model2vec-0.9.0/tests/integration/data/baai___bge-base-en-v1.5_baseline.json +91 -0
  31. model2vec-0.9.0/tests/integration/data/google___embeddinggemma-300m_baseline.json +91 -0
  32. model2vec-0.9.0/tests/integration/data/intfloat___multilingual-e5-base_baseline.json +91 -0
  33. model2vec-0.9.0/tests/integration/data/sentence-transformers___all-MiniLM-L6-v2_baseline.json +91 -0
  34. model2vec-0.9.0/tests/integration/distill_metrics.py +123 -0
  35. model2vec-0.9.0/tests/integration/test_distill_regression.py +145 -0
  36. model2vec-0.9.0/tests/integration/update_distill_baseline.py +47 -0
  37. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_distillation.py +1 -0
  38. model2vec-0.9.0/tests/test_inference.py +333 -0
  39. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_persistence.py +32 -0
  40. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_trainable.py +136 -3
  41. {model2vec-0.8.2 → model2vec-0.9.0}/uv.lock +1150 -495
  42. model2vec-0.8.2/Makefile +0 -23
  43. model2vec-0.8.2/model2vec/inference/README.md +0 -18
  44. model2vec-0.8.2/model2vec/inference/__init__.py +0 -10
  45. model2vec-0.8.2/model2vec/inference/model.py +0 -320
  46. model2vec-0.8.2/model2vec/train/lightning_modules.py +0 -99
  47. model2vec-0.8.2/model2vec/train/utils.py +0 -118
  48. model2vec-0.8.2/tests/test_inference.py +0 -107
  49. {model2vec-0.8.2 → model2vec-0.9.0}/.github/workflows/release.yaml +0 -0
  50. {model2vec-0.8.2 → model2vec-0.9.0}/.gitignore +0 -0
  51. {model2vec-0.8.2 → model2vec-0.9.0}/.pre-commit-config.yaml +0 -0
  52. {model2vec-0.8.2 → model2vec-0.9.0}/CITATION.cff +0 -0
  53. {model2vec-0.8.2 → model2vec-0.9.0}/LICENSE +0 -0
  54. {model2vec-0.8.2 → model2vec-0.9.0}/README.md +0 -0
  55. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/logo_v2.png +0 -0
  56. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/model2vec_logo.png +0 -0
  57. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/speed_vs_mteb_plot.png +0 -0
  58. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/speed_vs_mteb_score_v3.png +0 -0
  59. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/training_speed_vs_score.png +0 -0
  60. {model2vec-0.8.2 → model2vec-0.9.0}/assets/images/tutorial_ezlo.png +0 -0
  61. {model2vec-0.8.2 → model2vec-0.9.0}/docs/README.md +0 -0
  62. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/__init__.py +0 -0
  63. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/distill/__init__.py +0 -0
  64. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/distill/distillation.py +0 -0
  65. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/distill/utils.py +0 -0
  66. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/model.py +0 -0
  67. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/modelcards/__init__.py +0 -0
  68. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/modelcards/classifier_template.md +0 -0
  69. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/modelcards/model_card_template.md +0 -0
  70. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/modelcards/modelcards.py +0 -0
  71. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/persistence/__init__.py +0 -0
  72. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/persistence/datamodels.py +0 -0
  73. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/persistence/hf.py +0 -0
  74. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/py.typed +0 -0
  75. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/quantization.py +0 -0
  76. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/tokenizer/__init__.py +0 -0
  77. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/train/dataset.py +0 -0
  78. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/utils.py +0 -0
  79. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec/vocabulary_quantization.py +0 -0
  80. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec.egg-info/dependency_links.txt +0 -0
  81. {model2vec-0.8.2 → model2vec-0.9.0}/model2vec.egg-info/top_level.txt +0 -0
  82. {model2vec-0.8.2 → model2vec-0.9.0}/results/README.md +0 -0
  83. {model2vec-0.8.2 → model2vec-0.9.0}/results/make_speed_vs_mteb_plot.py +0 -0
  84. {model2vec-0.8.2 → model2vec-0.9.0}/scripts/export_to_onnx.py +0 -0
  85. {model2vec-0.8.2 → model2vec-0.9.0}/setup.cfg +0 -0
  86. {model2vec-0.8.2 → model2vec-0.9.0}/tests/__init__.py +0 -0
  87. {model2vec-0.8.2 → model2vec-0.9.0}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
  88. {model2vec-0.8.2 → model2vec-0.9.0}/tests/data/test_tokenizer/tokenizer.json +0 -0
  89. {model2vec-0.8.2 → model2vec-0.9.0}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
  90. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_model.py +0 -0
  91. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_quantization.py +0 -0
  92. {model2vec-0.8.2 → model2vec-0.9.0}/tests/test_utils.py +0 -0
  93. {model2vec-0.8.2 → model2vec-0.9.0}/tutorials/README.md +0 -0
  94. {model2vec-0.8.2 → model2vec-0.9.0}/tutorials/recipe_search.ipynb +0 -0
  95. {model2vec-0.8.2 → model2vec-0.9.0}/tutorials/semantic_chunking.ipynb +0 -0
  96. {model2vec-0.8.2 → model2vec-0.9.0}/tutorials/train_classifier.ipynb +0 -0
@@ -50,7 +50,7 @@ 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
@@ -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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: model2vec
3
- Version: 0.8.2
3
+ Version: 0.9.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
@@ -60,20 +60,19 @@ Provides-Extra: distill
60
60
  Requires-Dist: torch; extra == "distill"
61
61
  Requires-Dist: transformers<5.4.0; extra == "distill"
62
62
  Requires-Dist: scikit-learn; extra == "distill"
63
- Requires-Dist: skeletoken>=0.3.3; extra == "distill"
63
+ Requires-Dist: skeletoken<0.5.0,>=0.4.1; extra == "distill"
64
64
  Provides-Extra: onnx
65
65
  Requires-Dist: onnx; extra == "onnx"
66
66
  Requires-Dist: torch; extra == "onnx"
67
67
  Provides-Extra: train
68
68
  Requires-Dist: torch; extra == "train"
69
- Requires-Dist: lightning; extra == "train"
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"
75
69
  Provides-Extra: quantization
76
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"
77
76
 
78
77
 
79
78
  <h2 align="center">
@@ -235,7 +235,7 @@ def apply_pca(embeddings: np.ndarray, pca_dims: PCADimType) -> np.ndarray:
235
235
 
236
236
  orig_dims = embeddings.shape[1]
237
237
  p = PCA(n_components=pca_dims, svd_solver="full")
238
- embeddings = p.fit_transform(embeddings)
238
+ embeddings = np.ascontiguousarray(p.fit_transform(embeddings))
239
239
 
240
240
  if embeddings.shape[1] < orig_dims:
241
241
  explained_variance_ratio = np.sum(p.explained_variance_ratio_)
@@ -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,4 @@
1
+ from model2vec.inference.evaluation import evaluate_single_or_multi_label
2
+ from model2vec.inference.model import StaticModelPipeline, convert_legacy_pipeline
3
+
4
+ __all__ = ["StaticModelPipeline", "convert_legacy_pipeline", "evaluate_single_or_multi_label"]
@@ -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)
@@ -0,0 +1,365 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+ from collections.abc import Sequence
5
+ from pathlib import Path
6
+ from tempfile import TemporaryDirectory
7
+ from typing import Any, TypeVar, cast
8
+
9
+ import huggingface_hub
10
+ import numpy as np
11
+ from huggingface_hub.errors import EntryNotFoundError
12
+ from safetensors.numpy import load_file, save_file
13
+
14
+ from model2vec.inference.evaluation import evaluate_single_or_multi_label
15
+ from model2vec.inference.mlp import Activation, Layer, MLPHead
16
+ from model2vec.model import PathLike, StaticModel
17
+ from model2vec.persistence import save_pretrained
18
+
19
+ _DEFAULT_HEAD_FILENAME = "head.safetensors"
20
+ _LEGACY_HEAD_FILENAME = "pipeline.skops"
21
+
22
+ LabelType = TypeVar("LabelType", list[str], list[list[str]])
23
+
24
+
25
+ class StaticModelPipeline:
26
+ def __init__(self, model: StaticModel, head: MLPHead) -> None:
27
+ """Create a pipeline with a StaticModel encoder."""
28
+ self.model = model
29
+ self.head = head
30
+ self.classes_ = head.classes_
31
+
32
+ @classmethod
33
+ def from_pretrained(
34
+ cls: type[StaticModelPipeline], path: PathLike, token: str | None = None
35
+ ) -> StaticModelPipeline:
36
+ """Load a StaticModel from a local path or huggingface hub path.
37
+
38
+ NOTE: if you load a private model from the huggingface hub, you need to pass a token.
39
+
40
+ NOTE: if the pipeline was saved by an older version of model2vec (a `pipeline.skops` file instead of
41
+ `head.safetensors`), this falls back to loading it as a legacy pipeline and emits a warning. This requires
42
+ `scikit-learn` and `skops` to be installed. See `convert_legacy_pipeline` to upgrade it to the current format.
43
+
44
+ :param path: The path to the folder containing the pipeline, or a repository on the Hugging Face Hub
45
+ :param token: The token to use to download the pipeline from the hub.
46
+ :return: The loaded pipeline.
47
+ """
48
+ model, head = _load_pipeline(path, token)
49
+ model.embedding = np.nan_to_num(model.embedding)
50
+
51
+ return cls(model, head)
52
+
53
+ def save_pretrained(self, path: str) -> None:
54
+ """Save the model to a folder."""
55
+ _save_pipeline(self, path)
56
+
57
+ def push_to_hub(
58
+ self, repo_id: str, subfolder: str | None = None, token: str | None = None, private: bool = False
59
+ ) -> None:
60
+ """Save a model to a folder, and then push that folder to the hf hub.
61
+
62
+ :param repo_id: The id of the repository to push to.
63
+ :param subfolder: The subfolder to push to.
64
+ :param token: The token to use to push to the hub.
65
+ :param private: Whether the repository should be private.
66
+ """
67
+ from model2vec.persistence import push_folder_to_hub
68
+
69
+ with TemporaryDirectory() as temp_dir:
70
+ _save_pipeline(self, temp_dir)
71
+ push_folder_to_hub(Path(temp_dir), subfolder, repo_id, private, token)
72
+
73
+ def _encode_and_coerce_to_2d(
74
+ self,
75
+ X: Sequence[str],
76
+ show_progress_bar: bool,
77
+ max_length: int | None,
78
+ batch_size: int,
79
+ use_multiprocessing: bool,
80
+ multiprocessing_threshold: int,
81
+ ) -> np.ndarray:
82
+ """Encode the instances and coerce the output to a matrix."""
83
+ encoded = self.model.encode(
84
+ X,
85
+ show_progress_bar=show_progress_bar,
86
+ max_length=max_length,
87
+ batch_size=batch_size,
88
+ use_multiprocessing=use_multiprocessing,
89
+ multiprocessing_threshold=multiprocessing_threshold,
90
+ )
91
+ if np.ndim(encoded) == 1:
92
+ encoded = encoded[None, :]
93
+
94
+ return encoded
95
+
96
+ def predict(
97
+ self,
98
+ X: Sequence[str],
99
+ show_progress_bar: bool = False,
100
+ max_length: int | None = 512,
101
+ batch_size: int = 1024,
102
+ use_multiprocessing: bool = True,
103
+ multiprocessing_threshold: int = 10_000,
104
+ threshold: float = 0.5,
105
+ ) -> np.ndarray:
106
+ """Predict the labels of the input.
107
+
108
+ :param X: The input data to predict. Can be a list of strings or a single string.
109
+ :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
110
+ :param max_length: The maximum length of the input sequences. Defaults to 512.
111
+ :param batch_size: The batch size for prediction. Defaults to 1024.
112
+ :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
113
+ :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
114
+ :param threshold: The threshold for multilabel classification. Defaults to 0.5. Ignored if not multilabel.
115
+ :return: The predicted labels or probabilities.
116
+ """
117
+ encoded = self._encode_and_coerce_to_2d(
118
+ X,
119
+ show_progress_bar=show_progress_bar,
120
+ max_length=max_length,
121
+ batch_size=batch_size,
122
+ use_multiprocessing=use_multiprocessing,
123
+ multiprocessing_threshold=multiprocessing_threshold,
124
+ )
125
+
126
+ if self.head.activation == Activation.IDENTITY:
127
+ return self.head.predict_regression(encoded)
128
+
129
+ if self.head.activation == Activation.SIGMOID:
130
+ assert self.classes_ is not None
131
+ proba = self.head.predict_proba(encoded)
132
+ out_labels = [self.classes_[vector > threshold] for vector in proba]
133
+ return np.asarray(out_labels, dtype=object)
134
+
135
+ assert self.classes_ is not None
136
+ return self.classes_[self.head.predict_index(encoded)]
137
+
138
+ def predict_proba(
139
+ self,
140
+ X: Sequence[str],
141
+ show_progress_bar: bool = False,
142
+ max_length: int | None = 512,
143
+ batch_size: int = 1024,
144
+ use_multiprocessing: bool = True,
145
+ multiprocessing_threshold: int = 10_000,
146
+ ) -> np.ndarray:
147
+ """Predict the labels of the input.
148
+
149
+ :param X: The input data to predict. Can be a list of strings or a single string.
150
+ :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
151
+ :param max_length: The maximum length of the input sequences. Defaults to 512.
152
+ :param batch_size: The batch size for prediction. Defaults to 1024.
153
+ :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
154
+ :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
155
+ :return: The predicted labels or probabilities.
156
+ :raises ValueError: If the classifier type is projector.
157
+ """
158
+ if self.head.activation == Activation.IDENTITY:
159
+ raise ValueError("You are using evaluate on a projector model. This is not supported.")
160
+ encoded = self._encode_and_coerce_to_2d(
161
+ X,
162
+ show_progress_bar=show_progress_bar,
163
+ max_length=max_length,
164
+ batch_size=batch_size,
165
+ use_multiprocessing=use_multiprocessing,
166
+ multiprocessing_threshold=multiprocessing_threshold,
167
+ )
168
+
169
+ return self.head.predict_proba(encoded)
170
+
171
+ def evaluate(
172
+ self, X: Sequence[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5
173
+ ) -> dict[str, dict[str, float]]:
174
+ """Evaluate the classifier on a given dataset using a classification report.
175
+
176
+ :param X: The texts to predict on.
177
+ :param y: The ground truth labels.
178
+ :param batch_size: The batch size.
179
+ :param threshold: The threshold for multilabel classification.
180
+ :return: A classification report, as a dictionary.
181
+ :raises ValueError: If the classifier type is projector.
182
+ """
183
+ if self.head.activation == Activation.IDENTITY:
184
+ raise ValueError("You are using evaluate on a projector model. This is not supported.")
185
+ predictions = self.predict(X, show_progress_bar=True, batch_size=batch_size, threshold=threshold)
186
+ return evaluate_single_or_multi_label(predictions=predictions, y=y)
187
+
188
+
189
+ def _load_pipeline(folder_or_repo_path: PathLike, token: str | None = None) -> tuple[StaticModel, MLPHead]:
190
+ """Load a model and its head.
191
+
192
+ This assumes the following files are present in the repo:
193
+ - `head.safetensors`: The weights of the head.
194
+ - `config.json`: The configuration of the model, including the head's metadata.
195
+ - `model.safetensors`: The weights of the model.
196
+ - `tokenizer.json`: The tokenizer of the model.
197
+
198
+ :param folder_or_repo_path: The path to the folder containing the pipeline.
199
+ :param token: The token to use to download the pipeline from the hub. If this is None, you will only
200
+ be able to load the pipeline from a local folder, public repository, or a repository that you have access to
201
+ because you are logged in.
202
+ :return: The encoder model and the loaded head
203
+ :raises FileNotFoundError: If neither the head file nor a legacy pipeline file exist in the folder.
204
+ """
205
+ folder_or_repo_path = Path(folder_or_repo_path)
206
+ head_path: str | Path
207
+ if folder_or_repo_path.exists():
208
+ head_path = folder_or_repo_path / _DEFAULT_HEAD_FILENAME
209
+ if not head_path.exists():
210
+ if not (folder_or_repo_path / _LEGACY_HEAD_FILENAME).exists():
211
+ raise FileNotFoundError(f"Head file does not exist in {folder_or_repo_path}")
212
+ return _load_legacy_pipeline(folder_or_repo_path, token)
213
+ else:
214
+ try:
215
+ head_path = huggingface_hub.hf_hub_download(
216
+ folder_or_repo_path.as_posix(), _DEFAULT_HEAD_FILENAME, token=token
217
+ )
218
+ except EntryNotFoundError:
219
+ return _load_legacy_pipeline(folder_or_repo_path, token)
220
+
221
+ model = StaticModel.from_pretrained(folder_or_repo_path)
222
+
223
+ head_config = cast(dict[str, Any], model.config.get("head_config", {}))
224
+ activation = Activation(head_config.get("activation", Activation.IDENTITY.value))
225
+ n_layers = head_config.get("n_layers", 0)
226
+ classes = head_config.get("classes")
227
+
228
+ tensors = load_file(head_path)
229
+ layers = [
230
+ Layer(weight=tensors[f"head.{index}.weight"], bias=tensors[f"head.{index}.bias"]) for index in range(n_layers)
231
+ ]
232
+
233
+ head = MLPHead(
234
+ layers=layers,
235
+ activation=activation,
236
+ classes=np.asarray(classes) if classes is not None else None,
237
+ )
238
+
239
+ return model, head
240
+
241
+
242
+ def _load_legacy_pipeline(folder_or_repo_path: PathLike, token: str | None) -> tuple[StaticModel, MLPHead]:
243
+ """Load a model and its head from a legacy (scikit-learn/skops based) pipeline."""
244
+ _legacy_warning = (
245
+ f"No `{_DEFAULT_HEAD_FILENAME}` found for {folder_or_repo_path}; falling back to the legacy "
246
+ f"`{_LEGACY_HEAD_FILENAME}` format. Save this pipeline with `save_pretrained` to upgrade it."
247
+ )
248
+ warnings.warn(_legacy_warning, stacklevel=3)
249
+ converted = convert_legacy_pipeline(folder_or_repo_path, token=token)
250
+ return converted.model, converted.head
251
+
252
+
253
+ def convert_legacy_pipeline(
254
+ path: PathLike, token: str | None = None, trust_remote_code: bool = False
255
+ ) -> StaticModelPipeline:
256
+ """Convert an old-style (scikit-learn/skops based) `StaticModelPipeline` to the current, safetensors-based format.
257
+
258
+ This requires `scikit-learn` and `skops` to be installed.
259
+
260
+ :param path: The path to a local folder, or a repository on the Hugging Face Hub, containing a legacy pipeline
261
+ saved as a `pipeline.skops` file.
262
+ :param token: The token to use to download the pipeline from the hub.
263
+ :param trust_remote_code: Whether to trust the remote code in the skops file. If this is False, we will only
264
+ load components coming from `sklearn`.
265
+ :return: A new-style `StaticModelPipeline`, which can be persisted with `save_pretrained` or `push_to_hub`.
266
+ :raises ImportError: If `scikit-learn` and `skops` are not installed.
267
+ :raises FileNotFoundError: If the pipeline file does not exist in the folder.
268
+ :raises ValueError: If an untrusted type is found in the pipeline, or the head is not an MLP with a supported
269
+ hidden activation.
270
+ """
271
+ import re
272
+
273
+ try:
274
+ import skops.io
275
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
276
+ from sklearn.pipeline import Pipeline
277
+ except ImportError as exc:
278
+ raise ImportError("Converting a legacy pipeline requires `scikit-learn` and `skops`. ") from exc
279
+
280
+ folder_or_repo_path = Path(path)
281
+ legacy_head_path: str | Path
282
+ if folder_or_repo_path.exists():
283
+ legacy_head_path = folder_or_repo_path / _LEGACY_HEAD_FILENAME
284
+ if not legacy_head_path.exists():
285
+ raise FileNotFoundError(f"Pipeline file does not exist in {folder_or_repo_path}")
286
+ else:
287
+ legacy_head_path = huggingface_hub.hf_hub_download(
288
+ folder_or_repo_path.as_posix(), _LEGACY_HEAD_FILENAME, token=token
289
+ )
290
+
291
+ model = StaticModel.from_pretrained(folder_or_repo_path)
292
+ model.embedding = np.nan_to_num(model.embedding)
293
+
294
+ untrusted_types = skops.io.get_untrusted_types(file=legacy_head_path)
295
+ if not trust_remote_code:
296
+ trusted_pattern = re.compile(r"sklearn\..+")
297
+ for untrusted_type in untrusted_types:
298
+ if not trusted_pattern.match(untrusted_type):
299
+ raise ValueError(f"Untrusted type {untrusted_type}.")
300
+ legacy_pipeline = cast(Pipeline, skops.io.load(legacy_head_path, trusted=untrusted_types))
301
+ legacy_head = legacy_pipeline[-1]
302
+
303
+ if isinstance(legacy_head, MLPRegressor):
304
+ activation = Activation.IDENTITY
305
+ classes = None
306
+ elif isinstance(legacy_head, MLPClassifier):
307
+ activation = Activation.SIGMOID if legacy_head.out_activation_ == "logistic" else Activation.SOFTMAX
308
+ classes = np.asarray(legacy_head.classes_)
309
+ else:
310
+ raise ValueError(f"Unsupported legacy head type: {type(legacy_head)}. Expected MLPClassifier or MLPRegressor.")
311
+
312
+ if legacy_head.activation != "relu":
313
+ raise ValueError(f"Unsupported hidden activation: {legacy_head.activation}. Only `relu` is supported.")
314
+
315
+ layers = [
316
+ Layer(weight=coef.T, bias=intercept) for coef, intercept in zip(legacy_head.coefs_, legacy_head.intercepts_)
317
+ ]
318
+ head = MLPHead(layers=layers, activation=activation, classes=classes)
319
+
320
+ return StaticModelPipeline(model, head)
321
+
322
+
323
+ def _save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> None:
324
+ """Save a pipeline to a folder.
325
+
326
+ :param pipeline: The pipeline to save.
327
+ :param folder_path: The path to the folder to save the pipeline to.
328
+ """
329
+ folder_path = Path(folder_path)
330
+ folder_path.mkdir(parents=True, exist_ok=True)
331
+
332
+ head = pipeline.head
333
+ tensors: dict[str, np.ndarray] = {}
334
+ for index, layer in enumerate(head.layers):
335
+ tensors[f"head.{index}.weight"] = layer.weight
336
+ tensors[f"head.{index}.bias"] = layer.bias
337
+ save_file(tensors, folder_path / _DEFAULT_HEAD_FILENAME)
338
+
339
+ model = pipeline.model
340
+ config = dict(model.config)
341
+ config["head_config"] = {
342
+ "n_layers": len(head.layers),
343
+ "activation": head.activation.value,
344
+ "classes": np.asarray(pipeline.classes_).tolist() if pipeline.classes_ is not None else None,
345
+ }
346
+
347
+ base_model_name = model.base_model_name
348
+ if isinstance(base_model_name, list) and base_model_name:
349
+ name = base_model_name[0]
350
+ elif isinstance(base_model_name, str):
351
+ name = base_model_name
352
+ else:
353
+ name = "unknown"
354
+
355
+ save_pretrained(
356
+ folder_path=folder_path,
357
+ embeddings=model.embedding,
358
+ tokenizer=model.tokenizer,
359
+ config=config,
360
+ base_model_name=name,
361
+ language=model.language,
362
+ weights=model.weights,
363
+ mapping=model.token_mapping,
364
+ template_path="classifier_template.md",
365
+ )