diskann_disk/search/pq/
pq_scratch.rs1use diskann::{ANNError, ANNResult};
8
9use diskann_quantization::alloc::{AlignedAllocator, Poly};
10
11#[derive(Debug)]
12pub struct PQScratch {
14 pub aligned_pqtable_dist_scratch: Poly<[f32], AlignedAllocator>,
17
18 pub aligned_dist_scratch: Poly<[f32], AlignedAllocator>,
21
22 pub aligned_pq_coord_scratch: Poly<[u8], AlignedAllocator>,
25
26 pub query_scratch: Vec<f32>,
30}
31
32impl PQScratch {
33 pub fn new(
38 graph_degree: usize,
39 dim: usize,
40 num_pq_chunks: usize,
41 num_centers: usize,
42 ) -> ANNResult<Self> {
43 let aligned_pq_coord_scratch =
44 Poly::broadcast(0u8, graph_degree * num_pq_chunks, AlignedAllocator::A128)
45 .map_err(ANNError::log_index_error)?;
46 let aligned_pqtable_dist_scratch =
47 Poly::broadcast(0f32, num_centers * num_pq_chunks, AlignedAllocator::A128)
48 .map_err(ANNError::log_index_error)?;
49 let aligned_dist_scratch = Poly::broadcast(0f32, graph_degree, AlignedAllocator::A128)
50 .map_err(ANNError::log_index_error)?;
51 let query_scratch = vec![0.0f32; dim];
52
53 Ok(Self {
54 aligned_pqtable_dist_scratch,
55 aligned_dist_scratch,
56 aligned_pq_coord_scratch,
57 query_scratch,
58 })
59 }
60
61 pub fn set(&mut self, query: &[f32]) -> ANNResult<()> {
71 let dim = self.query_scratch.len();
72 if query.len() < dim {
73 return Err(ANNError::log_dimension_mismatch_error(format!(
74 "PQScratch::set: expected query of length >= {dim}, got {}",
75 query.len()
76 )));
77 }
78 self.query_scratch.copy_from_slice(&query[..dim]);
79 Ok(())
80 }
81
82 pub(crate) fn max_vectors(&self) -> usize {
85 self.aligned_dist_scratch.len()
86 }
87}
88
89#[cfg(test)]
90mod tests {
91 use diskann_quantization::num::PowerOfTwo;
92 use rstest::rstest;
93
94 use super::PQScratch;
95
96 #[rstest]
97 #[case(512, 8, 128, 256)] #[case(59, 16, 37, 41)] fn test_pq_scratch(
100 #[case] graph_degree: usize,
101 #[case] dim: usize,
102 #[case] num_pq_chunks: usize,
103 #[case] num_centers: usize,
104 ) {
105 let mut pq_scratch: PQScratch =
106 PQScratch::new(graph_degree, dim, num_pq_chunks, num_centers).unwrap();
107
108 assert_eq!(
109 (pq_scratch.aligned_pqtable_dist_scratch.as_ptr() as usize) % PowerOfTwo::V128.raw(),
110 0
111 );
112 assert_eq!(
113 (pq_scratch.aligned_dist_scratch.as_ptr() as usize) % PowerOfTwo::V128.raw(),
114 0
115 );
116 assert_eq!(
117 (pq_scratch.aligned_pq_coord_scratch.as_ptr() as usize) % PowerOfTwo::V128.raw(),
118 0
119 );
120
121 assert_eq!(pq_scratch.max_vectors(), graph_degree);
122
123 let query: Vec<f32> = (1..=dim).map(|i| i as f32).collect();
125 pq_scratch.set(&query).unwrap();
126
127 (0..query.len()).for_each(|i| {
128 assert_eq!(pq_scratch.query_scratch[i], query[i]);
129 });
130 }
131}