use anyhow::Context;
use std::path::{Path, PathBuf};
use std::process::Command;
const DUMPER_CANDIDATES: &[&str] = &["target/llama_logits", ".local-scripts/llama_logits"];
const DUMPER_ENV: &str = "FRINK_LLAMA_LOGITS";
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 {
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)
}
pub(super) fn reference_ngl(raw: Option<&str>) -> Option<u32> {
raw.and_then(|s| s.trim().parse::<u32>().ok())
.filter(|&n| n > 0)
}
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);
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)"
)
}
pub(super) struct Reference {
pub(super) logits: Vec<f32>,
pub(super) libllama: Option<String>,
}
const LIBLLAMA_LINE: &str = "libllama ";
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)),
})
}
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::*;
#[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));
}
#[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")
);
assert_eq!(parse_libllama("n_vocab 32000\n"), None);
assert_eq!(parse_libllama("libllama unknown\nn_vocab 32000\n"), None);
assert_eq!(parse_libllama("libllama \n"), None);
}
#[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}"
);
}
}