numcodecs_stochastic_rounding/
lib.rs1use 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)]
43pub struct StochasticRoundingCodec {
56 pub precision: NonNegative<f64>,
58 pub seed: u64,
60 #[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)] #[derive(Copy, Clone, PartialEq, PartialOrd, Hash)]
128pub 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)]
174pub enum StochasticRoundingCodecError {
176 #[error("StochasticRounding does not support the dtype {0}")]
178 UnsupportedDtype(AnyArrayDType),
179 #[error("StochasticRounding cannot decode into the provided array")]
181 MismatchedDecodeIntoArray {
182 #[from]
184 source: AnyArrayAssignError,
185 },
186}
187
188#[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 encoded.shape().hash(&mut hasher);
216 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 for x in &mut encoded {
227 if !x.is_finite() {
228 continue;
229 }
230
231 let remainder = x.rem_euclid(precision.0);
232
233 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 *x = if u01 >= threshold { lower } else { upper };
252 }
253
254 encoded
255}
256
257pub trait FloatExt: Float {
259 const NEG_HALF: Self;
261
262 fn hash_bits<H: Hasher>(self, hasher: &mut H);
264
265 #[must_use]
267 fn rem_euclid(self, rhs: Self) -> Self;
268
269 #[must_use]
271 fn next_up(self) -> Self;
272
273 #[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}