Skip to main content

hermes_core/structures/postings/sparse/
config.rs

1//! Configuration types for sparse vector posting lists
2
3use serde::{Deserialize, Serialize};
4
5/// Size of the index (term/dimension ID) in sparse vectors
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
7#[repr(u8)]
8pub enum IndexSize {
9    /// 16-bit index (0-65535), ideal for SPLADE vocabularies
10    U16 = 0,
11    /// 32-bit index (0-4B), for large vocabularies
12    #[default]
13    U32 = 1,
14}
15
16impl IndexSize {
17    /// Bytes per index
18    pub fn bytes(&self) -> usize {
19        match self {
20            IndexSize::U16 => 2,
21            IndexSize::U32 => 4,
22        }
23    }
24
25    /// Maximum value representable
26    pub fn max_value(&self) -> u32 {
27        match self {
28            IndexSize::U16 => u16::MAX as u32,
29            IndexSize::U32 => u32::MAX,
30        }
31    }
32
33    pub(crate) fn from_u8(v: u8) -> Option<Self> {
34        match v {
35            0 => Some(IndexSize::U16),
36            1 => Some(IndexSize::U32),
37            _ => None,
38        }
39    }
40}
41
42/// Quantization format for sparse vector weights
43///
44/// Research-validated compression/effectiveness trade-offs (Pati, 2025):
45/// - **UInt8**: 4x compression, ~1-2% nDCG@10 loss (RECOMMENDED for production)
46/// - **Float16**: 2x compression, <1% nDCG@10 loss
47/// - **Float32**: No compression, baseline effectiveness
48/// - **UInt4**: 8x compression, ~3-5% nDCG@10 loss (experimental)
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50#[repr(u8)]
51pub enum WeightQuantization {
52    /// Full 32-bit float precision
53    #[default]
54    Float32 = 0,
55    /// 16-bit float (half precision) - 2x compression, <1% effectiveness loss
56    Float16 = 1,
57    /// 8-bit unsigned integer with scale factor - 4x compression, ~1-2% effectiveness loss (RECOMMENDED)
58    UInt8 = 2,
59    /// 4-bit unsigned integer with scale factor (packed, 2 per byte) - 8x compression, ~3-5% effectiveness loss
60    UInt4 = 3,
61}
62
63impl WeightQuantization {
64    /// Bytes per weight (approximate for UInt4)
65    pub fn bytes_per_weight(&self) -> f32 {
66        match self {
67            WeightQuantization::Float32 => 4.0,
68            WeightQuantization::Float16 => 2.0,
69            WeightQuantization::UInt8 => 1.0,
70            WeightQuantization::UInt4 => 0.5,
71        }
72    }
73
74    pub(crate) fn from_u8(v: u8) -> Option<Self> {
75        match v {
76            0 => Some(WeightQuantization::Float32),
77            1 => Some(WeightQuantization::Float16),
78            2 => Some(WeightQuantization::UInt8),
79            3 => Some(WeightQuantization::UInt4),
80            _ => None,
81        }
82    }
83}
84
85/// Query-time weighting strategy for sparse vector queries
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
87pub enum QueryWeighting {
88    /// All terms get weight 1.0
89    #[default]
90    One,
91    /// Terms weighted by IDF (inverse document frequency) from the index
92    Idf,
93}
94
95/// Query-time configuration for sparse vectors
96///
97/// Research-validated query optimization strategies:
98/// - **max_query_dims (10-20)**: Process only top-k dimensions by weight
99///   - 30-50% latency reduction with <2% nDCG loss (Qiao et al., 2023)
100/// - **heap_factor (0.8)**: Skip blocks with low max score contribution
101///   - ~20% speedup with minor recall loss (SEISMIC-style)
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub struct SparseQueryConfig {
104    /// HuggingFace tokenizer path/name for query-time tokenization
105    /// Example: "Alibaba-NLP/gte-Qwen2-1.5B-instruct"
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub tokenizer: Option<String>,
108    /// Weighting strategy for tokenized query terms
109    #[serde(default)]
110    pub weighting: QueryWeighting,
111    /// Heap factor for approximate search (SEISMIC-style optimization)
112    /// A block is skipped if its max possible score < heap_factor * threshold
113    ///
114    /// Research recommendation:
115    /// - 1.0 = exact search (default)
116    /// - 0.8 = approximate, ~20% faster with minor recall loss (RECOMMENDED for production)
117    /// - 0.5 = very approximate, much faster but higher recall loss
118    #[serde(default = "default_heap_factor")]
119    pub heap_factor: f32,
120    /// Maximum number of query dimensions to process (query pruning)
121    /// Processes only the top-k dimensions by weight
122    ///
123    /// Research recommendation (Multiple papers 2022-2024):
124    /// - None = process all dimensions (default, exact)
125    /// - Some(10-20) = process top 10-20 dimensions only (RECOMMENDED for SPLADE)
126    ///   - 30-50% latency reduction
127    ///   - <2% nDCG@10 loss
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub max_query_dims: Option<usize>,
130}
131
132fn default_heap_factor() -> f32 {
133    1.0
134}
135
136impl Default for SparseQueryConfig {
137    fn default() -> Self {
138        Self {
139            tokenizer: None,
140            weighting: QueryWeighting::One,
141            heap_factor: 1.0,
142            max_query_dims: None,
143        }
144    }
145}
146
147/// Configuration for sparse vector storage
148///
149/// Research-validated optimizations for learned sparse retrieval (SPLADE, uniCOIL, etc.):
150/// - **Weight threshold (0.01-0.05)**: Removes ~30-50% of postings with minimal nDCG impact
151/// - **Posting list pruning (0.1)**: Keeps top 10% per dimension, 50-70% index reduction, <1% nDCG loss
152/// - **Query pruning (top 10-20 dims)**: 30-50% latency reduction, <2% nDCG loss
153/// - **UInt8 quantization**: 4x compression, 1-2% nDCG loss (optimal trade-off)
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155pub struct SparseVectorConfig {
156    /// Size of dimension/term indices
157    pub index_size: IndexSize,
158    /// Quantization for weights (see WeightQuantization docs for trade-offs)
159    pub weight_quantization: WeightQuantization,
160    /// Minimum weight threshold - weights below this value are not indexed
161    ///
162    /// Research recommendation (Guo et al., 2022; SPLADE v2):
163    /// - 0.01-0.05 for SPLADE models removes ~30-50% of postings
164    /// - Minimal impact on nDCG@10 (<1% loss)
165    /// - Major reduction in index size and query latency
166    #[serde(default)]
167    pub weight_threshold: f32,
168    /// Block size for posting lists (must be power of 2, default 128 for SIMD)
169    /// Larger blocks = better compression, smaller blocks = faster seeks
170    #[serde(default = "default_block_size")]
171    pub block_size: usize,
172    /// Static pruning: fraction of postings to keep per inverted list (SEISMIC-style)
173    /// Lists are sorted by weight descending and truncated to top fraction.
174    ///
175    /// Research recommendation (SPLADE v2, Formal et al., 2021):
176    /// - None = keep all postings (default, exact)
177    /// - Some(0.1) = keep top 10% of postings per dimension
178    ///   - 50-70% index size reduction
179    ///   - <1% nDCG@10 loss
180    ///   - Exploits "concentration of importance" in learned representations
181    ///
182    /// Applied only during initial segment build, not during merge.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub posting_list_pruning: Option<f32>,
185    /// Query-time configuration (tokenizer, weighting)
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub query_config: Option<SparseQueryConfig>,
188}
189
190fn default_block_size() -> usize {
191    128
192}
193
194impl Default for SparseVectorConfig {
195    fn default() -> Self {
196        Self {
197            index_size: IndexSize::U32,
198            weight_quantization: WeightQuantization::Float32,
199            weight_threshold: 0.0,
200            block_size: 128,
201            posting_list_pruning: None,
202            query_config: None,
203        }
204    }
205}
206
207impl SparseVectorConfig {
208    /// SPLADE-optimized config with research-validated defaults
209    ///
210    /// Optimized for SPLADE, uniCOIL, and similar learned sparse retrieval models.
211    /// Based on research findings from:
212    /// - Pati (2025): UInt8 quantization = 4x compression, 1-2% nDCG loss
213    /// - Formal et al. (2021): SPLADE v2 posting list pruning
214    /// - Qiao et al. (2023): Query dimension pruning and approximate search
215    /// - Guo et al. (2022): Weight thresholding for efficiency
216    ///
217    /// Expected performance vs. full precision baseline:
218    /// - Index size: ~15-25% of original (combined effect of all optimizations)
219    /// - Query latency: 40-60% faster
220    /// - Effectiveness: 2-4% nDCG@10 loss (typically acceptable for production)
221    ///
222    /// Vocabulary: ~30K dimensions (fits in u16)
223    pub fn splade() -> Self {
224        Self {
225            index_size: IndexSize::U16,
226            weight_quantization: WeightQuantization::UInt8,
227            weight_threshold: 0.01, // Remove ~30-50% of low-weight postings
228            block_size: 128,
229            posting_list_pruning: Some(0.1), // Keep top 10% per dimension
230            query_config: Some(SparseQueryConfig {
231                tokenizer: None,
232                weighting: QueryWeighting::One,
233                heap_factor: 0.8,         // 20% faster approximate search
234                max_query_dims: Some(20), // Process top 20 query dimensions
235            }),
236        }
237    }
238
239    /// Compact config: Maximum compression (experimental)
240    ///
241    /// Uses aggressive UInt4 quantization for smallest possible index size.
242    /// Expected trade-offs:
243    /// - Index size: ~10-15% of Float32 baseline
244    /// - Effectiveness: ~3-5% nDCG@10 loss
245    ///
246    /// Recommended for: Memory-constrained environments, cache-heavy workloads
247    pub fn compact() -> Self {
248        Self {
249            index_size: IndexSize::U16,
250            weight_quantization: WeightQuantization::UInt4,
251            weight_threshold: 0.02, // Slightly higher threshold for UInt4
252            block_size: 128,
253            posting_list_pruning: Some(0.15), // Keep top 15% per dimension
254            query_config: Some(SparseQueryConfig {
255                tokenizer: None,
256                weighting: QueryWeighting::One,
257                heap_factor: 0.7,         // More aggressive approximate search
258                max_query_dims: Some(15), // Fewer query dimensions
259            }),
260        }
261    }
262
263    /// Full precision config: No compression, baseline effectiveness
264    ///
265    /// Use for: Research baselines, when effectiveness is critical
266    pub fn full_precision() -> Self {
267        Self {
268            index_size: IndexSize::U32,
269            weight_quantization: WeightQuantization::Float32,
270            weight_threshold: 0.0,
271            block_size: 128,
272            posting_list_pruning: None,
273            query_config: None,
274        }
275    }
276
277    /// Conservative config: Mild optimizations, minimal effectiveness loss
278    ///
279    /// Balances compression and effectiveness with conservative defaults.
280    /// Expected trade-offs:
281    /// - Index size: ~40-50% of Float32 baseline
282    /// - Query latency: ~20-30% faster
283    /// - Effectiveness: <1% nDCG@10 loss
284    ///
285    /// Recommended for: Production deployments prioritizing effectiveness
286    pub fn conservative() -> Self {
287        Self {
288            index_size: IndexSize::U32,
289            weight_quantization: WeightQuantization::Float16,
290            weight_threshold: 0.005, // Minimal pruning
291            block_size: 128,
292            posting_list_pruning: None, // No posting list pruning
293            query_config: Some(SparseQueryConfig {
294                tokenizer: None,
295                weighting: QueryWeighting::One,
296                heap_factor: 0.9,         // Nearly exact search
297                max_query_dims: Some(50), // Process more dimensions
298            }),
299        }
300    }
301
302    /// Set weight threshold (builder pattern)
303    pub fn with_weight_threshold(mut self, threshold: f32) -> Self {
304        self.weight_threshold = threshold;
305        self
306    }
307
308    /// Set posting list pruning fraction (builder pattern)
309    /// e.g., 0.1 = keep top 10% of postings per dimension
310    pub fn with_pruning(mut self, fraction: f32) -> Self {
311        self.posting_list_pruning = Some(fraction.clamp(0.0, 1.0));
312        self
313    }
314
315    /// Bytes per entry (index + weight)
316    pub fn bytes_per_entry(&self) -> f32 {
317        self.index_size.bytes() as f32 + self.weight_quantization.bytes_per_weight()
318    }
319
320    /// Serialize config to a single byte
321    pub fn to_byte(&self) -> u8 {
322        ((self.index_size as u8) << 4) | (self.weight_quantization as u8)
323    }
324
325    /// Deserialize config from a single byte
326    /// Note: weight_threshold, block_size and query_config are not serialized in the byte
327    pub fn from_byte(b: u8) -> Option<Self> {
328        let index_size = IndexSize::from_u8(b >> 4)?;
329        let weight_quantization = WeightQuantization::from_u8(b & 0x0F)?;
330        Some(Self {
331            index_size,
332            weight_quantization,
333            weight_threshold: 0.0,
334            block_size: 128,
335            posting_list_pruning: None,
336            query_config: None,
337        })
338    }
339
340    /// Set block size (builder pattern)
341    /// Must be power of 2, recommended: 64, 128, 256
342    pub fn with_block_size(mut self, size: usize) -> Self {
343        self.block_size = size.next_power_of_two();
344        self
345    }
346
347    /// Set query configuration (builder pattern)
348    pub fn with_query_config(mut self, config: SparseQueryConfig) -> Self {
349        self.query_config = Some(config);
350        self
351    }
352}
353
354/// A sparse vector entry: (dimension_id, weight)
355#[derive(Debug, Clone, Copy, PartialEq)]
356pub struct SparseEntry {
357    pub dim_id: u32,
358    pub weight: f32,
359}
360
361/// Sparse vector representation
362#[derive(Debug, Clone, Default)]
363pub struct SparseVector {
364    pub(super) entries: Vec<SparseEntry>,
365}
366
367impl SparseVector {
368    /// Create a new sparse vector
369    pub fn new() -> Self {
370        Self {
371            entries: Vec::new(),
372        }
373    }
374
375    /// Create with pre-allocated capacity
376    pub fn with_capacity(capacity: usize) -> Self {
377        Self {
378            entries: Vec::with_capacity(capacity),
379        }
380    }
381
382    /// Create from dimension IDs and weights
383    pub fn from_entries(dim_ids: &[u32], weights: &[f32]) -> Self {
384        assert_eq!(dim_ids.len(), weights.len());
385        let mut entries: Vec<SparseEntry> = dim_ids
386            .iter()
387            .zip(weights.iter())
388            .map(|(&dim_id, &weight)| SparseEntry { dim_id, weight })
389            .collect();
390        // Sort by dimension ID for efficient intersection
391        entries.sort_by_key(|e| e.dim_id);
392        Self { entries }
393    }
394
395    /// Add an entry (must maintain sorted order by dim_id)
396    pub fn push(&mut self, dim_id: u32, weight: f32) {
397        debug_assert!(
398            self.entries.is_empty() || self.entries.last().unwrap().dim_id < dim_id,
399            "Entries must be added in sorted order by dim_id"
400        );
401        self.entries.push(SparseEntry { dim_id, weight });
402    }
403
404    /// Number of non-zero entries
405    pub fn len(&self) -> usize {
406        self.entries.len()
407    }
408
409    /// Check if empty
410    pub fn is_empty(&self) -> bool {
411        self.entries.is_empty()
412    }
413
414    /// Iterate over entries
415    pub fn iter(&self) -> impl Iterator<Item = &SparseEntry> {
416        self.entries.iter()
417    }
418
419    /// Sort by dimension ID (required for posting list encoding)
420    pub fn sort_by_dim(&mut self) {
421        self.entries.sort_by_key(|e| e.dim_id);
422    }
423
424    /// Sort by weight descending
425    pub fn sort_by_weight_desc(&mut self) {
426        self.entries.sort_by(|a, b| {
427            b.weight
428                .partial_cmp(&a.weight)
429                .unwrap_or(std::cmp::Ordering::Equal)
430        });
431    }
432
433    /// Get top-k entries by weight
434    pub fn top_k(&self, k: usize) -> Vec<SparseEntry> {
435        let mut sorted = self.entries.clone();
436        sorted.sort_by(|a, b| {
437            b.weight
438                .partial_cmp(&a.weight)
439                .unwrap_or(std::cmp::Ordering::Equal)
440        });
441        sorted.truncate(k);
442        sorted
443    }
444
445    /// Compute dot product with another sparse vector
446    pub fn dot(&self, other: &SparseVector) -> f32 {
447        let mut result = 0.0f32;
448        let mut i = 0;
449        let mut j = 0;
450
451        while i < self.entries.len() && j < other.entries.len() {
452            let a = &self.entries[i];
453            let b = &other.entries[j];
454
455            match a.dim_id.cmp(&b.dim_id) {
456                std::cmp::Ordering::Less => i += 1,
457                std::cmp::Ordering::Greater => j += 1,
458                std::cmp::Ordering::Equal => {
459                    result += a.weight * b.weight;
460                    i += 1;
461                    j += 1;
462                }
463            }
464        }
465
466        result
467    }
468
469    /// L2 norm squared
470    pub fn norm_squared(&self) -> f32 {
471        self.entries.iter().map(|e| e.weight * e.weight).sum()
472    }
473
474    /// L2 norm
475    pub fn norm(&self) -> f32 {
476        self.norm_squared().sqrt()
477    }
478
479    /// Prune dimensions below a weight threshold
480    pub fn filter_by_weight(&self, min_weight: f32) -> Self {
481        let entries: Vec<SparseEntry> = self
482            .entries
483            .iter()
484            .filter(|e| e.weight.abs() >= min_weight)
485            .cloned()
486            .collect();
487        Self { entries }
488    }
489}
490
491impl From<Vec<(u32, f32)>> for SparseVector {
492    fn from(pairs: Vec<(u32, f32)>) -> Self {
493        Self {
494            entries: pairs
495                .into_iter()
496                .map(|(dim_id, weight)| SparseEntry { dim_id, weight })
497                .collect(),
498        }
499    }
500}
501
502impl From<SparseVector> for Vec<(u32, f32)> {
503    fn from(vec: SparseVector) -> Self {
504        vec.entries
505            .into_iter()
506            .map(|e| (e.dim_id, e.weight))
507            .collect()
508    }
509}