Skip to main content

tinymind/
int8.rs

1//! Int8 affine-quantized inference, ported from tinymind (C++) `cpp/qaffine.hpp`,
2//! `cpp/qdense.hpp`, `cpp/qconv2d.hpp`, `cpp/qdepthwiseconv2d.hpp`,
3//! `cpp/qpointwiseconv2d.hpp`, `cpp/qpool2d.hpp`, `cpp/qadd.hpp`, `cpp/qmul.hpp`,
4//! `cpp/qpad.hpp`, `cpp/qconcat.hpp`, `cpp/qactivations.hpp`,
5//! `cpp/qsoftmax_fixedpoint.hpp`, `cpp/qlstm.hpp`, `cpp/qgru.hpp` and
6//! `cpp/qfft1d.hpp`.
7//!
8//! This is the TFLite / CMSIS-NN quantization model, separate from the Q-format
9//! [`QValue`](crate::QValue) pipeline: a real value is `scale * (q - zero_point)`,
10//! with int8 activations (asymmetric, any zero point), int8 weights (symmetric,
11//! zero point 0) and int32 biases and accumulators. Everything here is pure
12//! integer arithmetic at run time; turning float scales into the integer
13//! parameters is host-side work, in `calibration` (`std` feature).
14//!
15//! A layer computes `acc[o] = bias[o] + sum_i weight[o][i] * (input[i] - input_zero_point)`
16//! in `i32`, then a [`Requantizer`] rescales `acc` to the output tensor's int8 grid
17//! with a fixed-point multiplier, adds the output zero point and saturates.
18//!
19//! Layers run fastest as `const` or `static` items, as the importers generate
20//! them: the compiler then folds their weights and requantizers into the code.
21//! A layer built from values known only at run time gives the same results
22//! more slowly; on a Cortex-M4 a convolution over one input channel took about
23//! twice as long.
24//!
25//! # Convolution and pooling
26//!
27//! [`QConv2D`] (and [`QConv2DPerChannel`]), [`QDepthwiseConv2D`],
28//! [`QPointwiseConv2D`] (and [`QPointwiseConv2DPerChannel`]), [`QMaxPool2D`],
29//! [`QAvgPool2D`] and [`QGlobalAvgPool2D`] work on NHWC tensors without the batch
30//! axis, as nested arrays: an input is `[[[i8; C]; W]; H]`, indexed
31//! `[row][column][channel]`. Kernel, strides and padding are const parameters of
32//! the layer; the input and output sizes come from the arrays passed to
33//! `forward`, which writes into a caller-owned output so tensors can share
34//! buffers. The output must have the size the layer produces, `(H + PT + PB -
35//! KH) / SH + 1` rows and likewise columns, or the call does not compile; an
36//! invalid layer (a zero stride, a kernel larger than the padded input) does not
37//! compile either. Padding holds the input zero point, as TFLite pads, so a
38//! padded tap contributes nothing. Pooling keeps the input's scale and zero
39//! point: no requantizer.
40//!
41//! A convolution over two or more input channels widens its input rows and
42//! each filter's weights to 16 bits and adds the products in pairs. On cores
43//! with the DSP extension (Cortex-M4, M7, M33), LLVM can turn each pair into
44//! one `SMLAD` instruction, from this plain Rust, but by default it gives up
45//! on long unrolled sums. Building with `-C
46//! llvm-args=-arm-parallel-dsp-load-limit=512` (in the target's `rustflags`)
47//! lets it pair them: on an STM32F411 the MLPerf Tiny ResNet-8 then takes 35%
48//! fewer cycles. It is an LLVM internal option, not a stable Rust one.
49//!
50//! ```
51//! use tinymind::int8::{QConv2D, QMaxPool2D, Requantizer};
52//!
53//! // Eight 3x3 filters over a 20x20 single-channel input, then 2x2 max pooling.
54//! static WEIGHTS: [[[[i8; 1]; 3]; 3]; 8] = [[[[1]; 3]; 3]; 8];
55//! const RQ: Requantizer = Requantizer { multiplier: 1 << 30, shift: 3, zero_point: 0, qmin: -128, qmax: 127 };
56//! let conv: QConv2D<'_, 1, 3, 3, 8> =
57//!     QConv2D { weights: &WEIGHTS, biases: None, input_zero_point: 0, requantizer: RQ };
58//!
59//! let input = [[[2i8; 1]; 20]; 20];
60//! let mut features = [[[0i8; 8]; 18]; 18]; // 3x3, stride 1, no padding: 18 x 18
61//! conv.forward(&input, &mut features);
62//! let mut pooled = [[[0i8; 8]; 9]; 9]; // 2x2 windows: 9 x 9
63//! QMaxPool2D::<2, 2>.forward(&features, &mut pooled);
64//! // Each window sums nine 2s; the requantizer scales by 1/16: 18/16 rounds to 1.
65//! assert_eq!(pooled[0][0], [1; 8]);
66//! ```
67//!
68//! An output of the wrong size does not compile:
69//!
70//! ```compile_fail
71//! # use tinymind::int8::{QConv2D, Requantizer};
72//! # static WEIGHTS: [[[[i8; 1]; 3]; 3]; 8] = [[[[1]; 3]; 3]; 8];
73//! # const RQ: Requantizer = Requantizer { multiplier: 1 << 30, shift: 3, zero_point: 0, qmin: -128, qmax: 127 };
74//! # let conv: QConv2D<'_, 1, 3, 3, 8> =
75//! #     QConv2D { weights: &WEIGHTS, biases: None, input_zero_point: 0, requantizer: RQ };
76//! let input = [[[2i8; 1]; 20]; 20];
77//! let mut features = [[[0i8; 8]; 17]; 18]; // 17 columns: the layer makes 18
78//! conv.forward(&input, &mut features);
79//! ```
80//!
81//! [`QAdd`] adds two tensors of the same shape with their own scales and zero
82//! points (TFLite ADD), for residual connections, and [`QMul`] multiplies them
83//! (TFLite MUL, squeeze-and-excite gating). [`QPad2D`] pads a tensor with a
84//! constant and [`QConcat`] joins two along the channel axis.
85//!
86//! # Recurrent cells
87//!
88//! [`QLstmCell`] and [`QGruCell`] run one time step of an int8 LSTM or GRU
89//! cell, updating the caller's hidden state (and the LSTM's cell state, `i8`
90//! or `i16`) in place; the caller runs the time loop over a sequence. Weights
91//! are gate-major, `[gate][unit][input]`: PyTorch's `nn.LSTM` stacks its gates
92//! in the same order (i, f, g, o), so its weight matrices map onto them
93//! directly (add its two bias vectors, `bias_ih` and `bias_hh`, before
94//! quantizing them). The GRU applies its reset gate before the recurrent
95//! multiply, as Keras does with `reset_after=False` (whose kernels store the
96//! gates as update, reset, new, so reorder them); PyTorch's `nn.GRU` and Keras' default
97//! apply it after, which is a different function. The gate
98//! activations come from 256-entry sigmoid and tanh tables with fixed output
99//! grids; `calibration` builds the tables and the rescaling parameters from
100//! float scales.
101//!
102//! # FFT
103//!
104//! [`QFft1D`] is a radix-2 FFT for vibration, audio or IMU front ends: 16-bit
105//! samples, Q1.15 twiddle tables borrowed from flash, in place on the caller's
106//! real and imaginary buffers. Its bin magnitudes come out in `i32`, ready for a
107//! [`Requantizer`] onto an int8 grid; `calibration` builds the twiddle tables.
108//! [`QRFft1D`] takes real samples, the usual case for sensors: from the same
109//! tables it computes the `N / 2 + 1` bins that are not redundant with about
110//! half the work.
111//!
112//! # Equivalence with tinymind (C++)
113//!
114//! Results match tinymind (C++) bit for bit, and through it TFLite's reference
115//! kernels for the layers TFLite has (the recurrent cells' table-based gates
116//! are tinymind (C++)'s own, not TFLite's integer LSTM kernel). Where the C++ would hit undefined behaviour
117//! (an `i32` accumulator overflow, a shift out of its documented range), this
118//! port wraps or clamps instead, so every function is total and none panics.
119
120pub(crate) mod add;
121#[cfg(feature = "std")]
122pub mod calibration;
123pub(crate) mod compose;
124pub(crate) mod conv;
125pub(crate) mod fft;
126pub(crate) mod pool;
127pub(crate) mod recurrent;
128
129pub use add::{QAdd, Tensor};
130pub use compose::{QConcat, QMul, QPad2D};
131pub use conv::{
132    QConv2D, QConv2DPerChannel, QDepthwiseConv2D, QPointwiseConv2D, QPointwiseConv2DPerChannel,
133};
134pub use fft::{QFft1D, QRFft1D};
135pub use pool::{QAvgPool2D, QGlobalAvgPool2D, QMaxPool2D};
136pub use recurrent::{CellStorage, QGruCell, QLstmCell};
137
138/// Saturating rounding doubling high multiply: `(a * b + 2^30) >> 31`, the
139/// Q0.31 multiply of gemmlowp and TFLite, with `i32::MIN * i32::MIN` saturated
140/// to `i32::MAX` (C++ `saturatingRoundingDoublingHighMul`).
141pub fn saturating_rounding_doubling_high_mul(a: i32, b: i32) -> i32 {
142    let overflow = a == i32::MIN && b == i32::MIN;
143    // |a * b| <= 2^62, so adding 2^30 cannot overflow i64.
144    let ab = i64::from(a) * i64::from(b);
145    let high = ((ab + (1i64 << 30)) >> 31) as i32;
146    if overflow { i32::MAX } else { high }
147}
148
149/// `x / 2^exponent`, rounded to nearest with gemmlowp's tie rule (C++
150/// `roundingDivideByPOT`). An `exponent` of zero or less returns `x`; the
151/// documented range ends at 31, and larger exponents are treated as 31.
152pub fn rounding_divide_by_pot(x: i32, exponent: i32) -> i32 {
153    if exponent <= 0 {
154        return x;
155    }
156    let exponent = exponent.min(31) as u32;
157    let mask = ((1u32 << exponent) - 1) as i32;
158    let remainder = x & mask;
159    let threshold = (mask >> 1) + i32::from(x < 0);
160    (x >> exponent) + i32::from(remainder > threshold)
161}
162
163/// `rounding_divide_by_pot(saturating_rounding_doubling_high_mul(x, multiplier),
164/// exponent)` in one 64-bit rounding (C++ `roundingHighMulDivideByPOT`). Only
165/// valid for `multiplier >= 0` and `2 <= exponent <= 31`, which
166/// [`Requantizer::apply`] checks before calling it; the two forms then agree bit
167/// for bit (a Kani proof checks that).
168pub(crate) fn rounding_high_mul_divide_by_pot(x: i32, multiplier: i32, exponent: i32) -> i32 {
169    // nudge = 2^(30+e) + 2^30 - [x < 0] * 2^31, assembled from 32-bit halves.
170    let negative = (x as u32) >> 31;
171    let nudge_high = (1u32 << (exponent - 2)).wrapping_sub(negative);
172    let nudge_low = (negative << 31) | 0x4000_0000;
173    let nudge = (u64::from(nudge_high) << 32) | u64::from(nudge_low);
174    // The sum is formed modulo 2^64; its true value fits i64.
175    let v = nudge.wrapping_add((i64::from(x) * i64::from(multiplier)) as u64);
176    ((v >> 32) as u32 as i32) >> (exponent - 1)
177}
178
179/// Rescale an `i32` by a Q0.31 `multiplier` and a power-of-two `shift`, without
180/// zero point or saturation to storage (gemmlowp's "MultiplyByQuantizedMultiplier",
181/// C++ `multiplyByQuantizedMultiplier`). A negative `shift` left-shifts `x` first,
182/// saturating to the `i32` range; a positive one divides the product with
183/// rounding.
184pub fn multiply_by_quantized_multiplier(x: i32, multiplier: i32, shift: i32) -> i32 {
185    let left_shift = if shift < 0 { shift.unsigned_abs() } else { 0 };
186    let right_shift = shift.max(0);
187
188    let shifted = if left_shift > 30 {
189        // Any non-zero x saturates; 2^31 itself is not representable.
190        if x > 0 {
191            i32::MAX
192        } else if x < 0 {
193            i32::MIN
194        } else {
195            0
196        }
197    } else if left_shift > 0 {
198        // x * 2^left_shift fits i32 exactly when x lies in
199        // [-2^(31 - left_shift), 2^(31 - left_shift) - 1].
200        let limit = i32::MAX >> left_shift;
201        if x > limit {
202            i32::MAX
203        } else if x < -limit - 1 {
204            i32::MIN
205        } else {
206            x * (1 << left_shift)
207        }
208    } else {
209        x
210    };
211
212    rounding_divide_by_pot(
213        saturating_rounding_doubling_high_mul(shifted, multiplier),
214        right_shift,
215    )
216}
217
218/// `x * 2^n`, saturated to the `i32` range, for [`QAdd`]: the left shift in
219/// [`multiply_by_quantized_multiplier`].
220pub(crate) fn saturating_shl(x: i32, n: u32) -> i32 {
221    if n > 30 {
222        // Any non-zero x saturates; 2^31 itself is not representable.
223        if x > 0 {
224            i32::MAX
225        } else if x < 0 {
226            i32::MIN
227        } else {
228            0
229        }
230    } else if n > 0 {
231        // x * 2^n fits i32 exactly when x lies in [-2^(31 - n), 2^(31 - n) - 1].
232        let limit = i32::MAX >> n;
233        if x > limit {
234            i32::MAX
235        } else if x < -limit - 1 {
236            i32::MIN
237        } else {
238            x * (1 << n)
239        }
240    } else {
241        x
242    }
243}
244
245/// Rescales an `i32` accumulator to int8 storage (C++ `Requantizer<int32_t,
246/// int8_t>`).
247///
248/// `multiplier` (Q0.31) and `shift` encode the ratio
249/// `input_scale * weight_scale / output_scale`, and a negative `shift` means the
250/// ratio is above one. `zero_point` is the output tensor's, and the result
251/// saturates to `[qmin, qmax]` (usually `[-128, 127]`; raise `qmin` to the zero
252/// point to fuse a ReLU). Build one from float scales with
253/// `calibration::build_requantizer` on the host (`std` feature), or write the
254/// five integers out as constants.
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256pub struct Requantizer {
257    /// Q0.31 fixed-point multiplier, normally in `[2^30, 2^31)`.
258    pub multiplier: i32,
259    /// Power-of-two exponent: positive divides, negative multiplies. tinymind (C++)'s
260    /// contract is `-31..=31` (what `calibration::quantize_multiplier` returns);
261    /// outside it the result is still defined (see the module docs).
262    pub shift: i32,
263    /// Output tensor zero point.
264    pub zero_point: i8,
265    /// Lowest output value.
266    pub qmin: i8,
267    /// Highest output value.
268    pub qmax: i8,
269}
270
271impl Requantizer {
272    /// Rescale `acc`, add the zero point and saturate to `[qmin, qmax]`.
273    pub fn apply(&self, acc: i32) -> i8 {
274        let scaled = if self.one_rounding() {
275            // The common case (a scale ratio below 0.25): one rounding, equal to
276            // the two-step form below bit for bit.
277            rounding_high_mul_divide_by_pot(acc, self.multiplier, self.shift)
278        } else {
279            // This path can reach the i32 rails, where adding the zero point
280            // would overflow; clamping to +-2^30 first gives the same final
281            // result for int8 storage.
282            let rail = 1 << 30;
283            multiply_by_quantized_multiplier(acc, self.multiplier, self.shift).clamp(-rail, rail)
284        };
285        self.add_zero_point_and_clamp(scaled)
286    }
287
288    /// True when [`apply`](Self::apply) takes its one-rounding path: a
289    /// non-negative multiplier and a shift in `2..=31` (a scale ratio below
290    /// 0.25), as in nearly every imported layer (C++ `oneRounding`).
291    #[inline]
292    pub(crate) fn one_rounding(&self) -> bool {
293        self.multiplier >= 0 && (2..=31).contains(&self.shift)
294    }
295
296    /// [`apply`](Self::apply) for a requantizer with [`one_rounding`] true:
297    /// the same result without the general path's code (C++
298    /// `applyOneRounding`). Dense layers check every requantizer once and then
299    /// run a loop that calls only this, so the general path does not hold
300    /// registers in their output loop (on the Cortex-M0+, whose instructions
301    /// mostly reach eight registers, it made the dot product spill). The shift
302    /// is masked so that a call outside that contract stays total.
303    ///
304    /// [`one_rounding`]: Self::one_rounding
305    #[inline]
306    pub(crate) fn apply_one_rounding(&self, acc: i32) -> i8 {
307        let shift = 2 + (self.shift.wrapping_sub(2) & 31).min(29);
308        self.add_zero_point_and_clamp(rounding_high_mul_divide_by_pot(acc, self.multiplier, shift))
309    }
310
311    /// Add the zero point to a rescaled accumulator and saturate.
312    #[inline]
313    fn add_zero_point_and_clamp(&self, scaled: i32) -> i8 {
314        let mut with_zp = scaled + i32::from(self.zero_point);
315        // Two separate tests, as in the C++: with qmin > qmax the result is
316        // qmax (and `clamp` would panic).
317        if with_zp < i32::from(self.qmin) {
318            with_zp = i32::from(self.qmin);
319        }
320        if with_zp > i32::from(self.qmax) {
321            with_zp = i32::from(self.qmax);
322        }
323        with_zp as i8
324    }
325}
326
327/// [`Requantizer::apply`] with the work that does not depend on the
328/// accumulator done once (C++ `detail::FastRequantizer`): on the fused path
329/// the output zero point folds into the rounding nudge. The C++ form takes
330/// only the full int8 range; this one also takes the narrower ranges of a fused
331/// ReLU, saturating in `apply`'s order. Layers prepare one per filter
332/// and run their pixel loop once per form. A Kani proof checks it equals
333/// `apply` for every accumulator wherever [`FastRequantizer::new`] accepts the
334/// requantizer.
335#[derive(Clone, Copy, Debug)]
336pub(crate) struct FastRequantizer {
337    multiplier: i32,
338    nudge_high: u32,
339    high_shift: u32,
340    qmin: i32,
341    qmax: i32,
342}
343
344impl FastRequantizer {
345    /// The fast form, or `None` where `apply` must take its general path: a
346    /// negative multiplier, a shift outside `2..=31`, or a zero-point term
347    /// above 2^29 (which could carry out of the nudge's high word).
348    pub(crate) fn new(rq: &Requantizer) -> Option<Self> {
349        if rq.multiplier < 0 || !(2..=31).contains(&rq.shift) {
350            return None;
351        }
352        let zp_term = i64::from(rq.zero_point) * (1i64 << (rq.shift - 1));
353        if zp_term.abs() > 1 << 29 {
354            return None;
355        }
356        Some(FastRequantizer {
357            multiplier: rq.multiplier,
358            nudge_high: ((1i64 << (rq.shift - 2)) + zp_term) as u32,
359            high_shift: (rq.shift - 1) as u32,
360            qmin: rq.qmin.into(),
361            qmax: rq.qmax.into(),
362        })
363    }
364
365    /// `rq.apply(acc)` for the requantizer this was prepared from.
366    #[inline]
367    pub(crate) fn apply(&self, acc: i32) -> i8 {
368        let negative = (acc as u32) >> 31;
369        let high = self.nudge_high.wrapping_sub(negative);
370        let low = (negative << 31) | 0x4000_0000;
371        let nudge = (u64::from(high) << 32) | u64::from(low);
372        let v = nudge.wrapping_add((i64::from(acc) * i64::from(self.multiplier)) as u64);
373        let mut r = ((v >> 32) as u32 as i32) >> (self.high_shift & 31);
374        // Two tests in `apply`'s order: with qmin > qmax the result is qmax.
375        if r < self.qmin {
376            r = self.qmin;
377        }
378        if r > self.qmax {
379            r = self.qmax;
380        }
381        r as i8
382    }
383}
384
385/// `sum_i w[i] * (x[i] - zero_point)` in `i32` (C++
386/// `dotProductWithZeroPoint`, scalar path). The sum wraps on overflow, which
387/// needs vectors far longer than any layer here.
388fn dot_with_zero_point<const N: usize>(x: &[i8; N], w: &[i8; N], zero_point: i8) -> i32 {
389    x.iter().zip(w).fold(0i32, |acc, (&x, &w)| {
390        acc.wrapping_add(i32::from(w) * (i32::from(x) - i32::from(zero_point)))
391    })
392}
393
394/// A quantized fully connected layer with `IN` int8 inputs and `OUT` int8
395/// outputs (C++ `QDense<int8_t, int8_t, int32_t, int8_t, IN, OUT>`).
396///
397/// The layer borrows its weights and biases, so they can live in flash as
398/// `static` or `const` data. Weights are `weights[output][input]` (row-major,
399/// as PyTorch and TFLite store them), symmetric int8. Biases are in the
400/// accumulator's scale (`input_scale * weight_scale`); `None` means no bias.
401#[derive(Clone, Copy, Debug)]
402pub struct QDense<'a, const IN: usize, const OUT: usize> {
403    /// `weights[o][i]`: weight from input `i` to output `o`.
404    pub weights: &'a [[i8; IN]; OUT],
405    /// One `i32` bias per output, or `None`.
406    pub biases: Option<&'a [i32; OUT]>,
407    /// The input tensor's zero point.
408    pub input_zero_point: i8,
409    /// Rescales each accumulator to the output tensor's grid.
410    pub requantizer: Requantizer,
411}
412
413impl<const IN: usize, const OUT: usize> QDense<'_, IN, OUT> {
414    /// One forward pass.
415    pub fn forward(&self, input: &[i8; IN]) -> [i8; OUT] {
416        let rq = &self.requantizer;
417        if rq.one_rounding() {
418            self.forward_with(input, |acc| rq.apply_one_rounding(acc))
419        } else {
420            self.forward_with(input, |acc| rq.apply(acc))
421        }
422    }
423
424    /// The output loop, with the requantizer's form chosen once by `forward`.
425    #[inline(always)]
426    fn forward_with(&self, input: &[i8; IN], requantize: impl Fn(i32) -> i8) -> [i8; OUT] {
427        let mut output = [0i8; OUT];
428        for (o, (out, row)) in output.iter_mut().zip(self.weights).enumerate() {
429            let bias = self.biases.map_or(0, |b| b.get(o).copied().unwrap_or(0));
430            let acc = bias.wrapping_add(dot_with_zero_point(input, row, self.input_zero_point));
431            *out = requantize(acc);
432        }
433        output
434    }
435}
436
437/// A quantized fully connected layer with one [`Requantizer`] per output: the
438/// per-channel weight quantization TFLite applies to dense layers by default
439/// (C++ `QPointwiseConv2DPerChannel` over a 1x1 input, which is a dense layer).
440/// Otherwise the same as [`QDense`].
441#[derive(Clone, Copy, Debug)]
442pub struct QDensePerChannel<'a, const IN: usize, const OUT: usize> {
443    /// `weights[o][i]`: weight from input `i` to output `o`.
444    pub weights: &'a [[i8; IN]; OUT],
445    /// One `i32` bias per output, or `None`.
446    pub biases: Option<&'a [i32; OUT]>,
447    /// The input tensor's zero point.
448    pub input_zero_point: i8,
449    /// `requantizers[o]` rescales output `o`.
450    pub requantizers: &'a [Requantizer; OUT],
451}
452
453impl<const IN: usize, const OUT: usize> QDensePerChannel<'_, IN, OUT> {
454    /// One forward pass.
455    pub fn forward(&self, input: &[i8; IN]) -> [i8; OUT] {
456        if self.requantizers.iter().all(Requantizer::one_rounding) {
457            self.forward_with(input, Requantizer::apply_one_rounding)
458        } else {
459            self.forward_with(input, Requantizer::apply)
460        }
461    }
462
463    /// The output loop, with the requantizers' form chosen once by `forward`.
464    #[inline(always)]
465    fn forward_with(
466        &self,
467        input: &[i8; IN],
468        requantize: impl Fn(&Requantizer, i32) -> i8,
469    ) -> [i8; OUT] {
470        let mut output = [0i8; OUT];
471        let rows = self.weights.iter().zip(self.requantizers);
472        for (o, (out, (row, rq))) in output.iter_mut().zip(rows).enumerate() {
473            let bias = self.biases.map_or(0, |b| b.get(o).copied().unwrap_or(0));
474            let acc = bias.wrapping_add(dot_with_zero_point(input, row, self.input_zero_point));
475            *out = requantize(rq, acc);
476        }
477        output
478    }
479}
480
481/// Quantized ReLU: clamp at the tensor's zero point, which represents 0.0
482/// (C++ `qrelu`).
483pub fn qrelu(x: i8, zero_point: i8) -> i8 {
484    if x < zero_point { zero_point } else { x }
485}
486
487/// Quantized ReLU6: clamp to `[zero_point, q_six]`, where `q_six` is 6.0 in the
488/// tensor's grid (C++ `qrelu6`).
489pub fn qrelu6(x: i8, zero_point: i8, q_six: i8) -> i8 {
490    if x < zero_point {
491        zero_point
492    } else if x > q_six {
493        q_six
494    } else {
495        x
496    }
497}
498
499/// Entries in an int8 activation lookup table: one per int8 input.
500pub const LUT_SIZE: usize = 256;
501
502/// Index of `x` in an activation lookup table: -128 maps to 0, 0 to 128 and 127
503/// to 255 (C++ `qActivationLUTIndex`).
504pub fn lut_index(x: i8) -> usize {
505    usize::from((x as u8).wrapping_add(128))
506}
507
508/// Apply a 256-entry int8 lookup table, such as a sigmoid or tanh table built by
509/// `calibration::build_sigmoid_lut` (C++ `qApplyLUT`).
510pub fn apply_lut(x: i8, lut: &[i8; LUT_SIZE]) -> i8 {
511    lut[lut_index(x)]
512}
513
514/// `x * 2^exponent`, saturating to the `i32` range, for `1 <= exponent <= 30`
515/// (gemmlowp `SaturatingRoundingMultiplyByPOT`, C++
516/// `fixedPointMulByPOTSaturating`).
517fn mul_by_pot_saturating(x: i32, exponent: u32) -> i32 {
518    let threshold = ((1u32 << (31 - exponent)) - 1) as i32;
519    if x > threshold {
520        i32::MAX
521    } else if x < -threshold {
522        i32::MIN
523    } else {
524        x * (1 << exponent)
525    }
526}
527
528/// `exp(a)` for `a <= 0`: `a` in Q5.26, the result in Q0.31 (gemmlowp
529/// `exp_on_negative_values`, C++ `fixedPointExpOnNegativeValues`). A Taylor
530/// series around -1/8 covers the fraction within a quarter; each whole quarter
531/// multiplies in a constant `exp(-2^k)`.
532pub(crate) fn exp_on_negative_values(a: i32) -> i32 {
533    const ONE_QUARTER: i32 = 1 << 24;
534    // exp(-1/8) in Q0.31.
535    const EXP_OF_MINUS_ONE_EIGHTH: i32 = 1_895_147_668;
536    // exp(-1/4), exp(-1/2), exp(-1), exp(-2), exp(-4), exp(-8), exp(-16) in Q0.31.
537    const EXP_OF_MINUS_POWER_OF_TWO: [i32; 7] = [
538        1_672_461_947,
539        1_302_514_674,
540        790_015_084,
541        290_630_308,
542        39_332_535,
543        720_401,
544        242,
545    ];
546
547    let a_mod_quarter_minus_one_quarter = (a & (ONE_QUARTER - 1)) - ONE_QUARTER;
548
549    // exp on [-1/4, 0): Taylor series around -1/8, in Q0.31. These values are
550    // bounded whatever `a` is (an exhaustive test covers every fraction).
551    let x = a_mod_quarter_minus_one_quarter * 32 + (1 << 28);
552    let x2 = saturating_rounding_doubling_high_mul(x, x);
553    let x3 = saturating_rounding_doubling_high_mul(x2, x);
554    let x4 = saturating_rounding_doubling_high_mul(x2, x2);
555    let x4_over_4 = rounding_divide_by_pot(x4, 2);
556    let series = rounding_divide_by_pot(
557        saturating_rounding_doubling_high_mul(x4_over_4 + x3, 715_827_883) + x2,
558        1,
559    );
560    let mut result = EXP_OF_MINUS_ONE_EIGHTH
561        + saturating_rounding_doubling_high_mul(EXP_OF_MINUS_ONE_EIGHTH, x + series);
562
563    // The whole quarters. Wraps only for a > 0, outside the domain.
564    let remainder = a_mod_quarter_minus_one_quarter.wrapping_sub(a);
565    for (k, &factor) in EXP_OF_MINUS_POWER_OF_TWO.iter().enumerate() {
566        if remainder & (1 << (24 + k)) != 0 {
567            result = saturating_rounding_doubling_high_mul(result, factor);
568        }
569    }
570
571    if a == 0 { i32::MAX } else { result }
572}
573
574/// `1 / (1 + a)` for `a` in `[0, 1)`, both in Q0.31, by three Newton-Raphson
575/// steps (gemmlowp `one_over_one_plus_x_for_x_in_0_1`, C++
576/// `fixedPointOneOverOnePlusX`).
577pub(crate) fn one_over_one_plus_x(a: i32) -> i32 {
578    // (1 + a) / 2, rounded half away from zero; fits i32 for every a.
579    let sum = i64::from(a) + i64::from(i32::MAX);
580    let half_denominator = ((sum + if sum >= 0 { 1 } else { -1 }) / 2) as i32;
581
582    // Newton-Raphson in Q2.29 from the initial guess 48/17 - 32/17 * d. The
583    // sums stay in range for `a` in the domain; outside it they wrap.
584    let mut x =
585        1_515_870_810 + saturating_rounding_doubling_high_mul(half_denominator, -1_010_580_540);
586    let one: i32 = 1 << 29;
587    for _ in 0..3 {
588        let one_minus_half_denominator_times_x =
589            one.wrapping_sub(saturating_rounding_doubling_high_mul(half_denominator, x));
590        x = x.wrapping_add(mul_by_pot_saturating(
591            saturating_rounding_doubling_high_mul(x, one_minus_half_denominator_times_x),
592            2,
593        ));
594    }
595    mul_by_pot_saturating(x, 1)
596}
597
598/// Int8 softmax over a row of logits, bit-exact with TFLite's int8 softmax
599/// (the TFLite Micro reference kernel, which CMSIS-NN's `arm_softmax_s8` also
600/// reproduces), in gemmlowp fixed point (C++ `QSoftmaxFixedPoint1D`).
601///
602/// The output is on TFLite's probability grid, scale 1/256 and zero point
603/// -128: -128 is 0 and 127 is 255/256. The three parameters depend only on the
604/// input tensor's scale and the softmax's beta; compute them on the host with
605/// `calibration::build_softmax` (`std` feature), as TFLite Micro does, or write
606/// them out as constants.
607///
608/// For each row: subtract the maximum, take `exp((x - max) * input_scale *
609/// beta)` in Q5.26 -> Q0.31 for every `x - max >= diff_min` (the rest
610/// contribute 0), sum the terms in Q12.19, invert the sum by Newton-Raphson and
611/// scale each term by it. Pure integer arithmetic.
612#[derive(Clone, Copy, Debug, PartialEq, Eq)]
613pub struct QSoftmax {
614    /// Q0.31 multiplier of `input_scale * beta`.
615    pub input_multiplier: i32,
616    /// Left shift applied with the multiplier, `0..=31`.
617    pub input_left_shift: i32,
618    /// At most 0: a logit this far or further below the row's maximum gets
619    /// probability 0.
620    pub diff_min: i32,
621}
622
623impl QSoftmax {
624    /// Softmax over one row of `N` int8 logits in the input tensor's grid. `N`
625    /// must be in `1..512` (a compile error otherwise), as in TFLite: the sum
626    /// of the exponentials must fit its Q12.19 accumulator.
627    pub fn forward<const N: usize>(&self, input: &[i8; N]) -> [i8; N] {
628        const { assert!(N > 0 && N < 512, "QSoftmax needs 1 to 511 logits per row") };
629        const ACCUMULATION_INTEGER_BITS: i32 = 12;
630
631        // Out of its documented range the shift is clamped and the scaled
632        // difference wraps (the C++ would be undefined there); in range,
633        // `diff * 2^shift` cannot overflow for any `diff >= diff_min` from
634        // `calibration::build_softmax`.
635        let left_shift = self.input_left_shift.clamp(0, 31) as u32;
636        let exp_of = |diff: i32| {
637            let scaled = saturating_rounding_doubling_high_mul(
638                diff.wrapping_mul(1 << left_shift),
639                self.input_multiplier,
640            );
641            exp_on_negative_values(scaled)
642        };
643
644        let max = i32::from(input.iter().copied().fold(i8::MIN, i8::max));
645
646        // Each term is at most 1.0 = 2^19 in Q12.19, so with fewer than 512
647        // terms the sum stays below 2^28.
648        let mut sum_of_exps: i32 = 0;
649        for &x in input {
650            let diff = i32::from(x) - max;
651            if diff >= self.diff_min {
652                sum_of_exps = sum_of_exps.wrapping_add(rounding_divide_by_pot(
653                    exp_of(diff),
654                    ACCUMULATION_INTEGER_BITS,
655                ));
656            }
657        }
658
659        // The maximum contributes exactly 1.0, so the sum is at least 2^19:
660        // normalise it to [1, 2) and invert. (A sum of 0, possible only with a
661        // positive diff_min, leaves every output at -128.)
662        let headroom_plus_one = (sum_of_exps as u32).leading_zeros();
663        let shifted_sum_minus_one = (sum_of_exps as u32)
664            .checked_shl(headroom_plus_one)
665            .unwrap_or(0)
666            .wrapping_sub(1 << 31) as i32;
667        let shifted_scale = one_over_one_plus_x(shifted_sum_minus_one);
668        let exponent = (ACCUMULATION_INTEGER_BITS - headroom_plus_one as i32) + 31 - 8;
669
670        let mut output = [-128i8; N];
671        for (out, &x) in output.iter_mut().zip(input) {
672            let diff = i32::from(x) - max;
673            if diff >= self.diff_min {
674                // exponent >= 3, so the rounded value is within +-2^28.
675                let q = rounding_divide_by_pot(
676                    saturating_rounding_doubling_high_mul(shifted_scale, exp_of(diff)),
677                    exponent,
678                ) - 128;
679                *out = q.clamp(-128, 127) as i8;
680            }
681        }
682        output
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    /// The dense layers take the one-rounding loop only when every
691    /// requantizer allows it; a layer with one general-path requantizer must
692    /// still give `apply`'s results on every output.
693    #[test]
694    fn dense_requantizer_forms() {
695        const IN: usize = 5;
696        const OUT: usize = 4;
697        let weights: [[i8; IN]; OUT] =
698            core::array::from_fn(|o| core::array::from_fn(|i| (o as i8 * 37 - i as i8 * 29) | 1));
699        let biases: [i32; OUT] = [1000, -2000, 300, -40];
700        let input: [i8; IN] = [-128, -3, 0, 77, 127];
701        let fast = Requantizer {
702            multiplier: 1_518_500_250,
703            shift: 9,
704            zero_point: -5,
705            qmin: -128,
706            qmax: 127,
707        };
708        // A ratio of 2 (shift -1): the general, saturating path.
709        let general = Requantizer {
710            multiplier: 1 << 30,
711            shift: -1,
712            zero_point: 3,
713            qmin: -100,
714            qmax: 90,
715        };
716        let expect = |rqs: &[Requantizer; OUT]| -> [i8; OUT] {
717            core::array::from_fn(|o| {
718                rqs[o].apply(biases[o].wrapping_add(dot_with_zero_point(&input, &weights[o], -7)))
719            })
720        };
721        for rqs in [[fast; OUT], [fast, fast, general, fast], [general; OUT]] {
722            let layer = QDensePerChannel {
723                weights: &weights,
724                biases: Some(&biases),
725                input_zero_point: -7,
726                requantizers: &rqs,
727            };
728            assert_eq!(layer.forward(&input), expect(&rqs), "{rqs:?}");
729        }
730        for rq in [fast, general] {
731            let layer = QDense {
732                weights: &weights,
733                biases: Some(&biases),
734                input_zero_point: -7,
735                requantizer: rq,
736            };
737            assert_eq!(layer.forward(&input), expect(&[rq; OUT]), "{rq:?}");
738        }
739        assert!(fast.one_rounding() && !general.one_rounding());
740    }
741
742    /// About 1.0 in Q0.31.
743    const Q31_ONE: i32 = i32::MAX;
744
745    fn i8_requant(multiplier: i32, shift: i32, zero_point: i8) -> Requantizer {
746        Requantizer {
747            multiplier,
748            shift,
749            zero_point,
750            qmin: -128,
751            qmax: 127,
752        }
753    }
754
755    // Known answers from tinymind unit_test/quantization.
756    #[test]
757    fn high_mul_saturates_min_squared() {
758        assert_eq!(
759            saturating_rounding_doubling_high_mul(i32::MIN, i32::MIN),
760            i32::MAX
761        );
762    }
763
764    #[test]
765    fn rounding_divide_by_pot_cases() {
766        assert_eq!(rounding_divide_by_pot(1234, 0), 1234);
767        assert_eq!(rounding_divide_by_pot(-1234, 0), -1234);
768        assert_eq!(rounding_divide_by_pot(1234, -3), 1234);
769        for (x, expected) in [
770            (8, 1),
771            (11, 1),
772            (12, 2),
773            (15, 2),
774            (-8, -1),
775            (-12, -2),
776            (-11, -1),
777            (-13, -2),
778        ] {
779            assert_eq!(rounding_divide_by_pot(x, 3), expected, "{x} / 8");
780        }
781    }
782
783    #[test]
784    fn requantizer_known_answers() {
785        let identity = i8_requant(Q31_ONE, 0, 0);
786        assert_eq!(
787            [identity.apply(0), identity.apply(50), identity.apply(-50)],
788            [0, 50, -50]
789        );
790        assert_eq!([identity.apply(1000), identity.apply(-1000)], [127, -128]);
791        let halve = i8_requant(Q31_ONE, 1, 0);
792        assert_eq!(
793            [halve.apply(100), halve.apply(-100), halve.apply(0)],
794            [50, -50, 0]
795        );
796        let double = i8_requant(Q31_ONE, -1, 0);
797        assert_eq!([double.apply(30), double.apply(-30)], [60, -60]);
798        let zp = i8_requant(Q31_ONE, 0, 10);
799        assert_eq!(
800            [
801                zp.apply(0),
802                zp.apply(50),
803                zp.apply(-50),
804                zp.apply(200),
805                zp.apply(-200)
806            ],
807            [10, 60, -40, 127, -128]
808        );
809    }
810
811    /// tinymind (C++)'s `requantizer_saturating_path_at_int32_rails`, int8 part: the
812    /// saturating path's +-2^30 clamp gives the exact result, the rescaled value
813    /// plus the zero point clamped in i64.
814    #[test]
815    fn requantizer_saturating_path_at_rails() {
816        let accs = [
817            i32::MIN,
818            i32::MIN + 1,
819            -(1 << 30) - 1,
820            -(1 << 30),
821            -(1 << 30) + 1,
822            -70000,
823            -1,
824            0,
825            1,
826            70000,
827            (1 << 30) - 1,
828            1 << 30,
829            (1 << 30) + 1,
830            i32::MAX - 1,
831            i32::MAX,
832        ];
833        let multipliers = [0, 1, 1 << 30, Q31_ONE, -1, i32::MIN];
834        let zero_points: [i8; 5] = [-128, -127, 0, 126, 127];
835        let bounds: [[i8; 2]; 4] = [[-128, 127], [0, 127], [-128, 0], [0, 0]];
836        let mut cases = 0;
837        for shift in -31..=1 {
838            for multiplier in multipliers {
839                for zero_point in zero_points {
840                    for [qmin, qmax] in bounds {
841                        let rq = Requantizer {
842                            multiplier,
843                            shift,
844                            zero_point,
845                            qmin,
846                            qmax,
847                        };
848                        for acc in accs {
849                            let sum =
850                                i64::from(multiply_by_quantized_multiplier(acc, multiplier, shift))
851                                    + i64::from(zero_point);
852                            let expected = sum.clamp(i64::from(qmin), i64::from(qmax));
853                            assert_eq!(i64::from(rq.apply(acc)), expected);
854                            cases += 1;
855                        }
856                    }
857                }
858            }
859        }
860        assert!(cases > 10_000);
861    }
862
863    #[test]
864    fn dense_known_answers() {
865        let unit = i8_requant(Q31_ONE, 0, 0);
866        let w1 = [[1, 1]];
867        let layer = QDense {
868            weights: &w1,
869            biases: Some(&[0]),
870            input_zero_point: 0,
871            requantizer: unit,
872        };
873        assert_eq!(layer.forward(&[3, 5]), [8]);
874        let w2 = [[2, 1], [-1, 3]];
875        let layer = QDense {
876            weights: &w2,
877            biases: Some(&[0, 0]),
878            input_zero_point: 0,
879            requantizer: unit,
880        };
881        assert_eq!(layer.forward(&[1, 2]), [4, 5]);
882        let layer = QDense {
883            weights: &w1,
884            biases: Some(&[10]),
885            input_zero_point: 0,
886            requantizer: unit,
887        };
888        assert_eq!(layer.forward(&[3, 5]), [18]);
889        let w3 = [[2]];
890        let layer = QDense {
891            weights: &w3,
892            biases: None,
893            input_zero_point: 0,
894            requantizer: unit,
895        };
896        assert_eq!(layer.forward(&[4]), [8]);
897    }
898
899    #[test]
900    fn per_channel_dense_matches_dense_with_shared_requantizer() {
901        let rq = Requantizer {
902            multiplier: 1_200_000_000,
903            shift: 6,
904            zero_point: -3,
905            qmin: -128,
906            qmax: 127,
907        };
908        let weights = [[12, -7, 100], [-128, 5, 9]];
909        let biases = [1000, -2000];
910        let input = [-128, 0, 77];
911        let shared = QDense {
912            weights: &weights,
913            biases: Some(&biases),
914            input_zero_point: -5,
915            requantizer: rq,
916        };
917        let per_channel = QDensePerChannel {
918            weights: &weights,
919            biases: Some(&biases),
920            input_zero_point: -5,
921            requantizers: &[rq, rq],
922        };
923        assert_eq!(per_channel.forward(&input), shared.forward(&input));
924        // A different requantizer on output 1 changes only output 1.
925        let other = Requantizer { shift: 4, ..rq };
926        let mixed = QDensePerChannel {
927            requantizers: &[rq, other],
928            ..per_channel
929        };
930        let (a, b) = (mixed.forward(&input), shared.forward(&input));
931        assert_eq!(a[0], b[0]);
932        assert_ne!(a[1], b[1]);
933    }
934
935    #[test]
936    fn activations() {
937        assert_eq!([qrelu(-5, 0), qrelu(5, 0), qrelu(-128, -10)], [0, 5, -10]);
938        assert_eq!(
939            [qrelu6(-5, 0, 60), qrelu6(30, 0, 60), qrelu6(100, 0, 60)],
940            [0, 30, 60]
941        );
942        assert_eq!(
943            [lut_index(-128), lut_index(0), lut_index(127)],
944            [0, 128, 255]
945        );
946        let mut lut = [0i8; LUT_SIZE];
947        for (i, v) in lut.iter_mut().enumerate() {
948            *v = (i as i32 - 128) as i8;
949        }
950        assert_eq!(apply_lut(-7, &lut), -7);
951    }
952
953    /// Every fraction the Taylor step of `exp_on_negative_values` can see (its
954    /// result depends on `a` only through `a mod 2^24`), with overflow checks on
955    /// in this debug build: none of its plain additions overflows. Also exp(0)
956    /// is 1 and the result never increases as `a` falls.
957    #[test]
958    fn softmax_exp_every_fraction() {
959        let mut previous = exp_on_negative_values(0);
960        assert_eq!(previous, i32::MAX);
961        for a in (-(1 << 24)..0).rev() {
962            let e = exp_on_negative_values(a);
963            assert!(
964                e > 0 && e <= previous,
965                "exp({a}) = {e}, previous {previous}"
966            );
967            previous = e;
968        }
969        // Accuracy against f64 at whole and fractional points in Q5.26.
970        for a in [-(1 << 26), -(3 << 24), -(5 << 26) - 12_345, -(31 << 26)] {
971            let got = f64::from(exp_on_negative_values(a)) / 2f64.powi(31);
972            let want = (f64::from(a) / 2f64.powi(26)).exp();
973            // gemmlowp (and so TFLite) is accurate to about 1e-7 here.
974            assert!((got - want).abs() < 1e-6, "exp({a}): {got} vs {want}");
975        }
976    }
977
978    /// `one_over_one_plus_x` across its domain [0, 1) in Q0.31, against f64.
979    #[test]
980    fn softmax_reciprocal() {
981        for a in (0..i32::MAX).step_by(4093).chain([i32::MAX]) {
982            let got = f64::from(one_over_one_plus_x(a)) / 2f64.powi(31);
983            let want = 1.0 / (1.0 + f64::from(a) / 2f64.powi(31));
984            assert!((got - want).abs() < 1e-8, "1/(1+{a}): {got} vs {want}");
985        }
986    }
987
988    #[test]
989    fn softmax_basics() {
990        // Params for input scale 0.1, beta 1 (TFLite Micro computes these).
991        let softmax = QSoftmax {
992            input_multiplier: 1_717_986_918,
993            input_left_shift: 23,
994            diff_min: -248,
995        };
996        // One logit: probability 1, which saturates to 127.
997        assert_eq!(softmax.forward(&[5]), [127]);
998        // Order is kept, and the probabilities sum to about 1 (256 steps).
999        let y = softmax.forward(&[10, 20, 30]);
1000        assert!(y[0] < y[1] && y[1] < y[2]);
1001        let total: i32 = y.iter().map(|&v| i32::from(v) + 128).sum();
1002        assert!((254..=258).contains(&total), "{y:?}");
1003        // A logit at or below diff_min from the maximum gets exactly 0.
1004        assert_eq!(softmax.forward(&[127, -128])[1], -128);
1005    }
1006}