pub(crate) mod add;
#[cfg(feature = "std")]
pub mod calibration;
pub(crate) mod compose;
pub(crate) mod conv;
pub(crate) mod pool;
pub use add::{QAdd, Tensor};
pub use compose::{QConcat, QMul, QPad2D};
pub use conv::{
QConv2D, QConv2DPerChannel, QDepthwiseConv2D, QPointwiseConv2D, QPointwiseConv2DPerChannel,
};
pub use pool::{QAvgPool2D, QGlobalAvgPool2D, QMaxPool2D};
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,
)
}
pub(crate) fn saturating_shl(x: i32, n: u32) -> i32 {
if n > 30 {
if x > 0 {
i32::MAX
} else if x < 0 {
i32::MIN
} else {
0
}
} else if n > 0 {
let limit = i32::MAX >> n;
if x > limit {
i32::MAX
} else if x < -limit - 1 {
i32::MIN
} else {
x * (1 << n)
}
} else {
x
}
}
#[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
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct FastRequantizer {
multiplier: i32,
nudge_high: u32,
high_shift: u32,
qmin: i32,
qmax: i32,
}
impl FastRequantizer {
pub(crate) fn new(rq: &Requantizer) -> Option<Self> {
if rq.multiplier < 0 || !(2..=31).contains(&rq.shift) {
return None;
}
let zp_term = i64::from(rq.zero_point) * (1i64 << (rq.shift - 1));
if zp_term.abs() > 1 << 29 {
return None;
}
Some(FastRequantizer {
multiplier: rq.multiplier,
nudge_high: ((1i64 << (rq.shift - 2)) + zp_term) as u32,
high_shift: (rq.shift - 1) as u32,
qmin: rq.qmin.into(),
qmax: rq.qmax.into(),
})
}
#[inline]
pub(crate) fn apply(&self, acc: i32) -> i8 {
let negative = (acc as u32) >> 31;
let high = self.nudge_high.wrapping_sub(negative);
let low = (negative << 31) | 0x4000_0000;
let nudge = (u64::from(high) << 32) | u64::from(low);
let v = nudge.wrapping_add((i64::from(acc) * i64::from(self.multiplier)) as u64);
let mut r = ((v >> 32) as u32 as i32) >> (self.high_shift & 31);
if r < self.qmin {
r = self.qmin;
}
if r > self.qmax {
r = self.qmax;
}
r 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)]
}
fn mul_by_pot_saturating(x: i32, exponent: u32) -> i32 {
let threshold = ((1u32 << (31 - exponent)) - 1) as i32;
if x > threshold {
i32::MAX
} else if x < -threshold {
i32::MIN
} else {
x * (1 << exponent)
}
}
pub(crate) fn exp_on_negative_values(a: i32) -> i32 {
const ONE_QUARTER: i32 = 1 << 24;
const EXP_OF_MINUS_ONE_EIGHTH: i32 = 1_895_147_668;
const EXP_OF_MINUS_POWER_OF_TWO: [i32; 7] = [
1_672_461_947,
1_302_514_674,
790_015_084,
290_630_308,
39_332_535,
720_401,
242,
];
let a_mod_quarter_minus_one_quarter = (a & (ONE_QUARTER - 1)) - ONE_QUARTER;
let x = a_mod_quarter_minus_one_quarter * 32 + (1 << 28);
let x2 = saturating_rounding_doubling_high_mul(x, x);
let x3 = saturating_rounding_doubling_high_mul(x2, x);
let x4 = saturating_rounding_doubling_high_mul(x2, x2);
let x4_over_4 = rounding_divide_by_pot(x4, 2);
let series = rounding_divide_by_pot(
saturating_rounding_doubling_high_mul(x4_over_4 + x3, 715_827_883) + x2,
1,
);
let mut result = EXP_OF_MINUS_ONE_EIGHTH
+ saturating_rounding_doubling_high_mul(EXP_OF_MINUS_ONE_EIGHTH, x + series);
let remainder = a_mod_quarter_minus_one_quarter.wrapping_sub(a);
for (k, &factor) in EXP_OF_MINUS_POWER_OF_TWO.iter().enumerate() {
if remainder & (1 << (24 + k)) != 0 {
result = saturating_rounding_doubling_high_mul(result, factor);
}
}
if a == 0 { i32::MAX } else { result }
}
pub(crate) fn one_over_one_plus_x(a: i32) -> i32 {
let sum = i64::from(a) + i64::from(i32::MAX);
let half_denominator = ((sum + if sum >= 0 { 1 } else { -1 }) / 2) as i32;
let mut x =
1_515_870_810 + saturating_rounding_doubling_high_mul(half_denominator, -1_010_580_540);
let one: i32 = 1 << 29;
for _ in 0..3 {
let one_minus_half_denominator_times_x =
one.wrapping_sub(saturating_rounding_doubling_high_mul(half_denominator, x));
x = x.wrapping_add(mul_by_pot_saturating(
saturating_rounding_doubling_high_mul(x, one_minus_half_denominator_times_x),
2,
));
}
mul_by_pot_saturating(x, 1)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QSoftmax {
pub input_multiplier: i32,
pub input_left_shift: i32,
pub diff_min: i32,
}
impl QSoftmax {
pub fn forward<const N: usize>(&self, input: &[i8; N]) -> [i8; N] {
const { assert!(N > 0 && N < 512, "QSoftmax needs 1 to 511 logits per row") };
const ACCUMULATION_INTEGER_BITS: i32 = 12;
let left_shift = self.input_left_shift.clamp(0, 31) as u32;
let exp_of = |diff: i32| {
let scaled = saturating_rounding_doubling_high_mul(
diff.wrapping_mul(1 << left_shift),
self.input_multiplier,
);
exp_on_negative_values(scaled)
};
let max = i32::from(input.iter().copied().fold(i8::MIN, i8::max));
let mut sum_of_exps: i32 = 0;
for &x in input {
let diff = i32::from(x) - max;
if diff >= self.diff_min {
sum_of_exps = sum_of_exps.wrapping_add(rounding_divide_by_pot(
exp_of(diff),
ACCUMULATION_INTEGER_BITS,
));
}
}
let headroom_plus_one = (sum_of_exps as u32).leading_zeros();
let shifted_sum_minus_one = (sum_of_exps as u32)
.checked_shl(headroom_plus_one)
.unwrap_or(0)
.wrapping_sub(1 << 31) as i32;
let shifted_scale = one_over_one_plus_x(shifted_sum_minus_one);
let exponent = (ACCUMULATION_INTEGER_BITS - headroom_plus_one as i32) + 31 - 8;
let mut output = [-128i8; N];
for (out, &x) in output.iter_mut().zip(input) {
let diff = i32::from(x) - max;
if diff >= self.diff_min {
let q = rounding_divide_by_pot(
saturating_rounding_doubling_high_mul(shifted_scale, exp_of(diff)),
exponent,
) - 128;
*out = q.clamp(-128, 127) as i8;
}
}
output
}
}
#[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);
}
#[test]
fn softmax_exp_every_fraction() {
let mut previous = exp_on_negative_values(0);
assert_eq!(previous, i32::MAX);
for a in (-(1 << 24)..0).rev() {
let e = exp_on_negative_values(a);
assert!(
e > 0 && e <= previous,
"exp({a}) = {e}, previous {previous}"
);
previous = e;
}
for a in [-(1 << 26), -(3 << 24), -(5 << 26) - 12_345, -(31 << 26)] {
let got = f64::from(exp_on_negative_values(a)) / 2f64.powi(31);
let want = (f64::from(a) / 2f64.powi(26)).exp();
assert!((got - want).abs() < 1e-6, "exp({a}): {got} vs {want}");
}
}
#[test]
fn softmax_reciprocal() {
for a in (0..i32::MAX).step_by(4093).chain([i32::MAX]) {
let got = f64::from(one_over_one_plus_x(a)) / 2f64.powi(31);
let want = 1.0 / (1.0 + f64::from(a) / 2f64.powi(31));
assert!((got - want).abs() < 1e-8, "1/(1+{a}): {got} vs {want}");
}
}
#[test]
fn softmax_basics() {
let softmax = QSoftmax {
input_multiplier: 1_717_986_918,
input_left_shift: 23,
diff_min: -248,
};
assert_eq!(softmax.forward(&[5]), [127]);
let y = softmax.forward(&[10, 20, 30]);
assert!(y[0] < y[1] && y[1] < y[2]);
let total: i32 = y.iter().map(|&v| i32::from(v) + 128).sum();
assert!((254..=258).contains(&total), "{y:?}");
assert_eq!(softmax.forward(&[127, -128])[1], -128);
}
}