Skip to main content

numcodecs_stochastic_rounding/
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-stochastic-rounding
10//! [crates.io]: https://crates.io/crates/numcodecs-stochastic-rounding
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-stochastic-rounding
13//! [docs.rs]: https://docs.rs/numcodecs-stochastic-rounding/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_stochastic_rounding
17//!
18//! Stochastic rounding codec implementation for the [`numcodecs`] API.
19
20use std::borrow::Cow;
21use std::hash::{Hash, Hasher};
22
23use ndarray::{Array, ArrayBase, Data, Dimension};
24use num_traits::Float;
25use numcodecs::{
26    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
27    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
28};
29use rand::{
30    SeedableRng,
31    distr::{Distribution, Open01},
32};
33use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
34use serde::{Deserialize, Deserializer, Serialize, Serializer};
35use thiserror::Error;
36use wyhash::{WyHash, WyRng};
37
38#[cfg(test)]
39use ::serde_json as _;
40
41#[derive(Clone, Serialize, Deserialize, JsonSchema)]
42#[serde(deny_unknown_fields)]
43/// Codec that stochastically rounds the data to the nearest multiple of
44/// `precision` on encoding and passes through the input unchanged during
45/// decoding.
46///
47/// The nearest representable multiple is chosen such that the absolute
48/// difference between the original value and the rounded value do not exceed
49/// the precision. Therefore, the rounded value may have a non-zero remainder.
50///
51/// This codec first hashes the input array data and shape to then `seed` a
52/// pseudo-random number generator that is used to sample the stochasticity for
53/// rounding. Therefore, passing in the same input with the same `seed` will
54/// produce the same stochasticity and thus the same encoded output.
55pub struct StochasticRoundingCodec {
56    /// The precision of the rounding operation
57    pub precision: NonNegative<f64>,
58    /// Seed for the random generator
59    pub seed: u64,
60    /// The codec's encoding format version. Do not provide this parameter explicitly.
61    #[serde(default, rename = "_version")]
62    pub version: StaticCodecVersion<1, 0, 0>,
63}
64
65impl Codec for StochasticRoundingCodec {
66    type Error = StochasticRoundingCodecError;
67
68    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
69        match data {
70            #[expect(clippy::cast_possible_truncation)]
71            AnyCowArray::F32(data) => Ok(AnyArray::F32(stochastic_rounding(
72                data,
73                NonNegative(self.precision.0 as f32),
74                self.seed,
75            ))),
76            AnyCowArray::F64(data) => Ok(AnyArray::F64(stochastic_rounding(
77                data,
78                self.precision,
79                self.seed,
80            ))),
81            encoded => Err(StochasticRoundingCodecError::UnsupportedDtype(
82                encoded.dtype(),
83            )),
84        }
85    }
86
87    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
88        match encoded {
89            AnyCowArray::F32(encoded) => Ok(AnyArray::F32(encoded.into_owned())),
90            AnyCowArray::F64(encoded) => Ok(AnyArray::F64(encoded.into_owned())),
91            encoded => Err(StochasticRoundingCodecError::UnsupportedDtype(
92                encoded.dtype(),
93            )),
94        }
95    }
96
97    fn decode_into(
98        &self,
99        encoded: AnyArrayView,
100        mut decoded: AnyArrayViewMut,
101    ) -> Result<(), Self::Error> {
102        if !matches!(encoded.dtype(), AnyArrayDType::F32 | AnyArrayDType::F64) {
103            return Err(StochasticRoundingCodecError::UnsupportedDtype(
104                encoded.dtype(),
105            ));
106        }
107
108        Ok(decoded.assign(&encoded)?)
109    }
110}
111
112impl StaticCodec for StochasticRoundingCodec {
113    const CODEC_ID: &'static str = "stochastic-rounding.rs";
114
115    type Config<'de> = Self;
116
117    fn from_config(config: Self::Config<'_>) -> Self {
118        config
119    }
120
121    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
122        StaticCodecConfig::from(self)
123    }
124}
125
126#[expect(clippy::derive_partial_eq_without_eq)] // floats are not Eq
127#[derive(Copy, Clone, PartialEq, PartialOrd, Hash)]
128/// Non-negative floating point number
129pub struct NonNegative<T: Float>(T);
130
131impl Serialize for NonNegative<f64> {
132    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
133        serializer.serialize_f64(self.0)
134    }
135}
136
137impl<'de> Deserialize<'de> for NonNegative<f64> {
138    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
139        let x = f64::deserialize(deserializer)?;
140
141        if x >= 0.0 {
142            Ok(Self(x))
143        } else {
144            Err(serde::de::Error::invalid_value(
145                serde::de::Unexpected::Float(x),
146                &"a non-negative value",
147            ))
148        }
149    }
150}
151
152impl JsonSchema for NonNegative<f64> {
153    fn inline_schema() -> bool {
154        true
155    }
156
157    fn schema_name() -> Cow<'static, str> {
158        Cow::Borrowed("NonNegativeF64")
159    }
160
161    fn schema_id() -> Cow<'static, str> {
162        Cow::Borrowed(concat!(module_path!(), "::", "NonNegative<f64>"))
163    }
164
165    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
166        json_schema!({
167            "type": "number",
168            "minimum": 0.0
169        })
170    }
171}
172
173#[derive(Debug, Error)]
174/// Errors that may occur when applying the [`StochasticRoundingCodec`].
175pub enum StochasticRoundingCodecError {
176    /// [`StochasticRoundingCodec`] does not support the dtype
177    #[error("StochasticRounding does not support the dtype {0}")]
178    UnsupportedDtype(AnyArrayDType),
179    /// [`StochasticRoundingCodec`] cannot decode into the provided array
180    #[error("StochasticRounding cannot decode into the provided array")]
181    MismatchedDecodeIntoArray {
182        /// The source of the error
183        #[from]
184        source: AnyArrayAssignError,
185    },
186}
187
188/// Stochastically rounds the `data` to the nearest multiple of the `precision`.
189///
190/// The nearest representable multiple is chosen such that the absolute
191/// difference between the original value and the rounded value do not exceed
192/// the precision. Therefore, the rounded value may have a non-zero remainder.
193///
194/// This function first hashes the input array data and shape to then `seed` a
195/// pseudo-random number generator that is used to sample the stochasticity for
196/// rounding. Therefore, passing in the same input with the same `seed` will
197/// produce the same stochasticity and thus the same encoded output.
198#[must_use]
199pub fn stochastic_rounding<T: FloatExt, S: Data<Elem = T>, D: Dimension>(
200    data: ArrayBase<S, D>,
201    precision: NonNegative<T>,
202    seed: u64,
203) -> Array<T, D>
204where
205    Open01: Distribution<T>,
206{
207    let mut encoded = data.into_owned();
208
209    if precision.0.is_zero() {
210        return encoded;
211    }
212
213    let mut hasher = WyHash::with_seed(seed);
214    // hashing the shape provides a prefix for the flattened data
215    encoded.shape().hash(&mut hasher);
216    // the data must be visited in a defined order
217    encoded
218        .iter()
219        .copied()
220        .for_each(|x| x.hash_bits(&mut hasher));
221    let seed = hasher.finish();
222
223    let mut rng: WyRng = WyRng::seed_from_u64(seed);
224
225    // the data must be visited in a defined order
226    for x in &mut encoded {
227        if !x.is_finite() {
228            continue;
229        }
230
231        let remainder = x.rem_euclid(precision.0);
232
233        // compute the nearest multiples of precision based on the remainder
234        // correct max 1 ULP rounding errors to ensure that the nearest
235        //  multiples are at most precision away from the original value
236        let mut lower = *x - remainder;
237        if (*x - lower) > precision.0 {
238            lower = lower.next_up();
239        }
240        let mut upper = *x + (precision.0 - remainder);
241        if (upper - *x) > precision.0 {
242            upper = upper.next_down();
243        }
244
245        let threshold = remainder / precision.0;
246
247        let u01: T = Open01.sample(&mut rng);
248
249        // if remainder = 0, U(0, 1) >= 0, so lower (i.e. a) is always picked
250        // if threshold = 1/2, U(0, 1) picks lower and upper with equal chance
251        *x = if u01 >= threshold { lower } else { upper };
252    }
253
254    encoded
255}
256
257/// Floating point types
258pub trait FloatExt: Float {
259    /// -0.5
260    const NEG_HALF: Self;
261
262    /// Hash the binary representation of the floating point value
263    fn hash_bits<H: Hasher>(self, hasher: &mut H);
264
265    /// Calculates the least nonnegative remainder of self (mod rhs).
266    #[must_use]
267    fn rem_euclid(self, rhs: Self) -> Self;
268
269    /// Returns the least number greater than `self`.
270    #[must_use]
271    fn next_up(self) -> Self;
272
273    /// Returns the greatest number less than `self`.
274    #[must_use]
275    fn next_down(self) -> Self;
276}
277
278impl FloatExt for f32 {
279    const NEG_HALF: Self = -0.5;
280
281    fn hash_bits<H: Hasher>(self, hasher: &mut H) {
282        hasher.write_u32(self.to_bits());
283    }
284
285    fn rem_euclid(self, rhs: Self) -> Self {
286        Self::rem_euclid(self, rhs)
287    }
288
289    fn next_up(self) -> Self {
290        Self::next_up(self)
291    }
292
293    fn next_down(self) -> Self {
294        Self::next_down(self)
295    }
296}
297
298impl FloatExt for f64 {
299    const NEG_HALF: Self = -0.5;
300
301    fn hash_bits<H: Hasher>(self, hasher: &mut H) {
302        hasher.write_u64(self.to_bits());
303    }
304
305    fn rem_euclid(self, rhs: Self) -> Self {
306        Self::rem_euclid(self, rhs)
307    }
308
309    fn next_up(self) -> Self {
310        Self::next_up(self)
311    }
312
313    fn next_down(self) -> Self {
314        Self::next_down(self)
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use ndarray::{array, linspace};
321
322    use super::*;
323
324    #[test]
325    fn round_zero_precision() {
326        let data = array![1.1, 2.1];
327
328        let rounded = stochastic_rounding(data.view(), NonNegative(0.0), 42);
329
330        assert_eq!(data, rounded);
331    }
332
333    #[test]
334    fn round_infinite_precision() {
335        let data = array![1.1, 2.1];
336
337        let rounded = stochastic_rounding(data.view(), NonNegative(f64::INFINITY), 42);
338
339        assert_eq!(rounded, array![0.0, 0.0]);
340    }
341
342    #[test]
343    fn round_minimal_precision() {
344        let data = array![0.1, 1.0, 11.0, 21.0];
345
346        assert_eq!(11.0 / f64::MIN_POSITIVE, f64::INFINITY);
347        let rounded = stochastic_rounding(data.view(), NonNegative(f64::MIN_POSITIVE), 42);
348
349        assert_eq!(data, rounded);
350    }
351
352    #[test]
353    fn round_edge_cases() {
354        let data = array![
355            -f64::NAN,
356            -f64::INFINITY,
357            -42.0,
358            -4.2,
359            -0.0,
360            0.0,
361            4.2,
362            42.0,
363            f64::INFINITY,
364            f64::NAN
365        ];
366        let precision = 1.0;
367
368        let rounded = stochastic_rounding(data.view(), NonNegative(precision), 42);
369
370        for (d, r) in data.into_iter().zip(rounded) {
371            assert!((r - d).abs() <= precision || d.to_bits() == r.to_bits());
372        }
373    }
374
375    #[test]
376    fn round_rounding_errors() {
377        let data = Array::from_iter(linspace(-100.0, 100.0, 3741));
378        let precision = 0.1;
379
380        let rounded = stochastic_rounding(data.view(), NonNegative(precision), 42);
381
382        for (d, r) in data.into_iter().zip(rounded) {
383            assert!((r - d).abs() <= precision);
384        }
385    }
386
387    #[test]
388    fn test_rounding_bug() {
389        let data = array![
390            -1.23540_f32,
391            -1.23539_f32,
392            -1.23538_f32,
393            -1.23537_f32,
394            -1.23536_f32,
395            -1.23535_f32,
396            -1.23534_f32,
397            -1.23533_f32,
398            -1.23532_f32,
399            -1.23531_f32,
400            -1.23530_f32,
401            1.23540_f32,
402            1.23539_f32,
403            1.23538_f32,
404            1.23537_f32,
405            1.23536_f32,
406            1.23535_f32,
407            1.23534_f32,
408            1.23533_f32,
409            1.23532_f32,
410            1.23531_f32,
411            1.23530_f32,
412        ];
413        let precision = 0.00018_f32;
414
415        let rounded = stochastic_rounding(data.view(), NonNegative(precision), 42);
416
417        for (d, r) in data.into_iter().zip(rounded) {
418            assert!((r - d).abs() <= precision);
419        }
420    }
421}