use super::metrics;
use super::quant::DominantQuant;
pub(super) const KL_WRONG: f64 = 1e-2;
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Spread {
pub(super) kl: f64,
pub(super) between: (usize, usize),
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum WrongLine {
Calibrated { spread: Spread, line: f64 },
Absolute(f64),
Uncalibrated,
}
impl WrongLine {
fn decide(spread: Option<Spread>, quant: &DominantQuant) -> Self {
match spread {
Some(s) => {
let line = s.kl.max(KL_WRONG);
Self::Calibrated { spread: s, line }
}
None if quant.q8k_dotted() => Self::Uncalibrated,
None => Self::Absolute(KL_WRONG),
}
}
pub(super) fn value(&self) -> Option<f64> {
match self {
Self::Calibrated { line, .. } => Some(*line),
Self::Absolute(v) => Some(*v),
Self::Uncalibrated => None,
}
}
}
#[derive(Debug, Clone)]
pub(super) struct Band {
to_frink: Vec<f64>,
line: WrongLine,
}
impl Band {
pub(super) fn measure(references: &[&[f32]], frink: &[f32], quant: &DominantQuant) -> Self {
let probs: Vec<Vec<f64>> = references.iter().map(|r| metrics::softmax(r)).collect();
let fx = metrics::softmax(frink);
let to_frink = probs.iter().map(|p| metrics::kl(p, &fx)).collect();
let mut spread: Option<Spread> = None;
for (i, a) in probs.iter().enumerate() {
for (j, b) in probs.iter().enumerate() {
if i == j {
continue;
}
let kl = metrics::kl(a, b);
if kl > 0.0 && spread.as_ref().is_none_or(|s| kl > s.kl) {
spread = Some(Spread {
kl,
between: (i, j),
});
}
}
}
Self {
line: WrongLine::decide(spread, quant),
to_frink,
}
}
pub(super) fn kl_to_frink(&self, i: usize) -> f64 {
self.to_frink[i]
}
pub(super) fn nearest(&self) -> f64 {
self.to_frink.iter().copied().fold(f64::INFINITY, f64::min)
}
pub(super) fn line(&self) -> &WrongLine {
&self.line
}
pub(super) fn frink_is_outside(&self) -> bool {
self.line.value().is_some_and(|line| self.nearest() > line)
}
}
#[cfg(test)]
mod tests {
use super::super::quant::tests::{Q8K_DOTTED, Q8_0_DOTTED};
use super::*;
fn kquant() -> DominantQuant {
DominantQuant::weigh(Some("Q4K"), Some("Q4K"))
}
fn q8_0() -> DominantQuant {
DominantQuant::weigh(Some("Q8_0"), Some("Q8_0"))
}
fn spread(kl: f64) -> Option<Spread> {
Some(Spread {
kl,
between: (0, 1),
})
}
const SWEEP: &[(&str, f64, f64, f64, bool)] = &[
("Llama-3.2-1B-Q8_0", 0.0, 6.9121e-4, 6.9121e-4, false),
("tinyllama-1.1B-Q8_0", 0.0, 2.4448e-4, 2.4448e-4, false),
(
"Llama-3.2-1B-q6khead-q8body",
1.1399e-13,
2.3131e-4,
2.3132e-4,
true,
),
(
"Llama-3.2-1B-IQ4_XS",
2.9812e-4,
9.2083e-4,
1.4186e-3,
false,
),
("olmoe-1b-7b-Q4_0", 4.5703e-4, 4.8177e-4, 4.2587e-4, false),
("Llama-3.2-3B-Q4_K_M", 7.5180e-4, 9.1456e-4, 6.4631e-4, true),
("Llama-3.1-8B-Q4_K_M", 7.5787e-4, 1.0718e-3, 1.3068e-3, true),
(
"Llama-3.2-1B-pure-q4ks",
1.1626e-3,
1.1260e-3,
1.3212e-3,
true,
),
("Llama-3.2-1B-Q6_K", 1.2803e-3, 3.5602e-3, 6.9239e-3, true),
("Mistral-7B-Q4_K_M", 1.4363e-3, 4.6836e-4, 1.0008e-3, true),
(
"Llama-3.2-1B-q8head-q4ksbody",
1.8567e-3,
1.4173e-3,
8.6501e-4,
true,
),
("Llama-3.2-1B-Q4_K_M", 2.1176e-3, 1.8193e-3, 1.0773e-3, true),
("Llama-3.2-1B-Q5_K_M", 2.1742e-3, 3.4487e-3, 1.3816e-3, true),
("Phi-4-mini-Q4_K_M", 5.5853e-3, 1.1790e-2, 3.7999e-3, true),
(
"Qwen1.5-MoE-A2.7B-Q4_K_M",
5.6984e-3,
5.0306e-3,
4.8256e-3,
true,
),
("Yi-1.5-6B-Q4_K_M", 7.3179e-3, 2.1770e-3, 8.0876e-3, true),
(
"DeepSeek-R1-Distill-1.5B-Q4_K_M",
1.5695e-2,
1.9874e-2,
9.1570e-3,
true,
),
("gemma-2-2b-Q4_K_M", 1.6736e-2, 6.5107e-3, 1.5307e-2, true),
("Qwen2.5-1.5B-Q4_K_M", 2.7348e-2, 7.6786e-3, 2.6692e-2, true),
(
"Qwen3-0.6B-q8head-q4ksbody",
2.7459e-2,
1.2966e-2,
3.5192e-2,
true,
),
(
"Qwen3-0.6B-pure-q4ks",
3.5141e-2,
1.9748e-2,
3.8885e-2,
true,
),
];
fn band_of(spread_kl: f64, kls: &[f64], quant: &DominantQuant) -> Band {
Band {
to_frink: kls.to_vec(),
line: WrongLine::decide(
(spread_kl > 0.0).then_some(Spread {
kl: spread_kl,
between: (0, 1),
}),
quant,
),
}
}
#[test]
fn no_measured_checkpoint_is_wrong_when_the_references_are_calibrated() {
for &(name, spread_kl, kl_brew, kl_scratch, q8k) in SWEEP {
let quant = if q8k { kquant() } else { q8_0() };
let band = band_of(spread_kl, &[kl_brew, kl_scratch], &quant);
let line = band.line().value().expect("two references give a line");
assert!(
!band.frink_is_outside(),
"{name}: nearest {:.4e} crosses the {line:.4e} line built from a {spread_kl:.4e} \
reference spread",
band.nearest()
);
assert!(
band.nearest() <= 0.6 * line,
"{name}: {:.4e} is {:.2} of its {line:.4e} line — the measured worst is 0.58, \
so either the sweep moved or the rule did",
band.nearest(),
band.nearest() / line
);
}
}
#[test]
fn the_checkpoint_that_broke_the_constant_is_inside_its_own_measured_band() {
let band = band_of(3.5141e-2, &[1.9748e-2, 3.8885e-2], &kquant());
assert_eq!(
band.line().value(),
Some(3.5141e-2),
"the line is the spread itself, the floor being smaller"
);
assert!(!band.frink_is_outside());
assert_eq!(band.nearest(), 1.9748e-2);
let bumped_constant = 3.5141e-2 * 1.1;
assert!(
3.8885e-2 > bumped_constant,
"raising the constant to the newest spread leaves the newer reference over the \
line — the point of #111"
);
}
#[test]
fn one_reference_declines_to_convict_a_kquant_rather_than_guessing_a_line() {
for kind in Q8K_DOTTED {
let quant = DominantQuant::weigh(Some("Q8_0"), Some(kind));
let band = band_of(0.0, &[9.9e-1], &quant);
assert_eq!(*band.line(), WrongLine::Uncalibrated);
assert_eq!(band.line().value(), None, "{kind} must carry no number");
assert!(
!band.frink_is_outside(),
"{kind}: a KL of 0.99 is enormous, and with one reference this instrument still \
cannot say it is a wrong GRAPH — the top-1 half of the verdict is what covers it"
);
}
}
#[test]
fn one_reference_still_gates_a_q8_0_dotted_checkpoint_at_the_unchanged_line() {
for kind in Q8_0_DOTTED {
let quant = DominantQuant::weigh(Some(kind), Some(kind));
let band = band_of(0.0, &[1.1e-2], &quant);
assert_eq!(*band.line(), WrongLine::Absolute(1e-2));
assert!(
band.frink_is_outside(),
"{kind}: 1.1e-2 is over the 1e-2 line and nothing about this class is calibrated \
away"
);
assert!(!band_of(0.0, &[9.9e-3], &quant).frink_is_outside());
}
}
#[test]
fn a_pair_of_references_that_cannot_disagree_does_not_calibrate_anything() {
let identical = vec![0.5f32, 2.0, -1.0, 7.25];
let frink = vec![0.5f32, 2.9, -1.0, 7.25];
let band = Band::measure(&[&identical, &identical], &frink, &kquant());
assert_eq!(*band.line(), WrongLine::Uncalibrated);
assert!(!band.frink_is_outside());
let other = vec![0.5f32, 2.4, -1.0, 7.25];
let band = Band::measure(&[&identical, &other], &frink, &kquant());
assert!(matches!(band.line(), WrongLine::Calibrated { .. }));
}
#[test]
fn the_spread_is_the_larger_of_the_two_kl_directions() {
let peaked = vec![6.0f32, 0.0, 0.0, 0.0];
let flat = vec![0.0f32, 0.0, 0.0, 0.0];
let frink = vec![0.1f32, 0.0, 0.0, 0.0];
let p = metrics::softmax(&peaked);
let q = metrics::softmax(&flat);
let (fwd, back) = (metrics::kl(&p, &q), metrics::kl(&q, &p));
assert!(
back > fwd,
"the fixture must put the larger direction on the reversed pair: {fwd} vs {back}"
);
let band = Band::measure(&[&peaked, &flat], &frink, &kquant());
match band.line() {
WrongLine::Calibrated { spread, .. } => {
assert_eq!(spread.kl, back);
assert_ne!(spread.kl, fwd);
assert_eq!(
spread.between,
(1, 0),
"the reported pair must be the ordered one that produced the number"
);
}
other => panic!("expected a calibrated line, got {other:?}"),
}
}
#[test]
fn the_verdict_does_not_depend_on_which_reference_was_passed_first() {
for &(name, spread_kl, kl_brew, kl_scratch, q8k) in SWEEP {
let quant = if q8k { kquant() } else { q8_0() };
let forward = band_of(spread_kl, &[kl_brew, kl_scratch], &quant);
let reversed = band_of(spread_kl, &[kl_scratch, kl_brew], &quant);
assert_eq!(
forward.frink_is_outside(),
reversed.frink_is_outside(),
"{name}: the verdict moved when the references swapped places"
);
assert_eq!(forward.nearest(), reversed.nearest());
assert_eq!(forward.kl_to_frink(0), reversed.kl_to_frink(1));
}
}
#[test]
fn a_calibrated_line_never_drops_below_the_absolute_one() {
for kl in [1e-13, 1e-6, 1e-3, 9.99e-3, KL_WRONG, 1e-1] {
let line = WrongLine::decide(spread(kl), &kquant())
.value()
.expect("a spread gives a line");
assert!(
line >= KL_WRONG,
"a {kl:e} reference spread produced a {line:e} line"
);
assert!(line >= kl);
}
assert_eq!(
WrongLine::decide(spread(4.2e-2), &kquant()).value(),
Some(4.2e-2)
);
}
}