(
&self,
vector: &[f32],
storage_type: StorageType,
range: (f32, f32),
)
| 8 | |
| 9 | impl Quantization for ScalarQuantization { |
| 10 | fn quantize( |
| 11 | &self, |
| 12 | vector: &[f32], |
| 13 | storage_type: StorageType, |
| 14 | range: (f32, f32), |
| 15 | ) -> Result<Storage, QuantizationError> { |
| 16 | match storage_type { |
| 17 | StorageType::UnsignedByte => { |
| 18 | let quant_vec: Vec<u8> = vector |
| 19 | .iter() |
| 20 | .map(|&x| { |
| 21 | (((x.max(range.0).min(range.1) - range.0) / (range.1 - range.0)) * 255.0) |
| 22 | as u8 |
| 23 | }) |
| 24 | .collect(); |
| 25 | let mag = |
| 26 | (quant_vec.iter().map(|&x| x as u32 * x as u32).sum::<u32>() as f32).sqrt(); |
| 27 | Ok(Storage::UnsignedByte { mag, quant_vec }) |
| 28 | } |
| 29 | StorageType::SubByte(resolution) => { |
| 30 | let quant_vec: Vec<_> = quantize_to_u8_bits(vector, resolution); |
| 31 | let mag_sqr: f32 = vector.iter().map(|x| x * x).sum(); |
| 32 | let mag = mag_sqr.sqrt(); |
| 33 | Ok(Storage::SubByte { |
| 34 | mag, |
| 35 | quant_vec, |
| 36 | resolution, |
| 37 | }) |
| 38 | } |
| 39 | StorageType::HalfPrecisionFP => { |
| 40 | let quant_vec = vector.iter().map(|&x| f16::from_f32(x)).collect(); |
| 41 | let mag = vector.iter().map(|&x| x * x).sum::<f32>().sqrt(); |
| 42 | Ok(Storage::HalfPrecisionFP { mag, quant_vec }) |
| 43 | } |
| 44 | StorageType::FullPrecisionFP => { |
| 45 | let mag = vector.iter().map(|x| x * x).sum::<f32>().sqrt(); |
| 46 | Ok(Storage::FullPrecisionFP { |
| 47 | mag, |
| 48 | vec: vector.to_vec(), |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn train(&mut self, _vectors: &[&[f32]]) -> Result<(), QuantizationError> { |
| 55 | // Scalar quantization doesn't require training |
nothing calls this directly
no test coverage detected