frink-cli 0.75.0

llama.cpp-style CLI for the Frink inference engine
//! The reference side of `parity`: which dumper binaries to run, where
//! they run (`LLAMA_LOGITS_NGL`), and the logit vectors they answer with.

use anyhow::Context;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Where the reference dumper is looked for, in order. `target/` is
/// where `tools/build_llama_logits.sh` puts it; the second entry keeps
/// working for anyone who built it by hand before it moved into the
/// tracked tree.
const DUMPER_CANDIDATES: &[&str] = &["target/llama_logits", ".local-scripts/llama_logits"];

/// Environment override, for a dumper built somewhere else entirely.
const DUMPER_ENV: &str = "FRINK_LLAMA_LOGITS";

/// Runs every dumper on the same token ids and keeps the ones that
/// answered with a comparable vector.
///
/// The PRIMARY reference is load-bearing and its failures are fatal. A
/// SECONDARY one is evidence, and evidence that did not arrive leaves a
/// narrower experiment rather than no experiment — but it is said out
/// loud, because a run that silently lost its calibration would print a
/// WRONG line derived from one reference while looking like a
/// two-reference run.
pub(super) fn collect_references(
    dumpers: &[PathBuf],
    model: &str,
    tokens: &[u32],
    n_vocab: usize,
) -> anyhow::Result<Vec<Reference>> {
    let mut out: Vec<Reference> = Vec::new();
    for (i, dumper) in dumpers.iter().enumerate() {
        let primary = i == 0;
        let reference = match reference_logits(dumper, model, tokens, i, None) {
            Ok(r) => r,
            Err(e) if primary => return Err(e),
            Err(e) => {
                eprintln!(
                    "parity: reference [{i}] {} produced nothing ({e:#}); the WRONG line will be \
                     measured without it",
                    dumper.display()
                );
                continue;
            }
        };
        if reference.logits.len() != n_vocab {
            if primary {
                // Not a tolerance question: the two engines disagree
                // about how many tokens the model can emit, which is a
                // loader bug on one side and makes every other number
                // here meaningless.
                anyhow::bail!(
                    "vocab size disagrees: llama.cpp {} vs frink {n_vocab} — the logit vectors \
                     are not comparable, fix the loader before reading any metric",
                    reference.logits.len()
                );
            }
            eprintln!(
                "parity: reference [{i}] reports {} vocabulary entries against frink's \
                 {n_vocab}; dropped from the WRONG line rather than compared to a different \
                 distribution",
                reference.logits.len()
            );
            continue;
        }
        out.push(reference);
    }
    Ok(out)
}

/// The layers `LLAMA_LOGITS_NGL` asks the dumpers to offload, as
/// `tools/llama_logits.c` reads it (a positive count offloads; zero, or
/// text that does not start with digits, is its CPU default): `None`
/// when the references run on llama.cpp's CPU.
pub(super) fn reference_ngl(raw: Option<&str>) -> Option<u32> {
    raw.and_then(|s| s.trim().parse::<u32>().ok())
        .filter(|&n| n > 0)
}

/// Resolves every `--dumper`, or falls back to the single one the
/// environment and the tree offer.
pub(super) fn dumper_paths(explicit: &[String]) -> anyhow::Result<Vec<PathBuf>> {
    if !explicit.is_empty() {
        return explicit
            .iter()
            .map(|e| {
                let p = PathBuf::from(e);
                // An explicit path that does not exist is a typo, not a
                // reason to silently fall back to some other binary and
                // report its answer as the reference.
                if p.exists() {
                    Ok(p)
                } else {
                    anyhow::bail!("--dumper {} does not exist", p.display())
                }
            })
            .collect();
    }
    if let Some(e) = std::env::var_os(DUMPER_ENV) {
        let p = PathBuf::from(e);
        if p.exists() {
            return Ok(vec![p]);
        }
        anyhow::bail!(
            "{DUMPER_ENV} points at {}, which does not exist",
            p.display()
        );
    }
    for c in DUMPER_CANDIDATES {
        let p = PathBuf::from(c);
        if p.exists() {
            return Ok(vec![p]);
        }
    }
    anyhow::bail!(
        "reference dumper not built. It links llama.cpp's own library, so it is built \
         separately from the cargo workspace:\n\n  ./tools/build_llama_logits.sh\n\n\
         (set LLAMA_CPP_PREFIX if llama.cpp is not a Homebrew install, or --dumper / \
         {DUMPER_ENV} to point at a binary elsewhere)"
    )
}

/// What the reference said, and which library said it.
pub(super) struct Reference {
    pub(super) logits: Vec<f32>,
    /// The libllama the dumper actually loaded, as it reported itself.
    ///
    /// `None` when the dumper predates the line — an older binary is
    /// still usable, it just cannot be attributed, and that is worth
    /// saying rather than guessing a path from the dumper's own.
    pub(super) libllama: Option<String>,
}

/// Prefix the dumper uses to report the library it loaded. Spelled once
/// here and once in `tools/llama_logits.c`; the parse is tolerant of
/// its absence precisely because those two are the only things that
/// have to agree and nothing links them.
const LIBLLAMA_LINE: &str = "libllama ";

/// Runs the reference dumper on the SAME token ids and reads back its
/// logit vector.
///
/// `slot` distinguishes the temporary file per reference: two dumpers
/// run in one process would otherwise write the same path, and the
/// second answer would be read as the first.
///
/// `dump_tensors` turns on the dumper's per-tensor dump into that
/// directory ([`layers`](super::layers)).
pub(super) fn reference_logits(
    dumper: &Path,
    model: &str,
    tokens: &[u32],
    slot: usize,
    dump_tensors: Option<&Path>,
) -> anyhow::Result<Reference> {
    let out_path =
        std::env::temp_dir().join(format!("frink-parity-{}-{slot}.bin", std::process::id()));
    let mut cmd = Command::new(dumper);
    cmd.arg(model).arg(&out_path);
    if let Some(dir) = dump_tensors {
        cmd.env("LLAMA_LOGITS_DUMP_TENSORS", dir);
    }
    for t in tokens {
        cmd.arg(t.to_string());
    }
    let out = cmd.output().context("running the reference dumper")?;
    if !out.status.success() {
        anyhow::bail!(
            "reference dumper failed: {}",
            String::from_utf8_lossy(&out.stderr)
                .lines()
                .last()
                .unwrap_or("(no stderr)")
        );
    }
    let bytes = std::fs::read(&out_path)
        .with_context(|| format!("reading reference logits from {}", out_path.display()))?;
    let _ = std::fs::remove_file(&out_path);
    if bytes.len() % 4 != 0 {
        anyhow::bail!("reference logits file is not a whole number of f32");
    }
    Ok(Reference {
        logits: bytes
            .as_chunks::<4>()
            .0
            .iter()
            .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
            .collect(),
        libllama: parse_libllama(&String::from_utf8_lossy(&out.stdout)),
    })
}

/// Picks the `libllama <path>` line out of the dumper's stdout.
fn parse_libllama(stdout: &str) -> Option<String> {
    stdout
        .lines()
        .find_map(|l| l.trim().strip_prefix(LIBLLAMA_LINE))
        .map(str::trim)
        .filter(|p| !p.is_empty() && *p != "unknown")
        .map(str::to_string)
}

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

    /// The report names where the references ran: unset, zero and junk
    /// are the dumper's CPU default, a positive count is an offload.
    #[test]
    fn the_reference_side_follows_llama_logits_ngl() {
        assert_eq!(reference_ngl(None), None);
        assert_eq!(reference_ngl(Some("0")), None);
        assert_eq!(reference_ngl(Some("metal")), None);
        assert_eq!(reference_ngl(Some("99")), Some(99));
    }

    /// The dumper's self-report is read, and its absence is not
    /// mistaken for a library called "unknown".
    #[test]
    fn the_reference_identity_is_parsed_and_its_absence_is_not_invented() {
        assert_eq!(
            parse_libllama("libllama /opt/homebrew/lib/libllama.dylib\nn_vocab 32000\n").as_deref(),
            Some("/opt/homebrew/lib/libllama.dylib")
        );
        // An older dumper prints no such line: report that, do not guess.
        assert_eq!(parse_libllama("n_vocab 32000\n"), None);
        // The dumper says "unknown" when dladdr fails; that is an
        // absence too, and passing it through would print a reference
        // path of "unknown" as though it were one.
        assert_eq!(parse_libllama("libllama unknown\nn_vocab 32000\n"), None);
        assert_eq!(parse_libllama("libllama   \n"), None);
    }

    /// Every `--dumper` is resolved, in order, and a typo in ANY of them
    /// fails the run.
    ///
    /// A missing secondary that fell back to the tree's default would
    /// silently calibrate against the primary itself — a zero spread
    /// wearing the appearance of a two-reference experiment.
    #[test]
    fn every_dumper_is_resolved_and_a_missing_one_is_never_substituted() {
        let me = std::env::current_exe().unwrap();
        let me = me.to_string_lossy().into_owned();
        let resolved = dumper_paths(&[me.clone(), me.clone()]).unwrap();
        assert_eq!(resolved.len(), 2, "both references must survive");

        let err = dumper_paths(&[me, "/nonexistent/llama_logits".into()])
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("/nonexistent/llama_logits"),
            "a bad second dumper must name itself, got: {err}"
        );
    }
}