frink-cli 0.54.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! `frink bench -m`'s timed loops: one `pp<N>` and one `tg<N>` row per
//! engine, every repetition checked by `bench_guard` before and after.
//! Moved out of `bench_model.rs` unchanged.

use super::{BenchArgs, Row, RunOpts};
use crate::bench_guard::{self, CacheProbe, WorkloadDigest};
use frink_core::cache::KvCache;
use frink_models::engine::Engine;
use frink_models::{Decoder, Gemma4Engine};
use std::time::Instant;

/// `pp<N>` / `tg<N>` for the generic [`Decoder`].
pub(super) fn measure_decoder(decoder: &Decoder, args: &BenchArgs) -> anyhow::Result<Vec<Row>> {
    let mut rows: Vec<Row> = Vec::new();
    let mut tests = Tests::new(args);
    if args.n_prompt > 0 {
        let plan = tests.start(Phase::Prompt);
        rows.push(bench_prefill(decoder, args.n_prompt, &plan)?);
    }
    if args.n_gen > 0 {
        let plan = tests.start(Phase::Generation);
        rows.push(bench_decode(decoder, args.n_gen, &plan)?);
    }
    if let Some((pp, tg)) = args.pg {
        let plan = tests.start(Phase::Combined);
        rows.push(bench_combined(decoder, pp, tg, &plan)?);
    }
    for row in &rows {
        bench_guard::check_timed_samples(&row.test, args.reps, row.samples.len())?;
        bench_guard::check_sample_rates(&row.test, &row.samples)?;
    }
    Ok(rows)
}

/// `pp<N>` / `tg<N>` for [`Gemma4Engine`] (sequential tokens only).
pub(super) fn measure_gemma4(engine: &Gemma4Engine, args: &BenchArgs) -> anyhow::Result<Vec<Row>> {
    if args.pg.is_some() {
        anyhow::bail!(
            "-pg: the Gemma-4 engine has no batched prefill, so a combined prompt+generation \
             row would time a different prompt path from llama-bench's; run -p and -n instead"
        );
    }
    let mut rows: Vec<Row> = Vec::new();
    let mut tests = Tests::new(args);
    if args.n_prompt > 0 {
        let plan = tests.start(Phase::Prompt);
        rows.push(bench_prefill_gemma4(engine, args.n_prompt, &plan)?);
    }
    if args.n_gen > 0 {
        let plan = tests.start(Phase::Generation);
        rows.push(bench_decode_gemma4(engine, args.n_gen, &plan)?);
    }
    for row in &rows {
        bench_guard::check_timed_samples(&row.test, args.reps, row.samples.len())?;
        bench_guard::check_sample_rates(&row.test, &row.samples)?;
    }
    Ok(rows)
}

/// The engine-side half of the determinism assertion, threaded through
/// one row's repetitions.
///
/// Also where an empty logit vector is caught: a forward pass that
/// returned nothing cannot be shown to have computed anything, so the
/// duration it took is not a throughput.
pub(crate) fn check_result(
    test: &str,
    rep: usize,
    logits: &[f32],
    first: &mut Option<(usize, f32)>,
) -> anyhow::Result<()> {
    let pick = bench_guard::greedy_pick(logits)?.ok_or_else(|| {
        anyhow::anyhow!(
            "{test} rep {rep}: the forward pass returned no logits, so it cannot be \
             shown to have computed anything and its duration is not a throughput"
        )
    })?;
    let seen = *first.get_or_insert(pick);
    bench_guard::check_same_result(test, rep, seen, pick)
}

/// Snapshots every layer's KV cache for the guards in `bench_guard`.
pub(crate) fn probe(caches: &[KvCache]) -> Vec<CacheProbe> {
    caches.iter().map(probe_one).collect()
}

/// One layer's probe. An attention layer reports its resident ROWS,
/// beside the two buffer lengths they are derived from. A recurrent
/// layer (a Mamba, delta-net or short-conv block: K width zero, so
/// `rows()` is zero forever) has no rows to derive from, and its
/// position counter is the one length the block advances; reading rows
/// there refused every hybrid model's bench as "layer 0 consumed 0 of
/// 128 prompt tokens".
///
/// A windowed layer that evicts (#61, the default) is the other case
/// where rows stop being the length: past `window + slack` positions it
/// holds fewer rows than it consumed, and reading rows there would
/// refuse any row whose prompt passes the window as a run that skipped
/// work. Its position counter is what it consumed.
fn probe_one(c: &KvCache) -> CacheProbe {
    CacheProbe {
        seq_len: if c.k_width() == 0 || c.window().is_some() {
            c.positions()
        } else {
            c.rows()
        },
        k_len: c.k.len(),
        v_len: c.v.len(),
    }
}

/// Same, for Gemma-4's sparse `Vec<Option<KvCache>>` (shared-KV layers
/// leave holes, which are not caches and are not checked).
fn probe_gemma4(state: &frink_models::gemma4_engine::Gemma4DecodeState) -> Vec<CacheProbe> {
    state.kv.iter().flatten().map(probe_one).collect()
}

/// `pp<N>`: one batched forward over N tokens into fresh KV caches.
/// Reported as prompt tokens per second, as `llama-bench` does.
fn bench_prefill(decoder: &Decoder, n_prompt: usize, plan: &Test) -> anyhow::Result<Row> {
    let test = plan.label(format!("pp{n_prompt}"));
    let tokens = synthetic_tokens(decoder.config.vocab_size, n_prompt, 0);
    // Asserted BEFORE the run: the stream about to be fed is exactly as
    // long as the row's label promises, and every id is in vocabulary.
    bench_guard::check_prompt_before(&test, n_prompt, &tokens, decoder.config.vocab_size)?;
    let mut out = Vec::with_capacity(plan.reps);
    let mut first_digest: Option<WorkloadDigest> = None;
    let mut first_result: Option<(usize, f32)> = None;
    for rep in 0..plan.reps + plan.warmup {
        let mut caches = fresh_caches(decoder);
        // Every rep starts from an empty KV: a prefill that reused a
        // warm cache would report the engine's speed at work it did
        // not do. Asserted rather than assumed, so a later change to
        // `fresh_caches` cannot silently turn this into a cache-hit
        // benchmark.
        bench_guard::check_caches_cold(&test, rep, &probe(&caches))?;
        let mut digest = WorkloadDigest::new();
        let context = plan.fill_depth(rep, decoder.config.vocab_size, |ctx| {
            let _ = decoder.forward_batch_last(ctx, 0, &mut caches);
        });
        digest.feed_all(&context);
        digest.feed_all(&tokens);
        plan.announce(rep);
        let t = Instant::now();
        // `forward_batch_last`, not `forward_batch`: llama-bench's
        // `pp512` asks for logits at the final position only, so
        // projecting all 512 rows through the vocabulary would be work
        // the reference engine never does.
        let logits = prefill(decoder, &tokens, plan.depth, plan.chunk, &mut caches);
        let dt = t.elapsed().as_secs_f64();
        // The prompt length is asserted AFTER the run too, not only
        // before: an engine that silently truncated the batch would
        // otherwise divide the full token count by a partial run's
        // time and report a speedup for doing less work.
        bench_guard::check_prefill_after(&test, plan.depth + n_prompt, &probe(&caches))?;
        let first = *first_digest.get_or_insert(digest);
        bench_guard::check_same_workload(&test, rep, first, digest)?;
        check_result(&test, rep, &logits, &mut first_result)?;
        // Rep 0 is the warmup: first touch of every weight page, and on
        // Metal the first pipeline compile. Timing it would measure the
        // OS and the shader cache, not the engine.
        if rep >= plan.warmup {
            out.push(n_prompt as f64 / dt);
        }
    }
    Ok(Row {
        test,
        samples: out,
        n_prompt,
        n_gen: 0,
        n_depth: plan.depth,
        test_time: plan.time.clone(),
        digest: first_digest.unwrap_or_default(),
    })
}

/// Gemma-4 `pp<N>`: sequential `forward_token` over N synthetic ids.
/// Keeps only the final logits (same work llama-bench reports), but
/// without batched matmuls — honest for today's engine.
fn bench_prefill_gemma4(
    engine: &Gemma4Engine,
    n_prompt: usize,
    plan: &Test,
) -> anyhow::Result<Row> {
    let test = plan.label(format!("pp{n_prompt}"));
    let vocab = Engine::vocab_size(engine);
    let tokens = synthetic_tokens(vocab, n_prompt, 0);
    bench_guard::check_prompt_before(&test, n_prompt, &tokens, vocab)?;
    let mut out = Vec::with_capacity(plan.reps);
    let mut first_digest: Option<WorkloadDigest> = None;
    let mut first_result: Option<(usize, f32)> = None;
    for rep in 0..plan.reps + plan.warmup {
        let mut state = Engine::new_state(engine);
        bench_guard::check_caches_cold(&test, rep, &probe_gemma4(&state))?;
        let mut digest = WorkloadDigest::new();
        let context = plan.fill_depth(rep, vocab, |ctx| {
            for (i, &tok) in ctx.iter().enumerate() {
                let _ = Engine::forward_token(engine, tok, i, &mut state);
            }
        });
        digest.feed_all(&context);
        plan.announce(rep);
        let t = Instant::now();
        let mut logits = Vec::new();
        for (i, &tok) in tokens.iter().enumerate() {
            digest.feed(tok);
            logits = Engine::forward_token(engine, tok, plan.depth + i, &mut state);
        }
        let dt = t.elapsed().as_secs_f64();
        bench_guard::check_prefill_after(&test, plan.depth + n_prompt, &probe_gemma4(&state))?;
        let first = *first_digest.get_or_insert(digest);
        bench_guard::check_same_workload(&test, rep, first, digest)?;
        check_result(&test, rep, &logits, &mut first_result)?;
        if rep >= plan.warmup {
            out.push(n_prompt as f64 / dt);
        }
    }
    Ok(Row {
        test,
        samples: out,
        n_prompt,
        n_gen: 0,
        n_depth: plan.depth,
        test_time: plan.time.clone(),
        digest: first_digest.unwrap_or_default(),
    })
}

/// `tg<N>`: N single-token decode steps after a one-token prime, so KV
/// length grows exactly as it does in real generation.
/// Whether the host-side `KvCache` is where the KV actually lands.
///
/// With GPU offload it is not: the device holds the KV and the host
/// struct stays empty unless `FRINK_CPU_KV_OFFLOAD=1` syncs it back.
/// Any assertion that counts host cache positions has to know that, or
/// it refuses every GPU run for doing nothing wrong.
pub(crate) fn host_kv_is_the_record() -> bool {
    let off = |k: &str| std::env::var(k).map(|v| v == "0").unwrap_or(false);
    let synced = std::env::var("FRINK_CPU_KV_OFFLOAD").as_deref() == Ok("1");
    synced || (off("FRINK_METAL") && off("FRINK_CUDA"))
}

fn bench_decode(decoder: &Decoder, n_gen: usize, plan: &Test) -> anyhow::Result<Row> {
    let test = plan.label(format!("tg{n_gen}"));
    let vocab = decoder.config.vocab_size;
    let tokens = decode_tokens(vocab, n_gen, 0);
    // The decode stream gets the same BEFORE check the prompt does. It
    // is built up front for exactly that reason: a stream generated
    // inside the timed loop can only be checked once it is too late to
    // refuse.
    bench_guard::check_prompt_before(&test, n_gen, &tokens, vocab)?;
    let mut out = Vec::with_capacity(plan.reps);
    let mut first_digest: Option<WorkloadDigest> = None;
    let mut first_result: Option<(usize, f32)> = None;
    for rep in 0..plan.reps + plan.warmup {
        let mut caches = fresh_caches(decoder);
        bench_guard::check_caches_cold(&test, rep, &probe(&caches))?;
        let mut digest = WorkloadDigest::new();
        let context = plan.fill_depth(rep, vocab, |ctx| {
            let _ = decoder.forward_batch_last(ctx, 0, &mut caches);
        });
        digest.feed_all(&context);
        let _ = decoder.forward_token(0, plan.depth, &mut caches);
        plan.announce(rep);
        let t = Instant::now();
        let mut logits = Vec::new();
        for (i, &tok) in tokens.iter().enumerate() {
            digest.feed(tok);
            logits = decoder.forward_token(tok, plan.depth + i + 1, &mut caches);
        }
        let dt = t.elapsed().as_secs_f64();
        // One priming token plus n_gen decode steps. A short cache
        // means steps were skipped, which would inflate the rate.
        let kv_checked = bench_guard::check_decode_after(
            &test,
            plan.depth + 1,
            n_gen,
            &probe(&caches),
            host_kv_is_the_record(),
        )?;
        let _ = kv_checked;
        let first = *first_digest.get_or_insert(digest);
        bench_guard::check_same_workload(&test, rep, first, digest)?;
        check_result(&test, rep, &logits, &mut first_result)?;
        if rep >= plan.warmup {
            out.push(n_gen as f64 / dt);
        }
    }
    Ok(Row {
        test,
        samples: out,
        n_prompt: 0,
        n_gen,
        n_depth: plan.depth,
        test_time: plan.time.clone(),
        digest: first_digest.unwrap_or_default(),
    })
}

fn bench_decode_gemma4(engine: &Gemma4Engine, n_gen: usize, plan: &Test) -> anyhow::Result<Row> {
    let test = plan.label(format!("tg{n_gen}"));
    let vocab = Engine::vocab_size(engine);
    let tokens = decode_tokens(vocab, n_gen, 0);
    bench_guard::check_prompt_before(&test, n_gen, &tokens, vocab)?;
    let mut out = Vec::with_capacity(plan.reps);
    let mut first_digest: Option<WorkloadDigest> = None;
    let mut first_result: Option<(usize, f32)> = None;
    for rep in 0..plan.reps + plan.warmup {
        let mut state = Engine::new_state(engine);
        bench_guard::check_caches_cold(&test, rep, &probe_gemma4(&state))?;
        let mut digest = WorkloadDigest::new();
        let context = plan.fill_depth(rep, vocab, |ctx| {
            for (i, &tok) in ctx.iter().enumerate() {
                let _ = Engine::forward_token(engine, tok, i, &mut state);
            }
        });
        digest.feed_all(&context);
        let _ = Engine::forward_token(engine, 0, plan.depth, &mut state);
        plan.announce(rep);
        let t = Instant::now();
        let mut logits = Vec::new();
        for (i, &tok) in tokens.iter().enumerate() {
            digest.feed(tok);
            logits = Engine::forward_token(engine, tok, plan.depth + i + 1, &mut state);
        }
        let dt = t.elapsed().as_secs_f64();
        let kv_checked = bench_guard::check_decode_after(
            &test,
            plan.depth + 1,
            n_gen,
            &probe_gemma4(&state),
            host_kv_is_the_record(),
        )?;
        let _ = kv_checked;
        let first = *first_digest.get_or_insert(digest);
        bench_guard::check_same_workload(&test, rep, first, digest)?;
        check_result(&test, rep, &logits, &mut first_result)?;
        if rep >= plan.warmup {
            out.push(n_gen as f64 / dt);
        }
    }
    Ok(Row {
        test,
        samples: out,
        n_prompt: 0,
        n_gen,
        n_depth: plan.depth,
        test_time: plan.time.clone(),
        digest: first_digest.unwrap_or_default(),
    })
}

/// llama-bench's `-pg pp,tg` (`pp<P>+tg<G>`): a batched prompt of `pp`
/// tokens and then `tg` single-token steps continuing from it, the
/// whole timed as one test and reported as `(pp + tg) / time`, as
/// llama-bench's `get_ts` reports it. The generation continues straight
/// from the prompt with no priming token of its own, as llama-bench's
/// `test_gen` continues from the KV's last position.
fn bench_combined(decoder: &Decoder, pp: usize, tg: usize, plan: &Test) -> anyhow::Result<Row> {
    let test = plan.label(format!("pp{pp}+tg{tg}"));
    let vocab = decoder.config.vocab_size;
    let prompt = synthetic_tokens(vocab, pp, 0);
    let gen = decode_tokens(vocab, tg, 0);
    bench_guard::check_prompt_before(&test, pp, &prompt, vocab)?;
    bench_guard::check_prompt_before(&test, tg, &gen, vocab)?;
    let mut out = Vec::with_capacity(plan.reps);
    let mut first_digest: Option<WorkloadDigest> = None;
    let mut first_result: Option<(usize, f32)> = None;
    for rep in 0..plan.reps + plan.warmup {
        let mut caches = fresh_caches(decoder);
        bench_guard::check_caches_cold(&test, rep, &probe(&caches))?;
        let mut digest = WorkloadDigest::new();
        let context = plan.fill_depth(rep, vocab, |ctx| {
            let _ = decoder.forward_batch_last(ctx, 0, &mut caches);
        });
        digest.feed_all(&context);
        digest.feed_all(&prompt);
        plan.announce(rep);
        let t = Instant::now();
        let mut logits = prefill(decoder, &prompt, plan.depth, plan.chunk, &mut caches);
        plan.announce_generation(rep);
        for (i, &tok) in gen.iter().enumerate() {
            digest.feed(tok);
            logits = decoder.forward_token(tok, plan.depth + pp + i, &mut caches);
        }
        let dt = t.elapsed().as_secs_f64();
        // The prompt and every generation step must be in the cache: a
        // short one means work was skipped and the rate would count it.
        let kv_checked = bench_guard::check_decode_after(
            &test,
            plan.depth + pp,
            tg,
            &probe(&caches),
            host_kv_is_the_record(),
        )?;
        let _ = kv_checked;
        let first = *first_digest.get_or_insert(digest);
        bench_guard::check_same_workload(&test, rep, first, digest)?;
        check_result(&test, rep, &logits, &mut first_result)?;
        if rep >= plan.warmup {
            out.push((pp + tg) as f64 / dt);
        }
    }
    Ok(Row {
        test,
        samples: out,
        n_prompt: pp,
        n_gen: tg,
        n_depth: plan.depth,
        test_time: plan.time.clone(),
        digest: first_digest.unwrap_or_default(),
    })
}

/// A prompt's batched forward, in `chunk`-token pieces when llama-bench's
/// `-b` / `-ub` asked for them, as `test_prompt` submits it
/// (`llama-bench.cpp:2179-2192`): each piece continues from where the
/// last left the KV, and the logits are the final piece's last row.
/// `None` is the whole prompt in one pass.
fn prefill(
    decoder: &Decoder,
    tokens: &[usize],
    start: usize,
    chunk: Option<usize>,
    caches: &mut [KvCache],
) -> Vec<f32> {
    let step = chunk.unwrap_or(tokens.len()).max(1);
    let mut logits = Vec::new();
    for (k, piece) in tokens.chunks(step).enumerate() {
        logits = decoder.forward_batch_last(piece, start + k * step, caches);
    }
    logits
}

pub(crate) fn fresh_caches(decoder: &Decoder) -> Vec<KvCache> {
    decoder.config.new_kv_caches()
}

/// Token ids that exist in the vocabulary but carry no linguistic
/// meaning: the point is to move the same bytes through the same
/// kernels, not to generate text.
///
/// `seq` offsets the stream so that parallel sequences in a batched
/// row do not carry identical prompts. Sequence 0 is the stream
/// `frink bench` has always fed, so its published digests still
/// describe the same work.
pub(crate) fn synthetic_tokens(vocab: usize, n: usize, seq: usize) -> Vec<usize> {
    let vocab = vocab.max(1);
    (0..n)
        .map(|i| (i * 7 + 1 + seq * SEQ_STRIDE) % vocab)
        .collect()
}

/// The token stream a `tg<N>` row feeds after its priming token, built
/// before the clock starts so its length can be asserted BEFORE the run
/// rather than only reconstructed from the KV cache afterwards.
///
/// `seq` as in [`synthetic_tokens`]: sequence 0 is the historical
/// stream, other sequences are shifted copies of it.
pub(crate) fn decode_tokens(vocab: usize, n_gen: usize, seq: usize) -> Vec<usize> {
    let vocab = vocab.max(1);
    (0..n_gen)
        .map(|i| (i + 1 + seq * SEQ_STRIDE) % vocab)
        .collect()
}

/// How far apart two parallel sequences' token streams start. Any
/// non-zero value distinguishes them; this one is co-prime with the
/// prompt stride of 7 so no two sequences' prompts coincide either.
const SEQ_STRIDE: usize = 1013;

/// The stream a `-d` context is drawn from: its own sequence, so the
/// context never repeats the prompt that follows it.
const DEPTH_SEQ: usize = 7;

/// Which half of llama-bench's workload a test is, for its progress
/// lines.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Phase {
    Prompt,
    Generation,
    /// llama-bench's `-pg pp,tg`: a prompt then a generation, timed as
    /// one test.
    Combined,
}

/// The tests of one run, numbered as llama-bench numbers its instances
/// (`benchmark i/N`).
struct Tests {
    opts: RunOpts,
    reps: usize,
    count: usize,
    next: usize,
    depth: usize,
    chunk: Option<usize>,
}

impl Tests {
    fn new(args: &BenchArgs) -> Self {
        Self {
            opts: args.run,
            reps: args.reps,
            count: usize::from(args.n_prompt > 0)
                + usize::from(args.n_gen > 0)
                + usize::from(args.pg.is_some()),
            next: 0,
            depth: args.depth,
            chunk: args.chunk,
        }
    }

    /// Starts the next test: llama-bench's `starting` line, then its
    /// `--delay` cool-off, both before anything is timed.
    fn start(&mut self, phase: Phase) -> Test {
        self.next += 1;
        let t = Test {
            reps: self.reps,
            warmup: self.opts.warmup,
            phase,
            progress: self.opts.progress.then_some((self.next, self.count)),
            time: super::output::now_iso8601(),
            depth: self.depth,
            chunk: self.chunk,
        };
        if let Some(line) = t.line("starting") {
            eprintln!("{line}");
        }
        if self.opts.delay_s > 0 {
            std::thread::sleep(std::time::Duration::from_secs(self.opts.delay_s));
        }
        t
    }
}

/// One test's repetition plan: `warmup` untimed, then `reps` timed.
struct Test {
    reps: usize,
    warmup: usize,
    phase: Phase,
    /// `(i, N)` when `--progress` asked for llama-bench's lines.
    progress: Option<(usize, usize)>,
    /// When the test started, llama-bench's `test_time`.
    time: String,
    /// llama-bench's `-d`: context tokens in the KV before each timed
    /// repetition, put there untimed.
    depth: usize,
    /// llama-bench's `-b` / `-ub`, resolved: prompt tokens per forward
    /// pass, or the whole prompt in one when neither was given.
    chunk: Option<usize>,
}

impl Test {
    fn line(&self, what: &str) -> Option<String> {
        self.progress
            .map(|(i, n)| format!("frink bench: benchmark {i}/{n}: {what}"))
    }

    /// llama-bench's per-repetition progress text (`llama-bench.cpp`,
    /// the warmup and timed loops of `main`).
    fn rep_label(&self, rep: usize) -> String {
        self.rep_label_as(rep, self.phase)
    }

    /// [`Self::rep_label`] for one half of a test: a combined test
    /// announces its prompt and then its generation, as llama-bench
    /// does for a `-pg` instance.
    fn rep_label_as(&self, rep: usize, phase: Phase) -> String {
        let kind = match phase {
            Phase::Prompt | Phase::Combined => "prompt",
            Phase::Generation => "generation",
        };
        if rep < self.warmup {
            format!("warmup {kind} run")
        } else {
            format!("{kind} run {}/{}", rep - self.warmup + 1, self.reps)
        }
    }

    /// The row's name, with llama-bench's ` @ d<N>` when it ran at a
    /// depth (`llama-bench.cpp`, the markdown printer).
    fn label(&self, base: String) -> String {
        if self.depth > 0 {
            format!("{base} @ d{}", self.depth)
        } else {
            base
        }
    }

    /// Fills the KV with `depth` context tokens before a repetition,
    /// untimed, as llama-bench's depth run does; returns them so the
    /// caller can digest them. Nothing happens at depth 0.
    fn fill_depth(&self, rep: usize, vocab: usize, run: impl FnOnce(&[usize])) -> Vec<usize> {
        if self.depth == 0 {
            return Vec::new();
        }
        if rep >= self.warmup {
            if let Some(line) = self.line(&format!(
                "depth run {}/{}",
                rep - self.warmup + 1,
                self.reps
            )) {
                eprintln!("{line}");
            }
        }
        let context = synthetic_tokens(vocab, self.depth, DEPTH_SEQ);
        run(&context);
        context
    }

    /// The generation half of a combined test's repetition.
    fn announce_generation(&self, rep: usize) {
        if let Some(line) = self.line(&self.rep_label_as(rep, Phase::Generation)) {
            eprintln!("{line}");
        }
    }

    fn announce(&self, rep: usize) {
        if let Some(line) = self.line(&self.rep_label(rep)) {
            eprintln!("{line}");
        }
    }
}

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

    fn test(warmup: usize, phase: Phase, progress: bool) -> Test {
        Test {
            reps: 3,
            warmup,
            phase,
            progress: progress.then_some((2, 2)),
            time: String::new(),
            depth: 0,
            chunk: None,
        }
    }

    /// The progress text is llama-bench's, warmup first, timed
    /// repetitions counted from 1, under `frink bench`'s prefix.
    #[test]
    fn progress_lines_are_llama_benchs() {
        let t = test(1, Phase::Prompt, true);
        assert_eq!(
            t.line(&t.rep_label(0)).unwrap(),
            "frink bench: benchmark 2/2: warmup prompt run"
        );
        assert_eq!(t.rep_label(1), "prompt run 1/3");
        assert_eq!(t.rep_label(3), "prompt run 3/3");
        let g = test(1, Phase::Generation, true);
        assert_eq!(g.rep_label(0), "warmup generation run");
        assert_eq!(g.rep_label(2), "generation run 2/3");
    }

    /// A depth row is named as llama-bench names it, and a depth-0 row
    /// keeps the name every published receipt used.
    #[test]
    fn a_combined_test_announces_its_prompt_then_its_generation() {
        let t = test(1, Phase::Combined, true);
        assert_eq!(t.rep_label(0), "warmup prompt run");
        assert_eq!(t.rep_label(2), "prompt run 2/3");
        assert_eq!(t.rep_label_as(2, Phase::Generation), "generation run 2/3");
    }

    /// `-b` / `-ub` change how the prompt is submitted, not what it
    /// computes: the final logits of a prompt fed in pieces are the ones
    /// a single pass gives, to f32 accumulation order, and the KV ends at
    /// the same length. Odd sizes on purpose, so the last piece is short.
    #[test]
    fn a_chunked_prefill_computes_what_one_pass_does() {
        let cfg = frink_models::config::test_dense_fixture();
        let vocab = cfg.vocab_size;
        let decoder = frink_models::Decoder::new_random_small(cfg, 2, vocab);
        let tokens = synthetic_tokens(vocab, 23, 0);
        let mut whole_kv = fresh_caches(&decoder);
        let whole = prefill(&decoder, &tokens, 0, None, &mut whole_kv);
        for chunk in [1usize, 5, 8, 22, 23, 64] {
            let mut kv = fresh_caches(&decoder);
            let got = prefill(&decoder, &tokens, 0, Some(chunk), &mut kv);
            let worst = got
                .iter()
                .zip(&whole)
                .map(|(a, b)| (a - b).abs())
                .fold(0f32, f32::max);
            assert!(worst < 1e-4, "chunk {chunk}: logits moved {worst}");
            assert_eq!(probe(&kv), probe(&whole_kv), "chunk {chunk}: KV length");
        }
    }

    #[test]
    fn a_depth_row_is_named_with_llama_benchs_at_suffix() {
        let mut t = test(1, Phase::Prompt, false);
        assert_eq!(t.label("pp512".into()), "pp512");
        t.depth = 4096;
        assert_eq!(t.label("pp512".into()), "pp512 @ d4096");
        let mut ran = 0;
        let ctx = t.fill_depth(0, 32000, |c| ran = c.len());
        assert_eq!((ran, ctx.len()), (4096, 4096));
        t.depth = 0;
        assert!(t
            .fill_depth(0, 32000, |_| panic!("depth 0 runs nothing"))
            .is_empty());
    }

    /// `--no-warmup` makes repetition 0 a timed one, and with no
    /// `--progress` nothing is printed at all.
    #[test]
    fn no_warmup_times_from_the_first_repetition_and_quiet_prints_nothing() {
        let t = test(0, Phase::Prompt, false);
        assert_eq!(t.rep_label(0), "prompt run 1/3");
        assert!(t.line("starting").is_none());
    }

    #[test]
    fn both_token_streams_satisfy_the_before_check_they_are_handed_to() {
        // The generators and the guard have to agree, or the BEFORE
        // check would be a refusal of every run rather than of a bad
        // one. `vocab` deliberately includes values smaller than the
        // stream, where the modulo wraps.
        for &(vocab, n) in &[(49152usize, 512usize), (7, 512), (2, 4), (49152, 1)] {
            for seq in [0, 1, 31] {
                bench_guard::check_prompt_before("pp", n, &synthetic_tokens(vocab, n, seq), vocab)
                    .unwrap();
                bench_guard::check_prompt_before("tg", n, &decode_tokens(vocab, n, seq), vocab)
                    .unwrap();
            }
        }
    }

    /// Sequence 0 is the stream every published `frink bench` digest
    /// was computed over; adding the `seq` parameter must not have
    /// moved it. The other sequences must differ from it, or a batched
    /// row would prefill the same prompt B times.
    #[test]
    fn sequence_zero_is_the_historical_stream_and_other_sequences_differ() {
        let vocab = 32000;
        let historical: Vec<usize> = (0..64).map(|i| (i * 7 + 1) % vocab).collect();
        assert_eq!(synthetic_tokens(vocab, 64, 0), historical);
        assert_ne!(
            synthetic_tokens(vocab, 64, 1),
            synthetic_tokens(vocab, 64, 0)
        );
        assert_ne!(decode_tokens(vocab, 64, 1), decode_tokens(vocab, 64, 0));
        assert_ne!(
            synthetic_tokens(vocab, 64, 2),
            synthetic_tokens(vocab, 64, 1)
        );
    }

    #[test]
    fn the_decode_stream_is_the_one_the_loop_used_to_generate_inline() {
        // Hoisting it out of the timed loop must not have changed the
        // workload: same ids, same order, so digests published before
        // and after this change still describe the same work.
        let vocab = 32000;
        let inline: Vec<usize> = (0..128).map(|i| (i + 1) % vocab).collect();
        assert_eq!(decode_tokens(vocab, 128, 0), inline);
    }

    #[test]
    fn a_repetition_that_returned_no_logits_is_refused_rather_than_timed() {
        let mut first = None;
        let err = check_result("pp512", 1, &[], &mut first)
            .unwrap_err()
            .to_string();
        assert!(err.contains("returned no logits"), "{err}");
    }

    #[test]
    fn the_first_repetitions_answer_becomes_the_one_the_rest_must_match() {
        let mut first = None;
        check_result("pp512", 0, &[0.1, 0.9, 0.2], &mut first).unwrap();
        assert_eq!(first, Some((1, 0.9)));
        // Same answer, different magnitudes: still the same work.
        check_result("pp512", 1, &[0.2, 0.7, 0.1], &mut first).unwrap();
        // A different answer from the same token stream is not.
        assert!(check_result("pp512", 2, &[0.9, 0.1, 0.2], &mut first).is_err());
    }
}