hermes_core/structures/postings/sparse/config.rs
1//! Configuration types for sparse vector posting lists
2
3use serde::{Deserialize, Serialize};
4
5/// Sparse vector index format
6///
7/// Determines the on-disk layout and query execution strategy:
8/// - **MaxScore**: Per-dimension variable-size blocks (DAAT — document-at-a-time).
9/// Default, optimal for general sparse retrieval with block-max pruning.
10/// - **Bmp**: Fixed doc_id range blocks (BAAT — block-at-a-time).
11/// Based on Mallia, Suel & Tonellotto (SIGIR 2024). Divides the document
12/// space into fixed-size blocks and processes them in decreasing upper-bound
13/// order, enabling aggressive early termination.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
15pub enum SparseFormat {
16 /// Per-dimension variable-size blocks (existing format, DAAT MaxScore)
17 #[default]
18 MaxScore,
19 /// Fixed doc_id range blocks (BMP, BAAT block-at-a-time)
20 Bmp,
21}
22
23impl SparseFormat {
24 fn is_default(&self) -> bool {
25 *self == Self::MaxScore
26 }
27}
28
29/// Size of the index (term/dimension ID) in sparse vectors
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
31#[repr(u8)]
32pub enum IndexSize {
33 /// 16-bit index (0-65535), ideal for SPLADE vocabularies
34 U16 = 0,
35 /// 32-bit index (0-4B), for large vocabularies
36 #[default]
37 U32 = 1,
38}
39
40impl IndexSize {
41 /// Bytes per index
42 pub fn bytes(&self) -> usize {
43 match self {
44 IndexSize::U16 => 2,
45 IndexSize::U32 => 4,
46 }
47 }
48
49 /// Maximum value representable
50 pub fn max_value(&self) -> u32 {
51 match self {
52 IndexSize::U16 => u16::MAX as u32,
53 IndexSize::U32 => u32::MAX,
54 }
55 }
56
57 pub(crate) fn from_u8(v: u8) -> Option<Self> {
58 match v {
59 0 => Some(IndexSize::U16),
60 1 => Some(IndexSize::U32),
61 _ => None,
62 }
63 }
64}
65
66/// Quantization format for sparse vector weights
67///
68/// Research-validated compression/effectiveness trade-offs (Pati, 2025):
69/// - **UInt8**: 4x compression, ~1-2% nDCG@10 loss (RECOMMENDED for production)
70/// - **Float16**: 2x compression, <1% nDCG@10 loss
71/// - **Float32**: No compression, baseline effectiveness
72/// - **UInt4**: 8x compression, ~3-5% nDCG@10 loss (experimental)
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
74#[repr(u8)]
75pub enum WeightQuantization {
76 /// Full 32-bit float precision
77 #[default]
78 Float32 = 0,
79 /// 16-bit float (half precision) - 2x compression, <1% effectiveness loss
80 Float16 = 1,
81 /// 8-bit unsigned integer with scale factor - 4x compression, ~1-2% effectiveness loss (RECOMMENDED)
82 UInt8 = 2,
83 /// 4-bit unsigned integer with scale factor (packed, 2 per byte) - 8x compression, ~3-5% effectiveness loss
84 UInt4 = 3,
85}
86
87impl WeightQuantization {
88 /// Bytes per weight (approximate for UInt4)
89 pub fn bytes_per_weight(&self) -> f32 {
90 match self {
91 WeightQuantization::Float32 => 4.0,
92 WeightQuantization::Float16 => 2.0,
93 WeightQuantization::UInt8 => 1.0,
94 WeightQuantization::UInt4 => 0.5,
95 }
96 }
97
98 pub(crate) fn from_u8(v: u8) -> Option<Self> {
99 match v {
100 0 => Some(WeightQuantization::Float32),
101 1 => Some(WeightQuantization::Float16),
102 2 => Some(WeightQuantization::UInt8),
103 3 => Some(WeightQuantization::UInt4),
104 _ => None,
105 }
106 }
107}
108
109/// Query-time weighting strategy for sparse vector queries
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
111#[serde(rename_all = "snake_case")]
112pub enum QueryWeighting {
113 /// All terms get weight 1.0
114 #[default]
115 One,
116 /// Terms weighted by IDF (inverse document frequency) from global index statistics
117 /// Uses ln(N/df) where N = total docs, df = docs containing dimension
118 Idf,
119 /// Terms weighted by pre-computed IDF from model's idf.json file
120 /// Loaded from HuggingFace model repo. No fallback to global stats.
121 IdfFile,
122}
123
124/// Query-time configuration for sparse vectors
125///
126/// Research-validated query optimization strategies:
127/// - **weight_threshold (0.01-0.05)**: Drop query dimensions with weight below threshold
128/// - Filters low-IDF tokens that add latency without improving relevance
129/// - **max_query_dims (10-20)**: Process only top-k dimensions by weight
130/// - 30-50% latency reduction with <2% nDCG loss (Qiao et al., 2023)
131/// - **heap_factor (0.8)**: Skip blocks with low max score contribution
132/// - ~20% speedup with minor recall loss (SEISMIC-style)
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct SparseQueryConfig {
135 /// HuggingFace tokenizer path/name for query-time tokenization
136 /// Example: "Alibaba-NLP/gte-Qwen2-1.5B-instruct"
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub tokenizer: Option<String>,
139 /// Weighting strategy for tokenized query terms
140 #[serde(default)]
141 pub weighting: QueryWeighting,
142 /// Heap factor for approximate search (SEISMIC-style optimization)
143 /// A block is skipped if its max possible score < heap_factor * threshold
144 ///
145 /// Research recommendation:
146 /// - 1.0 = exact search (default)
147 /// - 0.8 = approximate, ~20% faster with minor recall loss (RECOMMENDED for production)
148 /// - 0.5 = very approximate, much faster but higher recall loss
149 #[serde(default = "default_heap_factor")]
150 pub heap_factor: f32,
151 /// Minimum weight for query dimensions (query-time pruning)
152 /// Dimensions with abs(weight) below this threshold are dropped before search.
153 /// Useful for filtering low-IDF tokens that add latency without improving relevance.
154 ///
155 /// - 0.0 = no filtering (default)
156 /// - 0.01-0.05 = recommended for SPLADE/learned sparse models
157 #[serde(default)]
158 pub weight_threshold: f32,
159 /// Maximum number of query dimensions to process (query pruning)
160 /// Processes only the top-k dimensions by weight
161 ///
162 /// Research recommendation (Multiple papers 2022-2024):
163 /// - None = process all dimensions (default, exact)
164 /// - Some(10-20) = process top 10-20 dimensions only (RECOMMENDED for SPLADE)
165 /// - 30-50% latency reduction
166 /// - <2% nDCG@10 loss
167 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub max_query_dims: Option<usize>,
169 /// Fraction of query dimensions to keep (0.0-1.0), same semantics as
170 /// indexing-time `pruning`: sort by abs(weight) descending and keep the
171 /// top fraction. BMP uses this subset for candidate generation and the
172 /// bounded full query for final scoring; MaxScore uses the subset for both.
173 /// None or 1.0 = no pruning.
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub pruning: Option<f32>,
176 /// Minimum number of query dimensions before pruning and weight_threshold
177 /// filtering are applied. Protects short queries from losing most signal.
178 ///
179 /// Default: 4. Set to 0 to always apply pruning/filtering.
180 #[serde(default = "default_min_terms")]
181 pub min_query_dims: usize,
182 /// LSP/0 top-superblock guarantee γ. `None` selects the paper-derived
183 /// schedule from retrieval depth; `Some(0)` requests exhaustive traversal.
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub lsp_gamma: Option<usize>,
186}
187
188fn default_heap_factor() -> f32 {
189 1.0
190}
191
192impl Default for SparseQueryConfig {
193 fn default() -> Self {
194 Self {
195 tokenizer: None,
196 weighting: QueryWeighting::One,
197 heap_factor: 1.0,
198 weight_threshold: 0.0,
199 max_query_dims: None,
200 pruning: None,
201 min_query_dims: 4,
202 lsp_gamma: None,
203 }
204 }
205}
206
207/// Configuration for sparse vector storage
208///
209/// Research-validated optimizations for learned sparse retrieval (SPLADE, uniCOIL, etc.):
210/// - **Weight threshold (0.01-0.05)**: Removes ~30-50% of postings with minimal nDCG impact
211/// - **Posting list pruning (0.1)**: Keeps top 10% per dimension, 50-70% index reduction, <1% nDCG loss
212/// - **Query pruning (top 10-20 dims)**: 30-50% latency reduction, <2% nDCG loss
213/// - **UInt8 quantization**: 4x compression, 1-2% nDCG loss (optimal trade-off)
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215pub struct SparseVectorConfig {
216 /// Index format: MaxScore (DAAT) or BMP (BAAT)
217 #[serde(default, skip_serializing_if = "SparseFormat::is_default")]
218 pub format: SparseFormat,
219 /// Size of dimension/term indices
220 pub index_size: IndexSize,
221 /// Quantization for weights (see WeightQuantization docs for trade-offs)
222 pub weight_quantization: WeightQuantization,
223 /// Minimum weight threshold - weights below this value are not indexed
224 ///
225 /// Research recommendation (Guo et al., 2022; SPLADE v2):
226 /// - 0.01-0.05 for SPLADE models removes ~30-50% of postings
227 /// - Minimal impact on nDCG@10 (<1% loss)
228 /// - Major reduction in index size and query latency
229 #[serde(default)]
230 pub weight_threshold: f32,
231 /// Document-side mass cropping: keep the top-|weight| entries covering
232 /// this fraction of a sparse vector's total |weight| mass; the excessive
233 /// tail is dropped at indexing time.
234 ///
235 /// SPLADE-style vectors concentrate importance in a few head terms; the
236 /// long tail inflates the index and query cost with little relevance
237 /// signal. 0.9-0.95 typically drops 20-40% of postings with <1% nDCG loss.
238 ///
239 /// - None or >= 1.0 = keep all entries (default)
240 /// - Applied after `weight_threshold`; vectors with <= `min_terms`
241 /// entries are never cropped.
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub doc_mass: Option<f32>,
244 /// Block size for posting lists (must be power of 2, default 128 for SIMD)
245 /// Larger blocks = better compression, smaller blocks = faster seeks.
246 /// Used by MaxScore format only.
247 #[serde(default = "default_block_size")]
248 pub block_size: usize,
249 /// BMP block size: number of consecutive doc_ids per block (must be power
250 /// of 2, max 256). Only used when format = Bmp. Uniform across every
251 /// segment of the field — set per field in SDL (`bmp_block_size: N`).
252 /// Smaller = better pruning granularity; larger means fewer locally
253 /// bit-packed maximum cells. Default 32 favors pruning granularity;
254 /// increase it only after representative tail-latency testing
255 /// (docs/bmp-grid-compression.md).
256 #[serde(default = "default_bmp_block_size")]
257 pub bmp_block_size: u32,
258 /// Bits per BMP block-grid cell: 4 (default) or 2. Two caps compressed D
259 /// payload groups at two bits; the exact space reduction depends on local
260 /// group widths. Measured pruning cost is small (+0.4-2.2% blocks scored;
261 /// the ceil-u4 superblock grid prunes first).
262 /// Grid bounds are ceil-quantized, so exact top-k results are unchanged
263 /// at any width. Uniform per field across all segments — set in SDL
264 /// (`bmp_grid_bits: 2`) at index creation.
265 #[serde(default = "default_bmp_grid_bits")]
266 pub bmp_grid_bits: u8,
267 /// Static pruning: fraction of postings to keep per inverted list (SEISMIC-style)
268 /// Lists are sorted by weight descending and truncated to top fraction.
269 ///
270 /// Research recommendation (SPLADE v2, Formal et al., 2021):
271 /// - None = keep all postings (default, exact)
272 /// - Some(0.1) = keep top 10% of postings per dimension
273 /// - 50-70% index size reduction
274 /// - <1% nDCG@10 loss
275 /// - Exploits "concentration of importance" in learned representations
276 ///
277 /// Applied only during initial segment build, not during merge.
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub pruning: Option<f32>,
280 /// Query-time configuration (tokenizer, weighting)
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub query_config: Option<SparseQueryConfig>,
283 /// Fixed vocabulary size (number of dimensions) for BMP format.
284 ///
285 /// When set, all BMP segments use the same grid dimensions (rows = dims),
286 /// enabling zero-copy block-copy merge. The grid is indexed by dim_id directly
287 /// (no dim_ids Section C needed).
288 ///
289 /// Required for BMP format. Typical values:
290 /// - SPLADE/BERT: 30522 or 105879 (WordPiece / Unigram vocabulary)
291 /// - uniCOIL: 30522
292 /// - Custom models: set to vocabulary size
293 ///
294 /// If None, the BMP builder derives dims from observed data.
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub dims: Option<u32>,
297 /// Fixed max weight scale for BMP format.
298 ///
299 /// When set, all BMP segments use the same quantization scale
300 /// (`max_weight_scale = max_weight`), eliminating rescaling during merge.
301 ///
302 /// For SPLADE models: 5.0 (covers typical weight range 0-5).
303 /// If None, the BMP builder derives scale from data.
304 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub max_weight: Option<f32>,
306 /// Minimum number of postings in a dimension before pruning and
307 /// weight_threshold filtering are applied. Protects dimensions with
308 /// very few postings from losing most of their signal.
309 ///
310 /// Default: 4. Set to 0 to always apply pruning/filtering.
311 #[serde(default = "default_min_terms")]
312 pub min_terms: usize,
313}
314
315fn default_block_size() -> usize {
316 128
317}
318
319fn default_bmp_block_size() -> u32 {
320 SparseVectorConfig::DEFAULT_BMP_BLOCK_SIZE
321}
322
323fn default_bmp_grid_bits() -> u8 {
324 SparseVectorConfig::DEFAULT_BMP_GRID_BITS
325}
326
327fn default_min_terms() -> usize {
328 4
329}
330
331impl Default for SparseVectorConfig {
332 fn default() -> Self {
333 Self {
334 format: SparseFormat::MaxScore,
335 index_size: IndexSize::U32,
336 weight_quantization: WeightQuantization::Float32,
337 weight_threshold: 0.0,
338 doc_mass: None,
339 block_size: 128,
340 bmp_block_size: default_bmp_block_size(),
341 bmp_grid_bits: default_bmp_grid_bits(),
342 pruning: None,
343 query_config: None,
344
345 dims: None,
346 max_weight: None,
347 min_terms: 4,
348 }
349 }
350}
351
352impl SparseVectorConfig {
353 pub const DEFAULT_BMP_BLOCK_SIZE: u32 = 32;
354 pub const DEFAULT_BMP_GRID_BITS: u8 = 4;
355
356 /// SPLADE-optimized config with research-validated defaults
357 ///
358 /// Optimized for SPLADE, uniCOIL, and similar learned sparse retrieval models.
359 /// Based on research findings from:
360 /// - Pati (2025): UInt8 quantization = 4x compression, 1-2% nDCG loss
361 /// - Formal et al. (2021): SPLADE v2 posting list pruning
362 /// - Qiao et al. (2023): Query dimension pruning and approximate search
363 /// - Guo et al. (2022): Weight thresholding for efficiency
364 ///
365 /// Expected performance vs. full precision baseline:
366 /// - Index size: ~15-25% of original (combined effect of all optimizations)
367 /// - Query latency: 40-60% faster
368 /// - Effectiveness: 2-4% nDCG@10 loss (typically acceptable for production)
369 ///
370 /// Vocabulary: ~30K dimensions (fits in u16)
371 pub fn splade() -> Self {
372 Self {
373 format: SparseFormat::MaxScore,
374 index_size: IndexSize::U16,
375 weight_quantization: WeightQuantization::UInt8,
376 weight_threshold: 0.01, // Remove ~30-50% of low-weight postings
377 doc_mass: None,
378 block_size: 128,
379 bmp_block_size: default_bmp_block_size(),
380 bmp_grid_bits: default_bmp_grid_bits(),
381 pruning: Some(0.1), // Keep top 10% per dimension
382 query_config: Some(SparseQueryConfig {
383 tokenizer: None,
384 weighting: QueryWeighting::One,
385 heap_factor: 0.8, // 20% faster approximate search
386 weight_threshold: 0.01, // Drop low-IDF query tokens
387 max_query_dims: Some(20), // Process top 20 query dimensions
388 pruning: Some(0.1), // Keep top 10% of query dims
389 min_query_dims: 4,
390 lsp_gamma: None,
391 }),
392
393 dims: None,
394 max_weight: None,
395 min_terms: 4,
396 }
397 }
398
399 /// SPLADE-optimized config with BMP (Block-Max Pruning) format
400 ///
401 /// Same optimization settings as `splade()` but uses the BMP block-at-a-time
402 /// format (Mallia, Suel & Tonellotto, SIGIR 2024) instead of MaxScore.
403 /// BMP divides the document space into fixed-size blocks and processes them
404 /// in decreasing upper-bound order, enabling aggressive early termination.
405 pub fn splade_bmp() -> Self {
406 Self {
407 format: SparseFormat::Bmp,
408 index_size: IndexSize::U16,
409 weight_quantization: WeightQuantization::UInt8,
410 weight_threshold: 0.01,
411 doc_mass: None,
412 block_size: 128,
413 bmp_block_size: default_bmp_block_size(),
414 bmp_grid_bits: default_bmp_grid_bits(),
415 pruning: Some(0.1),
416 query_config: Some(SparseQueryConfig {
417 tokenizer: None,
418 weighting: QueryWeighting::One,
419 heap_factor: 1.0,
420 weight_threshold: 0.01,
421 max_query_dims: None,
422 pruning: Some(0.33),
423 min_query_dims: 4,
424 lsp_gamma: None,
425 }),
426
427 dims: Some(105879),
428 max_weight: Some(5.0),
429 min_terms: 4,
430 }
431 }
432
433 /// Compact config: Maximum compression (experimental)
434 ///
435 /// Uses aggressive UInt4 quantization for smallest possible index size.
436 /// Expected trade-offs:
437 /// - Index size: ~10-15% of Float32 baseline
438 /// - Effectiveness: ~3-5% nDCG@10 loss
439 ///
440 /// Recommended for: Memory-constrained environments, cache-heavy workloads
441 pub fn compact() -> Self {
442 Self {
443 format: SparseFormat::MaxScore,
444 index_size: IndexSize::U16,
445 weight_quantization: WeightQuantization::UInt4,
446 weight_threshold: 0.02, // Slightly higher threshold for UInt4
447 doc_mass: None,
448 block_size: 128,
449 bmp_block_size: default_bmp_block_size(),
450 bmp_grid_bits: default_bmp_grid_bits(),
451 pruning: Some(0.15), // Keep top 15% per dimension
452 query_config: Some(SparseQueryConfig {
453 tokenizer: None,
454 weighting: QueryWeighting::One,
455 heap_factor: 0.7, // More aggressive approximate search
456 weight_threshold: 0.02, // Drop low-IDF query tokens
457 max_query_dims: Some(15), // Fewer query dimensions
458 pruning: Some(0.15), // Keep top 15% of query dims
459 min_query_dims: 4,
460 lsp_gamma: None,
461 }),
462
463 dims: None,
464 max_weight: None,
465 min_terms: 4,
466 }
467 }
468
469 /// Full precision config: No compression, baseline effectiveness
470 ///
471 /// Use for: Research baselines, when effectiveness is critical
472 pub fn full_precision() -> Self {
473 Self {
474 format: SparseFormat::MaxScore,
475 index_size: IndexSize::U32,
476 weight_quantization: WeightQuantization::Float32,
477 weight_threshold: 0.0,
478 doc_mass: None,
479 block_size: 128,
480 bmp_block_size: default_bmp_block_size(),
481 bmp_grid_bits: default_bmp_grid_bits(),
482 pruning: None,
483 query_config: None,
484
485 dims: None,
486 max_weight: None,
487 min_terms: 4,
488 }
489 }
490
491 /// Conservative config: Mild optimizations, minimal effectiveness loss
492 ///
493 /// Balances compression and effectiveness with conservative defaults.
494 /// Expected trade-offs:
495 /// - Index size: ~40-50% of Float32 baseline
496 /// - Query latency: ~20-30% faster
497 /// - Effectiveness: <1% nDCG@10 loss
498 ///
499 /// Recommended for: Production deployments prioritizing effectiveness
500 pub fn conservative() -> Self {
501 Self {
502 format: SparseFormat::MaxScore,
503 index_size: IndexSize::U32,
504 weight_quantization: WeightQuantization::Float16,
505 weight_threshold: 0.005, // Minimal pruning
506 doc_mass: None,
507 block_size: 128,
508 bmp_block_size: default_bmp_block_size(),
509 bmp_grid_bits: default_bmp_grid_bits(),
510 pruning: None, // No posting list pruning
511 query_config: Some(SparseQueryConfig {
512 tokenizer: None,
513 weighting: QueryWeighting::One,
514 heap_factor: 0.9, // Nearly exact search
515 weight_threshold: 0.005, // Minimal query pruning
516 max_query_dims: Some(50), // Process more dimensions
517 pruning: None, // No fraction-based pruning
518 min_query_dims: 4,
519 lsp_gamma: None,
520 }),
521
522 dims: None,
523 max_weight: None,
524 min_terms: 4,
525 }
526 }
527
528 /// Set weight threshold (builder pattern)
529 pub fn with_weight_threshold(mut self, threshold: f32) -> Self {
530 self.weight_threshold = threshold;
531 self
532 }
533
534 /// Set document-side mass cropping fraction (builder pattern)
535 /// e.g., 0.9 = keep top-weight entries covering 90% of each vector's mass
536 pub fn with_doc_mass(mut self, fraction: f32) -> Self {
537 self.doc_mass = Some(fraction.clamp(0.0, 1.0));
538 self
539 }
540
541 /// Set posting list pruning fraction (builder pattern)
542 /// e.g., 0.1 = keep top 10% of postings per dimension
543 pub fn with_pruning(mut self, fraction: f32) -> Self {
544 self.pruning = Some(fraction.clamp(0.0, 1.0));
545 self
546 }
547
548 /// Bytes per entry (index + weight)
549 pub fn bytes_per_entry(&self) -> f32 {
550 self.index_size.bytes() as f32 + self.weight_quantization.bytes_per_weight()
551 }
552
553 /// Serialize config to a single byte.
554 ///
555 /// Layout: bits 7-4 = IndexSize, bit 3 = format (0=MaxScore, 1=BMP), bits 2-0 = WeightQuantization
556 pub fn to_byte(&self) -> u8 {
557 let format_bit = if self.format == SparseFormat::Bmp {
558 0x08
559 } else {
560 0
561 };
562 ((self.index_size as u8) << 4) | format_bit | (self.weight_quantization as u8)
563 }
564
565 /// Deserialize config from a single byte.
566 ///
567 /// Note: weight_threshold, block_size, bmp_block_size, and query_config are not
568 /// serialized in the byte — they come from the schema.
569 pub fn from_byte(b: u8) -> Option<Self> {
570 let index_size = IndexSize::from_u8((b >> 4) & 0x03)?;
571 let format = if b & 0x08 != 0 {
572 SparseFormat::Bmp
573 } else {
574 SparseFormat::MaxScore
575 };
576 let weight_quantization = WeightQuantization::from_u8(b & 0x07)?;
577 Some(Self {
578 format,
579 index_size,
580 weight_quantization,
581 weight_threshold: 0.0,
582 doc_mass: None,
583 block_size: 128,
584 bmp_block_size: default_bmp_block_size(),
585 bmp_grid_bits: default_bmp_grid_bits(),
586 pruning: None,
587 query_config: None,
588
589 dims: None,
590 max_weight: None,
591 min_terms: 4,
592 })
593 }
594
595 /// Set block size (builder pattern)
596 /// Must be power of 2, recommended: 64, 128, 256
597 pub fn with_block_size(mut self, size: usize) -> Self {
598 self.block_size = size.next_power_of_two();
599 self
600 }
601
602 /// Set query configuration (builder pattern)
603 pub fn with_query_config(mut self, config: SparseQueryConfig) -> Self {
604 self.query_config = Some(config);
605 self
606 }
607}
608
609/// A sparse vector entry: (dimension_id, weight)
610#[derive(Debug, Clone, Copy, PartialEq)]
611pub struct SparseEntry {
612 pub dim_id: u32,
613 pub weight: f32,
614}
615
616/// Sparse vector representation
617#[derive(Debug, Clone, Default)]
618pub struct SparseVector {
619 pub(super) entries: Vec<SparseEntry>,
620}
621
622impl SparseVector {
623 /// Create a new sparse vector
624 pub fn new() -> Self {
625 Self {
626 entries: Vec::new(),
627 }
628 }
629
630 /// Create with pre-allocated capacity
631 pub fn with_capacity(capacity: usize) -> Self {
632 Self {
633 entries: Vec::with_capacity(capacity),
634 }
635 }
636
637 /// Create from dimension IDs and weights
638 pub fn from_entries(dim_ids: &[u32], weights: &[f32]) -> Self {
639 assert_eq!(dim_ids.len(), weights.len());
640 let mut entries: Vec<SparseEntry> = dim_ids
641 .iter()
642 .zip(weights.iter())
643 .map(|(&dim_id, &weight)| SparseEntry { dim_id, weight })
644 .collect();
645 // Sort by dimension ID for efficient intersection
646 entries.sort_by_key(|e| e.dim_id);
647 Self { entries }
648 }
649
650 /// Add an entry (must maintain sorted order by dim_id)
651 pub fn push(&mut self, dim_id: u32, weight: f32) {
652 debug_assert!(
653 self.entries.is_empty() || self.entries.last().unwrap().dim_id < dim_id,
654 "Entries must be added in sorted order by dim_id"
655 );
656 self.entries.push(SparseEntry { dim_id, weight });
657 }
658
659 /// Number of non-zero entries
660 pub fn len(&self) -> usize {
661 self.entries.len()
662 }
663
664 /// Check if empty
665 pub fn is_empty(&self) -> bool {
666 self.entries.is_empty()
667 }
668
669 /// Iterate over entries
670 pub fn iter(&self) -> impl Iterator<Item = &SparseEntry> {
671 self.entries.iter()
672 }
673
674 /// Sort by dimension ID (required for posting list encoding)
675 pub fn sort_by_dim(&mut self) {
676 self.entries.sort_by_key(|e| e.dim_id);
677 }
678
679 /// Sort by weight descending
680 pub fn sort_by_weight_desc(&mut self) {
681 self.entries.sort_by(|a, b| {
682 b.weight
683 .partial_cmp(&a.weight)
684 .unwrap_or(std::cmp::Ordering::Equal)
685 });
686 }
687
688 /// Get top-k entries by weight
689 pub fn top_k(&self, k: usize) -> Vec<SparseEntry> {
690 let mut sorted = self.entries.clone();
691 sorted.sort_by(|a, b| {
692 b.weight
693 .partial_cmp(&a.weight)
694 .unwrap_or(std::cmp::Ordering::Equal)
695 });
696 sorted.truncate(k);
697 sorted
698 }
699
700 /// Compute dot product with another sparse vector
701 pub fn dot(&self, other: &SparseVector) -> f32 {
702 let mut result = 0.0f32;
703 let mut i = 0;
704 let mut j = 0;
705
706 while i < self.entries.len() && j < other.entries.len() {
707 let a = &self.entries[i];
708 let b = &other.entries[j];
709
710 match a.dim_id.cmp(&b.dim_id) {
711 std::cmp::Ordering::Less => i += 1,
712 std::cmp::Ordering::Greater => j += 1,
713 std::cmp::Ordering::Equal => {
714 result += a.weight * b.weight;
715 i += 1;
716 j += 1;
717 }
718 }
719 }
720
721 result
722 }
723
724 /// L2 norm squared
725 pub fn norm_squared(&self) -> f32 {
726 self.entries.iter().map(|e| e.weight * e.weight).sum()
727 }
728
729 /// L2 norm
730 pub fn norm(&self) -> f32 {
731 self.norm_squared().sqrt()
732 }
733
734 /// Prune dimensions below a weight threshold
735 pub fn filter_by_weight(&self, min_weight: f32) -> Self {
736 let entries: Vec<SparseEntry> = self
737 .entries
738 .iter()
739 .filter(|e| e.weight.abs() >= min_weight)
740 .cloned()
741 .collect();
742 Self { entries }
743 }
744}
745
746impl From<Vec<(u32, f32)>> for SparseVector {
747 fn from(pairs: Vec<(u32, f32)>) -> Self {
748 Self {
749 entries: pairs
750 .into_iter()
751 .map(|(dim_id, weight)| SparseEntry { dim_id, weight })
752 .collect(),
753 }
754 }
755}
756
757impl From<SparseVector> for Vec<(u32, f32)> {
758 fn from(vec: SparseVector) -> Self {
759 vec.entries
760 .into_iter()
761 .map(|e| (e.dim_id, e.weight))
762 .collect()
763 }
764}