Skip to main content

numcodecs_linear_quantize/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-linear-quantize
10//! [crates.io]: https://crates.io/crates/numcodecs-linear-quantize
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-linear-quantize
13//! [docs.rs]: https://docs.rs/numcodecs-linear-quantize/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_linear_quantize
17//!
18//! Linear Quantization codec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)] // FIXME: twofloat -> hexf -> syn 1.0
21
22use std::{borrow::Cow, fmt};
23
24use ndarray::{Array, Array1, ArrayBase, ArrayD, ArrayViewMutD, Data, Dimension, ShapeError, Zip};
25use num_traits::{ConstOne, ConstZero, Float};
26use numcodecs::{
27    AnyArray, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray, Codec, StaticCodec,
28    StaticCodecConfig, StaticCodecVersion,
29};
30use schemars::{JsonSchema, JsonSchema_repr};
31use serde::{Deserialize, Serialize, de::DeserializeOwned};
32use serde_repr::{Deserialize_repr, Serialize_repr};
33use thiserror::Error;
34use twofloat::TwoFloat;
35
36#[cfg(test)]
37use ::serde_json as _;
38
39type LinearQuantizeCodecVersion = StaticCodecVersion<0, 1, 0>;
40
41#[derive(Clone, Serialize, Deserialize, JsonSchema)]
42#[serde(deny_unknown_fields)]
43/// Lossy codec to reduce the precision of floating point data.
44///
45/// The data is quantized to unsigned integers of the best-fitting type.
46/// The range and shape of the input data is stored in-band.
47pub struct LinearQuantizeCodec {
48    /// Dtype of the decoded data
49    pub dtype: LinearQuantizeDType,
50    /// Binary precision of the encoded data where `$bits = \log_{2}(bins)$`
51    pub bits: LinearQuantizeBins,
52    /// The codec's encoding format version. Do not provide this parameter explicitly.
53    #[serde(default, rename = "_version")]
54    pub version: LinearQuantizeCodecVersion,
55}
56
57/// Data types which the [`LinearQuantizeCodec`] can quantize
58#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema)]
59#[schemars(extend("enum" = ["f32", "float32", "f64", "float64"]))]
60#[schemars(inline)]
61#[expect(missing_docs)]
62pub enum LinearQuantizeDType {
63    #[serde(rename = "f32", alias = "float32")]
64    F32,
65    #[serde(rename = "f64", alias = "float64")]
66    F64,
67}
68
69impl fmt::Display for LinearQuantizeDType {
70    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
71        fmt.write_str(match self {
72            Self::F32 => "f32",
73            Self::F64 => "f64",
74        })
75    }
76}
77
78#[allow(clippy::used_underscore_items)]
79/// Number of bins for quantization, written in base-2 scientific notation.
80///
81/// The binary `#[repr(u8)]` value of each variant is equivalent to the binary
82/// logarithm of the number of bins, i.e. the binary precision or the number of
83/// bits used.
84#[derive(Copy, Clone, Serialize_repr, Deserialize_repr, JsonSchema_repr)]
85#[repr(u8)]
86#[schemars(inline)]
87#[rustfmt::skip]
88#[expect(missing_docs)]
89pub enum LinearQuantizeBins {
90    _1B1 = 1, _1B2, _1B3, _1B4, _1B5, _1B6, _1B7, _1B8,
91    _1B9, _1B10, _1B11, _1B12, _1B13, _1B14, _1B15, _1B16,
92    _1B17, _1B18, _1B19, _1B20, _1B21, _1B22, _1B23, _1B24,
93    _1B25, _1B26, _1B27, _1B28, _1B29, _1B30, _1B31, _1B32,
94    _1B33, _1B34, _1B35, _1B36, _1B37, _1B38, _1B39, _1B40,
95    _1B41, _1B42, _1B43, _1B44, _1B45, _1B46, _1B47, _1B48,
96    _1B49, _1B50, _1B51, _1B52, _1B53, _1B54, _1B55, _1B56,
97    _1B57, _1B58, _1B59, _1B60, _1B61, _1B62, _1B63, _1B64,
98}
99
100impl Codec for LinearQuantizeCodec {
101    type Error = LinearQuantizeCodecError;
102
103    #[expect(clippy::too_many_lines)]
104    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
105        let encoded = match (&data, self.dtype) {
106            (AnyCowArray::F32(data), LinearQuantizeDType::F32) => match self.bits as u8 {
107                bits @ ..=8 => AnyArray::U8(
108                    Array1::from_vec(quantize(data, |x| {
109                        let max = f32::from(u8::MAX >> (8 - bits));
110                        let x = x.mul_add(scale_for_bits::<f32>(bits), 0.5).clamp(0.0, max);
111                        #[expect(unsafe_code)]
112                        // Safety: x is clamped beforehand
113                        unsafe {
114                            x.to_int_unchecked::<u8>()
115                        }
116                    })?)
117                    .into_dyn(),
118                ),
119                bits @ 9..=16 => AnyArray::U16(
120                    Array1::from_vec(quantize(data, |x| {
121                        let max = f32::from(u16::MAX >> (16 - bits));
122                        let x = x.mul_add(scale_for_bits::<f32>(bits), 0.5).clamp(0.0, max);
123                        #[expect(unsafe_code)]
124                        // Safety: x is clamped beforehand
125                        unsafe {
126                            x.to_int_unchecked::<u16>()
127                        }
128                    })?)
129                    .into_dyn(),
130                ),
131                bits @ 17..=32 => AnyArray::U32(
132                    Array1::from_vec(quantize(data, |x| {
133                        // we need to use f64 here to have sufficient precision
134                        let max = f64::from(u32::MAX >> (32 - bits));
135                        let x = f64::from(x)
136                            .mul_add(scale_for_bits::<f64>(bits), 0.5)
137                            .clamp(0.0, max);
138                        #[expect(unsafe_code)]
139                        // Safety: x is clamped beforehand
140                        unsafe {
141                            x.to_int_unchecked::<u32>()
142                        }
143                    })?)
144                    .into_dyn(),
145                ),
146                bits @ 33.. => AnyArray::U64(
147                    Array1::from_vec(quantize(data, |x| {
148                        // we need to use TwoFloat here to have sufficient precision
149                        let max = TwoFloat::from(u64::MAX >> (64 - bits));
150                        let x = (TwoFloat::from(x) * scale_for_bits::<f64>(bits)
151                            + TwoFloat::from(0.5))
152                        .max(TwoFloat::from(0.0))
153                        .min(max);
154                        #[expect(unsafe_code)]
155                        // Safety: x is clamped beforehand
156                        unsafe {
157                            u64::try_from(x).unwrap_unchecked()
158                        }
159                    })?)
160                    .into_dyn(),
161                ),
162            },
163            (AnyCowArray::F64(data), LinearQuantizeDType::F64) => match self.bits as u8 {
164                bits @ ..=8 => AnyArray::U8(
165                    Array1::from_vec(quantize(data, |x| {
166                        let max = f64::from(u8::MAX >> (8 - bits));
167                        let x = x.mul_add(scale_for_bits::<f64>(bits), 0.5).clamp(0.0, max);
168                        #[expect(unsafe_code)]
169                        // Safety: x is clamped beforehand
170                        unsafe {
171                            x.to_int_unchecked::<u8>()
172                        }
173                    })?)
174                    .into_dyn(),
175                ),
176                bits @ 9..=16 => AnyArray::U16(
177                    Array1::from_vec(quantize(data, |x| {
178                        let max = f64::from(u16::MAX >> (16 - bits));
179                        let x = x.mul_add(scale_for_bits::<f64>(bits), 0.5).clamp(0.0, max);
180                        #[expect(unsafe_code)]
181                        // Safety: x is clamped beforehand
182                        unsafe {
183                            x.to_int_unchecked::<u16>()
184                        }
185                    })?)
186                    .into_dyn(),
187                ),
188                bits @ 17..=32 => AnyArray::U32(
189                    Array1::from_vec(quantize(data, |x| {
190                        let max = f64::from(u32::MAX >> (32 - bits));
191                        let x = x.mul_add(scale_for_bits::<f64>(bits), 0.5).clamp(0.0, max);
192                        #[expect(unsafe_code)]
193                        // Safety: x is clamped beforehand
194                        unsafe {
195                            x.to_int_unchecked::<u32>()
196                        }
197                    })?)
198                    .into_dyn(),
199                ),
200                bits @ 33.. => AnyArray::U64(
201                    Array1::from_vec(quantize(data, |x| {
202                        // we need to use TwoFloat here to have sufficient precision
203                        let max = TwoFloat::from(u64::MAX >> (64 - bits));
204                        let x = (TwoFloat::from(x) * scale_for_bits::<f64>(bits)
205                            + TwoFloat::from(0.5))
206                        .max(TwoFloat::from(0.0))
207                        .min(max);
208                        #[expect(unsafe_code)]
209                        // Safety: x is clamped beforehand
210                        unsafe {
211                            u64::try_from(x).unwrap_unchecked()
212                        }
213                    })?)
214                    .into_dyn(),
215                ),
216            },
217            (data, dtype) => {
218                return Err(LinearQuantizeCodecError::MismatchedEncodeDType {
219                    configured: dtype,
220                    provided: data.dtype(),
221                });
222            }
223        };
224
225        Ok(encoded)
226    }
227
228    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
229        #[expect(clippy::option_if_let_else)]
230        fn as_standard_order<T: Copy, S: Data<Elem = T>, D: Dimension>(
231            array: &ArrayBase<S, D>,
232        ) -> Cow<'_, [T]> {
233            if let Some(data) = array.as_slice() {
234                Cow::Borrowed(data)
235            } else {
236                Cow::Owned(array.iter().copied().collect())
237            }
238        }
239
240        if !matches!(encoded.shape(), [_]) {
241            return Err(LinearQuantizeCodecError::EncodedDataNotOneDimensional {
242                shape: encoded.shape().to_vec(),
243            });
244        }
245
246        let decoded = match (&encoded, self.dtype) {
247            (AnyCowArray::U8(encoded), LinearQuantizeDType::F32) => {
248                AnyArray::F32(reconstruct(&as_standard_order(encoded), |x| {
249                    f32::from(x) / scale_for_bits::<f32>(self.bits as u8)
250                })?)
251            }
252            (AnyCowArray::U16(encoded), LinearQuantizeDType::F32) => {
253                AnyArray::F32(reconstruct(&as_standard_order(encoded), |x| {
254                    f32::from(x) / scale_for_bits::<f32>(self.bits as u8)
255                })?)
256            }
257            (AnyCowArray::U32(encoded), LinearQuantizeDType::F32) => {
258                AnyArray::F32(reconstruct(&as_standard_order(encoded), |x| {
259                    // we need to use f64 here to have sufficient precision
260                    let x = f64::from(x) / scale_for_bits::<f64>(self.bits as u8);
261                    #[expect(clippy::cast_possible_truncation)]
262                    let x = x as f32;
263                    x
264                })?)
265            }
266            (AnyCowArray::U64(encoded), LinearQuantizeDType::F32) => {
267                AnyArray::F32(reconstruct(&as_standard_order(encoded), |x| {
268                    // we need to use TwoFloat here to have sufficient precision
269                    let x = TwoFloat::from(x) / scale_for_bits::<f64>(self.bits as u8);
270                    f32::from(x)
271                })?)
272            }
273            (AnyCowArray::U8(encoded), LinearQuantizeDType::F64) => {
274                AnyArray::F64(reconstruct(&as_standard_order(encoded), |x| {
275                    f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
276                })?)
277            }
278            (AnyCowArray::U16(encoded), LinearQuantizeDType::F64) => {
279                AnyArray::F64(reconstruct(&as_standard_order(encoded), |x| {
280                    f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
281                })?)
282            }
283            (AnyCowArray::U32(encoded), LinearQuantizeDType::F64) => {
284                AnyArray::F64(reconstruct(&as_standard_order(encoded), |x| {
285                    f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
286                })?)
287            }
288            (AnyCowArray::U64(encoded), LinearQuantizeDType::F64) => {
289                AnyArray::F64(reconstruct(&as_standard_order(encoded), |x| {
290                    // we need to use TwoFloat here to have sufficient precision
291                    let x = TwoFloat::from(x) / scale_for_bits::<f64>(self.bits as u8);
292                    f64::from(x)
293                })?)
294            }
295            (encoded, _dtype) => {
296                return Err(LinearQuantizeCodecError::InvalidEncodedDType {
297                    dtype: encoded.dtype(),
298                });
299            }
300        };
301
302        Ok(decoded)
303    }
304
305    fn decode_into(
306        &self,
307        encoded: AnyArrayView,
308        decoded: AnyArrayViewMut,
309    ) -> Result<(), Self::Error> {
310        fn as_standard_order<T: Copy, S: Data<Elem = T>, D: Dimension>(
311            array: &ArrayBase<S, D>,
312        ) -> Cow<'_, [T]> {
313            #[expect(clippy::option_if_let_else)]
314            if let Some(data) = array.as_slice() {
315                Cow::Borrowed(data)
316            } else {
317                Cow::Owned(array.iter().copied().collect())
318            }
319        }
320
321        if !matches!(encoded.shape(), [_]) {
322            return Err(LinearQuantizeCodecError::EncodedDataNotOneDimensional {
323                shape: encoded.shape().to_vec(),
324            });
325        }
326
327        match (decoded, self.dtype) {
328            (AnyArrayViewMut::F32(decoded), LinearQuantizeDType::F32) => {
329                match &encoded {
330                    AnyArrayView::U8(encoded) => {
331                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
332                            f32::from(x) / scale_for_bits::<f32>(self.bits as u8)
333                        })
334                    }
335                    AnyArrayView::U16(encoded) => {
336                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
337                            f32::from(x) / scale_for_bits::<f32>(self.bits as u8)
338                        })
339                    }
340                    AnyArrayView::U32(encoded) => {
341                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
342                            // we need to use f64 here to have sufficient precision
343                            let x = f64::from(x) / scale_for_bits::<f64>(self.bits as u8);
344                            #[expect(clippy::cast_possible_truncation)]
345                            let x = x as f32;
346                            x
347                        })
348                    }
349                    AnyArrayView::U64(encoded) => {
350                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
351                            // we need to use TwoFloat here to have sufficient precision
352                            let x = TwoFloat::from(x) / scale_for_bits::<f64>(self.bits as u8);
353                            f32::from(x)
354                        })
355                    }
356                    encoded => {
357                        return Err(LinearQuantizeCodecError::InvalidEncodedDType {
358                            dtype: encoded.dtype(),
359                        });
360                    }
361                }
362            }
363            (AnyArrayViewMut::F64(decoded), LinearQuantizeDType::F64) => {
364                match &encoded {
365                    AnyArrayView::U8(encoded) => {
366                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
367                            f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
368                        })
369                    }
370                    AnyArrayView::U16(encoded) => {
371                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
372                            f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
373                        })
374                    }
375                    AnyArrayView::U32(encoded) => {
376                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
377                            f64::from(x) / scale_for_bits::<f64>(self.bits as u8)
378                        })
379                    }
380                    AnyArrayView::U64(encoded) => {
381                        reconstruct_into(&as_standard_order(encoded), decoded, |x| {
382                            // we need to use TwoFloat here to have sufficient precision
383                            let x = TwoFloat::from(x) / scale_for_bits::<f64>(self.bits as u8);
384                            f64::from(x)
385                        })
386                    }
387                    encoded => {
388                        return Err(LinearQuantizeCodecError::InvalidEncodedDType {
389                            dtype: encoded.dtype(),
390                        });
391                    }
392                }
393            }
394            (decoded, dtype) => {
395                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
396                    configured: dtype,
397                    provided: decoded.dtype(),
398                });
399            }
400        }?;
401
402        Ok(())
403    }
404}
405
406impl StaticCodec for LinearQuantizeCodec {
407    const CODEC_ID: &'static str = "linear-quantize.rs";
408
409    type Config<'de> = Self;
410
411    fn from_config(config: Self::Config<'_>) -> Self {
412        config
413    }
414
415    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
416        StaticCodecConfig::from(self)
417    }
418}
419
420#[derive(Debug, Error)]
421/// Errors that may occur when applying the [`LinearQuantizeCodec`].
422pub enum LinearQuantizeCodecError {
423    /// [`LinearQuantizeCodec`] cannot encode the provided dtype which differs
424    /// from the configured dtype
425    #[error(
426        "LinearQuantize cannot encode the provided dtype {provided} which differs from the configured dtype {configured}"
427    )]
428    MismatchedEncodeDType {
429        /// Dtype of the `configured` `dtype`
430        configured: LinearQuantizeDType,
431        /// Dtype of the `provided` array from which the data is to be encoded
432        provided: AnyArrayDType,
433    },
434    /// [`LinearQuantizeCodec`] does not support non-finite (infinite or NaN) floating
435    /// point data
436    #[error("LinearQuantize does not support non-finite (infinite or NaN) floating point data")]
437    NonFiniteData,
438    /// [`LinearQuantizeCodec`] failed to encode the header
439    #[error("LinearQuantize failed to encode the header")]
440    HeaderEncodeFailed {
441        /// Opaque source error
442        source: LinearQuantizeHeaderError,
443    },
444    /// [`LinearQuantizeCodec`] can only decode one-dimensional arrays but
445    /// received an array of a different shape
446    #[error(
447        "LinearQuantize can only decode one-dimensional arrays but received an array of shape {shape:?}"
448    )]
449    EncodedDataNotOneDimensional {
450        /// The unexpected shape of the encoded array
451        shape: Vec<usize>,
452    },
453    /// [`LinearQuantizeCodec`] failed to decode the header
454    #[error("LinearQuantize failed to decode the header")]
455    HeaderDecodeFailed {
456        /// Opaque source error
457        source: LinearQuantizeHeaderError,
458    },
459    /// [`LinearQuantizeCodec`] decoded an invalid array shape header which does
460    /// not fit the decoded data
461    #[error(
462        "LinearQuantize decoded an invalid array shape header which does not fit the decoded data"
463    )]
464    DecodeInvalidShapeHeader {
465        /// Source error
466        #[from]
467        source: ShapeError,
468    },
469    /// [`LinearQuantizeCodec`] cannot decode the provided dtype
470    #[error("LinearQuantize cannot decode the provided dtype {dtype}")]
471    InvalidEncodedDType {
472        /// Dtype of the provided array from which the data is to be decoded
473        dtype: AnyArrayDType,
474    },
475    /// [`LinearQuantizeCodec`] cannot decode the provided dtype which differs
476    /// from the configured dtype
477    #[error(
478        "LinearQuantize cannot decode the provided dtype {provided} which differs from the configured dtype {configured}"
479    )]
480    MismatchedDecodeIntoDtype {
481        /// Dtype of the `configured` `dtype`
482        configured: LinearQuantizeDType,
483        /// Dtype of the `provided` array into which the data is to be decoded
484        provided: AnyArrayDType,
485    },
486    /// [`LinearQuantizeCodec`] cannot decode the decoded array into the provided
487    /// array of a different shape
488    #[error(
489        "LinearQuantize cannot decode the decoded array of shape {decoded:?} into the provided array of shape {provided:?}"
490    )]
491    MismatchedDecodeIntoShape {
492        /// Shape of the `decoded` data
493        decoded: Vec<usize>,
494        /// Shape of the `provided` array into which the data is to be decoded
495        provided: Vec<usize>,
496    },
497}
498
499#[derive(Debug, Error)]
500#[error(transparent)]
501/// Opaque error for when encoding or decoding the header fails
502pub struct LinearQuantizeHeaderError(postcard::Error);
503
504/// Linear-quantize the elements in the `data` array using the `quantize`
505/// closure.
506///
507/// # Errors
508///
509/// Errors with
510/// - [`LinearQuantizeCodecError::NonFiniteData`] if any data element is non-
511///   finite (infinite or NaN)
512/// - [`LinearQuantizeCodecError::HeaderEncodeFailed`] if encoding the header
513///   failed
514pub fn quantize<
515    T: Float + ConstZero + ConstOne + Serialize,
516    Q: Unsigned,
517    S: Data<Elem = T>,
518    D: Dimension,
519>(
520    data: &ArrayBase<S, D>,
521    quantize: impl Fn(T) -> Q,
522) -> Result<Vec<Q>, LinearQuantizeCodecError> {
523    if !Zip::from(data).all(|x| x.is_finite()) {
524        return Err(LinearQuantizeCodecError::NonFiniteData);
525    }
526
527    let (minimum, maximum) = data.first().map_or((T::ZERO, T::ONE), |first| {
528        (
529            Zip::from(data).fold(*first, |a, b| a.min(*b)),
530            Zip::from(data).fold(*first, |a, b| a.max(*b)),
531        )
532    });
533
534    let header = postcard::to_extend(
535        &CompressionHeader {
536            shape: Cow::Borrowed(data.shape()),
537            minimum,
538            maximum,
539            version: StaticCodecVersion,
540        },
541        Vec::new(),
542    )
543    .map_err(|err| LinearQuantizeCodecError::HeaderEncodeFailed {
544        source: LinearQuantizeHeaderError(err),
545    })?;
546
547    let mut encoded: Vec<Q> = vec![Q::ZERO; header.len().div_ceil(std::mem::size_of::<Q>())];
548    #[expect(unsafe_code)]
549    // Safety: encoded is at least header.len() bytes long and properly aligned for Q
550    unsafe {
551        std::ptr::copy_nonoverlapping(header.as_ptr(), encoded.as_mut_ptr().cast(), header.len());
552    }
553    encoded.reserve(data.len());
554
555    if maximum == minimum {
556        encoded.resize(encoded.len() + data.len(), quantize(T::ZERO));
557    } else {
558        encoded.extend(
559            data.iter()
560                .map(|x| quantize((*x - minimum) / (maximum - minimum))),
561        );
562    }
563
564    Ok(encoded)
565}
566
567/// Reconstruct the linear-quantized `encoded` array using the `floatify`
568/// closure.
569///
570/// # Errors
571///
572/// Errors with
573/// - [`LinearQuantizeCodecError::HeaderDecodeFailed`] if decoding the header
574///   failed
575pub fn reconstruct<T: Float + DeserializeOwned, Q: Unsigned>(
576    encoded: &[Q],
577    floatify: impl Fn(Q) -> T,
578) -> Result<ArrayD<T>, LinearQuantizeCodecError> {
579    #[expect(unsafe_code)]
580    // Safety: data is data.len()*size_of::<Q> bytes long and properly aligned for Q
581    let (header, remaining) = postcard::take_from_bytes::<CompressionHeader<T>>(unsafe {
582        std::slice::from_raw_parts(encoded.as_ptr().cast(), std::mem::size_of_val(encoded))
583    })
584    .map_err(|err| LinearQuantizeCodecError::HeaderDecodeFailed {
585        source: LinearQuantizeHeaderError(err),
586    })?;
587
588    let encoded = encoded
589        .get(encoded.len() - (remaining.len() / std::mem::size_of::<Q>())..)
590        .unwrap_or(&[]);
591
592    let decoded = encoded
593        .iter()
594        .map(|x| header.minimum + (floatify(*x) * (header.maximum - header.minimum)))
595        .map(|x| x.clamp(header.minimum, header.maximum))
596        .collect();
597
598    let decoded = Array::from_shape_vec(&*header.shape, decoded)?;
599
600    Ok(decoded)
601}
602
603/// Reconstruct the linear-quantized `encoded` array using the `floatify`
604/// closure into the `decoded` array.
605///
606/// # Errors
607///
608/// Errors with
609/// - [`LinearQuantizeCodecError::HeaderDecodeFailed`] if decoding the header
610///   failed
611/// - [`LinearQuantizeCodecError::MismatchedDecodeIntoShape`] if the `decoded`
612///   array is of the wrong shape
613pub fn reconstruct_into<T: Float + DeserializeOwned, Q: Unsigned>(
614    encoded: &[Q],
615    mut decoded: ArrayViewMutD<T>,
616    floatify: impl Fn(Q) -> T,
617) -> Result<(), LinearQuantizeCodecError> {
618    #[expect(unsafe_code)]
619    // Safety: data is data.len()*size_of::<Q> bytes long and properly aligned for Q
620    let (header, remaining) = postcard::take_from_bytes::<CompressionHeader<T>>(unsafe {
621        std::slice::from_raw_parts(encoded.as_ptr().cast(), std::mem::size_of_val(encoded))
622    })
623    .map_err(|err| LinearQuantizeCodecError::HeaderDecodeFailed {
624        source: LinearQuantizeHeaderError(err),
625    })?;
626
627    let encoded = encoded
628        .get(encoded.len() - (remaining.len() / std::mem::size_of::<Q>())..)
629        .unwrap_or(&[]);
630
631    if decoded.shape() != &*header.shape {
632        return Err(LinearQuantizeCodecError::MismatchedDecodeIntoShape {
633            decoded: header.shape.into_owned(),
634            provided: decoded.shape().to_vec(),
635        });
636    }
637
638    // iteration must occur in synchronised (standard) order
639    for (e, d) in encoded.iter().zip(decoded.iter_mut()) {
640        *d = (header.minimum + (floatify(*e) * (header.maximum - header.minimum)))
641            .clamp(header.minimum, header.maximum);
642    }
643
644    Ok(())
645}
646
647/// Returns `${2.0}^{bits} - 1.0$`
648fn scale_for_bits<T: Float + From<u8> + ConstOne>(bits: u8) -> T {
649    <T as From<u8>>::from(bits).exp2() - T::ONE
650}
651
652/// Unsigned binary types.
653pub trait Unsigned: Copy {
654    /// `0x0`
655    const ZERO: Self;
656}
657
658impl Unsigned for u8 {
659    const ZERO: Self = 0;
660}
661
662impl Unsigned for u16 {
663    const ZERO: Self = 0;
664}
665
666impl Unsigned for u32 {
667    const ZERO: Self = 0;
668}
669
670impl Unsigned for u64 {
671    const ZERO: Self = 0;
672}
673
674#[derive(Serialize, Deserialize)]
675struct CompressionHeader<'a, T> {
676    #[serde(borrow)]
677    shape: Cow<'a, [usize]>,
678    minimum: T,
679    maximum: T,
680    version: LinearQuantizeCodecVersion,
681}
682
683#[cfg(test)]
684mod tests {
685    use ndarray::CowArray;
686
687    use super::*;
688
689    #[test]
690    fn exact_roundtrip_f32_from() -> Result<(), LinearQuantizeCodecError> {
691        for bits in 1..=16 {
692            let codec = LinearQuantizeCodec {
693                dtype: LinearQuantizeDType::F32,
694                #[expect(unsafe_code)]
695                bits: unsafe { std::mem::transmute::<u8, LinearQuantizeBins>(bits) },
696                version: StaticCodecVersion,
697            };
698
699            let mut data: Vec<f32> = (0..(u16::MAX >> (16 - bits)))
700                .step_by(1 << (bits.max(8) - 8))
701                .map(f32::from)
702                .collect();
703            data.push(f32::from(u16::MAX >> (16 - bits)));
704
705            let encoded = codec.encode(AnyCowArray::F32(CowArray::from(&data).into_dyn()))?;
706            let decoded = codec.decode(encoded.cow())?;
707
708            let AnyArray::F32(decoded) = decoded else {
709                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
710                    configured: LinearQuantizeDType::F32,
711                    provided: decoded.dtype(),
712                });
713            };
714
715            for (o, d) in data.iter().zip(decoded.iter()) {
716                assert_eq!(o.to_bits(), d.to_bits());
717            }
718        }
719
720        Ok(())
721    }
722
723    #[test]
724    fn exact_roundtrip_f32_as() -> Result<(), LinearQuantizeCodecError> {
725        for bits in 1..=64 {
726            let codec = LinearQuantizeCodec {
727                dtype: LinearQuantizeDType::F32,
728                #[expect(unsafe_code)]
729                bits: unsafe { std::mem::transmute::<u8, LinearQuantizeBins>(bits) },
730                version: StaticCodecVersion,
731            };
732
733            #[expect(clippy::cast_precision_loss)]
734            let mut data: Vec<f32> = (0..(u64::MAX >> (64 - bits)))
735                .step_by(1 << (bits.max(8) - 8))
736                .map(|x| x as f32)
737                .collect();
738            #[expect(clippy::cast_precision_loss)]
739            data.push((u64::MAX >> (64 - bits)) as f32);
740
741            let encoded = codec.encode(AnyCowArray::F32(CowArray::from(&data).into_dyn()))?;
742            let decoded = codec.decode(encoded.cow())?;
743
744            let AnyArray::F32(decoded) = decoded else {
745                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
746                    configured: LinearQuantizeDType::F32,
747                    provided: decoded.dtype(),
748                });
749            };
750
751            for (o, d) in data.iter().zip(decoded.iter()) {
752                assert_eq!(o.to_bits(), d.to_bits());
753            }
754        }
755
756        Ok(())
757    }
758
759    #[test]
760    fn exact_roundtrip_f64_from() -> Result<(), LinearQuantizeCodecError> {
761        for bits in 1..=32 {
762            let codec = LinearQuantizeCodec {
763                dtype: LinearQuantizeDType::F64,
764                #[expect(unsafe_code)]
765                bits: unsafe { std::mem::transmute::<u8, LinearQuantizeBins>(bits) },
766                version: StaticCodecVersion,
767            };
768
769            let mut data: Vec<f64> = (0..(u32::MAX >> (32 - bits)))
770                .step_by(1 << (bits.max(8) - 8))
771                .map(f64::from)
772                .collect();
773            data.push(f64::from(u32::MAX >> (32 - bits)));
774
775            let encoded = codec.encode(AnyCowArray::F64(CowArray::from(&data).into_dyn()))?;
776            let decoded = codec.decode(encoded.cow())?;
777
778            let AnyArray::F64(decoded) = decoded else {
779                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
780                    configured: LinearQuantizeDType::F64,
781                    provided: decoded.dtype(),
782                });
783            };
784
785            for (o, d) in data.iter().zip(decoded.iter()) {
786                assert_eq!(o.to_bits(), d.to_bits());
787            }
788        }
789
790        Ok(())
791    }
792
793    #[test]
794    fn exact_roundtrip_f64_as() -> Result<(), LinearQuantizeCodecError> {
795        for bits in 1..=64 {
796            let codec = LinearQuantizeCodec {
797                dtype: LinearQuantizeDType::F64,
798                #[expect(unsafe_code)]
799                bits: unsafe { std::mem::transmute::<u8, LinearQuantizeBins>(bits) },
800                version: StaticCodecVersion,
801            };
802
803            #[expect(clippy::cast_precision_loss)]
804            let mut data: Vec<f64> = (0..(u64::MAX >> (64 - bits)))
805                .step_by(1 << (bits.max(8) - 8))
806                .map(|x| x as f64)
807                .collect();
808            #[expect(clippy::cast_precision_loss)]
809            data.push((u64::MAX >> (64 - bits)) as f64);
810
811            let encoded = codec.encode(AnyCowArray::F64(CowArray::from(&data).into_dyn()))?;
812            let decoded = codec.decode(encoded.cow())?;
813
814            let AnyArray::F64(decoded) = decoded else {
815                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
816                    configured: LinearQuantizeDType::F64,
817                    provided: decoded.dtype(),
818                });
819            };
820
821            for (o, d) in data.iter().zip(decoded.iter()) {
822                assert_eq!(o.to_bits(), d.to_bits());
823            }
824        }
825
826        Ok(())
827    }
828
829    #[test]
830    fn const_data_roundtrip() -> Result<(), LinearQuantizeCodecError> {
831        for bits in 1..=64 {
832            let data = [42.0, 42.0, 42.0, 42.0];
833
834            let codec = LinearQuantizeCodec {
835                dtype: LinearQuantizeDType::F64,
836                #[expect(unsafe_code)]
837                bits: unsafe { std::mem::transmute::<u8, LinearQuantizeBins>(bits) },
838                version: StaticCodecVersion,
839            };
840
841            let encoded = codec.encode(AnyCowArray::F64(CowArray::from(&data).into_dyn()))?;
842            let decoded = codec.decode(encoded.cow())?;
843
844            let AnyArray::F64(decoded) = decoded else {
845                return Err(LinearQuantizeCodecError::MismatchedDecodeIntoDtype {
846                    configured: LinearQuantizeDType::F64,
847                    provided: decoded.dtype(),
848                });
849            };
850
851            for (o, d) in data.iter().zip(decoded.iter()) {
852                assert_eq!(o.to_bits(), d.to_bits());
853            }
854        }
855
856        Ok(())
857    }
858}