frink-cli 0.56.0

llama.cpp-style CLI for the Frink inference engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! `frink bench --render`: turn the receipts on disk into the engine
//! table in [`benchmarks/RESULTS.md`](../../../benchmarks/RESULTS.md).
//!
//! Split out of `bench_suite` because running the suite and publishing
//! it are two concepts, and because `bench_suite` was 903 lines when
//! this table's shape needed changing. Rendering reads receipts and
//! writes markdown; it never measures anything.
//!
//! # One row per model
//!
//! The table used to carry one row per (model, test), so a ten-model
//! host was twenty rows and a single model's prefill and decode sat
//! ten rows apart. They are now one row: the two verdicts first,
//! because that is what a reader scans for, then the four raw tok/s
//! numbers for anyone who wants them.
//!
//! Rows sort by model name rather than worst-gap-first. With prefill
//! and decode on one line there is no single gap to sort on, and the
//! generated `### Summary` above already carries each host's range. A
//! stable alphabetical order also puts the same model in the same place
//! in every host's table.
//!
//! # One section per machine and llama.cpp build
//!
//! A gap is llama.cpp's number over frink's, so it is only comparable
//! with another gap taken against the same llama.cpp build (ADR 0006).
//! Rows are grouped by (host, llama.cpp reference), the way they were
//! already grouped by host, and two groups never share a table. A
//! receipt written before the reference was recorded is grouped under
//! an UNKNOWN reference and says so; no build is filled in for it.
//!
//! # What this file must never do
//!
//! Invent, adjust, or omit a number. Every cell comes from a receipt.
//! A hand-edited ledger is not a measurement, which is why the table
//! lives between markers and this is the only thing that writes it.

use std::path::{Path, PathBuf};

use crate::bench_llama::Reference;
use crate::bench_suite::{engine_receipt_dir, host_identity, load_suite};

/// The build this ledger is rendered by, so a stale row is visible as
/// stale rather than only as a number.
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 -->";

/// One measured (host, backend, model, test) cell.
#[derive(Clone)]
struct Row {
    /// Which machine produced this row. Rows never merge across hosts;
    /// see the grouping below.
    host: String,
    model: String,
    backend: String,
    test: String,
    frink: Option<f64>,
    llama: Option<f64>,
    gap: Option<f64>,
    /// The frink build that produced this row, off the receipt.
    ///
    /// Carried because a gap column cannot show its own age. Every
    /// CUDA row in this ledger was measured before the K-quant GEMM
    /// landed and overstated the gap by about six times for months,
    /// and nothing in the rendered table said so: the numbers were
    /// correct for the build that produced them and wrong about the
    /// engine by the time anyone read them.
    version: String,
    /// The llama.cpp build `llama` was measured on, off the receipt.
    /// Rows with different references are never in one table.
    reference: Reference,
}

/// One model's prefill and decode on one host and backend: the shape
/// the table actually prints.
#[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")
}

/// Collapse per-test rows into one row per model, preserving every
/// number. A test that is neither `pp*` nor `tg*` is dropped from this
/// view rather than silently filed under one of them.
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()
}

/// tok/s for the table, at a precision that cannot contradict the gap
/// beside it.
///
/// The gap column comes from the receipt, not from these two cells, so
/// a reader who divides the printed numbers must land on the printed
/// gap. Rounding everything to whole tok/s breaks that at small values
/// (149 ÷ 151 reads 0.99 against a printed 0.98), and carrying two
/// decimals to 3891.58 is noise nobody uses. One decimal below 100,
/// none above, keeps both ends honest.
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);
                }
            }
        }
    }

    // No receipts at all means there is nothing to render. Writing the
    // table anyway would replace a real ledger with an empty one and
    // report success, which is worse than doing nothing.
    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())
    };

    // Rows from two machines are not one table. `render` reads every
    // receipt in the directory, so the moment a second host writes one,
    // its numbers would sort in beside this one's under a single
    // heading with nothing saying so. A reader comparing a 5.06x row
    // against a 1.41x row would be comparing two computers.
    //
    // The same holds for two llama.cpp builds (ADR 0006): a gap is a
    // ratio against one build, so the grouping key is the pair.
    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",
    );
    // Which machine, stated in the generated block rather than in prose
    // above it, so it cannot drift away from the numbers it describes.
    {
        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()
            ));
        }
    }

    // A summary table, not prose. Generated from the same receipts as
    // the detail rows below, so it cannot drift away from them the way
    // a hand-written headline does.
    {
        use std::collections::BTreeMap;
        // Keyed by llama.cpp reference too: a range spanning two builds
        // would be the one place two references share a cell.
        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');
            // Stated once, from the same map the column came from, so a
            // reader never has to know which version is current to see
            // that a row is not at it.
            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;
        }
        // Column headers name the workloads actually measured rather
        // than hard-coding pp512/tg128, so a suite run at another size
        // cannot be mislabelled by this file.
        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 {
        // One section per machine. A reader scanning for a gap sees the
        // host before the number, which is the only order in which the
        // number means anything.
        //
        // A host measured against one llama.cpp build keeps its plain
        // heading; a host with several gets one section per build, each
        // heading naming it, so no table mixes two references.
        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);
        }
    }

    // The footer is generated too. Anything a reader needs in order to
    // read the table has to be inside the markers, or the next render
    // publishes a page whose legend has drifted from its numbers.
    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}×**")
}

/// Replaces the marked block, or appends it if the markers are absent.
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;