use super::{FastRequantizer, Requantizer, Tensor};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QMul {
pub input_a_zero_point: i8,
pub input_b_zero_point: i8,
pub requantizer: Requantizer,
}
impl QMul {
pub fn forward<T: Tensor>(&self, a: &T, b: &T, out: &mut T) {
let (a, b, out) = (a.as_flat(), b.as_flat(), out.as_flat_mut());
let (za, zb) = (
i32::from(self.input_a_zero_point),
i32::from(self.input_b_zero_point),
);
let products = a
.iter()
.zip(b)
.map(|(&x, &y)| (i32::from(x) - za) * (i32::from(y) - zb));
match FastRequantizer::new(&self.requantizer) {
Some(rq) => {
for (o, p) in out.iter_mut().zip(products) {
*o = rq.apply(p);
}
}
None => {
for (o, p) in out.iter_mut().zip(products) {
*o = self.requantizer.apply(p);
}
}
}
}
}
const fn sums_to(a: usize, b: usize, c: usize, d: usize) -> bool {
match a.checked_add(b) {
Some(ab) => match ab.checked_add(c) {
Some(abc) => abc == d,
None => false,
},
None => false,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QPad2D<const PT: usize, const PB: usize, const PL: usize, const PR: usize> {
pub pad_value: i8,
}
impl<const PT: usize, const PB: usize, const PL: usize, const PR: usize> QPad2D<PT, PB, PL, PR> {
pub fn forward<
const H: usize,
const W: usize,
const C: usize,
const OH: usize,
const OW: usize,
>(
&self,
input: &[[[i8; C]; W]; H],
output: &mut [[[i8; C]; OW]; OH],
) {
const {
assert!(
sums_to(H, PT, PB, OH) && sums_to(W, PL, PR, OW),
"QPad2D: the output size is not the input size plus the padding"
)
};
for (oh, out_row) in output.iter_mut().enumerate() {
let row = oh.checked_sub(PT).and_then(|r| input.get(r));
for (ow, pixel) in out_row.iter_mut().enumerate() {
let x = row.and_then(|r| ow.checked_sub(PL).and_then(|c| r.get(c)));
*pixel = x.copied().unwrap_or([self.pad_value; C]);
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QConcat {
pub input_a_zero_point: i8,
pub input_b_zero_point: i8,
pub requantizer_a: Requantizer,
pub requantizer_b: Requantizer,
}
impl QConcat {
pub fn forward<
const H: usize,
const W: usize,
const CA: usize,
const CB: usize,
const C: usize,
>(
&self,
a: &[[[i8; CA]; W]; H],
b: &[[[i8; CB]; W]; H],
out: &mut [[[i8; C]; W]; H],
) {
const {
assert!(
CA > 0 && CB > 0 && sums_to(CA, CB, 0, C),
"QConcat: the output's channels must be the two inputs' channels together"
)
};
let (za, zb) = (
i32::from(self.input_a_zero_point),
i32::from(self.input_b_zero_point),
);
let pixels = out
.as_flattened_mut()
.iter_mut()
.zip(a.as_flattened())
.zip(b.as_flattened());
for ((y, xa), xb) in pixels {
let (ya, yb) = y.split_at_mut(CA.min(C));
for (o, &x) in ya.iter_mut().zip(xa) {
*o = self.requantizer_a.apply(i32::from(x) - za);
}
for (o, &x) in yb.iter_mut().zip(xb) {
*o = self.requantizer_b.apply(i32::from(x) - zb);
}
}
}
}