1use super::{FastRequantizer, Requantizer, dot_with_zero_point};
6
7pub(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#[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#[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#[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 pub(crate) padded: bool,
59}
60
61#[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
149const BAND_MIN_CHANNELS: usize = 2;
153
154#[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#[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
251struct 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 #[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 #[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#[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 pub weights: &'a [[[[i8; C]; KW]; KH]; F],
373 pub biases: Option<&'a [i32; F]>,
375 pub input_zero_point: i8,
377 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 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#[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 pub weights: &'a [[[[i8; C]; KW]; KH]; F],
461 pub biases: Option<&'a [i32; F]>,
463 pub input_zero_point: i8,
465 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 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#[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 pub weights: &'a [[[i8; KW]; KH]; C],
550 pub biases: Option<&'a [i32; C]>,
552 pub input_zero_point: i8,
554 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 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 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
618struct 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 #[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 #[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 _ 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#[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#[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
736fn 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 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 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 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
813const PAIR_MIN_CHANNELS: usize = 32;
819
820#[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#[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#[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#[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#[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#[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#[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#[derive(Clone, Copy, Debug)]
984pub struct QPointwiseConv2D<'a, const C: usize, const F: usize> {
985 pub weights: &'a [[i8; C]; F],
987 pub biases: Option<&'a [i32; F]>,
989 pub input_zero_point: i8,
991 pub requantizer: Requantizer,
993}
994
995impl<const C: usize, const F: usize> QPointwiseConv2D<'_, C, F> {
996 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#[derive(Clone, Copy, Debug)]
1025pub struct QPointwiseConv2DPerChannel<'a, const C: usize, const F: usize> {
1026 pub weights: &'a [[i8; C]; F],
1028 pub biases: Option<&'a [i32; F]>,
1030 pub input_zero_point: i8,
1032 pub requantizers: &'a [Requantizer; F],
1034}
1035
1036impl<const C: usize, const F: usize> QPointwiseConv2DPerChannel<'_, C, F> {
1037 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}