use half::f16;
use super::qp_quants::make_qp_quants;
use crate::Q4_K_SCALE_BYTES;
pub(crate) const QK_SUB_ELEMS: usize = 32;
pub(crate) const QK_SUBS: usize = 8;
pub(crate) const GROUP_MAX_EPS: f32 = 1e-15;
#[inline]
pub(crate) fn nearest_int(fval: f32) -> i32 {
let val = fval + 12_582_912.0f32;
let i = val.to_bits() as i32;
(i & 0x007f_ffff) - 0x0040_0000
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn make_qkx2_quants(
x: &[f32],
weights: &[f32],
l: &mut [u8],
laux: &mut [u8],
nmax: i32,
rmin: f32,
rdelta: f32,
nstep: i32,
use_mad: bool,
) -> (f32, f32) {
let n = x.len();
debug_assert_eq!(weights.len(), n);
debug_assert_eq!(l.len(), n);
debug_assert!(laux.len() >= n);
let mut min = x[0];
let mut max = x[0];
let mut sum_w = weights[0];
let mut sum_x = sum_w * x[0];
for i in 1..n {
if x[i] < min {
min = x[i];
}
if x[i] > max {
max = x[i];
}
let w = weights[i];
sum_w += w;
sum_x = w.mul_add(x[i], sum_x);
}
if min > 0.0 {
min = 0.0;
}
if max == min {
l[..n].fill(0);
return (0.0, -min);
}
let mut iscale = nmax as f32 / (max - min);
let mut scale = 1.0 / iscale;
let mut best_error = 0.0f32;
for i in 0..n {
let li = nearest_int(iscale * (x[i] - min)).clamp(0, nmax);
l[i] = li as u8;
let diff = scale.mul_add(l[i] as f32, min) - x[i];
let diff = if use_mad { diff.abs() } else { diff * diff };
best_error = weights[i].mul_add(diff, best_error);
}
if nstep < 1 {
return (scale, -min);
}
for is in 0..=nstep {
iscale = (rmin + rdelta * is as f32 + nmax as f32) / (max - min);
let (mut sum_l, mut sum_l2, mut sum_xl) = (0.0f32, 0.0f32, 0.0f32);
for i in 0..n {
let li = nearest_int(iscale * (x[i] - min)).clamp(0, nmax);
laux[i] = li as u8;
let w = weights[i];
sum_l = w.mul_add(li as f32, sum_l);
sum_l2 = (w * li as f32).mul_add(li as f32, sum_l2);
sum_xl = (w * li as f32).mul_add(x[i], sum_xl);
}
let det = sum_w.mul_add(sum_l2, -(sum_l * sum_l));
if det > 0.0 {
let mut this_scale = sum_w.mul_add(sum_xl, -(sum_x * sum_l)) / det;
let mut this_min = sum_l2.mul_add(sum_x, -(sum_l * sum_xl)) / det;
if this_min > 0.0 {
this_min = 0.0;
this_scale = sum_xl / sum_l2;
}
let mut cur_error = 0.0f32;
for i in 0..n {
let diff = this_scale.mul_add(laux[i] as f32, this_min) - x[i];
let diff = if use_mad { diff.abs() } else { diff * diff };
cur_error = weights[i].mul_add(diff, cur_error);
}
if cur_error < best_error {
l[..n].copy_from_slice(&laux[..n]);
best_error = cur_error;
scale = this_scale;
min = this_min;
}
}
}
(scale, -min)
}
#[inline]
fn qx_weight(x: &[f32], qw: Option<&[f32]>, rmse_type: i32, i: usize) -> f32 {
match qw {
Some(qw) => qw[i],
None => match rmse_type {
1 => x[i] * x[i],
2 => 1.0,
3 => x[i].abs(),
_ => x[i].abs().sqrt(),
},
}
}
pub(crate) fn make_qx_quants(
x: &[f32],
l: &mut [i8],
nmax: i32,
rmse_type: i32,
qw: Option<&[f32]>,
) -> f32 {
let n = x.len();
debug_assert_eq!(l.len(), n);
let mut max = 0f32;
let mut amax = 0f32;
for &v in x {
let ax = v.abs();
if ax > amax {
amax = ax;
max = v;
}
}
if amax < GROUP_MAX_EPS {
l[..n].fill(0);
return 0.0;
}
let mut iscale = -(nmax as f32) / max;
if rmse_type == 0 {
for i in 0..n {
let li = nearest_int(iscale * x[i]);
l[i] = (nmax + li.clamp(-nmax, nmax - 1)) as i8;
}
return 1.0 / iscale;
}
let (rmse_type, return_early) = if rmse_type < 0 {
(-rmse_type, true)
} else {
(rmse_type, false)
};
let mut sumlx = 0f32;
let mut suml2 = 0f32;
for i in 0..n {
let li = nearest_int(iscale * x[i]).clamp(-nmax, nmax - 1);
l[i] = (li + nmax) as i8;
let w = qx_weight(x, qw, rmse_type, i);
sumlx = (w * x[i]).mul_add(li as f32, sumlx);
suml2 = (w * li as f32).mul_add(li as f32, suml2);
}
let mut scale = if suml2 != 0.0 { sumlx / suml2 } else { 0.0 };
if return_early {
return if suml2 > 0.0 {
0.5 * (scale + 1.0 / iscale)
} else {
1.0 / iscale
};
}
let mut best = scale * sumlx;
for is in -9..=9i32 {
if is == 0 {
continue;
}
iscale = -(nmax as f32 + 0.1 * is as f32) / max;
sumlx = 0.0;
suml2 = 0.0;
for i in 0..n {
let li = nearest_int(iscale * x[i]).clamp(-nmax, nmax - 1);
let w = qx_weight(x, qw, rmse_type, i);
sumlx = (w * x[i]).mul_add(li as f32, sumlx);
suml2 = (w * li as f32).mul_add(li as f32, suml2);
}
if suml2 > 0.0 && sumlx * sumlx > best * suml2 {
for i in 0..n {
let li = nearest_int(iscale * x[i]);
l[i] = (nmax + li.clamp(-nmax, nmax - 1)) as i8;
}
scale = sumlx / suml2;
best = scale * sumlx;
}
}
scale
}
pub(crate) fn qk_sub_block_weights(xs: &[f32], weights: &mut [f32; QK_SUB_ELEMS]) {
let mut sum_x2 = 0f32;
for &v in xs {
sum_x2 += v * v;
}
let av_x = (sum_x2 / QK_SUB_ELEMS as f32).sqrt();
for (w, &v) in weights.iter_mut().zip(xs) {
*w = av_x + v.abs();
}
}
pub(crate) struct QkSuperBlock {
pub d: f16,
pub dmin: f16,
pub packed: [u8; Q4_K_SCALE_BYTES],
pub l: [u8; QK_SUBS * QK_SUB_ELEMS],
}
#[derive(Clone, Copy)]
pub(crate) struct QkFit {
pub nmax: i32,
pub rmin: f32,
pub rdelta: f32,
pub nstep: i32,
pub imatrix_clamps_scale_codes: bool,
}
const IMATRIX_GRID: (f32, f32, i32) = (-0.9, 0.05, 36);
pub(crate) fn fit_qk_super_block(
block: &[f32; QK_SUBS * QK_SUB_ELEMS],
fit: QkFit,
qw: Option<&[f32; QK_SUBS * QK_SUB_ELEMS]>,
) -> QkSuperBlock {
let mut l = [0u8; QK_SUBS * QK_SUB_ELEMS];
let mut laux = [0u8; QK_SUB_ELEMS];
let mut weights = [0f32; QK_SUB_ELEMS];
let mut mins = [0f32; QK_SUBS];
let mut scales = [0f32; QK_SUBS];
let mut sw = [0f32; QK_SUBS];
let sigma2 = qw.map(|_| {
let mut sum_x2 = 0f32;
for &v in block.iter() {
sum_x2 = v.mul_add(v, sum_x2);
}
2.0 * sum_x2 / (QK_SUBS * QK_SUB_ELEMS) as f32
});
let (rmin, rdelta, nstep) = match qw {
Some(_) => IMATRIX_GRID,
None => (fit.rmin, fit.rdelta, fit.nstep),
};
let mut max_scale = 0f32; let mut max_min = 0f32;
for j in 0..QK_SUBS {
let lo = QK_SUB_ELEMS * j;
let xs = &block[lo..lo + QK_SUB_ELEMS];
match (qw, sigma2) {
(Some(qw), Some(sigma2)) => {
for (w, (&v, &q)) in weights.iter_mut().zip(xs.iter().zip(&qw[lo..])) {
*w = q * v.mul_add(v, sigma2).sqrt();
}
let mut sumw = 0f32;
for &w in &weights {
sumw += w;
}
sw[j] = sumw;
}
_ => qk_sub_block_weights(xs, &mut weights),
}
let (scale, min) = make_qkx2_quants(
xs,
&weights,
&mut l[lo..lo + QK_SUB_ELEMS],
&mut laux,
fit.nmax,
rmin,
rdelta,
nstep,
false,
);
scales[j] = scale;
mins[j] = min;
if scale > max_scale {
max_scale = scale;
}
if min > max_min {
max_min = min;
}
}
let mut packed = [0u8; Q4_K_SCALE_BYTES];
let (d, dmin) = match qw {
None => {
let inv_scale = if max_scale > 0.0 {
63.0 / max_scale
} else {
0.0
};
let inv_min = if max_min > 0.0 { 63.0 / max_min } else { 0.0 };
for j in 0..QK_SUBS {
let ls = (nearest_int(inv_scale * scales[j]) as u8).min(63);
let lm = (nearest_int(inv_min * mins[j]) as u8).min(63);
pack_scale_min(&mut packed, j, ls, lm);
}
(
f16::from_f32(max_scale / 63.0),
f16::from_f32(max_min / 63.0),
)
}
Some(_) => {
let mut ls = [0u8; QK_SUBS];
let mut lm = [0u8; QK_SUBS];
let d_block = make_qp_quants(&scales, &mut ls, 63, &sw);
let m_block = make_qp_quants(&mins, &mut lm, 63, &sw);
for j in 0..QK_SUBS {
let (mut s, mut m) = (ls[j], lm[j]);
if fit.imatrix_clamps_scale_codes {
s = s.min(63);
m = m.min(63);
}
pack_scale_min(&mut packed, j, s, m);
}
(f16::from_f32(d_block), f16::from_f32(m_block))
}
};
for j in 0..QK_SUBS {
let (sc, m) = crate::q4_k_scale_min(j, &packed);
let dj = d.to_f32() * sc as f32;
if dj == 0.0 {
continue;
}
let dm = dmin.to_f32() * m as f32;
for ii in 0..QK_SUB_ELEMS {
let idx = QK_SUB_ELEMS * j + ii;
l[idx] = nearest_int((block[idx] + dm) / dj).clamp(0, fit.nmax) as u8;
}
}
QkSuperBlock { d, dmin, packed, l }
}
#[inline]
fn pack_scale_min(packed: &mut [u8; Q4_K_SCALE_BYTES], j: usize, ls: u8, lm: u8) {
if j < 4 {
packed[j] = ls;
packed[j + 4] = lm;
} else {
packed[j + 4] = (ls & 0xF) | ((lm & 0xF) << 4);
packed[j - 4] |= (ls >> 4) << 6;
packed[j] |= (lm >> 4) << 6;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nearest_int_rounds_ties_to_even_like_the_fpu() {
assert_eq!(nearest_int(0.5), 0);
assert_eq!(nearest_int(1.5), 2);
assert_eq!(nearest_int(2.5), 2);
assert_eq!(nearest_int(-0.5), 0);
assert_eq!(nearest_int(-1.5), -2);
assert_eq!(nearest_int(3.7), 4);
assert_eq!(nearest_int(-3.7), -4);
assert_eq!(nearest_int(3.2), 3.2f32.round() as i32);
}
#[test]
fn make_qx_quants_reports_an_all_zero_group_with_zero_codes_and_zero_scale() {
let mut l = [7i8; 16];
let scale = make_qx_quants(&[0.0; 16], &mut l, 32, 1, None);
assert_eq!(scale, 0.0);
assert_eq!(l, [0i8; 16]);
}
#[test]
fn make_qx_quants_maps_the_extreme_element_to_the_negative_end() {
let x: [f32; 16] = [
1.0, -0.5, 0.25, 0.0, 0.125, -0.75, 0.5, -0.25, 0.0625, -0.0625, 0.3, -0.3, 0.9, -0.9,
0.7, -0.1,
];
let mut l = [0i8; 16];
let scale = make_qx_quants(&x, &mut l, 32, 1, None);
assert!(scale < 0.0, "scale {scale}");
assert_eq!(l[0], 0);
assert!(l[13] > 32, "l[13] = {}", l[13]);
}
#[test]
fn the_rmse_type_actually_selects_a_different_weight() {
let mut x = [0.001f32; 16];
x[0] = 1.0;
x[7] = -0.4;
let mut l1 = [0i8; 16];
let mut l2 = [0i8; 16];
let s1 = make_qx_quants(&x, &mut l1, 32, 1, None);
let s2 = make_qx_quants(&x, &mut l2, 32, 2, None);
assert_ne!(
s1, s2,
"rmse_type 1 and 2 produced the same scale; this input no \
longer distinguishes the weights"
);
}
#[test]
fn the_q4_k_and_q5_k_candidate_grids_fit_the_same_data_differently() {
let mut block = [0f32; QK_SUBS * QK_SUB_ELEMS];
let mut state: u32 = 0x2f6b_1c05;
for v in block.iter_mut() {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
*v = f16::from_f32(((state >> 8) as f32 / 8_388_608.0 - 1.0) * 0.07).to_f32();
}
let q4 = fit_qk_super_block(
&block,
QkFit {
nmax: 15,
rmin: -1.0,
rdelta: 0.1,
nstep: 20,
imatrix_clamps_scale_codes: false,
},
None,
);
let q5 = fit_qk_super_block(
&block,
QkFit {
nmax: 31,
rmin: -0.5,
rdelta: 0.1,
nstep: 15,
imatrix_clamps_scale_codes: true,
},
None,
);
assert_ne!(q4.d, q5.d);
assert_ne!(q4.packed, q5.packed);
assert!(q5.l.iter().any(|&c| c > 15));
assert!(q4.l.iter().all(|&c| c <= 15));
}
}