1use crate::error::{ProjectionError, Result};
16use serde::{Deserialize, Serialize};
17
18pub const PROJECTION_PROTOCOL: &str = "hawdb-rabitq-projection";
19pub const PROJECTION_FORMAT_VERSION: u32 = 2;
20pub const DEFAULT_PROJECTION_BIT_WIDTH: u8 = 4;
21pub const PROJECTION_BIT_WIDTH: u8 = DEFAULT_PROJECTION_BIT_WIDTH;
22pub const PROJECTION_ALGORITHM: &str = "rabitq";
23pub const PROJECTION_TRANSFORM: &str = "signed_block_hadamard_v2";
24pub const PROJECTION_QUANTIZER: &str = "rabitq_sign_then_refinement_scalar_4bit_v1";
25const ONE_BIT_PROJECTION_QUANTIZER: &str = "rabitq_sign_then_refinement_scalar_1bit_v1";
26pub const PROJECTION_CALIBRATION: &str = "inverse_alignment_v1";
27pub const DEFAULT_TRANSFORM_SEED: u64 = 0x534b_4549_4e56_5134;
28pub const DEFAULT_SEGMENT_ROWS: usize = 1_024;
29pub const DEFAULT_BUILD_MEMORY_BYTES: usize = 64 * 1024 * 1024;
30pub(crate) const BUILD_FIXED_WORKING_BYTES: usize = 1_024;
31
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[repr(u8)]
34pub enum RaBitQBitWidth {
35 One = 1,
36 #[default]
37 Four = 4,
38}
39
40impl RaBitQBitWidth {
41 pub const fn bits(self) -> u8 {
42 self as u8
43 }
44
45 pub const fn quantizer(self) -> &'static str {
46 match self {
47 Self::One => ONE_BIT_PROJECTION_QUANTIZER,
48 Self::Four => PROJECTION_QUANTIZER,
49 }
50 }
51
52 pub(crate) const fn sign_code_bytes(self, dimension: usize) -> usize {
53 let _ = self;
54 dimension.div_ceil(u8::BITS as usize)
55 }
56
57 pub(crate) const fn refinement_bits(self) -> usize {
58 self.bits() as usize - 1
59 }
60
61 pub(crate) const fn refinement_code_bytes(self, dimension: usize) -> usize {
62 dimension
63 .saturating_mul(self.refinement_bits())
64 .div_ceil(u8::BITS as usize)
65 }
66
67 pub(crate) fn from_bits(bits: u8) -> Result<Self> {
68 match bits {
69 1 => Ok(Self::One),
70 4 => Ok(Self::Four),
71 _ => Err(ProjectionError::CorruptArtifact(format!(
72 "unsupported RaBitQ bit width {bits}"
73 ))),
74 }
75 }
76}
77
78pub(crate) fn encoded_vector_bytes(dimension: usize, bit_width: RaBitQBitWidth) -> usize {
79 bit_width
80 .sign_code_bytes(dimension)
81 .saturating_add(bit_width.refinement_code_bytes(dimension))
82}
83
84#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum ProjectionMetric {
88 #[default]
89 Cosine,
90 SquaredL2,
91}
92
93impl From<hawdb_core::VectorDistance> for ProjectionMetric {
94 fn from(metric: hawdb_core::VectorDistance) -> Self {
95 match metric {
96 hawdb_core::VectorDistance::Cosine => Self::Cosine,
97 hawdb_core::VectorDistance::Euclidean => Self::SquaredL2,
98 }
99 }
100}
101
102impl From<ProjectionMetric> for hawdb_core::VectorDistance {
103 fn from(metric: ProjectionMetric) -> Self {
104 match metric {
105 ProjectionMetric::Cosine => Self::Cosine,
106 ProjectionMetric::SquaredL2 => Self::Euclidean,
107 }
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112pub struct ProjectionIdentity {
113 pub generation: u64,
114 pub source_epoch: Option<u64>,
115 pub embedding_model: Option<String>,
116 pub embedding_version: Option<String>,
117}
118
119impl ProjectionIdentity {
120 pub fn new(generation: u64) -> Self {
121 Self {
122 generation,
123 source_epoch: None,
124 embedding_model: None,
125 embedding_version: None,
126 }
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct ProjectionBuildConfig {
132 pub dimension: usize,
133 pub bit_width: RaBitQBitWidth,
134 pub metric: ProjectionMetric,
135 pub segment_rows: usize,
136 pub max_working_bytes: usize,
137 pub transform_seed: u64,
138 pub identity: ProjectionIdentity,
139}
140
141impl ProjectionBuildConfig {
142 pub fn new(dimension: usize, identity: ProjectionIdentity) -> Self {
143 Self {
144 dimension,
145 bit_width: RaBitQBitWidth::default(),
146 metric: ProjectionMetric::Cosine,
147 segment_rows: DEFAULT_SEGMENT_ROWS,
148 max_working_bytes: DEFAULT_BUILD_MEMORY_BYTES,
149 transform_seed: DEFAULT_TRANSFORM_SEED,
150 identity,
151 }
152 }
153
154 pub fn with_metric(mut self, metric: ProjectionMetric) -> Self {
155 self.metric = metric;
156 self
157 }
158
159 pub fn with_segment_rows(mut self, segment_rows: usize) -> Self {
160 self.segment_rows = segment_rows;
161 self
162 }
163
164 pub fn with_bit_width(mut self, bit_width: RaBitQBitWidth) -> Self {
165 self.bit_width = bit_width;
166 self
167 }
168
169 pub fn with_max_working_bytes(mut self, max_working_bytes: usize) -> Self {
170 self.max_working_bytes = max_working_bytes;
171 self
172 }
173
174 pub fn with_transform_seed(mut self, transform_seed: u64) -> Self {
175 self.transform_seed = transform_seed;
176 self
177 }
178
179 pub fn resource_admission(&self) -> Result<ProjectionBuildAdmission> {
180 let validated = self.validated()?;
181 Ok(ProjectionBuildAdmission {
182 configured_working_bytes: validated.max_working_bytes,
183 peak_working_bytes: validated.peak_working_bytes,
184 quantization_working_bytes: crate::rabitq::scratch_bytes(
185 self.dimension,
186 self.bit_width,
187 ),
188 requested_segment_rows: validated.requested_segment_rows,
189 admitted_segment_rows: validated.admitted_segment_rows,
190 })
191 }
192
193 pub(crate) fn validated(&self) -> Result<ValidatedBuildConfig> {
194 if self.dimension == 0 {
195 return Err(ProjectionError::InvalidConfiguration(
196 "dimension must be greater than zero".to_string(),
197 ));
198 }
199 if self.segment_rows == 0 {
200 return Err(ProjectionError::InvalidConfiguration(
201 "segment_rows must be greater than zero".to_string(),
202 ));
203 }
204 let bytes_per_vector = encoded_vector_bytes(self.dimension, self.bit_width);
205 let row_bytes = std::mem::size_of::<u64>()
206 .saturating_add(2 * std::mem::size_of::<f32>())
207 .saturating_add(std::mem::size_of::<f64>())
208 .saturating_add(bytes_per_vector);
209 let scratch_bytes = self
210 .dimension
211 .saturating_mul(std::mem::size_of::<f32>())
212 .saturating_add(bytes_per_vector)
213 .saturating_add(crate::rabitq::scratch_bytes(self.dimension, self.bit_width))
214 .saturating_add(BUILD_FIXED_WORKING_BYTES);
215 let available_for_rows = self.max_working_bytes.saturating_sub(scratch_bytes);
216 let admitted_rows = (available_for_rows / row_bytes).min(self.segment_rows);
217 if admitted_rows == 0 {
218 return Err(ProjectionError::ResourceBudgetExceeded {
219 required: scratch_bytes.saturating_add(row_bytes),
220 available: self.max_working_bytes,
221 });
222 }
223 let peak_working_bytes = scratch_bytes.saturating_add(admitted_rows * row_bytes);
224 Ok(ValidatedBuildConfig {
225 dimension: self.dimension,
226 requested_segment_rows: self.segment_rows,
227 admitted_segment_rows: admitted_rows,
228 max_working_bytes: self.max_working_bytes,
229 peak_working_bytes,
230 bytes_per_vector,
231 bit_width: self.bit_width,
232 metric: self.metric,
233 transform_seed: self.transform_seed,
234 identity: self.identity.clone(),
235 })
236 }
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub struct ProjectionBuildAdmission {
241 pub configured_working_bytes: usize,
242 pub peak_working_bytes: usize,
243 pub quantization_working_bytes: usize,
246 pub requested_segment_rows: usize,
247 pub admitted_segment_rows: usize,
248}
249
250#[derive(Debug, Clone)]
251pub(crate) struct ValidatedBuildConfig {
252 pub dimension: usize,
253 pub bit_width: RaBitQBitWidth,
254 pub metric: ProjectionMetric,
255 pub requested_segment_rows: usize,
256 pub admitted_segment_rows: usize,
257 pub max_working_bytes: usize,
258 pub peak_working_bytes: usize,
259 pub bytes_per_vector: usize,
260 pub transform_seed: u64,
261 pub identity: ProjectionIdentity,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265pub struct SegmentDescriptor {
266 pub index: usize,
267 pub base_ordinal: usize,
268 pub row_count: usize,
269 pub payload_offset: u64,
270 pub payload_bytes: u64,
271 pub payload_checksum: u32,
272}
273
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275pub struct ProjectionManifest {
276 pub protocol: String,
277 pub format_version: u32,
278 pub bit_width: u8,
279 pub algorithm: String,
280 pub metric: ProjectionMetric,
281 pub transform: String,
282 pub quantizer: String,
283 pub calibration: String,
284 pub transform_seed: u64,
285 pub dimension: usize,
286 pub requested_segment_rows: usize,
287 pub admitted_segment_rows: usize,
288 pub configured_build_working_bytes: usize,
289 pub peak_build_working_bytes: usize,
290 pub document_count: usize,
291 pub source_digest: u64,
292 pub payload_bytes: u64,
293 pub payload_checksum: u32,
294 pub identity: ProjectionIdentity,
295 pub segments: Vec<SegmentDescriptor>,
296}
297
298impl ProjectionManifest {
299 pub fn retained_capacity_bytes(&self) -> usize {
301 let strings = [
302 &self.protocol,
303 &self.algorithm,
304 &self.transform,
305 &self.quantizer,
306 &self.calibration,
307 ];
308 strings
309 .iter()
310 .fold(std::mem::size_of::<Self>(), |bytes, value| {
311 bytes.saturating_add(value.capacity())
312 })
313 .saturating_add(
314 self.identity
315 .embedding_model
316 .as_ref()
317 .map_or(0, String::capacity),
318 )
319 .saturating_add(
320 self.identity
321 .embedding_version
322 .as_ref()
323 .map_or(0, String::capacity),
324 )
325 .saturating_add(
326 self.segments
327 .capacity()
328 .saturating_mul(std::mem::size_of::<SegmentDescriptor>()),
329 )
330 }
331
332 pub(crate) fn new(
333 config: &ValidatedBuildConfig,
334 document_count: usize,
335 source_digest: u64,
336 payload_bytes: u64,
337 payload_checksum: u32,
338 segments: Vec<SegmentDescriptor>,
339 ) -> Self {
340 Self {
341 protocol: PROJECTION_PROTOCOL.to_string(),
342 format_version: PROJECTION_FORMAT_VERSION,
343 bit_width: config.bit_width.bits(),
344 algorithm: PROJECTION_ALGORITHM.to_string(),
345 metric: config.metric,
346 transform: PROJECTION_TRANSFORM.to_string(),
347 quantizer: config.bit_width.quantizer().to_string(),
348 calibration: PROJECTION_CALIBRATION.to_string(),
349 transform_seed: config.transform_seed,
350 dimension: config.dimension,
351 requested_segment_rows: config.requested_segment_rows,
352 admitted_segment_rows: config.admitted_segment_rows,
353 configured_build_working_bytes: config.max_working_bytes,
354 peak_build_working_bytes: config.peak_working_bytes,
355 document_count,
356 source_digest,
357 payload_bytes,
358 payload_checksum,
359 identity: config.identity.clone(),
360 segments,
361 }
362 }
363
364 pub(crate) fn validate(&self) -> Result<()> {
365 if self.protocol != PROJECTION_PROTOCOL {
366 return Err(ProjectionError::CorruptArtifact(format!(
367 "unsupported protocol {}",
368 self.protocol
369 )));
370 }
371 if self.format_version != PROJECTION_FORMAT_VERSION {
372 return Err(ProjectionError::CorruptArtifact(format!(
373 "unsupported format version {}; rebuild the development RaBitQ index from raw vectors",
374 self.format_version
375 )));
376 }
377 let bit_width = RaBitQBitWidth::from_bits(self.bit_width)?;
378 if self.algorithm != PROJECTION_ALGORITHM
379 || self.transform != PROJECTION_TRANSFORM
380 || self.quantizer != bit_width.quantizer()
381 || self.calibration != PROJECTION_CALIBRATION
382 {
383 return Err(ProjectionError::CorruptArtifact(
384 "unsupported algorithm, metric, transform, quantizer, or calibration".to_string(),
385 ));
386 }
387 if self.dimension == 0
388 || self.admitted_segment_rows == 0
389 || self.peak_build_working_bytes == 0
390 || self.peak_build_working_bytes > self.configured_build_working_bytes
391 {
392 return Err(ProjectionError::CorruptArtifact(
393 "dimension, segment rows, or build resource admission is invalid".to_string(),
394 ));
395 }
396
397 let mut expected_offset = 0u64;
398 let mut expected_ordinal = 0usize;
399 for (index, segment) in self.segments.iter().enumerate() {
400 if segment.index != index
401 || segment.base_ordinal != expected_ordinal
402 || segment.payload_offset != expected_offset
403 || segment.row_count == 0
404 || segment.row_count > self.admitted_segment_rows
405 {
406 return Err(ProjectionError::CorruptArtifact(format!(
407 "segment {} has an invalid index, ordinal, offset, or row count",
408 segment.index
409 )));
410 }
411 let expected_bytes =
412 segment_payload_bytes(self.dimension, bit_width, segment.row_count);
413 if segment.payload_bytes != expected_bytes as u64 {
414 return Err(ProjectionError::CorruptArtifact(format!(
415 "segment {} payload length mismatch",
416 segment.index
417 )));
418 }
419 expected_offset = expected_offset.saturating_add(segment.payload_bytes);
420 expected_ordinal = expected_ordinal.saturating_add(segment.row_count);
421 }
422 if expected_offset != self.payload_bytes || expected_ordinal != self.document_count {
423 return Err(ProjectionError::CorruptArtifact(
424 "manifest totals do not match segment descriptors".to_string(),
425 ));
426 }
427 Ok(())
428 }
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct ProjectionBuildReport {
433 pub document_count: usize,
434 pub segment_count: usize,
435 pub raw_vector_bytes: u64,
436 pub projection_payload_bytes: u64,
437 pub configured_working_bytes: usize,
438 pub peak_working_bytes: usize,
439 pub requested_segment_rows: usize,
440 pub admitted_segment_rows: usize,
441}
442
443#[derive(Debug)]
444pub(crate) struct QuantizedSegment {
445 pub base_ordinal: usize,
446 pub ids: Vec<u64>,
447 pub reconstruction_scales: Vec<f32>,
448 pub reconstruction_offsets: Vec<f32>,
449 pub original_norms: Vec<f64>,
450 pub codes: Vec<u8>,
451}
452
453impl QuantizedSegment {
454 pub(crate) fn payload_len(&self) -> usize {
455 self.ids.len() * std::mem::size_of::<u64>()
456 + self.reconstruction_scales.len() * std::mem::size_of::<f32>()
457 + self.reconstruction_offsets.len() * std::mem::size_of::<f32>()
458 + self.original_norms.len() * std::mem::size_of::<f64>()
459 + self.codes.len()
460 }
461
462 pub fn with_capacity(config: &ValidatedBuildConfig, base_ordinal: usize) -> Self {
463 Self {
464 base_ordinal,
465 ids: Vec::with_capacity(config.admitted_segment_rows),
466 reconstruction_scales: Vec::with_capacity(config.admitted_segment_rows),
467 reconstruction_offsets: Vec::with_capacity(config.admitted_segment_rows),
468 original_norms: Vec::with_capacity(config.admitted_segment_rows),
469 codes: Vec::with_capacity(
470 config
471 .admitted_segment_rows
472 .saturating_mul(config.bytes_per_vector),
473 ),
474 }
475 }
476
477 pub fn row_count(&self) -> usize {
478 self.ids.len()
479 }
480
481 pub fn empty(base_ordinal: usize) -> Self {
482 Self {
483 base_ordinal,
484 ids: Vec::new(),
485 reconstruction_scales: Vec::new(),
486 reconstruction_offsets: Vec::new(),
487 original_norms: Vec::new(),
488 codes: Vec::new(),
489 }
490 }
491
492 pub fn is_empty(&self) -> bool {
493 self.ids.is_empty()
494 }
495}
496
497#[derive(Debug)]
498pub struct InMemoryProjection {
499 pub(crate) manifest: ProjectionManifest,
500 pub(crate) segments: Vec<QuantizedSegment>,
501 pub(crate) build_report: ProjectionBuildReport,
502}
503
504impl InMemoryProjection {
505 pub fn retained_capacity_bytes(&self) -> usize {
507 self.segments.iter().fold(
508 self.manifest
509 .retained_capacity_bytes()
510 .saturating_add(std::mem::size_of::<Self>())
511 .saturating_add(
512 self.segments
513 .capacity()
514 .saturating_mul(std::mem::size_of::<QuantizedSegment>()),
515 ),
516 |bytes, segment| {
517 bytes
518 .saturating_add(
519 segment
520 .ids
521 .capacity()
522 .saturating_mul(std::mem::size_of::<u64>()),
523 )
524 .saturating_add(
525 segment
526 .reconstruction_scales
527 .capacity()
528 .saturating_mul(std::mem::size_of::<f32>()),
529 )
530 .saturating_add(
531 segment
532 .reconstruction_offsets
533 .capacity()
534 .saturating_mul(std::mem::size_of::<f32>()),
535 )
536 .saturating_add(
537 segment
538 .original_norms
539 .capacity()
540 .saturating_mul(std::mem::size_of::<f64>()),
541 )
542 .saturating_add(segment.codes.capacity())
543 },
544 )
545 }
546
547 pub fn manifest(&self) -> &ProjectionManifest {
548 &self.manifest
549 }
550
551 pub fn build_report(&self) -> &ProjectionBuildReport {
552 &self.build_report
553 }
554}
555
556pub(crate) fn segment_payload_bytes(
557 dimension: usize,
558 bit_width: RaBitQBitWidth,
559 rows: usize,
560) -> usize {
561 rows.saturating_mul(
562 std::mem::size_of::<u64>()
563 .saturating_add(2 * std::mem::size_of::<f32>())
564 .saturating_add(std::mem::size_of::<f64>())
565 .saturating_add(encoded_vector_bytes(dimension, bit_width)),
566 )
567}
568
569pub(crate) fn ids_bytes(rows: usize) -> usize {
570 rows.saturating_mul(std::mem::size_of::<u64>())
571}
572
573pub(crate) fn reconstruction_factor_bytes(rows: usize) -> usize {
574 rows.saturating_mul(std::mem::size_of::<f32>())
575}
576
577#[cfg(test)]
578mod tests {
579 use super::*;
580
581 #[test]
582 fn default_bit_width_favors_recall_over_faiss_standard_rabitq() {
583 assert_eq!(DEFAULT_PROJECTION_BIT_WIDTH, 4);
584 assert_eq!(RaBitQBitWidth::default(), RaBitQBitWidth::Four);
585 assert_eq!(RaBitQBitWidth::default().quantizer(), PROJECTION_QUANTIZER);
586 }
587}