Skip to main content

tinymind/int8/
pool.rs

1//! Int8 pooling over NHWC tensors, ported from tinymind (C++) `cpp/qpool2d.hpp`.
2//! Re-exported from [`int8`](super).
3//!
4//! Input and output share one scale and zero point: the maximum of the
5//! integers is the integer of the maximum, and the mean of `q` rounded to the
6//! nearest integer is the mean of the real values on the same grid. No
7//! requantizer is needed; follow with one to change the scale.
8
9use super::conv::{tap, window_fits};
10
11/// `numerator / denominator` rounded half away from zero, 0 for a zero
12/// denominator (C++ `detail::roundedDivide`). Total: where the C++ would
13/// overflow (a numerator within `denominator / 2` of the `i32` rails) the sum
14/// wraps, and `i32::MIN / -1` gives 0.
15pub(crate) fn rounded_divide(numerator: i32, denominator: i32) -> i32 {
16    let half = denominator / 2;
17    let biased = if numerator >= 0 {
18        numerator.wrapping_add(half)
19    } else {
20        numerator.wrapping_sub(half)
21    };
22    biased.checked_div(denominator).unwrap_or(0)
23}
24
25/// Clamp to `[qmin, qmax]` with two separate tests, as the C++ does: with
26/// `qmin > qmax` the result is `qmax` (and `clamp` would panic).
27fn saturate(v: i32, qmin: i8, qmax: i8) -> i8 {
28    let mut v = v;
29    if v < i32::from(qmin) {
30        v = i32::from(qmin);
31    }
32    if v > i32::from(qmax) {
33        v = i32::from(qmax);
34    }
35    v as i8
36}
37
38/// Max pooling over `PH` x `PW` windows at strides `SH`, `SW` (default: the
39/// window size, non-overlapping), no padding (C++ `QMaxPool2D`).
40#[derive(Clone, Copy, Debug, Default)]
41pub struct QMaxPool2D<const PH: usize, const PW: usize, const SH: usize = PH, const SW: usize = PW>;
42
43impl<const PH: usize, const PW: usize, const SH: usize, const SW: usize>
44    QMaxPool2D<PH, PW, SH, SW>
45{
46    /// One forward pass over an `H` x `W` x `C` input into an `OH` x `OW` x
47    /// `C` output, with `OH = (H - PH) / SH + 1` and likewise `OW` (a compile
48    /// error otherwise).
49    pub fn forward<
50        const H: usize,
51        const W: usize,
52        const C: usize,
53        const OH: usize,
54        const OW: usize,
55    >(
56        &self,
57        input: &[[[i8; C]; W]; H],
58        output: &mut [[[i8; C]; OW]; OH],
59    ) {
60        const {
61            assert!(
62                C > 0 && window_fits(H, PH, SH, 0, 0, OH) && window_fits(W, PW, SW, 0, 0, OW),
63                "QMaxPool2D: the output size does not match the input, window and strides, or the layer is invalid"
64            )
65        };
66        for (oh, out_row) in output.iter_mut().enumerate() {
67            for (ow, out_pixel) in out_row.iter_mut().enumerate() {
68                for (c, out) in out_pixel.iter_mut().enumerate() {
69                    let mut max = i8::MIN;
70                    for kh in 0..PH {
71                        for kw in 0..PW {
72                            let x = tap(input, oh * SH + kh, ow * SW + kw, 0, 0);
73                            if let Some(&x) = x.and_then(|p| p.get(c)) {
74                                max = max.max(x);
75                            }
76                        }
77                    }
78                    *out = max;
79                }
80            }
81        }
82    }
83}
84
85/// Average pooling over `PH` x `PW` windows at strides `SH`, `SW` (default: the
86/// window size), no padding: the window's sum divided by its area, rounded
87/// half away from zero, then clamped to `[qmin, qmax]` (C++ `QAvgPool2D`).
88#[derive(Clone, Copy, Debug)]
89pub struct QAvgPool2D<const PH: usize, const PW: usize, const SH: usize = PH, const SW: usize = PW>
90{
91    /// Lowest output value.
92    pub qmin: i8,
93    /// Highest output value.
94    pub qmax: i8,
95}
96
97impl<const PH: usize, const PW: usize, const SH: usize, const SW: usize>
98    QAvgPool2D<PH, PW, SH, SW>
99{
100    /// One forward pass; sizes as in [`QMaxPool2D::forward`].
101    pub fn forward<
102        const H: usize,
103        const W: usize,
104        const C: usize,
105        const OH: usize,
106        const OW: usize,
107    >(
108        &self,
109        input: &[[[i8; C]; W]; H],
110        output: &mut [[[i8; C]; OW]; OH],
111    ) {
112        const {
113            assert!(
114                C > 0 && window_fits(H, PH, SH, 0, 0, OH) && window_fits(W, PW, SW, 0, 0, OW),
115                "QAvgPool2D: the output size does not match the input, window and strides, or the layer is invalid"
116            )
117        };
118        // As the C++ casts the window area to int32_t.
119        let area = const { PH.wrapping_mul(PW) as i32 };
120        for (oh, out_row) in output.iter_mut().enumerate() {
121            for (ow, out_pixel) in out_row.iter_mut().enumerate() {
122                for (c, out) in out_pixel.iter_mut().enumerate() {
123                    let mut sum = 0i32;
124                    for kh in 0..PH {
125                        for kw in 0..PW {
126                            let x = tap(input, oh * SH + kh, ow * SW + kw, 0, 0);
127                            if let Some(&x) = x.and_then(|p| p.get(c)) {
128                                sum = sum.wrapping_add(i32::from(x));
129                            }
130                        }
131                    }
132                    *out = saturate(rounded_divide(sum, area), self.qmin, self.qmax);
133                }
134            }
135        }
136    }
137}
138
139/// Global average pooling: one value per channel, the mean over every pixel,
140/// rounded and clamped as in [`QAvgPool2D`] (C++ `QGlobalAvgPool2D`). Its
141/// output can feed a dense head in place of a large flatten-to-dense layer.
142#[derive(Clone, Copy, Debug)]
143pub struct QGlobalAvgPool2D {
144    /// Lowest output value.
145    pub qmin: i8,
146    /// Highest output value.
147    pub qmax: i8,
148}
149
150impl QGlobalAvgPool2D {
151    /// One forward pass over an `H` x `W` x `C` input.
152    pub fn forward<const H: usize, const W: usize, const C: usize>(
153        &self,
154        input: &[[[i8; C]; W]; H],
155    ) -> [i8; C] {
156        const {
157            assert!(
158                H > 0 && W > 0 && C > 0,
159                "QGlobalAvgPool2D: every size must be above zero"
160            )
161        };
162        let area = const { H.wrapping_mul(W) as i32 };
163        // Channel by channel, as the C++ runs it, so no per-channel sums are
164        // kept on the stack.
165        let mut output = [0i8; C];
166        for (c, out) in output.iter_mut().enumerate() {
167            let sum = input
168                .iter()
169                .flatten()
170                .filter_map(|pixel| pixel.get(c))
171                .fold(0i32, |sum, &x| sum.wrapping_add(i32::from(x)));
172            *out = saturate(rounded_divide(sum, area), self.qmin, self.qmax);
173        }
174        output
175    }
176}