frink-cli 0.68.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
//! Cross-backend output agreement.
//!
//! The benchmark harness measures throughput and never looks at what the
//! engine produced. That gap has hidden real bugs more than once: a d=64
//! prefill kernel applied softcap twice through a cross-simdgroup race
//! while reporting healthy tok/s; SmolLM2 once generated word salad on
//! Metal at full speed; Gemma-2 still emits a bare `:` on Metal. Every
//! one of those rows looked green.
//!
//! So: generate the same greedy continuation on two backends and compare
//! the token sequences. Greedy decoding is deterministic, and a kernel
//! that computes the wrong thing diverges within a few tokens. The CPU
//! path is the reference because it is the one cross-validated against
//! NumPy in `gguf_roundtrip.rs`.
//!
//! Backend choice is a process-lifetime `OnceLock` read from the
//! environment, so this cannot switch backends in-process — it re-invokes
//! itself once per backend, exactly as `bench --suite` does.
//!
//! Each child's switches are written out in full ([`child_env`]), from
//! the table `-dev` uses: the reference turns every GPU off and the
//! candidate turns on exactly the named one. Until #651 the children set
//! only `FRINK_METAL` and `FRINK_CUDA`, so `--backend vulkan` never set
//! `FRINK_VULKAN`: it compared the CPU with itself, Vulkan with itself
//! when the shell had exported `FRINK_VULKAN=1`, or Metal with the CPU on
//! a Metal build. The child now reports the backend its matvecs selected
//! and a mismatch is refused, so a wrong route cannot pass again.

use crate::verify_engine::Top2;
use anyhow::Context;
use frink_core::kernel_registry::Backend;
use frink_models::offload::{self, OffloadDevice};
use std::path::Path;
use std::process::Command;

/// Default for `-n`: how many tokens to compare. Divergence from a real
/// kernel bug shows up almost immediately; the cost of going further is
/// wall time on the slowest backend.
pub const DEFAULT_N_PREDICT: usize = 24;

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

/// Batch size at which the batched-prefill attention kernels turn on
/// (`fa_ext` / the simdgroup-MMA variants gate on `n_q >= 8`). Below it
/// the run only exercises single-token decode, so a green verdict says
/// nothing about the prefill kernels this tool exists to catch — hence
/// the warning rather than a silent pass.
const PREFILL_MIN_TOKENS: usize = 8;

pub struct VerifyArgs {
    pub model: String,
    /// Backend to check against the CPU reference: `metal`, `cuda`,
    /// `rocm` or `vulkan`.
    pub backend: String,
    /// Emit the token ids rather than a verdict (used by the child).
    pub emit: bool,
    /// Stretch the prompt to this many tokens before prefill, so the
    /// batched-prefill kernels are actually reached.
    pub prompt_tokens: Option<usize>,
    /// Override the fixed prompt.
    pub prompt: Option<String>,
    /// Tokens to greedy-decode and compare (`-n`).
    pub n_predict: usize,
    /// The global `--allow-multiple-instances` flag. Forwarded to the
    /// children, which are the processes that actually load a model: a
    /// clap flag, unlike an environment variable, is not inherited.
    pub allow_multiple_instances: bool,
}

/// Marker the child prints so the parent can find the payload even if the
/// engine writes other things to stdout. One `id,logit,id,logit` entry
/// per step: the token taken and the runner-up.
const TAG: &str = "FRINK_VERIFY_TOP2 ";

/// Second marker: how many tokens the prompt actually became. Only the
/// child tokenizes, so this is the one number that says whether the run
/// reached the batched-prefill kernels — `--prompt-tokens` is optional
/// and a long `--prompt` is just as good a way to get there.
const LEN_TAG: &str = "FRINK_VERIFY_PROMPT_LEN ";

/// Third marker: the backend the child's dense matvecs selected
/// ([`frink_core::weight_matrix::active_backend`]), so the parent can
/// refuse a run that did not reach the backend it was asked to check.
const BACKEND_TAG: &str = "FRINK_VERIFY_BACKEND ";

/// What `--backend` names, checked: a GPU backend this build has and
/// this machine can open. `cpu` is the reference and `auto` / `none`
/// name no backend, so all three are refused.
pub(crate) fn parse_backend(name: &str) -> anyhow::Result<OffloadDevice> {
    let device: OffloadDevice = name.parse().map_err(|e| {
        anyhow::anyhow!("--backend {name:?}: {e}; verify takes metal, cuda, rocm or vulkan")
    })?;
    if matches!(
        device,
        OffloadDevice::Auto | OffloadDevice::None | OffloadDevice::Cpu
    ) {
        anyhow::bail!(
            "--backend {device}: verify checks a GPU backend against the CPU reference; \
             it takes metal, cuda, rocm or vulkan"
        );
    }
    offload::check_available(device)?;
    Ok(device)
}

/// The backend [`frink_core::weight_matrix::active_backend`] must
/// report in a child routed to `device`. ROCm is the CUDA backend's
/// code compiled for HIP, so it reports `cuda`.
fn expected_backend(device: OffloadDevice) -> Backend {
    match device {
        OffloadDevice::Metal => Backend::Metal,
        OffloadDevice::Cuda | OffloadDevice::Rocm => Backend::Cuda,
        OffloadDevice::Vulkan => Backend::Vulkan,
        OffloadDevice::Auto | OffloadDevice::None | OffloadDevice::Cpu => Backend::Cpu,
    }
}

/// Every backend switch one child gets, from [`offload::switches_for`]
/// so it cannot drift from `-dev`. `metal_attn` is the parent's
/// `FRINK_METAL_ATTN`: where the table leaves that switch to the user
/// (the Metal candidate), a pre-set value is an ablation and holds,
/// and unset means on, as `-ngl 99` has it. `FRINK_METAL` alone turns
/// on only the Metal matvecs, so a Metal candidate without the
/// attention block would check a graph nobody runs.
pub(crate) fn child_env(
    device: OffloadDevice,
    metal_attn: Option<&str>,
) -> Vec<(&'static str, String)> {
    offload::switches_for(device)
        .into_iter()
        .filter_map(|(name, value)| match value {
            Some(v) => Some((name, v.to_string())),
            None if name == "FRINK_METAL_ATTN" => {
                Some((name, metal_attn.unwrap_or("1").to_string()))
            }
            None => None,
        })
        .collect()
}

pub fn run(args: VerifyArgs) -> anyhow::Result<()> {
    let prompt = args.prompt.clone().unwrap_or_else(|| PROMPT.to_string());
    if args.n_predict == 0 {
        anyhow::bail!("-n must be at least 1: there is nothing to compare at 0 tokens");
    }
    if args.emit {
        return emit_tokens(&args.model, &prompt, args.prompt_tokens, args.n_predict);
    }
    let device = parse_backend(&args.backend)?;

    let reference = child_tokens(&args, OffloadDevice::Cpu, &prompt)?;
    let candidate = child_tokens(&args, device, &prompt)?;
    let prompt_len = reference.prompt_len;
    let (reference, candidate) = (reference.steps, candidate.steps);

    if prompt_len < PREFILL_MIN_TOKENS {
        eprintln!(
            "verify: prompt is {prompt_len} tokens, under the {PREFILL_MIN_TOKENS} at which the \
             batched-prefill attention kernels turn on — this run checks decode only. \
             Pass --prompt-tokens {PREFILL_MIN_TOKENS} or more (or a longer --prompt) to \
             cover prefill."
        );
    }

    if reference.is_empty() {
        anyhow::bail!("CPU reference produced no tokens; cannot verify");
    }

    let ids = |s: &[Top2]| s.iter().map(|t| t.first.0).collect::<Vec<u32>>();
    let (ref_ids, cand_ids) = (ids(&reference), ids(&candidate));
    let diverge = ref_ids
        .iter()
        .zip(&cand_ids)
        .position(|(a, b)| a != b)
        .or_else(|| (ref_ids.len() != cand_ids.len()).then_some(ref_ids.len().min(cand_ids.len())));

    match diverge {
        None => {
            println!(
                "verify {}: OK — {} tokens identical on cpu and {device} ({})",
                short(&args.model),
                ref_ids.len(),
                prompt_desc(prompt_len)
            );
            Ok(())
        }
        Some(i) => {
            // Report where and with what, not just that it failed: the
            // index says whether the kernel is wrong from the first token
            // (dense path) or drifts (accumulating / attention path),
            // which is the first thing anyone debugging this needs.
            println!(
                "verify {}: DIVERGED at token {i} ({}) — cpu={:?} {device}={:?}",
                short(&args.model),
                prompt_desc(prompt_len),
                &ref_ids[i.saturating_sub(2)..ref_ids.len().min(i + 3)],
                &cand_ids[i.saturating_sub(2)..cand_ids.len().min(i + 3)],
            );
            // Both sides decoded the same prefix up to `i`, so their
            // step-`i` logits answer the same question; the margins say
            // whether the split is a near tie or a wrong kernel.
            for (name, steps) in [("cpu", &reference), (device.as_str(), &candidate)] {
                if let Some(t) = steps.get(i) {
                    println!("{}", margin_line(name, i, t));
                }
            }
            anyhow::bail!("{device} disagrees with the CPU reference from token {i}")
        }
    }
}

/// One backend's top two at the divergent step, and their margin.
fn margin_line(backend: &str, step: usize, t: &Top2) -> String {
    format!(
        "  {backend} at token {step}: top-1 {} ({}), top-2 {} ({}), margin {}",
        t.first.0,
        t.first.1,
        t.second.0,
        t.second.1,
        t.first.1 - t.second.1
    )
}

/// Says which path the verdict covers, so a decode-only pass is never
/// read as a prefill pass.
fn prompt_desc(prompt_len: usize) -> String {
    if prompt_len >= PREFILL_MIN_TOKENS {
        format!("{prompt_len}-token prompt, prefill covered")
    } else {
        format!("{prompt_len}-token prompt, decode only")
    }
}

fn short(model: &str) -> String {
    Path::new(model)
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| model.to_string())
}

/// What one child printed.
struct ChildRun {
    steps: Vec<Top2>,
    prompt_len: usize,
}

/// Runs one backend in a child and parses back its steps.
fn child_tokens(
    args: &VerifyArgs,
    device: OffloadDevice,
    prompt: &str,
) -> anyhow::Result<ChildRun> {
    let exe = std::env::current_exe()?;
    let mut cmd = Command::new(&exe);
    cmd.arg("verify")
        .args(["-m", &args.model])
        .args(["--backend", device.as_str()])
        .args(["--prompt", prompt])
        .args(["-n", &args.n_predict.to_string()])
        .arg("--emit");
    if let Some(n) = args.prompt_tokens {
        cmd.args(["--prompt-tokens", &n.to_string()]);
    }
    if args.allow_multiple_instances {
        cmd.env("FRINK_ALLOW_MULTIPLE_INSTANCES", "1");
    }
    let metal_attn = std::env::var("FRINK_METAL_ATTN").ok();
    cmd.envs(child_env(device, metal_attn.as_deref()));
    let out = cmd
        .output()
        .with_context(|| format!("spawning verify child for {device}"))?;
    if !out.status.success() {
        anyhow::bail!(
            "verify child for {device} failed: {}",
            String::from_utf8_lossy(&out.stderr)
                .lines()
                .last()
                .unwrap_or("(no stderr)")
        );
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let tagged = |tag: &str| text.lines().find_map(|l| l.strip_prefix(tag));
    let ran = tagged(BACKEND_TAG)
        .map(str::trim)
        .with_context(|| format!("verify child for {device} printed no backend line"))?;
    check_ran_on(device, ran)?;
    let line =
        tagged(TAG).with_context(|| format!("verify child for {device} printed no token line"))?;
    let prompt_len = tagged(LEN_TAG)
        .and_then(|l| l.trim().parse::<usize>().ok())
        .with_context(|| format!("verify child for {device} printed no prompt-length line"))?;
    let steps = parse_steps(line)
        .with_context(|| format!("verify child for {device} printed a malformed token line"))?;
    Ok(ChildRun { steps, prompt_len })
}

/// Refuse a child whose matvecs ran somewhere other than `device`: a
/// verdict over the wrong pair of backends is the bug #651 found.
fn check_ran_on(device: OffloadDevice, ran: &str) -> anyhow::Result<()> {
    let want = expected_backend(device).as_str();
    if ran != want {
        anyhow::bail!(
            "the {device} child ran on {ran}, not {want}: the comparison would not be \
             cpu against {device}"
        );
    }
    Ok(())
}

fn format_steps(steps: &[Top2]) -> String {
    let fields: Vec<String> = steps
        .iter()
        .map(|t| format!("{},{},{},{}", t.first.0, t.first.1, t.second.0, t.second.1))
        .collect();
    fields.join(" ")
}

fn parse_steps(line: &str) -> Option<Vec<Top2>> {
    line.split_whitespace()
        .map(|field| {
            let mut it = field.split(',');
            let step = Top2 {
                first: (it.next()?.parse().ok()?, it.next()?.parse().ok()?),
                second: (it.next()?.parse().ok()?, it.next()?.parse().ok()?),
            };
            it.next().is_none().then_some(step)
        })
        .collect()
}

/// Child side: greedy-decode `n` tokens and print each step's top two
/// and the backend the matvecs selected.
fn emit_tokens(
    model: &str,
    prompt: &str,
    prompt_tokens: Option<usize>,
    n: usize,
) -> anyhow::Result<()> {
    let path = crate::pull::resolve_model_path(model)?;
    let (steps, prompt_len) = crate::verify_engine::greedy_token_ids(
        Path::new(&path),
        prompt,
        frink_models::tokenizer::SpecialTokens::Parse,
        n,
        prompt_tokens,
    )?;
    println!("{LEN_TAG}{prompt_len}");
    println!("{TAG}{}", format_steps(&steps));
    println!(
        "{BACKEND_TAG}{}",
        frink_core::weight_matrix::active_backend().as_str()
    );
    Ok(())
}

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

    fn get<'a>(env: &'a [(&'static str, String)], name: &str) -> Option<&'a str> {
        env.iter()
            .find(|(n, _)| *n == name)
            .map(|(_, v)| v.as_str())
    }

    /// The bug: the reference inherited the shell's `FRINK_VULKAN`, so a
    /// `FRINK_VULKAN=1` shell checked Vulkan against Vulkan.
    #[test]
    fn the_reference_child_turns_every_gpu_off() {
        let env = child_env(OffloadDevice::Cpu, Some("1"));
        for name in offload::SWITCHES {
            assert_eq!(get(&env, name), Some("0"), "{name}");
        }
    }

    /// The other half: `--backend vulkan` set `FRINK_METAL=1` and never
    /// `FRINK_VULKAN`, so it checked the CPU or Metal instead.
    #[test]
    fn the_candidate_child_turns_on_only_its_backend() {
        for (device, own) in [
            (OffloadDevice::Metal, "FRINK_METAL"),
            (OffloadDevice::Cuda, "FRINK_CUDA"),
            (OffloadDevice::Rocm, "FRINK_CUDA"),
            (OffloadDevice::Vulkan, "FRINK_VULKAN"),
        ] {
            let env = child_env(device, None);
            for gpu in ["FRINK_METAL", "FRINK_CUDA", "FRINK_VULKAN"] {
                let want = if gpu == own { "1" } else { "0" };
                assert_eq!(get(&env, gpu), Some(want), "{device} {gpu}");
            }
        }
    }

    #[test]
    fn metal_attention_defaults_on_and_honours_an_ablation() {
        assert_eq!(
            get(&child_env(OffloadDevice::Metal, None), "FRINK_METAL_ATTN"),
            Some("1")
        );
        assert_eq!(
            get(
                &child_env(OffloadDevice::Metal, Some("0")),
                "FRINK_METAL_ATTN"
            ),
            Some("0")
        );
        // Off the Metal path it is off, whatever the shell said.
        assert_eq!(
            get(
                &child_env(OffloadDevice::Vulkan, Some("1")),
                "FRINK_METAL_ATTN"
            ),
            Some("0")
        );
    }

    #[test]
    fn unknown_and_non_gpu_backends_are_refused_by_name() {
        for name in ["hip", "auto", "none", "cpu"] {
            let err = parse_backend(name).unwrap_err().to_string();
            assert!(err.contains(name), "{name}: {err}");
            assert!(err.contains("metal, cuda, rocm or vulkan"), "{name}: {err}");
        }
    }

    /// A backend this binary was built without is refused before any
    /// child is spawned, naming the missing feature.
    #[cfg(not(feature = "vulkan"))]
    #[test]
    fn a_backend_not_compiled_in_is_refused_by_name() {
        let err = parse_backend("vulkan").unwrap_err().to_string();
        assert!(err.contains("--features vulkan"), "{err}");
    }

    #[test]
    fn a_child_that_ran_elsewhere_is_refused() {
        assert!(check_ran_on(OffloadDevice::Vulkan, "vulkan").is_ok());
        assert!(check_ran_on(OffloadDevice::Rocm, "cuda").is_ok());
        assert!(check_ran_on(OffloadDevice::Cpu, "cpu").is_ok());
        let err = check_ran_on(OffloadDevice::Vulkan, "metal").unwrap_err();
        assert!(err.to_string().contains("ran on metal"), "{err}");
        assert!(check_ran_on(OffloadDevice::Vulkan, "cpu").is_err());
        assert!(check_ran_on(OffloadDevice::Cpu, "vulkan").is_err());
    }

    #[test]
    fn steps_round_trip_through_the_child_line() {
        let steps = vec![
            Top2 {
                first: (9, 12.5),
                second: (3, 12.499_99),
            },
            Top2 {
                first: (0, -1.0e-7),
                second: (7, f32::NEG_INFINITY),
            },
        ];
        assert_eq!(parse_steps(&format_steps(&steps)), Some(steps));
        assert_eq!(parse_steps("1,2.0,3"), None);
        assert_eq!(parse_steps("1,2.0,3,4.0,5"), None);
    }
}