Files
leleka/crates/native-cpu-expert/src/rust_quant.rs
T

385 lines
16 KiB
Rust

//! Literal Original and pinned GGML activation quantizers.
use super::rust_simd::to_half;
use super::rust_types::{ActQ, Q8K, Q8Zero};
use std::arch::x86_64::*;
// Bounds: q8_zero asserts x.len()==32*y.len() and stores 32 i8 per Q8Zero; q8_one_* assert x.len()<=2560 && %32==0, so
// every store lands in a.q[..x.len()] (H = 2560 i8) and a.scale/sum/hx[..x.len()/32] (80 entries); all vector accesses
// are unaligned (loadu/storeu). Gate: see rust_simd.rs SAFETY CONTRACT.
// ggml nearest_int: signed bit-bias rounding; inputs bounded by signed maximum.
fn nearest_int(x: f32) -> i32 {
debug_assert!(x.abs() <= 4_194_303.0);
let y = x + 12_582_912.0;
(y.to_bits() & 0x007f_ffff) as i32 - 0x0040_0000
}
pub(super) fn q8_k(x: &[f32], y: &mut [Q8K]) {
assert_eq!(x.len(), 256 * y.len());
for (xb, y) in x.chunks_exact(256).zip(y) {
let mut max = 0.0f32;
let mut amax = 0.0f32;
for &x in xb {
let ax = x.abs();
if ax > amax {
amax = ax;
max = x;
}
}
if amax == 0.0 {
y.d = 0.0;
y.qs.fill(0);
continue;
}
let iscale = -127.0 / max;
for (q, &x) in y.qs.iter_mut().zip(xb) {
*q = nearest_int(iscale * x).min(127) as i8;
}
for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) {
*sum = q.iter().map(|&v| v as i32).sum::<i32>() as i16;
}
y.d = 1.0 / iscale;
}
}
/// `LELEKA_Q8K=legacy` keeps the scalar `q8_k` on the borrowed-group path (A/B arm); the default there is `q8_k_avx2`.
pub(super) fn q8k_fast() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_Q8K").as_deref() != Ok("legacy"))
}
/// Horizontal maximum of the 8 lanes of `m` (high half first, then the pairwise reductions).
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn hmax_ps(m: __m256) -> f32 {
let mut h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m));
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
h = _mm_max_ss(h, _mm_movehdup_ps(h));
_mm_cvtss_f32(h)
}
/// Largest magnitude of the 256 floats of `xb`.
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn absmax256(xb: &[f32]) -> f32 {
unsafe {
let sign = _mm256_set1_ps(-0.0);
let mut m = _mm256_setzero_ps();
for c in 0..32 {
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, _mm256_loadu_ps(xb.as_ptr().add(8 * c))));
}
hmax_ps(m)
}
}
/// Quantize the 256 floats of `xb` with `iscale` into `y.qs` and rebuild `y.bsums`.
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn q8_k_store(xb: &[f32], iscale: f32, y: &mut Q8K) {
unsafe {
let vs = _mm256_set1_ps(iscale);
let magic = _mm256_set1_ps(12_582_912.0);
let mant = _mm256_set1_epi32(0x007f_ffff);
let bias = _mm256_set1_epi32(0x0040_0000);
let top = _mm256_set1_epi32(127);
let q = |c: usize| {
let v = _mm256_add_ps(_mm256_mul_ps(vs, _mm256_loadu_ps(xb.as_ptr().add(8 * c))), magic);
_mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(v), mant), bias), top)
};
for g in 0..8 {
let a = _mm256_packs_epi32(q(4 * g), q(4 * g + 1));
let b = _mm256_packs_epi32(q(4 * g + 2), q(4 * g + 3));
let p = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(a, b), _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
_mm256_storeu_si256(y.qs.as_mut_ptr().add(32 * g).cast(), p);
}
for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) {
*sum = q.iter().map(|&v| v as i32).sum::<i32>() as i16;
}
}
}
/// `q8_k` with the 256 products, roundings and the clamp in 256-bit lanes: the same IEEE multiply `iscale*x`, the same magic-number
/// `nearest_int` (add 12582912, mantissa bits), `min(127)`; the signed maximum is the FIRST element of largest magnitude (the scalar loop's
/// strict `>`), `d = 1/iscale`, `bsums` summed as before, and an all-zero block leaves `bsums` as the scalar one does. Inputs must be finite
/// (the caller's check), so no NaN reaches the maximum. Bitwise `q8_k` (`q8_k_avx2_is_bitwise_q8_k`).
#[target_feature(enable = "avx2,fma,f16c")]
pub(super) unsafe fn q8_k_avx2(x: &[f32], y: &mut [Q8K]) {
unsafe {
assert_eq!(x.len(), 256 * y.len());
for (xb, y) in x.chunks_exact(256).zip(y) {
let amax = absmax256(xb);
if amax == 0.0 {
y.d = 0.0;
y.qs.fill(0);
continue;
}
let max = *xb.iter().find(|v| v.abs() == amax).unwrap_or(&amax);
let iscale = -127.0 / max;
q8_k_store(xb, iscale, y);
y.d = 1.0 / iscale;
}
}
}
#[target_feature(enable = "avx2,fma,f16c")]
pub(super) unsafe fn q8_zero(x: &[f32], y: &mut [Q8Zero]) {
unsafe {
assert_eq!(x.len(), 32 * y.len());
for (xb, y) in x.chunks_exact(32).zip(y) {
let mut v0 = _mm256_loadu_ps(xb.as_ptr());
let mut v1 = _mm256_loadu_ps(xb.as_ptr().add(8));
let mut v2 = _mm256_loadu_ps(xb.as_ptr().add(16));
let mut v3 = _mm256_loadu_ps(xb.as_ptr().add(24));
let sign = _mm256_set1_ps(-0.0);
let mut m = _mm256_andnot_ps(sign, v0);
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v1));
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v2));
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v3));
let amax = hmax_ps(m);
let d = amax / 127.0;
y.d = to_half(d);
let inv = _mm256_set1_ps(if amax != 0.0 { 127.0 / amax } else { 0.0 });
v0 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v0, inv));
v1 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v1, inv));
v2 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v2, inv));
v3 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v3, inv));
let i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1));
let i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3));
let i0 = _mm256_packs_epi16(i0, i2);
let i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
_mm256_storeu_si256(y.qs.as_mut_ptr().cast(), i0);
}
}
}
/// Scale (`amax / 127`, 0 for an all-zero block) of the 32 floats `v` of a Q8 one-block.
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn q8_one_scale(v: &[__m256; 4]) -> f32 {
let absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
let mut m = _mm256_setzero_ps();
for x in v {
m = _mm256_max_ps(m, _mm256_and_ps(*x, absmask));
}
let mut h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps::<1>(m));
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
let amax = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h)));
if amax > 0.0 { amax / 127.0 } else { 0.0 }
}
/// Round-half-away, clamp to +-127 and store the 32 quantized values of `v` into `qi`; returns their lane sums.
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn q8_one_round(v: &[__m256; 4], inv: f32, qi: &mut [i32; 32]) -> __m256i {
unsafe {
let half = _mm256_set1_ps(0.5);
let mhalf = _mm256_set1_ps(-0.5);
let zero = _mm256_setzero_ps();
let lo = _mm256_set1_epi32(-127);
let hi = _mm256_set1_epi32(127);
let vinv = _mm256_set1_ps(inv);
let mut sum = _mm256_setzero_si256();
for i in 0..4 {
let t = _mm256_mul_ps(v[i], vinv);
let r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps::<_CMP_GE_OQ>(t, zero)));
let q = _mm256_min_epi32(_mm256_max_epi32(_mm256_cvttps_epi32(r), lo), hi);
sum = _mm256_add_epi32(sum, q);
_mm256_storeu_si256(qi.as_mut_ptr().add(8 * i).cast(), q);
}
sum
}
}
#[target_feature(enable = "avx2,fma,f16c")]
pub(super) unsafe fn q8_one_avx2(x: &[f32], a: &mut ActQ) {
unsafe {
assert!(x.len() <= 2560 && x.len() % 32 == 0);
a.nchunks = (x.len() / 32) as i32;
for (k, xb) in x.chunks_exact(32).enumerate() {
let v: [__m256; 4] = std::array::from_fn(|i| _mm256_loadu_ps(xb.as_ptr().add(8 * i)));
let s = q8_one_scale(&v);
let inv = if s > 0.0 { 1.0 / s } else { 0.0 };
let mut qi = [0i32; 32];
let sum = q8_one_round(&v, inv, &mut qi);
for (j, &q) in qi.iter().enumerate() {
a.q[k * 32 + j] = q as i8;
}
let mut s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256::<1>(sum));
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0x4e>(s4));
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0xb1>(s4));
let total = _mm_cvtsi128_si32(s4);
a.scale[k] = s;
a.sum[k] = total;
a.hx[k] = s * total as f32;
}
}
}
/// Round-half-away and clamp to +-127 of the 16 floats `x * vinv`.
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
unsafe fn quant16(x: __m512, vinv: __m512) -> __m512i {
let half = _mm512_set1_ps(0.5);
let mhalf = _mm512_set1_ps(-0.5);
let zero = _mm512_setzero_ps();
let lo = _mm512_set1_epi32(-127);
let hi = _mm512_set1_epi32(127);
let t = _mm512_mul_ps(x, vinv);
let r = _mm512_add_ps(t, _mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t, zero), mhalf, half));
_mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r), lo), hi)
}
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
pub(super) unsafe fn q8_one_avx512(x: &[f32], a: &mut ActQ) {
unsafe {
assert!(x.len() <= 2560 && x.len() % 32 == 0);
a.nchunks = (x.len() / 32) as i32;
let absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
for (k, xb) in x.chunks_exact(32).enumerate() {
let x0 = _mm512_loadu_ps(xb.as_ptr());
let x1 = _mm512_loadu_ps(xb.as_ptr().add(16));
let amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask)));
let s = if amax > 0.0 { amax / 127.0 } else { 0.0 };
let inv = if s > 0.0 { 1.0 / s } else { 0.0 };
let vinv = _mm512_set1_ps(inv);
let v0 = quant16(x0, vinv);
let v1 = quant16(x1, vinv);
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32).cast(), _mm512_cvtepi32_epi8(v0));
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32 + 16).cast(), _mm512_cvtepi32_epi8(v1));
let sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1));
a.scale[k] = s;
a.sum[k] = sum;
a.hx[k] = s * sum as f32;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Original expert.cpp scalar rule, evaluated FIRST without SIMD quantization.
// This bounded transport-free oracle covers tie rounding and the whole public
// activation extent. It does not qualify IQ dots or model output.
fn original_scalar(x: &[f32]) -> ActQ {
let mut a = ActQ::default();
a.nchunks = (x.len() / 32) as i32;
for (k, xb) in x.chunks_exact(32).enumerate() {
let mut maximum = 0.0f32;
for &value in xb {
maximum = maximum.max(value.abs());
}
let scale = if maximum > 0.0 { maximum / 127.0 } else { 0.0 };
let inv = if scale > 0.0 { 1.0 / scale } else { 0.0 };
let mut sum = 0i32;
for (j, &value) in xb.iter().enumerate() {
let t = value * inv;
let rounded = t + if t >= 0.0 { 0.5 } else { -0.5 };
let q = (rounded as i32).clamp(-127, 127);
a.q[k * 32 + j] = q as i8;
sum += q;
}
a.scale[k] = scale;
a.sum[k] = sum;
a.hx[k] = scale * sum as f32;
}
a
}
fn exact(actual: &ActQ, expected: &ActQ, n: usize) {
assert_eq!(actual.nchunks, expected.nchunks);
assert_eq!(&actual.q[..n], &expected.q[..n]);
assert_eq!(&actual.sum[..n / 32], &expected.sum[..n / 32]);
for k in 0..n / 32 {
assert_eq!(actual.scale[k].to_bits(), expected.scale[k].to_bits());
assert_eq!(actual.hx[k].to_bits(), expected.hx[k].to_bits());
}
}
#[test]
fn original_scalar_first_q8_one_ties_zero_and_full_rows() {
if !super::super::rust_simd::avx2_ok() {
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
return;
}
for n in [640usize, 2560] {
for changed in [false, true] {
let mut x = vec![0.0f32; n];
for (i, value) in x.iter_mut().enumerate() {
*value = match i % 32 {
0 => 127.0,
1 => -127.0,
2 => 0.5,
3 => -0.5,
4 => 1.5,
5 => -1.5,
6 => 0.0,
7 => -0.0,
_ => {
if changed {
(i % 61) as f32 - 30.0
} else {
(i % 47) as f32 - 23.0
}
}
};
}
let expected = original_scalar(&x);
let mut actual = ActQ::default();
// SAFETY: actual CPUID/XCR0 admission above; whole sanitized arrays.
unsafe {
q8_one_avx2(&x, &mut actual);
}
exact(&actual, &expected, n);
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
unsafe {
q8_one_avx512(&x, &mut actual);
}
exact(&actual, &expected, n);
}
x.fill(-0.0);
let expected = original_scalar(&x);
unsafe {
q8_one_avx2(&x, &mut actual);
}
exact(&actual, &expected, n);
}
}
}
}
#[cfg(test)]
mod q8k_tests {
use super::*;
fn xorshift(s: &mut u64) -> u64 {
*s ^= *s << 13;
*s ^= *s >> 7;
*s ^= *s << 17;
*s
}
#[test]
fn q8_k_avx2_is_bitwise_q8_k() {
if !super::super::rust_simd::avx2_ok() {
eprintln!("SKIP");
return;
}
let mut seed = 0x7a11_5eed_0102_0304u64;
for round in 0..400 {
let nb = 10;
let scale = [1e-6f32, 1e-3, 0.5, 3.0, 1e3, 3e4][round % 6];
let mut x: Vec<f32> =
(0..nb * 256).map(|_| ((xorshift(&mut seed) % 200001) as f32 - 100000.0) * scale / 1e5).collect();
// ties of magnitude with both signs, zero blocks, rounding-half cases
if round % 5 == 1 {
x[3] = 7.0 * scale;
x[200] = -7.0 * scale;
for v in x[256..512].iter_mut() {
*v = 0.0;
}
}
if round % 5 == 2 {
let m = x[..256].iter().fold(0.0f32, |a, v| a.max(v.abs()));
x[10] = -m;
x[11] = m;
}
if round % 5 == 3 {
for (i, v) in x.iter_mut().enumerate().take(256) {
*v = (i as f32 - 128.0) * 0.5;
}
}
let mut a = vec![Q8K::default(); nb];
let mut b = vec![Q8K::default(); nb];
for (i, (p, q)) in a.iter_mut().zip(b.iter_mut()).enumerate() {
p.bsums = [i as i16; 16];
q.bsums = [i as i16; 16];
}
q8_k(&x, &mut a);
unsafe {
q8_k_avx2(&x, &mut b);
}
for (i, (p, q)) in a.iter().zip(&b).enumerate() {
assert_eq!(p.d.to_bits(), q.d.to_bits(), "d round {round} block {i}");
assert_eq!(p.qs, q.qs, "qs round {round} block {i}");
assert_eq!(p.bsums, q.bsums, "bsums round {round} block {i}");
}
}
}
}