Merge claude/size4-n1 into hexagonal-integ (STRA-338 size)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-07 09:47:47 +01:00
co-authored by Claude Sonnet 5.5
15 changed files with 2086 additions and 1476 deletions
@@ -2,233 +2,350 @@
#[allow(unused_imports)]
use super::*;
use std::ffi::CStr;
pub(super) fn cpu_blob(
f: &NativeFormat,
blob: &[u8],
x: &[f32],
seed: u32,
) -> std::result::Result<(Vec<f32>, usize), String> {
type Fail<T> = std::result::Result<T, String>;
/// The quantized activations and the gate/up result `ff` shared by the phases of `cpu_blob`.
struct Case<'a> {
f: &'a NativeFormat,
blob: &'a [u8],
act: [NativeActivation; NT],
hq: [NativeActivation<1024>; NT],
ff: Vec<f32>,
}
impl<'a> Case<'a> {
fn new(f: &'a NativeFormat, blob: &'a [u8], x: &[f32]) -> Fail<Self> {
let mut act: [NativeActivation; NT] = std::array::from_fn(|_| NativeActivation::default());
let hq: [NativeActivation<1024>; NT] = std::array::from_fn(|_| NativeActivation::default());
let ff = numerical(zeros::<f32>(NT * FF))?;
quantize_acts(&mut act, f.gu, x, H)?;
let mut case = Case { f, blob, act, hq, ff };
case.gate_up()?;
Ok(case)
}
fn gate_up(&mut self) -> Fail<()> {
numerical(cpu::native_gu_rows(self.f, self.blob, &refs(&self.act), &mut outputs(&mut self.ff, FF), 0, FF))
}
/// Quantizes `ff` (as left by the throughput loops) into `hq`, runs down, then re-runs GU for width invariance.
fn down(&mut self) -> Fail<Vec<f32>> {
// Original quantizes the ff left by the explicit throughput loops, BEFORE
// re-running GU for width invariance. Do not quantize hq again afterwards.
quantize_acts(&mut self.hq, self.f.down, &self.ff, FF)?;
let mut got = numerical(zeros::<f32>(NT * H))?;
numerical(cpu::native_down_rows(self.f, self.blob, &refs(&self.hq), &mut outputs(&mut got, H), 0, H))?;
self.gate_up()?;
Ok(got)
}
}
fn quantize_acts<const B: usize>(acts: &mut [NativeActivation<B>], kind: Kind, src: &[f32], width: usize) -> Fail<()> {
for (k, a) in acts.iter_mut().enumerate() {
numerical(a.quantize(kind, &src[k * width..(k + 1) * width]))?;
}
Ok(())
}
pub(super) fn cpu_blob(f: &NativeFormat, blob: &[u8], x: &[f32], seed: u32) -> Fail<(Vec<f32>, usize)> {
let mut failures = 0usize;
let gn = name(f.gu);
let dn = name(f.down);
let mut act: [NativeActivation; NT] = std::array::from_fn(|_| NativeActivation::default());
let mut hq: [NativeActivation<1024>; NT] = std::array::from_fn(|_| NativeActivation::default());
let mut ff = numerical(zeros::<f32>(NT * FF))?;
for k in 0..NT {
numerical(act[k].quantize(f.gu, &x[k * H..(k + 1) * H]))?;
}
numerical(cpu::native_gu_rows(f, blob, &refs(&act), &mut outputs(&mut ff, FF), 0, FF))?;
let mut case = Case::new(f, blob, x)?;
if cpu::iq_supported(f.gu) {
let mut gref = numerical(zeros::<f32>(NT * FF))?;
numerical(ggml_rows(f.gu, &blob[..f.up_offset], H, &act, &mut gref))?;
let start = Instant::now();
for _ in 0..50 {
for r in 0..FF {
std::hint::black_box(numerical(dot(f.gu, &blob[r * f.gu_row..(r + 1) * f.gu_row], &act[0], H))?);
std::hint::black_box(numerical(dot(
f.gu,
&blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row],
&act[0],
H,
))?);
}
failures += iq_gate_up(&mut case)?;
}
let got = case.down()?;
failures += width_invariance(&case, &got)?;
failures += kq_roles(f, blob, seed)?;
failures += down_alternatives(&case, &got)?;
// Keep the Original type name owner alive through all variadic calls.
drop(dn);
Ok((got, failures))
}
// ---- IQ gate/up rows against ggml, per ISA ----
fn iq_gate_up(c: &mut Case) -> Fail<usize> {
let f = c.f;
let mut gref = numerical(zeros::<f32>(NT * FF))?;
numerical(ggml_rows(f.gu, &c.blob[..f.up_offset], H, &c.act, &mut gref))?;
let usg = time_ggml_gu(c)?;
let mut failures = 0;
for is512 in [true, false] {
if is512 && !cpu::cpu_avx512_ok() {
continue;
}
let usg = elapsed(start, 50);
for is512 in [true, false] {
if is512 && !cpu::cpu_avx512_ok() {
continue;
}
let tag = if is512 { c"avx512" } else { c"avx2" };
let mut g = numerical(zeros::<f32>(NT * FF))?;
numerical(cpu::iq_rows(
f.gu,
&blob[..f.up_offset],
H,
&refs(&act),
&mut outputs(&mut g, FF),
0,
FF,
is512,
))?;
let rg = rel(&g, &gref)?;
report!(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", gn.as_ptr(), tag.as_ptr(), rg);
if rg > 1e-5 {
report!(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", gn.as_ptr(), tag.as_ptr(), rg);
failures += 1;
}
let a1 = [&act[0]];
let mut f1 = [&mut ff[..FF]];
let start = Instant::now();
for _ in 0..50 {
numerical(cpu::iq_gu_rows(f, blob, &a1, &mut f1, 0, FF, is512))?;
}
let us1 = elapsed(start, 50);
let aa = [&act[0], &act[1], &act[2]];
let mut views = outputs(&mut ff, FF);
let start = Instant::now();
for _ in 0..50 {
numerical(cpu::iq_gu_rows(f, blob, &aa, &mut views, 0, FF, is512))?;
}
let usn = elapsed(start, 50);
report!(
" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n",
tag.as_ptr(),
us1,
2.0 * f.up_offset as f64 / us1 / 1e3,
usg,
2.0 * f.up_offset as f64 / usg / 1e3
);
report!(
" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n",
NT as c_int,
tag.as_ptr(),
usn,
NT as c_int,
usg
);
failures += iq_isa(c, &gref, usg, is512)?;
}
Ok(failures)
}
fn time_ggml_gu(c: &Case) -> Fail<f64> {
let (f, a) = (c.f, &c.act[0]);
let start = Instant::now();
for _ in 0..50 {
for r in 0..FF {
let gate = &c.blob[r * f.gu_row..(r + 1) * f.gu_row];
let up = &c.blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row];
std::hint::black_box(numerical(dot(f.gu, gate, a, H))?);
std::hint::black_box(numerical(dot(f.gu, up, a, H))?);
}
}
// Original quantizes the ff left by the explicit throughput loops, BEFORE
// re-running GU for width invariance. Do not quantize hq again afterwards.
for k in 0..NT {
numerical(hq[k].quantize(f.down, &ff[k * FF..(k + 1) * FF]))?;
Ok(elapsed(start, 50))
}
fn iq_isa(c: &mut Case, gref: &[f32], usg: f64, is512: bool) -> Fail<usize> {
let tag = if is512 { c"avx512" } else { c"avx2" };
let failures = iq_gate_check(c, gref, tag, is512)?;
let (us1, usn) = time_iq_gu(c, is512)?;
let up = c.f.up_offset;
report!(
" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n",
tag.as_ptr(),
us1,
2.0 * up as f64 / us1 / 1e3,
usg,
2.0 * up as f64 / usg / 1e3
);
report!(
" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n",
NT as c_int,
tag.as_ptr(),
usn,
NT as c_int,
usg
);
Ok(failures)
}
fn iq_gate_check(c: &Case, gref: &[f32], tag: &CStr, is512: bool) -> Fail<usize> {
let (f, gn) = (c.f, name(c.f.gu));
let mut g = numerical(zeros::<f32>(NT * FF))?;
let weights = &c.blob[..f.up_offset];
numerical(cpu::iq_rows(f.gu, weights, H, &refs(&c.act), &mut outputs(&mut g, FF), 0, FF, is512))?;
let rg = rel(&g, gref)?;
report!(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", gn.as_ptr(), tag.as_ptr(), rg);
if rg <= 1e-5 {
return Ok(0);
}
let mut got = numerical(zeros::<f32>(NT * H))?;
numerical(cpu::native_down_rows(f, blob, &refs(&hq), &mut outputs(&mut got, H), 0, H))?;
numerical(cpu::native_gu_rows(f, blob, &refs(&act), &mut outputs(&mut ff, FF), 0, FF))?;
let (mut gu_diff, mut dn_diff) = (0usize, 0usize);
let mut one_ff = numerical(zeros::<f32>(FF))?;
let mut one_out = numerical(zeros::<f32>(H))?;
for k in 0..NT {
numerical(cpu::native_gu_rows(f, blob, &[&act[k]], &mut [&mut one_ff], 0, FF))?;
gu_diff += bits(&one_ff, &ff[k * FF..(k + 1) * FF])?;
numerical(cpu::native_down_rows(f, blob, &[&hq[k]], &mut [&mut one_out], 0, H))?;
dn_diff += bits(&one_out, &got[k * H..(k + 1) * H])?;
report!(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", gn.as_ptr(), tag.as_ptr(), rg);
Ok(1)
}
/// Microseconds per call of the one-token and of the three-token gate+up route.
fn time_iq_gu(c: &mut Case, is512: bool) -> Fail<(f64, f64)> {
let (f, blob) = (c.f, c.blob);
let a1 = [&c.act[0]];
let mut f1 = [&mut c.ff[..FF]];
let start = Instant::now();
for _ in 0..50 {
numerical(cpu::iq_gu_rows(f, blob, &a1, &mut f1, 0, FF, is512))?;
}
let us1 = elapsed(start, 50);
let aa = [&c.act[0], &c.act[1], &c.act[2]];
let mut views = outputs(&mut c.ff, FF);
let start = Instant::now();
for _ in 0..50 {
numerical(cpu::iq_gu_rows(f, blob, &aa, &mut views, 0, FF, is512))?;
}
Ok((us1, elapsed(start, 50)))
}
// ---- width invariance ----
fn width_invariance(c: &Case, got: &[f32]) -> Fail<usize> {
let (gu_diff, dn_diff) = width_diffs(c, got)?;
report!(
" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n",
NT as c_int,
gu_diff,
dn_diff
);
if gu_diff != 0 || dn_diff != 0 {
failures += 1;
Ok(usize::from(gu_diff != 0 || dn_diff != 0))
}
fn width_diffs(c: &Case, got: &[f32]) -> Fail<(usize, usize)> {
let (f, blob) = (c.f, c.blob);
let (mut gu_diff, mut dn_diff) = (0usize, 0usize);
let mut one_ff = numerical(zeros::<f32>(FF))?;
let mut one_out = numerical(zeros::<f32>(H))?;
for k in 0..NT {
numerical(cpu::native_gu_rows(f, blob, &[&c.act[k]], &mut [&mut one_ff], 0, FF))?;
gu_diff += bits(&one_ff, &c.ff[k * FF..(k + 1) * FF])?;
numerical(cpu::native_down_rows(f, blob, &[&c.hq[k]], &mut [&mut one_out], 0, H))?;
dn_diff += bits(&one_out, &got[k * H..(k + 1) * H])?;
}
Ok((gu_diff, dn_diff))
}
// ---- multi-token K-quant rows against ggml ----
/// One K-quant tensor of the blob (gate/up or down) the multi-token route is compared on.
struct KqCase<'a> {
kind: Kind,
role_name: &'static CStr,
w: &'a [u8],
width: usize,
rows: usize,
stride: usize,
}
fn kq_roles(f: &NativeFormat, blob: &[u8], seed: u32) -> Fail<usize> {
let mut failures = 0;
for role in 0..2 {
let kind = if role == 0 { f.gu } else { f.down };
if !cpu::kq_supported(kind) || (role == 0 && kind != Kind::Q4K) {
continue;
failures += kq_role(f, blob, seed, role)?;
}
Ok(failures)
}
fn kq_case<'a>(f: &NativeFormat, blob: &'a [u8], role: usize) -> Option<KqCase<'a>> {
let kind = if role == 0 { f.gu } else { f.down };
if !cpu::kq_supported(kind) || (role == 0 && kind != Kind::Q4K) {
return None;
}
Some(if role == 0 {
KqCase { kind, role_name: c"gate", w: &blob[..f.up_offset], width: H, rows: FF, stride: f.gu_row }
} else {
KqCase { kind, role_name: c"down", w: &blob[f.down_offset..], width: FF, rows: H, stride: f.down_row }
})
}
fn kq_role(f: &NativeFormat, blob: &[u8], seed: u32, role: usize) -> Fail<usize> {
let Some(case) = kq_case(f, blob, role) else { return Ok(0) };
let acts = kq_acts(case.kind, case.width, seed)?;
let mut reference = numerical(zeros::<f32>(8 * case.rows))?;
let mut values = numerical(zeros::<f32>(8 * case.rows))?;
numerical(ggml_rows(case.kind, case.w, case.width, &acts, &mut reference))?;
let differ = kq_differ(&case, &acts, &reference, &mut values)?;
let (usk, usg) = kq_times(&case, &acts, &mut values)?;
let kn = name(case.kind);
report!(
" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; \
4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n",
kn.as_ptr(),
case.role_name.as_ptr(),
differ,
usk,
usg,
usg / usk
);
Ok(usize::from(differ != 0))
}
fn kq_acts(kind: Kind, width: usize, seed: u32) -> Fail<[NativeActivation; 8]> {
let mut rng = bench::Mt19937::new(77u32.wrapping_add(seed));
let mut normal = bench::NormalFloat::default();
let mut xs = numerical(zeros::<f32>(width))?;
let mut acts: [NativeActivation; 8] = std::array::from_fn(|_| NativeActivation::default());
for a in &mut acts {
for v in &mut xs {
*v = normal.next(&mut rng);
}
let (width, rows, stride, w) = if role == 0 {
(H, FF, f.gu_row, &blob[..f.up_offset])
} else {
(FF, H, f.down_row, &blob[f.down_offset..])
};
let mut rng = bench::Mt19937::new(77u32.wrapping_add(seed));
let mut normal = bench::NormalFloat::default();
let mut xs = numerical(zeros::<f32>(width))?;
let mut acts: [NativeActivation; 8] = std::array::from_fn(|_| NativeActivation::default());
for a in &mut acts {
for v in &mut xs {
*v = normal.next(&mut rng);
}
numerical(a.quantize(kind, &xs))?;
numerical(a.quantize(kind, &xs))?;
}
Ok(acts)
}
/// Number of (1..=8 token) sets whose rows differ in any bit from the ggml reference.
fn kq_differ(k: &KqCase, acts: &[NativeActivation; 8], reference: &[f32], values: &mut [f32]) -> Fail<usize> {
let rows = k.rows;
let mut differ = 0usize;
for nt in 1..=8 {
let mut views = outputs(&mut values[..nt * rows], rows);
numerical(cpu::kq_rows(k.kind, k.w, k.width, &refs(&acts[..nt]), &mut views, 0, rows))?;
for t in 0..nt {
let (got, want) = (&values[t * rows..(t + 1) * rows], &reference[t * rows..(t + 1) * rows]);
differ += usize::from(bits(got, want)? != 0);
}
let mut reference = numerical(zeros::<f32>(8 * rows))?;
let mut values = numerical(zeros::<f32>(8 * rows))?;
numerical(ggml_rows(kind, w, width, &acts, &mut reference))?;
let mut differ = 0usize;
for nt in 1..=8 {
numerical(cpu::kq_rows(
kind,
w,
width,
&refs(&acts[..nt]),
&mut outputs(&mut values[..nt * rows], rows),
0,
rows,
))?;
for t in 0..nt {
differ +=
usize::from(bits(&values[t * rows..(t + 1) * rows], &reference[t * rows..(t + 1) * rows])? != 0);
}
Ok(differ)
}
/// Microseconds per call of the four-token route and of the same four tokens through ggml's dot.
fn kq_times(k: &KqCase, acts: &[NativeActivation; 8], values: &mut [f32]) -> Fail<(f64, f64)> {
let rows = k.rows;
let aa = [&acts[0], &acts[1], &acts[2], &acts[3]];
let mut views = outputs(&mut values[..4 * rows], rows);
let start = Instant::now();
for _ in 0..30 {
numerical(cpu::kq_rows(k.kind, k.w, k.width, &aa, &mut views, 0, rows))?;
}
let usk = elapsed(start, 30);
drop(views);
let start = Instant::now();
for _ in 0..30 {
for r in 0..rows {
for t in 0..4 {
let row = &k.w[r * k.stride..(r + 1) * k.stride];
values[t * rows + r] = numerical(dot(k.kind, row, &acts[t], k.width))?;
}
}
let aa = [&acts[0], &acts[1], &acts[2], &acts[3]];
let mut views = outputs(&mut values[..4 * rows], rows);
let start = Instant::now();
for _ in 0..30 {
numerical(cpu::kq_rows(kind, w, width, &aa, &mut views, 0, rows))?;
}
let usk = elapsed(start, 30);
drop(views);
let start = Instant::now();
for _ in 0..30 {
for r in 0..rows {
for t in 0..4 {
values[t * rows + r] = numerical(dot(kind, &w[r * stride..(r + 1) * stride], &acts[t], width))?;
}
}
}
let usg = elapsed(start, 30);
let kn = name(kind);
let rn = if role == 0 { c"gate" } else { c"down" };
report!(
" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; 4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n",
kn.as_ptr(),
rn.as_ptr(),
differ,
usk,
usg,
usg / usk
);
if differ != 0 {
failures += 1;
}
}
Ok((usk, elapsed(start, 30)))
}
// ---- the Q2_0 and IQ4_NL down alternatives ----
fn down_alternatives(c: &Case, got: &[f32]) -> Fail<usize> {
let mut failures = 0;
if c.f.down == Kind::Q2Zero {
q2_report(c, got)?;
}
if c.f.down == Kind::Iq4Nl {
failures += iq4nl_report(c)?;
}
Ok(failures)
}
fn q2_report(c: &Case, got: &[f32]) -> Fail<()> {
let mut a: [crate::rust_legacy::PlanarActivation; NT] =
std::array::from_fn(|_| crate::rust_legacy::PlanarActivation::default());
for k in 0..NT {
numerical(a[k].quantize_native(&c.ff[k * FF..(k + 1) * FF]))?;
}
let mut alt = numerical(zeros::<f32>(NT * H))?;
let aa: Vec<_> = a.iter().collect();
numerical(cpu::q2_rows(&c.blob[c.f.down_offset..], FF, &aa, &mut outputs(&mut alt, H), 0, H))?;
let tag = if cpu::cpu_avx512_ok() { c"AVX-512" } else { c"AVX-2" };
report!(" q2_0 %s down vs ggml down: rel %.2e\n", tag.as_ptr(), rel(&alt, got)?);
Ok(())
}
fn iq4nl_report(c: &Case) -> Fail<usize> {
let (f, w) = (c.f, &c.blob[c.f.down_offset..]);
let mut alt = numerical(zeros::<f32>(NT * H))?;
let mut reference = numerical(zeros::<f32>(NT * H))?;
numerical(iq4nl_hq(w, &c.hq, &mut alt))?;
numerical(ggml_rows(f.down, w, FF, &c.hq, &mut reference))?;
let rdn = rel(&alt, &reference)?;
report!(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn);
let failures = usize::from(rdn > 1e-5);
if failures != 0 {
report!(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn);
}
if f.down == Kind::Q2Zero {
let mut a: [crate::rust_legacy::PlanarActivation; NT] =
std::array::from_fn(|_| crate::rust_legacy::PlanarActivation::default());
for k in 0..NT {
numerical(a[k].quantize_native(&ff[k * FF..(k + 1) * FF]))?;
}
let mut alt = numerical(zeros::<f32>(NT * H))?;
let aa: Vec<_> = a.iter().collect();
numerical(cpu::q2_rows(&blob[f.down_offset..], FF, &aa, &mut outputs(&mut alt, H), 0, H))?;
let tag = if cpu::cpu_avx512_ok() { c"AVX-512" } else { c"AVX-2" };
report!(" q2_0 %s down vs ggml down: rel %.2e\n", tag.as_ptr(), rel(&alt, &got)?);
let (usn, usg) = iq4nl_times(c, &mut alt, &mut reference)?;
let bytes = (f.bytes - f.down_offset) as f64;
report!(
" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n",
NT as c_int,
usn,
bytes / usn / 1e3,
usg,
bytes / usg / 1e3
);
Ok(failures)
}
fn iq4nl_times(c: &Case, alt: &mut [f32], reference: &mut [f32]) -> Fail<(f64, f64)> {
let w = &c.blob[c.f.down_offset..];
let start = Instant::now();
for _ in 0..50 {
numerical(iq4nl_hq(w, &c.hq, alt))?;
}
if f.down == Kind::Iq4Nl {
let mut alt = numerical(zeros::<f32>(NT * H))?;
let mut reference = numerical(zeros::<f32>(NT * H))?;
numerical(iq4nl_hq(&blob[f.down_offset..], &hq, &mut alt))?;
numerical(ggml_rows(f.down, &blob[f.down_offset..], FF, &hq, &mut reference))?;
let rdn = rel(&alt, &reference)?;
report!(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn);
if rdn > 1e-5 {
report!(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn);
failures += 1;
}
let start = Instant::now();
for _ in 0..50 {
numerical(iq4nl_hq(&blob[f.down_offset..], &hq, &mut alt))?;
}
let usn = elapsed(start, 50);
let start = Instant::now();
for _ in 0..50 {
numerical(ggml_rows(f.down, &blob[f.down_offset..], FF, &hq, &mut reference))?;
}
let usg = elapsed(start, 50);
report!(
" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n",
NT as c_int,
usn,
(f.bytes - f.down_offset) as f64 / usn / 1e3,
usg,
(f.bytes - f.down_offset) as f64 / usg / 1e3
);
let usn = elapsed(start, 50);
let start = Instant::now();
for _ in 0..50 {
numerical(ggml_rows(c.f.down, w, FF, &c.hq, reference))?;
}
// Keep the Original type name owner alive through all variadic calls.
drop(dn);
Ok((got, failures))
Ok((usn, elapsed(start, 50)))
}
@@ -3,122 +3,80 @@
#[allow(unused_imports)]
use super::*;
type Fail<T> = std::result::Result<T, String>;
pub(super) fn float_reference(weights: &bench::DequantizedExpert, input: &[f32]) -> Result<Vec<f32>> {
if input.len() != NT * H
|| weights.gate.len() != FF * H
|| weights.up.len() != FF * H
|| weights.down.len() != H * FF
{
if !reference_shapes_ok(weights, input) {
return Err(Error::Shape);
}
let mut out = zeros::<f32>(NT * H)?;
for t in 0..NT {
let mut hidden = zeros::<f32>(FF)?;
for r in 0..FF {
let (mut g, mut u) = (0.0f64, 0.0f64);
for i in 0..H {
g += weights.gate[r * H + i] as f64 * input[t * H + i] as f64;
u += weights.up[r * H + i] as f64 * input[t * H + i] as f64;
}
hidden[r] = (g / (1.0 + (-g).exp()) * u) as f32;
}
for r in 0..H {
let mut value = 0.0f64;
for i in 0..FF {
value += weights.down[r * FF + i] as f64 * hidden[i] as f64;
}
out[t * H + r] = value as f32;
}
let hidden = swiglu_hidden(weights, &input[t * H..(t + 1) * H])?;
project_down(weights, &hidden, &mut out[t * H..(t + 1) * H]);
}
Ok(out)
}
fn reference_shapes_ok(weights: &bench::DequantizedExpert, input: &[f32]) -> bool {
input.len() == NT * H && weights.gate.len() == FF * H && weights.up.len() == FF * H && weights.down.len() == H * FF
}
/// silu(gate . x) * (up . x) per hidden row, accumulated in f64.
fn swiglu_hidden(weights: &bench::DequantizedExpert, x: &[f32]) -> Result<Vec<f32>> {
let mut hidden = zeros::<f32>(FF)?;
for r in 0..FF {
let (mut g, mut u) = (0.0f64, 0.0f64);
for i in 0..H {
g += weights.gate[r * H + i] as f64 * x[i] as f64;
u += weights.up[r * H + i] as f64 * x[i] as f64;
}
hidden[r] = (g / (1.0 + (-g).exp()) * u) as f32;
}
Ok(hidden)
}
fn project_down(weights: &bench::DequantizedExpert, hidden: &[f32], out: &mut [f32]) {
for r in 0..H {
let mut value = 0.0f64;
for i in 0..FF {
value += weights.down[r * FF + i] as f64 * hidden[i] as f64;
}
out[r] = value as f32;
}
}
pub(super) fn check_blob<G: ParityGpu>(
f: &NativeFormat,
blob: &[u8],
seed: u32,
label: &str,
gpu: &mut G,
) -> std::result::Result<usize, String> {
) -> Fail<usize> {
let (weights, x, reference) = blob_inputs(f, blob, seed)?;
let (cpu, failures) = cpu_blob(f, blob, &x, seed)?;
let mut expert = gpu.prepare_expert(f, blob, &x)?;
let candidate = gpu_expert_checks(f, gpu, &mut expert, &weights);
let close = gpu.release_expert(expert);
let (got, gpu_failures) = candidate.and_then(|v| close.map(|()| v))?;
let (errors, ok) = cpu_gpu_errors(&cpu, &got, &reference)?;
report_blob(f, label, errors, ok)?;
Ok(failures + gpu_failures + usize::from(!ok))
}
/// ([cpu, gpu, cpu-vs-gpu] relative errors, whether the cpu and gpu ones are finite and within 3e-2).
fn cpu_gpu_errors(cpu: &[f32], got: &[f32], reference: &[f32]) -> Fail<([f64; 3], bool)> {
let (ec, eg, ecg) = (rel(cpu, reference)?, rel(got, reference)?, rel(cpu, got)?);
Ok(([ec, eg, ecg], ec < 3e-2 && eg < 3e-2 && ec.is_finite() && eg.is_finite()))
}
fn blob_inputs(f: &NativeFormat, blob: &[u8], seed: u32) -> Fail<(bench::DequantizedExpert, Vec<f32>, Vec<f32>)> {
let weights = numerical(bench::dequantize_expert(f, blob))?;
let x = numerical(bench::check_inputs(seed, NT, H))?;
let reference = numerical(float_reference(&weights, &x))?;
let (cpu, mut failures) = cpu_blob(f, blob, &x, seed)?;
let mut expert = gpu.prepare_expert(f, blob, &x)?;
let candidate = (|| {
gpu.enqueue_expert(&mut expert)?;
let got = gpu.download_expert(&mut expert)?;
if got.len() != NT * H {
return Err("GPU expert output extent".into());
}
let was = gpu.old_kernels();
gpu.set_old_kernels(!was);
let enqueue = gpu.enqueue_expert(&mut expert);
gpu.set_old_kernels(was);
enqueue?;
let old = gpu.download_expert(&mut expert)?;
let same = bits(&old, &got)? == 0;
report!(
" gpu decode-once vs per-entry kernels: %s\n",
if same { c"bitwise equal" } else { c"MISMATCH" }.as_ptr()
);
if !same {
failures += 1;
}
let (mut dqerr, mut differ, mut hdiffer) = (0.0f64, 0usize, 0usize);
for (role, want) in [&weights.gate, &weights.up, &weights.down].iter().enumerate() {
let (dq, dh) = gpu.dequantize_expert_role(&expert, role)?;
if dq.len() != FF * H || dh.len() != FF * H {
return Err("GPU dequant output extent".into());
}
// std::max(old, value) preserves old on NaN (not f64::max policy).
let e = rel(&dq, want)?;
if dqerr < e {
dqerr = e;
}
differ += bits(&dq, want)?;
if !cpu::cpu_avx2_ok() {
return Err("CPU FP16 conversion unsupported".into());
}
// SAFETY (to_half below): cpu_avx2_ok() (F16C) checked on the previous line.
for (v, h) in dq.iter().zip(dh) {
hdiffer += usize::from(h != unsafe { crate::rust_simd::to_half(*v) });
}
}
let tk: Vec<i32> = (0..FF).map(|r| (FF - 1 - r) as i32).collect();
let emb = gpu.embed_expert_gate(&expert, &tk)?;
if emb.len() != FF * H {
return Err("GPU embedding output extent".into());
}
let mut embdiff = 0usize;
for r in 0..FF {
embdiff += usize::from(bits(&emb[r * H..(r + 1) * H], &weights.gate[(FF - 1 - r) * H..(FF - r) * H])? != 0);
}
report!(
" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of it: %zu differ; embedding rows: %zu of %lld differ\n",
dqerr,
differ,
(3 * FF * H) as i64,
hdiffer,
embdiff,
FF as i64
);
if !(dqerr < 1e-6)
|| hdiffer != 0
|| (f.gu == Kind::Q8Zero && f.down == Kind::Q8Zero && (differ != 0 || embdiff != 0))
{
failures += 1;
}
Ok(got)
})();
let close = gpu.release_expert(expert);
let got = match (candidate, close) {
(Err(e), _) => return Err(e),
(Ok(_), Err(e)) => return Err(e),
(Ok(v), Ok(())) => v,
};
let (ec, eg, ecg) = (rel(&cpu, &reference)?, rel(&got, &reference)?, rel(&cpu, &got)?);
let ok = ec < 3e-2 && eg < 3e-2 && ec.is_finite() && eg.is_finite();
Ok((weights, x, reference))
}
fn report_blob(f: &NativeFormat, label: &str, errors: [f64; 3], ok: bool) -> Fail<()> {
let label = CString::new(label).map_err(|_| "benchmark label contains NUL")?;
let gn = name(f.gu);
let dn = name(f.down);
@@ -128,52 +86,124 @@ pub(super) fn check_blob<G: ParityGpu>(
gn.as_ptr(),
dn.as_ptr(),
f.bytes,
ec,
eg,
ecg,
errors[0],
errors[1],
errors[2],
if ok { c"ok" } else { c"FAIL" }.as_ptr()
);
Ok(failures + usize::from(!ok))
Ok(())
}
pub(super) fn check_q5_one<G: ParityGpu>(gpu: &mut G) -> std::result::Result<usize, String> {
/// Runs the GPU expert and compares it with the old kernels, the dequantizers and the embedding; the failure count
/// of those comparisons comes with the GPU output.
fn gpu_expert_checks<G: ParityGpu>(
f: &NativeFormat,
gpu: &mut G,
expert: &mut G::Expert,
weights: &bench::DequantizedExpert,
) -> Fail<(Vec<f32>, usize)> {
gpu.enqueue_expert(expert)?;
let got = gpu.download_expert(expert)?;
if got.len() != NT * H {
return Err("GPU expert output extent".into());
}
let mut failures = old_kernels_check(gpu, expert, &got)?;
let (dqerr, differ, hdiffer) = dequant_checks(gpu, expert, weights)?;
let embdiff = embedding_check(gpu, expert, weights)?;
report!(
" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; \
fp16 of it: %zu differ; embedding rows: %zu of %lld differ\n",
dqerr,
differ,
(3 * FF * H) as i64,
hdiffer,
embdiff,
FF as i64
);
failures += usize::from(dequant_failed(f, dqerr, differ, hdiffer, embdiff));
Ok((got, failures))
}
fn dequant_failed(f: &NativeFormat, dqerr: f64, differ: usize, hdiffer: usize, embdiff: usize) -> bool {
let q8 = f.gu == Kind::Q8Zero && f.down == Kind::Q8Zero;
!(dqerr < 1e-6) || hdiffer != 0 || (q8 && (differ != 0 || embdiff != 0))
}
/// Runs the other generation of kernels on the same expert; 1 when its output differs from `got` in any bit.
fn old_kernels_check<G: ParityGpu>(gpu: &mut G, expert: &mut G::Expert, got: &[f32]) -> Fail<usize> {
let was = gpu.old_kernels();
gpu.set_old_kernels(!was);
let enqueue = gpu.enqueue_expert(expert);
gpu.set_old_kernels(was);
enqueue?;
let old = gpu.download_expert(expert)?;
let same = bits(&old, got)? == 0;
report!(
" gpu decode-once vs per-entry kernels: %s\n",
if same { c"bitwise equal" } else { c"MISMATCH" }.as_ptr()
);
Ok(usize::from(!same))
}
/// (largest relative error, values differing in any bit, fp16 values differing) over gate, up and down.
fn dequant_checks<G: ParityGpu>(
gpu: &mut G,
expert: &G::Expert,
weights: &bench::DequantizedExpert,
) -> Fail<(f64, usize, usize)> {
let (mut dqerr, mut differ, mut hdiffer) = (0.0f64, 0usize, 0usize);
for (role, want) in [&weights.gate, &weights.up, &weights.down].iter().enumerate() {
let (dq, dh) = dequant_role(gpu, expert, role)?;
// std::max(old, value) preserves old on NaN (not f64::max policy).
let e = rel(&dq, want)?;
if dqerr < e {
dqerr = e;
}
differ += bits(&dq, want)?;
hdiffer += half_differences(&dq, &dh)?;
}
Ok((dqerr, differ, hdiffer))
}
fn dequant_role<G: ParityGpu>(gpu: &mut G, expert: &G::Expert, role: usize) -> Fail<(Vec<f32>, Vec<u16>)> {
let (dq, dh) = gpu.dequantize_expert_role(expert, role)?;
if dq.len() != FF * H || dh.len() != FF * H {
return Err("GPU dequant output extent".into());
}
Ok((dq, dh))
}
fn half_differences(dq: &[f32], dh: &[u16]) -> Fail<usize> {
if !cpu::cpu_avx2_ok() {
return Err("CPU FP16 conversion unsupported".into());
}
// SAFETY (to_half below): cpu_avx2_ok() (F16C) checked above.
Ok(dq.iter().zip(dh).filter(|(v, h)| **h != unsafe { crate::rust_simd::to_half(**v) }).count())
}
/// Embedding rows of the gate tensor in reverse order; the number of rows differing in any bit.
fn embedding_check<G: ParityGpu>(gpu: &mut G, expert: &G::Expert, weights: &bench::DequantizedExpert) -> Fail<usize> {
let tk: Vec<i32> = (0..FF).map(|r| (FF - 1 - r) as i32).collect();
let emb = gpu.embed_expert_gate(expert, &tk)?;
if emb.len() != FF * H {
return Err("GPU embedding output extent".into());
}
let mut embdiff = 0usize;
for r in 0..FF {
embdiff += usize::from(bits(&emb[r * H..(r + 1) * H], &weights.gate[(FF - 1 - r) * H..(FF - r) * H])? != 0);
}
Ok(embdiff)
}
pub(super) fn check_q5_one<G: ParityGpu>(gpu: &mut G) -> Fail<usize> {
let case = numerical(bench::q5_one_min_case())?;
let (got, raw) = gpu.q5_one_min(&case.weights, &case.input)?;
if got.len() != 64 || raw.len() != 720 {
return Err("Q5_1 GPU product extent".into());
}
if !cpu::cpu_avx2_ok() {
return Err("Q5_1 CPU unsupported".into());
}
let mut stored = Q81Owner([0; 720]);
stored.0.copy_from_slice(&raw);
let mut summed = Q81Owner(stored.0);
let mut shift = 0.0f64;
// SAFETY (the half/to_half calls in this loop): cpu_avx2_ok() (F16C) was checked at the top of this function.
for b in summed.0.chunks_exact_mut(36) {
let d = u16::from_le_bytes([b[0], b[1]]);
let s = u16::from_le_bytes([b[2], b[3]]);
let sum = b[4..].iter().map(|v| *v as i8 as i32).sum::<i32>();
let dd = unsafe { crate::rust_simd::half(d) };
let ss = unsafe { crate::rust_simd::half(s) };
let e = (ss - dd * sum as f32).abs() as f64;
if shift < e {
shift = e;
}
b[2..4].copy_from_slice(&unsafe { crate::rust_simd::to_half(dd * sum as f32) }.to_le_bytes());
}
let mut want = numerical(zeros::<f32>(64))?;
let mut original = numerical(zeros::<f32>(64))?;
let stride = numerical(Kind::Q5One.row_bytes(640))?;
// SAFETY (dot_raw): `row` is one Q5_1 row (stride = row_bytes(640)); `summed.0`/`stored.0` are 720-byte, 64-aligned Q81Owner = 20 Q8One blocks.
for r in 0..64 {
let row = &case.weights[r * stride..(r + 1) * stride];
unsafe {
want[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &summed.0);
original[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &stored.0);
}
}
let (eq, es) = (rel(&got, &want)?, rel(&got, &original)?);
let ok = eq < 1e-3 && es > 10.0 * eq && shift > 0.0;
let (stored, summed, shift) = q5_sums(&raw)?;
let (want, original) = q5_dots(&case.weights, &summed, &stored)?;
let (eq, es, ok) = q5_verdict(&got, &want, &original, shift)?;
report!(
"q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n",
got[0] as f64,
@@ -181,7 +211,8 @@ pub(super) fn check_q5_one<G: ParityGpu>(gpu: &mut G) -> std::result::Result<usi
original[0] as f64
);
report!(
"q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e (largest per-block sum shift %.3g) %s\n",
"q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e \
(largest per-block sum shift %.3g) %s\n",
eq,
es,
shift,
@@ -189,35 +220,75 @@ pub(super) fn check_q5_one<G: ParityGpu>(gpu: &mut G) -> std::result::Result<usi
);
Ok(usize::from(!ok))
}
pub(super) fn check_bf16<G: ParityGpu>(gpu: &mut G) -> std::result::Result<usize, String> {
if !gpu.embed_type_supported(30) || gpu.iq_supported(30) || gpu.row_bytes(30, H) != H * 2 {
/// Relative errors against the quantized-sum and the stored-sum reference, and whether the first is the small one.
fn q5_verdict(got: &[f32], want: &[f32], original: &[f32], shift: f64) -> Fail<(f64, f64, bool)> {
let (eq, es) = (rel(got, want)?, rel(got, original)?);
Ok((eq, es, eq < 1e-3 && es > 10.0 * eq && shift > 0.0))
}
/// The stored Q8_1 blocks, the same with the sum recomputed as d*sum(q), and the largest shift of a block's sum.
fn q5_sums(raw: &[u8]) -> Fail<(Q81Owner, Q81Owner, f64)> {
if !cpu::cpu_avx2_ok() {
return Err("Q5_1 CPU unsupported".into());
}
let mut stored = Q81Owner([0; 720]);
stored.0.copy_from_slice(raw);
let mut summed = Q81Owner(stored.0);
let mut shift = 0.0f64;
for b in summed.0.chunks_exact_mut(36) {
// SAFETY: cpu_avx2_ok() (F16C) was checked at the top of this function.
let e = unsafe { requantize_block_sum(b) };
if shift < e {
shift = e;
}
}
Ok((stored, summed, shift))
}
/// Rewrites the sum `s` of one 36-byte Q8_1 block as d*sum(q) in fp16 and returns how far it moved.
///
/// # Safety
/// F16C must be available (`cpu_avx2_ok()`).
unsafe fn requantize_block_sum(b: &mut [u8]) -> f64 {
let d = u16::from_le_bytes([b[0], b[1]]);
let s = u16::from_le_bytes([b[2], b[3]]);
let sum = b[4..].iter().map(|v| *v as i8 as i32).sum::<i32>();
// SAFETY: F16C per this function's contract.
let (dd, ss) = unsafe { (crate::rust_simd::half(d), crate::rust_simd::half(s)) };
let e = (ss - dd * sum as f32).abs() as f64;
// SAFETY: F16C per this function's contract.
b[2..4].copy_from_slice(&unsafe { crate::rust_simd::to_half(dd * sum as f32) }.to_le_bytes());
e
}
/// The 64 row dots of the Q5_1 weights against the quantized-sum and the stored-sum activation.
fn q5_dots(weights: &[u8], summed: &Q81Owner, stored: &Q81Owner) -> Fail<(Vec<f32>, Vec<f32>)> {
let mut want = numerical(zeros::<f32>(64))?;
let mut original = numerical(zeros::<f32>(64))?;
let stride = numerical(Kind::Q5One.row_bytes(640))?;
// SAFETY (dot_raw): `row` is one Q5_1 row (stride = row_bytes(640)); `summed.0`/`stored.0` are 720-byte,
// 64-aligned Q81Owner = 20 Q8One blocks.
for r in 0..64 {
let row = &weights[r * stride..(r + 1) * stride];
unsafe {
want[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &summed.0);
original[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &stored.0);
}
}
Ok((want, original))
}
pub(super) fn check_bf16<G: ParityGpu>(gpu: &mut G) -> Fail<usize> {
if !bf16_supported(gpu) {
report!("bf16 embedding: type support / row bytes wrong\n");
return Ok(1);
}
let mut rng = bench::Mt19937::new(290);
let mut table = numerical(zeros::<u16>(61 * H))?;
for v in &mut table {
loop {
*v = (rng.next_u32() & 0xffff) as u16;
if !(*v & 0x7f80 == 0x7f80 && *v & 0x7f != 0) {
break;
}
}
}
let table = bf16_table(&mut rng)?;
let ids: Vec<i32> = (0..97).map(|_| (rng.next_u32() % 61) as i32).collect();
let (gathered, dequant) = gpu.bf16_embedding(&table, &ids)?;
if gathered.len() != 97 * H || dequant.len() != table.len() {
return Err("BF16 GPU products extent".into());
}
let mut rows = 0usize;
for (r, &id) in ids.iter().enumerate() {
for d in 0..H {
if gathered[r * H + d].to_bits() != (table[id as usize * H + d] as u32) << 16 {
rows += 1;
break;
}
}
}
let (gathered, dequant) = bf16_products(gpu, &table, &ids)?;
let rows = ids.iter().enumerate().filter(|(r, id)| bf16_row_differs(&gathered, &table, *r, **id as usize)).count();
let values = dequant.iter().zip(&table).filter(|(f, b)| f.to_bits() != (**b as u32) << 16).count();
report!(
"bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n",
@@ -228,3 +299,33 @@ pub(super) fn check_bf16<G: ParityGpu>(gpu: &mut G) -> std::result::Result<usize
);
Ok(usize::from(rows != 0 || values != 0))
}
fn bf16_supported<G: ParityGpu>(gpu: &G) -> bool {
gpu.embed_type_supported(30) && !gpu.iq_supported(30) && gpu.row_bytes(30, H) == H * 2
}
/// 61 rows of random bf16 values with every NaN pattern redrawn.
fn bf16_table(rng: &mut bench::Mt19937) -> Fail<Vec<u16>> {
let mut table = numerical(zeros::<u16>(61 * H))?;
for v in &mut table {
loop {
*v = (rng.next_u32() & 0xffff) as u16;
if !(*v & 0x7f80 == 0x7f80 && *v & 0x7f != 0) {
break;
}
}
}
Ok(table)
}
fn bf16_products<G: ParityGpu>(gpu: &mut G, table: &[u16], ids: &[i32]) -> Fail<(Vec<f32>, Vec<f32>)> {
let (gathered, dequant) = gpu.bf16_embedding(table, ids)?;
if gathered.len() != 97 * H || dequant.len() != table.len() {
return Err("BF16 GPU products extent".into());
}
Ok((gathered, dequant))
}
fn bf16_row_differs(gathered: &[f32], table: &[u16], r: usize, id: usize) -> bool {
(0..H).any(|d| gathered[r * H + d].to_bits() != (table[id * H + d] as u32) << 16)
}
@@ -51,7 +51,8 @@ pub(super) fn dot<const B: usize>(kind: Kind, row: &[u8], a: &NativeActivation<B
if !cpu::cpu_avx2_ok() || row.len() != kind.row_bytes(width)? || a.encoded_bytes()? > B {
return Err(Error::Shape);
}
// SAFETY: actual aligned initialized NativeActivation (check() + encoded_bytes() <= B above); no externally cast byte owner.
// SAFETY: actual aligned initialized NativeActivation (check() + encoded_bytes() <= B above); no externally
// cast byte owner.
Ok(unsafe { crate::rust_ggml::dot_raw(kind, row, width, a.raw()) })
}
pub(super) fn ggml_rows<const B: usize>(
@@ -75,6 +76,20 @@ pub(super) fn ggml_rows<const B: usize>(
}
/// Explicit IQ4_NL row kernel on the SAME 1024-byte HQ owners used by down.
pub(super) fn iq4nl_hq(weights: &[u8], acts: &[NativeActivation<1024>], out: &mut [f32]) -> Result<()> {
iq4nl_check(weights, acts, out)?;
// SAFETY (this view): check(Iq4Nl,FF) pinned n == FF == 640, so 20 Q8Zero = 680 B <= the 1024-byte, 64-aligned
// owner.
let aa: [&[crate::rust_types::Q8Zero]; NT] =
std::array::from_fn(|i| unsafe { std::slice::from_raw_parts(acts[i].raw().as_ptr().cast(), FF / 32) });
for r in 0..H {
let values = iq4nl_row(weights, &aa, r)?;
for t in 0..NT {
out[t * H + r] = values[t];
}
}
Ok(())
}
fn iq4nl_check(weights: &[u8], acts: &[NativeActivation<1024>], out: &[f32]) -> Result<()> {
if !cpu::cpu_avx2_ok() || acts.len() != NT || weights.len() != H * Kind::Iq4Nl.row_bytes(FF)? || out.len() != NT * H
{
return Err(Error::Shape);
@@ -82,26 +97,19 @@ pub(super) fn iq4nl_hq(weights: &[u8], acts: &[NativeActivation<1024>], out: &mu
for a in acts {
a.check(Kind::Iq4Nl, FF)?;
}
// SAFETY (this view): check(Iq4Nl,FF) pinned n == FF == 640, so 20 Q8Zero = 680 B <= the 1024-byte, 64-aligned owner.
let aa: [&[crate::rust_types::Q8Zero]; NT] =
std::array::from_fn(|i| unsafe { std::slice::from_raw_parts(acts[i].raw().as_ptr().cast(), FF / 32) });
// SAFETY (iq4nl): cpu_avx2_ok() checked above; each row slice is row_bytes(FF) = 360 B = 20 blocks = aa[t].len().
for r in 0..H {
let mut values = [0.0; NT];
unsafe {
crate::rust_iq::iq4nl(
&weights[r * Kind::Iq4Nl.row_bytes(FF)?..(r + 1) * Kind::Iq4Nl.row_bytes(FF)?],
&aa,
&mut values,
false,
);
}
for t in 0..NT {
out[t * H + r] = values[t];
}
}
Ok(())
}
/// The IQ4_NL dots of row `r` against the NT activations.
fn iq4nl_row(weights: &[u8], aa: &[&[crate::rust_types::Q8Zero]; NT], r: usize) -> Result<[f32; NT]> {
let stride = Kind::Iq4Nl.row_bytes(FF)?;
let mut values = [0.0; NT];
// SAFETY (iq4nl): the caller checked cpu_avx2_ok(); the row slice is row_bytes(FF) = 360 B = 20 blocks
// = aa[t].len().
unsafe {
crate::rust_iq::iq4nl(&weights[r * stride..(r + 1) * stride], aa, &mut values, false);
}
Ok(values)
}
pub(super) fn elapsed(start: Instant, iterations: usize) -> f64 {
start.elapsed().as_secs_f64() * 1e6 / iterations as f64
}
@@ -8,7 +8,8 @@ use super::*;
/// Original's absent-only setenv occurs here, before the actual stream factory.
/// `create_gpu` must create an actual stream and bind the declared owned methods.
pub unsafe fn run<G: ParityGpu>(args: &[String], create_gpu: impl FnOnce() -> std::result::Result<G, String>) -> i32 {
// SAFETY: `stdout` is glibc's FILE* global, read by value; unbuffering it before any output is the documented single-threaded entry.
// SAFETY: `stdout` is glibc's FILE* global, read by value; unbuffering it before any output is the documented
// single-threaded entry.
unsafe {
setvbuf(stdout, std::ptr::null_mut(), 2, 0);
}
@@ -16,13 +17,9 @@ pub unsafe fn run<G: ParityGpu>(args: &[String], create_gpu: impl FnOnce() -> st
eprint!("{USAGE}");
return 2;
}
// SAFETY: NUL-terminated literals; setenv races with other threads' getenv, so this relies on this fn's contract (process entry);
// rust_bench_cuda::main sets the variable first, so the branch is dead there (see its SAFETY note).
if std::env::var_os("STRATA_IQ_MT_MIN").is_none() {
if unsafe { setenv(c"STRATA_IQ_MT_MIN".as_ptr(), c"1".as_ptr(), 1) } != 0 {
eprintln!("native_expert_parity: setenv failed");
return 1;
}
// SAFETY: this fn's contract (process entry) is the contract of `default_iq_mt_min`.
if !unsafe { default_iq_mt_min() } {
return 1;
}
let mut gpu = match create_gpu() {
Ok(g) => g,
@@ -32,14 +29,36 @@ pub unsafe fn run<G: ParityGpu>(args: &[String], create_gpu: impl FnOnce() -> st
}
};
let result = run_modes(args, &mut gpu);
let close = gpu.close();
finish(result, gpu.close())
}
/// Sets STRATA_IQ_MT_MIN=1 when it is absent; false (after the message) when setenv fails.
///
/// # Safety
/// Process entry only: setenv races with other threads' getenv.
unsafe fn default_iq_mt_min() -> bool {
// SAFETY: NUL-terminated literals; the caller guarantees no other thread exists yet. rust_bench_cuda::main sets
// the variable first, so the branch is dead there (see its SAFETY note).
let absent = std::env::var_os("STRATA_IQ_MT_MIN").is_none();
if absent && unsafe { setenv(c"STRATA_IQ_MT_MIN".as_ptr(), c"1".as_ptr(), 1) } != 0 {
eprintln!("native_expert_parity: setenv failed");
return false;
}
true
}
fn finish(result: std::result::Result<usize, String>, close: std::result::Result<(), String>) -> i32 {
match (result, close) {
(Err(e), _) | (Ok(_), Err(e)) => {
eprintln!("native_expert_parity: {e}");
1
}
(Ok(failures), Ok(())) => {
report!("native_expert_parity: %d failures\n", failures as c_int);
report!(
"native_expert_parity: %d failures
",
failures as c_int
);
i32::from(failures != 0)
}
}
@@ -48,64 +67,90 @@ pub(super) fn run_modes<G: ParityGpu>(args: &[String], gpu: &mut G) -> std::resu
match args[1].as_str() {
"--q5_1-min" => check_q5_one(gpu),
"--bf16-embd" => check_bf16(gpu),
"--synthetic" => {
let mut failures = 0;
for (i, arg) in args.iter().enumerate().skip(2) {
let (gu, dn) = arg.split_once('/').map_or((-1, -1), |(g, d)| (type_of(g), type_of(d)));
let format = if gu < 0 || dn < 0 { Err(String::new()) } else { native_fmt(gu, dn) };
let f = match format {
Ok(f) if gpu::expert_supported(f.gu, f.down, H, FF) => f,
Ok(_) => {
let arg = CString::new(arg.as_str()).map_err(|_| "argument contains NUL")?;
report!("%s: not a pair the GPU expert kernels take\n", arg.as_ptr());
failures += 1;
continue;
}
Err(e) => {
let arg = CString::new(arg.as_str()).map_err(|_| "argument contains NUL")?;
let err = CString::new(if e.is_empty() {
"not a pair the GPU expert kernels take".into()
} else {
e
})
.unwrap();
report!("%s: %s\n", arg.as_ptr(), err.as_ptr());
failures += 1;
continue;
}
};
let blob = numerical(bench::synthetic_blob(&f, i as u32))?;
failures += check_blob(&f, &blob, i as u32, "synthetic", gpu)?;
}
Ok(failures)
"--synthetic" => run_synthetic(args, gpu),
path => run_layers(path, args, gpu),
}
}
fn run_synthetic<G: ParityGpu>(args: &[String], gpu: &mut G) -> std::result::Result<usize, String> {
let mut failures = 0;
for (i, arg) in args.iter().enumerate().skip(2) {
let Some(f) = synthetic_format(arg)? else {
failures += 1;
continue;
};
let blob = numerical(bench::synthetic_blob(&f, i as u32))?;
failures += check_blob(&f, &blob, i as u32, "synthetic", gpu)?;
}
Ok(failures)
}
/// The format named by a `GU/DOWN` argument; None (after the report) when it names no pair the GPU kernels take.
fn synthetic_format(arg: &str) -> std::result::Result<Option<NativeFormat>, String> {
let (gu, dn) = arg.split_once('/').map_or((-1, -1), |(g, d)| (type_of(g), type_of(d)));
let format = if gu < 0 || dn < 0 { Err(String::new()) } else { native_fmt(gu, dn) };
match format {
Ok(f) if gpu::expert_supported(f.gu, f.down, H, FF) => Ok(Some(f)),
Ok(_) => {
let arg = CString::new(arg).map_err(|_| "argument contains NUL")?;
report!(
"%s: not a pair the GPU expert kernels take
",
arg.as_ptr()
);
Ok(None)
}
path => {
let model = model::Model::open(path)?;
let layers = if args.len() == 2 {
vec![0, 1, 2, 3, 20, 47]
} else {
args[2..].iter().map(|v| crate::rust_simd::atoi(v)).collect()
};
let mut failures = 0;
for layer in layers {
let Some((g, d)) = model.kinds(layer) else {
report!("layer %d: no expert tensors\n", layer as c_int);
failures += 1;
continue;
};
let f = match native_fmt(g, d) {
Ok(f) => f,
Err(e) => {
let err = CString::new(e).unwrap();
report!("layer %d: %s\n", layer as c_int, err.as_ptr());
failures += 1;
continue;
}
};
let blob = model.expert(layer, &f)?;
failures += check_blob(&f, &blob, layer as u32, &format!("layer {layer}"), gpu)?;
}
Ok(failures)
Err(e) => {
let arg = CString::new(arg).map_err(|_| "argument contains NUL")?;
let msg = if e.is_empty() { "not a pair the GPU expert kernels take".into() } else { e };
let err = CString::new(msg).unwrap();
report!(
"%s: %s
",
arg.as_ptr(),
err.as_ptr()
);
Ok(None)
}
}
}
fn run_layers<G: ParityGpu>(path: &str, args: &[String], gpu: &mut G) -> std::result::Result<usize, String> {
let model = model::Model::open(path)?;
let layers = if args.len() == 2 {
vec![0, 1, 2, 3, 20, 47]
} else {
args[2..].iter().map(|v| crate::rust_simd::atoi(v)).collect()
};
let mut failures = 0;
for layer in layers {
let Some(f) = layer_format(&model, layer) else {
failures += 1;
continue;
};
let blob = model.expert(layer, &f)?;
failures += check_blob(&f, &blob, layer as u32, &format!("layer {layer}"), gpu)?;
}
Ok(failures)
}
/// The format of a layer's expert tensors; None (after the report) when it has none or the pair is unusable.
fn layer_format(model: &model::Model, layer: i32) -> Option<NativeFormat> {
let Some((g, d)) = model.kinds(layer) else {
report!(
"layer %d: no expert tensors
",
layer as c_int
);
return None;
};
match native_fmt(g, d) {
Ok(f) => Some(f),
Err(e) => {
let err = CString::new(e).unwrap();
report!(
"layer %d: %s
",
layer as c_int,
err.as_ptr()
);
None
}
}
}
@@ -3,6 +3,9 @@
#[allow(unused_imports)]
use super::*;
mod scale_search;
pub(super) use scale_search::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
pub(super) fn alloc<T: Default>(n: usize) -> Result<Vec<T>> {
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
@@ -12,28 +15,9 @@ pub(super) fn alloc<T: Default>(n: usize) -> Result<Vec<T>> {
impl Grid {
pub(super) fn new(codes: &[u16], dim: usize, bits: usize, want: usize) -> Result<Self> {
let size = if dim == 8 { 43692 } else { 4096 };
let mut points = alloc::<[i8; 8]>(codes.len())?;
let mut map = alloc::<i32>(size)?;
map.fill(-1);
for (i, &code) in codes.iter().enumerate() {
for j in 0..dim {
points[i][j] = (2 * ((code as usize >> (bits * j)) & ((1 << bits) - 1)) + 1) as i8;
}
map[code as usize] = i as i32;
}
let (points, mut map) = Self::index_points(codes, dim, bits, size)?;
let mut dist = alloc::<(i32, u16)>(codes.len())?;
let mut counts = alloc::<usize>(size)?;
let mut total = 0usize;
for i in 0..size {
if map[i] >= 0 {
continue;
}
Self::distances(i, dim, bits, &points, &mut dist);
dist.sort_unstable();
let n = Self::count(&dist, want);
counts[i] = n;
total = total.checked_add(n + 1).ok_or(Error::Allocation)?;
}
let (counts, total) = Self::neighbor_counts(&points, &map, (dim, bits, want), &mut dist)?;
let mut neighbors = alloc::<u16>(total)?;
let mut at = 0;
for i in 0..size {
@@ -52,6 +36,42 @@ impl Grid {
}
Ok(Self { points, map, neighbors, dim, bits })
}
/// The grid points of the codes, and the map from code to point index (-1 for codes that are not on the grid).
fn index_points(codes: &[u16], dim: usize, bits: usize, size: usize) -> Result<(Vec<[i8; 8]>, Vec<i32>)> {
let mut points = alloc::<[i8; 8]>(codes.len())?;
let mut map = alloc::<i32>(size)?;
map.fill(-1);
for (i, &code) in codes.iter().enumerate() {
for j in 0..dim {
points[i][j] = (2 * ((code as usize >> (bits * j)) & ((1 << bits) - 1)) + 1) as i8;
}
map[code as usize] = i as i32;
}
Ok((points, map))
}
/// How many nearest points each off-grid code keeps, and the length of the neighbor table;
/// `shape` is (dim, bits, want).
fn neighbor_counts(
points: &[[i8; 8]],
map: &[i32],
shape: (usize, usize, usize),
dist: &mut [(i32, u16)],
) -> Result<(Vec<usize>, usize)> {
let (dim, bits, want) = shape;
let mut counts = alloc::<usize>(map.len())?;
let mut total = 0usize;
for i in 0..map.len() {
if map[i] >= 0 {
continue;
}
Self::distances(i, dim, bits, points, dist);
dist.sort_unstable();
let n = Self::count(dist, want);
counts[i] = n;
total = total.checked_add(n + 1).ok_or(Error::Allocation)?;
}
Ok((counts, total))
}
pub(super) fn distances(i: usize, dim: usize, bits: usize, p: &[[i8; 8]], dist: &mut [(i32, u16)]) {
for (j, pg) in p.iter().enumerate() {
let mut d = 0;
@@ -178,16 +198,7 @@ pub(super) fn signs<const N: usize>(xb: &[f32], w: &[f32], parity: bool) -> ([f3
}
}
if parity && flips % 2 == 1 {
let mut least = 0;
let mut error = w[k * 8] * xb[k * 8] * xb[k * 8];
for j in 1..8 {
let at = k * 8 + j;
let e = w[at] * xb[at] * xb[at];
if e < error {
least = j;
error = e;
}
}
let least = least_error(xb, w, k * 8);
xv[k * 8 + least] = -xv[k * 8 + least];
s ^= 1 << least;
}
@@ -195,6 +206,20 @@ pub(super) fn signs<const N: usize>(xb: &[f32], w: &[f32], parity: bool) -> ([f3
}
(xv, signs)
}
/// The position (0..8) in the group at `first` with the smallest weighted square, first one winning ties.
fn least_error(xb: &[f32], w: &[f32], first: usize) -> usize {
let mut least = 0;
let mut error = w[first] * xb[first] * xb[first];
for j in 1..8 {
let at = first + j;
let e = w[at] * xb[at] * xb[at];
if e < error {
least = j;
error = e;
}
}
least
}
pub(super) fn totals(x: &[f32], w: &[f32], l: &[i8]) -> (f32, f32) {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
@@ -0,0 +1,130 @@
//! STRA-338: the block preparation and scale search shared by the IQ2_XS, IQ2_S and IQ3 quantizers.
#[allow(unused_imports)]
use super::*;
/// Sum of squares, accumulated left to right in f32.
pub(in super::super) fn sum_sq(x: &[f32]) -> f32 {
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
sum
}
/// The importance weights: imatrix * sqrt(sigma + x^2), or `plain(x)` without an imatrix.
pub(in super::super) fn weights<const N: usize>(
xb: &[f32],
qb: Option<&[f32]>,
sigma: f32,
plain: impl Fn(f32) -> f32,
) -> [f32; N] {
std::array::from_fn(|i| qb.map_or(plain(xb[i]), |q| q[i] * (sigma + xb[i] * xb[i]).sqrt()))
}
/// Largest value of a block, the first element winning ties.
pub(in super::super) fn vmax(xv: &[f32]) -> f32 {
let mut max = xv[0];
for &v in &xv[1..] {
if v > max {
max = v;
}
}
max
}
/// Flips the sign bytes of a block whose scale came out negative (`!s & mask`).
pub(in super::super) fn flip(signs: &mut [u8], mask: u8) {
for s in signs {
*s = !*s & mask;
}
}
/// A block folded to its magnitudes, with its weights, their roots, and the sign bits.
pub(in super::super) struct Block<const N: usize> {
pub(in super::super) xv: [f32; N],
pub(in super::super) w: [f32; N],
pub(in super::super) wa: [f32; N],
pub(in super::super) sign: [u8; 4],
}
impl<const N: usize> Block<N> {
pub(in super::super) fn new(xb: &[f32], w: [f32; N], parity: bool) -> Self {
let wa: [f32; N] = std::array::from_fn(|i| w[i].sqrt());
let (xv, sign) = signs::<N>(xb, &w, parity);
Block { xv, w, wa, sign }
}
}
/// The trial scales of the search: `(centre + is * step) / max` for `is` in -tries..=tries, with `levels` grid levels.
#[derive(Clone, Copy)]
pub(in super::super) struct Trial {
pub(in super::super) centre: f32,
pub(in super::super) step: f32,
pub(in super::super) tries: i32,
pub(in super::super) levels: i32,
}
/// The best levels found for a block, which of its `G` groups sat on the grid, and the scale.
pub(in super::super) struct Fit<const N: usize, const G: usize> {
pub(in super::super) l: [i8; N],
pub(in super::super) on: [bool; G],
pub(in super::super) scale: f32,
}
/// Tries the scales of `t` and keeps the levels with the best fit; `on` is the group state when none is accepted.
pub(in super::super) fn search_scale<const N: usize, const G: usize>(
g: &Grid,
b: &Block<N>,
max: f32,
t: Trial,
on: [bool; G],
) -> Fit<N, G> {
let mut fit = Fit { l: [0; N], on, scale: max / t.centre };
let mut best = 0.0;
for is in -t.tries..=t.tries {
let inv = (t.centre + is as f32 * t.step) / max;
let mut aux = [0i8; N];
let mut ao = [true; G];
quant_candidates(g, inv, &b.xv, &b.wa, 1.0 / inv, &mut aux, t.levels, &mut ao);
let (sx, s2) = totals(&b.xv, &b.w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
fit.scale = sx / s2;
best = fit.scale * sx;
fit.l = aux;
fit.on = ao;
}
}
fit
}
/// Re-quantizes the groups that were off the grid (all of them unless `skip_on`) to their nearest neighbors and
/// refits the scale.
#[allow(clippy::neg_cmp_op_on_partial_ord)]
pub(in super::super) fn fix_groups<const N: usize, const G: usize>(
g: &Grid,
b: &Block<N>,
fit: &mut Fit<N, G>,
skip_on: bool,
levels: i32,
) {
if !fit.on.iter().any(|v| !*v) || !(fit.scale > 0.0) {
return;
}
let inv = 1.0 / fit.scale;
let dim = g.dim;
for k in 0..G {
if skip_on && fit.on[k] {
continue;
}
let at = k * dim;
for j in 0..dim {
fit.l[at + j] = nearest(0.5 * (inv * b.xv[at + j] - 1.0)).clamp(0, levels - 1) as i8;
}
g.resolve(&mut fit.l[at..at + dim], &b.xv[at..at + dim], &b.wa[at..at + dim], fit.scale);
}
let (sx, s2) = totals(&b.xv, &b.w, &fit.l);
if s2 > 0.0 {
fit.scale = sx / s2;
}
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl Grid, fn iq1_s.
use super::alloc_fn::{sum_sq, weights};
#[allow(unused_imports)]
use super::*;
@@ -7,31 +8,15 @@ impl Grid {
pub(super) fn resolve_one(
&self,
l: &mut [i8],
x: &[f32],
w: &[f32],
xw: (&[f32], &[f32]),
scale: f32,
values: &[f32; 3],
v: &[f32; 3],
) -> Result<(usize, bool)> {
let mapped = self.map[self.key(l)];
if mapped >= 0 {
return Ok((mapped as usize, true));
}
let at = (-mapped - 1) as usize;
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let p = &self.points[g as usize];
let mut err = 0.0;
for i in 0..8 {
let q = values[((p[i] - 1) / 2) as usize];
let d = scale * q - x[i];
err += w[i] * d * d;
}
if err < best {
best = err;
index = g as usize;
}
}
let index = self.best_neighbor((-mapped - 1) as usize, |p| point_error(p, v, scale, xw));
// Finite inputs can still overflow this weighted error calculation. Pinned
// GGML's no-finite-best fallback indexes beyond its local point array.
// Refuse that arithmetic domain rather than reproducing an invalid access.
@@ -43,118 +28,194 @@ impl Grid {
}
Ok((index, false))
}
/// The neighbor table entry at `at`: the point with the smallest `err`, the first one winning ties
/// (usize::MAX when no error is below f32::MAX).
fn best_neighbor(&self, at: usize, err: impl Fn(&[i8; 8]) -> f32) -> usize {
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let e = err(&self.points[g as usize]);
if e < best {
best = e;
index = g as usize;
}
}
index
}
}
/// Weighted squared error of the grid point `p`, scaled by `scale` through the values `v`, against `xw` = (x, w).
fn point_error(p: &[i8; 8], v: &[f32; 3], scale: f32, xw: (&[f32], &[f32])) -> f32 {
let (x, w) = xw;
let mut err = 0.0;
for i in 0..8 {
let q = v[((p[i] - 1) / 2) as usize];
let d = scale * q - x[i];
err += w[i] * d * d;
}
err
}
/// Largest magnitude of a block.
pub(super) fn abs_max(xb: &[f32]) -> f32 {
let mut max = xb[0].abs();
for &v in &xb[1..] {
if v.abs() > max {
max = v.abs();
}
}
max
}
/// Level 0 for the first `b1` sorted values, 1 up to `b2`, 2 for the rest; indexed by original position.
pub(super) fn split_levels<const N: usize>(p: &[Pair; N], b1: usize, b2: usize) -> [i8; N] {
let mut l = [0i8; N];
for j in 0..N {
l[p[j].index as usize] = if j < b1 {
0
} else if j < b2 {
1
} else {
2
};
}
l
}
/// Mirrors the levels for a negative scale.
pub(super) fn flip_levels(l: &mut [i8]) {
for q in l {
*q = 2 - *q;
}
}
/// What the IQ1_S search settled on for one block of 32.
struct Iq1Fit {
scale: f32,
shift: i8,
indices: [usize; 4],
}
pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
y.fill(0);
let mut scales = [0.0; 8];
let mut shifts = [1i8; 8];
let mut heads = [0u16; 8];
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let xb = &x[at..at + 32];
let w: [f32; 32] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt());
let mut max = xb[0].abs();
for &v in &xb[1..] {
if v.abs() > max {
max = v.abs();
}
}
if max < 1e-12 {
continue;
}
let p = pairs::<32>(xb);
let mut sx = [0.0; 33];
let mut sw = sx;
for j in 0..32 {
let i = p[j].index as usize;
sx[j + 1] = sx[j] + w[i] * xb[i];
sw[j + 1] = sw[j] + w[i];
}
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut shift) = (-1i32, -1i32, 0i8);
for i1 in 0..=32 {
for i2 in i1..=32 {
for (values, s) in [(&XP, 1i8), (&XM, -1i8)] {
let qx =
(sx[i1] - sx[0]) * values[0] + (sx[i2] - sx[i1]) * values[1] + (sx[32] - sx[i2]) * values[2];
let q2 = (sw[i1] - sw[0]) * values[0] * values[0]
+ (sw[i2] - sw[i1]) * values[1] * values[1]
+ (sw[32] - sw[i2]) * values[2] * values[2];
if q2 > 0.0 && qx * qx > best * q2 {
scale = qx / q2;
best = scale * qx;
b1 = i1 as i32;
b2 = i2 as i32;
shift = s;
}
}
}
}
if b1 < 0 || b2 < 0 || shift == 0 {
continue;
}
let mut l = [0i8; 32];
for j in 0..32 {
l[p[j].index as usize] = if j < (b1 as usize) {
0
} else if j < (b2 as usize) {
1
} else {
2
};
}
if scale < 0.0 {
for q in &mut l {
*q = 2 - *q;
}
scale = -scale;
shift = -shift;
}
let values = if shift == 1 { &XP } else { &XM };
let mut indices = [0usize; 4];
let mut all = true;
for k in 0..4 {
let at = k * 8;
let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?;
indices[k] = index;
all &= on;
}
if !all {
let (mut qx, mut q2) = (0.0, 0.0);
for k in 0..4 {
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
}
if qx > 0.0 && q2 > 0.0 {
scale = qx / q2;
}
}
let w: [f32; 32] = weights(xb, Some(&qw[at..at + 32]), sigma, |v| v * v);
let Some(fit) = iq1_s_block(g, xb, &w)? else { continue };
let mut high = 0u16;
for k in 0..4 {
y[2 + ib * 4 + k] = indices[k] as u8;
high |= ((indices[k] >> 8) as u16) << (3 * k);
y[2 + ib * 4 + k] = fit.indices[k] as u8;
high |= ((fit.indices[k] >> 8) as u16) << (3 * k);
}
heads[ib] = high;
scales[ib] = scale;
shifts[ib] = shift;
if scale > maxs {
maxs = scale;
scales[ib] = fit.scale;
shifts[ib] = fit.shift;
if fit.scale > maxs {
maxs = fit.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
iq1_s_scales(y, maxs, &scales, &shifts, &mut heads);
Ok(())
}
/// The fit of one block of 32; None for a block the search leaves empty.
fn iq1_s_block(g: &Grid, xb: &[f32], w: &[f32; 32]) -> Result<Option<Iq1Fit>> {
let max = abs_max(xb);
if max < 1e-12 {
return Ok(None);
}
let p = pairs::<32>(xb);
let Some((mut scale, mut shift, b1, b2)) = iq1_s_search(&iq1_prefix(&p, xb, w), max) else { return Ok(None) };
let mut l = split_levels(&p, b1, b2);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
shift = -shift;
}
let values = if shift == 1 { &XP } else { &XM };
let (indices, all) = iq1_s_resolve(g, &mut l, (xb, w), scale, values)?;
if !all {
scale = iq1_s_refit(g, &indices, (xb, w), values, scale);
}
Ok(Some(Iq1Fit { scale, shift, indices }))
}
/// Prefix sums of w*x and w over the values in sorted order (index 0 is the empty prefix).
fn iq1_prefix(p: &[Pair; 32], xb: &[f32], w: &[f32; 32]) -> ([f32; 33], [f32; 33]) {
let mut sx = [0.0; 33];
let mut sw = sx;
for j in 0..32 {
let i = p[j].index as usize;
sx[j + 1] = sx[j] + w[i] * xb[i];
sw[j + 1] = sw[j] + w[i];
}
(sx, sw)
}
/// The split points and sign with the best fit as (scale, shift, b1, b2); None when no split fits.
fn iq1_s_search(prefix: &([f32; 33], [f32; 33]), max: f32) -> Option<(f32, i8, usize, usize)> {
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut shift) = (-1i32, -1i32, 0i8);
for i1 in 0..=32 {
for i2 in i1..=32 {
for (values, s) in [(&XP, 1i8), (&XM, -1i8)] {
let (qx, q2) = iq1_s_sums(prefix, (i1, i2), values);
if q2 > 0.0 && qx * qx > best * q2 {
scale = qx / q2;
best = scale * qx;
b1 = i1 as i32;
b2 = i2 as i32;
shift = s;
}
}
}
}
if b1 < 0 || b2 < 0 || shift == 0 { None } else { Some((scale, shift, b1 as usize, b2 as usize)) }
}
fn iq1_s_sums(prefix: &([f32; 33], [f32; 33]), split: (usize, usize), values: &[f32; 3]) -> (f32, f32) {
let (sx, sw) = prefix;
let (i1, i2) = split;
let qx = (sx[i1] - sx[0]) * values[0] + (sx[i2] - sx[i1]) * values[1] + (sx[32] - sx[i2]) * values[2];
let q2 = (sw[i1] - sw[0]) * values[0] * values[0]
+ (sw[i2] - sw[i1]) * values[1] * values[1]
+ (sw[32] - sw[i2]) * values[2] * values[2];
(qx, q2)
}
/// Grid indices of the four groups of 8 and whether all of them sat on the grid; `xw` is (x, w).
fn iq1_s_resolve(
g: &Grid,
l: &mut [i8; 32],
xw: (&[f32], &[f32; 32]),
scale: f32,
values: &[f32; 3],
) -> Result<([usize; 4], bool)> {
let mut indices = [0usize; 4];
let mut all = true;
for k in 0..4 {
let at = k * 8;
let (index, on) = g.resolve_one(&mut l[at..at + 8], (&xw.0[at..at + 8], &xw.1[at..at + 8]), scale, values)?;
indices[k] = index;
all &= on;
}
Ok((indices, all))
}
/// The scale refit against the chosen grid points; unchanged unless both sums are positive. `xw` is (x, w).
fn iq1_s_refit(g: &Grid, indices: &[usize; 4], xw: (&[f32], &[f32; 32]), values: &[f32; 3], scale: f32) -> f32 {
let (xb, w) = xw;
let (mut qx, mut q2) = (0.0, 0.0);
for k in 0..4 {
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
}
if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale }
}
/// The block-scale levels and shift flags (with the 3-bit group heads) and the super-block scale.
fn iq1_s_scales(y: &mut [u8], maxs: f32, scales: &[f32; 8], shifts: &[i8; 8], heads: &mut [u16; 8]) {
let d = maxs / 15.0;
put_h(y, d * 1.125);
let inv = 1.0 / d;
@@ -166,5 +227,4 @@ pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()>
heads[ib] |= l << 12;
y[34 + ib * 2..36 + ib * 2].copy_from_slice(&heads[ib].to_le_bytes());
}
Ok(())
}
@@ -1,126 +1,151 @@
//! Moved out of the parent module by STRA-338: fn iq1_m, fn row.
use super::alloc_fn::{sum_sq, weights};
use super::impl_grid::{abs_max, flip_levels, split_levels};
#[allow(unused_imports)]
use super::*;
/// What the IQ1_M search settled on for one block of 16.
struct Iq1MFit {
scale: f32,
which: usize,
indices: [usize; 2],
}
pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
y.fill(0);
let mut scales = [0.0; 16];
let mut shifts = [0usize; 16];
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] =
std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt()));
let mut max = xb[0].abs();
for &v in &xb[1..] {
if v.abs() > max {
max = v.abs();
}
}
if max < 1e-7 {
continue;
}
let p = pairs::<16>(xb);
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut which) = (-1i32, -1i32, -1i32);
for i1 in 0..=16 {
for i2 in i1..=16 {
let mut qx = [0.0; 4];
let mut q2 = qx;
for j in 0..16 {
let i = p[j].index as usize;
let value = if j < i1 {
0
} else if j < i2 {
1
} else {
2
};
for k in 0..4 {
let vals = if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM };
qx[k] += w[i] * vals[value] * xb[i];
q2[k] += w[i] * vals[value] * vals[value];
}
}
for k in 0..4 {
if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] {
scale = qx[k] / q2[k];
best = scale * qx[k];
b1 = i1 as i32;
b2 = i2 as i32;
which = k as i32;
}
}
}
}
if b1 < 0 || b2 < 0 || which < 0 {
continue;
}
let mut l = [0i8; 16];
for j in 0..16 {
l[p[j].index as usize] = if j < (b1 as usize) {
0
} else if j < (b2 as usize) {
1
} else {
2
};
}
if scale < 0.0 {
for q in &mut l {
*q = 2 - *q;
}
scale = -scale;
which = 3 - which;
}
let mut indices = [0usize; 2];
let mut all = true;
for k in 0..2 {
let values = if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM };
let at = k * 8;
let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?;
indices[k] = index;
all &= on;
}
if !all {
let (mut qx, mut q2) = (0.0, 0.0);
for k in 0..2 {
let values = if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM };
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
}
if qx > 0.0 && q2 > 0.0 {
scale = qx / q2;
}
}
y[2 * ib] = indices[0] as u8;
y[2 * ib + 1] = indices[1] as u8;
y[32 + ib] = (indices[0] >> 8) as u8 | (((indices[1] >> 8) as u8) << 4);
scales[ib] = scale;
shifts[ib] = which as usize;
if scale > maxs {
maxs = scale;
let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v);
let Some(fit) = iq1_m_block(g, xb, &w)? else { continue };
y[2 * ib] = fit.indices[0] as u8;
y[2 * ib + 1] = fit.indices[1] as u8;
y[32 + ib] = (fit.indices[0] >> 8) as u8 | (((fit.indices[1] >> 8) as u8) << 4);
scales[ib] = fit.scale;
shifts[ib] = fit.which;
if fit.scale > maxs {
maxs = fit.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
iq1_m_scales(g, (x, y), (qw, sigma), (&scales, &shifts), maxs);
Ok(())
}
/// The values (+ or - shifted grid) of half `k` of a block of 16 for the shift pattern `which`.
fn half_values(k: usize, which: usize) -> &'static [f32; 3] {
if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM }
}
/// The fit of one block of 16; None for a block the search leaves empty.
fn iq1_m_block(g: &Grid, xb: &[f32], w: &[f32; 16]) -> Result<Option<Iq1MFit>> {
let max = abs_max(xb);
if max < 1e-7 {
return Ok(None);
}
let p = pairs::<16>(xb);
let Some((mut scale, mut which, b1, b2)) = iq1_m_search(&p, (xb, w), max) else { return Ok(None) };
let mut l = split_levels(&p, b1, b2);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
which = 3 - which;
}
let mut indices = [0usize; 2];
let mut all = true;
for k in 0..2 {
let at = k * 8;
let xw = (&xb[at..at + 8], &w[at..at + 8]);
let (index, on) = g.resolve_one(&mut l[at..at + 8], xw, scale, half_values(k, which))?;
indices[k] = index;
all &= on;
}
if !all {
scale = iq1_m_refit(g, &indices, (xb, w), (which, scale));
}
Ok(Some(Iq1MFit { scale, which, indices }))
}
/// The split points and shift pattern with the best fit as (scale, which, b1, b2); None when no split fits.
fn iq1_m_search(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), max: f32) -> Option<(f32, usize, usize, usize)> {
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut which) = (-1i32, -1i32, -1i32);
for i1 in 0..=16 {
for i2 in i1..=16 {
let (qx, q2) = iq1_m_sums(p, xw, (i1, i2));
for k in 0..4 {
if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] {
scale = qx[k] / q2[k];
best = scale * qx[k];
b1 = i1 as i32;
b2 = i2 as i32;
which = k as i32;
}
}
}
}
if b1 < 0 || b2 < 0 || which < 0 { None } else { Some((scale, which as usize, b1 as usize, b2 as usize)) }
}
/// The weighted sums (sum w*q*x, sum w*q*q) of the four shift patterns for the split `(i1, i2)`.
fn iq1_m_sums(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), split: (usize, usize)) -> ([f32; 4], [f32; 4]) {
let (xb, w) = xw;
let (i1, i2) = split;
let mut qx = [0.0; 4];
let mut q2 = qx;
for j in 0..16 {
let i = p[j].index as usize;
let value = if j < i1 {
0
} else if j < i2 {
1
} else {
2
};
for k in 0..4 {
let vals = if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM };
qx[k] += w[i] * vals[value] * xb[i];
q2[k] += w[i] * vals[value] * vals[value];
}
}
(qx, q2)
}
/// The scale refit against the chosen grid points; unchanged unless both sums are positive.
/// `shape` is (which, scale).
fn iq1_m_refit(g: &Grid, indices: &[usize; 2], xw: (&[f32], &[f32; 16]), shape: (usize, f32)) -> f32 {
let (xb, w) = xw;
let (which, scale) = shape;
let (mut qx, mut q2) = (0.0, 0.0);
for k in 0..2 {
let values = half_values(k, which);
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
}
if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale }
}
/// Block-scale levels and shift flags into y, and the super-block scale refit against the stored indices.
/// `xy` is (x, y), `im` is (imatrix, sigma) and `blocks` is (scales, shifts).
fn iq1_m_scales(
g: &Grid,
xy: (&[f32], &mut [u8]),
im: (Option<&[f32]>, f32),
blocks: (&[f32; 16], &[usize; 16]),
maxs: f32,
) {
let (x, y) = xy;
let (qw, sigma) = im;
let (scales, shifts) = blocks;
let mut d = maxs / 15.0;
let inv = 1.0 / d;
let mut sc = [0u16; 4];
let (mut qx, mut q2) = (0.0, 0.0);
let mut acc = (0.0, 0.0);
let masks = [0u8, 128, 8, 136];
for ib in 0..16 {
let l = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 7);
@@ -128,22 +153,16 @@ pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Re
y[32 + ib] |= masks[shifts[ib]];
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] =
std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt()));
for k in 0..2 {
let values = if (k == 0 && shifts[ib] < 2) || (k == 1 && shifts[ib] % 2 == 0) { &XP } else { &XM };
let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700);
let p = &g.points[index];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize] * (2 * l + 1) as f32;
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
}
let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v);
iq1_m_accumulate(g, y, (ib, shifts[ib], l), (xb, &w), &mut acc);
}
if q2 > 0.0 {
d = qx / q2;
if acc.1 > 0.0 {
d = acc.0 / acc.1;
}
iq1_m_store_scales(y, sc, d);
}
/// Spreads the half-precision super-block scale over the top nibbles of the four scale words and stores them.
fn iq1_m_store_scales(y: &mut [u8], mut sc: [u16; 4], d: f32) {
let packed = half_rn(d * 1.1125);
sc[0] |= (packed & 15) << 12;
sc[1] |= (packed & 0xf0) << 8;
@@ -152,21 +171,41 @@ pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Re
for (i, v) in sc.into_iter().enumerate() {
y[48 + i * 2..50 + i * 2].copy_from_slice(&v.to_le_bytes());
}
Ok(())
}
/// Adds block `ib`'s (sum w*q*x, sum w*q*q) at the stored grid indices and block scale level to `acc`;
/// `block` is (ib, shift pattern, scale level).
fn iq1_m_accumulate(g: &Grid, y: &[u8], block: (usize, usize, i32), xw: (&[f32], &[f32; 16]), acc: &mut (f32, f32)) {
let (ib, shift, l) = block;
let (xb, w) = xw;
for k in 0..2 {
let values = half_values(k, shift);
let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700);
let p = &g.points[index];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize] * (2 * l + 1) as f32;
acc.0 += w[k * 8 + j] * q * xb[k * 8 + j];
acc.1 += w[k * 8 + j] * q * q;
}
}
}
pub(in super::super) fn row(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let g = grid(kind)?;
for (i, (x, y)) in x.chunks_exact(256).zip(y.chunks_exact_mut(kind.block().1)).enumerate() {
let w = qw.map(|q| &q[i * 256..i * 256 + 256]);
match kind {
Kind::Iq2Xxs => iq2_xxs(&g, x, y, w.ok_or(Error::Shape)?)?,
Kind::Iq2Xs => iq2_xs(&g, x, y, w.ok_or(Error::Shape)?)?,
Kind::Iq2S => iq2_s(&g, x, y, w)?,
Kind::Iq3Xxs | Kind::Iq3S => iq3(&g, kind, x, y, w)?,
Kind::Iq1S => iq1_s(&g, x, y, w.ok_or(Error::Shape)?)?,
Kind::Iq1M => iq1_m(&g, x, y, w)?,
_ => return Err(Error::Unsupported),
}
row_block(kind, &g, (x, y), w)?;
}
Ok(())
}
/// Quantizes one 256-value block with the quantizer of `kind`.
fn row_block(kind: Kind, g: &Grid, xy: (&[f32], &mut [u8]), w: Option<&[f32]>) -> Result<()> {
let (x, y) = xy;
match kind {
Kind::Iq2Xxs => iq2_xxs(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq2Xs => iq2_xs(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq2S => iq2_s(g, x, y, w),
Kind::Iq3Xxs | Kind::Iq3S => iq3(g, kind, x, y, w),
Kind::Iq1S => iq1_s(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq1M => iq1_m(g, x, y, w),
_ => Err(Error::Unsupported),
}
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn iq2_xxs, fn iq2_xs.
use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
#[allow(unused_imports)]
use super::*;
@@ -8,62 +9,11 @@ pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<(
let mut q2 = [0u32; 16];
y.fill(0);
put_h(y, 0.0);
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = sum / 256.0;
let sigma = sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let xb = &x[at..at + 32];
let w: [f32; 32] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt());
let wa: [f32; 32] = std::array::from_fn(|i| w[i].sqrt());
let (xv, mut sign) = signs::<32>(xb, &w, true);
let mut max = xv[0];
for &v in &xv[1..] {
if v > max {
max = v;
}
}
if max < 1e-15 {
continue;
}
let mut l = [0i8; 32];
let mut lp = [0u8; 32];
let mut scale = qp(&xv, 4, &mut lp, &w);
for i in 0..32 {
l[i] = lp[i] as i8;
}
let effective = scale * 3.0;
if effective <= 0.0 {
continue;
}
let mut best = 0.0;
for is in -6..=6 {
let inv = (5.0 + is as f32 * 0.1) / effective;
let mut aux = [0i8; 32];
quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]);
let (sx, s2) = totals(&xv, &w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
}
}
if scale > 0.0 {
quant_candidates(g, 1.0 / scale, &xv, &wa, scale, &mut l, 3, &mut [false; 4]);
let (sx, s2) = totals(&xv, &w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
if scale < 0.0 {
scale = -scale;
for s in &mut sign {
*s = !*s & 127;
}
}
let Some((scale, l, sign)) = iq2_xxs_block(g, &x[at..at + 32], &qw[at..at + 32], sigma) else { continue };
for k in 0..4 {
let i = g.index(&l[k * 8..k * 8 + 8])?;
q2[2 * ib] |= (i as u32) << (8 * k);
@@ -74,85 +24,77 @@ pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<(
maxs = scale;
}
}
if maxs == 0.0 {
return Ok(());
if maxs != 0.0 {
iq2_xxs_finish(y, &mut q2, &scales, maxs);
}
Ok(())
}
/// Writes the super-block scale, merges the block scale levels into the packed words and stores them.
fn iq2_xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d);
let inv = 1.0 / d;
for ib in 0..8 {
q2[2 * ib + 1] |= (nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u32) << 28;
}
for (i, v) in q2.into_iter().enumerate() {
for (i, v) in q2.iter().enumerate() {
y[2 + i * 4..6 + i * 4].copy_from_slice(&v.to_le_bytes());
}
Ok(())
}
/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty.
fn iq2_xxs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> {
let b = Block::<32>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true);
if vmax(&b.xv) < 1e-15 {
return None;
}
let mut lp = [0u8; 32];
let scale = qp(&b.xv, 4, &mut lp, &b.w);
let effective = scale * 3.0;
if effective <= 0.0 {
return None;
}
let (mut scale, l) = iq2_xxs_search(g, &b, (scale, lp.map(|v| v as i8)), effective);
let mut sign = b.sign;
if scale < 0.0 {
scale = -scale;
flip(&mut sign, 127);
}
Some((scale, l, sign))
}
/// Tries the 13 scales around `effective`, keeps the best levels, then re-quantizes them at the final scale;
/// `start` is the initial (scale, levels).
fn iq2_xxs_search(g: &Grid, b: &Block<32>, start: (f32, [i8; 32]), effective: f32) -> (f32, [i8; 32]) {
let (mut scale, mut l) = start;
let mut best = 0.0;
for is in -6..=6 {
let inv = (5.0 + is as f32 * 0.1) / effective;
let mut aux = [0i8; 32];
quant_candidates(g, inv, &b.xv, &b.wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]);
let (sx, s2) = totals(&b.xv, &b.w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
}
}
if scale > 0.0 {
quant_candidates(g, 1.0 / scale, &b.xv, &b.wa, scale, &mut l, 3, &mut [false; 4]);
let (sx, s2) = totals(&b.xv, &b.w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
(scale, l)
}
pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
let mut scales = [0.0; 16];
let mut q2 = [0u16; 32];
y.fill(0);
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = sum / 256.0;
let sigma = sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt());
let wa: [f32; 16] = std::array::from_fn(|i| w[i].sqrt());
let (xv, mut sign) = signs::<16>(xb, &w, true);
let mut max = xv[0];
for &v in &xv[1..] {
if v > max {
max = v;
}
}
if max < 1e-15 {
continue;
}
let mut l = [0i8; 16];
let mut on = [true; 2];
let mut scale = max / 5.0;
let mut best = 0.0;
for is in -9..=9 {
let inv = (5.0 + is as f32 * 0.1) / max;
let mut aux = [0i8; 16];
let mut ao = [true; 2];
quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut ao);
let (sx, s2) = totals(&xv, &w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
on = ao;
}
}
if on.iter().any(|v| !*v) && scale > 0.0 {
let inv = 1.0 / scale;
for k in 0..2 {
if on[k] {
continue;
}
let at = k * 8;
for j in 0..8 {
l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 2) as i8;
}
g.resolve(&mut l[at..at + 8], &xv[at..at + 8], &wa[at..at + 8], scale);
}
let (sx, s2) = totals(&xv, &w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
if scale < 0.0 {
scale = -scale;
for s in &mut sign[..2] {
*s = !*s & 127;
}
}
let Some((scale, l, sign)) = iq2_xs_block(g, &x[at..at + 16], &qw[at..at + 16], sigma) else { continue };
for k in 0..2 {
q2[2 * ib + k] = g.index(&l[k * 8..k * 8 + 8])? as u16 | ((sign[k] as u16) << 9);
}
@@ -161,9 +103,13 @@ pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()
maxs = scale;
}
}
if maxs == 0.0 {
return Ok(());
if maxs != 0.0 {
iq2_xs_finish(y, &q2, &scales, maxs);
}
Ok(())
}
/// Writes the super-block scale, the block scale levels and the packed words.
fn iq2_xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d);
let inv = 1.0 / d;
@@ -171,8 +117,24 @@ pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()
let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8;
y[66 + ib / 2] |= s << (4 * (ib % 2));
}
for (i, v) in q2.into_iter().enumerate() {
for (i, v) in q2.iter().enumerate() {
y[2 + i * 2..4 + i * 2].copy_from_slice(&v.to_le_bytes());
}
Ok(())
}
/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty.
fn iq2_xs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> {
let b = Block::<16>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true);
let max = vmax(&b.xv);
if max < 1e-15 {
return None;
}
let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 };
let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]);
fix_groups(g, &b, &mut fit, true, 3);
let mut sign = b.sign;
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign[..2], 127);
}
Some((fit.scale, fit.l, sign))
}
@@ -1,90 +1,67 @@
//! Moved out of the parent module by STRA-338: fn iq3, fn iq2_s, fn compare_pair, fn pairs.
use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
#[allow(unused_imports)]
use super::*;
pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let full = kind == Kind::Iq3S;
let mut scales = [0.0; 8];
let mut flags = [0u32; 8];
let mut q3 = [0u8; 104];
y.fill(0);
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let xb = &x[at..at + 32];
let w: [f32; 32] =
std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt()));
let wa: [f32; 32] = std::array::from_fn(|i| w[i].sqrt());
let (xv, mut sign) = signs::<32>(xb, &w, !full);
let mut max = xv[0];
for &v in &xv[1..] {
if v > max {
max = v;
}
}
if (full && max == 0.0) || (!full && max < 1e-8) {
continue;
}
let mut l = [0i8; 32];
let mut on = [!full; 8];
let mut scale = max / 15.0;
let mut best = 0.0;
let tries = if full { 9 } else { 15 };
for is in -tries..=tries {
let inv = (15.0 + is as f32 * 0.2) / max;
let mut aux = [0i8; 32];
let mut ao = [true; 8];
quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 8, &mut ao);
let (sx, s2) = totals(&xv, &w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
on = ao;
}
}
if on.iter().any(|v| !*v) && scale > 0.0 {
let inv = 1.0 / scale;
for k in 0..8 {
if !full && on[k] {
continue;
}
let at = k * 4;
for j in 0..4 {
l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 7) as i8;
}
g.resolve(&mut l[at..at + 4], &xv[at..at + 4], &wa[at..at + 4], scale);
}
let (sx, s2) = totals(&xv, &w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
if scale < 0.0 {
scale = -scale;
for s in &mut sign {
*s = if full { !*s } else { !*s & 127 };
}
}
/// The packed output of the IQ3 quantizers while the blocks are being fitted.
struct Iq3Out {
scales: [f32; 8],
flags: [u32; 8],
q3: [u8; 104],
}
impl Iq3Out {
/// Stores the grid indices and signs of block `ib`; `fit` is (levels, sign bytes).
fn store(&mut self, g: &Grid, full: bool, y: &mut [u8], ib: usize, fit: (&[i8; 32], &[u8; 4])) -> Result<()> {
let (l, sign) = fit;
for k in 0..8 {
let index = g.index(&l[k * 4..k * 4 + 4])?;
q3[ib * 8 + k] = index as u8;
self.q3[ib * 8 + k] = index as u8;
if full {
y[66 + ib] |= ((index >> 8) as u8) << k;
}
}
if full {
y[74 + ib * 4..78 + ib * 4].copy_from_slice(&sign);
y[74 + ib * 4..78 + ib * 4].copy_from_slice(sign);
} else {
flags[ib] = sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21);
self.flags[ib] =
sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21);
}
scales[ib] = scale;
Ok(())
}
/// Writes the super-block scale, the block scale levels and the packed indices and flags.
fn finish(&mut self, full: bool, y: &mut [u8], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d * if full { 1.033 } else { 1.0125 });
let inv = 1.0 / d;
for ib in 0..8 {
let s = nearest(0.5 * (inv * self.scales[ib] - 1.0)).clamp(0, 15) as u8;
if full {
y[106 + ib / 2] |= s << (4 * (ib % 2));
} else {
self.flags[ib] |= (s as u32) << 28;
}
}
y[2..66].copy_from_slice(&self.q3[..64]);
if !full {
for (i, v) in self.flags.into_iter().enumerate() {
y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes());
}
}
}
}
pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let full = kind == Kind::Iq3S;
let mut out = Iq3Out { scales: [0.0; 8], flags: [0u32; 8], q3: [0u8; 104] };
y.fill(0);
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let qb = qw.map(|q| &q[at..at + 32]);
let Some((scale, l, sign)) = iq3_block(g, full, (&x[at..at + 32], qb), sigma) else { continue };
out.store(g, full, y, ib, (&l, &sign))?;
out.scales[ib] = scale;
if scale > maxs {
maxs = scale;
}
@@ -92,91 +69,36 @@ pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f3
if maxs == 0.0 {
return Ok(());
}
let d = maxs / 31.0;
put_h(y, d * if full { 1.033 } else { 1.0125 });
let inv = 1.0 / d;
for ib in 0..8 {
let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8;
if full {
y[106 + ib / 2] |= s << (4 * (ib % 2));
} else {
flags[ib] |= (s as u32) << 28;
}
}
y[2..66].copy_from_slice(&q3[..64]);
if !full {
for (i, v) in flags.into_iter().enumerate() {
y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes());
}
}
out.finish(full, y, maxs);
Ok(())
}
/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty. `xq` is (x, imatrix).
fn iq3_block(g: &Grid, full: bool, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> {
let (xb, qb) = xq;
let b = Block::<32>::new(xb, weights(xb, qb, sigma, |v| v * v), !full);
let max = vmax(&b.xv);
if (full && max == 0.0) || (!full && max < 1e-8) {
return None;
}
let trial = Trial { centre: 15.0, step: 0.2, tries: if full { 9 } else { 15 }, levels: 8 };
let mut fit = search_scale::<32, 8>(g, &b, max, trial, [!full; 8]);
fix_groups(g, &b, &mut fit, !full, 8);
let mut sign = b.sign;
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign, if full { 255 } else { 127 });
}
Some((fit.scale, fit.l, sign))
}
pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let mut scales = [0.0; 16];
y.fill(0);
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] = std::array::from_fn(|i| {
qw.map_or(0.25 * sigma + xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt())
});
let wa: [f32; 16] = std::array::from_fn(|i| w[i].sqrt());
let (xv, mut sign) = signs::<16>(xb, &w, false);
let mut max = xv[0];
for &v in &xv[1..] {
if v > max {
max = v;
}
}
if max < 1e-8 {
continue;
}
let mut l = [0i8; 16];
let mut on = [true; 2];
let mut scale = max / 5.0;
let mut best = 0.0;
for is in -9..=9 {
let inv = (5.0 + is as f32 * 0.1) / max;
let mut aux = [0i8; 16];
let mut ao = [true; 2];
quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut ao);
let (sx, s2) = totals(&xv, &w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
on = ao;
}
}
if on.iter().any(|v| !*v) && scale > 0.0 {
let inv = 1.0 / scale;
for k in 0..2 {
if on[k] {
continue;
}
let at = k * 8;
for j in 0..8 {
l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 2) as i8;
}
g.resolve(&mut l[at..at + 8], &xv[at..at + 8], &wa[at..at + 8], scale);
}
let (sx, s2) = totals(&xv, &w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
if scale < 0.0 {
scale = -scale;
for s in &mut sign[..2] {
*s = !*s;
}
}
let qb = qw.map(|q| &q[at..at + 16]);
let Some((scale, l, sign)) = iq2_s_block(g, (&x[at..at + 16], qb), sigma) else { continue };
for k in 0..2 {
let index = g.index(&l[k * 8..k * 8 + 8])?;
let i8 = 2 * ib + k;
@@ -189,9 +111,13 @@ pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Re
maxs = scale;
}
}
if maxs == 0.0 {
return Ok(());
if maxs != 0.0 {
iq2_s_finish(y, &scales, maxs);
}
Ok(())
}
/// Writes the super-block scale and the block scale levels.
fn iq2_s_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d * 0.9875);
let inv = 1.0 / d;
@@ -199,7 +125,24 @@ pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Re
let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8;
y[74 + ib / 2] |= s << (4 * (ib % 2));
}
Ok(())
}
/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty. `xq` is (x, imatrix).
fn iq2_s_block(g: &Grid, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> {
let (xb, qb) = xq;
let b = Block::<16>::new(xb, weights(xb, qb, sigma, |v| 0.25 * sigma + v * v), false);
let max = vmax(&b.xv);
if max < 1e-8 {
return None;
}
let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 };
let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]);
fix_groups(g, &b, &mut fit, true, 3);
let mut sign = b.sign;
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign[..2], 255);
}
Some((fit.scale, fit.l, sign))
}
pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *const std::ffi::c_void) -> i32 {
unsafe {
@@ -215,7 +158,9 @@ pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *con
}
}
pub(super) fn pairs<const N: usize>(x: &[f32]) -> [Pair; N] {
let mut p = std::array::from_fn(|j| Pair { value: x[j], index: j as i32 }); /* SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them; qsort retains nothing. NaN keys make the comparator inconsistent and can only mis-order the (<= 256 B) array. */
let mut p = std::array::from_fn(|j| Pair { value: x[j], index: j as i32 });
// SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them; qsort retains
// nothing. NaN keys make the comparator inconsistent and can only mis-order the (<= 256 B) array.
unsafe {
qsort(p.as_mut_ptr().cast(), N, std::mem::size_of::<Pair>(), compare_pair);
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn best_fp4, fn fp4, fn ternary, fn pack_k2, fn q2k, fn pack_scale3 ....
use super::nearest_fn::{Qkx, Search, sum_sq};
#[allow(unused_imports)]
use super::*;
@@ -42,28 +43,34 @@ pub(super) fn ternary(kind: Kind, x: &[f32], y: &mut [u8]) {
let inv = if a != 0.0 { 1.0 / a } else { 0.0 };
if kind == Kind::Tq2 {
put_h(y, 64, a);
for p in 0..2 {
for j in 0..32 {
let mut q = 0;
for k in 0..4 {
q |= ((((x[p * 128 + k * 32 + j] * inv).round() as i32 + 1) & 3) as u8) << (2 * k);
}
y[p * 32 + j] = q;
}
}
tq2_levels(x, y, inv);
} else {
put_h(y, 52, a);
for (start, step, out, n) in [(0, 32, 0, 32), (160, 16, 32, 16), (240, 4, 48, 4)] {
for j in 0..n {
let mut q = 0u16;
for k in 0..if start == 240 { 4 } else { 5 } {
q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16;
}
if start == 240 {
q *= 3;
}
y[out + j] = ((q * 256 + 242) / 243) as u8;
tq1_levels(x, y, inv);
}
}
fn tq2_levels(x: &[f32], y: &mut [u8], inv: f32) {
for p in 0..2 {
for j in 0..32 {
let mut q = 0;
for k in 0..4 {
q |= ((((x[p * 128 + k * 32 + j] * inv).round() as i32 + 1) & 3) as u8) << (2 * k);
}
y[p * 32 + j] = q;
}
}
}
fn tq1_levels(x: &[f32], y: &mut [u8], inv: f32) {
for (start, step, out, n) in [(0, 32, 0, 32), (160, 16, 32, 16), (240, 4, 48, 4)] {
for j in 0..n {
let mut q = 0u16;
for k in 0..if start == 240 { 4 } else { 5 } {
q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16;
}
if start == 240 {
q *= 3;
}
y[out + j] = ((q * 256 + 242) / 243) as u8;
}
}
}
@@ -77,55 +84,56 @@ pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) {
}
pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0u8; 256];
let mut scales = [0.0; 16];
let mut mins = scales;
let mut sw = scales;
let mut maxs = 0.0;
let mut maxm = 0.0;
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = sum / 256.0;
let search = q2k_search(x, &mut l, qw);
let (ls, lm, d, m) = q2k_scales(&search, qw.is_some());
put_h(y, 80, d);
put_h(y, 82, m);
let (d, m) = (h(y, 80), h(y, 82));
q2k_requantize(x, y, [&ls, &lm], (d, m), &mut l);
pack_k2(&l, &mut y[16..80]);
}
/// Best (scale, minimum) of each 16-value block, with the levels of that fit in `l`.
fn q2k_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<16> {
let sigma = sum_sq(x) / 256.0;
let mut s = Search::<16>::new();
let plain = Qkx { rmin: -0.5, rdelta: 0.1, nstep: 15, mad: true, third: false };
for k in 0..16 {
let xb = &x[k * 16..k * 16 + 16];
let w: [f32; 16] = std::array::from_fn(|j| {
if let Some(q) = qw { q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j].abs() }
});
for &v in &w {
sw[k] += v;
s.sw[k] += v;
}
let (d, m) = if qw.is_some() {
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], -0.9, 0.05, 36, false, true)
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], Qkx::WEIGHTED)
} else {
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], -0.5, 0.1, 15, true, false)
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], plain)
};
scales[k] = d;
mins[k] = m;
if d > maxs {
maxs = d;
}
if m > maxm {
maxm = m;
}
s.record(k, d, m);
}
s
}
/// The 4-bit scale and minimum levels of the blocks and the super-block (d, m).
fn q2k_scales(s: &Search<16>, weighted: bool) -> ([u8; 16], [u8; 16], f32, f32) {
let mut ls = [0u8; 16];
let mut lm = ls;
let (d, m) = if qw.is_some() {
(qp(&scales, 15, &mut ls, &sw), qp(&mins, 15, &mut lm, &sw))
} else {
let si = if maxs > 0.0 { 15.0 / maxs } else { 0.0 };
let mi = if maxm > 0.0 { 15.0 / maxm } else { 0.0 };
for k in 0..16 {
ls[k] = nearest(si * scales[k]) as u8;
lm[k] = nearest(mi * mins[k]) as u8;
}
(maxs / 15.0, maxm / 15.0)
};
put_h(y, 80, d);
put_h(y, 82, m);
let d = h(y, 80);
let m = h(y, 82);
if weighted {
let (d, m) = (qp(&s.scales, 15, &mut ls, &s.sw), qp(&s.mins, 15, &mut lm, &s.sw));
return (ls, lm, d, m);
}
let (si, mi) = s.factors(15.0);
for k in 0..16 {
ls[k] = nearest(si * s.scales[k]) as u8;
lm[k] = nearest(mi * s.mins[k]) as u8;
}
let (d, m) = s.steps(15.0);
(ls, lm, d, m)
}
/// Stores the packed scales in y[..16] and requantizes the values against the stored (rounded) d and m.
fn q2k_requantize(x: &[f32], y: &mut [u8], levels: [&[u8; 16]; 2], dm: (f32, f32), l: &mut [u8; 256]) {
let [ls, lm] = levels;
let (d, m) = dm;
for k in 0..16 {
y[k] = ls[k] | (lm[k] << 4);
let ds = d * (y[k] & 15) as f32;
@@ -137,7 +145,6 @@ pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
l[k * 16 + j] = nearest((x[k * 16 + j] + dm) / ds).clamp(0, 3) as u8;
}
}
pack_k2(&l, &mut y[16..80]);
}
pub(super) fn pack_scale3(l: &[i8; 16], y: &mut [u8]) {
y.fill(0);
@@ -157,15 +164,22 @@ pub(super) fn unpack_scale3(y: &[u8], j: usize) -> i32 {
}
pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0i8; 256];
let (scales, sw, maxs) = q3k_search(x, &mut l, qw);
let mut ls = [0i8; 16];
let d = q3k_scale(&scales, &sw, maxs, &mut ls, qw.is_some());
pack_scale3(&ls, &mut y[96..108]);
put_h(y, 108, d);
let d = h(y, 108);
q3k_requantize(x, y, d, &mut l);
q3k_pack(y, &mut l);
}
/// The scale of each 16-value block (levels of that fit in `l`), the block weights, and the scale of largest magnitude.
fn q3k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], [f32; 16], f32) {
let mut scales = [0.0; 16];
let mut sw = scales;
let mut maxs = 0.0;
let mut amax = 0.0;
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let sigma = 2.0 * sum_sq(x) / 256.0;
for k in 0..16 {
let xb = &x[k * 16..k * 16 + 16];
scales[k] = if let Some(q) = qw {
@@ -182,29 +196,36 @@ pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
maxs = scales[k];
}
}
let mut ls = [0i8; 16];
let d = if qw.is_some() {
qx(&scales, 32, &mut ls, 1, Some(&sw))
} else if maxs != 0.0 {
let inv = -32.0 / maxs;
for k in 0..16 {
ls[k] = (nearest(inv * scales[k]).clamp(-32, 31) + 32) as i8;
}
1.0 / inv
} else {
0.0
};
pack_scale3(&ls, &mut y[96..108]);
put_h(y, 108, d);
let d = h(y, 108);
(scales, sw, maxs)
}
/// The super-block scale; the 6-bit block scale levels go to `ls`.
fn q3k_scale(scales: &[f32; 16], sw: &[f32; 16], maxs: f32, ls: &mut [i8; 16], weighted: bool) -> f32 {
if weighted {
return qx(scales, 32, ls, 1, Some(sw));
}
if maxs == 0.0 {
return 0.0;
}
let inv = -32.0 / maxs;
for k in 0..16 {
ls[k] = (nearest(inv * scales[k]).clamp(-32, 31) + 32) as i8;
}
1.0 / inv
}
/// Requantizes the values against the stored (rounded) super-block scale `d` and the packed block scales in y.
fn q3k_requantize(x: &[f32], y: &[u8], d: f32, l: &mut [i8; 256]) {
for k in 0..16 {
let ds = d * unpack_scale3(&y[96..108], k) as f32;
if ds != 0.0 {
for j in 0..16 {
l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8;
}
if ds == 0.0 {
continue;
}
for j in 0..16 {
l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8;
}
}
}
/// High bits into y[..32], the low two bits into y[32..96].
fn q3k_pack(y: &mut [u8], l: &mut [i8; 256]) {
y[..32].fill(0);
let mut low = [0u8; 256];
for j in 0..256 {
@@ -1,100 +1,117 @@
//! Moved out of the parent module by STRA-338: fn iq4, fn row_without_iq.
use super::nearest_fn::sum_sq;
#[allow(unused_imports)]
use super::*;
pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) {
let n = x.len();
let nb = n / 32;
let mut sigma = 0.0;
for &v in x {
sigma += v * v;
}
sigma *= 2.0 / n as f32;
let nb = x.len() / 32;
let mut sigma = sum_sq(x);
sigma *= 2.0 / x.len() as f32;
let mut l = [0u8; 256];
let mut scales = [0.0; 8];
let (mut maxs, mut amax) = (0.0, 0.0);
y.fill(0);
put_h(y, 0, 0.0);
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
for k in 0..nb {
let xb = &x[k * 32..k * 32 + 32];
let w: [f32; 32] = std::array::from_fn(|j| {
if let Some(q) = qw { q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j] * xb[j] }
});
let (a, max) = max_signed(xb);
if a < EPS {
scales[k] = 0.0;
continue;
}
let mut d = if ntry > 0 { -max / values[0] as f32 } else { max / values[0] as f32 };
let mut inv = 1.0 / d;
let (mut sx, mut s2) = (0.0, 0.0);
for j in 0..32 {
let q = best_iq4(inv * xb[j]);
l[k * 32 + j] = q;
let q = values[q as usize] as f32;
sx += w[j] * q * xb[j];
s2 += w[j] * q * q;
}
d = if s2 > 0.0 { sx / s2 } else { 0.0 };
let mut best = d * sx;
for itry in -ntry..=ntry {
inv = (itry as f32 + values[0] as f32) / max;
sx = 0.0;
s2 = 0.0;
for j in 0..32 {
let q = values[best_iq4(inv * xb[j]) as usize] as f32;
sx += w[j] * q * xb[j];
s2 += w[j] * q * q;
}
if s2 > 0.0 && sx * sx > best * s2 {
d = sx / s2;
best = d * sx;
}
}
scales[k] = d;
if d.abs() > amax {
amax = d.abs();
maxs = d;
}
}
let (scales, maxs) = iq4_search(x, &mut l, qw, (sigma, ntry));
let head = if kind == Kind::Iq4Xs {
let d = -maxs / 32.0;
put_h(y, 0, d);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
let mut high = 0u16;
for k in 0..nb {
let s = nearest(inv * scales[k]).clamp(-32, 31);
let ds = d * s as f32;
let di = if ds != 0.0 { 1.0 / ds } else { 0.0 };
for j in 0..32 {
l[k * 32 + j] = best_iq4(di * x[k * 32 + j]);
}
let s = (s + 32) as u8;
if k % 2 == 0 {
y[4 + k / 2] = s & 15;
} else {
y[4 + k / 2] |= (s & 15) << 4;
}
high |= ((s >> 4) as u16) << (2 * k);
}
y[2..4].copy_from_slice(&high.to_le_bytes());
8
iq4_xs_scales(x, y, &mut l, &scales[..nb], maxs)
} else {
put_h(y, 0, scales[0]);
if ntry > 0 {
let inv = if scales[0] != 0.0 { 1.0 / scales[0] } else { 0.0 };
for j in 0..n {
l[j] = best_iq4(inv * x[j]);
}
}
2
iq4_nl_scale(x, y, &mut l, scales[0], ntry)
};
for k in 0..nb {
pack4(&l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]);
}
}
/// The scale of each 32-value block (levels of that fit in `l`) and the scale of largest magnitude;
/// `fit` is (sigma, ntry).
fn iq4_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>, fit: (f32, i32)) -> ([f32; 8], f32) {
let (sigma, ntry) = fit;
let mut scales = [0.0; 8];
let (mut maxs, mut amax) = (0.0, 0.0);
for k in 0..x.len() / 32 {
let xb = &x[k * 32..k * 32 + 32];
let w: [f32; 32] = std::array::from_fn(|j| {
if let Some(q) = qw { q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j] * xb[j] }
});
scales[k] = iq4_block(xb, &w, &mut l[k * 32..k * 32 + 32], ntry);
if scales[k].abs() > amax {
amax = scales[k].abs();
maxs = scales[k];
}
}
(scales, maxs)
}
/// The best scale of one block among the 2 * ntry + 1 tried; 0 for an all-zero block, whose levels stay untouched.
fn iq4_block(xb: &[f32], w: &[f32; 32], lb: &mut [u8], ntry: i32) -> f32 {
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
let (a, max) = max_signed(xb);
if a < EPS {
return 0.0;
}
let d = if ntry > 0 { -max / values[0] as f32 } else { max / values[0] as f32 };
let inv = 1.0 / d;
for j in 0..32 {
lb[j] = best_iq4(inv * xb[j]);
}
let (sx, s2) = iq4_sums(xb, w, inv);
let mut d = if s2 > 0.0 { sx / s2 } else { 0.0 };
let mut best = d * sx;
for itry in -ntry..=ntry {
let inv = (itry as f32 + values[0] as f32) / max;
let (sx, s2) = iq4_sums(xb, w, inv);
if s2 > 0.0 && sx * sx > best * s2 {
d = sx / s2;
best = d * sx;
}
}
d
}
/// The weighted sums (sum w*q*x, sum w*q*q) of the codebook values nearest to `inv * x`.
fn iq4_sums(xb: &[f32], w: &[f32; 32], inv: f32) -> (f32, f32) {
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
let (mut sx, mut s2) = (0.0, 0.0);
for j in 0..32 {
let q = values[best_iq4(inv * xb[j]) as usize] as f32;
sx += w[j] * q * xb[j];
s2 += w[j] * q * q;
}
(sx, s2)
}
/// IQ4_XS: the 6-bit block scales (low four bits in y[4..8], high two in y[2..4]) and the levels against them;
/// the offset of the packed levels.
fn iq4_xs_scales(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scales: &[f32], maxs: f32) -> usize {
let d = -maxs / 32.0;
put_h(y, 0, d);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
let mut high = 0u16;
for (k, &scale) in scales.iter().enumerate() {
let s = nearest(inv * scale).clamp(-32, 31);
let ds = d * s as f32;
let di = if ds != 0.0 { 1.0 / ds } else { 0.0 };
for j in 0..32 {
l[k * 32 + j] = best_iq4(di * x[k * 32 + j]);
}
let s = (s + 32) as u8;
if k % 2 == 0 {
y[4 + k / 2] = s & 15;
} else {
y[4 + k / 2] |= (s & 15) << 4;
}
high |= ((s >> 4) as u16) << (2 * k);
}
y[2..4].copy_from_slice(&high.to_le_bytes());
8
}
/// IQ4_NL: the single scale; with `ntry > 0` the levels are redone against it. The offset of the packed levels.
fn iq4_nl_scale(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scale: f32, ntry: i32) -> usize {
put_h(y, 0, scale);
if ntry > 0 {
let inv = if scale != 0.0 { 1.0 / scale } else { 0.0 };
for j in 0..x.len() {
l[j] = best_iq4(inv * x[j]);
}
}
2
}
/// Reference/weighted rows sharing one imatrix vector per row, as ggml_quantize_chunk.
/// IQ lookup quantizers are registered by the separate pinned grid module.
pub(in super::super) fn row_without_iq(
@@ -108,33 +125,48 @@ pub(in super::super) fn row_without_iq(
return Err(Error::Shape);
}
let (q, b) = kind.block();
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = sum / x.len() as f32;
let sigma = sum_sq(x) / x.len() as f32;
for (i, (x, y)) in x.chunks_exact(q).zip(y.chunks_exact_mut(b)).enumerate() {
let w = qw.map(|w| &w[i * q..(i + 1) * q]);
match kind {
Kind::F32
| Kind::F16
| Kind::Bf16
| Kind::Q1Zero
| Kind::Q2Zero
| Kind::Q4Zero
| Kind::Q4One
| Kind::Q5Zero
| Kind::Q5One
| Kind::Q8Zero => small(kind, x, y, w, sigma),
Kind::MxFp4 | Kind::NvFp4 => fp4(kind, x, y),
Kind::Tq1 | Kind::Tq2 => ternary(kind, x, y),
Kind::Q2K => q2k(x, y, w),
Kind::Q3K => q3k(x, y, w),
Kind::Q4K | Kind::Q5K => q45k(kind == Kind::Q5K, x, y, w),
Kind::Q6K => q6k(x, y, w),
Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 }),
_ => return Ok(false),
if !block_without_iq(kind, (x, y), w, sigma, reference_iq4) {
return Ok(false);
}
}
Ok(true)
}
/// Quantizes one block of a kind this module handles; false for a kind it does not (the IQ lookup quantizers).
/// `block` is (values, output).
fn block_without_iq(
kind: Kind,
block: (&[f32], &mut [u8]),
w: Option<&[f32]>,
sigma: f32,
reference_iq4: bool,
) -> bool {
let (x, y) = block;
match kind {
Kind::F32
| Kind::F16
| Kind::Bf16
| Kind::Q1Zero
| Kind::Q2Zero
| Kind::Q4Zero
| Kind::Q4One
| Kind::Q5Zero
| Kind::Q5One
| Kind::Q8Zero => small(kind, x, y, w, sigma),
Kind::MxFp4 | Kind::NvFp4 => fp4(kind, x, y),
Kind::Tq1 | Kind::Tq2 => ternary(kind, x, y),
Kind::Q2K => q2k(x, y, w),
Kind::Q3K => q3k(x, y, w),
Kind::Q4K | Kind::Q5K => q45k(kind == Kind::Q5K, x, y, w),
Kind::Q6K => q6k(x, y, w),
Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, iq4_ntry(kind, reference_iq4)),
_ => return false,
}
true
}
/// Search width of the IQ4 quantizers: 7, or -1 for the reference IQ4_NL.
fn iq4_ntry(kind: Kind, reference_iq4: bool) -> i32 {
if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 }
}
@@ -14,6 +14,48 @@ pub(super) fn put_h(y: &mut [u8], at: usize, x: f32) {
pub(super) fn h(y: &[u8], at: usize) -> f32 {
half(u16::from_le_bytes([y[at], y[at + 1]]))
}
/// Sum of squares, accumulated left to right in f32.
pub(super) fn sum_sq(x: &[f32]) -> f32 {
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
sum
}
/// Per-block (scale, minimum) of a K-quant search, the block weights, and the largest scale and minimum.
pub(super) struct Search<const N: usize> {
pub(super) scales: [f32; N],
pub(super) mins: [f32; N],
pub(super) sw: [f32; N],
maxs: f32,
maxm: f32,
}
impl<const N: usize> Search<N> {
pub(super) fn new() -> Self {
Search { scales: [0.0; N], mins: [0.0; N], sw: [0.0; N], maxs: 0.0, maxm: 0.0 }
}
/// Stores the fit of block `k` and tracks the maxima.
pub(super) fn record(&mut self, k: usize, d: f32, m: f32) {
self.scales[k] = d;
self.mins[k] = m;
if d > self.maxs {
self.maxs = d;
}
if m > self.maxm {
self.maxm = m;
}
}
/// The 1/max factors for rounding scales and minima to `levels` steps (0 when the maximum is not positive).
pub(super) fn factors(&self, levels: f32) -> (f32, f32) {
let si = if self.maxs > 0.0 { levels / self.maxs } else { 0.0 };
let mi = if self.maxm > 0.0 { levels / self.maxm } else { 0.0 };
(si, mi)
}
/// maxs / levels and maxm / levels.
pub(super) fn steps(&self, levels: f32) -> (f32, f32) {
(self.maxs / levels, self.maxm / levels)
}
}
pub(super) fn max_signed(x: &[f32]) -> (f32, f32) {
let (mut a, mut v) = (0.0, 0.0);
for &f in x {
@@ -38,47 +80,49 @@ pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw
l.fill(0);
return 0.0;
}
let mut inv = -(nmax as f32) / max;
let inv = -(nmax as f32) / max;
if rmse == 0 {
for (&x, l) in x.iter().zip(l) {
*l = (nmax + nearest(inv * x).clamp(-nmax, nmax - 1)) as i8;
}
qx_levels(x, nmax, l, inv);
return 1.0 / inv;
}
let early = rmse < 0;
if early {
rmse = -rmse;
}
qx_levels(x, nmax, l, inv);
let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw);
let scale = if s2 != 0.0 { sx / s2 } else { 0.0 };
if early {
return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv };
}
qx_search(x, nmax, l, (max, rmse, qw), scale, sx)
}
/// The levels `nmax + clamp(round(inv * x))` as stored in `l`.
fn qx_levels(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) {
for (&x, l) in x.iter().zip(l) {
*l = (nmax + nearest(inv * x).clamp(-nmax, nmax - 1)) as i8;
}
}
/// The weighted sums (sum w*x*q, sum w*q*q) of the levels at `inv`.
fn qx_sums(x: &[f32], nmax: i32, inv: f32, rmse: i32, qw: Option<&[f32]>) -> (f32, f32) {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * x[i]).clamp(-nmax, nmax - 1);
l[i] = (q + nmax) as i8;
let w = weight(x[i], rmse, qw.map(|w| w[i]));
sx += w * x[i] * q as f32;
s2 += w * q as f32 * q as f32;
}
let mut scale = if s2 != 0.0 { sx / s2 } else { 0.0 };
if early {
return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv };
}
(sx, s2)
}
/// Tries the 18 other scales -(nmax + 0.1 * is) / max and keeps the levels of the best fit; `fit` is (max, rmse, qw).
fn qx_search(x: &[f32], nmax: i32, l: &mut [i8], fit: (f32, i32, Option<&[f32]>), mut scale: f32, sx: f32) -> f32 {
let (max, rmse, qw) = fit;
let mut best = scale * sx;
for is in -9..=9 {
if is == 0 {
continue;
}
inv = -(nmax as f32 + 0.1 * is as f32) / max;
sx = 0.0;
s2 = 0.0;
for i in 0..x.len() {
let q = nearest(inv * x[i]).clamp(-nmax, nmax - 1);
let w = weight(x[i], rmse, qw.map(|w| w[i]));
sx += w * x[i] * q as f32;
s2 += w * q as f32 * q as f32;
}
for is in (-9..=9).filter(|&is| is != 0) {
let inv = -(nmax as f32 + 0.1 * is as f32) / max;
let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw);
if s2 > 0.0 && sx * sx > best * s2 {
for i in 0..x.len() {
l[i] = (nmax + nearest(inv * x[i]).clamp(-nmax, nmax - 1)) as i8;
}
qx_levels(x, nmax, l, inv);
scale = sx / s2;
best = scale * sx;
}
@@ -101,26 +145,7 @@ pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 {
s2 += w * q as f32 * q as f32;
}
for _ in 0..5 {
let mut changed = 0;
for i in 0..x.len() {
let w = x[i] * x[i];
let mut tx = sx - w * x[i] * l[i] as f32;
if tx > 0.0 {
let mut t2 = s2 - w * l[i] as f32 * l[i] as f32;
let q = nearest(x[i] * t2 / tx).clamp(-4, 3);
if q != l[i] as i32 {
tx += w * x[i] * q as f32;
t2 += w * q as f32 * q as f32;
if t2 > 0.0 && tx * tx * s2 > sx * sx * t2 {
l[i] = q as i8;
sx = tx;
s2 = t2;
changed += 1;
}
}
}
}
if changed == 0 {
if q3_pass(x, l, &mut sx, &mut s2) == 0 {
break;
}
}
@@ -129,18 +154,81 @@ pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 {
}
if s2 > 0.0 { sx / s2 } else { 0.0 }
}
/// One sweep moving single levels while the fit improves; the number of levels changed.
fn q3_pass(x: &[f32], l: &mut [i8], sx: &mut f32, s2: &mut f32) -> i32 {
let mut changed = 0;
for i in 0..x.len() {
if let Some((q, tx, t2)) = q3_move(x[i], l[i], *sx, *s2) {
l[i] = q;
*sx = tx;
*s2 = t2;
changed += 1;
}
}
changed
}
/// The new level and sums when changing the level `li` of `xi` improves the fit.
#[allow(clippy::neg_cmp_op_on_partial_ord)]
fn q3_move(xi: f32, li: i8, sx: f32, s2: f32) -> Option<(i8, f32, f32)> {
let w = xi * xi;
let mut tx = sx - w * xi * li as f32;
if !(tx > 0.0) {
return None;
}
let mut t2 = s2 - w * li as f32 * li as f32;
let q = nearest(xi * t2 / tx).clamp(-4, 3);
if q == li as i32 {
return None;
}
tx += w * xi * q as f32;
t2 += w * q as f32 * q as f32;
if t2 > 0.0 && tx * tx * s2 > sx * sx * t2 { Some((q as i8, tx, t2)) } else { None }
}
/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights.
pub(super) fn qkx(
x: &[f32],
nmax: i32,
w: &[f32],
l: &mut [u8],
rmin: f32,
rdelta: f32,
nstep: i32,
mad: bool,
third: bool,
) -> (f32, f32) {
pub(super) fn qkx(x: &[f32], nmax: i32, w: &[f32], l: &mut [u8], p: Qkx) -> (f32, f32) {
let (mut min, max, sw, sx) = qkx_stats(x, w);
if (p.third && max <= min) || (!p.third && max == min) {
l.fill(0);
return (0.0, -min);
}
let inv = nmax as f32 / (max - min);
let mut scale = 1.0 / inv;
qkx_fill(x, l, nmax, inv, min);
let mut best = qkx_error(x, w, l, scale, min, p.mad);
let mut aux = [0u8; 32];
for is in 0..=p.nstep {
let inv = (p.rmin + p.rdelta * is as f32 + nmax as f32) / (max - min);
let (sl, sl2, sxl) = qkx_trial(x, w, &mut aux, nmax, inv, min);
let det = sw * sl2 - sl * sl;
if det > 0.0 {
let (ds, dm) = qkx_solve([sw, sx, sl, sl2, sxl], det);
let error = qkx_error(x, w, &aux, ds, dm, p.mad);
if error < best {
l.copy_from_slice(&aux[..x.len()]);
best = error;
scale = ds;
min = dm;
}
}
}
(scale, -min)
}
/// The search parameters of qkx: the first step offset and the step size, the number of steps, whether the error is
/// absolute (not squared), and the qkx3 variant.
#[derive(Clone, Copy)]
pub(super) struct Qkx {
pub(super) rmin: f32,
pub(super) rdelta: f32,
pub(super) nstep: i32,
pub(super) mad: bool,
pub(super) third: bool,
}
impl Qkx {
/// The importance-weighted search of the imatrix quantizers (qkx3).
pub(super) const WEIGHTED: Qkx = Qkx { rmin: -0.9, rdelta: 0.05, nstep: 36, mad: false, third: true };
}
/// (min clamped to <= 0, max, sum w, sum w*x) of the block.
fn qkx_stats(x: &[f32], w: &[f32]) -> (f32, f32, f32, f32) {
let (mut min, mut max) = (x[0], x[0]);
let (mut sw, mut sx) = (w[0], w[0] * x[0]);
for i in 1..x.len() {
@@ -156,49 +244,38 @@ pub(super) fn qkx(
if min > 0.0 {
min = 0.0;
}
if (third && max <= min) || (!third && max == min) {
l.fill(0);
return (0.0, -min);
}
let mut inv = nmax as f32 / (max - min);
let mut scale = 1.0 / inv;
let mut best = 0.0;
(min, max, sw, sx)
}
fn qkx_fill(x: &[f32], l: &mut [u8], nmax: i32, inv: f32, min: f32) {
for i in 0..x.len() {
l[i] = nearest(inv * (x[i] - min)).clamp(0, nmax) as u8;
let diff = scale * l[i] as f32 + min - x[i];
best += w[i] * if mad { diff.abs() } else { diff * diff };
}
let mut aux = [0u8; 32];
for is in 0..=nstep {
inv = (rmin + rdelta * is as f32 + nmax as f32) / (max - min);
let (mut sl, mut sl2, mut sxl) = (0.0, 0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * (x[i] - min)).clamp(0, nmax);
aux[i] = q as u8;
sl += w[i] * q as f32;
sl2 += w[i] * q as f32 * q as f32;
sxl += w[i] * q as f32 * x[i];
}
let det = sw * sl2 - sl * sl;
if det > 0.0 {
let mut ds = (sw * sxl - sx * sl) / det;
let mut dm = (sl2 * sx - sl * sxl) / det;
if dm > 0.0 {
dm = 0.0;
ds = sxl / sl2;
}
let mut error = 0.0;
for i in 0..x.len() {
let diff = ds * aux[i] as f32 + dm - x[i];
error += w[i] * if mad { diff.abs() } else { diff * diff };
}
if error < best {
l.copy_from_slice(&aux[..x.len()]);
best = error;
scale = ds;
min = dm;
}
}
}
/// Weighted error of the levels `q` against `x` under the affine map `scale * q + min`.
fn qkx_error(x: &[f32], w: &[f32], q: &[u8], scale: f32, min: f32, mad: bool) -> f32 {
let mut error = 0.0;
for i in 0..x.len() {
let diff = scale * q[i] as f32 + min - x[i];
error += w[i] * if mad { diff.abs() } else { diff * diff };
}
(scale, -min)
error
}
/// Quantizes into `aux` at `inv`; the sums (sum w*q, sum w*q*q, sum w*q*x).
fn qkx_trial(x: &[f32], w: &[f32], aux: &mut [u8; 32], nmax: i32, inv: f32, min: f32) -> (f32, f32, f32) {
let (mut sl, mut sl2, mut sxl) = (0.0, 0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * (x[i] - min)).clamp(0, nmax);
aux[i] = q as u8;
sl += w[i] * q as f32;
sl2 += w[i] * q as f32 * q as f32;
sxl += w[i] * q as f32 * x[i];
}
(sl, sl2, sxl)
}
/// Scale and (non-positive) minimum of the least-squares fit; `sums` is [sw, sx, sl, sl2, sxl].
fn qkx_solve(sums: [f32; 5], det: f32) -> (f32, f32) {
let [sw, sx, sl, sl2, sxl] = sums;
let ds = (sw * sxl - sx * sl) / det;
let dm = (sl2 * sx - sl * sxl) / det;
if dm > 0.0 { (sxl / sl2, 0.0) } else { (ds, dm) }
}
@@ -1,79 +1,72 @@
//! Moved out of the parent module by STRA-338: fn q45k, fn q6k, fn best_iq4.
use super::nearest_fn::{Qkx, Search, sum_sq};
#[allow(unused_imports)]
use super::*;
pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let nmax = if five { 31 } else { 15 };
let mut l = [0u8; 256];
let mut scales = [0.0; 8];
let mut mins = scales;
let mut sw = scales;
let (mut maxs, mut maxm) = (0.0, 0.0);
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
let sigma = 2.0 * sum / 256.0;
let av = sigma.sqrt();
for k in 0..8 {
let xb = &x[k * 32..k * 32 + 32];
let w: [f32; 32] = if let Some(q) = qw {
std::array::from_fn(|j| q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt())
} else {
let mut s = 0.0;
for &v in xb {
s += v * v;
}
let avg = (s / 32.0).sqrt();
std::array::from_fn(|j| avg + xb[j].abs())
};
for &v in &w {
sw[k] += v;
}
let (d, m) = if qw.is_some() {
qkx(xb, nmax, &w, &mut l[k * 32..k * 32 + 32], -0.9, 0.05, 36, false, true)
} else {
qkx(
xb,
nmax,
&w,
&mut l[k * 32..k * 32 + 32],
if five { -0.5 } else { -1.0 },
0.1,
if five { 15 } else { 20 },
false,
false,
)
};
scales[k] = d;
mins[k] = m;
if d > maxs {
maxs = d;
}
if m > maxm {
maxm = m;
}
}
// av belongs to the weighted implementation's no-imatrix branch; public
let search = q45k_search(five, x, &mut l, qw);
// The sigma.sqrt() of the weighted implementation's no-imatrix branch is not used: public
// quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML.
let _ = av;
let mut ls = [0u8; 8];
let mut lm = ls;
let (d, m) = if qw.is_some() {
(qp(&scales, 63, &mut ls, &sw), qp(&mins, 63, &mut lm, &sw))
} else {
let si = if maxs > 0.0 { 63.0 / maxs } else { 0.0 };
let mi = if maxm > 0.0 { 63.0 / maxm } else { 0.0 };
for k in 0..8 {
ls[k] = (nearest(si * scales[k]) as u8).min(63);
lm[k] = (nearest(mi * mins[k]) as u8).min(63);
}
(maxs / 63.0, maxm / 63.0)
};
let (ls, lm, d, m) = q45k_scales(&search, qw.is_some());
pack_scale4(&ls, &lm, &mut y[4..16]);
put_h(y, 0, d);
put_h(y, 2, m);
q45k_requantize(x, y, nmax, &mut l);
q45k_pack(five, y, &l);
}
/// Best (scale, minimum) of each 32-value block, with the levels of that fit in `l`.
fn q45k_search(five: bool, x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<8> {
let nmax = if five { 31 } else { 15 };
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut s = Search::<8>::new();
let plain = Qkx {
rmin: if five { -0.5 } else { -1.0 },
rdelta: 0.1,
nstep: if five { 15 } else { 20 },
mad: false,
third: false,
};
for k in 0..8 {
let xb = &x[k * 32..k * 32 + 32];
let w = q45k_weights(xb, qw.map(|q| &q[k * 32..k * 32 + 32]), sigma);
for &v in &w {
s.sw[k] += v;
}
let lb = &mut l[k * 32..k * 32 + 32];
let (d, m) = if qw.is_some() { qkx(xb, nmax, &w, lb, Qkx::WEIGHTED) } else { qkx(xb, nmax, &w, lb, plain) };
s.record(k, d, m);
}
s
}
/// Importance weights of a block: imatrix * sqrt(sigma + x^2), or rms + |x| without an imatrix.
fn q45k_weights(xb: &[f32], qb: Option<&[f32]>, sigma: f32) -> [f32; 32] {
if let Some(q) = qb {
return std::array::from_fn(|j| q[j] * (sigma + xb[j] * xb[j]).sqrt());
}
let avg = (sum_sq(xb) / 32.0).sqrt();
std::array::from_fn(|j| avg + xb[j].abs())
}
/// The 6-bit scale and minimum levels of the blocks and the super-block (d, m).
fn q45k_scales(s: &Search<8>, weighted: bool) -> ([u8; 8], [u8; 8], f32, f32) {
let mut ls = [0u8; 8];
let mut lm = ls;
if weighted {
let (d, m) = (qp(&s.scales, 63, &mut ls, &s.sw), qp(&s.mins, 63, &mut lm, &s.sw));
return (ls, lm, d, m);
}
let (si, mi) = s.factors(63.0);
for k in 0..8 {
ls[k] = (nearest(si * s.scales[k]) as u8).min(63);
lm[k] = (nearest(mi * s.mins[k]) as u8).min(63);
}
let (d, m) = s.steps(63.0);
(ls, lm, d, m)
}
/// Requantizes the values against the stored (rounded) d and m and the packed scales in y.
fn q45k_requantize(x: &[f32], y: &[u8], nmax: i32, l: &mut [u8; 256]) {
let d = h(y, 0);
let m = h(y, 2);
for k in 0..8 {
@@ -87,6 +80,9 @@ pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
l[k * 32 + j] = nearest((x[k * 32 + j] + dm) / ds).clamp(0, nmax) as u8;
}
}
}
/// Low nibbles from y[head], and for Q5_K the fifth bits in y[16..48].
fn q45k_pack(five: bool, y: &mut [u8], l: &[u8; 256]) {
let head = if five {
y[16..48].fill(0);
48
@@ -99,28 +95,14 @@ pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let b = l[k * 64 + j + 32];
y[head + k * 32 + j] = (a & 15) | ((b & 15) << 4);
if five {
if a > 15 {
y[16 + j] |= 1 << (2 * k);
}
if b > 15 {
y[16 + j] |= 2 << (2 * k);
}
y[16 + j] |= (u8::from(a > 15) << (2 * k)) | (u8::from(b > 15) << (2 * k + 1));
}
}
}
}
pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0i8; 256];
let mut scales = [0.0; 16];
let (mut maxs, mut amax) = (0.0, 0.0);
for k in 0..16 {
let d = qx(&x[k * 16..k * 16 + 16], 32, &mut l[k * 16..k * 16 + 16], 1, qw.map(|q| &q[k * 16..k * 16 + 16]));
scales[k] = d;
if d.abs() > amax {
amax = d.abs();
maxs = d;
}
}
let (scales, maxs, amax) = q6k_search(x, &mut l, qw);
if amax < EPS {
y.fill(0);
put_h(y, 208, 0.0);
@@ -131,6 +113,25 @@ pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
for k in 0..16 {
y[192 + k] = nearest(inv * scales[k]).min(127) as i8 as u8;
}
q6k_requantize(x, y, &mut l);
q6k_pack(y, &l);
}
/// The scale of each 16-value block (levels of that fit in `l`), the scale of largest magnitude and that magnitude.
fn q6k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], f32, f32) {
let mut scales = [0.0; 16];
let (mut maxs, mut amax) = (0.0, 0.0);
for k in 0..16 {
let d = qx(&x[k * 16..k * 16 + 16], 32, &mut l[k * 16..k * 16 + 16], 1, qw.map(|q| &q[k * 16..k * 16 + 16]));
scales[k] = d;
if d.abs() > amax {
amax = d.abs();
maxs = d;
}
}
(scales, maxs, amax)
}
/// Requantizes the values against the stored (rounded) super-block scale and the block scales in y[192..208].
fn q6k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) {
let d = h(y, 208);
for k in 0..16 {
let ds = d * y[192 + k] as i8 as f32;
@@ -141,6 +142,9 @@ pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-32, 31) + 32) as i8;
}
}
}
/// Low nibbles into y[..128], the high two bits into y[128..192].
fn q6k_pack(y: &mut [u8], l: &[i8; 256]) {
for k in 0..2 {
for j in 0..32 {
let a = l[k * 128 + j] as u8;
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn qp, fn pack4, fn small, fn e8_half, fn ue4, fn pack_ue4.
use super::nearest_fn::Qkx;
#[allow(unused_imports)]
use super::*;
@@ -14,6 +15,12 @@ pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32
l.fill(0);
return 0.0;
}
let inv = qp_scale(x, nmax, l, w, max);
qp_refine(x, nmax, l, w, inv)
}
/// The inverse scale among nmax/max and the eight 0.1-steps around it with the smallest weighted error;
/// `l` holds the levels of nmax/max on return.
fn qp_scale(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], max: f32) -> f32 {
let mut inv = nmax as f32 / max;
for i in 0..x.len() {
l[i] = nearest(inv * x[i]) as u8;
@@ -24,23 +31,29 @@ pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32
let d = x[i] - scale * l[i] as f32;
best += w[i] * d * d;
}
for is in -4..=4 {
if is == 0 {
continue;
}
for is in (-4..=4).filter(|&is| is != 0) {
let ti = (0.1 * is as f32 + nmax as f32) / max;
let ds = 1.0 / ti;
let mut err = 0.0;
for i in 0..x.len() {
let q = nearest(ti * x[i]).min(nmax);
let d = x[i] - ds * q as f32;
err += w[i] * d * d;
}
let err = qp_error(x, nmax, w, ti);
if err < best {
best = err;
inv = ti;
}
}
inv
}
/// Weighted squared error of the levels at the inverse scale `ti`.
fn qp_error(x: &[f32], nmax: i32, w: &[f32], ti: f32) -> f32 {
let ds = 1.0 / ti;
let mut err = 0.0;
for i in 0..x.len() {
let q = nearest(ti * x[i]).min(nmax);
let d = x[i] - ds * q as f32;
err += w[i] * d * d;
}
err
}
/// Levels at `inv`, then up to five sweeps moving single levels while the fit improves; the scale.
fn qp_refine(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], inv: f32) -> f32 {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * x[i]).min(nmax);
@@ -51,20 +64,11 @@ pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32
for _ in 0..5 {
let mut changed = 0;
for i in 0..x.len() {
let mut tx = sx - w[i] * x[i] * l[i] as f32;
let mut t2 = s2 - w[i] * l[i] as f32 * l[i] as f32;
if tx > 0.0 && t2 > 0.0 {
let q = nearest(x[i] * t2 / tx).min(nmax);
if q != l[i] as i32 {
tx += w[i] * x[i] * q as f32;
t2 += w[i] * q as f32 * q as f32;
if tx * tx * s2 > sx * sx * t2 {
l[i] = q as u8;
sx = tx;
s2 = t2;
changed += 1;
}
}
if let Some((q, tx, t2)) = qp_move(x[i], w[i], l[i], nmax, (sx, s2)) {
l[i] = q;
sx = tx;
s2 = t2;
changed += 1;
}
}
if changed == 0 {
@@ -73,126 +77,166 @@ pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32
}
if s2 > 0.0 { sx / s2 } else { 0.0 }
}
/// The new level and sums when changing the level `li` of `xi` (weight `wi`) improves the fit; `sums` is (sx, s2).
fn qp_move(xi: f32, wi: f32, li: u8, nmax: i32, sums: (f32, f32)) -> Option<(u8, f32, f32)> {
let (sx, s2) = sums;
let mut tx = sx - wi * xi * li as f32;
let mut t2 = s2 - wi * li as f32 * li as f32;
if !(tx > 0.0 && t2 > 0.0) {
return None;
}
let q = nearest(xi * t2 / tx).min(nmax);
if q == li as i32 {
return None;
}
tx += wi * xi * q as f32;
t2 += wi * q as f32 * q as f32;
if tx * tx * s2 > sx * sx * t2 { Some((q as u8, tx, t2)) } else { None }
}
pub(super) fn pack4(l: &[u8], y: &mut [u8]) {
for j in 0..16 {
y[j] = l[j] | (l[j + 16] << 4);
}
}
pub(super) fn small(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
if matches!(kind, Kind::F32 | Kind::F16 | Kind::Bf16) {
match kind {
Kind::F32 => y.copy_from_slice(&x[0].to_le_bytes()),
Kind::F16 => put_h(y, 0, x[0]),
_ => {
let b = x[0].to_bits();
let h = if b & 0x7fffffff > 0x7f800000 {
(b >> 16) | 64
} else {
b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16
};
y.copy_from_slice(&(h as u16).to_le_bytes());
}
}
return;
match kind {
Kind::F32 | Kind::F16 | Kind::Bf16 => small_float(kind, x, y),
Kind::Q1Zero => small_q1(x, y),
Kind::Q2Zero => small_q2(x, y),
Kind::Q8Zero => small_q8(x, y),
_ => small_q45(kind, x, y, qw, sigma),
}
if kind == Kind::Q1Zero {
let mut sum = 0.0;
for &v in x {
sum += v.abs();
}
fn small_float(kind: Kind, x: &[f32], y: &mut [u8]) {
match kind {
Kind::F32 => y.copy_from_slice(&x[0].to_le_bytes()),
Kind::F16 => put_h(y, 0, x[0]),
_ => {
let b = x[0].to_bits();
let h = if b & 0x7fffffff > 0x7f800000 {
(b >> 16) | 64
} else {
b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16
};
y.copy_from_slice(&(h as u16).to_le_bytes());
}
put_h(y, 0, sum / 128.0);
y[2..].fill(0);
for j in 0..128 {
if x[j] >= 0.0 {
y[2 + j / 8] |= 1 << (j % 8);
}
}
return;
}
if kind == Kind::Q2Zero {
let (a, _) = max_signed(x);
put_h(y, 0, a);
let inv = if a > 0.0 { 1.0 / a } else { 0.0 };
y[2..].fill(0);
for j in 0..64 {
let q = ((x[j] * inv).round() as i32 + 1).clamp(0, 3);
y[2 + j / 4] |= (q as u8) << (2 * (j % 4));
}
return;
}
fn small_q1(x: &[f32], y: &mut [u8]) {
let mut sum = 0.0;
for &v in x {
sum += v.abs();
}
if kind == Kind::Q8Zero {
let (a, _) = max_signed(x);
let d = a / 127.0;
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
put_h(y, 0, d);
for j in 0..32 {
y[j + 2] = (x[j] * inv).round() as i8 as u8;
put_h(y, 0, sum / 128.0);
y[2..].fill(0);
for j in 0..128 {
if x[j] >= 0.0 {
y[2 + j / 8] |= 1 << (j % 8);
}
return;
}
let is_min = matches!(kind, Kind::Q4One | Kind::Q5One);
}
fn small_q2(x: &[f32], y: &mut [u8]) {
let (a, _) = max_signed(x);
put_h(y, 0, a);
let inv = if a > 0.0 { 1.0 / a } else { 0.0 };
y[2..].fill(0);
for j in 0..64 {
let q = ((x[j] * inv).round() as i32 + 1).clamp(0, 3);
y[2 + j / 4] |= (q as u8) << (2 * (j % 4));
}
}
fn small_q8(x: &[f32], y: &mut [u8]) {
let (a, _) = max_signed(x);
let d = a / 127.0;
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
put_h(y, 0, d);
for j in 0..32 {
y[j + 2] = (x[j] * inv).round() as i8 as u8;
}
}
/// What distinguishes Q4_0/Q4_1/Q5_0/Q5_1: a minimum is stored, five bits, and the top level.
#[derive(Clone, Copy)]
struct Shape {
is_min: bool,
five: bool,
nmax: i32,
}
fn small_q45(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
let five = matches!(kind, Kind::Q5Zero | Kind::Q5One);
let nmax = if five { 31 } else { 15 };
let shape = Shape { is_min: matches!(kind, Kind::Q4One | Kind::Q5One), five, nmax: if five { 31 } else { 15 } };
let mut l = [0u8; 32];
let (d, m) = if let Some(qw) = qw {
let w = std::array::from_fn::<_, 32, _>(|j| qw[j] * (sigma + x[j] * x[j]).sqrt());
if is_min {
let (s, m) = qkx(x, nmax, &w, &mut l, -0.9, 0.05, 36, false, true);
(s, -m)
} else {
let mut q = [0i8; 32];
let d = qx(x, if five { 16 } else { 8 }, &mut q, 1, Some(&w));
for j in 0..32 {
l[j] = q[j] as u8;
}
(d, 0.0)
}
} else if is_min {
let (mut min, mut max) = (f32::MAX, -f32::MAX);
for &v in x {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
let d = (max - min) / nmax as f32;
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
let q = ((x[j] - min) * inv + 0.5) as i32;
l[j] = if five { q as u8 } else { q.min(15) as u8 };
}
(d, min)
} else {
let (_, max) = max_signed(x);
let center = if five { 16 } else { 8 };
let d = max / -(center as f32);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(nmax) as u8;
}
(d, 0.0)
let (d, m) = match qw {
Some(qw) => small_weighted(x, qw, sigma, shape, &mut l),
None if shape.is_min => small_plain_min(x, shape, &mut l),
None => small_plain_sym(x, shape, &mut l),
};
put_h(y, 0, d);
let head = if is_min {
let head = if shape.is_min {
put_h(y, 2, m);
4
} else {
2
};
if five {
let mut hi = 0u32;
for j in 0..16 {
y[head + 4 + j] = (l[j] & 15) | ((l[j + 16] & 15) << 4);
hi |= ((l[j] as u32 & 16) >> 4) << j;
hi |= ((l[j + 16] as u32 & 16) >> 4) << (j + 16);
}
y[head..head + 4].copy_from_slice(&hi.to_le_bytes());
pack5(&l, y, head);
} else {
pack4(&l, &mut y[head..]);
}
}
/// Levels from the importance-weighted search; (scale, minimum).
fn small_weighted(x: &[f32], qw: &[f32], sigma: f32, shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
let w = std::array::from_fn::<_, 32, _>(|j| qw[j] * (sigma + x[j] * x[j]).sqrt());
if shape.is_min {
let (s, m) = qkx(x, shape.nmax, &w, l, Qkx::WEIGHTED);
return (s, -m);
}
let mut q = [0i8; 32];
let d = qx(x, if shape.five { 16 } else { 8 }, &mut q, 1, Some(&w));
for j in 0..32 {
l[j] = q[j] as u8;
}
(d, 0.0)
}
/// Reference levels of Q4_1/Q5_1 from the min and max of the block; (scale, minimum).
fn small_plain_min(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
let (mut min, mut max) = (f32::MAX, -f32::MAX);
for &v in x {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
let d = (max - min) / shape.nmax as f32;
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
let q = ((x[j] - min) * inv + 0.5) as i32;
l[j] = if shape.five { q as u8 } else { q.min(15) as u8 };
}
(d, min)
}
/// Reference levels of Q4_0/Q5_0 around the centre level; (scale, 0).
fn small_plain_sym(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
let (_, max) = max_signed(x);
let center = if shape.five { 16 } else { 8 };
let d = max / -(center as f32);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(shape.nmax) as u8;
}
(d, 0.0)
}
/// Five-bit packing: the low nibbles at `head + 4`, the fifth bits as a little-endian u32 at `head`.
fn pack5(l: &[u8; 32], y: &mut [u8], head: usize) {
let mut hi = 0u32;
for j in 0..16 {
y[head + 4 + j] = (l[j] & 15) | ((l[j + 16] & 15) << 4);
hi |= ((l[j] as u32 & 16) >> 4) << j;
hi |= ((l[j + 16] as u32 & 16) >> 4) << (j + 16);
}
y[head..head + 4].copy_from_slice(&hi.to_le_bytes());
}
pub(super) fn e8_half(e: u8) -> f32 {
f32::from_bits(if e < 2 { 0x00200000u32 << e } else { ((e as u32) - 1) << 23 })
}