model2vec-rs 0.4.0__tar.gz → 0.5.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 (39) hide show
  1. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/.github/workflows/release-python.yaml +13 -0
  2. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/Cargo.lock +1 -1
  3. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/Cargo.toml +1 -1
  4. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/PKG-INFO +6 -2
  5. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/README.md +4 -2
  6. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/pyproject.toml +6 -3
  7. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/Cargo.lock +2 -2
  8. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/Cargo.toml +2 -2
  9. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/README.md +5 -1
  10. model2vec_rs-0.5.0/python/model2vec_rs/__init__.py +5 -0
  11. model2vec_rs-0.4.0/python/model2vec_rs.pyi → model2vec_rs-0.5.0/python/model2vec_rs/__init__.pyi +19 -3
  12. model2vec_rs-0.5.0/python/model2vec_rs/py.typed +0 -0
  13. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/src/lib.rs +97 -23
  14. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/tests/test_bindings.py +94 -0
  15. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/src/model.rs +65 -19
  16. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/.github/workflows/ci.yaml +0 -0
  17. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/.github/workflows/release.yaml +0 -0
  18. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/.gitignore +0 -0
  19. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/CITATION.cff +0 -0
  20. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/LICENSE +0 -0
  21. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/README.md +0 -0
  22. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/encode.rs +0 -0
  23. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/nanobeir.rs +0 -0
  24. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/nanobeir_baseline.json +0 -0
  25. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/python_compare.rs +0 -0
  26. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/quantize.rs +0 -0
  27. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/benches/throughput.rs +0 -0
  28. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/python/uv.lock +0 -0
  29. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/rustfmt.toml +0 -0
  30. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/scripts/bench_compare.py +0 -0
  31. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/scripts/bindings_chart.py +0 -0
  32. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/scripts/nanobeir.py +0 -0
  33. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/scripts/python_compare.py +0 -0
  34. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/scripts/speedup_chart.py +0 -0
  35. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/src/fast_unigram.rs +0 -0
  36. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/src/fast_wordpiece.rs +0 -0
  37. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/src/lib.rs +0 -0
  38. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/src/main.rs +0 -0
  39. {model2vec_rs-0.4.0 → model2vec_rs-0.5.0}/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.0"
776
776
  dependencies = [
777
777
  "anyhow",
778
778
  "approx",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "model2vec-rs"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  edition = "2024"
5
5
  rust-version = "1.88"
6
6
  description = "Official Rust Implementation of Model2Vec"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: model2vec-rs
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Requires-Dist: numpy
@@ -33,9 +33,13 @@ embeddings = model.encode(["Hello world", "Rust is awesome"]) # np.ndarray, sha
33
33
  embedding = model.encode("Hello world") # np.ndarray, shape (dim,)
34
34
 
35
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
36
38
  ```
37
39
 
38
- `encode` accepts `max_length` (default `512`, `None` for no limit) and `batch_size` (default `None`, which encodes all sentences in one parallel pass), and releases the GIL while encoding.
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.
39
43
 
40
44
  ## Performance
41
45
 
@@ -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
 
@@ -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 data (`from_owned`, `from_borrowed`, and `from_owned_i8`, `from_borrowed_i8` for int8 embeddings) for embedded and WASM use cases. Models built from owned/borrowed 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
 
@@ -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.0"
655
655
  dependencies = [
656
656
  "anyhow",
657
657
  "half",
@@ -667,7 +667,7 @@ dependencies = [
667
667
 
668
668
  [[package]]
669
669
  name = "model2vec-rs-python"
670
- version = "0.4.0"
670
+ version = "0.5.0"
671
671
  dependencies = [
672
672
  "model2vec-rs",
673
673
  "ndarray",
@@ -1,12 +1,12 @@
1
1
  [package]
2
2
  name = "model2vec-rs-python"
3
- version = "0.4.0"
3
+ version = "0.5.0"
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"
@@ -20,9 +20,13 @@ embeddings = model.encode(["Hello world", "Rust is awesome"]) # np.ndarray, sha
20
20
  embedding = model.encode("Hello world") # np.ndarray, shape (dim,)
21
21
 
22
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
23
25
  ```
24
26
 
25
- `encode` accepts `max_length` (default `512`, `None` for no limit) and `batch_size` (default `None`, which encodes all sentences in one parallel pass), and releases the GIL while encoding.
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.
26
30
 
27
31
  ## Performance
28
32
 
@@ -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__
@@ -14,20 +14,36 @@ class StaticModel:
14
14
  token: str | None = None,
15
15
  normalize: bool | None = None,
16
16
  subfolder: str | None = None,
17
+ max_length: int | None = ...,
17
18
  ) -> StaticModel: ...
18
19
  @staticmethod
19
20
  def from_arrays(
20
21
  tokenizer: str,
21
- embeddings: npt.NDArray[np.float32],
22
+ embeddings: npt.NDArray[np.float32] | npt.NDArray[np.int8],
22
23
  normalize: bool = False,
23
24
  weights: npt.NDArray[np.float32] | None = None,
24
25
  token_mapping: npt.NDArray[np.int64] | None = None,
26
+ max_length: int | None = 512,
25
27
  ) -> StaticModel: ...
26
28
  @overload
27
- def encode(self, sentences: str, max_length: int | None = 512, batch_size: int | None = None) -> npt.NDArray[np.float32]: ...
29
+ def encode(
30
+ self,
31
+ sentences: str,
32
+ max_length: int | None = ...,
33
+ batch_size: int | None = None,
34
+ normalize: bool | None = None,
35
+ ) -> npt.NDArray[np.float32]: ...
28
36
  @overload
29
37
  def encode(
30
- self, sentences: Sequence[str], max_length: int | None = 512, batch_size: int | None = None
38
+ self,
39
+ sentences: Sequence[str],
40
+ max_length: int | None = ...,
41
+ batch_size: int | None = None,
42
+ normalize: bool | None = None,
31
43
  ) -> npt.NDArray[np.float32]: ...
32
44
  @property
33
45
  def dim(self) -> int: ...
46
+ @property
47
+ def normalize(self) -> bool: ...
48
+ @property
49
+ def max_length(self) -> int | None: ...
File without changes
@@ -1,7 +1,7 @@
1
1
  use std::path::PathBuf;
2
2
  use std::str::FromStr;
3
3
 
4
- use model2vec_rs::model::StaticModel as RustStaticModel;
4
+ use model2vec_rs::model::{DEFAULT_MAX_LENGTH, StaticModel as RustStaticModel};
5
5
  use ndarray::Array2;
6
6
  use numpy::{IntoPyArray, PyReadonlyArray1, PyReadonlyArray2};
7
7
  use pyo3::exceptions::PyValueError;
@@ -16,6 +16,43 @@ enum Sentences {
16
16
  Many(Vec<String>),
17
17
  }
18
18
 
19
+ #[derive(FromPyObject)]
20
+ enum EmbeddingArray<'py> {
21
+ F32(PyReadonlyArray2<'py, f32>),
22
+ I8(PyReadonlyArray2<'py, i8>),
23
+ }
24
+
25
+ impl EmbeddingArray<'_> {
26
+ fn dim(&self) -> (usize, usize) {
27
+ match self {
28
+ Self::F32(array) => array.as_array().dim(),
29
+ Self::I8(array) => array.as_array().dim(),
30
+ }
31
+ }
32
+ }
33
+
34
+ enum MaxLength {
35
+ Unset,
36
+ Set(Option<usize>),
37
+ }
38
+
39
+ impl<'a, 'py> FromPyObject<'a, 'py> for MaxLength {
40
+ type Error = PyErr;
41
+
42
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
43
+ Ok(Self::Set(obj.extract()?))
44
+ }
45
+ }
46
+
47
+ impl MaxLength {
48
+ fn or(self, default: Option<usize>) -> Option<usize> {
49
+ match self {
50
+ Self::Unset => default,
51
+ Self::Set(max_length) => max_length,
52
+ }
53
+ }
54
+ }
55
+
19
56
  /// Static embedding model for Model2Vec.
20
57
  #[pyclass(module = "model2vec_rs", name = "StaticModel", frozen)]
21
58
  struct StaticModel {
@@ -31,39 +68,46 @@ impl StaticModel {
31
68
  /// token: Optional Hugging Face token for private models.
32
69
  /// normalize: Override the normalization setting from the model config.
33
70
  /// subfolder: Optional subfolder within the repo or folder.
71
+ /// max_length: Override the default maximum number of tokens per sentence used by `encode`,
72
+ /// or None for no limit. If not passed, the value from the model config is used (512 if unset).
34
73
  #[staticmethod]
35
- #[pyo3(signature = (path, token=None, normalize=None, subfolder=None))]
74
+ #[pyo3(signature = (path, token=None, normalize=None, subfolder=None, max_length=MaxLength::Unset))]
36
75
  fn from_pretrained(
37
76
  py: Python<'_>,
38
77
  path: PathBuf,
39
78
  token: Option<&str>,
40
79
  normalize: Option<bool>,
41
80
  subfolder: Option<&str>,
81
+ max_length: MaxLength,
42
82
  ) -> PyResult<Self> {
43
83
  let model = py.detach(|| RustStaticModel::from_pretrained(path, token, normalize, subfolder))?;
44
- Ok(Self { model })
84
+ let max_length = max_length.or(model.max_length());
85
+ Ok(Self {
86
+ model: model.with_max_length(max_length),
87
+ })
45
88
  }
46
89
 
47
90
  /// Build a model from in-memory data.
48
91
  ///
49
92
  /// Args:
50
93
  /// tokenizer: The tokenizer serialized as a JSON string.
51
- /// embeddings: A float32 array of shape (rows, dim).
94
+ /// embeddings: A float32 or int8 array of shape (rows, dim).
52
95
  /// normalize: Whether to L2-normalize output embeddings.
53
96
  /// weights: Optional float32 per-token weights, indexed by token id.
54
97
  /// token_mapping: Optional int64 mapping from token id to embedding row.
98
+ /// max_length: The default maximum number of tokens per sentence used by `encode`, or None for no limit.
55
99
  #[staticmethod]
56
- #[pyo3(signature = (tokenizer, embeddings, normalize=false, weights=None, token_mapping=None))]
100
+ #[pyo3(signature = (tokenizer, embeddings, normalize=false, weights=None, token_mapping=None, max_length=Some(DEFAULT_MAX_LENGTH)))]
57
101
  fn from_arrays(
58
102
  tokenizer: &str,
59
- embeddings: PyReadonlyArray2<'_, f32>,
103
+ embeddings: EmbeddingArray<'_>,
60
104
  normalize: bool,
61
105
  weights: Option<PyReadonlyArray1<'_, f32>>,
62
106
  token_mapping: Option<PyReadonlyArray1<'_, i64>>,
107
+ max_length: Option<usize>,
63
108
  ) -> PyResult<Self> {
64
109
  let tokenizer = Tokenizer::from_str(tokenizer)
65
110
  .map_err(|e| PyValueError::new_err(format!("failed to load tokenizer: {e}")))?;
66
- let embeddings = embeddings.as_array();
67
111
  let (rows, cols) = embeddings.dim();
68
112
  let vocab_size = tokenizer
69
113
  .get_vocab(true)
@@ -106,35 +150,53 @@ impl StaticModel {
106
150
  weights.as_array().len()
107
151
  )));
108
152
  }
109
- let model = RustStaticModel::from_owned(
110
- tokenizer,
111
- embeddings.iter().copied().collect(),
112
- rows,
113
- cols,
114
- normalize,
115
- weights.map(|w| w.as_array().to_vec()),
116
- token_mapping,
117
- )?;
118
- Ok(Self { model })
153
+ let weights = weights.map(|w| w.as_array().to_vec());
154
+ let model = match embeddings {
155
+ EmbeddingArray::F32(array) => RustStaticModel::from_owned(
156
+ tokenizer,
157
+ array.as_array().iter().copied().collect(),
158
+ rows,
159
+ cols,
160
+ normalize,
161
+ weights,
162
+ token_mapping,
163
+ )?,
164
+ EmbeddingArray::I8(array) => RustStaticModel::from_owned_i8(
165
+ tokenizer,
166
+ array.as_array().iter().copied().collect(),
167
+ rows,
168
+ cols,
169
+ normalize,
170
+ weights,
171
+ token_mapping,
172
+ )?,
173
+ };
174
+ Ok(Self {
175
+ model: model.with_max_length(max_length),
176
+ })
119
177
  }
120
178
 
121
179
  /// Encode one or more sentences into embeddings.
122
180
  ///
123
181
  /// Args:
124
182
  /// sentences: A single string or a sequence of strings.
125
- /// max_length: Maximum number of tokens per sentence, or None for no limit.
183
+ /// max_length: Maximum number of tokens per sentence, or None for no limit. If not passed, the
184
+ /// model's `max_length` is used.
126
185
  /// batch_size: Number of sentences encoded per parallel pass, or None to encode all at once.
186
+ /// normalize: Whether to L2-normalize the embeddings, or None to use the model's setting.
127
187
  ///
128
188
  /// Returns:
129
189
  /// A float32 array of shape (dim,) for a single string, or (n, dim) for a sequence.
130
- #[pyo3(signature = (sentences, max_length=Some(512), batch_size=None))]
190
+ #[pyo3(signature = (sentences, max_length=MaxLength::Unset, batch_size=None, normalize=None))]
131
191
  fn encode<'py>(
132
192
  &self,
133
193
  py: Python<'py>,
134
194
  sentences: Sentences,
135
- max_length: Option<usize>,
195
+ max_length: MaxLength,
136
196
  batch_size: Option<usize>,
197
+ normalize: Option<bool>,
137
198
  ) -> PyResult<Bound<'py, PyAny>> {
199
+ let max_length = max_length.or(self.model.max_length());
138
200
  if batch_size == Some(0) {
139
201
  return Err(PyValueError::new_err("batch_size must be greater than 0"));
140
202
  }
@@ -143,17 +205,17 @@ impl StaticModel {
143
205
  Sentences::Single(sentence) => {
144
206
  let embedding = py.detach(|| {
145
207
  self.model
146
- .encode_flat_with_args(std::slice::from_ref(&sentence), max_length)
208
+ .encode_flat_with_args(std::slice::from_ref(&sentence), max_length, normalize)
147
209
  });
148
210
  Ok(embedding.into_pyarray(py).into_any())
149
211
  }
150
212
  Sentences::Many(sentences) => {
151
213
  let flat = py.detach(|| match batch_size {
152
- None => self.model.encode_flat_with_args(&sentences, max_length),
214
+ None => self.model.encode_flat_with_args(&sentences, max_length, normalize),
153
215
  Some(batch_size) => {
154
216
  let mut flat = Vec::with_capacity(sentences.len() * dim);
155
217
  for batch in sentences.chunks(batch_size) {
156
- flat.extend(self.model.encode_flat_with_args(batch, max_length));
218
+ flat.extend(self.model.encode_flat_with_args(batch, max_length, normalize));
157
219
  }
158
220
  flat
159
221
  }
@@ -171,6 +233,18 @@ impl StaticModel {
171
233
  self.model.dim()
172
234
  }
173
235
 
236
+ /// Whether the model L2-normalizes its embeddings by default.
237
+ #[getter]
238
+ fn normalize(&self) -> bool {
239
+ self.model.normalize()
240
+ }
241
+
242
+ /// The default maximum number of tokens per sentence used by `encode`, or None for no limit.
243
+ #[getter]
244
+ fn max_length(&self) -> Option<usize> {
245
+ self.model.max_length()
246
+ }
247
+
174
248
  fn __repr__(&self) -> String {
175
249
  format!("StaticModel(dim={})", self.model.dim())
176
250
  }
@@ -1,6 +1,7 @@
1
1
  import json
2
2
  from importlib.metadata import version
3
3
  import multiprocessing
4
+ import shutil
4
5
  import sys
5
6
  from pathlib import Path
6
7
 
@@ -94,6 +95,74 @@ def test_normalize_override() -> None:
94
95
  np.testing.assert_allclose(np.linalg.norm(model.encode(["hello world", "foo"]), axis=1), 1.0, atol=1e-5)
95
96
 
96
97
 
98
+ def test_encode_normalize() -> None:
99
+ texts = ["hello world", "foo", ""]
100
+ normalized = StaticModel.from_pretrained(str(FIXTURES / "test-model-float32"), normalize=True)
101
+ unnormalized = StaticModel.from_pretrained(str(FIXTURES / "test-model-float32"), normalize=False)
102
+ assert normalized.normalize is True
103
+ assert unnormalized.normalize is False
104
+ for model, other, flag in [(normalized, unnormalized, False), (unnormalized, normalized, True)]:
105
+ np.testing.assert_array_equal(model.encode(texts, normalize=None), model.encode(texts))
106
+ np.testing.assert_array_equal(model.encode(texts, normalize=flag), other.encode(texts))
107
+ np.testing.assert_array_equal(model.encode(texts, normalize=flag, batch_size=2), other.encode(texts))
108
+ np.testing.assert_array_equal(model.encode("hello world", normalize=flag), other.encode("hello world"))
109
+
110
+
111
+ LONG_TEXT = " ".join(["hello world"] * 400 + ["foo bar baz"])
112
+
113
+
114
+ def model_with_config_max_length(tmp_path: Path, max_length: int | None) -> Path:
115
+ shutil.copytree(FIXTURES / "test-model-float32", tmp_path / "model")
116
+ config_path = tmp_path / "model" / "config.json"
117
+ config = json.loads(config_path.read_text(encoding="utf-8"))
118
+ config["max_length"] = max_length
119
+ config_path.write_text(json.dumps(config), encoding="utf-8")
120
+ return tmp_path / "model"
121
+
122
+
123
+ @pytest.mark.parametrize("config_max_length", [None, 7])
124
+ def test_max_length_from_config(tmp_path: Path, config_max_length: int | None) -> None:
125
+ path = model_with_config_max_length(tmp_path, config_max_length)
126
+ model = StaticModel.from_pretrained(path)
127
+ assert model.max_length == config_max_length
128
+ texts = [LONG_TEXT, "hello world"]
129
+ np.testing.assert_array_equal(model.encode(texts), model.encode(texts, max_length=config_max_length))
130
+ np.testing.assert_array_equal(model.encode(LONG_TEXT), model.encode(LONG_TEXT, max_length=config_max_length))
131
+ other = 3 if config_max_length is None else None
132
+ assert not np.array_equal(model.encode(LONG_TEXT), model.encode(LONG_TEXT, max_length=other))
133
+
134
+
135
+ def test_max_length_default(model: StaticModel) -> None:
136
+ assert model.max_length == 512
137
+ unlimited = model.encode(LONG_TEXT, max_length=None)
138
+ assert not np.array_equal(model.encode(LONG_TEXT), unlimited)
139
+ np.testing.assert_array_equal(model.encode(LONG_TEXT), model.encode(LONG_TEXT, max_length=512))
140
+
141
+
142
+ @pytest.mark.parametrize("override", [None, 3, 600])
143
+ def test_from_pretrained_max_length_override(tmp_path: Path, override: int | None) -> None:
144
+ path = model_with_config_max_length(tmp_path, 7)
145
+ model = StaticModel.from_pretrained(path, max_length=override)
146
+ assert model.max_length == override
147
+ np.testing.assert_array_equal(model.encode(LONG_TEXT), model.encode(LONG_TEXT, max_length=override))
148
+
149
+
150
+ def test_from_arrays_max_length() -> None:
151
+ tokenizer = (FIXTURES / "test-model-float32" / "tokenizer.json").read_text(encoding="utf-8")
152
+ embeddings = np.random.default_rng(0).random((tokenizers_vocab_size(tokenizer), 4), dtype=np.float32)
153
+ assert StaticModel.from_arrays(tokenizer, embeddings).max_length == 512
154
+ for max_length in [None, 7]:
155
+ model = StaticModel.from_arrays(tokenizer, embeddings, max_length=max_length)
156
+ assert model.max_length == max_length
157
+ np.testing.assert_array_equal(model.encode(LONG_TEXT), model.encode(LONG_TEXT, max_length=max_length))
158
+
159
+
160
+ def test_invalid_config_max_length(tmp_path: Path) -> None:
161
+ path = model_with_config_max_length(tmp_path, -1)
162
+ with pytest.raises(RuntimeError, match="max_length"):
163
+ StaticModel.from_pretrained(path)
164
+
165
+
97
166
  def test_repr(model: StaticModel) -> None:
98
167
  assert repr(model).startswith("StaticModel(dim=")
99
168
 
@@ -117,6 +186,31 @@ def test_from_arrays() -> None:
117
186
  assert model.encode(["hello world"]).shape == (1, 4)
118
187
 
119
188
 
189
+ @pytest.mark.parametrize("vocab_quantized", [False, True])
190
+ @pytest.mark.parametrize("normalize", [False, True])
191
+ def test_from_arrays_int8_matches_float32(vocab_quantized: bool, normalize: bool) -> None:
192
+ tokenizer = (FIXTURES / "test-model-float32" / "tokenizer.json").read_text(encoding="utf-8")
193
+ vocab_size = tokenizers_vocab_size(tokenizer)
194
+ rng = np.random.default_rng(0)
195
+ rows = 10 if vocab_quantized else vocab_size
196
+ embeddings = rng.integers(-128, 128, size=(rows, 4), dtype=np.int8)
197
+ weights = rng.random(vocab_size, dtype=np.float32)
198
+ mapping = np.arange(vocab_size, dtype=np.int64) % rows if vocab_quantized else None
199
+ texts = ["hello world", "foo bar baz", ""]
200
+ int8 = StaticModel.from_arrays(tokenizer, embeddings, normalize=normalize, weights=weights, token_mapping=mapping)
201
+ float32 = StaticModel.from_arrays(
202
+ tokenizer, embeddings.astype(np.float32), normalize=normalize, weights=weights, token_mapping=mapping
203
+ )
204
+ np.testing.assert_allclose(int8.encode(texts), float32.encode(texts), rtol=1e-6)
205
+
206
+
207
+ def test_from_arrays_rejects_other_dtypes() -> None:
208
+ tokenizer = (FIXTURES / "test-model-float32" / "tokenizer.json").read_text(encoding="utf-8")
209
+ vocab_size = tokenizers_vocab_size(tokenizer)
210
+ with pytest.raises(TypeError):
211
+ StaticModel.from_arrays(tokenizer, np.zeros((vocab_size, 4), dtype=np.float64))
212
+
213
+
120
214
  def test_from_arrays_too_few_rows() -> None:
121
215
  tokenizer = (FIXTURES / "test-model-float32" / "tokenizer.json").read_text(encoding="utf-8")
122
216
  with pytest.raises(ValueError, match="rows"):
@@ -20,6 +20,9 @@ use tokenizers::{
20
20
  use crate::fast_unigram::FastUnigram;
21
21
  use crate::fast_wordpiece::FastWordPiece;
22
22
 
23
+ /// Default `max_length` when a model config does not set one, as in model2vec.
24
+ pub const DEFAULT_MAX_LENGTH: usize = 512;
25
+
23
26
  thread_local! {
24
27
  static TOKEN_IDS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
25
28
  }
@@ -30,6 +33,7 @@ thread_local! {
30
33
  #[derive(Debug, Clone)]
31
34
  pub struct StaticModel {
32
35
  inner: Arc<StaticModelInner>,
36
+ max_length: Option<usize>,
33
37
  }
34
38
 
35
39
  #[derive(Debug)]
@@ -298,10 +302,19 @@ impl StaticModel {
298
302
  config_bytes: &[u8],
299
303
  normalize: Option<bool>,
300
304
  ) -> Result<Self> {
301
- // Read normalize default from config.json
302
305
  let cfg: Value = serde_json::from_slice(config_bytes).context("failed to parse config.json")?;
303
306
  let cfg_norm = cfg.get("normalize").and_then(Value::as_bool).unwrap_or(true);
304
307
  let normalize = normalize.unwrap_or(cfg_norm);
308
+ let max_length = match cfg.get("max_length") {
309
+ None => Some(DEFAULT_MAX_LENGTH),
310
+ Some(Value::Null) => None,
311
+ Some(value) => Some(
312
+ value
313
+ .as_u64()
314
+ .and_then(|n| usize::try_from(n).ok())
315
+ .ok_or_else(|| anyhow!("invalid max_length in config.json: {value}"))?,
316
+ ),
317
+ };
305
318
 
306
319
  // Load the safetensors
307
320
  let safet = SafeTensors::deserialize(model_bytes).context("failed to parse safetensors")?;
@@ -353,6 +366,7 @@ impl StaticModel {
353
366
  weights.map(Cow::Owned),
354
367
  token_mapping.map(Cow::Owned),
355
368
  )
369
+ .map(|model| model.with_max_length(max_length))
356
370
  }
357
371
 
358
372
  /// Load a Model2Vec model from a local folder or the HuggingFace Hub.
@@ -527,6 +541,7 @@ impl StaticModel {
527
541
  token_mapping,
528
542
  normalize,
529
543
  }),
544
+ max_length: Some(DEFAULT_MAX_LENGTH),
530
545
  })
531
546
  }
532
547
 
@@ -563,7 +578,10 @@ impl StaticModel {
563
578
  }
564
579
  }
565
580
  inner.row_scales = Some(scales);
566
- StaticModel { inner: Arc::new(inner) }
581
+ StaticModel {
582
+ inner: Arc::new(inner),
583
+ max_length: self.max_length,
584
+ }
567
585
  }
568
586
 
569
587
  /// Char-level truncation to max_tokens * median_token_length
@@ -579,26 +597,29 @@ impl StaticModel {
579
597
  /// * `sentences` - the list of sentences to encode.
580
598
  /// * `max_length` - max tokens per text.
581
599
  /// * `batch_size` - number of texts per batch.
600
+ /// * `normalize` - whether to L2-normalize the embeddings, or `None` to use the model's setting.
582
601
  pub fn encode_with_args(
583
602
  &self,
584
603
  sentences: &[String],
585
604
  max_length: Option<usize>,
586
605
  batch_size: usize,
606
+ normalize: Option<bool>,
587
607
  ) -> Vec<Vec<f32>> {
608
+ let normalize = normalize.unwrap_or(self.inner.normalize);
588
609
  let mut embeddings = Vec::with_capacity(sentences.len());
589
610
  for batch in sentences.chunks(batch_size) {
590
611
  let pooled: Vec<Vec<f32>> = batch
591
612
  .maybe_par_iter()
592
- .map(|text| self.encode_one(text, max_length))
613
+ .map(|text| self.encode_one(text, max_length, normalize))
593
614
  .collect();
594
615
  embeddings.extend(pooled);
595
616
  }
596
617
  embeddings
597
618
  }
598
619
 
599
- /// Default encode: `max_length=512`, all sentences in one batch
620
+ /// Default encode: the model's `max_length`, all sentences in one batch
600
621
  pub fn encode(&self, sentences: &[String]) -> Vec<Vec<f32>> {
601
- self.encode_with_args(sentences, Some(512), sentences.len().max(1))
622
+ self.encode_with_args(sentences, self.max_length, sentences.len().max(1), None)
602
623
  }
603
624
 
604
625
  /// Embedding dimension of the vectors this model produces.
@@ -611,36 +632,61 @@ impl StaticModel {
611
632
  /// # Arguments
612
633
  /// * `sentences` - the list of sentences to encode.
613
634
  /// * `max_length` - max tokens per text.
614
- pub fn encode_flat_with_args(&self, sentences: &[String], max_length: Option<usize>) -> Vec<f32> {
635
+ /// * `normalize` - whether to L2-normalize the embeddings, or `None` to use the model's setting.
636
+ pub fn encode_flat_with_args(
637
+ &self,
638
+ sentences: &[String],
639
+ max_length: Option<usize>,
640
+ normalize: Option<bool>,
641
+ ) -> Vec<f32> {
615
642
  let dim = self.inner.dim;
643
+ let normalize = normalize.unwrap_or(self.inner.normalize);
616
644
  let mut out = vec![0.0_f32; sentences.len() * dim];
617
645
  let mut jobs: Vec<(&str, &mut [f32])> = sentences.iter().map(String::as_str).zip(out.chunks_mut(dim)).collect();
618
646
  jobs.maybe_par_iter_mut()
619
- .for_each(|(text, row)| self.encode_into(text, max_length, row));
647
+ .for_each(|(text, row)| self.encode_into(text, max_length, normalize, row));
620
648
  out
621
649
  }
622
650
 
623
- /// Default flat encode: `max_length=512`
651
+ /// Whether the model L2-normalizes its embeddings by default.
652
+ pub fn normalize(&self) -> bool {
653
+ self.inner.normalize
654
+ }
655
+
656
+ /// Set the default max tokens per text used by `encode`, or `None` for no limit.
657
+ /// Models loaded from files use the config's `max_length` (512 if absent); models
658
+ /// built from arrays default to 512.
659
+ pub fn with_max_length(mut self, max_length: Option<usize>) -> Self {
660
+ self.max_length = max_length;
661
+ self
662
+ }
663
+
664
+ /// The default max tokens per text used by `encode`, or `None` for no limit.
665
+ pub fn max_length(&self) -> Option<usize> {
666
+ self.max_length
667
+ }
668
+
669
+ /// Default flat encode: the model's `max_length`
624
670
  pub fn encode_flat(&self, sentences: &[String]) -> Vec<f32> {
625
- self.encode_flat_with_args(sentences, Some(512))
671
+ self.encode_flat_with_args(sentences, self.max_length, None)
626
672
  }
627
673
 
628
- /// Encode a single sentence into a vector.
674
+ /// Encode a single sentence into a vector, using the model's `max_length`.
629
675
  pub fn encode_single(&self, sentence: &str) -> Vec<f32> {
630
- self.encode_one(sentence, Some(512))
676
+ self.encode_one(sentence, self.max_length, self.inner.normalize)
631
677
  }
632
678
 
633
679
  /// Truncate, tokenize and pool one text.
634
680
  /// Uses the custom WordPiece tokenizer or Unigram model when the model
635
681
  /// matches that pipeline; other pipelines use the `tokenizers` crate.
636
- fn encode_one(&self, text: &str, max_length: Option<usize>) -> Vec<f32> {
682
+ fn encode_one(&self, text: &str, max_length: Option<usize>, normalize: bool) -> Vec<f32> {
637
683
  let mut out = vec![0.0_f32; self.inner.dim];
638
- self.encode_into(text, max_length, &mut out);
684
+ self.encode_into(text, max_length, normalize, &mut out);
639
685
  out
640
686
  }
641
687
 
642
688
  /// Truncate, tokenize and pool one text into `out`, which must hold `dim` zeros.
643
- fn encode_into(&self, text: &str, max_length: Option<usize>, out: &mut [f32]) {
689
+ fn encode_into(&self, text: &str, max_length: Option<usize>, normalize: bool, out: &mut [f32]) {
644
690
  let model = &self.inner;
645
691
  let text = max_length.map_or(text, |max_tok| {
646
692
  Self::truncate_str(text, max_tok, model.tokenizer.median_token_length)
@@ -649,21 +695,21 @@ impl StaticModel {
649
695
  Tokenization::WordPiece(ft) => TOKEN_IDS.with_borrow_mut(|ids| {
650
696
  ids.clear();
651
697
  ft.encode_ids_into(text, ids);
652
- self.pool_ids(ids, max_length, out)
698
+ self.pool_ids(ids, max_length, normalize, out)
653
699
  }),
654
700
  Tokenization::Unigram(tokenizer, fu) => {
655
701
  let ids = fu.encode_ids(tokenizer, text).expect("tokenization failed");
656
- self.pool_ids(&ids, max_length, out)
702
+ self.pool_ids(&ids, max_length, normalize, out)
657
703
  }
658
704
  Tokenization::Crate(tokenizer) => {
659
705
  let encoding = tokenizer.encode_fast(text, false).expect("tokenization failed");
660
- self.pool_ids(encoding.get_ids(), max_length, out)
706
+ self.pool_ids(encoding.get_ids(), max_length, normalize, out)
661
707
  }
662
708
  }
663
709
  }
664
710
 
665
711
  /// Mean-pool the first `max_length` token IDs, skipping the unk token.
666
- fn pool_ids(&self, ids: &[u32], max_length: Option<usize>, sum: &mut [f32]) {
712
+ fn pool_ids(&self, ids: &[u32], max_length: Option<usize>, normalize: bool, sum: &mut [f32]) {
667
713
  let model = &self.inner;
668
714
  let ids = &ids[..max_length.map_or(ids.len(), |max_tok| max_tok.min(ids.len()))];
669
715
  let cnt = match &model.embeddings {
@@ -671,7 +717,7 @@ impl StaticModel {
671
717
  Embeddings::I8(table) => self.sum_rows(table, ids, sum),
672
718
  };
673
719
  let denom = cnt.max(1) as f32;
674
- if model.normalize {
720
+ if normalize {
675
721
  let mut sq = 0.0_f32;
676
722
  for x in sum.iter_mut() {
677
723
  *x /= denom;
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes