tinymind 0.2.0

Neural networks for embedded Rust: a no_std, allocation-free port of the tinymind (C++) library, bit-exact with it
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Host-side calibration: turning float scales into the integer parameters the
//! int8 layers use (C++ `quantizeMultiplier`, `buildRequantizer`, `quantize`,
//! `dequantize`, `buildQSigmoidLUT`, `buildQTanhLUT`,
//! `buildQSoftmaxFixedPointParams`, `computeAffineParamsAsymmetric`,
//! `computeAffineParamsSymmetric`, `computePerChannelSymmetricScales`, the
//! `RangeObserver`, `buildQAddParams`, `buildRescaler`,
//! `buildQMulRequantizer`).
//!
//! Needs the `std` feature, for `f32::exp` and `f32::tanh`; tinymind (C++) gates the
//! same functions on `TINYMIND_ENABLE_FLOAT && TINYMIND_ENABLE_STD`. On a device,
//! run these on the host and embed the results as constants. The float
//! arithmetic follows the C++ step for step, so the tables and requantizers match
//! the C++ ones on the same platform: `exp` and `tanh` come from the system math
//! library in both.

use super::{LUT_SIZE, QAdd, QSoftmax, Requantizer};

/// C `frexp`: `x = mantissa * 2^exponent` with `|mantissa|` in `[0.5, 1)`.
/// Zero, infinities and NaN come back unchanged with exponent 0.
fn frexp(x: f64) -> (f64, i32) {
    if x == 0.0 || !x.is_finite() {
        return (x, 0);
    }
    let bits = x.to_bits();
    let biased = ((bits >> 52) & 0x7ff) as i32;
    if biased == 0 {
        // Subnormal: scale into the normal range first.
        let (m, e) = frexp(x * f64::from_bits(0x4350_0000_0000_0000)); // 2^54
        return (m, e - 54);
    }
    let mantissa = f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52));
    (mantissa, biased - 1022)
}

/// Decompose a positive real scale ratio into a Q0.31 multiplier and a shift
/// (C++ `quantizeMultiplier`). Returns `(multiplier, shift)`: `shift < 0` for a
/// ratio above 1, `shift > 0` below 1. A zero ratio gives `(0, 0)`.
///
/// The shift always lies in `-31..=31`, the [`Requantizer`]'s contract. A ratio
/// below 2^-32 rounds every `i32` accumulator to 0 and comes back as `(0, 0)`;
/// a ratio of 2^31 or more gets shift -31, which already saturates every
/// non-zero accumulator.
pub fn quantize_multiplier(ratio: f64) -> (i32, i32) {
    if ratio == 0.0 {
        return (0, 0);
    }
    let (mantissa, mut exponent) = frexp(ratio);
    // C++ llround: round half away from zero, as f64::round does.
    let mut q = (mantissa * (1i64 << 31) as f64).round() as i64;
    // The mantissa can round up to exactly 2^31; renormalise.
    if q == 1i64 << 31 {
        q >>= 1;
        exponent += 1;
    }
    let shift = -exponent;
    if shift > 31 {
        (0, 0)
    } else {
        (q as i32, shift.max(-31))
    }
}

/// Build a [`Requantizer`] for `(input_scale * weight_scale) / output_scale`
/// (C++ `buildRequantizer<int8_t>`). The zero point and bounds are narrowed to
/// `i8` as the C++ `static_cast` does.
pub fn build_requantizer(
    input_scale: f32,
    weight_scale: f32,
    output_scale: f32,
    output_zero_point: i32,
    qmin: i32,
    qmax: i32,
) -> Requantizer {
    let ratio = (f64::from(input_scale) * f64::from(weight_scale)) / f64::from(output_scale);
    let (multiplier, shift) = quantize_multiplier(ratio);
    Requantizer {
        multiplier,
        shift,
        zero_point: output_zero_point as i8,
        qmin: qmin as i8,
        qmax: qmax as i8,
    }
}

/// A requantizer for a pure rescale, `input_scale / output_scale`, with no
/// weight: for [`QConcat`](super::QConcat) inputs and anything else that
/// copies values from one grid to another (C++ `buildRescaler`, which is
/// `buildRequantizer` with a weight scale of 1).
pub fn build_rescaler(
    input_scale: f32,
    output_scale: f32,
    output_zero_point: i32,
    qmin: i32,
    qmax: i32,
) -> Requantizer {
    build_requantizer(
        input_scale,
        1.0,
        output_scale,
        output_zero_point,
        qmin,
        qmax,
    )
}

/// The requantizer of a [`QMul`](super::QMul): `input_a_scale * input_b_scale /
/// output_scale`, in `f64` from the `f32` scales (C++ `buildQMulRequantizer`;
/// the same ratio as [`build_requantizer`] with the second input's scale as the
/// weight scale).
pub fn build_mul_requantizer(
    input_a_scale: f32,
    input_b_scale: f32,
    output_scale: f32,
    output_zero_point: i32,
    qmin: i32,
    qmax: i32,
) -> Requantizer {
    build_requantizer(
        input_a_scale,
        input_b_scale,
        output_scale,
        output_zero_point,
        qmin,
        qmax,
    )
}

/// Build a [`QAdd`] for inputs `(scale, zero point)` `input_a` and `input_b`
/// and output `output` (C++ `buildQAddParams` with its default left shift of 20,
/// TFLite's). Both inputs are rescaled to twice the larger input scale; ratios
/// are formed in `f64` from the `f32` scales, as the C++ does. Zero points and
/// bounds are narrowed to `i8`; raise `qmin` to the output zero point to fuse a
/// ReLU.
pub fn build_add(
    input_a: (f32, i32),
    input_b: (f32, i32),
    output: (f32, i32),
    qmin: i32,
    qmax: i32,
) -> QAdd {
    const LEFT_SHIFT: i32 = 20;
    let (a_scale, b_scale) = (input_a.0, input_b.0);
    // The C++ comparison, so equal or NaN scales take the same branch.
    let max_in = if a_scale > b_scale { a_scale } else { b_scale };
    let twice_max = 2.0 * f64::from(max_in);
    let real_a = f64::from(a_scale) / twice_max;
    let real_b = f64::from(b_scale) / twice_max;
    let real_out = twice_max / ((1i64 << LEFT_SHIFT) as f64 * f64::from(output.0));
    let (input_a_multiplier, input_a_shift) = quantize_multiplier(real_a);
    let (input_b_multiplier, input_b_shift) = quantize_multiplier(real_b);
    let (multiplier, shift) = quantize_multiplier(real_out);
    QAdd {
        input_a_zero_point: input_a.1 as i8,
        input_b_zero_point: input_b.1 as i8,
        left_shift: LEFT_SHIFT,
        input_a_multiplier,
        input_a_shift,
        input_b_multiplier,
        input_b_shift,
        output_requantizer: Requantizer {
            multiplier,
            shift,
            zero_point: output.1 as i8,
            qmin: qmin as i8,
            qmax: qmax as i8,
        },
    }
}

/// Symmetric affine parameters `(scale, 0)` covering `[fmin, fmax]`: the scale
/// maps the larger magnitude to `qmax` (C++ `computeAffineParamsSymmetric`).
/// A range of zeros, or a `qmax` of 0 or below, gives scale 1.0.
pub fn affine_params_symmetric(fmin: f32, fmax: f32, qmax: i32) -> (f32, i32) {
    // Comparisons as the C++ writes them, so a NaN takes the same branch.
    let abs_min = if fmin < 0.0 { -fmin } else { fmin };
    let abs_max = if fmax < 0.0 { -fmax } else { fmax };
    let absmax = if abs_min > abs_max { abs_min } else { abs_max };
    if absmax == 0.0 || qmax <= 0 {
        return (1.0, 0);
    }
    (absmax / qmax as f32, 0)
}

/// The running minimum and maximum of the values it has observed, for fitting
/// an activation's scale from calibration inputs (C++ `RangeObserver`). Before
/// any observation the range is `[0, 0]`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RangeObserver {
    /// Smallest value observed.
    pub min_value: f32,
    /// Largest value observed.
    pub max_value: f32,
    /// Whether anything has been observed.
    pub has_data: bool,
}

impl RangeObserver {
    /// An observer with nothing observed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Widen the range to include `x`. The first value sets both ends.
    pub fn observe(&mut self, x: f32) {
        if !self.has_data {
            self.min_value = x;
            self.max_value = x;
            self.has_data = true;
        } else {
            if x < self.min_value {
                self.min_value = x;
            }
            if x > self.max_value {
                self.max_value = x;
            }
        }
    }

    /// [`observe`](Self::observe) each value in order.
    pub fn observe_all(&mut self, xs: &[f32]) {
        for &x in xs {
            self.observe(x);
        }
    }
}

/// Asymmetric per-tensor affine parameters `(scale, zero_point)` that map the
/// real range `[fmin, fmax]`, widened to include 0, onto `[qmin, qmax]` (C++
/// `computeAffineParamsAsymmetric`). An empty range gives `(1.0, qmin)`.
pub fn affine_params_asymmetric(fmin: f32, fmax: f32, qmin: i32, qmax: i32) -> (f32, i32) {
    // `if`s rather than min/max, which treat NaN differently from the C++.
    let fmin = if fmin > 0.0 { 0.0 } else { fmin };
    let fmax = if fmax < 0.0 { 0.0 } else { fmax };
    let qrange = qmax.wrapping_sub(qmin) as f32;
    if fmax == fmin || qrange == 0.0 {
        return (1.0, qmin);
    }
    let scale = (fmax - fmin) / qrange;
    // C++ lround: half away from zero, as f64::round.
    let mut zp = (f64::from(qmin) - f64::from(fmin) / f64::from(scale)).round() as i64;
    if zp < i64::from(qmin) {
        zp = i64::from(qmin);
    }
    if zp > i64::from(qmax) {
        zp = i64::from(qmax);
    }
    (scale, zp as i32)
}

/// One symmetric weight scale per output channel, `max |w| / qmax` over each
/// channel's weights (C++ `computePerChannelSymmetricScales`), as TFLite
/// quantizes depthwise and convolution weights. A channel of zeros, or a
/// `qmax` of 0 or below, gets scale 1.0.
pub fn per_channel_symmetric_scales<const C: usize, const N: usize>(
    weights: &[[f32; N]; C],
    qmax: i32,
) -> [f32; C] {
    let mut scales = [1.0f32; C];
    for (scale, channel) in scales.iter_mut().zip(weights) {
        // Comparisons as the C++ writes them, so a NaN is skipped the same way.
        let mut absmax = 0.0f32;
        for &v in channel {
            let a = if v < 0.0 { -v } else { v };
            if a > absmax {
                absmax = a;
            }
        }
        if absmax != 0.0 && qmax > 0 {
            *scale = absmax / qmax as f32;
        }
    }
    scales
}

/// Quantize a real value to int8: `round(x / scale) + zero_point`, ties away
/// from zero (as TFLite), saturated to `[qmin, qmax]` (C++ `quantize<int8_t>`).
pub fn quantize(x: f32, scale: f32, zero_point: i32, qmin: i32, qmax: i32) -> i8 {
    let q = (f64::from(x) / f64::from(scale)).round() + f64::from(zero_point);
    let mut qi = q as i64;
    if qi < i64::from(qmin) {
        qi = i64::from(qmin);
    }
    if qi > i64::from(qmax) {
        qi = i64::from(qmax);
    }
    qi as i8
}

/// The real value an int8 stands for: `scale * (q - zero_point)` (C++
/// `dequantize<int8_t>`).
pub fn dequantize(q: i8, scale: f32, zero_point: i32) -> f32 {
    scale * (i32::from(q) - zero_point) as f32
}

/// Round to nearest, ties away from zero, and saturate to int8 (C++
/// `qSaturateRoundToInt8`).
fn saturate_round_to_i8(v: f32) -> i8 {
    (f64::from(v).round() as i64).clamp(-128, 127) as i8
}

/// A 256-entry lookup table for `f` from the input tensor's grid to the output
/// tensor's: dequantize each int8, apply `f`, requantize.
fn build_lut(
    input_scale: f32,
    input_zero_point: i32,
    output_scale: f32,
    output_zero_point: i32,
    f: impl Fn(f32) -> f32,
) -> [i8; LUT_SIZE] {
    core::array::from_fn(|index| {
        let x = index as i32 - 128;
        let x_real = input_scale * (x - input_zero_point) as f32;
        let y_q = output_zero_point as f32 + f(x_real) / output_scale;
        saturate_round_to_i8(y_q)
    })
}

/// Sigmoid lookup table, `1 / (1 + exp(-x))` (C++ `buildQSigmoidLUT`). An output
/// grid of scale 1/256 and zero point -128 uses the full int8 range.
pub fn build_sigmoid_lut(
    input_scale: f32,
    input_zero_point: i32,
    output_scale: f32,
    output_zero_point: i32,
) -> [i8; LUT_SIZE] {
    build_lut(
        input_scale,
        input_zero_point,
        output_scale,
        output_zero_point,
        |x| 1.0 / (1.0 + (-x).exp()),
    )
}

/// Tanh lookup table (C++ `buildQTanhLUT`). An output grid of scale 1/128 and
/// zero point 0 uses the full int8 range.
pub fn build_tanh_lut(
    input_scale: f32,
    input_zero_point: i32,
    output_scale: f32,
    output_zero_point: i32,
) -> [i8; LUT_SIZE] {
    build_lut(
        input_scale,
        input_zero_point,
        output_scale,
        output_zero_point,
        f32::tanh,
    )
}

/// [`QSoftmax`] parameters for an input tensor of scale `input_scale` and a
/// softmax of `beta` (1.0 for a plain softmax), computed as TFLite Micro does
/// for an int8 softmax (`PreprocessSoftmaxScaling` with 5 integer bits, then
/// `CalculateInputRadius`; C++ `buildQSoftmaxFixedPointParams`).
pub fn build_softmax(input_scale: f64, beta: f64) -> QSoftmax {
    const INPUT_INTEGER_BITS: i32 = 5;
    let max_real_multiplier = ((1i64 << 31) - 1) as f64;
    let mut real_multiplier = beta * input_scale * (1i64 << (31 - INPUT_INTEGER_BITS)) as f64;
    if real_multiplier > max_real_multiplier {
        real_multiplier = max_real_multiplier;
    }

    // quantize_multiplier returns shift = -exponent; a multiplier above one is
    // a left shift.
    let (input_multiplier, shift) = quantize_multiplier(real_multiplier);
    let input_left_shift = -shift;

    // 2^input_left_shift is exact in f64 (the C++ shifts an int64).
    let max_input_rescaled = f64::from((1 << INPUT_INTEGER_BITS) - 1)
        * (1i64 << (31 - INPUT_INTEGER_BITS)) as f64
        / 2f64.powi(input_left_shift);
    QSoftmax {
        input_multiplier,
        input_left_shift,
        diff_min: (max_input_rescaled.floor() as i32).saturating_neg(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Known answers from tinymind unit_test/quantization.
    #[test]
    fn quantize_multiplier_cases() {
        assert_eq!(quantize_multiplier(0.0), (0, 0));
        // frexp(1.0) = 0.5 * 2^1.
        assert_eq!(quantize_multiplier(1.0), (1 << 30, -1));
        assert_eq!(quantize_multiplier(0.5), (1 << 30, 0));
        // A mantissa that rounds up to 2^31 is renormalised.
        assert_eq!(quantize_multiplier(1.0 - 1e-10), (1 << 30, -1));
        // The shift stays in -31..=31 (tinymind #247); values from the C++.
        assert_eq!(quantize_multiplier(2f64.powi(-31)), (1 << 30, 30));
        assert_eq!(quantize_multiplier(2f64.powi(-32)), (1 << 30, 31));
        assert_eq!(quantize_multiplier(0.75 * 2f64.powi(-32)), (0, 0));
        assert_eq!(quantize_multiplier(2f64.powi(-40)), (0, 0));
        assert_eq!(quantize_multiplier(1e-12), (0, 0));
        assert_eq!(quantize_multiplier(2f64.powi(30)), (1 << 30, -31));
        assert_eq!(quantize_multiplier(2f64.powi(31)), (1 << 30, -31));
        assert_eq!(
            quantize_multiplier(0.75 * 2f64.powi(32)),
            (1_610_612_736, -31)
        );
        assert_eq!(quantize_multiplier(2f64.powi(40)), (1 << 30, -31));
        assert_eq!(quantize_multiplier(1e15), (1_907_348_633, -31));
        // A ratio below 2^-32 rounds every accumulator to 0, so the output is
        // the zero point; a left shift past 31 saturates exactly as 31 does.
        let rq = |(multiplier, shift)| Requantizer {
            multiplier,
            shift,
            zero_point: 3,
            qmin: -128,
            qmax: 127,
        };
        for acc in [i32::MIN, -1 << 20, -2, -1, 0, 1, 2, 1 << 20, i32::MAX] {
            assert_eq!(rq(quantize_multiplier(2f64.powi(-40))).apply(acc), 3);
            assert_eq!(rq((1 << 30, -41)).apply(acc), rq((1 << 30, -31)).apply(acc));
        }
        let unity = build_requantizer(1.0, 1.0, 1.0, 0, -128, 127);
        assert_eq!(unity.apply(42), 42);
        let half = build_requantizer(1.0, 0.5, 1.0, 0, -128, 127);
        assert_eq!(half.apply(100), 50);
    }

    #[test]
    fn frexp_matches_c() {
        for (x, m, e) in [
            (1.0, 0.5, 1),
            (0.75, 0.75, 0),
            (3.0, 0.75, 2),
            (-3.0, -0.75, 2),
            (f64::MIN_POSITIVE, 0.5, -1021),
            (f64::MIN_POSITIVE / 4.0, 0.5, -1023),
        ] {
            assert_eq!(frexp(x), (m, e), "frexp({x})");
        }
    }

    #[test]
    fn quantize_rounds_half_away_and_saturates() {
        assert_eq!(quantize(0.5, 1.0, 0, -128, 127), 1);
        assert_eq!(quantize(-0.5, 1.0, 0, -128, 127), -1);
        assert_eq!(quantize(1000.0, 1.0, 0, -128, 127), 127);
        assert_eq!(quantize(-1000.0, 1.0, 0, -128, 127), -128);
        assert_eq!(dequantize(-128, 0.5, -128), 0.0);
    }

    #[test]
    fn range_observer_starts_from_its_first_value() {
        let mut obs = RangeObserver::new();
        assert!(!obs.has_data);
        obs.observe(5.0);
        assert_eq!((obs.min_value, obs.max_value), (5.0, 5.0));
        obs.observe_all(&[7.0, 6.0, 2.5]);
        assert_eq!((obs.min_value, obs.max_value), (2.5, 7.0));
        assert!(obs.has_data);
    }

    #[test]
    fn symmetric_params_cover_the_larger_magnitude() {
        assert_eq!(affine_params_symmetric(-4.0, 2.0, 127), (4.0 / 127.0, 0));
        assert_eq!(affine_params_symmetric(-1.0, 3.0, 127), (3.0 / 127.0, 0));
        assert_eq!(affine_params_symmetric(0.0, 0.0, 127), (1.0, 0));
        assert_eq!(affine_params_symmetric(-1.0, 1.0, 0), (1.0, 0));
    }
}