lance-index 4.0.1

Lance indices implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! Product Quantization
//!

use std::sync::Arc;

use arrow::datatypes::{self, ArrowPrimitiveType};
use arrow_array::{Array, FixedSizeListArray, UInt8Array, cast::AsArray};
use arrow_array::{ArrayRef, Float32Array, PrimitiveArray};
use arrow_schema::{DataType, Field};
use deepsize::DeepSizeOf;
use distance::build_distance_table_dot;
use lance_arrow::*;
use lance_core::{Error, Result, assume_eq};
use lance_linalg::distance::{DistanceType, Dot, L2, l2::L2Prepared};
use lance_table::utils::LanceIteratorExtension;
use num_traits::Float;
use prost::Message;
use storage::{PQ_METADATA_KEY, ProductQuantizationMetadata, ProductQuantizationStorage};
use tracing::instrument;

pub mod builder;
pub mod distance;
pub mod storage;
pub mod transform;
pub(crate) mod utils;

use self::distance::{
    build_distance_table_l2, build_distance_table_l2_prepared, compute_pq_distance,
};
pub use self::utils::num_centroids;
use super::quantizer::{
    Quantization, QuantizationMetadata, QuantizationType, Quantizer, QuantizerBuildParams,
};
use super::{PQ_CODE_COLUMN, pb};
use crate::vector::kmeans::compute_partition;
pub use builder::PQBuildParams;
use utils::get_sub_vector_centroids;

#[derive(Debug, Clone)]
pub struct ProductQuantizer {
    pub num_sub_vectors: usize,
    pub num_bits: u32,
    pub dimension: usize,
    pub codebook: FixedSizeListArray,
    pub distance_type: DistanceType,
    /// Pre-transposed L2 targets per sub-vector for fast f32 L2 batch computation.
    /// Only populated when codebook is f32 and distance_type is L2
    /// (Cosine is converted to L2 before construction, so it benefits too).
    l2_targets: Option<Vec<L2Prepared>>,
}

impl DeepSizeOf for ProductQuantizer {
    fn deep_size_of_children(&self, _context: &mut deepsize::Context) -> usize {
        self.codebook.get_array_memory_size()
            + self.num_sub_vectors.deep_size_of_children(_context)
            + self.num_bits.deep_size_of_children(_context)
            + self.dimension.deep_size_of_children(_context)
            + self.distance_type.deep_size_of_children(_context)
            + self
                .l2_targets
                .as_ref()
                .map_or(0, |v| v.iter().map(|t| t.size_bytes()).sum())
    }
}

impl ProductQuantizer {
    /// Build per-sub-vector L2Prepared from the codebook if applicable (f32 + L2).
    fn build_l2_targets(
        codebook: &FixedSizeListArray,
        distance_type: DistanceType,
        num_sub_vectors: usize,
        num_bits: u32,
        dimension: usize,
    ) -> Option<Vec<L2Prepared>> {
        if codebook.value_type() != DataType::Float32 || distance_type != DistanceType::L2 {
            return None;
        }
        let values = codebook
            .values()
            .as_primitive::<datatypes::Float32Type>()
            .values();
        let sub_dim = dimension / num_sub_vectors;
        let num_centroids = 2_usize.pow(num_bits);
        let block_size = sub_dim * num_centroids;

        let targets = (0..num_sub_vectors)
            .map(|sub_idx| {
                let block_start = sub_idx * block_size;
                let block = &values[block_start..block_start + block_size];
                L2Prepared::new(block, sub_dim)
            })
            .collect();
        Some(targets)
    }

    pub fn new(
        num_sub_vectors: usize,
        num_bits: u32,
        dimension: usize,
        codebook: FixedSizeListArray,
        distance_type: DistanceType,
    ) -> Self {
        let l2_targets = Self::build_l2_targets(
            &codebook,
            distance_type,
            num_sub_vectors,
            num_bits,
            dimension,
        );
        Self {
            num_bits,
            num_sub_vectors,
            dimension,
            codebook,
            distance_type,
            l2_targets,
        }
    }

    pub fn from_proto(proto: &pb::Pq, distance_type: DistanceType) -> Result<Self> {
        let distance_type = match distance_type {
            DistanceType::Cosine => DistanceType::L2,
            _ => distance_type,
        };
        let codebook = match proto.codebook_tensor.as_ref() {
            Some(tensor) => FixedSizeListArray::try_from(tensor)?,
            None => FixedSizeListArray::try_new_from_values(
                Float32Array::from(proto.codebook.clone()),
                proto.dimension as i32,
            )?,
        };
        Ok(Self::new(
            proto.num_sub_vectors as usize,
            proto.num_bits,
            proto.dimension as usize,
            codebook,
            distance_type,
        ))
    }

    #[instrument(name = "ProductQuantizer::transform", level = "debug", skip_all)]
    fn transform<T: ArrowPrimitiveType>(&self, vectors: &dyn Array) -> Result<ArrayRef>
    where
        T::Native: Float + L2 + Dot,
    {
        match self.num_bits {
            4 => self.transform_impl::<4, T>(vectors),
            8 => self.transform_impl::<8, T>(vectors),
            _ => Err(Error::index(format!(
                "ProductQuantization: num_bits {} not supported",
                self.num_bits
            ))),
        }
    }

    fn transform_impl<const NUM_BITS: u32, T: ArrowPrimitiveType>(
        &self,
        vectors: &dyn Array,
    ) -> Result<ArrayRef>
    where
        T::Native: Float + L2 + Dot,
    {
        let fsl = vectors
            .as_fixed_size_list_opt()
            .ok_or(Error::index(format!(
                "Expect to be a FixedSizeList<float> vector array, got: {:?} array",
                vectors.data_type()
            )))?;
        let num_sub_vectors = self.num_sub_vectors;
        let dim = self.dimension;
        if NUM_BITS == 4 && !num_sub_vectors.is_multiple_of(2) {
            return Err(Error::index(format!(
                "PQ: num_sub_vectors must be divisible by 2 for num_bits=4, but got {}",
                num_sub_vectors,
            )));
        }
        let codebook = self.codebook.values().as_primitive::<T>();

        let distance_type = self.distance_type;

        let flatten_data = fsl.values().as_primitive::<T>();
        let sub_dim = dim / num_sub_vectors;
        let num_centroids = 2_usize.pow(NUM_BITS);
        let total_code_length = fsl.len() * num_sub_vectors / (8 / NUM_BITS as usize);

        let values = if let Some(targets) = &self.l2_targets {
            // Fast path for f32 + L2: use pre-transposed codebook.
            // SAFETY: l2_targets is only populated when T::Native is f32.
            let flat_f32: &[f32] = unsafe {
                std::slice::from_raw_parts(
                    flatten_data.values().as_ptr() as *const f32,
                    flatten_data.values().len(),
                )
            };
            let mut values = vec![0u8; total_code_length];
            let bytes_per_vector = num_sub_vectors / (8 / NUM_BITS as usize);
            let mut dist_buf = vec![0.0f32; num_centroids];
            for (vec_idx, vector) in flat_f32.chunks_exact(dim).enumerate() {
                let out = &mut values[vec_idx * bytes_per_vector..][..bytes_per_vector];
                if NUM_BITS == 4 {
                    for (pair_idx, pair) in vector.chunks_exact(sub_dim * 2).enumerate() {
                        let lo = targets[pair_idx * 2]
                            .nearest_into(&pair[..sub_dim], &mut dist_buf)
                            .unwrap_or(0) as u8;
                        let hi = targets[pair_idx * 2 + 1]
                            .nearest_into(&pair[sub_dim..], &mut dist_buf)
                            .unwrap_or(0) as u8;
                        out[pair_idx] = (hi << 4) | lo;
                    }
                } else {
                    for (sub_idx, sv) in vector.chunks_exact(sub_dim).enumerate() {
                        out[sub_idx] = targets[sub_idx]
                            .nearest_into(sv, &mut dist_buf)
                            .unwrap_or(0) as u8;
                    }
                }
            }
            values
        } else {
            flatten_data
                .values()
                .chunks_exact(dim)
                .flat_map(|vector| {
                    let sub_vec_code: Vec<u8> = vector
                        .chunks_exact(sub_dim)
                        .enumerate()
                        .map(|(sub_idx, sub_vector)| {
                            let centroids = get_sub_vector_centroids::<NUM_BITS, _>(
                                codebook.values(),
                                dim,
                                num_sub_vectors,
                                sub_idx,
                            );
                            assume_eq!(centroids.len(), num_centroids * sub_dim);
                            compute_partition(centroids, sub_vector, distance_type).unwrap_or(0)
                                as u8
                        })
                        .collect();
                    if NUM_BITS == 4 {
                        sub_vec_code
                            .chunks_exact(2)
                            .map(|v| (v[1] << 4) | v[0])
                            .collect::<Vec<_>>()
                    } else {
                        sub_vec_code
                    }
                })
                .exact_size(total_code_length)
                .collect::<Vec<_>>()
        };

        let num_sub_vectors_in_byte = if NUM_BITS == 4 {
            num_sub_vectors / 2
        } else {
            num_sub_vectors
        };

        debug_assert_eq!(values.len(), fsl.len() * num_sub_vectors_in_byte);
        Ok(Arc::new(FixedSizeListArray::try_new_from_values(
            UInt8Array::from(values),
            num_sub_vectors_in_byte as i32,
        )?))
    }

    // the code must be transposed
    pub fn compute_distances(&self, query: &dyn Array, code: &UInt8Array) -> Result<Float32Array> {
        if code.is_empty() {
            return Ok(Float32Array::from(Vec::<f32>::new()));
        }

        match self.distance_type {
            DistanceType::L2 => self.l2_distances(query, code),
            DistanceType::Cosine => {
                // it seems we implemented cosine distance at some version,
                // but from now on, we should use normalized L2 distance.
                debug_assert!(
                    false,
                    "cosine distance should be converted to normalized L2 distance"
                );
                // L2 over normalized vectors:  ||x - y|| = x^2 + y^2 - 2 * xy = 1 + 1 - 2 * xy = 2 * (1 - xy)
                // Cosine distance: 1 - |xy| / (||x|| * ||y||) = 1 - xy / (x^2 * y^2) = 1 - xy / (1 * 1) = 1 - xy
                // Therefore, Cosine = L2 / 2
                let l2_dists = self.l2_distances(query, code)?;
                Ok(l2_dists.values().iter().map(|v| *v / 2.0).collect())
            }
            DistanceType::Dot => self.dot_distances(query, code),
            _ => panic!(
                "ProductQuantization: distance type {} not supported",
                self.distance_type
            ),
        }
    }

    /// Pre-compute L2 distance from the query to all code.
    ///
    /// It returns the squared L2 distance.
    fn l2_distances(&self, key: &dyn Array, code: &UInt8Array) -> Result<Float32Array> {
        let distance_table = self.build_l2_distance_table(key)?;
        Ok(self.compute_l2_distance(&distance_table, code.values()))
    }

    /// Parameters
    /// ----------
    ///  - query: the query vector, with shape (dimension, )
    ///  - code: the PQ code in one partition.
    ///
    fn dot_distances(&self, key: &dyn Array, code: &UInt8Array) -> Result<Float32Array> {
        match key.data_type() {
            DataType::Float16 => {
                self.dot_distances_impl::<datatypes::Float16Type>(key.as_primitive(), code)
            }
            DataType::Float32 => {
                self.dot_distances_impl::<datatypes::Float32Type>(key.as_primitive(), code)
            }
            DataType::Float64 => {
                self.dot_distances_impl::<datatypes::Float64Type>(key.as_primitive(), code)
            }
            _ => Err(Error::index(format!(
                "unsupported data type: {}",
                key.data_type()
            ))),
        }
    }

    fn dot_distances_impl<T: ArrowPrimitiveType>(
        &self,
        key: &PrimitiveArray<T>,
        code: &UInt8Array,
    ) -> Result<Float32Array>
    where
        T::Native: Dot,
    {
        let distance_table = build_distance_table_dot(
            self.codebook.values().as_primitive::<T>().values(),
            self.num_bits,
            self.num_sub_vectors,
            key.values(),
        );

        let distances = compute_pq_distance(
            &distance_table,
            self.num_bits,
            self.num_sub_vectors,
            code.values(),
            0,
        );

        let diff = self.num_sub_vectors as f32 - 1.0;
        let distances = distances.into_iter().map(|d| d - diff).collect::<Vec<_>>();
        Ok(distances.into())
    }

    fn build_l2_distance_table(&self, key: &dyn Array) -> Result<Vec<f32>> {
        match key.data_type() {
            DataType::Float16 => {
                Ok(self.build_l2_distance_table_impl::<datatypes::Float16Type>(key.as_primitive()))
            }
            DataType::Float32 => {
                if let Some(targets) = &self.l2_targets {
                    let query = key.as_primitive::<datatypes::Float32Type>().values();
                    Ok(build_distance_table_l2_prepared(targets, query))
                } else {
                    Ok(self
                        .build_l2_distance_table_impl::<datatypes::Float32Type>(key.as_primitive()))
                }
            }
            DataType::Float64 => {
                Ok(self.build_l2_distance_table_impl::<datatypes::Float64Type>(key.as_primitive()))
            }
            _ => Err(Error::index(format!(
                "unsupported data type: {}",
                key.data_type()
            ))),
        }
    }

    fn build_l2_distance_table_impl<T: ArrowPrimitiveType>(
        &self,
        key: &PrimitiveArray<T>,
    ) -> Vec<f32>
    where
        T::Native: L2,
    {
        build_distance_table_l2(
            self.codebook.values().as_primitive::<T>().values(),
            self.num_bits,
            self.num_sub_vectors,
            key.values(),
        )
    }

    /// Compute L2 distance from the query to all code.
    ///
    /// Type parameters
    /// ---------------
    /// - C: the tile size of code-book to run at once.
    /// - V: the tile size of PQ code to run at once.
    ///
    /// Parameters
    /// ----------
    /// - distance_table: the pre-computed L2 distance table.
    ///   It is a flatten array of [num_sub_vectors, num_centroids] f32.
    /// - code: the PQ code to be used to compute the distances.
    ///
    /// Returns
    /// -------
    ///  The squared L2 distance.
    #[inline]
    fn compute_l2_distance(&self, distance_table: &[f32], code: &[u8]) -> Float32Array {
        Float32Array::from(compute_pq_distance(
            distance_table,
            self.num_bits,
            self.num_sub_vectors,
            code,
            100,
        ))
    }

    /// Get the centroids for one sub-vector.
    ///
    /// Returns a flatten `num_centroids * sub_vector_width` f32 array.
    pub fn centroids<T: ArrowPrimitiveType>(&self, sub_vector_idx: usize) -> &[T::Native] {
        match self.num_bits {
            4 => get_sub_vector_centroids::<4, _>(
                self.codebook.values().as_primitive::<T>().values(),
                self.dimension,
                self.num_sub_vectors,
                sub_vector_idx,
            ),
            8 => get_sub_vector_centroids::<8, _>(
                self.codebook.values().as_primitive::<T>().values(),
                self.dimension,
                self.num_sub_vectors,
                sub_vector_idx,
            ),
            _ => panic!(
                "ProductQuantization: num_bits {} not supported",
                self.num_bits
            ),
        }
    }
}

impl Quantization for ProductQuantizer {
    type BuildParams = PQBuildParams;
    type Metadata = ProductQuantizationMetadata;
    type Storage = ProductQuantizationStorage;

    fn build(
        data: &dyn Array,
        distance_type: DistanceType,
        params: &Self::BuildParams,
    ) -> Result<Self> {
        assert_eq!(data.null_count(), 0);
        let fsl = data.as_fixed_size_list_opt().ok_or(Error::index(format!(
            "PQ builder: input is not a FixedSizeList: {}",
            data.data_type()
        )))?;

        if let Some(codebook) = params.codebook.as_ref() {
            return Ok(Self::new(
                params.num_sub_vectors,
                params.num_bits as u32,
                fsl.value_length() as usize,
                FixedSizeListArray::try_new_from_values(codebook.clone(), fsl.value_length())?,
                distance_type,
            ));
        }

        params.build(data, distance_type)
    }

    fn retrain(&mut self, data: &dyn Array) -> Result<()> {
        assert_eq!(data.null_count(), 0);
        let params = PQBuildParams::with_codebook(
            self.num_sub_vectors,
            self.num_bits as usize,
            Arc::new(self.codebook.clone()),
        );

        *self = params.build(data, self.distance_type)?;
        Ok(())
    }

    fn code_dim(&self) -> usize {
        self.num_sub_vectors
    }

    fn column(&self) -> &'static str {
        PQ_CODE_COLUMN
    }

    fn use_residual(distance_type: DistanceType) -> bool {
        PQBuildParams::use_residual(distance_type)
    }

    fn quantize(&self, vectors: &dyn Array) -> Result<ArrayRef> {
        let fsl = vectors
            .as_fixed_size_list_opt()
            .ok_or(Error::index(format!(
                "Expect to be a FixedSizeList<float> vector array, got: {:?} array",
                vectors.data_type()
            )))?;

        match fsl.value_type() {
            DataType::Float16 => self.transform::<datatypes::Float16Type>(vectors),
            DataType::Float32 => self.transform::<datatypes::Float32Type>(vectors),
            DataType::Float64 => self.transform::<datatypes::Float64Type>(vectors),
            _ => Err(Error::index(format!(
                "unsupported data type: {}",
                fsl.value_type()
            ))),
        }
    }

    fn metadata_key() -> &'static str {
        PQ_METADATA_KEY
    }

    fn quantization_type() -> QuantizationType {
        QuantizationType::Product
    }

    fn metadata(&self, args: Option<QuantizationMetadata>) -> Self::Metadata {
        let codebook_position = match &args {
            Some(args) => args.codebook_position,
            None => Some(0),
        };

        let codebook_position = codebook_position.expect("codebook position should be set");
        ProductQuantizationMetadata {
            codebook_position,
            nbits: self.num_bits,
            num_sub_vectors: self.num_sub_vectors,
            dimension: self.dimension,
            codebook: Some(self.codebook.clone()),
            codebook_tensor: Vec::new(),
            transposed: args.map(|args| args.transposed).unwrap_or_default(),
        }
    }

    fn from_metadata(metadata: &Self::Metadata, distance_type: DistanceType) -> Result<Quantizer> {
        let distance_type = match distance_type {
            DistanceType::Cosine => DistanceType::L2,
            _ => distance_type,
        };
        let codebook = match metadata.codebook.as_ref() {
            Some(fsl) => fsl.clone(),
            None => {
                let tensor = pb::Tensor::decode(metadata.codebook_tensor.as_ref())?;
                FixedSizeListArray::try_from(&tensor)?
            }
        };
        Ok(Quantizer::Product(Self::new(
            metadata.num_sub_vectors,
            metadata.nbits,
            metadata.dimension,
            codebook,
            distance_type,
        )))
    }

    fn field(&self) -> Field {
        let num_bytes_per_sub_vector = self.num_sub_vectors * self.num_bits as usize / 8;
        Field::new(
            PQ_CODE_COLUMN,
            DataType::FixedSizeList(
                Arc::new(Field::new("item", DataType::UInt8, true)),
                num_bytes_per_sub_vector as i32,
            ),
            true,
        )
    }
}

impl TryFrom<&ProductQuantizer> for pb::Pq {
    type Error = Error;

    fn try_from(pq: &ProductQuantizer) -> Result<Self> {
        let tensor = pb::Tensor::try_from(&pq.codebook)?;
        Ok(Self {
            num_bits: pq.num_bits,
            num_sub_vectors: pq.num_sub_vectors as u32,
            dimension: pq.dimension as u32,
            codebook: vec![],
            codebook_tensor: Some(tensor),
        })
    }
}

impl TryFrom<Quantizer> for ProductQuantizer {
    type Error = Error;
    fn try_from(value: Quantizer) -> Result<Self> {
        match value {
            Quantizer::Product(pq) => Ok(pq),
            _ => Err(Error::index("Expect to be a ProductQuantizer".to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::iter::repeat_n;

    use approx::assert_relative_eq;
    use arrow::datatypes::UInt8Type;
    use arrow_array::Float16Array;
    use half::f16;
    use lance_linalg::distance::l2_distance_batch;
    use lance_linalg::kernels::argmin;
    use lance_testing::datagen::generate_random_array;
    use num_traits::Zero;
    use storage::transpose;

    #[test]
    fn test_f16_pq_to_protobuf() {
        let pq = ProductQuantizer::new(
            4,
            8,
            16,
            FixedSizeListArray::try_new_from_values(
                Float16Array::from_iter_values(repeat_n(f16::zero(), 256 * 16)),
                16,
            )
            .unwrap(),
            DistanceType::L2,
        );
        let proto: pb::Pq = pb::Pq::try_from(&pq).unwrap();
        assert_eq!(proto.num_bits, 8);
        assert_eq!(proto.num_sub_vectors, 4);
        assert_eq!(proto.dimension, 16);
        assert!(proto.codebook.is_empty());
        assert!(proto.codebook_tensor.is_some());

        let tensor = proto.codebook_tensor.as_ref().unwrap();
        assert_eq!(tensor.data_type, pb::tensor::DataType::Float16 as i32);
        assert_eq!(tensor.shape, vec![256, 16]);
    }

    #[test]
    fn test_l2_distance() {
        const DIM: usize = 512;
        const TOTAL: usize = 66; // 64 + 2 to make sure reminder is handled correctly.
        let codebook = generate_random_array(256 * DIM);
        let pq = ProductQuantizer::new(
            16,
            8,
            DIM,
            FixedSizeListArray::try_new_from_values(codebook, DIM as i32).unwrap(),
            DistanceType::L2,
        );
        let pq_code = UInt8Array::from_iter_values((0..16 * TOTAL).map(|v| v as u8));
        let query = generate_random_array(DIM);

        let transposed_pq_codes = transpose(&pq_code, TOTAL, 16);
        let dists = pq.compute_distances(&query, &transposed_pq_codes).unwrap();

        let sub_vec_len = DIM / 16;
        let expected = pq_code
            .values()
            .chunks(16)
            .map(|code| {
                code.iter()
                    .enumerate()
                    .flat_map(|(sub_idx, c)| {
                        let subvec_centroids = pq.centroids::<datatypes::Float32Type>(sub_idx);
                        let subvec =
                            &query.values()[sub_idx * sub_vec_len..(sub_idx + 1) * sub_vec_len];
                        l2_distance_batch(
                            subvec,
                            &subvec_centroids
                                [*c as usize * sub_vec_len..(*c as usize + 1) * sub_vec_len],
                            sub_vec_len,
                        )
                    })
                    .sum::<f32>()
            })
            .collect::<Vec<_>>();
        dists
            .values()
            .iter()
            .zip(expected.iter())
            .for_each(|(v, e)| {
                assert_relative_eq!(*v, *e, epsilon = 1e-4);
            });
    }

    #[test]
    fn test_pq_transform() {
        const DIM: usize = 16;
        const TOTAL: usize = 64;
        let codebook = generate_random_array(DIM * 256);
        let pq = ProductQuantizer::new(
            4,
            8,
            DIM,
            FixedSizeListArray::try_new_from_values(codebook, DIM as i32).unwrap(),
            DistanceType::L2,
        );

        let vectors = generate_random_array(DIM * TOTAL);
        let fsl = FixedSizeListArray::try_new_from_values(vectors.clone(), DIM as i32).unwrap();
        let pq_code = pq.quantize(&fsl).unwrap();

        let mut expected = Vec::with_capacity(TOTAL * 4);
        vectors.values().chunks_exact(DIM).for_each(|vec| {
            vec.chunks_exact(DIM / 4)
                .enumerate()
                .for_each(|(sub_idx, sub_vec)| {
                    let centroids = pq.centroids::<datatypes::Float32Type>(sub_idx);
                    let dists = l2_distance_batch(sub_vec, centroids, DIM / 4);
                    let code = argmin(dists).unwrap() as u8;
                    expected.push(code);
                });
        });

        assert_eq!(pq_code.len(), TOTAL);
        assert_eq!(
            &expected,
            pq_code
                .as_fixed_size_list()
                .values()
                .as_primitive::<UInt8Type>()
                .values()
        );
    }
}