frink-cli 0.72.0

llama.cpp-style CLI for the Frink inference engine
//! Answer parity against llama.cpp, measured on the distribution rather
//! than on sampled text.
//!
//! Why this exists: `frink verify` compares frink-CPU against
//! frink-Metal, so it can prove the two frink backends agree with each
//! other while both disagree with the reference implementation. The
//! quality gate in `4dc195e5:docs/plans/llama-cpp-parity-push.md` says a row is
//! only closed when "answers match llama", and nothing measured that.
//!
//! Why not greedy text: it was tried. With tokenization matched by hand
//! (6 tokens on both sides) frink and llama.cpp still diverged after
//! about three tokens on TinyLlama Q8_0, a model with no exotic graph
//! features. Greedy text is a chain of argmaxes, so ordinary
//! last-bit numeric drift flips one token and every token after it is
//! then conditioned on different input. A text diff cannot separate "the
//! graph is wrong" from "two near-tied logits swapped", and those are
//! the only two hypotheses worth telling apart.
//!
//! So this compares the FIRST-TOKEN distribution at the last prompt
//! position: one forward pass per engine, no sampling, no feedback. The
//! same token ids are fed to both sides, which removes the tokenizer
//! from the experiment — frink tokenizes, and llama.cpp is handed the
//! resulting ids.
//!
//! Removing the tokenizer from THIS experiment is right, and for years
//! it also meant nothing tested the tokenizer at all: a single hardcoded
//! pre-tokenizer regex mistokenized every digit run of four or more and
//! every whitespace run of two or more, on Llama-3.x, Qwen, DeepSeek and
//! SmolLM, and the repo's only cross-engine oracle was structurally
//! unable to see it. So `parity` now runs a SECOND comparison first, in
//! [`tokenize`]: same file, same library, frink's token ids against
//! llama.cpp's for a corpus built out of the inputs the pre-tokenizers
//! actually disagree on. It runs before the logit comparison because a
//! tokenizer divergence means the distribution comparison below is
//! measuring two different prompts.
//!
//! The reference side is a small C program (`tools/llama_logits.c`)
//! linked against the installed `libllama`, in the same spirit as the
//! IQ-tier goldens, which link ggml's own `ggml-quants.c` rather than
//! re-reading the format spec. A reference you re-implemented is not a
//! reference. Build it with `tools/build_llama_logits.sh`.
//!
//! `--dumper` may be given MORE THAN ONCE, each pointing at a dumper
//! built against a different libllama. That is not a convenience: it is
//! what turns the WRONG verdict from a fitted constant into a
//! measurement this run makes for itself. See [`calibration`].

mod calibration;
mod decode;
mod dump;
mod layers;
mod metrics;
mod quant;
mod reference;
mod report;
mod tokenize;
mod verdict;

use anyhow::Context;
use calibration::{Band, KL_WRONG};
use quant::DominantQuant;
use reference::{collect_references, dumper_paths, reference_ngl};
use report::{int_dot_line, print_report, Run};
use std::path::Path;
use verdict::{compare, Verdict};

/// Prompt held fixed so runs are comparable across models and sessions.
const PROMPT: &str = "The capital of France is";

/// Below this KL the two engines are doing the same arithmetic to within
/// f32 accumulation-order noise. Chosen as the scale at which a
/// reordered reduction over a few thousand terms lands: it is a noise
/// floor, not a quality target.
///
/// A statement about the PRIMARY reference, unlike the WRONG line: the
/// report's numbers are that reference's, and "indistinguishable from
/// the reference you named" is what MATCH has always meant.
const KL_NOISE: f64 = 1e-3;

/// The verdict ladder, checked at COMPILE time.
///
/// One rung is a constant now — [`KL_WRONG`], the floor under every
/// calibrated line — and the other is measured per checkpoint, so the
/// only ordering left to enforce is that MATCH is tighter than the
/// tightest possible WRONG. The three constants this assert used to
/// hold in order (`KL_REFERENCE_BUILD_SPREAD_KQUANT`,
/// `KL_WRONG_Q8K_DOTTED` and its 1.1 margin) are DELETED: a rule that
/// measures its own line has no thresholds left to keep in step. See
/// [`calibration`] for why keeping them was not an option.
const _: () = {
    assert!(
        KL_NOISE < KL_WRONG,
        "MATCH must be tighter than the tightest WRONG line"
    );
};

pub struct ParityArgs {
    pub model: String,
    pub prompt: Option<String>,
    pub prompt_tokens: Option<usize>,
    pub top_k: usize,
    /// Paths to compiled reference dumpers. The first is the PRIMARY —
    /// the one every printed number is about. Any further ones exist to
    /// measure how much llama.cpp disagrees with itself on this
    /// checkpoint, which is what the WRONG line is made of.
    pub dumper: Vec<String>,
    /// Prefix to write every compared logit vector under. See [`dump`].
    pub dump_logits: Option<String>,
    /// Directory to dump both engines' per-layer intermediates under,
    /// then compare. See [`layers`].
    pub dump_tensors: Option<String>,
    /// Token ids to compare on instead of tokenizing a prompt. The
    /// tokenizer half is skipped, said so, and not counted as a pass.
    pub tokens: Option<Vec<u32>>,
    /// Greedy decode steps to compare after the first token; 0 skips
    /// the decode half. See [`decode`].
    pub decode_steps: usize,
}

pub fn run(args: ParityArgs) -> anyhow::Result<()> {
    // frink's side runs the arithmetic `frink run` and the server run:
    // the integer-dot tier wherever they turn it on. Without this the
    // library default held, every CPU matmul dotted f32 activations
    // against dequantized weights, and the comparison was of a path no
    // user takes. On a pure Q2_K file that path differs from llama.cpp's
    // Q8_K one by 3.6e-3 relative at `Qcur-0` and 1.9e-2 at `Vcur-0`,
    // from bit-identical inputs (#584). `FRINK_CPU_INT_DOT=0` still
    // selects the f32 path, as it does for `frink run`.
    //
    // SAFETY: `main` has started no thread before dispatching here; the
    // rayon pool and the backends start in the prefill below.
    unsafe { frink_core::weight_matrix::default_cpu_int_dot_on() };

    let path = crate::pull::resolve_model_path(&args.model)?;

    // Resolved before anything expensive runs: a missing dumper is the
    // most common way this command fails, and finding that out after a
    // multi-second model load helps nobody.
    let dumpers = dumper_paths(&args.dumper)?;

    // The tokenizer comparison goes first. It is vocab-only on both
    // sides, so it costs a fraction of the prefill below, and a
    // divergence here means the logit numbers underneath it were
    // computed from a prompt the two engines do not even agree on.
    // Only the primary reference tokenizes: the tokenizer half is not
    // the half that needs calibrating.
    let tokens_report = match args.tokens {
        Some(_) => None,
        None => tokenize::run(&dumpers[0], Path::new(&path))?,
    };
    match &tokens_report {
        Some(r) => tokenize::print_report(r),
        None if args.tokens.is_some() => {
            println!("tokenizer: SKIPPED — --tokens gave the ids, so there is no text to tokenize.")
        }
        None => println!(
            "tokenizer: SKIPPED — the installed libllama cannot load this checkpoint, so it has \
             no tokenization to compare against. The logit comparison below will fail for the \
             same reason."
        ),
    }
    println!();

    let prompt = args.prompt.clone().unwrap_or_else(|| PROMPT.to_string());

    // Opened before the prefill, which is the pass the hooks write.
    let dump_tensors = args.dump_tensors.as_deref().map(Path::new);
    if let Some(root) = dump_tensors {
        frink_models::tensor_dump::dump_to(&layers::frink_dir(root))
            .with_context(|| format!("opening the tensor dump under {}", root.display()))?;
    }

    let (tokens, frink_logits) = match &args.tokens {
        Some(ids) if ids.is_empty() => anyhow::bail!("--tokens is empty"),
        Some(ids) => {
            let ids_usize: Vec<usize> = ids.iter().map(|&t| t as usize).collect();
            let mut rows =
                crate::verify_engine::teacher_forced_logits(Path::new(&path), &ids_usize, &[])
                    .context("frink prefill")?;
            (ids.clone(), rows.swap_remove(0))
        }
        None => crate::verify_engine::prefill_logits(
            Path::new(&path),
            &prompt,
            frink_models::tokenizer::SpecialTokens::Parse,
            args.prompt_tokens,
        )
        .context("frink prefill")?,
    };

    // The reference runs llama.cpp's CPU path (n_gpu_layers = 0) unless
    // LLAMA_LOGITS_NGL offloads it, because frink's CPU path is the one
    // cross-validated against NumPy. Say which side each ran on rather
    // than leaving it to the environment: a Metal-vs-llama-CPU verdict
    // has two possible causes and must not be read as one.
    println!("{}", int_dot_line());
    let backend = frink_core::weight_matrix::active_backend();
    let ref_ngl = reference_ngl(std::env::var("LLAMA_LOGITS_NGL").ok().as_deref());
    let ref_side = ref_ngl.map_or_else(|| "cpu".to_string(), |n| format!("ngl {n}"));
    if let Some(n) = ref_ngl {
        eprintln!(
            "parity: frink ran on {}; LLAMA_LOGITS_NGL={n} offloads each reference whose \
             libllama has a GPU backend and leaves the others on its CPU, so with a Metal \
             and a CPU dumper the WRONG line is the two backends' own distance (#714).",
            backend.as_str()
        );
    } else if backend != frink_core::kernel_registry::Backend::Cpu {
        eprintln!(
            "parity: frink ran on {}, the reference on llama.cpp CPU — a non-MATCH verdict \
             here could be either engine or the backend difference. Run with FRINK_METAL=0 \
             FRINK_CUDA=0 to isolate the engines.",
            backend.as_str()
        );
    }

    let references = collect_references(&dumpers, &path, &tokens, frink_logits.len())?;

    // Dumped BEFORE the verdict is computed, so a run that ends in the
    // `bail!` below still leaves the evidence behind. The whole reason
    // to dump is to investigate a bad verdict; losing the vectors
    // exactly when the verdict is bad would defeat it.
    let ref_logits: Vec<&[f32]> = references.iter().map(|r| r.logits.as_slice()).collect();
    if let Some(prefix) = args.dump_logits.as_deref() {
        for p in dump::write(prefix, &tokens, &ref_logits, &frink_logits)? {
            println!("wrote {}", p.display());
        }
        println!();
    }

    // ONE value, read by the DRIFT message and by the uncalibrated
    // fallback of the WRONG line. Deriving it twice was #109.
    let gguf = frink_gguf::GgufFile::open(&path).ok();
    let quant = DominantQuant::of(gguf.as_ref().map_or(&[][..], |f| &f.tensors));

    let band = Band::measure(&ref_logits, &frink_logits, &quant);
    let report = compare(ref_logits[0], &frink_logits, args.top_k, &band);
    print_report(
        &Run {
            model: &args.model,
            n_tokens: tokens.len(),
            top_k: args.top_k,
            backend: backend.as_str(),
            reference: &ref_side,
        },
        &quant,
        &references,
        &band,
        &report,
    );
    if let Some(root) = dump_tensors {
        layers::run(&dumpers[0], &path, &tokens, root, ref_logits[0])?;
    }

    // Both halves are reported before either is allowed to abort the
    // command: a run that printed the tokenizer divergence and then
    // exited would hide the logit numbers that say whether the graph is
    // also wrong, and those are two separate pieces of work.
    let mut failures: Vec<String> = Vec::new();
    if tokens_report.as_ref().is_some_and(|r| r.diverged()) {
        failures.push("frink and llama.cpp tokenize the same text differently".to_string());
    }
    if report.verdict == Verdict::Wrong {
        failures.push(format!(
            "frink disagrees with llama.cpp beyond numeric noise (KL {:.3e} nats to its \
             nearest reference)",
            band.nearest()
        ));
    }
    if args.decode_steps > 0 {
        println!();
        let worst = decode::run(&dumpers[0], Path::new(&path), &tokens, args.decode_steps)?;
        if worst == decode::StepVerdict::Wrong {
            failures.push("frink's greedy decode disagrees with llama.cpp's".to_string());
        }
    }
    if !failures.is_empty() {
        anyhow::bail!("{}", failures.join("; "));
    }
    Ok(())
}