tinymind/int8/recurrent.rs
1//! Int8 recurrent cells, ported from tinymind (C++) `cpp/qlstm.hpp` and
2//! `cpp/qgru.hpp`. Re-exported from [`int8`](super).
3
4use super::{
5 LUT_SIZE, Requantizer, apply_lut, dot_with_zero_point, multiply_by_quantized_multiplier,
6};
7
8// Where the C++ sums would overflow `i32` (outside its contract), these wrap.
9
10/// Zero point of the sigmoid LUTs' output grid, scale 1/256: -128 stands for 0.
11const SIGMOID_ZERO_POINT: i32 = -128;
12
13mod sealed {
14 pub trait Sealed {}
15}
16
17/// The storage of a [`QLstmCell`]'s cell state: `i8` (the default) or `i16`.
18/// An `i16` cell state has 256 times the resolution, for long sequences.
19/// Sealed: the crate implements it.
20pub trait CellStorage: sealed::Sealed + Copy + Into<i32> {
21 /// `v` narrowed to this type; the cell calls it only on values already in
22 /// range.
23 #[doc(hidden)]
24 fn narrow(v: i32) -> Self;
25}
26
27impl sealed::Sealed for i8 {}
28impl CellStorage for i8 {
29 fn narrow(v: i32) -> Self {
30 v as i8
31 }
32}
33
34impl sealed::Sealed for i16 {}
35impl CellStorage for i16 {
36 fn narrow(v: i32) -> Self {
37 v as i16
38 }
39}
40
41/// Saturate to the int8 range (C++ `qLstmSaturateInt8`, `qGruSaturateInt8`).
42fn saturate_i8(v: i32) -> i8 {
43 v.clamp(-128, 127) as i8
44}
45
46/// One gate's pre-activations for every hidden unit:
47/// `bias + rescale(W x) + rescale(R h)`, saturated to the LUT input's int8
48/// grid. The input and recurrent sums each subtract their tensor's zero point.
49#[allow(clippy::too_many_arguments)]
50fn gate_preactivations<const IN: usize, const HID: usize>(
51 input: &[i8; IN],
52 input_zero_point: i8,
53 recurrent: &[i8; HID],
54 recurrent_zero_point: i8,
55 input_weights: &[[i8; IN]; HID],
56 recurrent_weights: &[[i8; HID]; HID],
57 biases: &[i32; HID],
58 input_rescale: (i32, i32),
59 recurrent_rescale: (i32, i32),
60) -> [i8; HID] {
61 let mut pre = [0i8; HID];
62 let rows = input_weights.iter().zip(recurrent_weights).zip(biases);
63 for (out, ((w_in, w_rec), &bias)) in pre.iter_mut().zip(rows) {
64 let acc_in = dot_with_zero_point(input, w_in, input_zero_point);
65 let acc_rec = dot_with_zero_point(recurrent, w_rec, recurrent_zero_point);
66 let r_in = multiply_by_quantized_multiplier(acc_in, input_rescale.0, input_rescale.1);
67 let r_rec =
68 multiply_by_quantized_multiplier(acc_rec, recurrent_rescale.0, recurrent_rescale.1);
69 *out = saturate_i8(r_in.wrapping_add(r_rec).wrapping_add(bias));
70 }
71 pre
72}
73
74/// One time step of a quantized LSTM cell with `IN` int8 inputs and `HID`
75/// hidden units (C++ `QLSTMCell`), in the TFLite / CMSIS-NN quantization model.
76///
77/// The cell borrows its weights, biases and lookup tables, so they can live in
78/// flash, and [`forward`](Self::forward) updates the caller's hidden and cell
79/// state in place: the caller runs the time loop. Gates are in TFLite's order:
80/// input `i`, forget `f`, cell `g`, output `o`, and the weights are gate-major,
81/// `input_weights[gate][unit][input]`, symmetric int8.
82///
83/// Each step, for each gate and hidden unit, the input and recurrent sums
84/// (`i32`, each less its tensor's zero point) are rescaled to the gate LUT's
85/// input grid and added to the bias, which is in that grid too; the result,
86/// saturated to int8, indexes the gate's LUT. The LUTs' output grids are
87/// fixed: sigmoid scale 1/256 with zero point -128, tanh scale 1/128 with zero
88/// point 0. Then
89///
90/// - `c = clamp(rescale(f * (c_prev - c_zp)) + rescale(i * g) + c_zp, cell_qmin, cell_qmax)`
91/// - `h = output_requantizer(o * tanh(c))`, with `tanh(c)` from
92/// `tanh_cell_lut` after rescaling `c - c_zp` to its input grid.
93///
94/// Build the multipliers and shifts from float scales with
95/// `calibration::build_lstm_params`, the biases with
96/// `calibration::quantize_gate_biases` and the LUTs with
97/// `calibration::build_sigmoid_lut` and `build_tanh_lut` (`std` feature), or
98/// write the integers out as constants.
99///
100/// ```
101/// use tinymind::int8::{QLstmCell, Requantizer};
102///
103/// // With zero weights and biases every gate sees 0: with these LUTs each
104/// // sigmoid gate is 0.5 (0 in its grid) and the cell input g is 0. Each step
105/// // the cell state halves (f_times_c is 2^-8: f centred at 128, times c, over
106/// // 256) and the hidden state, o * tanh(c), is 0 (the tanh table is all 0).
107/// static ZERO_LUT: [i8; 256] = [0; 256];
108/// let cell: QLstmCell<'_, 2, 3> = QLstmCell {
109/// input_weights: &[[[0; 2]; 3]; 4],
110/// recurrent_weights: &[[[0; 3]; 3]; 4],
111/// biases: &[[0; 3]; 4],
112/// input_zero_point: 0,
113/// hidden_zero_point: 0,
114/// cell_zero_point: 0,
115/// input_to_lut_multiplier: [1 << 30; 4],
116/// input_to_lut_shift: [0; 4],
117/// recurrent_to_lut_multiplier: [1 << 30; 4],
118/// recurrent_to_lut_shift: [0; 4],
119/// sigmoid_lut: &ZERO_LUT,
120/// tanh_lut: &ZERO_LUT,
121/// f_times_c_multiplier: 1 << 30,
122/// f_times_c_shift: 7,
123/// i_times_g_multiplier: 1 << 30,
124/// i_times_g_shift: 7,
125/// cell_qmin: -127,
126/// cell_qmax: 127,
127/// cell_to_tanh_multiplier: 1 << 30,
128/// cell_to_tanh_shift: 0,
129/// tanh_cell_lut: &ZERO_LUT,
130/// output_requantizer: Requantizer { multiplier: 1 << 30, shift: 7, zero_point: 0, qmin: -128, qmax: 127 },
131/// };
132/// let mut hidden = [5i8, -5, 0];
133/// let mut state = [100i8, -60, 7];
134/// cell.forward(&[10, -10], &mut hidden, &mut state);
135/// assert_eq!(state, [50, -30, 4]); // 3.5 rounds away from zero
136/// assert_eq!(hidden, [0, 0, 0]);
137/// ```
138#[derive(Clone, Copy, Debug)]
139pub struct QLstmCell<'a, const IN: usize, const HID: usize, C: CellStorage = i8> {
140 /// `input_weights[gate][unit][input]`, gates in the order i, f, g, o.
141 pub input_weights: &'a [[[i8; IN]; HID]; 4],
142 /// `recurrent_weights[gate][unit][previous unit]`.
143 pub recurrent_weights: &'a [[[i8; HID]; HID]; 4],
144 /// `biases[gate][unit]`, in the LUT input grid.
145 pub biases: &'a [[i32; HID]; 4],
146 /// The input tensor's zero point.
147 pub input_zero_point: i8,
148 /// The hidden state's zero point (also the output requantizer's).
149 pub hidden_zero_point: i8,
150 /// The cell state's zero point.
151 pub cell_zero_point: C,
152 /// Per gate, the Q0.31 multiplier rescaling the input sum to the LUT input grid.
153 pub input_to_lut_multiplier: [i32; 4],
154 /// Per gate, the shift for `input_to_lut_multiplier` (positive divides, as
155 /// in [`Requantizer`]).
156 pub input_to_lut_shift: [i32; 4],
157 /// Per gate, the multiplier rescaling the recurrent sum to the LUT input grid.
158 pub recurrent_to_lut_multiplier: [i32; 4],
159 /// Per gate, the shift for `recurrent_to_lut_multiplier`.
160 pub recurrent_to_lut_shift: [i32; 4],
161 /// Sigmoid table for the i, f and o gates (output scale 1/256, zero point -128).
162 pub sigmoid_lut: &'a [i8; LUT_SIZE],
163 /// Tanh table for the g gate (output scale 1/128, zero point 0).
164 pub tanh_lut: &'a [i8; LUT_SIZE],
165 /// Multiplier rescaling `f * (c_prev - c_zp)` to the cell grid.
166 pub f_times_c_multiplier: i32,
167 /// Shift for `f_times_c_multiplier`.
168 pub f_times_c_shift: i32,
169 /// Multiplier rescaling `i * g` to the cell grid.
170 pub i_times_g_multiplier: i32,
171 /// Shift for `i_times_g_multiplier`.
172 pub i_times_g_shift: i32,
173 /// Lowest cell state. If `cell_qmin > cell_qmax` the cell state is `cell_qmax`.
174 pub cell_qmin: C,
175 /// Highest cell state.
176 pub cell_qmax: C,
177 /// Multiplier rescaling `c - c_zp` to `tanh_cell_lut`'s input grid.
178 pub cell_to_tanh_multiplier: i32,
179 /// Shift for `cell_to_tanh_multiplier`.
180 pub cell_to_tanh_shift: i32,
181 /// Tanh table for the cell state (output scale 1/128, zero point 0).
182 pub tanh_cell_lut: &'a [i8; LUT_SIZE],
183 /// Rescales `o * tanh(c)` to the hidden state's grid, adds its zero point
184 /// and saturates.
185 pub output_requantizer: Requantizer,
186}
187
188impl<const IN: usize, const HID: usize, C: CellStorage> QLstmCell<'_, IN, HID, C> {
189 /// One time step: reads `input`, `hidden` (h at t-1) and `cell` (c at t-1),
190 /// and leaves h and c at t in `hidden` and `cell`.
191 pub fn forward(&self, input: &[i8; IN], hidden: &mut [i8; HID], cell: &mut [C; HID]) {
192 // Every gate reads the whole previous hidden state, so all four are
193 // computed before any unit is updated.
194 let pre: [[i8; HID]; 4] = core::array::from_fn(|g| {
195 gate_preactivations(
196 input,
197 self.input_zero_point,
198 hidden,
199 self.hidden_zero_point,
200 &self.input_weights[g],
201 &self.recurrent_weights[g],
202 &self.biases[g],
203 (self.input_to_lut_multiplier[g], self.input_to_lut_shift[g]),
204 (
205 self.recurrent_to_lut_multiplier[g],
206 self.recurrent_to_lut_shift[g],
207 ),
208 )
209 });
210 let [pre_i, pre_f, pre_g, pre_o] = ⪯
211
212 let cell_zp: i32 = self.cell_zero_point.into();
213 let cell_lo: i32 = self.cell_qmin.into();
214 let cell_hi: i32 = self.cell_qmax.into();
215 let units = hidden.iter_mut().zip(cell.iter_mut());
216 let gates = pre_i.iter().zip(pre_f).zip(pre_g).zip(pre_o);
217 for ((h, c), (((&pi, &pf), &pg), &po)) in units.zip(gates) {
218 // Sigmoid outputs less their zero point (0..=255, i.e. 0 to 255/256);
219 // tanh's zero point is 0.
220 let i = i32::from(apply_lut(pi, self.sigmoid_lut)) - SIGMOID_ZERO_POINT;
221 let f = i32::from(apply_lut(pf, self.sigmoid_lut)) - SIGMOID_ZERO_POINT;
222 let g = i32::from(apply_lut(pg, self.tanh_lut));
223 let o = i32::from(apply_lut(po, self.sigmoid_lut)) - SIGMOID_ZERO_POINT;
224
225 let c_prev: i32 = (*c).into();
226 let scaled_fc = multiply_by_quantized_multiplier(
227 f * (c_prev - cell_zp),
228 self.f_times_c_multiplier,
229 self.f_times_c_shift,
230 );
231 let scaled_ig = multiply_by_quantized_multiplier(
232 i * g,
233 self.i_times_g_multiplier,
234 self.i_times_g_shift,
235 );
236 let mut c_new = scaled_fc.wrapping_add(scaled_ig).wrapping_add(cell_zp);
237 // Two tests, as in the C++: with qmin > qmax the result is qmax.
238 if c_new < cell_lo {
239 c_new = cell_lo;
240 }
241 if c_new > cell_hi {
242 c_new = cell_hi;
243 }
244 *c = C::narrow(c_new);
245
246 let tanh_index = saturate_i8(multiply_by_quantized_multiplier(
247 c_new - cell_zp,
248 self.cell_to_tanh_multiplier,
249 self.cell_to_tanh_shift,
250 ));
251 let tanh_c = i32::from(apply_lut(tanh_index, self.tanh_cell_lut));
252 *h = self.output_requantizer.apply(o * tanh_c);
253 }
254 }
255}
256
257/// One time step of a quantized GRU cell with `IN` int8 inputs and `HID`
258/// hidden units (C++ `QGRUCell`), the reset-before-multiply variant:
259///
260/// - `r = sigmoid(W_r x + R_r h + b_r)`, `z = sigmoid(W_z x + R_z h + b_z)`
261/// - `n = tanh(W_n x + R_n (r * h) + b_n)`
262/// - `h' = (1 - z) * n + z * h`
263///
264/// This is not PyTorch's `nn.GRU` (nor Keras' default, `reset_after=True`),
265/// which computes `n = tanh(W_n x + b_in + r * (R_n h + b_hn))`, so a model
266/// trained that way does not run on this cell.
267///
268/// Gates are in the order reset `r`, update `z`, new `n`, and the weights are
269/// gate-major, `input_weights[gate][unit][input]`, symmetric int8. Each gate's
270/// sums are rescaled to the LUT input grid and added to the bias as in
271/// [`QLstmCell`], with the same fixed LUT output grids. `r * h` is rescaled to
272/// the hidden state's grid (and saturated to int8) before `R_n` multiplies it;
273/// `h'` is rescaled to that grid too and clamped to `[output_qmin,
274/// output_qmax]`.
275///
276/// The cell borrows its weights, biases and LUTs, and
277/// [`forward`](Self::forward) updates the caller's hidden state in place.
278/// Build the multipliers and shifts from float scales with
279/// `calibration::build_gru_params` (`std` feature), or write them out.
280///
281/// ```
282/// use tinymind::int8::QGruCell;
283///
284/// // With zero weights and biases, these LUTs make the update gate z 0.5 (0
285/// // in the sigmoid grid) and the candidate n 0, so each step halves the
286/// // hidden state: z * h, with z centred at 128 and z_times_h 2^-8.
287/// static ZERO_LUT: [i8; 256] = [0; 256];
288/// let cell: QGruCell<'_, 2, 3> = QGruCell {
289/// input_weights: &[[[0; 2]; 3]; 3],
290/// recurrent_weights: &[[[0; 3]; 3]; 3],
291/// biases: &[[0; 3]; 3],
292/// input_zero_point: 0,
293/// hidden_zero_point: 0,
294/// input_to_lut_multiplier: [1 << 30; 3],
295/// input_to_lut_shift: [0; 3],
296/// recurrent_to_lut_multiplier: [1 << 30; 3],
297/// recurrent_to_lut_shift: [0; 3],
298/// sigmoid_lut: &ZERO_LUT,
299/// tanh_lut: &ZERO_LUT,
300/// r_times_h_multiplier: 1 << 30,
301/// r_times_h_shift: 7,
302/// one_minus_z_times_n_multiplier: 1 << 30,
303/// one_minus_z_times_n_shift: 7,
304/// z_times_h_multiplier: 1 << 30,
305/// z_times_h_shift: 7,
306/// output_qmin: -128,
307/// output_qmax: 127,
308/// };
309/// let mut hidden = [64i8, -40, 7];
310/// cell.forward(&[10, -10], &mut hidden);
311/// assert_eq!(hidden, [32, -20, 4]); // 3.5 rounds away from zero
312/// ```
313#[derive(Clone, Copy, Debug)]
314pub struct QGruCell<'a, const IN: usize, const HID: usize> {
315 /// `input_weights[gate][unit][input]`, gates in the order r, z, n.
316 pub input_weights: &'a [[[i8; IN]; HID]; 3],
317 /// `recurrent_weights[gate][unit][previous unit]`.
318 pub recurrent_weights: &'a [[[i8; HID]; HID]; 3],
319 /// `biases[gate][unit]`, in the LUT input grid.
320 pub biases: &'a [[i32; HID]; 3],
321 /// The input tensor's zero point.
322 pub input_zero_point: i8,
323 /// The hidden state's zero point.
324 pub hidden_zero_point: i8,
325 /// Per gate, the Q0.31 multiplier rescaling the input sum to the LUT input grid.
326 pub input_to_lut_multiplier: [i32; 3],
327 /// Per gate, the shift for `input_to_lut_multiplier` (positive divides, as
328 /// in [`Requantizer`]).
329 pub input_to_lut_shift: [i32; 3],
330 /// Per gate, the multiplier rescaling the recurrent sum to the LUT input grid.
331 pub recurrent_to_lut_multiplier: [i32; 3],
332 /// Per gate, the shift for `recurrent_to_lut_multiplier`.
333 pub recurrent_to_lut_shift: [i32; 3],
334 /// Sigmoid table for the r and z gates (output scale 1/256, zero point -128).
335 pub sigmoid_lut: &'a [i8; LUT_SIZE],
336 /// Tanh table for the n gate (output scale 1/128, zero point 0).
337 pub tanh_lut: &'a [i8; LUT_SIZE],
338 /// Multiplier rescaling `r * (h - h_zp)` to the hidden grid.
339 pub r_times_h_multiplier: i32,
340 /// Shift for `r_times_h_multiplier`.
341 pub r_times_h_shift: i32,
342 /// Multiplier rescaling `(1 - z) * n` to the hidden grid.
343 pub one_minus_z_times_n_multiplier: i32,
344 /// Shift for `one_minus_z_times_n_multiplier`.
345 pub one_minus_z_times_n_shift: i32,
346 /// Multiplier rescaling `z * (h - h_zp)` to the hidden grid.
347 pub z_times_h_multiplier: i32,
348 /// Shift for `z_times_h_multiplier`.
349 pub z_times_h_shift: i32,
350 /// Lowest hidden state. If `output_qmin > output_qmax` the hidden state is
351 /// `output_qmax`.
352 pub output_qmin: i8,
353 /// Highest hidden state.
354 pub output_qmax: i8,
355}
356
357impl<const IN: usize, const HID: usize> QGruCell<'_, IN, HID> {
358 /// One time step: reads `input` and `hidden` (h at t-1) and leaves h at t
359 /// in `hidden`.
360 pub fn forward(&self, input: &[i8; IN], hidden: &mut [i8; HID]) {
361 let h_zp = i32::from(self.hidden_zero_point);
362 let gate = |g: usize, recurrent: &[i8; HID]| {
363 gate_preactivations(
364 input,
365 self.input_zero_point,
366 recurrent,
367 self.hidden_zero_point,
368 &self.input_weights[g],
369 &self.recurrent_weights[g],
370 &self.biases[g],
371 (self.input_to_lut_multiplier[g], self.input_to_lut_shift[g]),
372 (
373 self.recurrent_to_lut_multiplier[g],
374 self.recurrent_to_lut_shift[g],
375 ),
376 )
377 };
378 let r = gate(0, hidden).map(|p| apply_lut(p, self.sigmoid_lut));
379 let z = gate(1, hidden).map(|p| apply_lut(p, self.sigmoid_lut));
380
381 // r * h in the hidden grid, the recurrent input of the n gate.
382 let mut rh = [0i8; HID];
383 for ((out, &r), &h) in rh.iter_mut().zip(&r).zip(hidden.iter()) {
384 let product = (i32::from(r) - SIGMOID_ZERO_POINT) * (i32::from(h) - h_zp);
385 let scaled = multiply_by_quantized_multiplier(
386 product,
387 self.r_times_h_multiplier,
388 self.r_times_h_shift,
389 );
390 *out = saturate_i8(scaled.wrapping_add(h_zp));
391 }
392 let n = gate(2, &rh).map(|p| apply_lut(p, self.tanh_lut));
393
394 let lo = i32::from(self.output_qmin);
395 let hi = i32::from(self.output_qmax);
396 for ((h, &z), &n) in hidden.iter_mut().zip(&z).zip(&n) {
397 // 1 - z in the sigmoid grid less its zero point: 128 - z (1..=256).
398 let one_minus_z = -SIGMOID_ZERO_POINT - i32::from(z);
399 let z_centered = i32::from(z) - SIGMOID_ZERO_POINT;
400 let scaled_a = multiply_by_quantized_multiplier(
401 one_minus_z * i32::from(n),
402 self.one_minus_z_times_n_multiplier,
403 self.one_minus_z_times_n_shift,
404 );
405 let scaled_b = multiply_by_quantized_multiplier(
406 z_centered * (i32::from(*h) - h_zp),
407 self.z_times_h_multiplier,
408 self.z_times_h_shift,
409 );
410 let mut h_new = scaled_a.wrapping_add(scaled_b).wrapping_add(h_zp);
411 if h_new < lo {
412 h_new = lo;
413 }
414 if h_new > hi {
415 h_new = hi;
416 }
417 *h = h_new as i8;
418 }
419 }
420}