vectlite 0.1.11 → 0.1.12
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.
- package/README.md +37 -0
- package/native/Cargo.toml +1 -1
- package/native/src/lib.rs +123 -0
- package/native/vectlite-core/Cargo.toml +1 -1
- package/native/vectlite-core/src/lib.rs +421 -7
- package/native/vectlite-core/src/quantization.rs +1087 -0
- package/package.json +1 -1
- package/prebuilds/darwin-arm64/vectlite.node +0 -0
- package/prebuilds/darwin-x64/vectlite.node +0 -0
- package/prebuilds/linux-x64-gnu/vectlite.node +0 -0
- package/prebuilds/win32-x64-msvc/vectlite.node +0 -0
|
@@ -0,0 +1,1087 @@
|
|
|
1
|
+
//! Vector quantization module for memory-efficient similarity search.
|
|
2
|
+
//!
|
|
3
|
+
//! Supports three quantization strategies:
|
|
4
|
+
//! - **Scalar (int8)**: 4x memory reduction with minimal recall loss
|
|
5
|
+
//! - **Binary**: 32x memory reduction, uses Hamming distance for fast filtering
|
|
6
|
+
//! - **Product Quantization (PQ)**: Configurable compression for very large datasets
|
|
7
|
+
//!
|
|
8
|
+
//! All strategies support a 2-stage pipeline: fast quantized search followed by
|
|
9
|
+
//! exact float32 rescoring of top candidates.
|
|
10
|
+
|
|
11
|
+
use std::io::{Read, Write};
|
|
12
|
+
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
// Public types
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
/// Configuration for enabling quantization on a database.
|
|
18
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
19
|
+
pub enum QuantizationConfig {
|
|
20
|
+
/// Scalar quantization: maps each f32 dimension to int8 using per-dimension
|
|
21
|
+
/// min/max calibration. 4x memory reduction.
|
|
22
|
+
Scalar(ScalarQuantizationConfig),
|
|
23
|
+
/// Binary quantization: maps each f32 dimension to a single bit.
|
|
24
|
+
/// 32x memory reduction. Best for high-dimensional normalized embeddings.
|
|
25
|
+
Binary(BinaryQuantizationConfig),
|
|
26
|
+
/// Product quantization: splits vector into sub-vectors and quantizes each
|
|
27
|
+
/// to a centroid index. Highest compression for large datasets.
|
|
28
|
+
Product(ProductQuantizationConfig),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
32
|
+
pub struct ScalarQuantizationConfig {
|
|
33
|
+
/// Number of top candidates from quantized search to rescore with float32.
|
|
34
|
+
/// Default: 5x top_k (minimum 100).
|
|
35
|
+
pub rescore_multiplier: usize,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
impl Default for ScalarQuantizationConfig {
|
|
39
|
+
fn default() -> Self {
|
|
40
|
+
Self {
|
|
41
|
+
rescore_multiplier: 5,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
47
|
+
pub struct BinaryQuantizationConfig {
|
|
48
|
+
/// Number of top candidates from Hamming search to rescore with float32.
|
|
49
|
+
/// Default: 10x top_k (minimum 100).
|
|
50
|
+
pub rescore_multiplier: usize,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
impl Default for BinaryQuantizationConfig {
|
|
54
|
+
fn default() -> Self {
|
|
55
|
+
Self {
|
|
56
|
+
rescore_multiplier: 10,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
62
|
+
pub struct ProductQuantizationConfig {
|
|
63
|
+
/// Number of sub-vectors (sub-spaces). Must divide the vector dimension evenly.
|
|
64
|
+
/// Typical values: 8, 16, 32, 64.
|
|
65
|
+
pub num_sub_vectors: usize,
|
|
66
|
+
/// Number of centroids per sub-vector (k in k-means). Must be <= 256.
|
|
67
|
+
/// Default: 256 (uses u8 codes).
|
|
68
|
+
pub num_centroids: usize,
|
|
69
|
+
/// Number of k-means training iterations.
|
|
70
|
+
pub training_iterations: usize,
|
|
71
|
+
/// Number of top candidates from PQ search to rescore with float32.
|
|
72
|
+
pub rescore_multiplier: usize,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
impl Default for ProductQuantizationConfig {
|
|
76
|
+
fn default() -> Self {
|
|
77
|
+
Self {
|
|
78
|
+
num_sub_vectors: 16,
|
|
79
|
+
num_centroids: 256,
|
|
80
|
+
training_iterations: 20,
|
|
81
|
+
rescore_multiplier: 10,
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
// Scalar Quantization
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
/// Calibration parameters for scalar quantization (per-dimension min/max).
|
|
91
|
+
#[derive(Clone, Debug)]
|
|
92
|
+
pub struct ScalarQuantizer {
|
|
93
|
+
pub dimension: usize,
|
|
94
|
+
/// Per-dimension minimum values used for calibration.
|
|
95
|
+
pub mins: Vec<f32>,
|
|
96
|
+
/// Per-dimension maximum values used for calibration.
|
|
97
|
+
pub maxs: Vec<f32>,
|
|
98
|
+
/// Per-dimension scale: 255.0 / (max - min). Pre-computed for fast quantization.
|
|
99
|
+
scales: Vec<f32>,
|
|
100
|
+
/// Quantized vectors stored as flat u8 array (n * dimension).
|
|
101
|
+
pub codes: Vec<u8>,
|
|
102
|
+
/// Number of quantized vectors.
|
|
103
|
+
pub count: usize,
|
|
104
|
+
pub config: ScalarQuantizationConfig,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
impl ScalarQuantizer {
|
|
108
|
+
/// Train a scalar quantizer by computing per-dimension min/max from training vectors.
|
|
109
|
+
pub fn train(vectors: &[&[f32]], dimension: usize, config: ScalarQuantizationConfig) -> Self {
|
|
110
|
+
assert!(!vectors.is_empty(), "need at least one vector to train");
|
|
111
|
+
assert!(vectors[0].len() == dimension);
|
|
112
|
+
|
|
113
|
+
let mut mins = vec![f32::INFINITY; dimension];
|
|
114
|
+
let mut maxs = vec![f32::NEG_INFINITY; dimension];
|
|
115
|
+
|
|
116
|
+
for vector in vectors {
|
|
117
|
+
for (i, &val) in vector.iter().enumerate() {
|
|
118
|
+
if val < mins[i] {
|
|
119
|
+
mins[i] = val;
|
|
120
|
+
}
|
|
121
|
+
if val > maxs[i] {
|
|
122
|
+
maxs[i] = val;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let scales: Vec<f32> = mins
|
|
128
|
+
.iter()
|
|
129
|
+
.zip(maxs.iter())
|
|
130
|
+
.map(|(&min, &max)| {
|
|
131
|
+
let range = max - min;
|
|
132
|
+
if range < 1e-10 { 0.0 } else { 255.0 / range }
|
|
133
|
+
})
|
|
134
|
+
.collect();
|
|
135
|
+
|
|
136
|
+
let mut codes = Vec::with_capacity(vectors.len() * dimension);
|
|
137
|
+
for vector in vectors {
|
|
138
|
+
for (i, &val) in vector.iter().enumerate() {
|
|
139
|
+
codes.push(quantize_scalar(val, mins[i], scales[i]));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
Self {
|
|
144
|
+
dimension,
|
|
145
|
+
mins,
|
|
146
|
+
maxs,
|
|
147
|
+
scales,
|
|
148
|
+
codes,
|
|
149
|
+
count: vectors.len(),
|
|
150
|
+
config,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/// Add vectors to the quantized index (after initial training).
|
|
155
|
+
pub fn add_vectors(&mut self, vectors: &[&[f32]]) {
|
|
156
|
+
for vector in vectors {
|
|
157
|
+
assert_eq!(vector.len(), self.dimension);
|
|
158
|
+
for (i, &val) in vector.iter().enumerate() {
|
|
159
|
+
self.codes
|
|
160
|
+
.push(quantize_scalar(val, self.mins[i], self.scales[i]));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
self.count += vectors.len();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// Quantize a single query vector.
|
|
167
|
+
pub fn quantize_query(&self, query: &[f32]) -> Vec<u8> {
|
|
168
|
+
assert_eq!(query.len(), self.dimension);
|
|
169
|
+
query
|
|
170
|
+
.iter()
|
|
171
|
+
.enumerate()
|
|
172
|
+
.map(|(i, &val)| quantize_scalar(val, self.mins[i], self.scales[i]))
|
|
173
|
+
.collect()
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// Compute approximate cosine distance between a quantized query and all stored vectors.
|
|
177
|
+
/// Returns indices sorted by approximate similarity (best first).
|
|
178
|
+
pub fn search(&self, query: &[f32], top_k: usize) -> Vec<(usize, f32)> {
|
|
179
|
+
let rescore_count = (top_k * self.config.rescore_multiplier)
|
|
180
|
+
.max(100)
|
|
181
|
+
.min(self.count);
|
|
182
|
+
let query_quantized = self.quantize_query(query);
|
|
183
|
+
let mut scores: Vec<(usize, f32)> = (0..self.count)
|
|
184
|
+
.map(|idx| {
|
|
185
|
+
let offset = idx * self.dimension;
|
|
186
|
+
let code_slice = &self.codes[offset..offset + self.dimension];
|
|
187
|
+
let sim = scalar_quantized_dot(&query_quantized, code_slice);
|
|
188
|
+
(idx, sim)
|
|
189
|
+
})
|
|
190
|
+
.collect();
|
|
191
|
+
|
|
192
|
+
// Partial sort: get top rescore_count candidates
|
|
193
|
+
scores.sort_unstable_by(|a, b| b.1.total_cmp(&a.1));
|
|
194
|
+
scores.truncate(rescore_count);
|
|
195
|
+
scores
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/// Rebuild codes from training vectors (used after deserialization with new vectors).
|
|
199
|
+
pub fn rebuild_codes(&mut self, vectors: &[&[f32]]) {
|
|
200
|
+
self.codes.clear();
|
|
201
|
+
self.codes.reserve(vectors.len() * self.dimension);
|
|
202
|
+
for vector in vectors {
|
|
203
|
+
for (i, &val) in vector.iter().enumerate() {
|
|
204
|
+
self.codes
|
|
205
|
+
.push(quantize_scalar(val, self.mins[i], self.scales[i]));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
self.count = vectors.len();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/// Serialize the quantizer parameters (not the codes, which are rebuilt on load).
|
|
212
|
+
pub fn write_params(&self, writer: &mut impl Write) -> std::io::Result<()> {
|
|
213
|
+
// Tag byte: 1 = scalar
|
|
214
|
+
writer.write_all(&[1u8])?;
|
|
215
|
+
write_usize(writer, self.dimension)?;
|
|
216
|
+
write_usize(writer, self.config.rescore_multiplier)?;
|
|
217
|
+
for &v in &self.mins {
|
|
218
|
+
writer.write_all(&v.to_le_bytes())?;
|
|
219
|
+
}
|
|
220
|
+
for &v in &self.maxs {
|
|
221
|
+
writer.write_all(&v.to_le_bytes())?;
|
|
222
|
+
}
|
|
223
|
+
Ok(())
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/// Deserialize quantizer parameters.
|
|
227
|
+
pub fn read_params(reader: &mut impl Read) -> std::io::Result<Self> {
|
|
228
|
+
let dimension = read_usize(reader)?;
|
|
229
|
+
let rescore_multiplier = read_usize(reader)?;
|
|
230
|
+
let mut mins = vec![0.0_f32; dimension];
|
|
231
|
+
let mut maxs = vec![0.0_f32; dimension];
|
|
232
|
+
for v in &mut mins {
|
|
233
|
+
let mut buf = [0u8; 4];
|
|
234
|
+
reader.read_exact(&mut buf)?;
|
|
235
|
+
*v = f32::from_le_bytes(buf);
|
|
236
|
+
}
|
|
237
|
+
for v in &mut maxs {
|
|
238
|
+
let mut buf = [0u8; 4];
|
|
239
|
+
reader.read_exact(&mut buf)?;
|
|
240
|
+
*v = f32::from_le_bytes(buf);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let scales: Vec<f32> = mins
|
|
244
|
+
.iter()
|
|
245
|
+
.zip(maxs.iter())
|
|
246
|
+
.map(|(&min, &max)| {
|
|
247
|
+
let range = max - min;
|
|
248
|
+
if range < 1e-10 { 0.0 } else { 255.0 / range }
|
|
249
|
+
})
|
|
250
|
+
.collect();
|
|
251
|
+
|
|
252
|
+
Ok(Self {
|
|
253
|
+
dimension,
|
|
254
|
+
mins,
|
|
255
|
+
maxs,
|
|
256
|
+
scales,
|
|
257
|
+
codes: Vec::new(),
|
|
258
|
+
count: 0,
|
|
259
|
+
config: ScalarQuantizationConfig { rescore_multiplier },
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
// Binary Quantization
|
|
266
|
+
// ---------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
/// Binary quantizer: each dimension is mapped to a single bit (sign of the value).
|
|
269
|
+
/// Uses Hamming distance for fast candidate selection.
|
|
270
|
+
#[derive(Clone, Debug)]
|
|
271
|
+
pub struct BinaryQuantizer {
|
|
272
|
+
pub dimension: usize,
|
|
273
|
+
/// Number of bytes per vector: ceil(dimension / 8).
|
|
274
|
+
pub bytes_per_vector: usize,
|
|
275
|
+
/// Binary codes stored as flat byte array (n * bytes_per_vector).
|
|
276
|
+
pub codes: Vec<u8>,
|
|
277
|
+
/// Number of quantized vectors.
|
|
278
|
+
pub count: usize,
|
|
279
|
+
pub config: BinaryQuantizationConfig,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
impl BinaryQuantizer {
|
|
283
|
+
/// Create a binary quantizer for vectors of the given dimension.
|
|
284
|
+
pub fn new(dimension: usize, config: BinaryQuantizationConfig) -> Self {
|
|
285
|
+
let bytes_per_vector = (dimension + 7) / 8;
|
|
286
|
+
Self {
|
|
287
|
+
dimension,
|
|
288
|
+
bytes_per_vector,
|
|
289
|
+
codes: Vec::new(),
|
|
290
|
+
count: 0,
|
|
291
|
+
config,
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/// Binarize vectors and add to the index.
|
|
296
|
+
pub fn add_vectors(&mut self, vectors: &[&[f32]]) {
|
|
297
|
+
for vector in vectors {
|
|
298
|
+
assert_eq!(vector.len(), self.dimension);
|
|
299
|
+
let binary = binarize_vector(vector);
|
|
300
|
+
self.codes.extend_from_slice(&binary);
|
|
301
|
+
}
|
|
302
|
+
self.count += vectors.len();
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/// Binarize a query vector.
|
|
306
|
+
pub fn binarize_query(&self, query: &[f32]) -> Vec<u8> {
|
|
307
|
+
assert_eq!(query.len(), self.dimension);
|
|
308
|
+
binarize_vector(query)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// Search using Hamming distance. Returns candidate indices sorted by
|
|
312
|
+
/// Hamming similarity (fewest differing bits first).
|
|
313
|
+
pub fn search(&self, query: &[f32], top_k: usize) -> Vec<(usize, u32)> {
|
|
314
|
+
let rescore_count = (top_k * self.config.rescore_multiplier)
|
|
315
|
+
.max(100)
|
|
316
|
+
.min(self.count);
|
|
317
|
+
let query_binary = self.binarize_query(query);
|
|
318
|
+
let mut distances: Vec<(usize, u32)> = (0..self.count)
|
|
319
|
+
.map(|idx| {
|
|
320
|
+
let offset = idx * self.bytes_per_vector;
|
|
321
|
+
let code_slice = &self.codes[offset..offset + self.bytes_per_vector];
|
|
322
|
+
let dist = hamming_distance(&query_binary, code_slice);
|
|
323
|
+
(idx, dist)
|
|
324
|
+
})
|
|
325
|
+
.collect();
|
|
326
|
+
|
|
327
|
+
// Sort by Hamming distance (ascending = most similar first)
|
|
328
|
+
distances.sort_unstable_by_key(|&(_, d)| d);
|
|
329
|
+
distances.truncate(rescore_count);
|
|
330
|
+
distances
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// Rebuild codes from vectors.
|
|
334
|
+
pub fn rebuild_codes(&mut self, vectors: &[&[f32]]) {
|
|
335
|
+
self.codes.clear();
|
|
336
|
+
self.codes.reserve(vectors.len() * self.bytes_per_vector);
|
|
337
|
+
for vector in vectors {
|
|
338
|
+
let binary = binarize_vector(vector);
|
|
339
|
+
self.codes.extend_from_slice(&binary);
|
|
340
|
+
}
|
|
341
|
+
self.count = vectors.len();
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/// Serialize parameters.
|
|
345
|
+
pub fn write_params(&self, writer: &mut impl Write) -> std::io::Result<()> {
|
|
346
|
+
// Tag byte: 2 = binary
|
|
347
|
+
writer.write_all(&[2u8])?;
|
|
348
|
+
write_usize(writer, self.dimension)?;
|
|
349
|
+
write_usize(writer, self.config.rescore_multiplier)?;
|
|
350
|
+
Ok(())
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/// Deserialize parameters.
|
|
354
|
+
pub fn read_params(reader: &mut impl Read) -> std::io::Result<Self> {
|
|
355
|
+
let dimension = read_usize(reader)?;
|
|
356
|
+
let rescore_multiplier = read_usize(reader)?;
|
|
357
|
+
let bytes_per_vector = (dimension + 7) / 8;
|
|
358
|
+
Ok(Self {
|
|
359
|
+
dimension,
|
|
360
|
+
bytes_per_vector,
|
|
361
|
+
codes: Vec::new(),
|
|
362
|
+
count: 0,
|
|
363
|
+
config: BinaryQuantizationConfig { rescore_multiplier },
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ---------------------------------------------------------------------------
|
|
369
|
+
// Product Quantization
|
|
370
|
+
// ---------------------------------------------------------------------------
|
|
371
|
+
|
|
372
|
+
/// Product quantizer: divides vector into sub-vectors and maps each to a centroid.
|
|
373
|
+
#[derive(Clone, Debug)]
|
|
374
|
+
pub struct ProductQuantizer {
|
|
375
|
+
pub dimension: usize,
|
|
376
|
+
pub num_sub_vectors: usize,
|
|
377
|
+
pub sub_dimension: usize,
|
|
378
|
+
pub num_centroids: usize,
|
|
379
|
+
/// Codebooks: shape [num_sub_vectors][num_centroids][sub_dimension].
|
|
380
|
+
pub codebooks: Vec<Vec<Vec<f32>>>,
|
|
381
|
+
/// PQ codes: flat array of (n * num_sub_vectors) u8 indices.
|
|
382
|
+
pub codes: Vec<u8>,
|
|
383
|
+
/// Number of quantized vectors.
|
|
384
|
+
pub count: usize,
|
|
385
|
+
pub config: ProductQuantizationConfig,
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
impl ProductQuantizer {
|
|
389
|
+
/// Train a product quantizer using k-means on sub-vectors.
|
|
390
|
+
pub fn train(vectors: &[&[f32]], dimension: usize, config: ProductQuantizationConfig) -> Self {
|
|
391
|
+
assert!(!vectors.is_empty(), "need at least one vector to train PQ");
|
|
392
|
+
assert!(
|
|
393
|
+
dimension % config.num_sub_vectors == 0,
|
|
394
|
+
"dimension ({dimension}) must be divisible by num_sub_vectors ({})",
|
|
395
|
+
config.num_sub_vectors
|
|
396
|
+
);
|
|
397
|
+
assert!(config.num_centroids <= 256, "num_centroids must be <= 256");
|
|
398
|
+
|
|
399
|
+
let sub_dimension = dimension / config.num_sub_vectors;
|
|
400
|
+
let mut codebooks = Vec::with_capacity(config.num_sub_vectors);
|
|
401
|
+
|
|
402
|
+
for sub_idx in 0..config.num_sub_vectors {
|
|
403
|
+
let offset = sub_idx * sub_dimension;
|
|
404
|
+
// Extract sub-vectors for this partition
|
|
405
|
+
let sub_vectors: Vec<&[f32]> = vectors
|
|
406
|
+
.iter()
|
|
407
|
+
.map(|v| &v[offset..offset + sub_dimension])
|
|
408
|
+
.collect();
|
|
409
|
+
|
|
410
|
+
let centroids = kmeans(
|
|
411
|
+
&sub_vectors,
|
|
412
|
+
sub_dimension,
|
|
413
|
+
config.num_centroids,
|
|
414
|
+
config.training_iterations,
|
|
415
|
+
);
|
|
416
|
+
codebooks.push(centroids);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Encode all training vectors
|
|
420
|
+
let mut codes = Vec::with_capacity(vectors.len() * config.num_sub_vectors);
|
|
421
|
+
for vector in vectors {
|
|
422
|
+
for sub_idx in 0..config.num_sub_vectors {
|
|
423
|
+
let offset = sub_idx * sub_dimension;
|
|
424
|
+
let sub_vector = &vector[offset..offset + sub_dimension];
|
|
425
|
+
let nearest = find_nearest_centroid(sub_vector, &codebooks[sub_idx]);
|
|
426
|
+
codes.push(nearest as u8);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
Self {
|
|
431
|
+
dimension,
|
|
432
|
+
num_sub_vectors: config.num_sub_vectors,
|
|
433
|
+
sub_dimension,
|
|
434
|
+
num_centroids: config.num_centroids,
|
|
435
|
+
codebooks,
|
|
436
|
+
codes,
|
|
437
|
+
count: vectors.len(),
|
|
438
|
+
config,
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/// Add vectors to the PQ index.
|
|
443
|
+
pub fn add_vectors(&mut self, vectors: &[&[f32]]) {
|
|
444
|
+
for vector in vectors {
|
|
445
|
+
assert_eq!(vector.len(), self.dimension);
|
|
446
|
+
for sub_idx in 0..self.num_sub_vectors {
|
|
447
|
+
let offset = sub_idx * self.sub_dimension;
|
|
448
|
+
let sub_vector = &vector[offset..offset + self.sub_dimension];
|
|
449
|
+
let nearest = find_nearest_centroid(sub_vector, &self.codebooks[sub_idx]);
|
|
450
|
+
self.codes.push(nearest as u8);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
self.count += vectors.len();
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/// Compute asymmetric distance table for a query. This precomputes distances
|
|
457
|
+
/// from the query sub-vectors to all centroids, enabling fast approximate
|
|
458
|
+
/// distance computation.
|
|
459
|
+
pub fn compute_distance_table(&self, query: &[f32]) -> Vec<Vec<f32>> {
|
|
460
|
+
assert_eq!(query.len(), self.dimension);
|
|
461
|
+
let mut table = Vec::with_capacity(self.num_sub_vectors);
|
|
462
|
+
|
|
463
|
+
for sub_idx in 0..self.num_sub_vectors {
|
|
464
|
+
let offset = sub_idx * self.sub_dimension;
|
|
465
|
+
let query_sub = &query[offset..offset + self.sub_dimension];
|
|
466
|
+
let distances: Vec<f32> = self.codebooks[sub_idx]
|
|
467
|
+
.iter()
|
|
468
|
+
.map(|centroid| l2_distance_sq(query_sub, centroid))
|
|
469
|
+
.collect();
|
|
470
|
+
table.push(distances);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
table
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/// Search using asymmetric distance computation (ADC).
|
|
477
|
+
/// Returns candidate indices sorted by approximate L2 distance.
|
|
478
|
+
pub fn search(&self, query: &[f32], top_k: usize) -> Vec<(usize, f32)> {
|
|
479
|
+
let rescore_count = (top_k * self.config.rescore_multiplier)
|
|
480
|
+
.max(100)
|
|
481
|
+
.min(self.count);
|
|
482
|
+
let distance_table = self.compute_distance_table(query);
|
|
483
|
+
|
|
484
|
+
let mut distances: Vec<(usize, f32)> = (0..self.count)
|
|
485
|
+
.map(|idx| {
|
|
486
|
+
let code_offset = idx * self.num_sub_vectors;
|
|
487
|
+
let mut dist = 0.0_f32;
|
|
488
|
+
for sub_idx in 0..self.num_sub_vectors {
|
|
489
|
+
let centroid_idx = self.codes[code_offset + sub_idx] as usize;
|
|
490
|
+
dist += distance_table[sub_idx][centroid_idx];
|
|
491
|
+
}
|
|
492
|
+
(idx, dist)
|
|
493
|
+
})
|
|
494
|
+
.collect();
|
|
495
|
+
|
|
496
|
+
// Sort by distance (ascending)
|
|
497
|
+
distances.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
|
|
498
|
+
distances.truncate(rescore_count);
|
|
499
|
+
distances
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/// Rebuild codes from vectors.
|
|
503
|
+
pub fn rebuild_codes(&mut self, vectors: &[&[f32]]) {
|
|
504
|
+
self.codes.clear();
|
|
505
|
+
self.codes.reserve(vectors.len() * self.num_sub_vectors);
|
|
506
|
+
for vector in vectors {
|
|
507
|
+
for sub_idx in 0..self.num_sub_vectors {
|
|
508
|
+
let offset = sub_idx * self.sub_dimension;
|
|
509
|
+
let sub_vector = &vector[offset..offset + self.sub_dimension];
|
|
510
|
+
let nearest = find_nearest_centroid(sub_vector, &self.codebooks[sub_idx]);
|
|
511
|
+
self.codes.push(nearest as u8);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
self.count = vectors.len();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/// Serialize the codebooks and parameters.
|
|
518
|
+
pub fn write_params(&self, writer: &mut impl Write) -> std::io::Result<()> {
|
|
519
|
+
// Tag byte: 3 = product
|
|
520
|
+
writer.write_all(&[3u8])?;
|
|
521
|
+
write_usize(writer, self.dimension)?;
|
|
522
|
+
write_usize(writer, self.num_sub_vectors)?;
|
|
523
|
+
write_usize(writer, self.num_centroids)?;
|
|
524
|
+
write_usize(writer, self.config.training_iterations)?;
|
|
525
|
+
write_usize(writer, self.config.rescore_multiplier)?;
|
|
526
|
+
|
|
527
|
+
// Write codebooks
|
|
528
|
+
for sub_codebook in &self.codebooks {
|
|
529
|
+
for centroid in sub_codebook {
|
|
530
|
+
for &val in centroid {
|
|
531
|
+
writer.write_all(&val.to_le_bytes())?;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
Ok(())
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/// Deserialize codebooks and parameters.
|
|
539
|
+
pub fn read_params(reader: &mut impl Read) -> std::io::Result<Self> {
|
|
540
|
+
let dimension = read_usize(reader)?;
|
|
541
|
+
let num_sub_vectors = read_usize(reader)?;
|
|
542
|
+
let num_centroids = read_usize(reader)?;
|
|
543
|
+
let training_iterations = read_usize(reader)?;
|
|
544
|
+
let rescore_multiplier = read_usize(reader)?;
|
|
545
|
+
let sub_dimension = dimension / num_sub_vectors;
|
|
546
|
+
|
|
547
|
+
// Read codebooks
|
|
548
|
+
let mut codebooks = Vec::with_capacity(num_sub_vectors);
|
|
549
|
+
for _ in 0..num_sub_vectors {
|
|
550
|
+
let mut sub_codebook = Vec::with_capacity(num_centroids);
|
|
551
|
+
for _ in 0..num_centroids {
|
|
552
|
+
let mut centroid = vec![0.0_f32; sub_dimension];
|
|
553
|
+
for v in &mut centroid {
|
|
554
|
+
let mut buf = [0u8; 4];
|
|
555
|
+
reader.read_exact(&mut buf)?;
|
|
556
|
+
*v = f32::from_le_bytes(buf);
|
|
557
|
+
}
|
|
558
|
+
sub_codebook.push(centroid);
|
|
559
|
+
}
|
|
560
|
+
codebooks.push(sub_codebook);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
Ok(Self {
|
|
564
|
+
dimension,
|
|
565
|
+
num_sub_vectors,
|
|
566
|
+
sub_dimension,
|
|
567
|
+
num_centroids,
|
|
568
|
+
codebooks,
|
|
569
|
+
codes: Vec::new(),
|
|
570
|
+
count: 0,
|
|
571
|
+
config: ProductQuantizationConfig {
|
|
572
|
+
num_sub_vectors,
|
|
573
|
+
num_centroids,
|
|
574
|
+
training_iterations,
|
|
575
|
+
rescore_multiplier,
|
|
576
|
+
},
|
|
577
|
+
})
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// ---------------------------------------------------------------------------
|
|
582
|
+
// Unified quantization index
|
|
583
|
+
// ---------------------------------------------------------------------------
|
|
584
|
+
|
|
585
|
+
/// A quantized index that wraps any of the three quantization strategies.
|
|
586
|
+
/// Used by the Database to accelerate search.
|
|
587
|
+
#[derive(Clone, Debug)]
|
|
588
|
+
pub enum QuantizedIndex {
|
|
589
|
+
Scalar(ScalarQuantizer),
|
|
590
|
+
Binary(BinaryQuantizer),
|
|
591
|
+
Product(ProductQuantizer),
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
impl QuantizedIndex {
|
|
595
|
+
/// Build a quantized index from vectors.
|
|
596
|
+
pub fn build(vectors: &[&[f32]], dimension: usize, config: &QuantizationConfig) -> Self {
|
|
597
|
+
match config {
|
|
598
|
+
QuantizationConfig::Scalar(cfg) => {
|
|
599
|
+
QuantizedIndex::Scalar(ScalarQuantizer::train(vectors, dimension, cfg.clone()))
|
|
600
|
+
}
|
|
601
|
+
QuantizationConfig::Binary(cfg) => {
|
|
602
|
+
let mut quantizer = BinaryQuantizer::new(dimension, cfg.clone());
|
|
603
|
+
quantizer.add_vectors(vectors);
|
|
604
|
+
QuantizedIndex::Binary(quantizer)
|
|
605
|
+
}
|
|
606
|
+
QuantizationConfig::Product(cfg) => {
|
|
607
|
+
QuantizedIndex::Product(ProductQuantizer::train(vectors, dimension, cfg.clone()))
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/// Search the quantized index. Returns candidate indices sorted by
|
|
613
|
+
/// approximate similarity (best first), to be rescored with exact vectors.
|
|
614
|
+
pub fn search_candidates(&self, query: &[f32], top_k: usize) -> Vec<usize> {
|
|
615
|
+
match self {
|
|
616
|
+
QuantizedIndex::Scalar(q) => {
|
|
617
|
+
q.search(query, top_k).into_iter().map(|(i, _)| i).collect()
|
|
618
|
+
}
|
|
619
|
+
QuantizedIndex::Binary(q) => {
|
|
620
|
+
q.search(query, top_k).into_iter().map(|(i, _)| i).collect()
|
|
621
|
+
}
|
|
622
|
+
QuantizedIndex::Product(q) => {
|
|
623
|
+
q.search(query, top_k).into_iter().map(|(i, _)| i).collect()
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/// Rebuild quantized codes from current vectors (after deserialization or updates).
|
|
629
|
+
pub fn rebuild_codes(&mut self, vectors: &[&[f32]]) {
|
|
630
|
+
match self {
|
|
631
|
+
QuantizedIndex::Scalar(q) => q.rebuild_codes(vectors),
|
|
632
|
+
QuantizedIndex::Binary(q) => q.rebuild_codes(vectors),
|
|
633
|
+
QuantizedIndex::Product(q) => q.rebuild_codes(vectors),
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/// Get the vector count in the quantized index.
|
|
638
|
+
pub fn count(&self) -> usize {
|
|
639
|
+
match self {
|
|
640
|
+
QuantizedIndex::Scalar(q) => q.count,
|
|
641
|
+
QuantizedIndex::Binary(q) => q.count,
|
|
642
|
+
QuantizedIndex::Product(q) => q.count,
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/// Get the rescore multiplier for this quantization strategy.
|
|
647
|
+
pub fn rescore_multiplier(&self) -> usize {
|
|
648
|
+
match self {
|
|
649
|
+
QuantizedIndex::Scalar(q) => q.config.rescore_multiplier,
|
|
650
|
+
QuantizedIndex::Binary(q) => q.config.rescore_multiplier,
|
|
651
|
+
QuantizedIndex::Product(q) => q.config.rescore_multiplier,
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/// Serialize quantization parameters to a writer.
|
|
656
|
+
pub fn write_params(&self, writer: &mut impl Write) -> std::io::Result<()> {
|
|
657
|
+
match self {
|
|
658
|
+
QuantizedIndex::Scalar(q) => q.write_params(writer),
|
|
659
|
+
QuantizedIndex::Binary(q) => q.write_params(writer),
|
|
660
|
+
QuantizedIndex::Product(q) => q.write_params(writer),
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/// Deserialize quantization parameters from a reader.
|
|
665
|
+
pub fn read_params(reader: &mut impl Read) -> std::io::Result<Self> {
|
|
666
|
+
let mut tag = [0u8; 1];
|
|
667
|
+
reader.read_exact(&mut tag)?;
|
|
668
|
+
match tag[0] {
|
|
669
|
+
1 => Ok(QuantizedIndex::Scalar(ScalarQuantizer::read_params(
|
|
670
|
+
reader,
|
|
671
|
+
)?)),
|
|
672
|
+
2 => Ok(QuantizedIndex::Binary(BinaryQuantizer::read_params(
|
|
673
|
+
reader,
|
|
674
|
+
)?)),
|
|
675
|
+
3 => Ok(QuantizedIndex::Product(ProductQuantizer::read_params(
|
|
676
|
+
reader,
|
|
677
|
+
)?)),
|
|
678
|
+
other => Err(std::io::Error::new(
|
|
679
|
+
std::io::ErrorKind::InvalidData,
|
|
680
|
+
format!("unknown quantization tag: {other}"),
|
|
681
|
+
)),
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/// Get the config used to build this index.
|
|
686
|
+
pub fn config(&self) -> QuantizationConfig {
|
|
687
|
+
match self {
|
|
688
|
+
QuantizedIndex::Scalar(q) => QuantizationConfig::Scalar(q.config.clone()),
|
|
689
|
+
QuantizedIndex::Binary(q) => QuantizationConfig::Binary(q.config.clone()),
|
|
690
|
+
QuantizedIndex::Product(q) => QuantizationConfig::Product(q.config.clone()),
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// ---------------------------------------------------------------------------
|
|
696
|
+
// Internal helper functions
|
|
697
|
+
// ---------------------------------------------------------------------------
|
|
698
|
+
|
|
699
|
+
/// Quantize a single f32 value to u8 using the given min and scale.
|
|
700
|
+
#[inline]
|
|
701
|
+
fn quantize_scalar(val: f32, min: f32, scale: f32) -> u8 {
|
|
702
|
+
if scale == 0.0 {
|
|
703
|
+
128 // midpoint for constant dimensions
|
|
704
|
+
} else {
|
|
705
|
+
((val - min) * scale).clamp(0.0, 255.0) as u8
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/// Approximate dot product between two u8-quantized vectors.
|
|
710
|
+
/// Higher value = more similar (analogous to cosine similarity for normalized vectors).
|
|
711
|
+
#[inline]
|
|
712
|
+
fn scalar_quantized_dot(a: &[u8], b: &[u8]) -> f32 {
|
|
713
|
+
let mut sum = 0i32;
|
|
714
|
+
for (&ai, &bi) in a.iter().zip(b.iter()) {
|
|
715
|
+
sum += (ai as i32) * (bi as i32);
|
|
716
|
+
}
|
|
717
|
+
sum as f32
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/// Convert a float vector to a binary representation (1 bit per dimension).
|
|
721
|
+
/// Positive values map to 1, non-positive to 0.
|
|
722
|
+
fn binarize_vector(vector: &[f32]) -> Vec<u8> {
|
|
723
|
+
let bytes = (vector.len() + 7) / 8;
|
|
724
|
+
let mut result = vec![0u8; bytes];
|
|
725
|
+
for (i, &val) in vector.iter().enumerate() {
|
|
726
|
+
if val > 0.0 {
|
|
727
|
+
result[i / 8] |= 1 << (i % 8);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
result
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/// Compute Hamming distance between two binary vectors.
|
|
734
|
+
#[inline]
|
|
735
|
+
fn hamming_distance(a: &[u8], b: &[u8]) -> u32 {
|
|
736
|
+
let mut dist = 0u32;
|
|
737
|
+
for (&ai, &bi) in a.iter().zip(b.iter()) {
|
|
738
|
+
dist += (ai ^ bi).count_ones();
|
|
739
|
+
}
|
|
740
|
+
dist
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/// Squared L2 distance between two vectors.
|
|
744
|
+
#[inline]
|
|
745
|
+
fn l2_distance_sq(a: &[f32], b: &[f32]) -> f32 {
|
|
746
|
+
a.iter()
|
|
747
|
+
.zip(b.iter())
|
|
748
|
+
.map(|(&ai, &bi)| {
|
|
749
|
+
let diff = ai - bi;
|
|
750
|
+
diff * diff
|
|
751
|
+
})
|
|
752
|
+
.sum()
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/// Find the nearest centroid index for a sub-vector.
|
|
756
|
+
fn find_nearest_centroid(vector: &[f32], centroids: &[Vec<f32>]) -> usize {
|
|
757
|
+
let mut best_idx = 0;
|
|
758
|
+
let mut best_dist = f32::INFINITY;
|
|
759
|
+
for (idx, centroid) in centroids.iter().enumerate() {
|
|
760
|
+
let dist = l2_distance_sq(vector, centroid);
|
|
761
|
+
if dist < best_dist {
|
|
762
|
+
best_dist = dist;
|
|
763
|
+
best_idx = idx;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
best_idx
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/// Simple k-means clustering for PQ training.
|
|
770
|
+
fn kmeans(vectors: &[&[f32]], dimension: usize, k: usize, iterations: usize) -> Vec<Vec<f32>> {
|
|
771
|
+
let n = vectors.len();
|
|
772
|
+
let actual_k = k.min(n);
|
|
773
|
+
|
|
774
|
+
// Initialize centroids using first k vectors (or modular selection if k > n)
|
|
775
|
+
let mut centroids: Vec<Vec<f32>> = (0..actual_k).map(|i| vectors[i % n].to_vec()).collect();
|
|
776
|
+
|
|
777
|
+
let mut assignments = vec![0usize; n];
|
|
778
|
+
|
|
779
|
+
for _ in 0..iterations {
|
|
780
|
+
// Assign each vector to nearest centroid
|
|
781
|
+
for (i, vector) in vectors.iter().enumerate() {
|
|
782
|
+
assignments[i] = find_nearest_centroid(vector, ¢roids);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// Update centroids
|
|
786
|
+
let mut new_centroids = vec![vec![0.0_f32; dimension]; actual_k];
|
|
787
|
+
let mut counts = vec![0usize; actual_k];
|
|
788
|
+
|
|
789
|
+
for (i, vector) in vectors.iter().enumerate() {
|
|
790
|
+
let cluster = assignments[i];
|
|
791
|
+
counts[cluster] += 1;
|
|
792
|
+
for (j, &val) in vector.iter().enumerate() {
|
|
793
|
+
new_centroids[cluster][j] += val;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
for (cluster, centroid) in new_centroids.iter_mut().enumerate() {
|
|
798
|
+
if counts[cluster] > 0 {
|
|
799
|
+
for val in centroid.iter_mut() {
|
|
800
|
+
*val /= counts[cluster] as f32;
|
|
801
|
+
}
|
|
802
|
+
} else {
|
|
803
|
+
// Keep old centroid for empty clusters
|
|
804
|
+
centroid.copy_from_slice(¢roids[cluster]);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
centroids = new_centroids;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// Pad with zeros if actual_k < k (shouldn't happen in practice)
|
|
812
|
+
while centroids.len() < k {
|
|
813
|
+
centroids.push(vec![0.0_f32; dimension]);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
centroids
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// ---------------------------------------------------------------------------
|
|
820
|
+
// Serialization helpers
|
|
821
|
+
// ---------------------------------------------------------------------------
|
|
822
|
+
|
|
823
|
+
fn write_usize(writer: &mut impl Write, val: usize) -> std::io::Result<()> {
|
|
824
|
+
writer.write_all(&(val as u64).to_le_bytes())
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
fn read_usize(reader: &mut impl Read) -> std::io::Result<usize> {
|
|
828
|
+
let mut buf = [0u8; 8];
|
|
829
|
+
reader.read_exact(&mut buf)?;
|
|
830
|
+
Ok(u64::from_le_bytes(buf) as usize)
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// ---------------------------------------------------------------------------
|
|
834
|
+
// Tests
|
|
835
|
+
// ---------------------------------------------------------------------------
|
|
836
|
+
|
|
837
|
+
#[cfg(test)]
|
|
838
|
+
mod tests {
|
|
839
|
+
use super::*;
|
|
840
|
+
|
|
841
|
+
fn random_vectors(n: usize, dim: usize, seed: u64) -> Vec<Vec<f32>> {
|
|
842
|
+
// Simple deterministic pseudo-random generator (xorshift64)
|
|
843
|
+
let mut state = seed;
|
|
844
|
+
(0..n)
|
|
845
|
+
.map(|_| {
|
|
846
|
+
(0..dim)
|
|
847
|
+
.map(|_| {
|
|
848
|
+
state ^= state << 13;
|
|
849
|
+
state ^= state >> 7;
|
|
850
|
+
state ^= state << 17;
|
|
851
|
+
// Map to [-1, 1]
|
|
852
|
+
(state as f32 / u64::MAX as f32) * 2.0 - 1.0
|
|
853
|
+
})
|
|
854
|
+
.collect()
|
|
855
|
+
})
|
|
856
|
+
.collect()
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
#[test]
|
|
860
|
+
fn scalar_quantization_basic() {
|
|
861
|
+
let vectors = random_vectors(100, 128, 42);
|
|
862
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
863
|
+
|
|
864
|
+
let quantizer = ScalarQuantizer::train(&refs, 128, ScalarQuantizationConfig::default());
|
|
865
|
+
|
|
866
|
+
assert_eq!(quantizer.count, 100);
|
|
867
|
+
assert_eq!(quantizer.codes.len(), 100 * 128);
|
|
868
|
+
assert_eq!(quantizer.dimension, 128);
|
|
869
|
+
|
|
870
|
+
// Search should return candidates
|
|
871
|
+
let query = &vectors[0];
|
|
872
|
+
let results = quantizer.search(query, 10);
|
|
873
|
+
assert!(!results.is_empty());
|
|
874
|
+
// The query vector itself should be among the top results
|
|
875
|
+
assert!(results.iter().take(5).any(|(idx, _)| *idx == 0));
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
#[test]
|
|
879
|
+
fn binary_quantization_basic() {
|
|
880
|
+
let vectors = random_vectors(100, 128, 42);
|
|
881
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
882
|
+
|
|
883
|
+
let mut quantizer = BinaryQuantizer::new(128, BinaryQuantizationConfig::default());
|
|
884
|
+
quantizer.add_vectors(&refs);
|
|
885
|
+
|
|
886
|
+
assert_eq!(quantizer.count, 100);
|
|
887
|
+
assert_eq!(quantizer.bytes_per_vector, 16); // 128 / 8
|
|
888
|
+
assert_eq!(quantizer.codes.len(), 100 * 16);
|
|
889
|
+
|
|
890
|
+
// Search should find the query itself at distance 0
|
|
891
|
+
let query = &vectors[0];
|
|
892
|
+
let results = quantizer.search(query, 10);
|
|
893
|
+
assert!(!results.is_empty());
|
|
894
|
+
assert_eq!(results[0].0, 0); // First result should be index 0
|
|
895
|
+
assert_eq!(results[0].1, 0); // Hamming distance 0
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
#[test]
|
|
899
|
+
fn product_quantization_basic() {
|
|
900
|
+
let vectors = random_vectors(200, 128, 42);
|
|
901
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
902
|
+
|
|
903
|
+
let config = ProductQuantizationConfig {
|
|
904
|
+
num_sub_vectors: 8,
|
|
905
|
+
num_centroids: 16, // Small for testing
|
|
906
|
+
training_iterations: 5,
|
|
907
|
+
rescore_multiplier: 10,
|
|
908
|
+
};
|
|
909
|
+
|
|
910
|
+
let quantizer = ProductQuantizer::train(&refs, 128, config);
|
|
911
|
+
|
|
912
|
+
assert_eq!(quantizer.count, 200);
|
|
913
|
+
assert_eq!(quantizer.num_sub_vectors, 8);
|
|
914
|
+
assert_eq!(quantizer.sub_dimension, 16);
|
|
915
|
+
assert_eq!(quantizer.codes.len(), 200 * 8);
|
|
916
|
+
|
|
917
|
+
// Search should return candidates
|
|
918
|
+
let query = &vectors[0];
|
|
919
|
+
let results = quantizer.search(query, 10);
|
|
920
|
+
assert!(!results.is_empty());
|
|
921
|
+
// Query itself should be the closest (distance 0 with its own centroids)
|
|
922
|
+
assert_eq!(results[0].0, 0);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
#[test]
|
|
926
|
+
fn quantized_index_build_and_search() {
|
|
927
|
+
let vectors = random_vectors(100, 64, 123);
|
|
928
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
929
|
+
|
|
930
|
+
// Test scalar
|
|
931
|
+
let idx = QuantizedIndex::build(
|
|
932
|
+
&refs,
|
|
933
|
+
64,
|
|
934
|
+
&QuantizationConfig::Scalar(ScalarQuantizationConfig::default()),
|
|
935
|
+
);
|
|
936
|
+
let candidates = idx.search_candidates(&vectors[0], 10);
|
|
937
|
+
assert!(!candidates.is_empty());
|
|
938
|
+
assert!(candidates.contains(&0));
|
|
939
|
+
|
|
940
|
+
// Test binary
|
|
941
|
+
let idx = QuantizedIndex::build(
|
|
942
|
+
&refs,
|
|
943
|
+
64,
|
|
944
|
+
&QuantizationConfig::Binary(BinaryQuantizationConfig::default()),
|
|
945
|
+
);
|
|
946
|
+
let candidates = idx.search_candidates(&vectors[0], 10);
|
|
947
|
+
assert!(!candidates.is_empty());
|
|
948
|
+
assert_eq!(candidates[0], 0);
|
|
949
|
+
|
|
950
|
+
// Test product
|
|
951
|
+
let idx = QuantizedIndex::build(
|
|
952
|
+
&refs,
|
|
953
|
+
64,
|
|
954
|
+
&QuantizationConfig::Product(ProductQuantizationConfig {
|
|
955
|
+
num_sub_vectors: 8,
|
|
956
|
+
num_centroids: 16,
|
|
957
|
+
training_iterations: 5,
|
|
958
|
+
rescore_multiplier: 10,
|
|
959
|
+
}),
|
|
960
|
+
);
|
|
961
|
+
let candidates = idx.search_candidates(&vectors[0], 10);
|
|
962
|
+
assert!(!candidates.is_empty());
|
|
963
|
+
assert_eq!(candidates[0], 0);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
#[test]
|
|
967
|
+
fn serialization_roundtrip_scalar() {
|
|
968
|
+
let vectors = random_vectors(50, 32, 99);
|
|
969
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
970
|
+
|
|
971
|
+
let original = QuantizedIndex::build(
|
|
972
|
+
&refs,
|
|
973
|
+
32,
|
|
974
|
+
&QuantizationConfig::Scalar(ScalarQuantizationConfig {
|
|
975
|
+
rescore_multiplier: 7,
|
|
976
|
+
}),
|
|
977
|
+
);
|
|
978
|
+
|
|
979
|
+
let mut buf = Vec::new();
|
|
980
|
+
original.write_params(&mut buf).unwrap();
|
|
981
|
+
|
|
982
|
+
let mut cursor = std::io::Cursor::new(&buf);
|
|
983
|
+
let restored = QuantizedIndex::read_params(&mut cursor).unwrap();
|
|
984
|
+
|
|
985
|
+
match (&original, &restored) {
|
|
986
|
+
(QuantizedIndex::Scalar(a), QuantizedIndex::Scalar(b)) => {
|
|
987
|
+
assert_eq!(a.dimension, b.dimension);
|
|
988
|
+
assert_eq!(a.mins, b.mins);
|
|
989
|
+
assert_eq!(a.maxs, b.maxs);
|
|
990
|
+
assert_eq!(a.config, b.config);
|
|
991
|
+
}
|
|
992
|
+
_ => panic!("type mismatch"),
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
#[test]
|
|
997
|
+
fn serialization_roundtrip_binary() {
|
|
998
|
+
let original = QuantizedIndex::build(
|
|
999
|
+
&[&[1.0, -1.0, 0.5, -0.3][..]],
|
|
1000
|
+
4,
|
|
1001
|
+
&QuantizationConfig::Binary(BinaryQuantizationConfig {
|
|
1002
|
+
rescore_multiplier: 12,
|
|
1003
|
+
}),
|
|
1004
|
+
);
|
|
1005
|
+
|
|
1006
|
+
let mut buf = Vec::new();
|
|
1007
|
+
original.write_params(&mut buf).unwrap();
|
|
1008
|
+
|
|
1009
|
+
let mut cursor = std::io::Cursor::new(&buf);
|
|
1010
|
+
let restored = QuantizedIndex::read_params(&mut cursor).unwrap();
|
|
1011
|
+
|
|
1012
|
+
match (&original, &restored) {
|
|
1013
|
+
(QuantizedIndex::Binary(a), QuantizedIndex::Binary(b)) => {
|
|
1014
|
+
assert_eq!(a.dimension, b.dimension);
|
|
1015
|
+
assert_eq!(a.config, b.config);
|
|
1016
|
+
}
|
|
1017
|
+
_ => panic!("type mismatch"),
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
#[test]
|
|
1022
|
+
fn serialization_roundtrip_product() {
|
|
1023
|
+
let vectors = random_vectors(50, 32, 77);
|
|
1024
|
+
let refs: Vec<&[f32]> = vectors.iter().map(Vec::as_slice).collect();
|
|
1025
|
+
|
|
1026
|
+
let original = QuantizedIndex::build(
|
|
1027
|
+
&refs,
|
|
1028
|
+
32,
|
|
1029
|
+
&QuantizationConfig::Product(ProductQuantizationConfig {
|
|
1030
|
+
num_sub_vectors: 4,
|
|
1031
|
+
num_centroids: 8,
|
|
1032
|
+
training_iterations: 3,
|
|
1033
|
+
rescore_multiplier: 5,
|
|
1034
|
+
}),
|
|
1035
|
+
);
|
|
1036
|
+
|
|
1037
|
+
let mut buf = Vec::new();
|
|
1038
|
+
original.write_params(&mut buf).unwrap();
|
|
1039
|
+
|
|
1040
|
+
let mut cursor = std::io::Cursor::new(&buf);
|
|
1041
|
+
let restored = QuantizedIndex::read_params(&mut cursor).unwrap();
|
|
1042
|
+
|
|
1043
|
+
match (&original, &restored) {
|
|
1044
|
+
(QuantizedIndex::Product(a), QuantizedIndex::Product(b)) => {
|
|
1045
|
+
assert_eq!(a.dimension, b.dimension);
|
|
1046
|
+
assert_eq!(a.num_sub_vectors, b.num_sub_vectors);
|
|
1047
|
+
assert_eq!(a.num_centroids, b.num_centroids);
|
|
1048
|
+
assert_eq!(a.codebooks.len(), b.codebooks.len());
|
|
1049
|
+
for (ca, cb) in a.codebooks.iter().zip(b.codebooks.iter()) {
|
|
1050
|
+
for (va, vb) in ca.iter().zip(cb.iter()) {
|
|
1051
|
+
assert_eq!(va.len(), vb.len());
|
|
1052
|
+
for (&fa, &fb) in va.iter().zip(vb.iter()) {
|
|
1053
|
+
assert!((fa - fb).abs() < 1e-6);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
assert_eq!(a.config, b.config);
|
|
1058
|
+
}
|
|
1059
|
+
_ => panic!("type mismatch"),
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
#[test]
|
|
1064
|
+
fn hamming_distance_correctness() {
|
|
1065
|
+
assert_eq!(hamming_distance(&[0b00000000], &[0b00000000]), 0);
|
|
1066
|
+
assert_eq!(hamming_distance(&[0b11111111], &[0b00000000]), 8);
|
|
1067
|
+
assert_eq!(hamming_distance(&[0b10101010], &[0b01010101]), 8);
|
|
1068
|
+
assert_eq!(hamming_distance(&[0b10101010], &[0b10101010]), 0);
|
|
1069
|
+
assert_eq!(hamming_distance(&[0b10000000], &[0b00000000]), 1);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
#[test]
|
|
1073
|
+
fn binarize_vector_correctness() {
|
|
1074
|
+
let v = vec![1.0, -1.0, 0.5, -0.5, 0.0, 0.1, -0.1, 0.9];
|
|
1075
|
+
let binary = binarize_vector(&v);
|
|
1076
|
+
assert_eq!(binary.len(), 1);
|
|
1077
|
+
// Bit 0: 1.0 > 0 -> 1
|
|
1078
|
+
// Bit 1: -1.0 -> 0
|
|
1079
|
+
// Bit 2: 0.5 > 0 -> 1
|
|
1080
|
+
// Bit 3: -0.5 -> 0
|
|
1081
|
+
// Bit 4: 0.0 -> 0 (not strictly positive)
|
|
1082
|
+
// Bit 5: 0.1 > 0 -> 1
|
|
1083
|
+
// Bit 6: -0.1 -> 0
|
|
1084
|
+
// Bit 7: 0.9 > 0 -> 1
|
|
1085
|
+
assert_eq!(binary[0], 0b10100101);
|
|
1086
|
+
}
|
|
1087
|
+
}
|