tinymind/int8/add.rs
1//! Int8 elementwise addition, ported from tinymind (C++) `cpp/qadd.hpp`.
2//! Re-exported from [`int8`](super).
3
4use super::{FastRequantizer, Requantizer, multiply_by_quantized_multiplier, saturating_shl};
5
6// The sum of the two rescaled inputs wraps where the C++ sum would overflow
7// (outside its contract).
8
9/// Elementwise addition of two int8 tensors with their own scales and zero
10/// points, into a third (C++ `QAdd`, TFLite ADD): the skip connections of
11/// ResNet and MobileNet-V2.
12///
13/// Each input, less its zero point, is shifted left by `left_shift` (20 in
14/// TFLite) and rescaled by its own multiplier to a common scale, twice the
15/// larger input scale; the `i32` sum is then requantized to the output.
16/// A fused ReLU raises `output_requantizer.qmin` to the output zero point.
17/// Build one from float scales with `calibration::build_add` (`std` feature),
18/// or write the integers out as constants.
19///
20/// ```
21/// use tinymind::int8::{QAdd, Requantizer};
22///
23/// // Both inputs and the output share one scale (left shift 20, then 1/2, then
24/// // 2^-19 back): the sum of the real values, on the same grid.
25/// const ADD: QAdd = QAdd {
26/// input_a_zero_point: 0,
27/// input_b_zero_point: 0,
28/// left_shift: 20,
29/// input_a_multiplier: 1 << 30,
30/// input_a_shift: 0,
31/// input_b_multiplier: 1 << 30,
32/// input_b_shift: 0,
33/// output_requantizer: Requantizer {
34/// multiplier: 1 << 30,
35/// shift: 18,
36/// zero_point: 0,
37/// qmin: -128,
38/// qmax: 127,
39/// },
40/// };
41/// let a = [[[10i8, -20]; 3]; 2];
42/// let b = [[[5i8, 100]; 3]; 2];
43/// let mut sum = [[[0i8; 2]; 3]; 2];
44/// ADD.forward(&a, &b, &mut sum);
45/// assert_eq!(sum[1][2], [15, 80]);
46/// ```
47///
48/// Tensors of different shapes do not compile:
49///
50/// ```compile_fail
51/// # use tinymind::int8::{QAdd, Requantizer};
52/// # let rq = Requantizer { multiplier: 1 << 30, shift: 18, zero_point: 0, qmin: -128, qmax: 127 };
53/// # let add = QAdd { input_a_zero_point: 0, input_b_zero_point: 0, left_shift: 20,
54/// # input_a_multiplier: 1 << 30, input_a_shift: 0, input_b_multiplier: 1 << 30,
55/// # input_b_shift: 0, output_requantizer: rq };
56/// let a = [[[0i8; 2]; 3]; 2];
57/// let b = [[[0i8; 2]; 2]; 3]; // 3 x 2, not 2 x 3
58/// let mut sum = [[[0i8; 2]; 3]; 2];
59/// add.forward(&a, &b, &mut sum);
60/// ```
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct QAdd {
63 /// Zero point of the first input.
64 pub input_a_zero_point: i8,
65 /// Zero point of the second input.
66 pub input_b_zero_point: i8,
67 /// Left shift applied to each input less its zero point, before rescaling:
68 /// head room for the multipliers. tinymind (C++)'s contract is `0..=23`
69 /// (the shifted value fits an `i32`); a negative one is treated as 0, and a
70 /// larger one saturates.
71 pub left_shift: i32,
72 /// Q0.31 multiplier rescaling the first input to the common scale.
73 pub input_a_multiplier: i32,
74 /// Shift for `input_a_multiplier` (positive divides, as in [`Requantizer`]).
75 pub input_a_shift: i32,
76 /// Q0.31 multiplier rescaling the second input to the common scale.
77 pub input_b_multiplier: i32,
78 /// Shift for `input_b_multiplier`.
79 pub input_b_shift: i32,
80 /// Rescales the `i32` sum to the output: its multiplier and shift, the
81 /// output zero point and the saturation range.
82 pub output_requantizer: Requantizer,
83}
84
85/// Elements from which [`QAdd::forward`] tabulates each input's rescaling:
86/// building the two 256-entry tables costs about as much as rescaling 190
87/// elements one by one.
88const TABLE_MIN_ELEMENTS: usize = 256;
89
90impl QAdd {
91 /// `out = a + b` element by element. The three tensors have the same type,
92 /// so the same shape: a flat `[i8; N]`, a row `[[i8; C]; W]` or an NHWC
93 /// tensor `[[[i8; C]; W]; H]`.
94 ///
95 /// From 256 elements, each input's rescaling is tabulated first for all
96 /// 256 int8 values (2 KB of stack), so an element costs two table reads, an
97 /// add and the requantizer: about a ninth of the cycles on a Cortex-M4.
98 /// The table holds the same values the element-wise form computes.
99 pub fn forward<T: Tensor>(&self, a: &T, b: &T, out: &mut T) {
100 let (a, b, out) = (a.as_flat(), b.as_flat(), out.as_flat_mut());
101 if out.len() < TABLE_MIN_ELEMENTS {
102 for ((o, &x), &y) in out.iter_mut().zip(a).zip(b) {
103 *o = self
104 .output_requantizer
105 .apply(self.scaled_a(x).wrapping_add(self.scaled_b(y)));
106 }
107 return;
108 }
109 let mut table_a = [0i32; 256];
110 let mut table_b = [0i32; 256];
111 for (i, (ta, tb)) in table_a.iter_mut().zip(table_b.iter_mut()).enumerate() {
112 let x = i as u8 as i8;
113 *ta = self.scaled_a(x);
114 *tb = self.scaled_b(x);
115 }
116 let sums = a.iter().zip(b).map(|(&x, &y)| {
117 table_a[usize::from(x as u8)].wrapping_add(table_b[usize::from(y as u8)])
118 });
119 match FastRequantizer::new(&self.output_requantizer) {
120 Some(rq) => {
121 for (o, sum) in out.iter_mut().zip(sums) {
122 *o = rq.apply(sum);
123 }
124 }
125 None => {
126 for (o, sum) in out.iter_mut().zip(sums) {
127 *o = self.output_requantizer.apply(sum);
128 }
129 }
130 }
131 }
132
133 /// The first input less its zero point, shifted left and rescaled to the
134 /// common scale.
135 #[inline]
136 fn scaled_a(&self, a: i8) -> i32 {
137 let a_minus_zp = i32::from(a) - i32::from(self.input_a_zero_point);
138 multiply_by_quantized_multiplier(
139 saturating_shl(a_minus_zp, self.left_shift.max(0).unsigned_abs()),
140 self.input_a_multiplier,
141 self.input_a_shift,
142 )
143 }
144
145 /// The same for the second input.
146 #[inline]
147 fn scaled_b(&self, b: i8) -> i32 {
148 let b_minus_zp = i32::from(b) - i32::from(self.input_b_zero_point);
149 multiply_by_quantized_multiplier(
150 saturating_shl(b_minus_zp, self.left_shift.max(0).unsigned_abs()),
151 self.input_b_multiplier,
152 self.input_b_shift,
153 )
154 }
155}
156
157mod sealed {
158 pub trait Sealed {}
159}
160
161/// An int8 tensor for the elementwise layers ([`QAdd`], [`QMul`](super::QMul)): `[i8; N]`,
162/// `[[i8; C]; W]` or `[[[i8; C]; W]; H]`, read as its elements in memory
163/// order. Sealed: the crate implements it.
164pub trait Tensor: sealed::Sealed {
165 /// The elements in memory order.
166 fn as_flat(&self) -> &[i8];
167 /// The elements in memory order, mutable.
168 fn as_flat_mut(&mut self) -> &mut [i8];
169}
170
171impl<const N: usize> sealed::Sealed for [i8; N] {}
172impl<const N: usize> Tensor for [i8; N] {
173 fn as_flat(&self) -> &[i8] {
174 self
175 }
176 fn as_flat_mut(&mut self) -> &mut [i8] {
177 self
178 }
179}
180
181impl<const W: usize, const C: usize> sealed::Sealed for [[i8; C]; W] {}
182impl<const W: usize, const C: usize> Tensor for [[i8; C]; W] {
183 fn as_flat(&self) -> &[i8] {
184 self.as_flattened()
185 }
186 fn as_flat_mut(&mut self) -> &mut [i8] {
187 self.as_flattened_mut()
188 }
189}
190
191impl<const H: usize, const W: usize, const C: usize> sealed::Sealed for [[[i8; C]; W]; H] {}
192impl<const H: usize, const W: usize, const C: usize> Tensor for [[[i8; C]; W]; H] {
193 fn as_flat(&self) -> &[i8] {
194 self.as_flattened().as_flattened()
195 }
196 fn as_flat_mut(&mut self) -> &mut [i8] {
197 self.as_flattened_mut().as_flattened_mut()
198 }
199}