tinymind/qformat.rs
1//! Signed fixed-point Q-format arithmetic, ported from tinymind (C++) `cpp/qformat.hpp`.
2//!
3//! The C++ `QValue<FixedBits, FractionalBits, IsSigned, RoundingPolicy, SaturatePolicy>`
4//! picks its storage type from `FixedBits + FractionalBits` at compile time
5//! (`QTypeChooser`). Stable Rust cannot compute a type from const-generic
6//! arithmetic (that needs the nightly `generic_const_exprs` feature), so here the
7//! storage type is an explicit parameter: `QValue<i32, 16>` is Q16.16 and
8//! `QValue<i16, 8>` is Q8.8. The methods and operators are generated for each
9//! supported storage type by a macro, each with the wider type C++ uses for
10//! products and quotients (`i64` for `i32`, `i32` for `i16`).
11//!
12//! Only tinymind (C++)'s default policies are ported: `TruncatePolicy` (multiplication
13//! drops the low bits) and `WrapPolicy` (addition and subtraction wrap modulo the
14//! storage width).
15//!
16//! The module also defines [`Scalar`], the value-type trait every network is
17//! generic over, implemented for these formats and for `f32` and `f64` (and the
18//! deprecated [`Fixed`], its name up to 0.1.5).
19
20use core::fmt;
21use core::ops::{Add, AddAssign, Div, Mul, Sub};
22
23/// A signed fixed-point value stored in `S` (`i16` or `i32`) with `FRAC`
24/// fractional bits.
25///
26/// The derived `PartialOrd`/`Ord` compare the raw integer, which is exactly what
27/// the C++ comparison operators do (they compare `getValue()`).
28///
29/// `FRAC` must be at least 1 and less than the storage width; anything else is a
30/// compile-time error wherever the format's arithmetic is used:
31///
32/// ```compile_fail
33/// // 40 fractional bits do not fit in i32 storage.
34/// let x = tinymind::QValue::<i32, 40>::default();
35/// let _ = x.to_f64();
36/// ```
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct QValue<S, const FRAC: u32>(S);
39
40/// Q16.16: 16 integer bits (including sign), 16 fractional bits, `i32` storage.
41pub type Q16_16 = QValue<i32, 16>;
42
43/// Q8.8: 8 integer bits (including sign), 8 fractional bits, `i16` storage.
44pub type Q8_8 = QValue<i16, 8>;
45
46/// Prints the raw LSBs, matching the C++ `operator<<` (not the real value).
47impl<S: fmt::Display, const FRAC: u32> fmt::Display for QValue<S, FRAC> {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 fmt::Display::fmt(&self.0, f)
50 }
51}
52
53/// A network's value type: the arithmetic a network needs from the numbers it
54/// computes with. This is the Rust counterpart of the implicit "ValueType
55/// concept" that the C++ templates rely on: in C++ a missing operator is a
56/// template instantiation error, here it is a trait-bound error at the call
57/// site.
58///
59/// Implemented for the [`QValue`] formats and for `f32` and `f64`: the networks
60/// run in fixed point or in floating point, as tinymind (C++)'s do when
61/// instantiated with a Q format, `float` or `double`. Called `Fixed` up to
62/// 0.1.5; that name remains as a deprecated alias ([`Fixed`]).
63pub trait Scalar:
64 Copy
65 + Default
66 + PartialOrd
67 + Add<Output = Self>
68 + AddAssign
69 + Sub<Output = Self>
70 + Mul<Output = Self>
71 + Div<Output = Self>
72{
73 /// 0.0
74 const ZERO: Self;
75 /// 1.0
76 const ONE: Self;
77 /// `2^-n`
78 fn pow2_neg(n: u32) -> Self;
79 /// Divide by a whole number (C++ `operator/=(int)`).
80 fn div_int(self, n: i32) -> Self;
81 /// `self * rhs` rounded toward zero (C++ `multiplyRoundTowardZero`), used
82 /// for SGD's momentum and acceleration terms so that a delta weight no
83 /// gradient refreshes decays to exactly 0. The default is `self * rhs`,
84 /// right for floating point; the Q formats round their product toward
85 /// zero instead of flooring it.
86 fn mul_round_toward_zero(self, rhs: Self) -> Self {
87 self * rhs
88 }
89 /// `self * rhs` rounded to nearest, ties away from zero (C++
90 /// `multiplyRoundNearest`), used for SGD's step `learning rate *
91 /// gradient`, so that steps smaller than the format's resolution do not
92 /// all drift one way. The default is `self * rhs`, right for floating
93 /// point; the Q formats round their product to nearest instead of
94 /// flooring it.
95 fn mul_round_nearest(self, rhs: Self) -> Self {
96 self * rhs
97 }
98}
99
100/// The name of [`Scalar`] up to 0.1.5, kept so that bounds written `V: Fixed`
101/// still compile. Every [`Scalar`] is a `Fixed`; implement [`Scalar`] instead.
102/// `Fixed` has no items of its own, so paths that name them through it
103/// (`<V as Fixed>::ONE`, `Fixed::div_int(..)`) must name [`Scalar`].
104///
105/// ```
106/// # #![allow(deprecated)]
107/// use tinymind::{Fixed, Q16_16};
108///
109/// // Code written against 0.1.5 keeps compiling (with a deprecation warning).
110/// fn one<V: Fixed>() -> V {
111/// V::ONE
112/// }
113/// assert_eq!(one::<Q16_16>(), Q16_16::ONE);
114/// assert_eq!(one::<f64>(), 1.0);
115/// ```
116#[deprecated(
117 since = "0.2.0",
118 note = "renamed to `Scalar`, which covers f32 and f64 as well as the Q formats"
119)]
120pub trait Fixed: Scalar {}
121
122#[allow(deprecated)]
123impl<T: Scalar> Fixed for T {}
124
125/// `f32` and `f64` as network value types. `pow2_neg` builds the power of two
126/// exactly; `div_int` divides by the integer converted to the float type, as
127/// the C++ `value /= n` does.
128macro_rules! impl_fixed_float {
129 ($t:ty) => {
130 impl Scalar for $t {
131 const ZERO: Self = 0.0;
132 const ONE: Self = 1.0;
133
134 fn pow2_neg(n: u32) -> Self {
135 let mut x: $t = 1.0;
136 for _ in 0..n.min(1100) {
137 x *= 0.5;
138 }
139 x
140 }
141
142 fn div_int(self, n: i32) -> Self {
143 self / (n as $t)
144 }
145 }
146 };
147}
148
149impl_fixed_float!(f32);
150impl_fixed_float!(f64);
151
152/// Square root of a non-negative value (C++ `SquareRootApproximation`):
153/// integer Newton iteration on `raw << FRAC` in the wide type, which gives the
154/// floor of the exact root in raw units. Zero and negative values give zero. The
155/// Adam and RMSprop optimizers use it.
156pub trait Sqrt {
157 /// `floor(sqrt(self))` in this format; 0 for `self <= 0`.
158 fn sqrt(self) -> Self;
159}
160
161/// Generates everything that depends on the storage type: `$s` is the storage,
162/// `$wide` the C++ `MultiplicationResultFullWidthValueType` /
163/// `DivisionResultFullWidthValueType` for it (twice the width).
164macro_rules! impl_qvalue {
165 ($s:ty, $wide:ty) => {
166 impl<const FRAC: u32> QValue<$s, FRAC> {
167 /// Compile-time format check, evaluated once per instantiated format.
168 /// The C++ library does the same job with `static_assert`. Every method
169 /// whose arithmetic depends on `FRAC` evaluates it, so an invalid format
170 /// such as `QValue<i32, 40>` fails to compile wherever it is used, even
171 /// when the value came from `Default`.
172 const FORMAT_OK: () = assert!(
173 FRAC >= 1 && FRAC < <$s>::BITS,
174 "QValue needs at least 1 fractional bit and fewer than the storage width"
175 );
176
177 /// Number of fractional bits (`FRAC`).
178 pub const FRACTIONAL_BITS: u32 = FRAC;
179 /// Number of integer bits, including the sign bit (storage width - `FRAC`).
180 pub const FIXED_BITS: u32 = <$s>::BITS - FRAC;
181 /// 0.0
182 pub const ZERO: Self = Self::from_raw(0);
183 /// 1.0. When `FRAC` is one less than the storage width (Q1.15, Q1.31)
184 /// there are no integer bits besides the sign, 1.0 is not
185 /// representable, and this wraps to -1.0 (the storage type's minimum).
186 pub const ONE: Self = Self::from_int(1);
187
188 /// Build from raw LSBs (C++ `QValue(FullWidthFieldType)` / `setValue(raw)`).
189 pub const fn from_raw(raw: $s) -> Self {
190 let () = Self::FORMAT_OK;
191 Self(raw)
192 }
193
194 /// Build from a whole number (C++ `QValue(fixedPart, 0)`). The fixed part
195 /// is truncated to `FIXED_BITS`, as the C++ `fromParts` does, which is the
196 /// same as shifting left and letting the high bits fall off: in Q8.8, 200
197 /// becomes -56.
198 pub const fn from_int(n: i32) -> Self {
199 let () = Self::FORMAT_OK;
200 Self(((n as u32) << FRAC) as $s)
201 }
202
203 /// `2^-n`, used for tinymind (C++)'s default learning/momentum/acceleration rates.
204 ///
205 /// For `n > FRAC`, `2^-n` is below the format's resolution and the result
206 /// is [`ZERO`](Self::ZERO): the value truncated to the format, as
207 /// TruncatePolicy rounds every other result. `pow2_neg(0)` is
208 /// [`ONE`](Self::ONE), with the same caveat for formats without integer bits.
209 pub const fn pow2_neg(n: u32) -> Self {
210 if n > FRAC {
211 return Self::from_raw(0);
212 }
213 Self::from_raw((1 as $s) << (FRAC - n))
214 }
215
216 /// Raw LSBs (C++ `getValue()`).
217 pub const fn raw(self) -> $s {
218 self.0
219 }
220
221 /// Real-number view, computed as the C++ example does: `raw / 2^FRAC` in `f64`.
222 pub fn to_f64(self) -> f64 {
223 let () = Self::FORMAT_OK;
224 f64::from(self.0) / f64::from(1u32 << FRAC)
225 }
226
227 /// Truncating conversion from `f64` (C++
228 /// `setValue(static_cast<FullWidthValueType>(x * 2^FRAC))`). Out-of-range
229 /// input saturates; in C++ it is undefined behaviour.
230 pub fn from_f64_trunc(x: f64) -> Self {
231 Self::from_raw((x * f64::from(1u32 << FRAC)) as $s)
232 }
233
234 /// `self * rhs` with the product rounded toward zero instead of
235 /// floored (C++ `multiplyRoundTowardZero`): the same widening and
236 /// wrap to the storage width as `*`. SGD uses it for the momentum
237 /// and acceleration terms: floored, `0.5 * (-1 LSB)` stays -1 LSB,
238 /// so a delta weight no gradient refreshes would never decay.
239 pub fn mul_round_toward_zero(self, rhs: Self) -> Self {
240 let () = Self::FORMAT_OK;
241 let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
242 // Toward zero without a branch: a negative product gets
243 // 2^FRAC - 1 added before the flooring shift. |product| <=
244 // 2^(2 * storage bits - 2), so the sum cannot overflow.
245 let bias = (product >> (<$wide>::BITS - 1)) & ((1 << FRAC) - 1);
246 Self(((product + bias) >> FRAC) as $s)
247 }
248
249 /// `self * rhs` with the product rounded to nearest, ties away
250 /// from zero, instead of floored (C++ `multiplyRoundNearest`): the
251 /// same widening and wrap to the storage width as `*`. SGD uses it
252 /// for the step `learning rate * gradient`: floored, a step smaller
253 /// than one LSB is 0 when positive but a whole -1 LSB when
254 /// negative, so weights with small gradients drift down.
255 pub fn mul_round_nearest(self, rhs: Self) -> Self {
256 let () = Self::FORMAT_OK;
257 let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
258 // Half away from zero without a branch: adding half and then
259 // flooring rounds half up, which is right for a positive
260 // product; a negative one also gets the sign word, -1, added,
261 // which turns its ties down (away from zero) and leaves every
262 // other value where half up puts it. Kani proves it for every
263 // input. |product| <= 2^(2 * storage bits - 2), so the sum
264 // cannot overflow.
265 let sign = product >> (<$wide>::BITS - 1);
266 Self(((product + (1 << (FRAC - 1)) + sign) >> FRAC) as $s)
267 }
268
269 /// Divide by a whole number, truncating toward zero (C++
270 /// `QValue::operator/=(int)`). This is *not* the same as dividing by
271 /// `QValue::from_int(n)`.
272 pub const fn div_int(self, n: i32) -> Self {
273 if n == 0 {
274 return Self::div_by_zero(self.0);
275 }
276 // C++ applyInteger works in int64 for every format up to 32 bits.
277 Self((self.0 as i64 / n as i64) as $s)
278 }
279
280 /// C++ `ZeroToleranceCalculator`: true when `|raw| < 1 << (FRAC - 7)` for
281 /// formats with more than 7 fractional bits (512 LSBs for Q16.16, 2 for
282 /// Q8.8), else `|raw| < 2`.
283 pub const fn is_within_zero_tolerance(self) -> bool {
284 let () = Self::FORMAT_OK;
285 let shift = if FRAC > 7 { FRAC - 7 } else { 1 };
286 let tolerance = (1 as $s) << shift;
287 self.0 == 0 || (self.0 < tolerance && self.0 > -tolerance)
288 }
289
290 /// The bound a quotient by zero saturates to: max for a positive dividend,
291 /// min for a negative one, 0 for 0 (C++ `WrapPolicy` division case).
292 const fn div_by_zero(dividend: $s) -> Self {
293 if dividend > 0 {
294 Self(<$s>::MAX)
295 } else if dividend < 0 {
296 Self(<$s>::MIN)
297 } else {
298 Self(0)
299 }
300 }
301 }
302
303 impl<const FRAC: u32> Add for QValue<$s, FRAC> {
304 type Output = Self;
305 fn add(self, rhs: Self) -> Self {
306 // C++ adds in the unsigned counterpart to get defined wrap-around;
307 // Rust says what it means directly.
308 Self(self.0.wrapping_add(rhs.0))
309 }
310 }
311
312 impl<const FRAC: u32> AddAssign for QValue<$s, FRAC> {
313 fn add_assign(&mut self, rhs: Self) {
314 *self = *self + rhs;
315 }
316 }
317
318 impl<const FRAC: u32> Sub for QValue<$s, FRAC> {
319 type Output = Self;
320 fn sub(self, rhs: Self) -> Self {
321 Self(self.0.wrapping_sub(rhs.0))
322 }
323 }
324
325 impl<const FRAC: u32> Mul for QValue<$s, FRAC> {
326 type Output = Self;
327 fn mul(self, rhs: Self) -> Self {
328 let () = Self::FORMAT_OK;
329 // Widen, truncate (arithmetic shift right floors toward -inf), then
330 // wrap back to the storage width.
331 let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
332 Self((product >> FRAC) as $s)
333 }
334 }
335
336 impl<const FRAC: u32> Div for QValue<$s, FRAC> {
337 type Output = Self;
338 fn div(self, rhs: Self) -> Self {
339 let () = Self::FORMAT_OK;
340 if rhs.0 == 0 {
341 return Self::div_by_zero(self.0);
342 }
343 // Scale the dividend up by 2^FRAC in the wide type, divide
344 // (truncating toward zero, like C++), then wrap back.
345 let dividend = <$wide>::from(self.0) * ((1 as $wide) << FRAC);
346 Self((dividend / <$wide>::from(rhs.0)) as $s)
347 }
348 }
349
350 impl<const FRAC: u32> Sqrt for QValue<$s, FRAC> {
351 fn sqrt(self) -> Self {
352 let () = Self::FORMAT_OK;
353 if self.0 <= 0 {
354 return Self(0);
355 }
356 // n < 2^(storage bits - 1 + FRAC), so it and every sum below fit
357 // the wide type, and x stays >= 1.
358 let n = <$wide>::from(self.0) << FRAC;
359 let mut x = n;
360 let mut y = (x + 1) / 2;
361 while y < x {
362 x = y;
363 // x >= 1 here, but the compiler cannot prove it; the
364 // fallback is unreachable and keeps the function panic-free.
365 y = (x + n.checked_div(x).unwrap_or(0)) / 2;
366 }
367 // n < 2^(2 * storage bits - 2), so the root is below 2^(storage
368 // bits - 1) and the narrowing (the C++ static_cast) never truncates.
369 Self(x as $s)
370 }
371 }
372
373 impl<const FRAC: u32> Scalar for QValue<$s, FRAC> {
374 const ZERO: Self = Self::ZERO;
375 const ONE: Self = Self::ONE;
376 fn pow2_neg(n: u32) -> Self {
377 Self::pow2_neg(n)
378 }
379 fn div_int(self, n: i32) -> Self {
380 self.div_int(n)
381 }
382 fn mul_round_toward_zero(self, rhs: Self) -> Self {
383 self.mul_round_toward_zero(rhs)
384 }
385 fn mul_round_nearest(self, rhs: Self) -> Self {
386 self.mul_round_nearest(rhs)
387 }
388 }
389 };
390}
391
392impl_qvalue!(i32, i64);
393impl_qvalue!(i16, i32);
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 /// `sqrt` is the floor of the exact root of `raw << FRAC`: r*r <= n < (r+1)^2.
400 fn check_floor_root(raw: i64, frac: u32, root: i64) {
401 let n = raw << frac;
402 assert!(
403 root * root <= n && (root + 1) * (root + 1) > n,
404 "raw {raw}: root {root}"
405 );
406 }
407
408 #[test]
409 fn sqrt_every_q8_8_value() {
410 for raw in i16::MIN..=i16::MAX {
411 let r = i64::from(Q8_8::from_raw(raw).sqrt().raw());
412 if raw <= 0 {
413 assert_eq!(r, 0);
414 } else {
415 check_floor_root(i64::from(raw), 8, r);
416 }
417 }
418 assert_eq!(Q8_8::from_int(4).sqrt(), Q8_8::from_int(2));
419 }
420
421 #[test]
422 fn sqrt_q16_16_sample_and_edges() {
423 let mut x: u32 = 1;
424 let edges = [1, 2, 3, 65_535, 65_536, 65_537, i32::MAX - 1, i32::MAX];
425 for raw in edges.into_iter().chain((0..100_000).map(|_| {
426 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
427 (x >> 1) as i32
428 })) {
429 check_floor_root(
430 i64::from(raw),
431 16,
432 i64::from(Q16_16::from_raw(raw).sqrt().raw()),
433 );
434 }
435 assert_eq!(Q16_16::from_int(9).sqrt(), Q16_16::from_int(3));
436 assert_eq!(Q16_16::from_int(-9).sqrt(), Q16_16::ZERO);
437 // Formats with one integer bit: the root of a value near 1 is near 1 and
438 // does not fit; it wraps as the C++ static_cast does, without panicking.
439 let _ = QValue::<i32, 31>::from_raw(i32::MAX).sqrt();
440 let _ = QValue::<i16, 15>::from_raw(i16::MAX).sqrt();
441 }
442
443 #[test]
444 fn constants() {
445 assert_eq!(Q16_16::ONE.raw(), 65536);
446 assert_eq!(Q16_16::from_int(-1).raw(), -65536);
447 assert_eq!(Q16_16::pow2_neg(2).raw(), 16384);
448 assert_eq!(Q8_8::ONE.raw(), 256);
449 assert_eq!(Q8_8::from_int(-1).raw(), -256);
450 assert_eq!(Q8_8::pow2_neg(4).raw(), 16);
451 assert_eq!((Q8_8::FIXED_BITS, Q8_8::FRACTIONAL_BITS), (8, 8));
452 }
453
454 #[test]
455 fn from_int_truncates_the_fixed_part() {
456 // tinymind's own example (qformat.hpp, applyInteger comment): Q8.8 200 -> -56.
457 assert_eq!(Q8_8::from_int(200), Q8_8::from_int(-56));
458 assert_eq!(Q8_8::from_int(127).raw(), 127 * 256);
459 }
460
461 #[test]
462 fn multiply_truncates_toward_negative_infinity() {
463 // -1 LSB * 0.5 = -0.5 LSB, which an arithmetic shift floors to -1 LSB.
464 let r = Q16_16::from_raw(-1) * Q16_16::pow2_neg(1);
465 assert_eq!(r.raw(), -1);
466 let r = Q16_16::from_raw(1) * Q16_16::pow2_neg(1);
467 assert_eq!(r.raw(), 0);
468 assert_eq!((Q8_8::from_raw(-1) * Q8_8::pow2_neg(1)).raw(), -1);
469 assert_eq!((Q8_8::from_raw(1) * Q8_8::pow2_neg(1)).raw(), 0);
470 }
471
472 #[test]
473 fn multiply_wraps_to_the_storage_width() {
474 // 100.0 * 2.0 = 200.0 does not fit Q8.8; the product wraps to -56.0.
475 let r = Q8_8::from_int(100) * Q8_8::from_int(2);
476 assert_eq!(r, Q8_8::from_int(-56));
477 }
478
479 #[test]
480 fn divide_truncates_toward_zero_and_saturates_on_zero() {
481 assert_eq!((Q16_16::from_raw(-3) / Q16_16::from_int(2)).raw(), -1);
482 assert_eq!((Q16_16::ONE / Q16_16::ZERO).raw(), i32::MAX);
483 assert_eq!((Q16_16::from_int(-1) / Q16_16::ZERO).raw(), i32::MIN);
484 assert_eq!((Q16_16::ZERO / Q16_16::ZERO).raw(), 0);
485 assert_eq!((Q8_8::from_raw(-3) / Q8_8::from_int(2)).raw(), -1);
486 assert_eq!((Q8_8::ONE / Q8_8::ZERO).raw(), i16::MAX);
487 assert_eq!((Q8_8::from_int(-1) / Q8_8::ZERO).raw(), i16::MIN);
488 assert_eq!(Q8_8::ONE.div_int(0).raw(), i16::MAX);
489 }
490
491 #[test]
492 fn pow2_neg_range() {
493 assert_eq!(Q16_16::pow2_neg(16).raw(), 1);
494 assert_eq!(Q16_16::pow2_neg(0), Q16_16::ONE);
495 assert_eq!(Q8_8::pow2_neg(8).raw(), 1);
496 }
497
498 #[test]
499 fn pow2_neg_below_resolution_truncates_to_zero() {
500 for n in [17, 20, 32, 63, 64, u32::MAX] {
501 assert_eq!(
502 Q16_16::pow2_neg(core::hint::black_box(n)),
503 Q16_16::ZERO,
504 "n = {n}"
505 );
506 }
507 assert_eq!(Q8_8::pow2_neg(9), Q8_8::ZERO);
508 }
509
510 #[test]
511 fn add_wraps() {
512 let r = Q16_16::from_raw(i32::MAX) + Q16_16::from_raw(1);
513 assert_eq!(r.raw(), i32::MIN);
514 let r = Q8_8::from_raw(i16::MAX) + Q8_8::from_raw(1);
515 assert_eq!(r.raw(), i16::MIN);
516 }
517
518 #[test]
519 fn zero_tolerance() {
520 assert!(Q16_16::from_raw(511).is_within_zero_tolerance());
521 assert!(Q16_16::from_raw(-511).is_within_zero_tolerance());
522 assert!(!Q16_16::from_raw(512).is_within_zero_tolerance());
523 assert!(Q8_8::from_raw(1).is_within_zero_tolerance());
524 assert!(Q8_8::from_raw(-1).is_within_zero_tolerance());
525 assert!(!Q8_8::from_raw(2).is_within_zero_tolerance());
526 assert!(!Q8_8::from_raw(-2).is_within_zero_tolerance());
527 }
528}