frink-cli 0.75.0

llama.cpp-style CLI for the Frink inference engine
//! What `parity` prints about the first-token comparison: the run, each
//! reference, the WRONG line and the verdict's explanation.

use super::calibration::{Band, WrongLine};
use super::quant::DominantQuant;
use super::reference::Reference;
use super::verdict::{Report, Verdict};
use std::path::Path;

/// What the run WAS, as opposed to what it found. Grouped because a
/// print function taking eight positional arguments is one careless
/// edit away from two of them being swapped, and `&str` next to `&str`
/// swaps silently.
pub(super) struct Run<'a> {
    pub(super) model: &'a str,
    pub(super) n_tokens: usize,
    pub(super) top_k: usize,
    pub(super) backend: &'a str,
    /// Where the references ran: `cpu`, or `ngl N` under LLAMA_LOGITS_NGL.
    pub(super) reference: &'a str,
}

pub(super) fn print_report(
    run: &Run<'_>,
    quant: &DominantQuant,
    references: &[Reference],
    band: &Band,
    r: &Report,
) {
    let Run {
        model,
        n_tokens,
        top_k: k,
        backend,
        reference: ref_side,
    } = *run;
    let name = Path::new(model)
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| model.to_string());
    let verdict = r.verdict.label();
    println!(
        "parity {name}: {verdict} ({n_tokens}-token prompt, first-token distribution, \
         frink {backend} vs llama.cpp {ref_side})"
    );
    // Named on every row, not only when it surprises. Two libllama
    // builds gave the same checkpoint DRIFT and WRONG (#102), and the
    // difference between the runs was invisible in this report.
    for (i, reference) in references.iter().enumerate() {
        let who = match reference.libllama.as_deref() {
            Some(p) => p.to_string(),
            None => "(this dumper predates the `libllama` line — rebuild with \
                     tools/build_llama_logits.sh)"
                .to_string(),
        };
        println!(
            "  reference [{i}]     {who}   KL(llama||frink) {:.3e}",
            band.kl_to_frink(i)
        );
    }
    print_wrong_line(quant, references, band);
    println!(
        "  KL(llama||frink) {:.3e} nats   KL(frink||llama) {:.3e} nats   [reference 0]",
        r.kl_ref_frink, r.kl_frink_ref
    );
    println!(
        "  total variation   {:.3e}        max |delta p|     {:.3e}",
        r.total_variation, r.max_prob_delta
    );
    println!(
        "  top-1  llama {} / frink {}   (llama's top-1 is rank {} for frink)",
        r.top1_ref, r.top1_frink, r.ref_top1_rank_in_frink
    );
    println!(
        "  top-{k} overlap    {}/{k}          llama top-2 margin {:.3e}",
        r.topk_overlap, r.ref_top2_margin
    );
    // Printed for every verdict, not only TIE-FLIP: how close the
    // argmax call was is what says whether the NEXT prompt would flip
    // too, and a row that did not flip is the evidence that a row which
    // did was one prompt's luck.
    println!(
        "  top-1/top-2 gap   {:+.3e} logits ({} ulps)   frink on the same pair {:+.3e}",
        r.ref_top2_logit_gap, r.ref_top2_logit_gap_ulps, r.frink_gap_on_ref_pair
    );
    match r.verdict {
        Verdict::Match => println!("  same distribution to within f32 accumulation-order noise."),
        // `q8k_dotted` is the SAME predicate on the SAME value the
        // uncalibrated WRONG line reads, so the explanation and the
        // line are never about different tensors (#109).
        Verdict::Drift => match quant.label().filter(|_| quant.q8k_dotted()) {
            // Expected, with a named cause. Saying "go run a per-layer
            // divergence" here would send the reader after a bug that
            // is not there.
            Some(q) => println!(
                "  same token. The distributions differ by more than summation order. For \
                 {q}, llama.cpp quantizes the ACTIVATION to Q8_K (`vec_dot_type`) and frink \
                 does the same, bit for bit; what remains is the order of the integer \
                 reductions and the repack GEMMs, listed in docs/adr/0009-numerics-follow-ggml.md. \
                 A WRONG verdict on {q} is a bug, not this."
            ),
            None => println!(
                "  same token, but the distributions differ by more than accumulation order \
                 explains — worth a per-layer divergence run before trusting this row."
            ),
        },
        Verdict::TieFlip => {
            println!(
                "  top-1 differs, but llama's own top-2 margin ({:.3e}) is under the observed \
                 per-token noise ({:.3e}): a tie swapped, not a wrong graph.",
                r.ref_top2_margin, r.max_prob_delta
            );
            // The magnitude, in the units the claim is made in. Without
            // it "tie" is an assertion; with it a reader can check
            // whether the two candidates really are inseparable or
            // whether a real difference merely landed near the argmax.
            println!(
                "  the two candidates are {} ulps apart in llama's logits ({:+.3e} absolute); \
                 frink puts the same pair {:+.3e} apart, so the flip is a sign change of a gap \
                 this size — not a redistribution.",
                r.ref_top2_logit_gap_ulps, r.ref_top2_logit_gap, r.frink_gap_on_ref_pair
            );
        }
        Verdict::Wrong => println!(
            "  the graphs disagree. This is not sampling noise and not a tie: something in \
             the forward pass differs."
        ),
    }
}

/// The WRONG line, and where it came from.
///
/// Printed on EVERY row, including the ones that are nowhere near it.
/// A verdict whose line is invisible cannot be audited, and the line is
/// no longer a constant a reader could look up.
fn print_wrong_line(quant: &DominantQuant, references: &[Reference], band: &Band) {
    match band.line() {
        WrongLine::Calibrated { spread, line } => {
            let (a, b) = spread.between;
            println!(
                "  WRONG line        {line:.3e}  measured: references [{a}] and [{b}] disagree \
                 with EACH OTHER by {:.3e} on this checkpoint",
                spread.kl
            );
            println!(
                "                    frink's nearest reference is {:.3e}, {:.0}% of the line",
                band.nearest(),
                100.0 * band.nearest() / line
            );
        }
        WrongLine::Absolute(line) => println!(
            "  WRONG line        {line:.3e}  absolute: llama.cpp's own build-to-build spread on \
             {} is 0 to 4.6e-4, two orders under it",
            quant.label().unwrap_or("this checkpoint")
        ),
        WrongLine::Uncalibrated => {
            println!(
                "  WRONG line        NONE — {} is dotted against Q8_K activations, and two \
                 builds of llama.cpp disagree with EACH OTHER by up to 3.5e-2 there (#111), so \
                 no constant can mean `the graphs disagree`.",
                quant.label().unwrap_or("this checkpoint")
            );
            println!(
                "                    Pass --dumper a second time, built against another \
                 libllama, to measure this checkpoint's own line. ({} reference in this run.)",
                references.len()
            );
        }
    }
}

/// Which activations frink's CPU matmuls took on this run: int8 (each
/// kind's ggml `vec_dot_type`, as llama.cpp's CPU backend) or f32. A
/// verdict means something different under each, so the report says.
/// Prefill and decode are named apart because a host once quantized one
/// and not the other (#721); they now share the one switch.
pub(super) fn int_dot_line() -> String {
    let side = if frink_core::weight_matrix::cpu_int_dot_enabled() {
        "int8"
    } else {
        "f32"
    };
    format!(
        "frink activations prefill {side}, decode {side} (FRINK_CPU_INT_DOT, as `frink run` sets it)"
    )
}