use std::path::{Path, PathBuf};
use crate::bench_llama::Reference;
use crate::bench_suite::{engine_receipt_dir, host_identity, load_suite};
const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const BEGIN: &str = "<!-- BEGIN ENGINE TABLE (generated by `frink bench --render`) -->";
pub const END: &str = "<!-- END ENGINE TABLE -->";
#[derive(Clone)]
struct Row {
host: String,
model: String,
backend: String,
test: String,
frink: Option<f64>,
llama: Option<f64>,
gap: Option<f64>,
version: String,
reference: Reference,
}
#[derive(Default, Clone)]
struct ModelRow {
model: String,
pp_test: String,
pp_frink: Option<f64>,
pp_llama: Option<f64>,
pp_gap: Option<f64>,
tg_test: String,
tg_frink: Option<f64>,
tg_llama: Option<f64>,
tg_gap: Option<f64>,
}
fn is_prefill(test: &str) -> bool {
test.starts_with("pp")
}
fn is_decode(test: &str) -> bool {
test.starts_with("tg")
}
fn pivot(rows: &[&Row]) -> Vec<ModelRow> {
use std::collections::BTreeMap;
let mut by: BTreeMap<String, ModelRow> = BTreeMap::new();
for r in rows {
let e = by.entry(r.model.clone()).or_default();
e.model.clone_from(&r.model);
if is_prefill(&r.test) {
e.pp_test.clone_from(&r.test);
e.pp_frink = r.frink;
e.pp_llama = r.llama;
e.pp_gap = r.gap;
} else if is_decode(&r.test) {
e.tg_test.clone_from(&r.test);
e.tg_frink = r.frink;
e.tg_llama = r.llama;
e.tg_gap = r.gap;
}
}
by.into_values().collect()
}
fn tps(v: Option<f64>) -> String {
v.map(|v| {
if v >= 100.0 {
format!("{v:.0}")
} else {
format!("{v:.1}")
}
})
.unwrap_or_else(|| "—".into())
}
pub fn render(bench_dir: &Path) -> anyhow::Result<()> {
let dir = engine_receipt_dir(bench_dir);
let mut receipts: Vec<serde_json::Value> = Vec::new();
if dir.is_dir() {
let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
paths.sort();
for p in paths {
if let Ok(text) = std::fs::read_to_string(&p) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
receipts.push(v);
}
}
}
}
if receipts.is_empty() {
anyhow::bail!(
"no engine receipts under {}, so there is nothing to render. \
Run `frink bench --suite` first.",
dir.display()
);
}
let suite = load_suite(bench_dir).unwrap_or_default();
let name_of = |id: &str| {
suite
.iter()
.find(|e| e.id == id)
.map(|e| e.name.clone())
.unwrap_or_else(|| id.to_string())
};
let mut hosts: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
let mut groups: std::collections::BTreeSet<(String, Reference)> =
std::collections::BTreeSet::new();
for r in &receipts {
hosts.insert(host_identity(r));
groups.insert((host_identity(r), Reference::from_receipt(r)));
}
let references: std::collections::BTreeSet<&Reference> =
groups.iter().map(|(_, r)| r).collect();
let mut rows: Vec<Row> = Vec::new();
for r in &receipts {
let host_label = host_identity(r);
let reference = Reference::from_receipt(r);
let id = r.get("id").and_then(|v| v.as_str()).unwrap_or("?");
let backend = r
.get("backend")
.and_then(|v| v.as_str())
.unwrap_or("?")
.to_string();
let Some(tests) = r.get("tests").and_then(|v| v.as_array()) else {
continue;
};
for t in tests {
rows.push(Row {
host: host_label.clone(),
model: name_of(id),
backend: backend.clone(),
test: t
.get("test")
.and_then(|v| v.as_str())
.unwrap_or("?")
.to_string(),
frink: t.get("frink_tps").and_then(|v| v.as_f64()),
llama: t.get("llama_tps").and_then(|v| v.as_f64()),
gap: t.get("gap").and_then(|v| v.as_f64()),
version: r
.get("frink_version")
.and_then(|v| v.as_str())
.unwrap_or("?")
.to_string(),
reference: reference.clone(),
});
}
}
let mut table = String::new();
table.push_str(BEGIN);
table.push_str("\n\n# frink vs llama.cpp\n\n");
table.push_str(
"Same machine, same GGUF, same backend. `pp` is prefill, `tg` is decode.\n\n\
**Gap = llama.cpp ÷ frink. Below 1.00 means frink is faster.**\n\
🟢 faster · ⚪ within 5% · 🔴 slower\n\n",
);
{
let n = hosts.len();
if groups.len() == 1 {
if let Some((host, reference)) = groups.iter().next() {
table.push_str(&format!(
"Measured on: **{host}**, against {}\n\n",
reference.describe()
));
}
} else if n == 1 {
table.push_str(&format!(
"Measured on: **{}**\n\n",
hosts.iter().next().cloned().unwrap_or_default()
));
}
if n > 1 {
table.push_str(&format!(
"Measured on **{n} machines**, one section each. \
A gap only means something against the machine it was measured on, \
so rows are never compared across sections.\n\n"
));
}
if references.len() > 1 {
table.push_str(&format!(
"Compared against **{} llama.cpp references**, one section each. \
A gap is a ratio against one llama.cpp build, \
so gaps from different sections are not one comparison.\n\n",
references.len()
));
}
}
{
use std::collections::BTreeMap;
type Key = (String, String, Reference);
let mut by: BTreeMap<(Key, bool), Vec<f64>> = BTreeMap::new();
let mut versions: BTreeMap<Key, std::collections::BTreeSet<String>> = BTreeMap::new();
for r in &rows {
let key: Key = (r.host.clone(), r.backend.clone(), r.reference.clone());
versions
.entry(key.clone())
.or_default()
.insert(r.version.clone());
if let Some(g) = r.gap {
by.entry((key, is_prefill(&r.test))).or_default().push(g);
}
}
if !by.is_empty() {
table.push_str("### At a glance\n\n");
table.push_str("| Machine | Backend | llama.cpp | Measured at | Prefill | Decode |\n");
table.push_str("|---|---|---|---|---|---|\n");
let mut seen: Vec<Key> = by.keys().map(|(k, _)| k.clone()).collect();
seen.dedup();
for key in seen {
let (host, backend, reference) = &key;
let fmt = |pp: bool| -> String {
match by.get(&(key.clone(), pp)) {
Some(v) if !v.is_empty() => {
let lo = v.iter().cloned().fold(f64::INFINITY, f64::min);
let hi = v.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
if (hi - lo).abs() < 0.005 {
gap_cell(lo)
} else {
format!("{} to {}", gap_cell(lo), gap_cell(hi))
}
}
_ => "—".to_string(),
}
};
let taken = versions
.get(&key)
.map(|v| v.iter().cloned().collect::<Vec<_>>().join(", "))
.unwrap_or_else(|| "?".into());
let current = versions
.get(&key)
.is_some_and(|v| v.len() == 1 && v.contains(CURRENT_VERSION));
let age = if current {
format!("`{taken}`")
} else {
format!("`{taken}` ⚠️")
};
table.push_str(&format!(
"| {host} | {} | {} | {age} | {} | {} |\n",
backend.to_uppercase(),
reference.short(),
fmt(true),
fmt(false)
));
}
table.push('\n');
let stale = versions
.values()
.any(|v| v.len() != 1 || !v.contains(CURRENT_VERSION));
if stale {
table.push_str(&format!(
"⚠️ marks rows measured on a build older than this one \
(**{CURRENT_VERSION}**). They are what that build did, \
not what this one does, and are kept until the machine \
that produced them is available again.\n\n"
));
}
}
}
fn push_section_at(table: &mut String, depth: &str, title: &str, rows: &[&Row]) {
if rows.is_empty() {
return;
}
let models = pivot(rows);
if models.is_empty() {
return;
}
let pp = models
.iter()
.map(|m| m.pp_test.as_str())
.find(|s| !s.is_empty())
.unwrap_or("pp")
.to_string();
let tg = models
.iter()
.map(|m| m.tg_test.as_str())
.find(|s| !s.is_empty())
.unwrap_or("tg")
.to_string();
table.push_str(&format!("{depth} {title}\n\n"));
table.push_str(&format!(
"| Model | Prefill | Decode | frink {pp} | llama.cpp {pp} | frink {tg} | llama.cpp {tg} |\n"
));
table.push_str("|---|---|---|---:|---:|---:|---:|\n");
for m in &models {
table.push_str(&format!(
"| {} | {} | {} | {} | {} | {} | {} |\n",
m.model,
m.pp_gap.map(gap_cell).unwrap_or_else(|| "—".into()),
m.tg_gap.map(gap_cell).unwrap_or_else(|| "—".into()),
tps(m.pp_frink),
tps(m.pp_llama),
tps(m.tg_frink),
tps(m.tg_llama),
));
}
table.push('\n');
}
let metal: Vec<&Row> = rows.iter().filter(|r| r.backend == "metal").collect();
let cuda: Vec<&Row> = rows.iter().filter(|r| r.backend == "cuda").collect();
let cpu: Vec<&Row> = rows.iter().filter(|r| r.backend == "cpu").collect();
let other: Vec<&Row> = rows
.iter()
.filter(|r| !matches!(r.backend.as_str(), "metal" | "cuda" | "cpu"))
.collect();
if rows.is_empty() {
table.push_str("| _no engine receipts yet_ | | | | | |\n\n");
} else if groups.len() <= 1 {
push_section_at(&mut table, "###", "Metal", &metal);
push_section_at(&mut table, "###", "CUDA", &cuda);
push_section_at(&mut table, "###", "CPU", &cpu);
push_section_at(&mut table, "###", "Other backends", &other);
} else {
for (host, reference) in &groups {
let here: Vec<&Row> = rows
.iter()
.filter(|r| &r.host == host && &r.reference == reference)
.collect();
let shared_host = groups.iter().filter(|(h, _)| h == host).count() > 1;
if shared_host {
table.push_str(&format!("### {host}, llama.cpp {}\n\n", reference.short()));
} else {
table.push_str(&format!("### {host}\n\n"));
}
table.push_str(&format!("Against {}.\n\n", reference.describe()));
for (title, backend) in [("Metal", "metal"), ("CUDA", "cuda"), ("CPU", "cpu")] {
let sub: Vec<&Row> = here
.iter()
.copied()
.filter(|r| r.backend == backend)
.collect();
push_section_at(&mut table, "####", title, &sub);
}
let sub: Vec<&Row> = here
.iter()
.copied()
.filter(|r| !matches!(r.backend.as_str(), "metal" | "cuda" | "cpu"))
.collect();
push_section_at(&mut table, "####", "Other backends", &sub);
}
}
table.push_str(
"---\n\n\
Generated by `frink bench --render` from [`receipts/engine/`](receipts/engine/). \
Do not hand-edit: the next render overwrites it.\n\
How the numbers are taken, and the traps they have fallen into: \
[`README.md`](README.md). \
Older measurements and before/after studies: [`HISTORY.md`](HISTORY.md).\n\n",
);
table.push_str(END);
let results = bench_dir.join("RESULTS.md");
let existing = std::fs::read_to_string(&results).unwrap_or_default();
let updated = splice(&existing, &table);
std::fs::write(&results, updated)?;
eprintln!("frink bench: engine table written to {}", results.display());
Ok(())
}
fn gap_cell(g: f64) -> String {
let marker = if g < 0.95 {
"🟢"
} else if g <= 1.05 {
"⚪"
} else {
"🔴"
};
format!("{marker} **{g:.2}×**")
}
fn splice(existing: &str, block: &str) -> String {
if let (Some(start), Some(end)) = (existing.find(BEGIN), existing.find(END)) {
let mut out = String::with_capacity(existing.len() + block.len());
out.push_str(&existing[..start]);
out.push_str(block);
out.push_str(&existing[end + END.len()..]);
return out;
}
let mut out = existing.to_string();
if !out.ends_with('\n') {
out.push('\n');
}
out.push('\n');
out.push_str(block);
out.push('\n');
out
}
#[cfg(test)]
mod tests;