#[cfg(feature = "std")]
pub mod calibration;
pub fn saturating_rounding_doubling_high_mul(a: i32, b: i32) -> i32 {
let overflow = a == i32::MIN && b == i32::MIN;
let ab = i64::from(a) * i64::from(b);
let high = ((ab + (1i64 << 30)) >> 31) as i32;
if overflow { i32::MAX } else { high }
}
pub fn rounding_divide_by_pot(x: i32, exponent: i32) -> i32 {
if exponent <= 0 {
return x;
}
let exponent = exponent.min(31) as u32;
let mask = ((1u32 << exponent) - 1) as i32;
let remainder = x & mask;
let threshold = (mask >> 1) + i32::from(x < 0);
(x >> exponent) + i32::from(remainder > threshold)
}
pub(crate) fn rounding_high_mul_divide_by_pot(x: i32, multiplier: i32, exponent: i32) -> i32 {
let negative = (x as u32) >> 31;
let nudge_high = (1u32 << (exponent - 2)).wrapping_sub(negative);
let nudge_low = (negative << 31) | 0x4000_0000;
let nudge = (u64::from(nudge_high) << 32) | u64::from(nudge_low);
let v = nudge.wrapping_add((i64::from(x) * i64::from(multiplier)) as u64);
((v >> 32) as u32 as i32) >> (exponent - 1)
}
pub fn multiply_by_quantized_multiplier(x: i32, multiplier: i32, shift: i32) -> i32 {
let left_shift = if shift < 0 { shift.unsigned_abs() } else { 0 };
let right_shift = shift.max(0);
let shifted = if left_shift > 30 {
if x > 0 {
i32::MAX
} else if x < 0 {
i32::MIN
} else {
0
}
} else if left_shift > 0 {
let limit = i32::MAX >> left_shift;
if x > limit {
i32::MAX
} else if x < -limit - 1 {
i32::MIN
} else {
x * (1 << left_shift)
}
} else {
x
};
rounding_divide_by_pot(
saturating_rounding_doubling_high_mul(shifted, multiplier),
right_shift,
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Requantizer {
pub multiplier: i32,
pub shift: i32,
pub zero_point: i8,
pub qmin: i8,
pub qmax: i8,
}
impl Requantizer {
pub fn apply(&self, acc: i32) -> i8 {
let scaled = if self.multiplier >= 0 && (2..=31).contains(&self.shift) {
rounding_high_mul_divide_by_pot(acc, self.multiplier, self.shift)
} else {
let rail = 1 << 30;
multiply_by_quantized_multiplier(acc, self.multiplier, self.shift).clamp(-rail, rail)
};
let mut with_zp = scaled + i32::from(self.zero_point);
if with_zp < i32::from(self.qmin) {
with_zp = i32::from(self.qmin);
}
if with_zp > i32::from(self.qmax) {
with_zp = i32::from(self.qmax);
}
with_zp as i8
}
}
fn dot_with_zero_point<const N: usize>(x: &[i8; N], w: &[i8; N], zero_point: i8) -> i32 {
x.iter().zip(w).fold(0i32, |acc, (&x, &w)| {
acc.wrapping_add(i32::from(w) * (i32::from(x) - i32::from(zero_point)))
})
}
#[derive(Clone, Copy, Debug)]
pub struct QDense<'a, const IN: usize, const OUT: usize> {
pub weights: &'a [[i8; IN]; OUT],
pub biases: Option<&'a [i32; OUT]>,
pub input_zero_point: i8,
pub requantizer: Requantizer,
}
impl<const IN: usize, const OUT: usize> QDense<'_, IN, OUT> {
pub fn forward(&self, input: &[i8; IN]) -> [i8; OUT] {
let mut output = [0i8; OUT];
for (o, (out, row)) in output.iter_mut().zip(self.weights).enumerate() {
let bias = self.biases.map_or(0, |b| b.get(o).copied().unwrap_or(0));
let acc = bias.wrapping_add(dot_with_zero_point(input, row, self.input_zero_point));
*out = self.requantizer.apply(acc);
}
output
}
}
#[derive(Clone, Copy, Debug)]
pub struct QDensePerChannel<'a, const IN: usize, const OUT: usize> {
pub weights: &'a [[i8; IN]; OUT],
pub biases: Option<&'a [i32; OUT]>,
pub input_zero_point: i8,
pub requantizers: &'a [Requantizer; OUT],
}
impl<const IN: usize, const OUT: usize> QDensePerChannel<'_, IN, OUT> {
pub fn forward(&self, input: &[i8; IN]) -> [i8; OUT] {
let mut output = [0i8; OUT];
let rows = self.weights.iter().zip(self.requantizers);
for (o, (out, (row, rq))) in output.iter_mut().zip(rows).enumerate() {
let bias = self.biases.map_or(0, |b| b.get(o).copied().unwrap_or(0));
let acc = bias.wrapping_add(dot_with_zero_point(input, row, self.input_zero_point));
*out = rq.apply(acc);
}
output
}
}
pub fn qrelu(x: i8, zero_point: i8) -> i8 {
if x < zero_point { zero_point } else { x }
}
pub fn qrelu6(x: i8, zero_point: i8, q_six: i8) -> i8 {
if x < zero_point {
zero_point
} else if x > q_six {
q_six
} else {
x
}
}
pub const LUT_SIZE: usize = 256;
pub fn lut_index(x: i8) -> usize {
usize::from((x as u8).wrapping_add(128))
}
pub fn apply_lut(x: i8, lut: &[i8; LUT_SIZE]) -> i8 {
lut[lut_index(x)]
}
#[cfg(test)]
mod tests {
use super::*;
const Q31_ONE: i32 = i32::MAX;
fn i8_requant(multiplier: i32, shift: i32, zero_point: i8) -> Requantizer {
Requantizer {
multiplier,
shift,
zero_point,
qmin: -128,
qmax: 127,
}
}
#[test]
fn high_mul_saturates_min_squared() {
assert_eq!(
saturating_rounding_doubling_high_mul(i32::MIN, i32::MIN),
i32::MAX
);
}
#[test]
fn rounding_divide_by_pot_cases() {
assert_eq!(rounding_divide_by_pot(1234, 0), 1234);
assert_eq!(rounding_divide_by_pot(-1234, 0), -1234);
assert_eq!(rounding_divide_by_pot(1234, -3), 1234);
for (x, expected) in [
(8, 1),
(11, 1),
(12, 2),
(15, 2),
(-8, -1),
(-12, -2),
(-11, -1),
(-13, -2),
] {
assert_eq!(rounding_divide_by_pot(x, 3), expected, "{x} / 8");
}
}
#[test]
fn requantizer_known_answers() {
let identity = i8_requant(Q31_ONE, 0, 0);
assert_eq!(
[identity.apply(0), identity.apply(50), identity.apply(-50)],
[0, 50, -50]
);
assert_eq!([identity.apply(1000), identity.apply(-1000)], [127, -128]);
let halve = i8_requant(Q31_ONE, 1, 0);
assert_eq!(
[halve.apply(100), halve.apply(-100), halve.apply(0)],
[50, -50, 0]
);
let double = i8_requant(Q31_ONE, -1, 0);
assert_eq!([double.apply(30), double.apply(-30)], [60, -60]);
let zp = i8_requant(Q31_ONE, 0, 10);
assert_eq!(
[
zp.apply(0),
zp.apply(50),
zp.apply(-50),
zp.apply(200),
zp.apply(-200)
],
[10, 60, -40, 127, -128]
);
}
#[test]
fn requantizer_saturating_path_at_rails() {
let accs = [
i32::MIN,
i32::MIN + 1,
-(1 << 30) - 1,
-(1 << 30),
-(1 << 30) + 1,
-70000,
-1,
0,
1,
70000,
(1 << 30) - 1,
1 << 30,
(1 << 30) + 1,
i32::MAX - 1,
i32::MAX,
];
let multipliers = [0, 1, 1 << 30, Q31_ONE, -1, i32::MIN];
let zero_points: [i8; 5] = [-128, -127, 0, 126, 127];
let bounds: [[i8; 2]; 4] = [[-128, 127], [0, 127], [-128, 0], [0, 0]];
let mut cases = 0;
for shift in -31..=1 {
for multiplier in multipliers {
for zero_point in zero_points {
for [qmin, qmax] in bounds {
let rq = Requantizer {
multiplier,
shift,
zero_point,
qmin,
qmax,
};
for acc in accs {
let sum =
i64::from(multiply_by_quantized_multiplier(acc, multiplier, shift))
+ i64::from(zero_point);
let expected = sum.clamp(i64::from(qmin), i64::from(qmax));
assert_eq!(i64::from(rq.apply(acc)), expected);
cases += 1;
}
}
}
}
}
assert!(cases > 10_000);
}
#[test]
fn dense_known_answers() {
let unit = i8_requant(Q31_ONE, 0, 0);
let w1 = [[1, 1]];
let layer = QDense {
weights: &w1,
biases: Some(&[0]),
input_zero_point: 0,
requantizer: unit,
};
assert_eq!(layer.forward(&[3, 5]), [8]);
let w2 = [[2, 1], [-1, 3]];
let layer = QDense {
weights: &w2,
biases: Some(&[0, 0]),
input_zero_point: 0,
requantizer: unit,
};
assert_eq!(layer.forward(&[1, 2]), [4, 5]);
let layer = QDense {
weights: &w1,
biases: Some(&[10]),
input_zero_point: 0,
requantizer: unit,
};
assert_eq!(layer.forward(&[3, 5]), [18]);
let w3 = [[2]];
let layer = QDense {
weights: &w3,
biases: None,
input_zero_point: 0,
requantizer: unit,
};
assert_eq!(layer.forward(&[4]), [8]);
}
#[test]
fn per_channel_dense_matches_dense_with_shared_requantizer() {
let rq = Requantizer {
multiplier: 1_200_000_000,
shift: 6,
zero_point: -3,
qmin: -128,
qmax: 127,
};
let weights = [[12, -7, 100], [-128, 5, 9]];
let biases = [1000, -2000];
let input = [-128, 0, 77];
let shared = QDense {
weights: &weights,
biases: Some(&biases),
input_zero_point: -5,
requantizer: rq,
};
let per_channel = QDensePerChannel {
weights: &weights,
biases: Some(&biases),
input_zero_point: -5,
requantizers: &[rq, rq],
};
assert_eq!(per_channel.forward(&input), shared.forward(&input));
let other = Requantizer { shift: 4, ..rq };
let mixed = QDensePerChannel {
requantizers: &[rq, other],
..per_channel
};
let (a, b) = (mixed.forward(&input), shared.forward(&input));
assert_eq!(a[0], b[0]);
assert_ne!(a[1], b[1]);
}
#[test]
fn activations() {
assert_eq!([qrelu(-5, 0), qrelu(5, 0), qrelu(-128, -10)], [0, 5, -10]);
assert_eq!(
[qrelu6(-5, 0, 60), qrelu6(30, 0, 60), qrelu6(100, 0, 60)],
[0, 30, 60]
);
assert_eq!(
[lut_index(-128), lut_index(0), lut_index(127)],
[0, 128, 255]
);
let mut lut = [0i8; LUT_SIZE];
for (i, v) in lut.iter_mut().enumerate() {
*v = (i as i32 - 128) as i8;
}
assert_eq!(apply_lut(-7, &lut), -7);
}
}