frink-cli 0.74.0

llama.cpp-style CLI for the Frink inference engine
//! The greedy multi-step decode half of `frink parity`.
//!
//! The first-token comparison reads the last PROMPT position, which is
//! prefill. A decode-side defect (a KV push skipped once the cache
//! grows, a RoPE position off by one in the single-token body, a
//! window evicted one row early, a recurrent state not carried) can
//! produce fluent nonsense while that half stays MATCH. This half asks
//! the dumper for llama.cpp's own greedy decode
//! (`LLAMA_LOGITS_DECODE_STEPS`, `tools/llama_logits.c`) and feeds
//! frink the SAME tokens one at a time, so every step compares two
//! distributions over one context.
//!
//! Teacher-forced rather than free-running: a near tie that flips at
//! step 7 is reported at step 7 and does not turn steps 8 to 32 into a
//! comparison of two different prefixes.
//!
//! # One verdict for both halves
//!
//! Every step is judged by the first-token half's own rule
//! ([`Band::measure`] and [`compare`]), not by a ladder of its own. The
//! decode half used to judge against the primary reference alone with
//! the absolute [`super::calibration::KL_WRONG`] line, which the
//! first-token half refuses to draw for a K-quant checkpoint with one
//! reference (#111), and that is what #776 was. On
//! Qwen3.8-27B-UD-Q4_K_M, a prompt of the 5-token loop `--prompt-tokens`
//! stretches, every step that predicts the loop's fourth token amplifies
//! any change in arithmetic: two builds of the SAME pinned llama.cpp,
//! `GGML_NATIVE` off and on, are 1.2e-2 apart there at a 64-token prompt,
//! 1.2e-1 at 128 and 6.9 (a top-1 flip, 310 at p = 0.56 against 314 at
//! 0.98) at 512, and frink against itself (int8 against f32
//! activations) is 2.0e-1. The single-reference line called that WRONG.
//!
//! # Which references a step is measured against
//!
//! frink is fed the PRIMARY reference's greedy tokens. Each further
//! dumper runs its own greedy decode, so its row `i` shares frink's
//! context only while its argmax at every earlier step equals the
//! primary's. From the first step where it chose differently, its rows
//! describe another prefix and it stops counting: the step where it
//! departed still counts, since both had been fed the same tokens up to
//! there.

use super::calibration::Band;
use super::quant::DominantQuant;
use super::verdict::{compare, Verdict};
use anyhow::Context;
use std::path::{Path, PathBuf};
use std::process::Command;

/// The top-k the step report would intersect. Only the verdict is read,
/// which does not depend on it.
const STEP_TOP_K: usize = 10;

/// One step's verdict, and what it rests on.
pub(super) struct Step {
    pub(super) kl: f64,
    pub(super) top1_ref: usize,
    pub(super) top1_frink: usize,
    pub(super) verdict: Verdict,
    /// References that share frink's context at this step.
    pub(super) n_refs: usize,
    /// The WRONG line for this step, `None` when the instrument has none.
    pub(super) line: Option<f64>,
}

/// Judges every step. `references[0]` is the primary, whose greedy
/// tokens frink was fed; `frink[i]` is frink's row `i`. A secondary
/// reference whose row count or vocabulary differs from the primary's
/// is not comparable at all and counts at no step.
pub(super) fn judge_steps(
    references: &[Vec<Vec<f32>>],
    frink: &[Vec<f32>],
    quant: &DominantQuant,
) -> Vec<Step> {
    let primary = &references[0];
    let fed: Vec<usize> = primary.iter().map(|r| first_argmax(r)).collect();
    let comparable: Vec<&Vec<Vec<f32>>> = references
        .iter()
        .filter(|r| r.len() == primary.len() && r[0].len() == primary[0].len())
        .collect();
    frink
        .iter()
        .enumerate()
        .map(|(i, f)| {
            // Row `i` of a reference that was fed `fed[..i]`.
            let rows: Vec<&[f32]> = comparable
                .iter()
                .filter(|r| (0..i).all(|j| first_argmax(&r[j]) == fed[j]))
                .map(|r| r[i].as_slice())
                .collect();
            let band = Band::measure(&rows, f, quant);
            let report = compare(rows[0], f, STEP_TOP_K, &band);
            Step {
                kl: report.kl_ref_frink,
                top1_ref: report.top1_ref,
                top1_frink: report.top1_frink,
                verdict: report.verdict,
                n_refs: rows.len(),
                line: band.line().value(),
            }
        })
        .collect()
}

/// llama.cpp's greedy decode: `steps` rows of `n_vocab` logits, row 0
/// at the last prompt position.
fn reference_rows(
    dumper: &Path,
    model: &Path,
    prompt: &[u32],
    steps: usize,
    index: usize,
) -> anyhow::Result<Vec<Vec<f32>>> {
    let out_path = std::env::temp_dir().join(format!(
        "frink-parity-decode-{}-{index}.bin",
        std::process::id()
    ));
    let out = Command::new(dumper)
        .env("LLAMA_LOGITS_DECODE_STEPS", steps.to_string())
        .arg(model)
        .arg(&out_path)
        .args(prompt.iter().map(u32::to_string))
        .output()
        .context("running the reference dumper for the decode")?;
    if !out.status.success() {
        anyhow::bail!(
            "reference decode failed: {}",
            String::from_utf8_lossy(&out.stderr)
                .lines()
                .last()
                .unwrap_or("(no stderr)")
        );
    }
    let bytes = std::fs::read(&out_path)
        .with_context(|| format!("reading the reference decode from {}", out_path.display()))?;
    let _ = std::fs::remove_file(&out_path);
    let floats: Vec<f32> = bytes
        .as_chunks::<4>()
        .0
        .iter()
        .map(|c| f32::from_le_bytes(*c))
        .collect();
    if steps == 0
        || floats.is_empty()
        || !floats.len().is_multiple_of(steps)
        || !bytes.len().is_multiple_of(4)
    {
        anyhow::bail!(
            "the reference decode wrote {} bytes, not {steps} whole rows of f32 (a dumper \
             without LLAMA_LOGITS_DECODE_STEPS writes one row: rebuild it with \
             tools/build_llama_logits.sh)",
            bytes.len()
        );
    }
    let n_vocab = floats.len() / steps;
    Ok(floats.chunks(n_vocab).map(<[f32]>::to_vec).collect())
}

/// The first maximum, as the dumper's own argmax picks it: a tie must
/// resolve to the same token on both sides of the comparison.
fn first_argmax(row: &[f32]) -> usize {
    let mut best = 0;
    for (i, &v) in row.iter().enumerate() {
        if v > row[best] {
            best = i;
        }
    }
    best
}

/// Runs the decode comparison and prints one line per step plus a
/// verdict line. Returns the worst step's verdict.
///
/// The primary dumper's decode is load-bearing and its failure is
/// fatal; a further dumper that fails is said out loud and left out, as
/// `collect_references` does for the first-token half.
pub(super) fn run(
    dumpers: &[PathBuf],
    model: &Path,
    prompt: &[u32],
    steps: usize,
    quant: &DominantQuant,
) -> anyhow::Result<Verdict> {
    let mut references = vec![reference_rows(&dumpers[0], model, prompt, steps, 0)?];
    for (i, dumper) in dumpers.iter().enumerate().skip(1) {
        match reference_rows(dumper, model, prompt, steps, i) {
            Ok(rows) => references.push(rows),
            Err(e) => eprintln!(
                "parity: reference [{i}] {} produced no decode ({e:#}); the decode's WRONG \
                 line will be measured without it",
                dumper.display()
            ),
        }
    }
    let reference = &references[0];
    let fed: Vec<usize> = reference[..steps - 1]
        .iter()
        .map(|r| first_argmax(r))
        .collect();
    let prompt: Vec<usize> = prompt.iter().map(|&t| t as usize).collect();
    let frink = crate::verify_engine::teacher_forced_logits(model, &prompt, &fed)
        .context("frink teacher-forced decode")?;
    if frink.len() != reference.len() || frink[0].len() != reference[0].len() {
        anyhow::bail!(
            "decode shapes disagree: llama.cpp {} x {}, frink {} x {}",
            reference.len(),
            reference[0].len(),
            frink.len(),
            frink[0].len()
        );
    }
    let judged = judge_steps(&references, &frink, quant);
    let worst = judged
        .iter()
        .map(|s| s.verdict)
        .max()
        .unwrap_or(Verdict::Match);
    let worst_kl = judged.iter().map(|s| s.kl).fold(0.0, f64::max);
    println!(
        "decode: {} ({steps} greedy steps, frink fed llama.cpp's tokens; worst KL(llama||frink) \
         {worst_kl:.3e}; {})",
        worst.label(),
        line_summary(&judged, references.len())
    );
    for (i, s) in judged.iter().enumerate() {
        if s.verdict != Verdict::Match {
            let line = s
                .line
                .map_or_else(|| "none".to_string(), |l| format!("{l:.3e}"));
            println!(
                "  step {i:>3}  {:8}  KL {:.3e}  top-1 llama {} / frink {}  WRONG line {line} \
                 ({} reference{})",
                s.verdict.label(),
                s.kl,
                s.top1_ref,
                s.top1_frink,
                s.n_refs,
                if s.n_refs == 1 { "" } else { "s" }
            );
        }
    }
    Ok(worst)
}

/// What the WRONG line of this decode rested on, in one clause.
fn line_summary(judged: &[Step], n_dumpers: usize) -> String {
    if judged.iter().all(|s| s.line.is_none()) {
        return "WRONG line NONE: one reference on a K-quant checkpoint, pass --dumper again \
                to measure one (#111); a top-1 flip outside a tie is still WRONG"
            .to_string();
    }
    let shared = judged.iter().filter(|s| s.n_refs > 1).count();
    if n_dumpers > 1 {
        format!(
            "WRONG line per step, {n_dumpers} references, the secondaries sharing frink's \
             context on {shared} of {} steps",
            judged.len()
        )
    } else {
        "WRONG line per step".to_string()
    }
}

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

    fn kquant() -> DominantQuant {
        DominantQuant::weigh(Some("Q4K"), Some("Q4K"))
    }

    fn q8_0() -> DominantQuant {
        DominantQuant::weigh(Some("Q8_0"), Some("Q8_0"))
    }

    fn kl(a: &[f32], b: &[f32]) -> f64 {
        metrics::kl(&metrics::softmax(a), &metrics::softmax(b))
    }

    /// One reference per entry, one step each.
    fn one_step(refs: &[&[f32]], frink: &[f32], quant: &DominantQuant) -> Step {
        let references: Vec<Vec<Vec<f32>>> = refs.iter().map(|r| vec![r.to_vec()]).collect();
        judge_steps(&references, &[frink.to_vec()], quant)
            .pop()
            .expect("one step")
    }

    const PRIMARY: [f32; 3] = [8.0, 0.0, 0.0];
    /// Same top-1 as [`PRIMARY`], over the absolute line from it.
    const FRINK: [f32; 3] = [4.0, 0.0, 0.0];
    /// A second build further from [`PRIMARY`] than [`FRINK`] is.
    const SECOND_BUILD: [f32; 3] = [3.0, 0.0, 0.0];

    #[test]
    fn the_same_row_is_a_match() {
        let r = [0.1f32, 4.0, -1.0];
        assert_eq!(one_step(&[&r], &r, &q8_0()).verdict, Verdict::Match);
    }

    #[test]
    fn a_decisive_different_token_is_wrong() {
        let a = [0.0f32, 8.0, 0.0];
        let b = [0.0f32, 0.0, 8.0];
        assert_eq!(one_step(&[&a], &b, &q8_0()).verdict, Verdict::Wrong);
        // With no line, a flip is still WRONG when the reference's own
        // margin is wider than the mass that moved.
        let c = [0.0f32, 2.0, 8.0];
        assert_eq!(one_step(&[&a], &c, &kquant()).verdict, Verdict::Wrong);
    }

    /// #776: a K-quant step over the absolute line but inside the
    /// distance two llama.cpp builds measure between themselves is the
    /// instrument's noise, not a wrong graph.
    #[test]
    fn a_kquant_step_inside_the_two_build_spread_is_not_wrong() {
        assert!(
            kl(&PRIMARY, &FRINK) > KL_WRONG,
            "the fixture must cross 1e-2"
        );
        assert!(kl(&PRIMARY, &SECOND_BUILD) > kl(&PRIMARY, &FRINK));
        let step = one_step(&[&PRIMARY, &SECOND_BUILD], &FRINK, &kquant());
        assert_eq!(step.verdict, Verdict::Drift);
        assert_eq!(step.n_refs, 2);
        assert!(step.line.is_some_and(|l| l > KL_WRONG));
        // With one reference there is no line to cross at all.
        let solo = one_step(&[&PRIMARY], &FRINK, &kquant());
        assert_eq!((solo.verdict, solo.line), (Verdict::Drift, None));
    }

    /// The other side of the same rule: where llama.cpp dots against
    /// Q8_0 (and on F32) the line stays the absolute one.
    #[test]
    fn an_f32_or_q8_0_step_over_the_absolute_line_is_wrong() {
        let step = one_step(&[&PRIMARY], &FRINK, &q8_0());
        assert_eq!(step.line, Some(KL_WRONG));
        assert_eq!(step.verdict, Verdict::Wrong);
    }

    /// A secondary reference runs its own greedy decode, so once its
    /// argmax parts from the primary's its later rows are another
    /// prefix and must not widen the line.
    #[test]
    fn a_secondary_stops_counting_after_its_greedy_tokens_diverge() {
        let primary = vec![PRIMARY.to_vec(), PRIMARY.to_vec(), PRIMARY.to_vec()];
        // Agrees at step 0, picks token 1 at step 1, so step 2 is not
        // the context frink was fed.
        let secondary = vec![
            SECOND_BUILD.to_vec(),
            vec![0.0, 8.0, 0.0],
            SECOND_BUILD.to_vec(),
        ];
        let frink = vec![FRINK.to_vec(); 3];
        let steps = judge_steps(&[primary, secondary], &frink, &kquant());
        let n_refs: Vec<usize> = steps.iter().map(|s| s.n_refs).collect();
        // Step 1, where it departed, still shares the context.
        assert_eq!(n_refs, [2, 2, 1]);
        assert_eq!(steps[2].line, None, "one reference left on a K-quant");
    }

    #[test]
    fn the_worst_step_orders_above_the_rest() {
        assert!(Verdict::Wrong > Verdict::TieFlip);
        assert!(Verdict::TieFlip > Verdict::Drift);
        assert!(Verdict::Drift > Verdict::Match);
    }

    #[test]
    fn a_tie_resolves_to_the_first_maximum_like_the_dumper() {
        assert_eq!(first_argmax(&[1.0, 3.0, 3.0]), 1);
    }
}