use super::{LUT_SIZE, QAdd, QSoftmax, Requantizer};
#[cfg(doc)]
use super::{QGruCell, QLstmCell};
fn frexp(x: f64) -> (f64, i32) {
if x == 0.0 || !x.is_finite() {
return (x, 0);
}
let bits = x.to_bits();
let biased = ((bits >> 52) & 0x7ff) as i32;
if biased == 0 {
let (m, e) = frexp(x * f64::from_bits(0x4350_0000_0000_0000)); return (m, e - 54);
}
let mantissa = f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52));
(mantissa, biased - 1022)
}
pub fn quantize_multiplier(ratio: f64) -> (i32, i32) {
if ratio == 0.0 {
return (0, 0);
}
let (mantissa, mut exponent) = frexp(ratio);
let mut q = (mantissa * (1i64 << 31) as f64).round() as i64;
if q == 1i64 << 31 {
q >>= 1;
exponent += 1;
}
let shift = -exponent;
if shift > 31 {
(0, 0)
} else {
(q as i32, shift.max(-31))
}
}
pub fn build_requantizer(
input_scale: f32,
weight_scale: f32,
output_scale: f32,
output_zero_point: i32,
qmin: i32,
qmax: i32,
) -> Requantizer {
let ratio = (f64::from(input_scale) * f64::from(weight_scale)) / f64::from(output_scale);
let (multiplier, shift) = quantize_multiplier(ratio);
Requantizer {
multiplier,
shift,
zero_point: output_zero_point as i8,
qmin: qmin as i8,
qmax: qmax as i8,
}
}
pub fn build_rescaler(
input_scale: f32,
output_scale: f32,
output_zero_point: i32,
qmin: i32,
qmax: i32,
) -> Requantizer {
build_requantizer(
input_scale,
1.0,
output_scale,
output_zero_point,
qmin,
qmax,
)
}
pub fn build_mul_requantizer(
input_a_scale: f32,
input_b_scale: f32,
output_scale: f32,
output_zero_point: i32,
qmin: i32,
qmax: i32,
) -> Requantizer {
build_requantizer(
input_a_scale,
input_b_scale,
output_scale,
output_zero_point,
qmin,
qmax,
)
}
pub fn build_add(
input_a: (f32, i32),
input_b: (f32, i32),
output: (f32, i32),
qmin: i32,
qmax: i32,
) -> QAdd {
const LEFT_SHIFT: i32 = 20;
let (a_scale, b_scale) = (input_a.0, input_b.0);
let max_in = if a_scale > b_scale { a_scale } else { b_scale };
let twice_max = 2.0 * f64::from(max_in);
let real_a = f64::from(a_scale) / twice_max;
let real_b = f64::from(b_scale) / twice_max;
let real_out = twice_max / ((1i64 << LEFT_SHIFT) as f64 * f64::from(output.0));
let (input_a_multiplier, input_a_shift) = quantize_multiplier(real_a);
let (input_b_multiplier, input_b_shift) = quantize_multiplier(real_b);
let (multiplier, shift) = quantize_multiplier(real_out);
QAdd {
input_a_zero_point: input_a.1 as i8,
input_b_zero_point: input_b.1 as i8,
left_shift: LEFT_SHIFT,
input_a_multiplier,
input_a_shift,
input_b_multiplier,
input_b_shift,
output_requantizer: Requantizer {
multiplier,
shift,
zero_point: output.1 as i8,
qmin: qmin as i8,
qmax: qmax as i8,
},
}
}
pub fn affine_params_symmetric(fmin: f32, fmax: f32, qmax: i32) -> (f32, i32) {
let abs_min = if fmin < 0.0 { -fmin } else { fmin };
let abs_max = if fmax < 0.0 { -fmax } else { fmax };
let absmax = if abs_min > abs_max { abs_min } else { abs_max };
if absmax == 0.0 || qmax <= 0 {
return (1.0, 0);
}
(absmax / qmax as f32, 0)
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RangeObserver {
pub min_value: f32,
pub max_value: f32,
pub has_data: bool,
}
impl RangeObserver {
pub fn new() -> Self {
Self::default()
}
pub fn observe(&mut self, x: f32) {
if !self.has_data {
self.min_value = x;
self.max_value = x;
self.has_data = true;
} else {
if x < self.min_value {
self.min_value = x;
}
if x > self.max_value {
self.max_value = x;
}
}
}
pub fn observe_all(&mut self, xs: &[f32]) {
for &x in xs {
self.observe(x);
}
}
}
pub fn affine_params_asymmetric(fmin: f32, fmax: f32, qmin: i32, qmax: i32) -> (f32, i32) {
let fmin = if fmin > 0.0 { 0.0 } else { fmin };
let fmax = if fmax < 0.0 { 0.0 } else { fmax };
let qrange = qmax.wrapping_sub(qmin) as f32;
if fmax == fmin || qrange == 0.0 {
return (1.0, qmin);
}
let scale = (fmax - fmin) / qrange;
let mut zp = (f64::from(qmin) - f64::from(fmin) / f64::from(scale)).round() as i64;
if zp < i64::from(qmin) {
zp = i64::from(qmin);
}
if zp > i64::from(qmax) {
zp = i64::from(qmax);
}
(scale, zp as i32)
}
pub fn per_channel_symmetric_scales<const C: usize, const N: usize>(
weights: &[[f32; N]; C],
qmax: i32,
) -> [f32; C] {
let mut scales = [1.0f32; C];
for (scale, channel) in scales.iter_mut().zip(weights) {
let mut absmax = 0.0f32;
for &v in channel {
let a = if v < 0.0 { -v } else { v };
if a > absmax {
absmax = a;
}
}
if absmax != 0.0 && qmax > 0 {
*scale = absmax / qmax as f32;
}
}
scales
}
pub fn quantize(x: f32, scale: f32, zero_point: i32, qmin: i32, qmax: i32) -> i8 {
let q = (f64::from(x) / f64::from(scale)).round() + f64::from(zero_point);
let mut qi = q as i64;
if qi < i64::from(qmin) {
qi = i64::from(qmin);
}
if qi > i64::from(qmax) {
qi = i64::from(qmax);
}
qi as i8
}
pub fn dequantize(q: i8, scale: f32, zero_point: i32) -> f32 {
scale * (i32::from(q) - zero_point) as f32
}
fn saturate_round_to_i8(v: f32) -> i8 {
(f64::from(v).round() as i64).clamp(-128, 127) as i8
}
fn build_lut(
input_scale: f32,
input_zero_point: i32,
output_scale: f32,
output_zero_point: i32,
f: impl Fn(f32) -> f32,
) -> [i8; LUT_SIZE] {
core::array::from_fn(|index| {
let x = index as i32 - 128;
let x_real = input_scale * (x - input_zero_point) as f32;
let y_q = output_zero_point as f32 + f(x_real) / output_scale;
saturate_round_to_i8(y_q)
})
}
pub fn build_sigmoid_lut(
input_scale: f32,
input_zero_point: i32,
output_scale: f32,
output_zero_point: i32,
) -> [i8; LUT_SIZE] {
build_lut(
input_scale,
input_zero_point,
output_scale,
output_zero_point,
|x| 1.0 / (1.0 + (-x).exp()),
)
}
pub fn build_tanh_lut(
input_scale: f32,
input_zero_point: i32,
output_scale: f32,
output_zero_point: i32,
) -> [i8; LUT_SIZE] {
build_lut(
input_scale,
input_zero_point,
output_scale,
output_zero_point,
f32::tanh,
)
}
pub fn build_softmax(input_scale: f64, beta: f64) -> QSoftmax {
const INPUT_INTEGER_BITS: i32 = 5;
let max_real_multiplier = ((1i64 << 31) - 1) as f64;
let mut real_multiplier = beta * input_scale * (1i64 << (31 - INPUT_INTEGER_BITS)) as f64;
if real_multiplier > max_real_multiplier {
real_multiplier = max_real_multiplier;
}
let (input_multiplier, shift) = quantize_multiplier(real_multiplier);
let input_left_shift = -shift;
let max_input_rescaled = f64::from((1 << INPUT_INTEGER_BITS) - 1)
* (1i64 << (31 - INPUT_INTEGER_BITS)) as f64
/ 2f64.powi(input_left_shift);
QSoftmax {
input_multiplier,
input_left_shift,
diff_min: (max_input_rescaled.floor() as i32).saturating_neg(),
}
}
pub const SIGMOID_LUT_OUTPUT_SCALE: f32 = 1.0 / 256.0;
pub const TANH_LUT_OUTPUT_SCALE: f32 = 1.0 / 128.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LstmScales {
pub input_scale: f32,
pub hidden_scale: f32,
pub cell_scale: f32,
pub lut_input_scale: f32,
pub input_weight_scales: [f32; 4],
pub recurrent_weight_scales: [f32; 4],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LstmParams {
pub input_to_lut_multiplier: [i32; 4],
pub input_to_lut_shift: [i32; 4],
pub recurrent_to_lut_multiplier: [i32; 4],
pub recurrent_to_lut_shift: [i32; 4],
pub f_times_c_multiplier: i32,
pub f_times_c_shift: i32,
pub i_times_g_multiplier: i32,
pub i_times_g_shift: i32,
pub cell_to_tanh_multiplier: i32,
pub cell_to_tanh_shift: i32,
pub output_multiplier: i32,
pub output_shift: i32,
}
#[allow(clippy::type_complexity)]
fn gate_rescales<const G: usize>(
input_scale: f32,
hidden_scale: f32,
lut_input_scale: f32,
input_weight_scales: &[f32; G],
recurrent_weight_scales: &[f32; G],
) -> ([i32; G], [i32; G], [i32; G], [i32; G]) {
let mut out = ([0; G], [0; G], [0; G], [0; G]);
let lut = f64::from(lut_input_scale);
for g in 0..G {
let r_in = f64::from(input_scale) * f64::from(input_weight_scales[g]) / lut;
(out.0[g], out.1[g]) = quantize_multiplier(r_in);
let r_rec = f64::from(hidden_scale) * f64::from(recurrent_weight_scales[g]) / lut;
(out.2[g], out.3[g]) = quantize_multiplier(r_rec);
}
out
}
pub fn build_lstm_params(scales: &LstmScales) -> LstmParams {
let (in_m, in_s, rec_m, rec_s) = gate_rescales(
scales.input_scale,
scales.hidden_scale,
scales.lut_input_scale,
&scales.input_weight_scales,
&scales.recurrent_weight_scales,
);
let sig = f64::from(SIGMOID_LUT_OUTPUT_SCALE);
let tanh = f64::from(TANH_LUT_OUTPUT_SCALE);
let c = f64::from(scales.cell_scale);
let h = f64::from(scales.hidden_scale);
let (f_times_c_multiplier, f_times_c_shift) = quantize_multiplier(sig * c / c);
let (i_times_g_multiplier, i_times_g_shift) = quantize_multiplier(sig * tanh / c);
let (cell_to_tanh_multiplier, cell_to_tanh_shift) =
quantize_multiplier(c / f64::from(scales.lut_input_scale));
let (output_multiplier, output_shift) = quantize_multiplier(sig * tanh / h);
LstmParams {
input_to_lut_multiplier: in_m,
input_to_lut_shift: in_s,
recurrent_to_lut_multiplier: rec_m,
recurrent_to_lut_shift: rec_s,
f_times_c_multiplier,
f_times_c_shift,
i_times_g_multiplier,
i_times_g_shift,
cell_to_tanh_multiplier,
cell_to_tanh_shift,
output_multiplier,
output_shift,
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GruScales {
pub input_scale: f32,
pub hidden_scale: f32,
pub lut_input_scale: f32,
pub input_weight_scales: [f32; 3],
pub recurrent_weight_scales: [f32; 3],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GruParams {
pub input_to_lut_multiplier: [i32; 3],
pub input_to_lut_shift: [i32; 3],
pub recurrent_to_lut_multiplier: [i32; 3],
pub recurrent_to_lut_shift: [i32; 3],
pub r_times_h_multiplier: i32,
pub r_times_h_shift: i32,
pub one_minus_z_times_n_multiplier: i32,
pub one_minus_z_times_n_shift: i32,
pub z_times_h_multiplier: i32,
pub z_times_h_shift: i32,
}
pub fn build_gru_params(scales: &GruScales) -> GruParams {
let (in_m, in_s, rec_m, rec_s) = gate_rescales(
scales.input_scale,
scales.hidden_scale,
scales.lut_input_scale,
&scales.input_weight_scales,
&scales.recurrent_weight_scales,
);
let sig = f64::from(SIGMOID_LUT_OUTPUT_SCALE);
let tanh = f64::from(TANH_LUT_OUTPUT_SCALE);
let h = f64::from(scales.hidden_scale);
let (r_times_h_multiplier, r_times_h_shift) = quantize_multiplier(sig);
let (one_minus_z_times_n_multiplier, one_minus_z_times_n_shift) =
quantize_multiplier(sig * tanh / h);
let (z_times_h_multiplier, z_times_h_shift) = quantize_multiplier(sig);
GruParams {
input_to_lut_multiplier: in_m,
input_to_lut_shift: in_s,
recurrent_to_lut_multiplier: rec_m,
recurrent_to_lut_shift: rec_s,
r_times_h_multiplier,
r_times_h_shift,
one_minus_z_times_n_multiplier,
one_minus_z_times_n_shift,
z_times_h_multiplier,
z_times_h_shift,
}
}
pub fn quantize_gate_biases<const G: usize, const HID: usize>(
biases: &[[f32; HID]; G],
lut_input_scale: f32,
) -> [[i32; HID]; G] {
biases
.map(|gate| gate.map(|b| (f64::from(b) / f64::from(lut_input_scale)).round() as i64 as i32))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quantize_multiplier_cases() {
assert_eq!(quantize_multiplier(0.0), (0, 0));
assert_eq!(quantize_multiplier(1.0), (1 << 30, -1));
assert_eq!(quantize_multiplier(0.5), (1 << 30, 0));
assert_eq!(quantize_multiplier(1.0 - 1e-10), (1 << 30, -1));
assert_eq!(quantize_multiplier(2f64.powi(-31)), (1 << 30, 30));
assert_eq!(quantize_multiplier(2f64.powi(-32)), (1 << 30, 31));
assert_eq!(quantize_multiplier(0.75 * 2f64.powi(-32)), (0, 0));
assert_eq!(quantize_multiplier(2f64.powi(-40)), (0, 0));
assert_eq!(quantize_multiplier(1e-12), (0, 0));
assert_eq!(quantize_multiplier(2f64.powi(30)), (1 << 30, -31));
assert_eq!(quantize_multiplier(2f64.powi(31)), (1 << 30, -31));
assert_eq!(
quantize_multiplier(0.75 * 2f64.powi(32)),
(1_610_612_736, -31)
);
assert_eq!(quantize_multiplier(2f64.powi(40)), (1 << 30, -31));
assert_eq!(quantize_multiplier(1e15), (1_907_348_633, -31));
let rq = |(multiplier, shift)| Requantizer {
multiplier,
shift,
zero_point: 3,
qmin: -128,
qmax: 127,
};
for acc in [i32::MIN, -1 << 20, -2, -1, 0, 1, 2, 1 << 20, i32::MAX] {
assert_eq!(rq(quantize_multiplier(2f64.powi(-40))).apply(acc), 3);
assert_eq!(rq((1 << 30, -41)).apply(acc), rq((1 << 30, -31)).apply(acc));
}
let unity = build_requantizer(1.0, 1.0, 1.0, 0, -128, 127);
assert_eq!(unity.apply(42), 42);
let half = build_requantizer(1.0, 0.5, 1.0, 0, -128, 127);
assert_eq!(half.apply(100), 50);
}
#[test]
fn frexp_matches_c() {
for (x, m, e) in [
(1.0, 0.5, 1),
(0.75, 0.75, 0),
(3.0, 0.75, 2),
(-3.0, -0.75, 2),
(f64::MIN_POSITIVE, 0.5, -1021),
(f64::MIN_POSITIVE / 4.0, 0.5, -1023),
] {
assert_eq!(frexp(x), (m, e), "frexp({x})");
}
}
#[test]
fn quantize_rounds_half_away_and_saturates() {
assert_eq!(quantize(0.5, 1.0, 0, -128, 127), 1);
assert_eq!(quantize(-0.5, 1.0, 0, -128, 127), -1);
assert_eq!(quantize(1000.0, 1.0, 0, -128, 127), 127);
assert_eq!(quantize(-1000.0, 1.0, 0, -128, 127), -128);
assert_eq!(dequantize(-128, 0.5, -128), 0.0);
}
#[test]
fn range_observer_starts_from_its_first_value() {
let mut obs = RangeObserver::new();
assert!(!obs.has_data);
obs.observe(5.0);
assert_eq!((obs.min_value, obs.max_value), (5.0, 5.0));
obs.observe_all(&[7.0, 6.0, 2.5]);
assert_eq!((obs.min_value, obs.max_value), (2.5, 7.0));
assert!(obs.has_data);
}
#[test]
fn symmetric_params_cover_the_larger_magnitude() {
assert_eq!(affine_params_symmetric(-4.0, 2.0, 127), (4.0 / 127.0, 0));
assert_eq!(affine_params_symmetric(-1.0, 3.0, 127), (3.0 / 127.0, 0));
assert_eq!(affine_params_symmetric(0.0, 0.0, 127), (1.0, 0));
assert_eq!(affine_params_symmetric(-1.0, 1.0, 0), (1.0, 0));
}
}