Skip to main content

tinymind/int8/
calibration.rs

1//! Host-side calibration: turning float scales into the integer parameters the
2//! int8 layers use (C++ `quantizeMultiplier`, `buildRequantizer`, `quantize`,
3//! `dequantize`, `buildQSigmoidLUT`, `buildQTanhLUT`,
4//! `buildQSoftmaxFixedPointParams`, `computeAffineParamsAsymmetric`,
5//! `computeAffineParamsSymmetric`, `computePerChannelSymmetricScales`, the
6//! `RangeObserver`, `buildQAddParams`, `buildRescaler`,
7//! `buildQMulRequantizer`, `buildQLSTMParams`, `buildQGRUParams`,
8//! `quantizeQLSTMBiases`, `quantizeQGRUBiases`, `buildQFFTTwiddles`).
9//!
10//! Needs the `std` feature, for `exp`, `tanh`, `cos` and `sin`; tinymind (C++) gates the
11//! same functions on `TINYMIND_ENABLE_FLOAT && TINYMIND_ENABLE_STD`. On a device,
12//! run these on the host and embed the results as constants. The float
13//! arithmetic follows the C++ step for step, so the tables and requantizers match
14//! the C++ ones on the same platform: `exp` and `tanh` come from the system math
15//! library in both.
16
17use super::{LUT_SIZE, QAdd, QSoftmax, Requantizer};
18#[cfg(doc)]
19use super::{QFft1D, QGruCell, QLstmCell};
20
21/// C `frexp`: `x = mantissa * 2^exponent` with `|mantissa|` in `[0.5, 1)`.
22/// Zero, infinities and NaN come back unchanged with exponent 0.
23fn frexp(x: f64) -> (f64, i32) {
24    if x == 0.0 || !x.is_finite() {
25        return (x, 0);
26    }
27    let bits = x.to_bits();
28    let biased = ((bits >> 52) & 0x7ff) as i32;
29    if biased == 0 {
30        // Subnormal: scale into the normal range first.
31        let (m, e) = frexp(x * f64::from_bits(0x4350_0000_0000_0000)); // 2^54
32        return (m, e - 54);
33    }
34    let mantissa = f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52));
35    (mantissa, biased - 1022)
36}
37
38/// Decompose a positive real scale ratio into a Q0.31 multiplier and a shift
39/// (C++ `quantizeMultiplier`). Returns `(multiplier, shift)`: `shift < 0` for a
40/// ratio above 1, `shift > 0` below 1. A zero ratio gives `(0, 0)`.
41///
42/// The shift always lies in `-31..=31`, the [`Requantizer`]'s contract. A ratio
43/// below 2^-32 rounds every `i32` accumulator to 0 and comes back as `(0, 0)`;
44/// a ratio of 2^31 or more gets shift -31, which already saturates every
45/// non-zero accumulator.
46pub fn quantize_multiplier(ratio: f64) -> (i32, i32) {
47    if ratio == 0.0 {
48        return (0, 0);
49    }
50    let (mantissa, mut exponent) = frexp(ratio);
51    // C++ llround: round half away from zero, as f64::round does.
52    let mut q = (mantissa * (1i64 << 31) as f64).round() as i64;
53    // The mantissa can round up to exactly 2^31; renormalise.
54    if q == 1i64 << 31 {
55        q >>= 1;
56        exponent += 1;
57    }
58    let shift = -exponent;
59    if shift > 31 {
60        (0, 0)
61    } else {
62        (q as i32, shift.max(-31))
63    }
64}
65
66/// Build a [`Requantizer`] for `(input_scale * weight_scale) / output_scale`
67/// (C++ `buildRequantizer<int8_t>`). The zero point and bounds are narrowed to
68/// `i8` as the C++ `static_cast` does.
69pub fn build_requantizer(
70    input_scale: f32,
71    weight_scale: f32,
72    output_scale: f32,
73    output_zero_point: i32,
74    qmin: i32,
75    qmax: i32,
76) -> Requantizer {
77    let ratio = (f64::from(input_scale) * f64::from(weight_scale)) / f64::from(output_scale);
78    let (multiplier, shift) = quantize_multiplier(ratio);
79    Requantizer {
80        multiplier,
81        shift,
82        zero_point: output_zero_point as i8,
83        qmin: qmin as i8,
84        qmax: qmax as i8,
85    }
86}
87
88/// A requantizer for a pure rescale, `input_scale / output_scale`, with no
89/// weight: for [`QConcat`](super::QConcat) inputs and anything else that
90/// copies values from one grid to another (C++ `buildRescaler`, which is
91/// `buildRequantizer` with a weight scale of 1).
92pub fn build_rescaler(
93    input_scale: f32,
94    output_scale: f32,
95    output_zero_point: i32,
96    qmin: i32,
97    qmax: i32,
98) -> Requantizer {
99    build_requantizer(
100        input_scale,
101        1.0,
102        output_scale,
103        output_zero_point,
104        qmin,
105        qmax,
106    )
107}
108
109/// The requantizer of a [`QMul`](super::QMul): `input_a_scale * input_b_scale /
110/// output_scale`, in `f64` from the `f32` scales (C++ `buildQMulRequantizer`;
111/// the same ratio as [`build_requantizer`] with the second input's scale as the
112/// weight scale).
113pub fn build_mul_requantizer(
114    input_a_scale: f32,
115    input_b_scale: f32,
116    output_scale: f32,
117    output_zero_point: i32,
118    qmin: i32,
119    qmax: i32,
120) -> Requantizer {
121    build_requantizer(
122        input_a_scale,
123        input_b_scale,
124        output_scale,
125        output_zero_point,
126        qmin,
127        qmax,
128    )
129}
130
131/// Build a [`QAdd`] for inputs `(scale, zero point)` `input_a` and `input_b`
132/// and output `output` (C++ `buildQAddParams` with its default left shift of 20,
133/// TFLite's). Both inputs are rescaled to twice the larger input scale; ratios
134/// are formed in `f64` from the `f32` scales, as the C++ does. Zero points and
135/// bounds are narrowed to `i8`; raise `qmin` to the output zero point to fuse a
136/// ReLU.
137pub fn build_add(
138    input_a: (f32, i32),
139    input_b: (f32, i32),
140    output: (f32, i32),
141    qmin: i32,
142    qmax: i32,
143) -> QAdd {
144    const LEFT_SHIFT: i32 = 20;
145    let (a_scale, b_scale) = (input_a.0, input_b.0);
146    // The C++ comparison, so equal or NaN scales take the same branch.
147    let max_in = if a_scale > b_scale { a_scale } else { b_scale };
148    let twice_max = 2.0 * f64::from(max_in);
149    let real_a = f64::from(a_scale) / twice_max;
150    let real_b = f64::from(b_scale) / twice_max;
151    let real_out = twice_max / ((1i64 << LEFT_SHIFT) as f64 * f64::from(output.0));
152    let (input_a_multiplier, input_a_shift) = quantize_multiplier(real_a);
153    let (input_b_multiplier, input_b_shift) = quantize_multiplier(real_b);
154    let (multiplier, shift) = quantize_multiplier(real_out);
155    QAdd {
156        input_a_zero_point: input_a.1 as i8,
157        input_b_zero_point: input_b.1 as i8,
158        left_shift: LEFT_SHIFT,
159        input_a_multiplier,
160        input_a_shift,
161        input_b_multiplier,
162        input_b_shift,
163        output_requantizer: Requantizer {
164            multiplier,
165            shift,
166            zero_point: output.1 as i8,
167            qmin: qmin as i8,
168            qmax: qmax as i8,
169        },
170    }
171}
172
173/// Symmetric affine parameters `(scale, 0)` covering `[fmin, fmax]`: the scale
174/// maps the larger magnitude to `qmax` (C++ `computeAffineParamsSymmetric`).
175/// A range of zeros, or a `qmax` of 0 or below, gives scale 1.0.
176pub fn affine_params_symmetric(fmin: f32, fmax: f32, qmax: i32) -> (f32, i32) {
177    // Comparisons as the C++ writes them, so a NaN takes the same branch.
178    let abs_min = if fmin < 0.0 { -fmin } else { fmin };
179    let abs_max = if fmax < 0.0 { -fmax } else { fmax };
180    let absmax = if abs_min > abs_max { abs_min } else { abs_max };
181    if absmax == 0.0 || qmax <= 0 {
182        return (1.0, 0);
183    }
184    (absmax / qmax as f32, 0)
185}
186
187/// The running minimum and maximum of the values it has observed, for fitting
188/// an activation's scale from calibration inputs (C++ `RangeObserver`). Before
189/// any observation the range is `[0, 0]`.
190#[derive(Clone, Copy, Debug, Default, PartialEq)]
191pub struct RangeObserver {
192    /// Smallest value observed.
193    pub min_value: f32,
194    /// Largest value observed.
195    pub max_value: f32,
196    /// Whether anything has been observed.
197    pub has_data: bool,
198}
199
200impl RangeObserver {
201    /// An observer with nothing observed.
202    pub fn new() -> Self {
203        Self::default()
204    }
205
206    /// Widen the range to include `x`. The first value sets both ends.
207    pub fn observe(&mut self, x: f32) {
208        if !self.has_data {
209            self.min_value = x;
210            self.max_value = x;
211            self.has_data = true;
212        } else {
213            if x < self.min_value {
214                self.min_value = x;
215            }
216            if x > self.max_value {
217                self.max_value = x;
218            }
219        }
220    }
221
222    /// [`observe`](Self::observe) each value in order.
223    pub fn observe_all(&mut self, xs: &[f32]) {
224        for &x in xs {
225            self.observe(x);
226        }
227    }
228}
229
230/// Asymmetric per-tensor affine parameters `(scale, zero_point)` that map the
231/// real range `[fmin, fmax]`, widened to include 0, onto `[qmin, qmax]` (C++
232/// `computeAffineParamsAsymmetric`). An empty range gives `(1.0, qmin)`.
233pub fn affine_params_asymmetric(fmin: f32, fmax: f32, qmin: i32, qmax: i32) -> (f32, i32) {
234    // `if`s rather than min/max, which treat NaN differently from the C++.
235    let fmin = if fmin > 0.0 { 0.0 } else { fmin };
236    let fmax = if fmax < 0.0 { 0.0 } else { fmax };
237    let qrange = qmax.wrapping_sub(qmin) as f32;
238    if fmax == fmin || qrange == 0.0 {
239        return (1.0, qmin);
240    }
241    let scale = (fmax - fmin) / qrange;
242    // C++ lround: half away from zero, as f64::round.
243    let mut zp = (f64::from(qmin) - f64::from(fmin) / f64::from(scale)).round() as i64;
244    if zp < i64::from(qmin) {
245        zp = i64::from(qmin);
246    }
247    if zp > i64::from(qmax) {
248        zp = i64::from(qmax);
249    }
250    (scale, zp as i32)
251}
252
253/// One symmetric weight scale per output channel, `max |w| / qmax` over each
254/// channel's weights (C++ `computePerChannelSymmetricScales`), as TFLite
255/// quantizes depthwise and convolution weights. A channel of zeros, or a
256/// `qmax` of 0 or below, gets scale 1.0.
257pub fn per_channel_symmetric_scales<const C: usize, const N: usize>(
258    weights: &[[f32; N]; C],
259    qmax: i32,
260) -> [f32; C] {
261    let mut scales = [1.0f32; C];
262    for (scale, channel) in scales.iter_mut().zip(weights) {
263        // Comparisons as the C++ writes them, so a NaN is skipped the same way.
264        let mut absmax = 0.0f32;
265        for &v in channel {
266            let a = if v < 0.0 { -v } else { v };
267            if a > absmax {
268                absmax = a;
269            }
270        }
271        if absmax != 0.0 && qmax > 0 {
272            *scale = absmax / qmax as f32;
273        }
274    }
275    scales
276}
277
278/// Quantize a real value to int8: `round(x / scale) + zero_point`, ties away
279/// from zero (as TFLite), saturated to `[qmin, qmax]` (C++ `quantize<int8_t>`).
280pub fn quantize(x: f32, scale: f32, zero_point: i32, qmin: i32, qmax: i32) -> i8 {
281    let q = (f64::from(x) / f64::from(scale)).round() + f64::from(zero_point);
282    let mut qi = q as i64;
283    if qi < i64::from(qmin) {
284        qi = i64::from(qmin);
285    }
286    if qi > i64::from(qmax) {
287        qi = i64::from(qmax);
288    }
289    qi as i8
290}
291
292/// The real value an int8 stands for: `scale * (q - zero_point)` (C++
293/// `dequantize<int8_t>`).
294pub fn dequantize(q: i8, scale: f32, zero_point: i32) -> f32 {
295    scale * (i32::from(q) - zero_point) as f32
296}
297
298/// Round to nearest, ties away from zero, and saturate to int8 (C++
299/// `qSaturateRoundToInt8`).
300fn saturate_round_to_i8(v: f32) -> i8 {
301    (f64::from(v).round() as i64).clamp(-128, 127) as i8
302}
303
304/// A 256-entry lookup table for `f` from the input tensor's grid to the output
305/// tensor's: dequantize each int8, apply `f`, requantize.
306fn build_lut(
307    input_scale: f32,
308    input_zero_point: i32,
309    output_scale: f32,
310    output_zero_point: i32,
311    f: impl Fn(f32) -> f32,
312) -> [i8; LUT_SIZE] {
313    core::array::from_fn(|index| {
314        let x = index as i32 - 128;
315        let x_real = input_scale * (x - input_zero_point) as f32;
316        let y_q = output_zero_point as f32 + f(x_real) / output_scale;
317        saturate_round_to_i8(y_q)
318    })
319}
320
321/// Sigmoid lookup table, `1 / (1 + exp(-x))` (C++ `buildQSigmoidLUT`). An output
322/// grid of scale 1/256 and zero point -128 uses the full int8 range.
323pub fn build_sigmoid_lut(
324    input_scale: f32,
325    input_zero_point: i32,
326    output_scale: f32,
327    output_zero_point: i32,
328) -> [i8; LUT_SIZE] {
329    build_lut(
330        input_scale,
331        input_zero_point,
332        output_scale,
333        output_zero_point,
334        |x| 1.0 / (1.0 + (-x).exp()),
335    )
336}
337
338/// Tanh lookup table (C++ `buildQTanhLUT`). An output grid of scale 1/128 and
339/// zero point 0 uses the full int8 range.
340pub fn build_tanh_lut(
341    input_scale: f32,
342    input_zero_point: i32,
343    output_scale: f32,
344    output_zero_point: i32,
345) -> [i8; LUT_SIZE] {
346    build_lut(
347        input_scale,
348        input_zero_point,
349        output_scale,
350        output_zero_point,
351        f32::tanh,
352    )
353}
354
355/// [`QSoftmax`] parameters for an input tensor of scale `input_scale` and a
356/// softmax of `beta` (1.0 for a plain softmax), computed as TFLite Micro does
357/// for an int8 softmax (`PreprocessSoftmaxScaling` with 5 integer bits, then
358/// `CalculateInputRadius`; C++ `buildQSoftmaxFixedPointParams`).
359pub fn build_softmax(input_scale: f64, beta: f64) -> QSoftmax {
360    const INPUT_INTEGER_BITS: i32 = 5;
361    let max_real_multiplier = ((1i64 << 31) - 1) as f64;
362    let mut real_multiplier = beta * input_scale * (1i64 << (31 - INPUT_INTEGER_BITS)) as f64;
363    if real_multiplier > max_real_multiplier {
364        real_multiplier = max_real_multiplier;
365    }
366
367    // quantize_multiplier returns shift = -exponent; a multiplier above one is
368    // a left shift.
369    let (input_multiplier, shift) = quantize_multiplier(real_multiplier);
370    let input_left_shift = -shift;
371
372    // 2^input_left_shift is exact in f64 (the C++ shifts an int64).
373    let max_input_rescaled = f64::from((1 << INPUT_INTEGER_BITS) - 1)
374        * (1i64 << (31 - INPUT_INTEGER_BITS)) as f64
375        / 2f64.powi(input_left_shift);
376    QSoftmax {
377        input_multiplier,
378        input_left_shift,
379        diff_min: (max_input_rescaled.floor() as i32).saturating_neg(),
380    }
381}
382
383/// Output scale of the sigmoid LUTs the recurrent cells read: 1/256, with zero
384/// point -128 (C++ `kQLstmSigmoidOutputScale`). Build them with
385/// `build_sigmoid_lut(lut_input_scale, 0, SIGMOID_LUT_OUTPUT_SCALE, -128)`.
386pub const SIGMOID_LUT_OUTPUT_SCALE: f32 = 1.0 / 256.0;
387
388/// Output scale of the tanh LUTs the recurrent cells read: 1/128, with zero
389/// point 0 (C++ `kQLstmTanhOutputScale`). Build them with
390/// `build_tanh_lut(lut_input_scale, 0, TANH_LUT_OUTPUT_SCALE, 0)`.
391pub const TANH_LUT_OUTPUT_SCALE: f32 = 1.0 / 128.0;
392
393/// The float scales a [`QLstmCell`] is calibrated from (C++ `QLSTMScales`).
394/// Gates are in the order i, f, g, o.
395#[derive(Clone, Copy, Debug, PartialEq)]
396pub struct LstmScales {
397    /// Scale of the input tensor.
398    pub input_scale: f32,
399    /// Scale of the hidden state.
400    pub hidden_scale: f32,
401    /// Scale of the cell state.
402    pub cell_scale: f32,
403    /// Scale of the LUTs' input grid, shared by every gate and the cell's tanh.
404    pub lut_input_scale: f32,
405    /// Per gate, the scale of the symmetric input weights.
406    pub input_weight_scales: [f32; 4],
407    /// Per gate, the scale of the symmetric recurrent weights.
408    pub recurrent_weight_scales: [f32; 4],
409}
410
411/// The multipliers and shifts of a [`QLstmCell`] (C++ `QLSTMParams`), with the
412/// same field names as the cell. `output_multiplier` and `output_shift` go in
413/// the cell's `output_requantizer`, with the hidden zero point and bounds.
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub struct LstmParams {
416    /// Per gate, the cell's `input_to_lut_multiplier`.
417    pub input_to_lut_multiplier: [i32; 4],
418    /// Per gate, the cell's `input_to_lut_shift`.
419    pub input_to_lut_shift: [i32; 4],
420    /// Per gate, the cell's `recurrent_to_lut_multiplier`.
421    pub recurrent_to_lut_multiplier: [i32; 4],
422    /// Per gate, the cell's `recurrent_to_lut_shift`.
423    pub recurrent_to_lut_shift: [i32; 4],
424    /// The cell's `f_times_c_multiplier`.
425    pub f_times_c_multiplier: i32,
426    /// The cell's `f_times_c_shift`.
427    pub f_times_c_shift: i32,
428    /// The cell's `i_times_g_multiplier`.
429    pub i_times_g_multiplier: i32,
430    /// The cell's `i_times_g_shift`.
431    pub i_times_g_shift: i32,
432    /// The cell's `cell_to_tanh_multiplier`.
433    pub cell_to_tanh_multiplier: i32,
434    /// The cell's `cell_to_tanh_shift`.
435    pub cell_to_tanh_shift: i32,
436    /// The `multiplier` of the cell's `output_requantizer`.
437    pub output_multiplier: i32,
438    /// The `shift` of the cell's `output_requantizer`.
439    pub output_shift: i32,
440}
441
442/// Per gate, the multipliers rescaling the input and recurrent sums to the LUT
443/// input grid: `input_scale * weight_scale / lut_input_scale`, in `f64`.
444#[allow(clippy::type_complexity)]
445fn gate_rescales<const G: usize>(
446    input_scale: f32,
447    hidden_scale: f32,
448    lut_input_scale: f32,
449    input_weight_scales: &[f32; G],
450    recurrent_weight_scales: &[f32; G],
451) -> ([i32; G], [i32; G], [i32; G], [i32; G]) {
452    let mut out = ([0; G], [0; G], [0; G], [0; G]);
453    let lut = f64::from(lut_input_scale);
454    for g in 0..G {
455        let r_in = f64::from(input_scale) * f64::from(input_weight_scales[g]) / lut;
456        (out.0[g], out.1[g]) = quantize_multiplier(r_in);
457        let r_rec = f64::from(hidden_scale) * f64::from(recurrent_weight_scales[g]) / lut;
458        (out.2[g], out.3[g]) = quantize_multiplier(r_rec);
459    }
460    out
461}
462
463/// Build a [`QLstmCell`]'s multipliers and shifts from its float scales (C++
464/// `buildQLSTMParams`). The ratios are formed in `f64` from the `f32` scales,
465/// as the C++ does.
466///
467/// ```
468/// use tinymind::int8::calibration::{
469///     LstmScales, SIGMOID_LUT_OUTPUT_SCALE, TANH_LUT_OUTPUT_SCALE, build_lstm_params,
470///     build_sigmoid_lut, build_tanh_lut, quantize, quantize_gate_biases,
471/// };
472/// use tinymind::int8::{QLstmCell, Requantizer};
473///
474/// // A float LSTM with 1 input and 2 hidden units.
475/// let w_in = [[[0.5f32], [-0.25]], [[0.3], [0.1]], [[-0.4], [0.2]], [[0.25], [0.5]]];
476/// let w_rec = [[[0.1f32, 0.2], [0.0, -0.1]]; 4];
477/// let bias = [[0.0f32, 0.1], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0]];
478///
479/// let scales = LstmScales {
480///     input_scale: 1.0 / 127.0,
481///     hidden_scale: 1.0 / 127.0,
482///     cell_scale: 4.0 / 127.0,
483///     lut_input_scale: 8.0 / 127.0,
484///     input_weight_scales: [0.5 / 127.0, 0.3 / 127.0, 0.4 / 127.0, 0.5 / 127.0],
485///     recurrent_weight_scales: [0.2 / 127.0; 4],
486/// };
487/// let p = build_lstm_params(&scales);
488/// let q = |w: f32, s: f32| quantize(w, s, 0, -127, 127);
489/// let input_weights: [[[i8; 1]; 2]; 4] =
490///     core::array::from_fn(|g| w_in[g].map(|row| row.map(|w| q(w, scales.input_weight_scales[g]))));
491/// let recurrent_weights: [[[i8; 2]; 2]; 4] = core::array::from_fn(|g| {
492///     w_rec[g].map(|row| row.map(|w| q(w, scales.recurrent_weight_scales[g])))
493/// });
494/// let biases = quantize_gate_biases(&bias, scales.lut_input_scale);
495/// let sigmoid = build_sigmoid_lut(scales.lut_input_scale, 0, SIGMOID_LUT_OUTPUT_SCALE, -128);
496/// let tanh = build_tanh_lut(scales.lut_input_scale, 0, TANH_LUT_OUTPUT_SCALE, 0);
497///
498/// let cell: QLstmCell<'_, 1, 2> = QLstmCell {
499///     input_weights: &input_weights,
500///     recurrent_weights: &recurrent_weights,
501///     biases: &biases,
502///     input_zero_point: 0,
503///     hidden_zero_point: 0,
504///     cell_zero_point: 0,
505///     input_to_lut_multiplier: p.input_to_lut_multiplier,
506///     input_to_lut_shift: p.input_to_lut_shift,
507///     recurrent_to_lut_multiplier: p.recurrent_to_lut_multiplier,
508///     recurrent_to_lut_shift: p.recurrent_to_lut_shift,
509///     sigmoid_lut: &sigmoid,
510///     tanh_lut: &tanh,
511///     f_times_c_multiplier: p.f_times_c_multiplier,
512///     f_times_c_shift: p.f_times_c_shift,
513///     i_times_g_multiplier: p.i_times_g_multiplier,
514///     i_times_g_shift: p.i_times_g_shift,
515///     cell_qmin: -127,
516///     cell_qmax: 127,
517///     cell_to_tanh_multiplier: p.cell_to_tanh_multiplier,
518///     cell_to_tanh_shift: p.cell_to_tanh_shift,
519///     tanh_cell_lut: &tanh,
520///     output_requantizer: Requantizer {
521///         multiplier: p.output_multiplier,
522///         shift: p.output_shift,
523///         zero_point: 0,
524///         qmin: -128,
525///         qmax: 127,
526///     },
527/// };
528/// let (mut h, mut c) = ([0i8; 2], [0i8; 2]);
529/// for x in [0.5f32, -0.3, 0.7] {
530///     cell.forward(&[quantize(x, scales.input_scale, 0, -128, 127)], &mut h, &mut c);
531/// }
532/// println!("h = {:?}", h.map(|v| f32::from(v) * scales.hidden_scale));
533/// ```
534pub fn build_lstm_params(scales: &LstmScales) -> LstmParams {
535    let (in_m, in_s, rec_m, rec_s) = gate_rescales(
536        scales.input_scale,
537        scales.hidden_scale,
538        scales.lut_input_scale,
539        &scales.input_weight_scales,
540        &scales.recurrent_weight_scales,
541    );
542    let sig = f64::from(SIGMOID_LUT_OUTPUT_SCALE);
543    let tanh = f64::from(TANH_LUT_OUTPUT_SCALE);
544    let c = f64::from(scales.cell_scale);
545    let h = f64::from(scales.hidden_scale);
546    let (f_times_c_multiplier, f_times_c_shift) = quantize_multiplier(sig * c / c);
547    let (i_times_g_multiplier, i_times_g_shift) = quantize_multiplier(sig * tanh / c);
548    let (cell_to_tanh_multiplier, cell_to_tanh_shift) =
549        quantize_multiplier(c / f64::from(scales.lut_input_scale));
550    let (output_multiplier, output_shift) = quantize_multiplier(sig * tanh / h);
551    LstmParams {
552        input_to_lut_multiplier: in_m,
553        input_to_lut_shift: in_s,
554        recurrent_to_lut_multiplier: rec_m,
555        recurrent_to_lut_shift: rec_s,
556        f_times_c_multiplier,
557        f_times_c_shift,
558        i_times_g_multiplier,
559        i_times_g_shift,
560        cell_to_tanh_multiplier,
561        cell_to_tanh_shift,
562        output_multiplier,
563        output_shift,
564    }
565}
566
567/// The float scales a [`QGruCell`] is calibrated from (C++ `QGRUScales`).
568/// Gates are in the order r, z, n.
569#[derive(Clone, Copy, Debug, PartialEq)]
570pub struct GruScales {
571    /// Scale of the input tensor.
572    pub input_scale: f32,
573    /// Scale of the hidden state.
574    pub hidden_scale: f32,
575    /// Scale of the LUTs' input grid, shared by every gate.
576    pub lut_input_scale: f32,
577    /// Per gate, the scale of the symmetric input weights.
578    pub input_weight_scales: [f32; 3],
579    /// Per gate, the scale of the symmetric recurrent weights.
580    pub recurrent_weight_scales: [f32; 3],
581}
582
583/// The multipliers and shifts of a [`QGruCell`] (C++ `QGRUParams`), with the
584/// same field names as the cell.
585#[derive(Clone, Copy, Debug, PartialEq, Eq)]
586pub struct GruParams {
587    /// Per gate, the cell's `input_to_lut_multiplier`.
588    pub input_to_lut_multiplier: [i32; 3],
589    /// Per gate, the cell's `input_to_lut_shift`.
590    pub input_to_lut_shift: [i32; 3],
591    /// Per gate, the cell's `recurrent_to_lut_multiplier`.
592    pub recurrent_to_lut_multiplier: [i32; 3],
593    /// Per gate, the cell's `recurrent_to_lut_shift`.
594    pub recurrent_to_lut_shift: [i32; 3],
595    /// The cell's `r_times_h_multiplier`.
596    pub r_times_h_multiplier: i32,
597    /// The cell's `r_times_h_shift`.
598    pub r_times_h_shift: i32,
599    /// The cell's `one_minus_z_times_n_multiplier`.
600    pub one_minus_z_times_n_multiplier: i32,
601    /// The cell's `one_minus_z_times_n_shift`.
602    pub one_minus_z_times_n_shift: i32,
603    /// The cell's `z_times_h_multiplier`.
604    pub z_times_h_multiplier: i32,
605    /// The cell's `z_times_h_shift`.
606    pub z_times_h_shift: i32,
607}
608
609/// Build a [`QGruCell`]'s multipliers and shifts from its float scales (C++
610/// `buildQGRUParams`). Use the LUTs and biases as for [`build_lstm_params`].
611pub fn build_gru_params(scales: &GruScales) -> GruParams {
612    let (in_m, in_s, rec_m, rec_s) = gate_rescales(
613        scales.input_scale,
614        scales.hidden_scale,
615        scales.lut_input_scale,
616        &scales.input_weight_scales,
617        &scales.recurrent_weight_scales,
618    );
619    let sig = f64::from(SIGMOID_LUT_OUTPUT_SCALE);
620    let tanh = f64::from(TANH_LUT_OUTPUT_SCALE);
621    let h = f64::from(scales.hidden_scale);
622    let (r_times_h_multiplier, r_times_h_shift) = quantize_multiplier(sig);
623    let (one_minus_z_times_n_multiplier, one_minus_z_times_n_shift) =
624        quantize_multiplier(sig * tanh / h);
625    let (z_times_h_multiplier, z_times_h_shift) = quantize_multiplier(sig);
626    GruParams {
627        input_to_lut_multiplier: in_m,
628        input_to_lut_shift: in_s,
629        recurrent_to_lut_multiplier: rec_m,
630        recurrent_to_lut_shift: rec_s,
631        r_times_h_multiplier,
632        r_times_h_shift,
633        one_minus_z_times_n_multiplier,
634        one_minus_z_times_n_shift,
635        z_times_h_multiplier,
636        z_times_h_shift,
637    }
638}
639
640/// Quantize a recurrent cell's float biases, `biases[gate][unit]`, into the LUT
641/// input grid: `round(b / lut_input_scale)` in `f64`, ties away from zero
642/// (C++ `quantizeQLSTMBiases` with `G` = 4, `quantizeQGRUBiases` with `G` = 3).
643/// A value beyond the `i32` range wraps, as the C++ conversion from `long`
644/// does.
645pub fn quantize_gate_biases<const G: usize, const HID: usize>(
646    biases: &[[f32; HID]; G],
647    lut_input_scale: f32,
648) -> [[i32; HID]; G] {
649    biases
650        .map(|gate| gate.map(|b| (f64::from(b) / f64::from(lut_input_scale)).round() as i64 as i32))
651}
652
653/// The Q1.15 twiddle tables of a [`QFft1D`]`<N, HALF>`: `cos(-2πk/N)` and
654/// `sin(-2πk/N)` for `k` in `0..N/2`, times 32768, rounded to nearest (ties
655/// away from zero) and clamped to `i16` (C++ `buildQFFTTwiddles`). Returns
656/// `(cos, sin)`.
657///
658/// `1.0` (`k = 0`) clamps to 32767, the convention of TFLite and CMSIS-DSP;
659/// `-1.0` (the sine at `k = N/4`) is exactly -32768. `cos` and `sin` come from
660/// the system math library, as in the C++, so the tables match the C++ ones on
661/// the same platform. The same checks on `N` and `HALF` as the layer's apply.
662///
663/// ```
664/// use tinymind::int8::QFft1D;
665/// use tinymind::int8::calibration::build_fft_twiddles;
666///
667/// let (cos, sin) = build_fft_twiddles::<8, 4>();
668/// assert_eq!(cos, [32767, 23170, 0, -23170]);
669/// assert_eq!(sin, [0, -23170, -32768, -23170]);
670/// let fft: QFft1D<'_, 8, 4> = QFft1D { twiddle_cos: &cos, twiddle_sin: &sin };
671/// # let _ = fft;
672/// ```
673pub fn build_fft_twiddles<const N: usize, const HALF: usize>() -> ([i16; HALF], [i16; HALF]) {
674    const {
675        assert!(N >= 2, "FFT length must be at least 2");
676        assert!(N.is_power_of_two(), "FFT length must be a power of two");
677        assert!(HALF == N / 2, "HALF must be N / 2");
678    }
679    // C `lround`, then the C++ clamp to the i16 range.
680    let q15 = |x: f64| (x * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
681    let mut cos = [0i16; HALF];
682    let mut sin = [0i16; HALF];
683    for (k, (c, s)) in cos.iter_mut().zip(sin.iter_mut()).enumerate() {
684        // The C++ literal 6.283185307179586476925286766559 is TAU as an f64.
685        let phase = -core::f64::consts::TAU * k as f64 / N as f64;
686        *c = q15(phase.cos());
687        *s = q15(phase.sin());
688    }
689    (cos, sin)
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695
696    // Known answers from tinymind unit_test/quantization.
697    #[test]
698    fn quantize_multiplier_cases() {
699        assert_eq!(quantize_multiplier(0.0), (0, 0));
700        // frexp(1.0) = 0.5 * 2^1.
701        assert_eq!(quantize_multiplier(1.0), (1 << 30, -1));
702        assert_eq!(quantize_multiplier(0.5), (1 << 30, 0));
703        // A mantissa that rounds up to 2^31 is renormalised.
704        assert_eq!(quantize_multiplier(1.0 - 1e-10), (1 << 30, -1));
705        // The shift stays in -31..=31 (tinymind #247); values from the C++.
706        assert_eq!(quantize_multiplier(2f64.powi(-31)), (1 << 30, 30));
707        assert_eq!(quantize_multiplier(2f64.powi(-32)), (1 << 30, 31));
708        assert_eq!(quantize_multiplier(0.75 * 2f64.powi(-32)), (0, 0));
709        assert_eq!(quantize_multiplier(2f64.powi(-40)), (0, 0));
710        assert_eq!(quantize_multiplier(1e-12), (0, 0));
711        assert_eq!(quantize_multiplier(2f64.powi(30)), (1 << 30, -31));
712        assert_eq!(quantize_multiplier(2f64.powi(31)), (1 << 30, -31));
713        assert_eq!(
714            quantize_multiplier(0.75 * 2f64.powi(32)),
715            (1_610_612_736, -31)
716        );
717        assert_eq!(quantize_multiplier(2f64.powi(40)), (1 << 30, -31));
718        assert_eq!(quantize_multiplier(1e15), (1_907_348_633, -31));
719        // A ratio below 2^-32 rounds every accumulator to 0, so the output is
720        // the zero point; a left shift past 31 saturates exactly as 31 does.
721        let rq = |(multiplier, shift)| Requantizer {
722            multiplier,
723            shift,
724            zero_point: 3,
725            qmin: -128,
726            qmax: 127,
727        };
728        for acc in [i32::MIN, -1 << 20, -2, -1, 0, 1, 2, 1 << 20, i32::MAX] {
729            assert_eq!(rq(quantize_multiplier(2f64.powi(-40))).apply(acc), 3);
730            assert_eq!(rq((1 << 30, -41)).apply(acc), rq((1 << 30, -31)).apply(acc));
731        }
732        let unity = build_requantizer(1.0, 1.0, 1.0, 0, -128, 127);
733        assert_eq!(unity.apply(42), 42);
734        let half = build_requantizer(1.0, 0.5, 1.0, 0, -128, 127);
735        assert_eq!(half.apply(100), 50);
736    }
737
738    #[test]
739    fn frexp_matches_c() {
740        for (x, m, e) in [
741            (1.0, 0.5, 1),
742            (0.75, 0.75, 0),
743            (3.0, 0.75, 2),
744            (-3.0, -0.75, 2),
745            (f64::MIN_POSITIVE, 0.5, -1021),
746            (f64::MIN_POSITIVE / 4.0, 0.5, -1023),
747        ] {
748            assert_eq!(frexp(x), (m, e), "frexp({x})");
749        }
750    }
751
752    #[test]
753    fn quantize_rounds_half_away_and_saturates() {
754        assert_eq!(quantize(0.5, 1.0, 0, -128, 127), 1);
755        assert_eq!(quantize(-0.5, 1.0, 0, -128, 127), -1);
756        assert_eq!(quantize(1000.0, 1.0, 0, -128, 127), 127);
757        assert_eq!(quantize(-1000.0, 1.0, 0, -128, 127), -128);
758        assert_eq!(dequantize(-128, 0.5, -128), 0.0);
759    }
760
761    #[test]
762    fn range_observer_starts_from_its_first_value() {
763        let mut obs = RangeObserver::new();
764        assert!(!obs.has_data);
765        obs.observe(5.0);
766        assert_eq!((obs.min_value, obs.max_value), (5.0, 5.0));
767        obs.observe_all(&[7.0, 6.0, 2.5]);
768        assert_eq!((obs.min_value, obs.max_value), (2.5, 7.0));
769        assert!(obs.has_data);
770    }
771
772    #[test]
773    fn symmetric_params_cover_the_larger_magnitude() {
774        assert_eq!(affine_params_symmetric(-4.0, 2.0, 127), (4.0 / 127.0, 0));
775        assert_eq!(affine_params_symmetric(-1.0, 3.0, 127), (3.0 / 127.0, 0));
776        assert_eq!(affine_params_symmetric(0.0, 0.0, 127), (1.0, 0));
777        assert_eq!(affine_params_symmetric(-1.0, 1.0, 0), (1.0, 0));
778    }
779}