Skip to main content

tinymind/int8/
conv.rs

1//! Int8 convolutions over NHWC tensors, ported from tinymind (C++)
2//! `cpp/qconv2d.hpp`, `cpp/qdepthwiseconv2d.hpp` and `cpp/qpointwiseconv2d.hpp`.
3//! Re-exported from [`int8`](super); the conventions are in its module docs.
4
5use super::{FastRequantizer, Requantizer, dot_with_zero_point};
6
7/// Whether `out` is the size a window of `kernel` at `stride` produces over
8/// `input` padded by `before` and `after`, `(input + before + after - kernel)
9/// / stride + 1`, on a valid layer: stride and kernel above zero, kernel no
10/// larger than the padded input. Every layer checks it at compile time.
11pub(crate) const fn window_fits(
12    input: usize,
13    kernel: usize,
14    stride: usize,
15    before: usize,
16    after: usize,
17    out: usize,
18) -> bool {
19    let Some(padded) = input.checked_add(before) else {
20        return false;
21    };
22    let Some(padded) = padded.checked_add(after) else {
23        return false;
24    };
25    stride > 0 && kernel > 0 && padded >= kernel && (padded - kernel) / stride + 1 == out
26}
27
28/// The input element at padded position (`row`, `column`), or `None` in the
29/// padding.
30#[inline]
31pub(crate) fn tap<T, const W: usize, const H: usize>(
32    input: &[[T; W]; H],
33    row: usize,
34    column: usize,
35    pad_top: usize,
36    pad_left: usize,
37) -> Option<&T> {
38    let r = row.checked_sub(pad_top)?;
39    let c = column.checked_sub(pad_left)?;
40    input.get(r)?.get(c)
41}
42
43/// `biases[i]`, or 0 without biases.
44#[inline]
45fn bias_of<const N: usize>(biases: Option<&[i32; N]>, i: usize) -> i32 {
46    biases.map_or(0, |b| b.get(i).copied().unwrap_or(0))
47}
48
49/// A window's strides and its padding before the first row and column.
50#[derive(Clone, Copy)]
51pub(crate) struct Window {
52    pub(crate) stride_h: usize,
53    pub(crate) stride_w: usize,
54    pub(crate) pad_top: usize,
55    pub(crate) pad_left: usize,
56    /// Any padding at all. Without it every window lies inside the input, so
57    /// a layer needs no code for windows that reach into the padding.
58    pub(crate) padded: bool,
59}
60
61// The bodies of `QConv2D` and `QConv2DPerChannel` (`conv2d_gather`,
62// `conv2d_band`) take `rqs` yielding filter `f`'s requantizer as its `f`-th
63// item (the per-tensor layer repeats one). Both compute `acc = bias + sum
64// over the window of w * (x - zero_point)`; a padded tap holds the zero
65// point, as TFLite pads, so it adds nothing. tinymind (C++) gathers patches,
66// tiles rows and pairs filters for speed; those add the same products, and
67// `i32` sums wrap the same in any order.
68
69/// The convolution for layers with fewer than [`BAND_MIN_CHANNELS`] input
70/// channels (a stem over one channel): per output pixel the window is gathered once
71/// into `win`, the padding filled with the zero point, so every filter runs a
72/// plain multiply-accumulate against it with the zero point folded into its
73/// bias (a padded tap then adds `w * zp - w * zp = 0`).
74/// Filters run in pairs, so each window value loaded serves two. Same `i32`
75/// sums modulo 2^32.
76#[allow(clippy::too_many_arguments)]
77fn conv2d_gather<
78    'r,
79    const H: usize,
80    const W: usize,
81    const C: usize,
82    const KH: usize,
83    const KW: usize,
84    const F: usize,
85    const OH: usize,
86    const OW: usize,
87>(
88    input: &[[[i8; C]; W]; H],
89    output: &mut [[[i8; F]; OW]; OH],
90    weights: &[[[[i8; C]; KW]; KH]; F],
91    biases: Option<&[i32; F]>,
92    zero_point: i8,
93    rqs: impl Iterator<Item = &'r Requantizer> + Clone,
94    window: Window,
95) {
96    let folded: [i32; F] = core::array::from_fn(|f| {
97        let taps = weights
98            .get(f)
99            .into_iter()
100            .flatten()
101            .flatten()
102            .flatten()
103            .copied();
104        folded_bias(bias_of(biases, f), zero_point, taps)
105    });
106    let requantize = |f: usize, acc: i32| rqs.clone().nth(f).map_or(0, |rq| rq.apply(acc));
107    let mut win = [[[zero_point; C]; KW]; KH];
108    for (oh, out_row) in output.iter_mut().enumerate() {
109        let top = oh * window.stride_h;
110        for (ow, out_pixel) in out_row.iter_mut().enumerate() {
111            let left = ow * window.stride_w;
112            for (kh, win_row) in win.iter_mut().enumerate() {
113                for (kw, taps) in win_row.iter_mut().enumerate() {
114                    *taps = *tap(input, top + kh, left + kw, window.pad_top, window.pad_left)
115                        .unwrap_or(&[zero_point; C]);
116                }
117            }
118            let x = win.as_flattened().as_flattened();
119            let mut f = 0;
120            while f + 1 < F {
121                if let (Some(w0), Some(w1)) = (weights.get(f), weights.get(f + 1)) {
122                    let (a0, a1) = dot2(
123                        x,
124                        w0.as_flattened().as_flattened(),
125                        w1.as_flattened().as_flattened(),
126                    );
127                    let b0 = folded.get(f).copied().unwrap_or(0);
128                    let b1 = folded.get(f + 1).copied().unwrap_or(0);
129                    if let Some(out) = out_pixel.get_mut(f) {
130                        *out = requantize(f, b0.wrapping_add(a0));
131                    }
132                    if let Some(out) = out_pixel.get_mut(f + 1) {
133                        *out = requantize(f + 1, b1.wrapping_add(a1));
134                    }
135                }
136                f += 2;
137            }
138            if let (Some(wf), Some(out), Some(&b)) =
139                (weights.get(f), out_pixel.get_mut(f), folded.get(f))
140            {
141                let wf = wf.as_flattened().as_flattened();
142                let (a, _) = dot2(x, wf, wf);
143                *out = requantize(f, b.wrapping_add(a));
144            }
145        }
146    }
147}
148
149/// Input channels from which [`QConv2D`] and [`QConv2DPerChannel`] take
150/// [`conv2d_band`]. With fewer (a stem over one or a few channels) the window
151/// is too short to pair, and reading each window once for all filters wins.
152const BAND_MIN_CHANNELS: usize = 2;
153
154/// `acc + sum x[i] * w[i]` over the shorter of the two rows, wrapping. Written
155/// as pairs of products added to one accumulator: on Cortex-M cores with the
156/// DSP extension (M4, M7, M33), LLVM's Arm parallel-DSP pass turns each pair
157/// of adjacent `i16` products into one `SMLAD`, whose sum wraps like
158/// `wrapping_add`.
159#[inline(always)]
160fn dot16(mut acc: i32, x: &[i16], w: &[i16]) -> i32 {
161    let n = x.len().min(w.len());
162    let mut i = 0;
163    while i + 1 < n && i + 1 < x.len() && i + 1 < w.len() {
164        let p0 = i32::from(x[i]) * i32::from(w[i]);
165        let p1 = i32::from(x[i + 1]) * i32::from(w[i + 1]);
166        acc = acc.wrapping_add(p0).wrapping_add(p1);
167        i += 2;
168    }
169    if let (Some(&x), Some(&w)) = (x.get(i), w.get(i)) {
170        if i < n {
171            acc = acc.wrapping_add(i32::from(x) * i32::from(w));
172        }
173    }
174    acc
175}
176
177/// The convolution for layers with several input channels, in 16 bits: per output
178/// row, the `KH` input rows it reads are widened once into `band` as `x -
179/// zero_point` (`i16`), and per filter its weights into `wide`; each window
180/// inside the input is then `KH` dot products over contiguous `KW * C`
181/// elements ([`dot16`]). Windows reaching into the padding add tap by tap.
182/// Widening costs one pass over the rows and over the weights per output row,
183/// small against the `OW * KH * KW * C` products per filter; the scratch is
184/// `2 * KH * (W + KW) * C` bytes of stack. Same `i32` sums modulo 2^32.
185#[allow(clippy::too_many_arguments)]
186fn conv2d_band<
187    'r,
188    const H: usize,
189    const W: usize,
190    const C: usize,
191    const KH: usize,
192    const KW: usize,
193    const F: usize,
194    const OH: usize,
195    const OW: usize,
196>(
197    input: &[[[i8; C]; W]; H],
198    output: &mut [[[i8; F]; OW]; OH],
199    weights: &[[[[i8; C]; KW]; KH]; F],
200    biases: Option<&[i32; F]>,
201    zero_point: i8,
202    rqs: impl Iterator<Item = &'r Requantizer> + Clone,
203    window: Window,
204) {
205    let mut band = [[[0i16; C]; W]; KH];
206    let mut valid = [false; KH];
207    let mut wide = [[[0i16; C]; KW]; KH];
208    let zp = i16::from(zero_point);
209    for (oh, out_row) in output.iter_mut().enumerate() {
210        let top = oh * window.stride_h;
211        for (kh, (band_row, ok)) in band.iter_mut().zip(valid.iter_mut()).enumerate() {
212            let row = (top + kh)
213                .checked_sub(window.pad_top)
214                .and_then(|r| input.get(r));
215            *ok = row.is_some();
216            if let Some(row) = row {
217                for (b, &x) in band_row
218                    .as_flattened_mut()
219                    .iter_mut()
220                    .zip(row.as_flattened())
221                {
222                    *b = i16::from(x) - zp;
223                }
224            }
225        }
226        for (f, (filter, rq)) in weights.iter().zip(rqs.clone()).enumerate() {
227            for (wide_row, filter_row) in wide.iter_mut().zip(filter) {
228                for (w16, &w) in wide_row
229                    .as_flattened_mut()
230                    .iter_mut()
231                    .zip(filter_row.as_flattened())
232                {
233                    *w16 = i16::from(w);
234                }
235            }
236            let rows = BandRows {
237                band: &band,
238                valid: &valid,
239                wide: &wide,
240                bias: bias_of(biases, f),
241                window,
242            };
243            match FastRequantizer::new(rq) {
244                Some(fast) => rows.run(out_row, f, |acc| fast.apply(acc)),
245                None => rows.run_general(out_row, f, rq),
246            }
247        }
248    }
249}
250
251/// One output row of one filter in [`conv2d_band`].
252struct BandRows<'t, const W: usize, const C: usize, const KH: usize, const KW: usize> {
253    band: &'t [[[i16; C]; W]; KH],
254    valid: &'t [bool; KH],
255    wide: &'t [[[i16; C]; KW]; KH],
256    bias: i32,
257    window: Window,
258}
259
260impl<const W: usize, const C: usize, const KH: usize, const KW: usize> BandRows<'_, W, C, KH, KW> {
261    /// The row for a requantizer without a prepared form, out of line and
262    /// tap by tap (the same sums as `run`, in less code): rare, so small.
263    #[cold]
264    #[inline(never)]
265    fn run_general<const F: usize, const OW: usize>(
266        &self,
267        out_row: &mut [[i8; F]; OW],
268        f: usize,
269        rq: &Requantizer,
270    ) {
271        for (ow, pixel) in out_row.iter_mut().enumerate() {
272            let acc = self.edge(ow * self.window.stride_w);
273            if let Some(out) = pixel.get_mut(f) {
274                *out = rq.apply(acc);
275            }
276        }
277    }
278
279    /// `bias + sum over the window` at padded column `left`, tap by tap: for
280    /// windows reaching into the padding.
281    #[inline(always)]
282    fn edge(&self, left: usize) -> i32 {
283        let mut acc = self.bias;
284        for ((band_row, &ok), wide_row) in self.band.iter().zip(self.valid).zip(self.wide) {
285            if !ok {
286                continue;
287            }
288            for (kw, taps) in wide_row.iter().enumerate() {
289                let x = (left + kw)
290                    .checked_sub(self.window.pad_left)
291                    .and_then(|c| band_row.get(c));
292                if let Some(x) = x {
293                    acc = dot16(acc, x, taps);
294                }
295            }
296        }
297        acc
298    }
299
300    #[inline(always)]
301    fn run<const F: usize, const OW: usize>(
302        &self,
303        out_row: &mut [[i8; F]; OW],
304        f: usize,
305        requantize: impl Fn(i32) -> i8,
306    ) {
307        let pad_left = self.window.pad_left;
308        for (ow, pixel) in out_row.iter_mut().enumerate() {
309            let left = ow * self.window.stride_w;
310            let mut acc = self.bias;
311            let interior = left
312                .checked_sub(pad_left)
313                .and_then(|c| self.band[0].get(c..c + KW).map(|_| c));
314            if let Some(c0) = interior {
315                for ((band_row, &ok), wide_row) in self.band.iter().zip(self.valid).zip(self.wide) {
316                    if let (true, Some(xs)) = (ok, band_row.get(c0..c0 + KW)) {
317                        acc = dot16(acc, xs.as_flattened(), wide_row.as_flattened());
318                    }
319                }
320            } else {
321                acc = self.edge(left);
322            }
323            if let Some(out) = pixel.get_mut(f) {
324                *out = requantize(acc);
325            }
326        }
327    }
328}
329
330/// A quantized 2D convolution with one requantizer for the whole output (C++
331/// `QConv2D<int8_t, int8_t, int32_t, int8_t, H, W, C, KH, KW, SH, SW, F, PT,
332/// PB, PL, PR>`).
333///
334/// `C` input channels, a `KH` x `KW` kernel, `F` filters, strides `SH` and
335/// `SW` (default 1) and padding `PT`, `PB`, `PL`, `PR` rows and columns
336/// (default 0, VALID). Weights are `weights[filter][row][column][channel]`
337/// (OHWI, as TFLite stores them), symmetric int8; biases are in the
338/// accumulator's scale. The layer borrows them, so they can live in flash.
339///
340/// ```
341/// use tinymind::int8::{QConv2D, Requantizer};
342///
343/// // Two 2x2 filters over a 3x3 single-channel input: a 2x2x2 output.
344/// static WEIGHTS: [[[[i8; 1]; 2]; 2]; 2] = [[[[1], [1]], [[1], [1]]], [[[1], [0]], [[0], [-1]]]];
345/// let conv: QConv2D<'_, 1, 2, 2, 2> = QConv2D {
346///     weights: &WEIGHTS,
347///     biases: None,
348///     input_zero_point: 0,
349///     requantizer: Requantizer { multiplier: 1 << 30, shift: -1, zero_point: 0, qmin: -128, qmax: 127 },
350/// };
351/// let input = [[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]];
352/// let mut output = [[[0i8; 2]; 2]; 2];
353/// conv.forward(&input, &mut output);
354/// // The sum of each window, and its top-left minus bottom-right.
355/// assert_eq!(output, [[[12, -4], [16, -4]], [[24, -4], [28, -4]]]);
356/// ```
357#[derive(Clone, Copy, Debug)]
358pub struct QConv2D<
359    'a,
360    const C: usize,
361    const KH: usize,
362    const KW: usize,
363    const F: usize,
364    const SH: usize = 1,
365    const SW: usize = 1,
366    const PT: usize = 0,
367    const PB: usize = 0,
368    const PL: usize = 0,
369    const PR: usize = 0,
370> {
371    /// `weights[f][kh][kw][c]`.
372    pub weights: &'a [[[[i8; C]; KW]; KH]; F],
373    /// One `i32` bias per filter, or `None`.
374    pub biases: Option<&'a [i32; F]>,
375    /// The input tensor's zero point, which also fills the padding.
376    pub input_zero_point: i8,
377    /// Rescales every accumulator to the output tensor's grid.
378    pub requantizer: Requantizer,
379}
380
381impl<
382    const C: usize,
383    const KH: usize,
384    const KW: usize,
385    const F: usize,
386    const SH: usize,
387    const SW: usize,
388    const PT: usize,
389    const PB: usize,
390    const PL: usize,
391    const PR: usize,
392> QConv2D<'_, C, KH, KW, F, SH, SW, PT, PB, PL, PR>
393{
394    /// One forward pass over an `H` x `W` x `C` input into an `OH` x `OW` x
395    /// `F` output. `OH` and `OW` must be what the kernel, strides and padding
396    /// produce (a compile error otherwise).
397    pub fn forward<const H: usize, const W: usize, const OH: usize, const OW: usize>(
398        &self,
399        input: &[[[i8; C]; W]; H],
400        output: &mut [[[i8; F]; OW]; OH],
401    ) {
402        const {
403            assert!(
404                C > 0
405                    && F > 0
406                    && window_fits(H, KH, SH, PT, PB, OH)
407                    && window_fits(W, KW, SW, PL, PR, OW),
408                "QConv2D: the output size does not match the input, kernel, strides and padding, or the layer is invalid"
409            )
410        };
411        let window = Window {
412            stride_h: SH,
413            stride_w: SW,
414            pad_top: PT,
415            pad_left: PL,
416            padded: PT + PB + PL + PR != 0,
417        };
418        let rqs = core::iter::repeat(&self.requantizer);
419        if C >= BAND_MIN_CHANNELS {
420            conv2d_band(
421                input,
422                output,
423                self.weights,
424                self.biases,
425                self.input_zero_point,
426                rqs,
427                window,
428            );
429        } else {
430            conv2d_gather(
431                input,
432                output,
433                self.weights,
434                self.biases,
435                self.input_zero_point,
436                rqs,
437                window,
438            );
439        }
440    }
441}
442
443/// [`QConv2D`] with one requantizer per filter, the per-channel weight
444/// quantization TFLite applies to convolutions (C++ `QConv2DPerChannel`).
445#[derive(Clone, Copy, Debug)]
446pub struct QConv2DPerChannel<
447    'a,
448    const C: usize,
449    const KH: usize,
450    const KW: usize,
451    const F: usize,
452    const SH: usize = 1,
453    const SW: usize = 1,
454    const PT: usize = 0,
455    const PB: usize = 0,
456    const PL: usize = 0,
457    const PR: usize = 0,
458> {
459    /// `weights[f][kh][kw][c]`.
460    pub weights: &'a [[[[i8; C]; KW]; KH]; F],
461    /// One `i32` bias per filter, or `None`.
462    pub biases: Option<&'a [i32; F]>,
463    /// The input tensor's zero point, which also fills the padding.
464    pub input_zero_point: i8,
465    /// `requantizers[f]` rescales filter `f`'s outputs.
466    pub requantizers: &'a [Requantizer; F],
467}
468
469impl<
470    const C: usize,
471    const KH: usize,
472    const KW: usize,
473    const F: usize,
474    const SH: usize,
475    const SW: usize,
476    const PT: usize,
477    const PB: usize,
478    const PL: usize,
479    const PR: usize,
480> QConv2DPerChannel<'_, C, KH, KW, F, SH, SW, PT, PB, PL, PR>
481{
482    /// One forward pass; see [`QConv2D::forward`].
483    pub fn forward<const H: usize, const W: usize, const OH: usize, const OW: usize>(
484        &self,
485        input: &[[[i8; C]; W]; H],
486        output: &mut [[[i8; F]; OW]; OH],
487    ) {
488        const {
489            assert!(
490                C > 0
491                    && F > 0
492                    && window_fits(H, KH, SH, PT, PB, OH)
493                    && window_fits(W, KW, SW, PL, PR, OW),
494                "QConv2DPerChannel: the output size does not match the input, kernel, strides and padding, or the layer is invalid"
495            )
496        };
497        let window = Window {
498            stride_h: SH,
499            stride_w: SW,
500            pad_top: PT,
501            pad_left: PL,
502            padded: PT + PB + PL + PR != 0,
503        };
504        let rqs = self.requantizers.iter();
505        if C >= BAND_MIN_CHANNELS {
506            conv2d_band(
507                input,
508                output,
509                self.weights,
510                self.biases,
511                self.input_zero_point,
512                rqs,
513                window,
514            );
515        } else {
516            conv2d_gather(
517                input,
518                output,
519                self.weights,
520                self.biases,
521                self.input_zero_point,
522                rqs,
523                window,
524            );
525        }
526    }
527}
528
529/// A quantized depthwise 2D convolution: one `KH` x `KW` filter per channel,
530/// channels never mixed, one requantizer per channel as TFLite requires (C++
531/// `QDepthwiseConv2D`).
532///
533/// Weights are `weights[channel][row][column]`; strides and padding as in
534/// [`QConv2D`]. The output has the input's `C` channels.
535#[derive(Clone, Copy, Debug)]
536pub struct QDepthwiseConv2D<
537    'a,
538    const C: usize,
539    const KH: usize,
540    const KW: usize,
541    const SH: usize = 1,
542    const SW: usize = 1,
543    const PT: usize = 0,
544    const PB: usize = 0,
545    const PL: usize = 0,
546    const PR: usize = 0,
547> {
548    /// `weights[c][kh][kw]`.
549    pub weights: &'a [[[i8; KW]; KH]; C],
550    /// One `i32` bias per channel, or `None`.
551    pub biases: Option<&'a [i32; C]>,
552    /// The input tensor's zero point, which also fills the padding.
553    pub input_zero_point: i8,
554    /// `requantizers[c]` rescales channel `c`.
555    pub requantizers: &'a [Requantizer; C],
556}
557
558impl<
559    const C: usize,
560    const KH: usize,
561    const KW: usize,
562    const SH: usize,
563    const SW: usize,
564    const PT: usize,
565    const PB: usize,
566    const PL: usize,
567    const PR: usize,
568> QDepthwiseConv2D<'_, C, KH, KW, SH, SW, PT, PB, PL, PR>
569{
570    /// One forward pass over an `H` x `W` x `C` input into an `OH` x `OW` x
571    /// `C` output; `OH` and `OW` as in [`QConv2D::forward`].
572    ///
573    /// Channel by channel, as tinymind (C++) runs it: each channel's taps, its
574    /// bias folded with the zero point (`bias - zp * sum w`) and its prepared
575    /// requantizer stay put across the pixels. The `i32` sums are the same
576    /// integers as the per-tap form, modulo 2^32.
577    pub fn forward<const H: usize, const W: usize, const OH: usize, const OW: usize>(
578        &self,
579        input: &[[[i8; C]; W]; H],
580        output: &mut [[[i8; C]; OW]; OH],
581    ) {
582        const {
583            assert!(
584                C > 0 && window_fits(H, KH, SH, PT, PB, OH) && window_fits(W, KW, SW, PL, PR, OW),
585                "QDepthwiseConv2D: the output size does not match the input, kernel, strides and padding, or the layer is invalid"
586            )
587        };
588        let window = Window {
589            stride_h: SH,
590            stride_w: SW,
591            pad_top: PT,
592            pad_left: PL,
593            padded: PT + PB + PL + PR != 0,
594        };
595        let zero_point = self.input_zero_point;
596        let channels = self.weights.iter().zip(self.requantizers);
597        for (c, (taps, rq)) in channels.enumerate() {
598            let taps = *taps;
599            let bias = bias_of(self.biases, c);
600            let folded = folded_bias(bias, zero_point, taps.iter().flatten().copied());
601            let k = DepthwiseChannel {
602                c,
603                taps: &taps,
604                bias,
605                folded,
606                zero_point,
607                window,
608            };
609            // The pixel loop once per requantizer form, as the C++ writes it.
610            match FastRequantizer::new(rq) {
611                Some(fast) => k.run(input, output, |acc| fast.apply(acc)),
612                None => k.run_general(input, output, *rq),
613            }
614        }
615    }
616}
617
618/// One depthwise channel: its taps, its bias as given and folded with the
619/// zero point (see [`folded_bias`]).
620struct DepthwiseChannel<'t, const KH: usize, const KW: usize> {
621    c: usize,
622    taps: &'t [[i8; KW]; KH],
623    bias: i32,
624    folded: i32,
625    zero_point: i8,
626    window: Window,
627}
628
629impl<const KH: usize, const KW: usize> DepthwiseChannel<'_, KH, KW> {
630    /// [`run`](Self::run) for a requantizer without a prepared form (a
631    /// scale ratio of 0.25 or more, a negative multiplier): rare, so kept out
632    /// of line and cold, which keeps the common loop's code from doubling.
633    #[cold]
634    #[inline(never)]
635    fn run_general<
636        const H: usize,
637        const W: usize,
638        const C: usize,
639        const OH: usize,
640        const OW: usize,
641    >(
642        &self,
643        input: &[[[i8; C]; W]; H],
644        output: &mut [[[i8; C]; OW]; OH],
645        rq: Requantizer,
646    ) {
647        self.run(input, output, |acc| rq.apply(acc));
648    }
649
650    /// Every output pixel of this channel. A window wholly inside the input
651    /// reads its rows and pixels as slices and runs a plain multiply-accumulate
652    /// on the folded bias; one that reaches into the padding takes the
653    /// general form, skipping the padded taps.
654    #[inline(always)]
655    fn run<const H: usize, const W: usize, const C: usize, const OH: usize, const OW: usize>(
656        &self,
657        input: &[[[i8; C]; W]; H],
658        output: &mut [[[i8; C]; OW]; OH],
659        requantize: impl Fn(i32) -> i8,
660    ) {
661        let Window {
662            stride_h,
663            stride_w,
664            pad_top,
665            pad_left,
666            padded,
667        } = self.window;
668        let c = self.c;
669        for (oh, out_row) in output.iter_mut().enumerate() {
670            let top = oh * stride_h;
671            for (ow, out_pixel) in out_row.iter_mut().enumerate() {
672                let left = ow * stride_w;
673                let rows = top.checked_sub(pad_top).and_then(|r| input.get(r..r + KH));
674                let column = left.checked_sub(pad_left).filter(|&col| col + KW <= W);
675                let acc = match (rows, column) {
676                    (Some(rows), Some(col)) => {
677                        let mut acc = self.folded;
678                        for (row, tap_row) in rows.iter().zip(self.taps) {
679                            if let Some(pixels) = row.get(col..col + KW) {
680                                for (pixel, &w) in pixels.iter().zip(tap_row) {
681                                    if let Some(&x) = pixel.get(c) {
682                                        acc = acc.wrapping_add(i32::from(w) * i32::from(x));
683                                    }
684                                }
685                            }
686                        }
687                        acc
688                    }
689                    // Unreachable without padding (every window lies inside
690                    // the input); this arm keeps the general path out of an
691                    // unpadded layer's code.
692                    _ if !padded => self.folded,
693                    _ => {
694                        let zp = i32::from(self.zero_point);
695                        let mut acc = self.bias;
696                        for (kh, tap_row) in self.taps.iter().enumerate() {
697                            for (kw, &w) in tap_row.iter().enumerate() {
698                                let pixel = tap(input, top + kh, left + kw, pad_top, pad_left);
699                                if let Some(&x) = pixel.and_then(|p| p.get(c)) {
700                                    acc = acc.wrapping_add(i32::from(w) * (i32::from(x) - zp));
701                                }
702                            }
703                        }
704                        acc
705                    }
706                };
707                if let Some(out) = out_pixel.get_mut(c) {
708                    *out = requantize(acc);
709                }
710            }
711        }
712    }
713}
714
715/// `sum w * x` in `i32`, wrapping. With the zero point folded into the bias
716/// (see [`folded_bias`]) this is the whole per-output dot product.
717#[inline]
718fn dot<const N: usize>(x: &[i8; N], w: &[i8; N]) -> i32 {
719    x.iter().zip(w).fold(0i32, |acc, (&x, &w)| {
720        acc.wrapping_add(i32::from(w) * i32::from(x))
721    })
722}
723
724/// `bias - zero_point * sum w`: since `sum w * (x - zp) == sum w * x - zp *
725/// sum w`, a filter whose taps all read the input (no padding) can run a plain
726/// multiply-accumulate. `i32` arithmetic wraps, so the two forms are equal
727/// modulo 2^32, as the C++'s are.
728#[inline]
729fn folded_bias(bias: i32, zero_point: i8, weights: impl IntoIterator<Item = i8>) -> i32 {
730    let sum = weights
731        .into_iter()
732        .fold(0i32, |s, w| s.wrapping_add(i32::from(w)));
733    bias.wrapping_sub(i32::from(zero_point).wrapping_mul(sum))
734}
735
736/// The body of [`QPointwiseConv2D`] and [`QPointwiseConv2DPerChannel`]: a
737/// dense layer applied to every pixel. Filter by filter, as the C++ runs it:
738/// each filter's weights, folded bias and requantizer stay in registers or on
739/// the stack across the pixels.
740fn pointwise<'r, const H: usize, const W: usize, const C: usize, const F: usize>(
741    input: &[[[i8; C]; W]; H],
742    output: &mut [[[i8; F]; W]; H],
743    weights: &[[i8; C]; F],
744    biases: Option<&[i32; F]>,
745    zero_point: i8,
746    rqs: impl Iterator<Item = &'r Requantizer>,
747) {
748    if H * W == 1 {
749        // A single pixel (a dense layer): one pass, output by output, so the
750        // folded bias is not worth its sum of the weights.
751        let pixel = output
752            .iter_mut()
753            .flatten()
754            .next()
755            .zip(input.iter().flatten().next());
756        if let Some((out_pixel, in_pixel)) = pixel {
757            let filters = out_pixel.iter_mut().zip(weights).zip(rqs);
758            for (f, ((out, row), rq)) in filters.enumerate() {
759                let acc =
760                    bias_of(biases, f).wrapping_add(dot_with_zero_point(in_pixel, row, zero_point));
761                *out = rq.apply(acc);
762            }
763        }
764        return;
765    }
766    if C < PAIR_MIN_CHANNELS {
767        // Short rows: one filter at a time. `C` is a constant, so this is
768        // the only loop such a layer compiles.
769        for (f, (row, rq)) in weights.iter().zip(rqs).enumerate() {
770            let w = *row;
771            let bias = folded_bias(bias_of(biases, f), zero_point, w);
772            pointwise_one_filter(input, output, f, &w, bias, rq);
773        }
774        return;
775    }
776    // Filters in pairs, two pixels at a time (2x2): each input value loaded
777    // serves both filters and each weight both pixels. A pair needs both
778    // requantizers in their prepared form; otherwise, and for an odd last
779    // filter, filters run one at a time.
780    let mut filters = weights.iter().zip(rqs).enumerate();
781    while let Some((f0, (row0, rq0))) = filters.next() {
782        let w0 = *row0;
783        let bias0 = folded_bias(bias_of(biases, f0), zero_point, w0);
784        let second = filters.next();
785        let fast = FastRequantizer::new(rq0)
786            .zip(second.and_then(|(_, (_, rq1))| FastRequantizer::new(rq1)));
787        match (second, fast) {
788            (Some((f1, (row1, _))), Some((fast0, fast1))) => {
789                let w1 = *row1;
790                let bias1 = folded_bias(bias_of(biases, f1), zero_point, w1);
791                pointwise_filter_pair(
792                    input,
793                    output,
794                    (f0, f1),
795                    (&w0, &w1),
796                    (bias0, bias1),
797                    |acc| fast0.apply(acc),
798                    |acc| fast1.apply(acc),
799                );
800            }
801            (second, _) => {
802                pointwise_one_filter(input, output, f0, &w0, bias0, rq0);
803                if let Some((f1, (row1, rq1))) = second {
804                    let w1 = *row1;
805                    let bias1 = folded_bias(bias_of(biases, f1), zero_point, w1);
806                    pointwise_one_filter(input, output, f1, &w1, bias1, rq1);
807                }
808            }
809        }
810    }
811}
812
813/// Shortest input row for which [`pointwise`] runs filters in pairs. Measured
814/// on the F411 (2026-11-11): with 8 channels pairs made the KWS-shaped
815/// network's pointwise layer 28% slower (L031 9%); with 64 they made the
816/// MLPerf DS-CNN 9% faster. Rows of 16 to 32 were not measured, nor 64 on the
817/// M0+.
818const PAIR_MIN_CHANNELS: usize = 32;
819
820/// One pointwise filter, with the pixel loop once per requantizer form, so
821/// neither tests the form per output.
822#[inline(always)]
823fn pointwise_one_filter<const H: usize, const W: usize, const C: usize, const F: usize>(
824    input: &[[[i8; C]; W]; H],
825    output: &mut [[[i8; F]; W]; H],
826    f: usize,
827    w: &[i8; C],
828    bias: i32,
829    rq: &Requantizer,
830) {
831    match FastRequantizer::new(rq) {
832        Some(fast) => pointwise_filter(input, output, f, w, bias, |acc| fast.apply(acc)),
833        None => pointwise_filter_general(input, output, f, w, bias, *rq),
834    }
835}
836
837/// Two pointwise filters over every pixel, two pixels at a time; an odd last
838/// pixel runs against both filters alone.
839#[inline(always)]
840fn pointwise_filter_pair<const H: usize, const W: usize, const C: usize, const F: usize>(
841    input: &[[[i8; C]; W]; H],
842    output: &mut [[[i8; F]; W]; H],
843    (f0, f1): (usize, usize),
844    (w0, w1): (&[i8; C], &[i8; C]),
845    (bias0, bias1): (i32, i32),
846    requantize0: impl Fn(i32) -> i8,
847    requantize1: impl Fn(i32) -> i8,
848) {
849    let inputs = input.as_flattened();
850    let outputs = output.as_flattened_mut();
851    let mut ins = inputs.chunks_exact(2);
852    let mut outs = outputs.chunks_exact_mut(2);
853    for (out_pair, in_pair) in (&mut outs).zip(&mut ins) {
854        if let ([o0, o1], [x0, x1]) = (out_pair, in_pair) {
855            let [a00, a01, a10, a11] = dot2x2(x0, x1, w0, w1);
856            if let Some(out) = o0.get_mut(f0) {
857                *out = requantize0(bias0.wrapping_add(a00));
858            }
859            if let Some(out) = o1.get_mut(f0) {
860                *out = requantize0(bias0.wrapping_add(a01));
861            }
862            if let Some(out) = o0.get_mut(f1) {
863                *out = requantize1(bias1.wrapping_add(a10));
864            }
865            if let Some(out) = o1.get_mut(f1) {
866                *out = requantize1(bias1.wrapping_add(a11));
867            }
868        }
869    }
870    for (out_pixel, in_pixel) in outs.into_remainder().iter_mut().zip(ins.remainder()) {
871        let (a0, a1) = dot2(in_pixel, w0, w1);
872        if let Some(out) = out_pixel.get_mut(f0) {
873            *out = requantize0(bias0.wrapping_add(a0));
874        }
875        if let Some(out) = out_pixel.get_mut(f1) {
876            *out = requantize1(bias1.wrapping_add(a1));
877        }
878    }
879}
880
881/// `[sum w0 * x0, sum w0 * x1, sum w1 * x0, sum w1 * x1]`, wrapping: two
882/// pixels against two filters.
883#[inline(always)]
884fn dot2x2<const N: usize>(x0: &[i8; N], x1: &[i8; N], w0: &[i8; N], w1: &[i8; N]) -> [i32; 4] {
885    x0.iter().zip(x1).zip(w0.iter().zip(w1)).fold(
886        [0i32; 4],
887        |[a00, a01, a10, a11], ((&x0, &x1), (&w0, &w1))| {
888            let (x0, x1, w0, w1) = (i32::from(x0), i32::from(x1), i32::from(w0), i32::from(w1));
889            [
890                a00.wrapping_add(w0 * x0),
891                a01.wrapping_add(w0 * x1),
892                a10.wrapping_add(w1 * x0),
893                a11.wrapping_add(w1 * x1),
894            ]
895        },
896    )
897}
898
899/// [`pointwise_filter`] for a requantizer without a prepared form: rare, so
900/// kept out of line and cold (see [`DepthwiseChannel::run_general`]).
901#[cold]
902#[inline(never)]
903fn pointwise_filter_general<const H: usize, const W: usize, const C: usize, const F: usize>(
904    input: &[[[i8; C]; W]; H],
905    output: &mut [[[i8; F]; W]; H],
906    f: usize,
907    w: &[i8; C],
908    bias: i32,
909    rq: Requantizer,
910) {
911    pointwise_filter(input, output, f, w, bias, |acc| rq.apply(acc));
912}
913
914/// One pointwise filter over every pixel, two pixels at a time: each weight
915/// loaded serves both (four would spill registers on a Cortex-M4). Pixels are
916/// taken from the flattened rows; an odd last pixel runs alone.
917#[inline(always)]
918fn pointwise_filter<const H: usize, const W: usize, const C: usize, const F: usize>(
919    input: &[[[i8; C]; W]; H],
920    output: &mut [[[i8; F]; W]; H],
921    f: usize,
922    w: &[i8; C],
923    bias: i32,
924    requantize: impl Fn(i32) -> i8,
925) {
926    let inputs = input.as_flattened();
927    let outputs = output.as_flattened_mut();
928    let mut ins = inputs.chunks_exact(2);
929    let mut outs = outputs.chunks_exact_mut(2);
930    for (out_pair, in_pair) in (&mut outs).zip(&mut ins) {
931        if let ([o0, o1], [x0, x1]) = (out_pair, in_pair) {
932            let (a0, a1) = dot2_pixels(x0, x1, w);
933            if let Some(out) = o0.get_mut(f) {
934                *out = requantize(bias.wrapping_add(a0));
935            }
936            if let Some(out) = o1.get_mut(f) {
937                *out = requantize(bias.wrapping_add(a1));
938            }
939        }
940    }
941    for (out_pixel, in_pixel) in outs.into_remainder().iter_mut().zip(ins.remainder()) {
942        if let Some(out) = out_pixel.get_mut(f) {
943            *out = requantize(bias.wrapping_add(dot(in_pixel, w)));
944        }
945    }
946}
947
948/// `(sum x0 * w, sum x1 * w)`, wrapping: two pixels against one filter.
949#[inline(always)]
950fn dot2_pixels<const N: usize>(x0: &[i8; N], x1: &[i8; N], w: &[i8; N]) -> (i32, i32) {
951    x0.iter()
952        .zip(x1)
953        .zip(w)
954        .fold((0i32, 0i32), |(a0, a1), ((&x0, &x1), &w)| {
955            let w = i32::from(w);
956            (
957                a0.wrapping_add(w * i32::from(x0)),
958                a1.wrapping_add(w * i32::from(x1)),
959            )
960        })
961}
962
963/// `(sum x * w0, sum x * w1)` over the shortest of the three, wrapping: one
964/// window against two filters (an odd last filter passes itself twice).
965#[inline(always)]
966fn dot2(x: &[i8], w0: &[i8], w1: &[i8]) -> (i32, i32) {
967    x.iter()
968        .zip(w0)
969        .zip(w1)
970        .fold((0i32, 0i32), |(a0, a1), ((&x, &w0), &w1)| {
971            let x = i32::from(x);
972            (
973                a0.wrapping_add(x * i32::from(w0)),
974                a1.wrapping_add(x * i32::from(w1)),
975            )
976        })
977}
978
979/// A quantized 1x1 ("pointwise") convolution, the channel-mixing half of a
980/// depthwise-separable block, with one requantizer for the whole output (C++
981/// `QPointwiseConv2D`). Every pixel goes through the same `C`-to-`F` dense
982/// layer; weights are `weights[filter][channel]`.
983#[derive(Clone, Copy, Debug)]
984pub struct QPointwiseConv2D<'a, const C: usize, const F: usize> {
985    /// `weights[f][c]`.
986    pub weights: &'a [[i8; C]; F],
987    /// One `i32` bias per filter, or `None`.
988    pub biases: Option<&'a [i32; F]>,
989    /// The input tensor's zero point.
990    pub input_zero_point: i8,
991    /// Rescales every accumulator to the output tensor's grid.
992    pub requantizer: Requantizer,
993}
994
995impl<const C: usize, const F: usize> QPointwiseConv2D<'_, C, F> {
996    /// One forward pass over an `H` x `W` x `C` input into an `H` x `W` x `F`
997    /// output.
998    pub fn forward<const H: usize, const W: usize>(
999        &self,
1000        input: &[[[i8; C]; W]; H],
1001        output: &mut [[[i8; F]; W]; H],
1002    ) {
1003        const {
1004            assert!(
1005                H > 0 && W > 0 && C > 0 && F > 0,
1006                "QPointwiseConv2D: every size must be above zero"
1007            )
1008        };
1009        let rqs = core::iter::repeat(&self.requantizer);
1010        pointwise(
1011            input,
1012            output,
1013            self.weights,
1014            self.biases,
1015            self.input_zero_point,
1016            rqs,
1017        );
1018    }
1019}
1020
1021/// [`QPointwiseConv2D`] with one requantizer per filter (C++
1022/// `QPointwiseConv2DPerChannel`). For a single pixel this is
1023/// [`QDensePerChannel`](super::QDensePerChannel).
1024#[derive(Clone, Copy, Debug)]
1025pub struct QPointwiseConv2DPerChannel<'a, const C: usize, const F: usize> {
1026    /// `weights[f][c]`.
1027    pub weights: &'a [[i8; C]; F],
1028    /// One `i32` bias per filter, or `None`.
1029    pub biases: Option<&'a [i32; F]>,
1030    /// The input tensor's zero point.
1031    pub input_zero_point: i8,
1032    /// `requantizers[f]` rescales filter `f`'s outputs.
1033    pub requantizers: &'a [Requantizer; F],
1034}
1035
1036impl<const C: usize, const F: usize> QPointwiseConv2DPerChannel<'_, C, F> {
1037    /// One forward pass; see [`QPointwiseConv2D::forward`].
1038    pub fn forward<const H: usize, const W: usize>(
1039        &self,
1040        input: &[[[i8; C]; W]; H],
1041        output: &mut [[[i8; F]; W]; H],
1042    ) {
1043        const {
1044            assert!(
1045                H > 0 && W > 0 && C > 0 && F > 0,
1046                "QPointwiseConv2DPerChannel: every size must be above zero"
1047            )
1048        };
1049        let rqs = self.requantizers.iter();
1050        pointwise(
1051            input,
1052            output,
1053            self.weights,
1054            self.biases,
1055            self.input_zero_point,
1056            rqs,
1057        );
1058    }
1059}