frink-cli 0.74.0

llama.cpp-style CLI for the Frink inference engine
//! The verdict: frink's first-token distribution scored against the
//! primary reference, with the WRONG rung taken from the calibrated band.

use super::calibration::Band;
use super::{metrics, KL_NOISE};

/// Ordered worst last, so the decode half's worst step is a `max`.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub(super) enum Verdict {
    /// Same distribution to within accumulation-order noise.
    Match,
    /// Same top-1, but the distributions drift more than noise explains.
    Drift,
    /// Top-1 differs, and the reference's own top-2 margin is so small
    /// that noise of the observed size is enough to swap them. This is
    /// NOT evidence of a wrong graph and must not be reported as one.
    TieFlip,
    /// Different distributions.
    Wrong,
}

impl Verdict {
    pub(super) fn label(self) -> &'static str {
        match self {
            Verdict::Match => "MATCH",
            Verdict::Drift => "DRIFT",
            Verdict::TieFlip => "TIE-FLIP",
            Verdict::Wrong => "WRONG",
        }
    }
}

pub(super) struct Report {
    pub(super) verdict: Verdict,
    pub(super) kl_ref_frink: f64,
    pub(super) kl_frink_ref: f64,
    pub(super) total_variation: f64,
    pub(super) max_prob_delta: f64,
    pub(super) top1_ref: usize,
    pub(super) top1_frink: usize,
    /// Where the reference's top-1 sits in frink's ordering (0 = top).
    pub(super) ref_top1_rank_in_frink: usize,
    /// p1 - p2 in the reference distribution: how close the call was.
    pub(super) ref_top2_margin: f64,
    /// The same call in LOGIT space, on both sides, and how many
    /// representable f32 values separate the reference's two
    /// candidates.
    ///
    /// A TIE-FLIP verdict is a claim about magnitude — "the two
    /// candidates are closer than the arithmetic can resolve" — and
    /// probability margin does not settle it, because softmax over a
    /// 128k vocabulary turns a wide logit gap into a small probability
    /// gap whenever the distribution is flat. The gap in ulps is the
    /// claim's own units: single digits is a tie, millions is a
    /// difference that happens to sit near the argmax
    /// ([#103](https://github.com/antonellof/frink/issues/103)).
    pub(super) ref_top2_logit_gap: f32,
    pub(super) ref_top2_logit_gap_ulps: i64,
    /// The same gap as frink sees it, signed by the reference's
    /// ordering: negative means frink ranks them the other way round.
    pub(super) frink_gap_on_ref_pair: f32,
    pub(super) topk_overlap: usize,
}

/// Scores frink against the PRIMARY reference, and takes the WRONG
/// rung from `band`.
///
/// The split is deliberate. MATCH and DRIFT are statements about the
/// reference the report names — "indistinguishable from it", "differs
/// from it by more than summation order" — and they move with it, which
/// is correct: they describe a comparison, not a defect. WRONG is a
/// claim about frink itself, so it is the one rung that must not
/// change with which libllama happens to be installed (#102), and
/// `band` is what makes it not.
pub(super) fn compare(ref_logits: &[f32], frink_logits: &[f32], k: usize, band: &Band) -> Report {
    let p = metrics::softmax(ref_logits);
    let q = metrics::softmax(frink_logits);

    // The primary's KL comes from the band rather than being recomputed
    // here: one number, one owner. Two evaluations would be two places
    // for the guarded-zero convention to drift apart.
    let kl_pq = band.kl_to_frink(0);
    let kl_qp = metrics::kl(&q, &p);
    let (tv, max_delta) = metrics::total_variation(&p, &q);

    let ref_order = metrics::order_desc(&p);
    let fx_order = metrics::order_desc(&q);
    let top1_ref = ref_order[0];
    let top1_frink = fx_order[0];
    let ref_top1_rank_in_frink = fx_order.iter().position(|&i| i == top1_ref).unwrap_or(0);
    let (ref_top2_margin, ref_top2_logit_gap, ref_top2_logit_gap_ulps, frink_gap_on_ref_pair) =
        if ref_order.len() > 1 {
            let (i1, i2) = (ref_order[0], ref_order[1]);
            (
                p[i1] - p[i2],
                ref_logits[i1] - ref_logits[i2],
                metrics::ulps_between(ref_logits[i1], ref_logits[i2]),
                // Same pair, frink's numbers, keeping the reference's
                // order: the sign is the flip itself.
                frink_logits[i1] - frink_logits[i2],
            )
        } else {
            (1.0, 0.0, 0, 0.0)
        };

    let k = k.min(ref_order.len());
    let ref_top: std::collections::HashSet<usize> = ref_order[..k].iter().copied().collect();
    let topk_overlap = fx_order[..k].iter().filter(|i| ref_top.contains(i)).count();

    // ONE predicate, read by both branches below. They were two
    // spellings of `kl_pq < kl_wrong` before, which is the shape this
    // repo keeps paying for.
    let outside = band.frink_is_outside();
    let verdict = if top1_ref == top1_frink {
        if kl_pq < KL_NOISE {
            Verdict::Match
        } else if !outside {
            Verdict::Drift
        } else {
            Verdict::Wrong
        }
    } else if !outside && ref_top2_margin <= max_delta {
        // The two engines put nearly the same mass on both candidates and
        // the reference itself could barely separate them. Calling this a
        // failure would make the instrument cry wolf on exactly the case
        // that motivated building it.
        Verdict::TieFlip
    } else {
        Verdict::Wrong
    };

    Report {
        verdict,
        kl_ref_frink: kl_pq,
        kl_frink_ref: kl_qp,
        total_variation: tv,
        max_prob_delta: max_delta,
        top1_ref,
        top1_frink,
        ref_top1_rank_in_frink,
        ref_top2_margin,
        ref_top2_logit_gap,
        ref_top2_logit_gap_ulps,
        frink_gap_on_ref_pair,
        topk_overlap,
    }
}

#[cfg(test)]
mod tests {
    use super::super::calibration::KL_WRONG;
    use super::super::quant::DominantQuant;
    use super::*;

    /// A band from ONE reference, which is what every pre-existing
    /// verdict test is about: the KL to that reference IS the nearest,
    /// so these exercise the ladder and not the calibration.
    fn one_reference(reference: &[f32], frink: &[f32]) -> Band {
        Band::measure(
            &[reference],
            frink,
            &DominantQuant::weigh(Some("Q8_0"), Some("Q8_0")),
        )
    }

    #[test]
    fn identical_logits_are_a_match() {
        let l = vec![0.1f32, 5.0, -2.0, 3.3];
        let r = compare(&l, &l, 3, &one_reference(&l, &l));
        assert_eq!(r.verdict, Verdict::Match);
        assert!(r.kl_ref_frink < 1e-12, "KL was {}", r.kl_ref_frink);
        assert_eq!(r.top1_ref, r.top1_frink);
        assert_eq!(r.topk_overlap, 3);
        assert_eq!(r.ref_top1_rank_in_frink, 0);
    }

    #[test]
    fn a_different_graph_is_reported_wrong() {
        // Mass moved to a different token entirely.
        let a = vec![0.0f32, 8.0, 0.0, 0.0];
        let b = vec![0.0f32, 0.0, 8.0, 0.0];
        let r = compare(&a, &b, 2, &one_reference(&a, &b));
        assert_eq!(r.verdict, Verdict::Wrong);
        assert_ne!(r.top1_ref, r.top1_frink);
    }

    #[test]
    fn a_near_tie_that_swaps_is_a_tie_flip_not_a_failure() {
        // Two candidates the reference itself can barely separate: the
        // whole point of measuring the distribution instead of the draw.
        let a = vec![-10.0f32, 2.000_01, 2.0];
        let b = vec![-10.0f32, 2.0, 2.000_01];
        let r = compare(&a, &b, 2, &one_reference(&a, &b));
        assert_eq!(r.verdict, Verdict::TieFlip);
        assert_ne!(r.top1_ref, r.top1_frink);
        // Both engines still agree on WHICH two tokens are in play.
        assert_eq!(r.topk_overlap, 2);
    }

    #[test]
    fn same_top1_with_a_shifted_tail_is_drift_not_a_match() {
        // Top-1 survives, but the rest of the distribution has moved
        // further than accumulation order explains.
        let a = vec![6.0f32, 1.0, 1.0, 1.0];
        let b = vec![6.0f32, 1.0, 1.0, 2.0];
        let r = compare(&a, &b, 4, &one_reference(&a, &b));
        assert_eq!(r.verdict, Verdict::Drift);
        assert_eq!(r.top1_ref, r.top1_frink);
        assert!(r.kl_ref_frink >= KL_NOISE && r.kl_ref_frink < KL_WRONG);
    }

    #[test]
    fn a_uniform_logit_shift_is_invisible_because_softmax_is_shift_invariant() {
        // Guards against ever "fixing" a false alarm by comparing raw
        // logits: an additive constant is not a disagreement.
        let a = vec![0.5f32, 1.5, -3.0];
        let b: Vec<f32> = a.iter().map(|v| v + 7.25).collect();
        let r = compare(&a, &b, 3, &one_reference(&a, &b));
        assert_eq!(r.verdict, Verdict::Match);
    }

    /// The reported top-1/top-2 gap describes the pair the REFERENCE
    /// picked, on both sides, so the flip shows up as a sign change.
    ///
    /// Reporting frink's own top-2 pair instead would compare two
    /// different questions and could print two positive gaps for a run
    /// whose whole finding is that the order reversed.
    #[test]
    fn the_reported_gap_is_the_same_pair_on_both_sides_and_flips_sign() {
        let a = vec![-10.0f32, 2.000_01, 2.0];
        let b = vec![-10.0f32, 2.0, 2.000_01];
        let r = compare(&a, &b, 2, &one_reference(&a, &b));
        assert_eq!(r.verdict, Verdict::TieFlip);
        assert!(
            r.ref_top2_logit_gap > 0.0,
            "the reference ranks its own pair the right way round"
        );
        assert!(
            r.frink_gap_on_ref_pair < 0.0,
            "frink ranks the SAME pair the other way: gap {}",
            r.frink_gap_on_ref_pair
        );
        assert!(
            r.ref_top2_logit_gap_ulps > 0 && r.ref_top2_logit_gap_ulps < 1_000,
            "a tie must be a handful of ulps, got {}",
            r.ref_top2_logit_gap_ulps
        );
    }

    /// THE VERDICT THAT #102 AND #111 ARE ABOUT: one frink, one file,
    /// two libllama, and the answer must not depend on which one the
    /// report happens to name first.
    ///
    /// The fixture is the shape Qwen3-0.6B `--pure` Q4_K_S has: the two
    /// references sit further from each other than frink sits from the
    /// nearer of them. Under the old absolute constant this read DRIFT
    /// against one and WRONG against the other. It must now read the
    /// same either way round, and it must still be a DRIFT rather than
    /// a MATCH, because the distributions really have moved.
    #[test]
    fn the_verdict_is_the_same_whichever_reference_the_report_names() {
        // frink reproduces reference A closely; B is off on its own,
        // and A and B are further apart than frink is from A.
        let a = vec![0.0f32, 4.0, 1.0, 0.5];
        let b = vec![0.0f32, 2.5, 1.0, 0.5];
        let frink = vec![0.0f32, 3.6, 1.0, 0.5];
        let quant = DominantQuant::weigh(Some("Q4K"), Some("Q4K"));

        let ab = Band::measure(&[&a, &b], &frink, &quant);
        let ba = Band::measure(&[&b, &a], &frink, &quant);

        let first = compare(&a, &frink, 4, &ab);
        let second = compare(&b, &frink, 4, &ba);
        assert_eq!(first.verdict, Verdict::Drift);
        assert_eq!(second.verdict, Verdict::Drift);
        // Both really did drift — neither is a MATCH that would make
        // the agreement trivial.
        assert!(first.kl_ref_frink > KL_NOISE && second.kl_ref_frink > KL_NOISE);
        // The printed KL is still the named reference's, which is the
        // whole reason both numbers appear in the report.
        assert_ne!(first.kl_ref_frink, second.kl_ref_frink);

        // With ONE reference and a K-quant body there is no line at
        // all, so the same B-vs-frink comparison cannot be a WRONG
        // either — even though its KL is an order of magnitude over
        // the 3.008e-2 constant that used to be the line.
        let alone = Band::measure(&[&b], &frink, &quant);
        let solo = compare(&b, &frink, 4, &alone);
        assert!(solo.kl_ref_frink > 3.008e-2, "{}", solo.kl_ref_frink);
        assert_eq!(solo.verdict, Verdict::Drift);
    }

    /// THE WRONG RUNG READS THE NEAREST REFERENCE, NOT THE ONE THE
    /// REPORT NAMES.
    ///
    /// This is the whole change, in the one geometry that separates it
    /// from the old rule: the KL printed against the named reference is
    /// OVER that checkpoint's line, while frink is nowhere near being
    /// the outlier — the two references disagree with each other, and
    /// frink reproduces the other one to within a fiftieth of their
    /// disagreement. Qwen3-0.6B `--pure` Q4_K_S is this shape at
    /// smaller scale (3.889e-2 printed, 3.514e-2 spread, 1.975e-2 to
    /// the other build), and deciding it on the printed number is what
    /// made one file DRIFT on one bottle and WRONG on another (#102,
    /// #111).
    ///
    /// The report still prints the large number. It is a true statement
    /// about the named reference; it is just not evidence about frink.
    #[test]
    fn the_wrong_rung_is_decided_by_the_nearest_reference_not_the_one_being_reported() {
        let a = vec![0.0f32, 4.0, 1.0, 0.5];
        let b = vec![0.0f32, 2.0, 1.0, 0.5];
        let frink = vec![0.0f32, 3.8, 0.2, 0.5];
        let quant = DominantQuant::weigh(Some("Q4K"), Some("Q4K"));

        // B is the primary, so B's KL is what the report carries.
        let band = Band::measure(&[&b, &a], &frink, &quant);
        let line = band.line().value().expect("two references give a line");
        assert!(
            band.kl_to_frink(0) > line,
            "the fixture must put the PRIMARY over the line, else this proves nothing: {:.4e} \
             against {line:.4e}",
            band.kl_to_frink(0)
        );
        assert!(band.nearest() < line);

        let r = compare(&b, &frink, 4, &band);
        assert_eq!(r.verdict, Verdict::Drift);
        assert!(
            r.kl_ref_frink > line,
            "the printed KL is still the named reference's"
        );
    }

    /// A WRONG still happens, and it happens to a calibrated band.
    ///
    /// The rule is a relaxation on the checkpoints measured here, so a
    /// test suite that only proved things are no longer WRONG would be
    /// consistent with a verdict that can never fire.
    #[test]
    fn a_frink_further_from_every_reference_than_they_are_from_each_other_is_wrong() {
        // Two references a hair apart, frink a long way from both.
        let a = vec![0.0f32, 4.00, 1.0, 0.5];
        let b = vec![0.0f32, 3.99, 1.0, 0.5];
        let frink = vec![0.0f32, 1.00, 1.0, 0.5];
        let quant = DominantQuant::weigh(Some("Q4K"), Some("Q4K"));
        let band = Band::measure(&[&a, &b], &frink, &quant);
        assert!(band.frink_is_outside());
        assert_eq!(compare(&a, &frink, 4, &band).verdict, Verdict::Wrong);
    }
}