tinymind/int8/compose.rs
1//! Int8 composition layers, ported from tinymind (C++) `cpp/qmul.hpp`,
2//! `cpp/qpad.hpp` and `cpp/qconcat.hpp`: elementwise multiplication, explicit
3//! padding and channel concatenation. Re-exported from [`int8`](super).
4
5use super::{FastRequantizer, Requantizer, Tensor};
6
7/// Elementwise multiplication of two int8 tensors with their own zero points
8/// (C++ `QMul`, TFLite MUL): squeeze-and-excite gating in MobileNet-V3 and
9/// EfficientNet. `out = requantize((a - zp_a) * (b - zp_b))`, where the
10/// requantizer encodes `scale_a * scale_b / scale_out`
11/// (`calibration::build_mul_requantizer`).
12///
13/// ```
14/// use tinymind::int8::{QMul, Requantizer};
15///
16/// // Scales 1/4, 1/4 and 1/16: the product of the real values, in quarters
17/// // times quarters, is exact on the output grid (ratio 1, shift -1 then 1/2).
18/// let mul = QMul {
19/// input_a_zero_point: 0,
20/// input_b_zero_point: 2,
21/// requantizer: Requantizer { multiplier: 1 << 30, shift: -1, zero_point: 0, qmin: -128, qmax: 127 },
22/// };
23/// let a = [[4i8, -8], [3, 0]];
24/// let b = [[6i8, 4], [2, 9]];
25/// let mut y = [[0i8; 2]; 2];
26/// mul.forward(&a, &b, &mut y);
27/// assert_eq!(y, [[16, -16], [0, 0]]);
28/// ```
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct QMul {
31 /// Zero point of the first input.
32 pub input_a_zero_point: i8,
33 /// Zero point of the second input.
34 pub input_b_zero_point: i8,
35 /// Rescales each product to the output: `scale_a * scale_b / scale_out`,
36 /// the output zero point and the saturation range.
37 pub requantizer: Requantizer,
38}
39
40impl QMul {
41 /// `out = a * b` element by element. The three tensors have the same type,
42 /// so the same shape (see [`Tensor`]).
43 pub fn forward<T: Tensor>(&self, a: &T, b: &T, out: &mut T) {
44 let (a, b, out) = (a.as_flat(), b.as_flat(), out.as_flat_mut());
45 let (za, zb) = (
46 i32::from(self.input_a_zero_point),
47 i32::from(self.input_b_zero_point),
48 );
49 // |a - zp_a| * |b - zp_b| <= 255 * 255: the product fits an i32.
50 let products = a
51 .iter()
52 .zip(b)
53 .map(|(&x, &y)| (i32::from(x) - za) * (i32::from(y) - zb));
54 match FastRequantizer::new(&self.requantizer) {
55 Some(rq) => {
56 for (o, p) in out.iter_mut().zip(products) {
57 *o = rq.apply(p);
58 }
59 }
60 None => {
61 for (o, p) in out.iter_mut().zip(products) {
62 *o = self.requantizer.apply(p);
63 }
64 }
65 }
66 }
67}
68
69/// `a + b + c == d`, without overflowing.
70const fn sums_to(a: usize, b: usize, c: usize, d: usize) -> bool {
71 match a.checked_add(b) {
72 Some(ab) => match ab.checked_add(c) {
73 Some(abc) => abc == d,
74 None => false,
75 },
76 None => false,
77 }
78}
79
80/// Explicit spatial padding of an NHWC tensor with a constant (C++ `QPad2D`,
81/// TFLite PAD): `PT` rows above, `PB` below, `PL` columns on the left and
82/// `PR` on the right, each holding `pad_value` in every channel. The
83/// convolution layers pad by themselves; this is for models with a separate
84/// PAD operator. The output must be `H + PT + PB` by `W + PL + PR`, or the call
85/// does not compile.
86///
87/// ```
88/// use tinymind::int8::QPad2D;
89///
90/// let input = [[[1i8, 2]; 2]; 1];
91/// let mut padded = [[[0i8; 2]; 3]; 2]; // one row below, one column on the left
92/// QPad2D::<0, 1, 1, 0> { pad_value: -7 }.forward(&input, &mut padded);
93/// assert_eq!(padded, [[[-7, -7], [1, 2], [1, 2]], [[-7, -7]; 3]]);
94/// ```
95///
96/// A padded size that does not add up does not compile:
97///
98/// ```compile_fail
99/// # use tinymind::int8::QPad2D;
100/// let input = [[[1i8, 2]; 2]; 1];
101/// let mut padded = [[[0i8; 2]; 4]; 2]; // 4 columns: 2 + 1 + 0 is 3
102/// QPad2D::<0, 1, 1, 0> { pad_value: -7 }.forward(&input, &mut padded);
103/// ```
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct QPad2D<const PT: usize, const PB: usize, const PL: usize, const PR: usize> {
106 /// The value every padded element holds: the tensor's zero point for a
107 /// real 0.0, as TFLite pads.
108 pub pad_value: i8,
109}
110
111impl<const PT: usize, const PB: usize, const PL: usize, const PR: usize> QPad2D<PT, PB, PL, PR> {
112 /// Pad an `H` x `W` x `C` input into an `OH` x `OW` x `C` output.
113 pub fn forward<
114 const H: usize,
115 const W: usize,
116 const C: usize,
117 const OH: usize,
118 const OW: usize,
119 >(
120 &self,
121 input: &[[[i8; C]; W]; H],
122 output: &mut [[[i8; C]; OW]; OH],
123 ) {
124 const {
125 assert!(
126 sums_to(H, PT, PB, OH) && sums_to(W, PL, PR, OW),
127 "QPad2D: the output size is not the input size plus the padding"
128 )
129 };
130 for (oh, out_row) in output.iter_mut().enumerate() {
131 let row = oh.checked_sub(PT).and_then(|r| input.get(r));
132 for (ow, pixel) in out_row.iter_mut().enumerate() {
133 let x = row.and_then(|r| ow.checked_sub(PL).and_then(|c| r.get(c)));
134 *pixel = x.copied().unwrap_or([self.pad_value; C]);
135 }
136 }
137 }
138}
139
140/// Concatenation of two NHWC tensors along the channel axis (C++
141/// `QConcat2_2D`, TFLite CONCATENATION on the last axis): the output's
142/// channels are the first input's, then the second's, each rescaled onto the
143/// output grid by its own requantizer (`calibration::build_rescaler`). The
144/// output's channel count must be `CA + CB`, or the call does not compile.
145///
146/// ```
147/// use tinymind::int8::{QConcat, Requantizer};
148///
149/// // Both inputs already on the output grid: ratio 1 (multiplier 2^30, shift -1).
150/// let same = Requantizer { multiplier: 1 << 30, shift: -1, zero_point: 0, qmin: -128, qmax: 127 };
151/// let concat = QConcat { input_a_zero_point: 0, input_b_zero_point: 0, requantizer_a: same, requantizer_b: same };
152/// let a = [[[1i8]; 2]; 1];
153/// let b = [[[2i8, 3]; 2]; 1];
154/// let mut y = [[[0i8; 3]; 2]; 1];
155/// concat.forward(&a, &b, &mut y);
156/// assert_eq!(y, [[[1, 2, 3]; 2]]);
157/// ```
158///
159/// An output whose channels are not the two inputs' together does not compile:
160///
161/// ```compile_fail
162/// # use tinymind::int8::{QConcat, Requantizer};
163/// # let same = Requantizer { multiplier: 1 << 30, shift: -1, zero_point: 0, qmin: -128, qmax: 127 };
164/// # let concat = QConcat { input_a_zero_point: 0, input_b_zero_point: 0, requantizer_a: same, requantizer_b: same };
165/// let a = [[[1i8]; 2]; 1];
166/// let b = [[[2i8, 3]; 2]; 1];
167/// let mut y = [[[0i8; 4]; 2]; 1]; // 4 channels: 1 + 2 is 3
168/// concat.forward(&a, &b, &mut y);
169/// ```
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub struct QConcat {
172 /// Zero point of the first input.
173 pub input_a_zero_point: i8,
174 /// Zero point of the second input.
175 pub input_b_zero_point: i8,
176 /// Rescales the first input to the output: `scale_a / scale_out`.
177 pub requantizer_a: Requantizer,
178 /// Rescales the second input to the output: `scale_b / scale_out`.
179 pub requantizer_b: Requantizer,
180}
181
182impl QConcat {
183 /// Concatenate `a` (`CA` channels) and `b` (`CB` channels) into `out`
184 /// (`C = CA + CB` channels), pixel by pixel.
185 pub fn forward<
186 const H: usize,
187 const W: usize,
188 const CA: usize,
189 const CB: usize,
190 const C: usize,
191 >(
192 &self,
193 a: &[[[i8; CA]; W]; H],
194 b: &[[[i8; CB]; W]; H],
195 out: &mut [[[i8; C]; W]; H],
196 ) {
197 const {
198 assert!(
199 CA > 0 && CB > 0 && sums_to(CA, CB, 0, C),
200 "QConcat: the output's channels must be the two inputs' channels together"
201 )
202 };
203 let (za, zb) = (
204 i32::from(self.input_a_zero_point),
205 i32::from(self.input_b_zero_point),
206 );
207 let pixels = out
208 .as_flattened_mut()
209 .iter_mut()
210 .zip(a.as_flattened())
211 .zip(b.as_flattened());
212 for ((y, xa), xb) in pixels {
213 let (ya, yb) = y.split_at_mut(CA.min(C));
214 for (o, &x) in ya.iter_mut().zip(xa) {
215 *o = self.requantizer_a.apply(i32::from(x) - za);
216 }
217 for (o, &x) in yb.iter_mut().zip(xb) {
218 *o = self.requantizer_b.apply(i32::from(x) - zb);
219 }
220 }
221 }
222}