model2vec-rs 0.4.0__tar.gz → 0.5.1__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 (47) hide show
  1. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/.github/workflows/release-python.yaml +13 -0
  2. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/Cargo.lock +2 -26
  3. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/Cargo.toml +2 -2
  4. model2vec_rs-0.5.1/PKG-INFO +80 -0
  5. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/README.md +15 -13
  6. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/README.md +31 -1
  7. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/pyproject.toml +6 -3
  8. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/python/Cargo.lock +3 -18
  9. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/python/Cargo.toml +2 -2
  10. model2vec_rs-0.5.1/python/README.md +66 -0
  11. model2vec_rs-0.5.1/python/model2vec_rs/__init__.py +5 -0
  12. model2vec_rs-0.5.1/python/model2vec_rs/__init__.pyi +67 -0
  13. model2vec_rs-0.5.1/python/model2vec_rs/py.typed +0 -0
  14. model2vec_rs-0.5.1/python/src/lib.rs +393 -0
  15. model2vec_rs-0.5.1/python/tests/test_bindings.py +461 -0
  16. model2vec_rs-0.5.1/scripts/ascii_chart.py +165 -0
  17. model2vec_rs-0.5.1/scripts/bench_suite.py +775 -0
  18. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/scripts/speedup_chart.py +10 -3
  19. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/fast_wordpiece.rs +799 -65
  20. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/lib.rs +1 -0
  21. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/model.rs +680 -75
  22. model2vec_rs-0.5.1/src/piece_table.rs +223 -0
  23. model2vec_rs-0.4.0/PKG-INFO +0 -58
  24. model2vec_rs-0.4.0/python/README.md +0 -44
  25. model2vec_rs-0.4.0/python/model2vec_rs.pyi +0 -33
  26. model2vec_rs-0.4.0/python/src/lib.rs +0 -199
  27. model2vec_rs-0.4.0/python/tests/test_bindings.py +0 -148
  28. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/.github/workflows/ci.yaml +0 -0
  29. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/.github/workflows/release.yaml +0 -0
  30. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/.gitignore +0 -0
  31. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/CITATION.cff +0 -0
  32. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/LICENSE +0 -0
  33. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/encode.rs +0 -0
  34. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/nanobeir.rs +0 -0
  35. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/nanobeir_baseline.json +0 -0
  36. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/python_compare.rs +0 -0
  37. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/quantize.rs +0 -0
  38. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/benches/throughput.rs +0 -0
  39. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/python/uv.lock +0 -0
  40. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/rustfmt.toml +0 -0
  41. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/scripts/bench_compare.py +0 -0
  42. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/scripts/bindings_chart.py +0 -0
  43. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/scripts/nanobeir.py +0 -0
  44. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/scripts/python_compare.py +0 -0
  45. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/fast_unigram.rs +0 -0
  46. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/main.rs +0 -0
  47. {model2vec_rs-0.4.0 → model2vec_rs-0.5.1}/src/trie.rs +0 -0
@@ -103,6 +103,19 @@ jobs:
103
103
  tar -xzf python/dist/*.tar.gz -C "$RUNNER_TEMP/sdist-check"
104
104
  python -m pip wheel --no-deps --wheel-dir "$RUNNER_TEMP/sdist-wheel" "$RUNNER_TEMP"/sdist-check/*/
105
105
 
106
+ - name: Check wheel built from sdist contents
107
+ shell: python
108
+ run: |
109
+ import glob, os, zipfile
110
+ (path,) = glob.glob(os.path.join(os.environ["RUNNER_TEMP"], "sdist-wheel", "*.whl"))
111
+ with zipfile.ZipFile(path) as whl:
112
+ names = set(whl.namelist())
113
+ for required in ("model2vec_rs/__init__.pyi", "model2vec_rs/py.typed"):
114
+ assert required in names, f"{required} missing from {path}"
115
+ (metadata,) = [n for n in names if n.endswith(".dist-info/METADATA")]
116
+ body = whl.read(metadata).decode().split("\n\n", 1)[1]
117
+ assert body.lstrip().startswith("# model2vec-rs (Python)"), "wheel long description is not python/README.md"
118
+
106
119
  - name: Test wheel built from sdist
107
120
  working-directory: python
108
121
  run: |
@@ -772,7 +772,7 @@ dependencies = [
772
772
 
773
773
  [[package]]
774
774
  name = "model2vec-rs"
775
- version = "0.4.0"
775
+ version = "0.5.1"
776
776
  dependencies = [
777
777
  "anyhow",
778
778
  "approx",
@@ -784,7 +784,7 @@ dependencies = [
784
784
  "serde_json",
785
785
  "tempfile",
786
786
  "tokenizers",
787
- "unicode-normalization",
787
+ "unicode-normalization-alignments",
788
788
  "unicode_categories",
789
789
  "ureq",
790
790
  ]
@@ -1281,21 +1281,6 @@ dependencies = [
1281
1281
  "zerovec",
1282
1282
  ]
1283
1283
 
1284
- [[package]]
1285
- name = "tinyvec"
1286
- version = "1.12.0"
1287
- source = "registry+https://github.com/rust-lang/crates.io-index"
1288
- checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
1289
- dependencies = [
1290
- "tinyvec_macros",
1291
- ]
1292
-
1293
- [[package]]
1294
- name = "tinyvec_macros"
1295
- version = "0.1.1"
1296
- source = "registry+https://github.com/rust-lang/crates.io-index"
1297
- checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
1298
-
1299
1284
  [[package]]
1300
1285
  name = "tokenizers"
1301
1286
  version = "0.21.4"
@@ -1337,15 +1322,6 @@ version = "1.0.18"
1337
1322
  source = "registry+https://github.com/rust-lang/crates.io-index"
1338
1323
  checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
1339
1324
 
1340
- [[package]]
1341
- name = "unicode-normalization"
1342
- version = "0.1.25"
1343
- source = "registry+https://github.com/rust-lang/crates.io-index"
1344
- checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
1345
- dependencies = [
1346
- "tinyvec",
1347
- ]
1348
-
1349
1325
  [[package]]
1350
1326
  name = "unicode-normalization-alignments"
1351
1327
  version = "0.1.12"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "model2vec-rs"
3
- version = "0.4.0"
3
+ version = "0.5.1"
4
4
  edition = "2024"
5
5
  rust-version = "1.88"
6
6
  description = "Official Rust Implementation of Model2Vec"
@@ -39,7 +39,7 @@ anyhow = "1.0"
39
39
  serde_json = { version = "1.0", features = ["raw_value"] }
40
40
  serde = { version = "1.0", features = ["derive"] }
41
41
  half = "2.0"
42
- unicode-normalization = "0.1"
42
+ unicode-normalization-alignments = "0.1"
43
43
  unicode_categories = "0.1"
44
44
 
45
45
  [dev-dependencies]
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: model2vec-rs
3
+ Version: 0.5.1
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Requires-Dist: numpy
7
+ Requires-Dist: pytest ; extra == 'dev'
8
+ Provides-Extra: dev
9
+ Summary: Python bindings for model2vec-rs, the Rust implementation of Model2Vec
10
+ License: MIT
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
13
+
14
+ # model2vec-rs (Python)
15
+
16
+ Python bindings for [model2vec-rs](https://github.com/MinishLab/model2vec-rs), the Rust implementation of [Model2Vec](https://github.com/MinishLab/model2vec).
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install maturin
22
+ maturin develop --release # from this directory
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```python
28
+ from model2vec_rs import StaticModel
29
+
30
+ model = StaticModel.from_pretrained("minishlab/potion-base-8M")
31
+
32
+ embeddings = model.encode(["Hello world", "Rust is awesome"]) # np.ndarray, shape (2, dim)
33
+ embedding = model.encode("Hello world") # np.ndarray, shape (dim,)
34
+
35
+ model.dim # int
36
+ model.normalize # bool, whether encode L2-normalizes by default
37
+ model.max_length # int | None, the default max tokens per sentence for encode
38
+ ```
39
+
40
+ `encode` accepts `max_length` (default: the model's `max_length`, `None` for no limit), `batch_size` (default `None`, which encodes all sentences in one parallel pass) and `normalize` (default `None`, which uses the model's setting), and releases the GIL while encoding.
41
+
42
+ As in `model2vec`, the model's `max_length` comes from its config (512 if unset, `null` for no limit). Override it with `StaticModel.from_pretrained(..., max_length=...)`; `from_arrays` defaults to 512.
43
+
44
+ ### Loading from arrays
45
+
46
+ `from_arrays` builds a model from a tokenizer JSON string and NumPy arrays you have already loaded:
47
+
48
+ ```python
49
+ import numpy as np
50
+ from model2vec_rs import StaticModel
51
+
52
+ tokenizer = open("tokenizer.json").read()
53
+ embeddings = np.load("embeddings.npy") # float32 or int8, shape (rows, dim)
54
+
55
+ model = StaticModel.from_arrays(tokenizer, embeddings, normalize=True)
56
+ ```
57
+
58
+ `embeddings` and `weights` are copied, so later changes to your arrays don't affect the model. To avoid the copy, pass C-contiguous arrays over memory that cannot be written to, such as `np.load("embeddings.npy", mmap_mode="r")` or `np.frombuffer(data, dtype=np.float32).reshape(rows, dim)` with `data` a `bytes` object: these are shared with the model, which keeps them alive. Writable arrays are always copied, because another thread could write to them while `encode` reads them without the GIL. `token_mapping` is always copied.
59
+
60
+ `model.embeddings` and `model.weights` return the arrays the model reads from as read-only arrays, without copying. Use them instead of your original arrays to keep only one copy in memory; passing them to `from_arrays` again shares them with the new model. They are `None` for models loaded with `from_pretrained`.
61
+
62
+ ## Performance
63
+
64
+ We encoded the same 666,808 Wikipedia paragraphs (11M words) with [`blink-8m`](https://huggingface.co/minishlab/blink-8m) using the Rust crate, these bindings, and Python [`model2vec`](https://github.com/MinishLab/model2vec):
65
+
66
+ <p align="center">
67
+ <img width="85%" alt="Encoding throughput of Rust, the Python bindings and Python model2vec" src="https://raw.githubusercontent.com/MinishLab/model2vec-rs/main/assets/images/bindings_throughput.png">
68
+ </p>
69
+
70
+ On a single thread the bindings are about as fast as Rust and roughly **24×** faster than `model2vec`; on all cores they are roughly **38×** faster than `model2vec`.
71
+
72
+ To reproduce (from the repository root):
73
+
74
+ ```bash
75
+ uv run --with ./python scripts/python_compare.py --model minishlab/blink-8m --bindings --rust-api flat --no-python-multiprocessing --out bindings.json
76
+ uv run scripts/bindings_chart.py bindings.json
77
+ ```
78
+
79
+ Measured on an Apple M3 Pro with 5 alternating rounds per implementation, 5 timed passes each; throughput is the median over all passes. As in the [main benchmark](https://github.com/MinishLab/model2vec-rs#performance), `model2vec` runs with `use_multiprocessing=False`, which is faster than its default process pool. See [`scripts/python_compare.py`](https://github.com/MinishLab/model2vec-rs/blob/main/scripts/python_compare.py) for the options.
80
+
@@ -75,7 +75,8 @@ fn main() -> Result<()> {
75
75
  ];
76
76
 
77
77
  // Generate embeddings using default parameters
78
- // (Default max_length: Some(512), all sentences in one batch)
78
+ // (Default max_length: the config's `max_length` (512 if unset), all sentences in one batch;
79
+ // change it with `model.with_max_length(...)`)
79
80
  let embeddings = model.encode(&sentences);
80
81
  // `embeddings` is a Vec<Vec<f32>>
81
82
  println!("Generated {} embeddings.", embeddings.len());
@@ -85,6 +86,7 @@ fn main() -> Result<()> {
85
86
  &sentences,
86
87
  Some(256), // Optional: custom max token length for truncation
87
88
  512, // Custom batch size for processing
89
+ None, // Optional: override the model's normalization setting
88
90
  );
89
91
  println!("Generated {} custom embeddings.", custom_embeddings.len());
90
92
 
@@ -126,7 +128,7 @@ use model2vec_rs::model::StaticModel;
126
128
  let model = StaticModel::from_pretrained("minishlab/potion-base-8M", None, None, None)?.quantize_int8();
127
129
  ```
128
130
 
129
- `quantize_int8` stores the embeddings as int8 with one scale per row, using a quarter of the memory and encoding faster. Outputs stay very close to the f32 model (cosine similarity above 0.9998 on the potion models).
131
+ `quantize_int8` stores the embeddings as int8 with one scale per column and a power-of-two scale per row, using a quarter of the memory and encoding faster, since pooling then sums integers. Outputs stay very close to the f32 model (cosine similarity above 0.9997 on the potion models).
130
132
 
131
133
  See the [feature flags](#feature-flags) section for `wasm` and `local-only` build configurations.
132
134
 
@@ -177,7 +179,7 @@ See the [bindings README](python/README.md) for installation, the API and benchm
177
179
  * **Fast Inference:** Optimized Rust implementation for fast embedding generation.
178
180
  * **Hugging Face Hub Integration:** Load pre-trained Model2Vec models directly from the Hugging Face Hub using model IDs, or use models from local paths.
179
181
  * **Model Formats:** Supports models with f32, f16, and i8 weight types stored in `safetensors` files. Int8 models (model2vec's `quantize_to="int8"`) stay int8 in memory, and f32 models can be quantized to int8 at load time with `quantize_int8`.
180
- * **Flexible Loading:** Load models from the Hub (`from_pretrained`), raw bytes (`from_bytes`), or owned/borrowed data (`from_owned`, `from_borrowed`, and `from_owned_i8`, `from_borrowed_i8` for int8 embeddings) for embedded and WASM use cases.
182
+ * **Flexible Loading:** Load models from the Hub (`from_pretrained`), raw bytes (`from_bytes`), or owned/borrowed/shared data (`from_owned`, `from_borrowed`, `from_shared`, and `from_owned_i8`, `from_borrowed_i8`, `from_shared_i8` for int8 embeddings) for embedded and WASM use cases, or for data owned elsewhere, such as NumPy arrays. Models built from owned/borrowed/shared data truncate at 512 tokens by default; change this with `with_max_length`.
181
183
  * **Batch Processing:** Encodes multiple sentences in batches.
182
184
  * **Configurable Encoding:** Allows customization of maximum sequence length and batch size during encoding.
183
185
 
@@ -223,15 +225,15 @@ A variety of pre-trained Model2Vec models are available on the [HuggingFace Hub
223
225
 
224
226
  ## Performance
225
227
 
226
- We compared `model2vec-rs` with the Python version of Model2Vec by encoding the same 666,808 texts with [`potion-base-8M`](https://huggingface.co/minishlab/potion-base-8M) in both.
228
+ We compared `model2vec-rs` with the Python version of Model2Vec by encoding the same 666,808 texts with [`blink-8m`](https://huggingface.co/minishlab/blink-8m) in both.
227
229
 
228
230
  | Implementation | Single thread | All cores | Model load |
229
231
  | -------------- | ------------------- | --------------------- | ---------- |
230
- | **Rust** | 575K texts/second | 2.60M texts/second | 24 ms |
231
- | **Python** | 38K texts/second | 110K texts/second | 436 ms |
232
- | **Speedup** | **15.2×** | **23.6×** | **18.2×** |
232
+ | **Rust** | 1.13M texts/second | 4.93M texts/second | 30 ms |
233
+ | **Python** | 45K texts/second | 134K texts/second | 464 ms |
234
+ | **Speedup** | **25.4×** | **36.9×** | **15.5×** |
233
235
 
234
- On a single thread, the Rust version is roughly **15×** faster than the Python version, and about **24×** faster when using all cores. With int8 models the speedup is larger:
236
+ On a single thread, the Rust version is roughly **25×** faster than the Python version, and about **37×** faster when using all cores. With int8 models the speedup is larger:
235
237
 
236
238
  <div align="center">
237
239
  <img width="85%" alt="model2vec-rs speedup over Python model2vec" src="assets/images/speedup.png">
@@ -240,7 +242,7 @@ On a single thread, the Rust version is roughly **15×** faster than the Python
240
242
  To reproduce these numbers, run this from the repository root (it needs Rust and [`uv`](https://docs.astral.sh/uv/)):
241
243
 
242
244
  ```sh
243
- uv run scripts/python_compare.py --no-python-multiprocessing
245
+ uv run scripts/python_compare.py --model minishlab/blink-8m --no-python-multiprocessing
244
246
  ```
245
247
 
246
248
  The script downloads the corpus, builds [`benches/python_compare.rs`](benches/python_compare.rs), runs both implementations and prints the table above. For the int8 bars of the chart, add `--quantize int8`, then pass both results to [`scripts/speedup_chart.py`](scripts/speedup_chart.py). See [`scripts/python_compare.py`](scripts/python_compare.py) for the options.
@@ -250,17 +252,17 @@ Benchmark details:
250
252
  * **Corpus:** 28,721 random articles from English Wikipedia: shard [`20231101.en/train-00017-of-00041.parquet`](https://huggingface.co/datasets/wikimedia/wikipedia/blob/b04c8d1ceb2f5cd4588862100d08de323dccfbaa/20231101.en/train-00017-of-00041.parquet) of [`wikimedia/wikipedia`](https://huggingface.co/datasets/wikimedia/wikipedia), shuffled with seed 0 and taken until they reach 11M words, joined by blank lines (70.0 MB, SHA-256 `b6535c025aca457f71ef010b7c4d06f54f564981cb6db5683437ccc8e1ae9710`).
251
253
  * **Texts:** each of the 666,808 non-empty lines (paragraphs and section headings, 16.5 words and 104 bytes on average) is one text. Every timed pass encodes all of them in a single `encode` call with the default `max_length` of 512.
252
254
  * **Hardware:** Apple M3 Pro (12 cores), 18 GB RAM.
253
- * **Software:** `model2vec-rs` 0.4.0 (release build, Rust 1.99.1); Python 3.14.3 with `model2vec` 0.10.0, `tokenizers` 0.23.3 and `numpy` 2.5.4.
255
+ * **Software:** `model2vec-rs` 0.5.1 (release build, Rust 1.99.1); Python 3.14.6 with `model2vec` 0.10.0, `tokenizers` 0.23.3 and `numpy` 2.5.5.
254
256
  * **Single thread:** `RAYON_NUM_THREADS=1` and `TOKENIZERS_PARALLELISM=false` for both; Python with `use_multiprocessing=False`.
255
257
  * **All cores:** Rust with Rayon parallelism; Python with tokenizer parallelism and `use_multiprocessing=False`. Python's default `use_multiprocessing=True` spreads the texts over a process pool, which makes it slower.
256
258
  * **Method:** 5 alternating rounds of Rust and Python processes, 5 timed passes each after one warm-up pass; throughput is the median over the 25 passes.
257
259
  * **Model load:** median time over all 10 process launches per side to load the model from the local Hugging Face cache; for Python this includes importing `model2vec`.
258
- * **Output:** for float32, the Rust and Python embeddings differ by at most 3.0e-7 per value (minimum cosine similarity 0.9999998).
259
- * **int8:** the model is quantized at load time on both sides, with `quantize_int8` in Rust and `quantize_to="int8"` in Python. Rust keeps one scale per row and Python one scale for the whole table, so the int8 embeddings differ between the two (minimum cosine similarity 0.27); these bars compare speed only.
260
+ * **Output:** for float32, the Rust and Python embeddings differ by at most 6.0e-8 per value (minimum cosine similarity 0.9999999).
261
+ * **int8:** the model is quantized at load time on both sides, with `quantize_int8` in Rust and `quantize_to="int8"` in Python. Rust keeps one scale per column plus a power-of-two scale per row and Python one scale for the whole table, so the int8 embeddings differ between the two; these bars compare speed only.
260
262
 
261
263
  ## Relation to Python `model2vec`
262
264
 
263
- * **`model2vec-rs` (This Crate):** High-performance Rust engine for up to 28x faster **Model2Vec inference**.
265
+ * **`model2vec-rs` (This Crate):** High-performance Rust engine for up to 51x faster **Model2Vec inference**.
264
266
  * **[`model2vec`](https://github.com/MinishLab/model2vec) (Python-based):** Handles model **distillation, training, fine-tuning**, and slower Python-based inference.
265
267
 
266
268
  ## License
@@ -45,6 +45,36 @@ For trustworthy numbers:
45
45
  4. Only claim a speedup for configurations marked `faster` whose output is
46
46
  `identical` (for changes that must not alter embeddings).
47
47
 
48
+ ## Full suite: corpora, languages and other libraries
49
+
50
+ ```sh
51
+ uv run scripts/bench_suite.py --quick # smoke run: big, en, ko
52
+ uv run scripts/bench_suite.py # everything
53
+ uv run scripts/bench_suite.py --sections libs --corpora en,ko --modes batch
54
+ ```
55
+
56
+ `scripts/bench_suite.py` rebuilds its inputs from pinned sources under
57
+ `target/bench-suite/data/`, checking each corpus against a SHA-256 digest:
58
+ `big.txt`, NanoMIRACL passages in 18 languages (`hakari-bench/NanoMIRACL`,
59
+ pinned revision), the English passages with non-ASCII chars removed, and
60
+ Python-style int8 copies (one scale for the whole table) of three models.
61
+ It then runs:
62
+
63
+ - `ab`: `bench_compare.py` on every corpus, `--baseline` vs `--candidate`.
64
+ - `int8-ab`: `bench_compare.py` on the int8 copies.
65
+ - `libs`: MB/s of model2vec-rs (f32, `quantize_int8`, Python int8),
66
+ [go-potion](https://github.com/trengrj/go-potion) at a pinned version
67
+ from the Go module proxy (or a local checkout with `--go-potion PATH`), and
68
+ [encoders](https://crates.io/crates/encoders) (f32 and int8), on 256-word
69
+ chunks: one chunk per call on one thread, and one batch on all cores.
70
+ - `accuracy`: cosine similarity of every library and precision to the
71
+ model2vec-rs f32 output.
72
+
73
+ go-potion and encoders are skipped, with a notice, when they cannot be
74
+ built. encoders runs batches of fewer than 128 texts on one thread; the
75
+ report marks corpora where that applies. Results are written to
76
+ `target/bench-suite/results/<timestamp>/` (`report.md`, `results.json`).
77
+
48
78
  ## Comparing with Python model2vec
49
79
 
50
80
  ```sh
@@ -76,7 +106,7 @@ for model_id in ["minishlab/potion-base-8M", "minishlab/potion-retrieval-32M"]:
76
106
  ## Runtime int8 quantization
77
107
 
78
108
  `quantize.rs` compares the f32 model, a separately loaded copy of it (a
79
- control that should come out at 1.00x), the per-row quantized model, and
109
+ control that should come out at 1.00x), the `quantize_int8` model, and
80
110
  optionally a model2vec int8 model, all in one process:
81
111
 
82
112
  ```sh
@@ -5,7 +5,6 @@ build-backend = "maturin"
5
5
  [project]
6
6
  name = "model2vec-rs"
7
7
  description = "Python bindings for model2vec-rs, the Rust implementation of Model2Vec"
8
- readme = "README.md"
9
8
  license = { text = "MIT" }
10
9
  requires-python = ">=3.10"
11
10
  dependencies = ["numpy"]
@@ -13,21 +12,25 @@ classifiers = [
13
12
  "Programming Language :: Rust",
14
13
  "Programming Language :: Python :: Implementation :: CPython",
15
14
  ]
16
- dynamic = ["version"]
15
+ dynamic = ["version", "readme"]
17
16
 
18
17
  [project.optional-dependencies]
19
18
  dev = ["pytest"]
20
19
 
21
20
  [tool.maturin]
22
- module-name = "model2vec_rs"
21
+ module-name = "model2vec_rs.model2vec_rs"
23
22
  features = ["pyo3/extension-module"]
24
23
  manifest-path = "python/Cargo.toml"
24
+ python-source = "python"
25
25
 
26
26
  [tool.uv]
27
27
  cache-keys = [
28
28
  { file = "pyproject.toml" },
29
29
  { file = "Cargo.toml" },
30
30
  { file = "src/**/*.rs" },
31
+ { file = "python/**/*.py" },
32
+ { file = "python/**/*.pyi" },
33
+ { file = "python/**/py.typed" },
31
34
  { file = "../Cargo.toml" },
32
35
  { file = "../src/**/*.rs" },
33
36
  ]
@@ -651,7 +651,7 @@ dependencies = [
651
651
 
652
652
  [[package]]
653
653
  name = "model2vec-rs"
654
- version = "0.4.0"
654
+ version = "0.5.1"
655
655
  dependencies = [
656
656
  "anyhow",
657
657
  "half",
@@ -660,14 +660,14 @@ dependencies = [
660
660
  "serde",
661
661
  "serde_json",
662
662
  "tokenizers",
663
- "unicode-normalization",
663
+ "unicode-normalization-alignments",
664
664
  "unicode_categories",
665
665
  "ureq",
666
666
  ]
667
667
 
668
668
  [[package]]
669
669
  name = "model2vec-rs-python"
670
- version = "0.4.0"
670
+ version = "0.5.1"
671
671
  dependencies = [
672
672
  "model2vec-rs",
673
673
  "ndarray",
@@ -1305,12 +1305,6 @@ dependencies = [
1305
1305
  "zerovec",
1306
1306
  ]
1307
1307
 
1308
- [[package]]
1309
- name = "tinyvec"
1310
- version = "1.13.3"
1311
- source = "registry+https://github.com/rust-lang/crates.io-index"
1312
- checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
1313
-
1314
1308
  [[package]]
1315
1309
  name = "tokenizers"
1316
1310
  version = "0.21.4"
@@ -1351,15 +1345,6 @@ version = "1.0.27"
1351
1345
  source = "registry+https://github.com/rust-lang/crates.io-index"
1352
1346
  checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
1353
1347
 
1354
- [[package]]
1355
- name = "unicode-normalization"
1356
- version = "0.1.26"
1357
- source = "registry+https://github.com/rust-lang/crates.io-index"
1358
- checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
1359
- dependencies = [
1360
- "tinyvec",
1361
- ]
1362
-
1363
1348
  [[package]]
1364
1349
  name = "unicode-normalization-alignments"
1365
1350
  version = "0.1.12"
@@ -1,12 +1,12 @@
1
1
  [package]
2
2
  name = "model2vec-rs-python"
3
- version = "0.4.0"
3
+ version = "0.5.1"
4
4
  edition = "2024"
5
5
  rust-version = "1.88"
6
6
  description = "Python bindings for model2vec-rs"
7
7
  license = "MIT"
8
- publish = false
9
8
  readme = "README.md"
9
+ publish = false
10
10
 
11
11
  [lib]
12
12
  name = "model2vec_rs_py"
@@ -0,0 +1,66 @@
1
+ # model2vec-rs (Python)
2
+
3
+ Python bindings for [model2vec-rs](https://github.com/MinishLab/model2vec-rs), the Rust implementation of [Model2Vec](https://github.com/MinishLab/model2vec).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install maturin
9
+ maturin develop --release # from this directory
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```python
15
+ from model2vec_rs import StaticModel
16
+
17
+ model = StaticModel.from_pretrained("minishlab/potion-base-8M")
18
+
19
+ embeddings = model.encode(["Hello world", "Rust is awesome"]) # np.ndarray, shape (2, dim)
20
+ embedding = model.encode("Hello world") # np.ndarray, shape (dim,)
21
+
22
+ model.dim # int
23
+ model.normalize # bool, whether encode L2-normalizes by default
24
+ model.max_length # int | None, the default max tokens per sentence for encode
25
+ ```
26
+
27
+ `encode` accepts `max_length` (default: the model's `max_length`, `None` for no limit), `batch_size` (default `None`, which encodes all sentences in one parallel pass) and `normalize` (default `None`, which uses the model's setting), and releases the GIL while encoding.
28
+
29
+ As in `model2vec`, the model's `max_length` comes from its config (512 if unset, `null` for no limit). Override it with `StaticModel.from_pretrained(..., max_length=...)`; `from_arrays` defaults to 512.
30
+
31
+ ### Loading from arrays
32
+
33
+ `from_arrays` builds a model from a tokenizer JSON string and NumPy arrays you have already loaded:
34
+
35
+ ```python
36
+ import numpy as np
37
+ from model2vec_rs import StaticModel
38
+
39
+ tokenizer = open("tokenizer.json").read()
40
+ embeddings = np.load("embeddings.npy") # float32 or int8, shape (rows, dim)
41
+
42
+ model = StaticModel.from_arrays(tokenizer, embeddings, normalize=True)
43
+ ```
44
+
45
+ `embeddings` and `weights` are copied, so later changes to your arrays don't affect the model. To avoid the copy, pass C-contiguous arrays over memory that cannot be written to, such as `np.load("embeddings.npy", mmap_mode="r")` or `np.frombuffer(data, dtype=np.float32).reshape(rows, dim)` with `data` a `bytes` object: these are shared with the model, which keeps them alive. Writable arrays are always copied, because another thread could write to them while `encode` reads them without the GIL. `token_mapping` is always copied.
46
+
47
+ `model.embeddings` and `model.weights` return the arrays the model reads from as read-only arrays, without copying. Use them instead of your original arrays to keep only one copy in memory; passing them to `from_arrays` again shares them with the new model. They are `None` for models loaded with `from_pretrained`.
48
+
49
+ ## Performance
50
+
51
+ We encoded the same 666,808 Wikipedia paragraphs (11M words) with [`blink-8m`](https://huggingface.co/minishlab/blink-8m) using the Rust crate, these bindings, and Python [`model2vec`](https://github.com/MinishLab/model2vec):
52
+
53
+ <p align="center">
54
+ <img width="85%" alt="Encoding throughput of Rust, the Python bindings and Python model2vec" src="https://raw.githubusercontent.com/MinishLab/model2vec-rs/main/assets/images/bindings_throughput.png">
55
+ </p>
56
+
57
+ On a single thread the bindings are about as fast as Rust and roughly **24×** faster than `model2vec`; on all cores they are roughly **38×** faster than `model2vec`.
58
+
59
+ To reproduce (from the repository root):
60
+
61
+ ```bash
62
+ uv run --with ./python scripts/python_compare.py --model minishlab/blink-8m --bindings --rust-api flat --no-python-multiprocessing --out bindings.json
63
+ uv run scripts/bindings_chart.py bindings.json
64
+ ```
65
+
66
+ Measured on an Apple M3 Pro with 5 alternating rounds per implementation, 5 timed passes each; throughput is the median over all passes. As in the [main benchmark](https://github.com/MinishLab/model2vec-rs#performance), `model2vec` runs with `use_multiprocessing=False`, which is faster than its default process pool. See [`scripts/python_compare.py`](https://github.com/MinishLab/model2vec-rs/blob/main/scripts/python_compare.py) for the options.
@@ -0,0 +1,5 @@
1
+ from .model2vec_rs import *
2
+
3
+ __doc__ = model2vec_rs.__doc__
4
+ if hasattr(model2vec_rs, "__all__"):
5
+ __all__ = model2vec_rs.__all__
@@ -0,0 +1,67 @@
1
+ import os
2
+ from collections.abc import Sequence
3
+ from typing import overload
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ __version__: str
9
+
10
+ class StaticModel:
11
+ @staticmethod
12
+ def from_pretrained(
13
+ path: str | os.PathLike[str],
14
+ token: str | None = None,
15
+ normalize: bool | None = None,
16
+ subfolder: str | None = None,
17
+ max_length: int | None = ...,
18
+ ) -> StaticModel: ...
19
+ @staticmethod
20
+ def from_arrays(
21
+ tokenizer: str,
22
+ embeddings: npt.NDArray[np.float32] | npt.NDArray[np.int8],
23
+ normalize: bool = False,
24
+ weights: npt.NDArray[np.float32] | None = None,
25
+ token_mapping: npt.NDArray[np.int64] | None = None,
26
+ max_length: int | None = 512,
27
+ ) -> StaticModel:
28
+ """Build a model from in-memory data.
29
+
30
+ `embeddings` and `weights` are copied, unless they are C-contiguous arrays over memory that cannot be
31
+ written to, such as `np.frombuffer(bytes)`, `np.load(..., mmap_mode="r")`, or the `embeddings` and
32
+ `weights` of another model: those are shared with the model instead. `token_mapping` is always copied.
33
+ """
34
+ @overload
35
+ def encode(
36
+ self,
37
+ sentences: str,
38
+ max_length: int | None = ...,
39
+ batch_size: int | None = None,
40
+ normalize: bool | None = None,
41
+ ) -> npt.NDArray[np.float32]: ...
42
+ @overload
43
+ def encode(
44
+ self,
45
+ sentences: Sequence[str],
46
+ max_length: int | None = ...,
47
+ batch_size: int | None = None,
48
+ normalize: bool | None = None,
49
+ ) -> npt.NDArray[np.float32]: ...
50
+ @property
51
+ def dim(self) -> int: ...
52
+ @property
53
+ def normalize(self) -> bool: ...
54
+ @property
55
+ def max_length(self) -> int | None: ...
56
+ @property
57
+ def embeddings(self) -> npt.NDArray[np.float32] | npt.NDArray[np.int8] | None:
58
+ """The embedding table of a model built with `from_arrays`, as a read-only array over the model's memory.
59
+
60
+ None for a model loaded with `from_pretrained`.
61
+ """
62
+ @property
63
+ def weights(self) -> npt.NDArray[np.float32] | None:
64
+ """The token weights of a model built with `from_arrays`, as a read-only array over the model's memory.
65
+
66
+ None if the model has no weights or was loaded with `from_pretrained`.
67
+ """
File without changes