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