frink-cli 0.61.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
//! `frink bench`: the flag surface, and the synthetic kernel benchmark
//! that runs when no model is named.
//!
//! Moved out of `main.rs` verbatim (a pure move) before `frink bench`
//! grew llama-bench's flags, so they land in a file of their own rather
//! than in a 1500-line one.

use clap::Args;

use frink_models::{deepseek_v4_pro, glm_5_2, kimi_k3, Decoder};

use crate::{bench_model, bench_render, bench_suite, host_state};

/// `frink bench`'s flags (llama-bench's `-m`/`-p`/`-n`/`-r`/...).
#[derive(Args)]
pub struct BenchCmd {
    /// Real GGUF to benchmark. With this set, `bench` becomes a
    /// `llama-bench` work-alike (pp/tg on real weights) and the
    /// synthetic matvec microbenchmark below is skipped.
    #[arg(short = 'm', long)]
    pub model: Option<String>,
    /// Hugging Face repo to benchmark, `user/repo[:QUANT]`, llama-bench's
    /// `-hf`. Fetched into the frink cache on first use, as `frink run
    /// -hf` does, before anything else reads the model path.
    #[arg(long = "hf-repo", visible_aliases = ["hf", "hfr"], value_name = "REPO[:QUANT]",
          conflicts_with = "model")]
    pub hf_repo: Option<String>,
    /// Exact filename inside `--hf-repo`, llama-bench's `-hff`.
    #[arg(
        long = "hf-file",
        visible_alias = "hff",
        value_name = "FILE",
        requires = "hf_repo"
    )]
    pub hf_file: Option<String>,
    /// Hugging Face access token for `-hf`, llama-bench's `-hft`. Sets
    /// `HF_TOKEN`, the variable the downloader reads.
    #[arg(long = "hf-token", visible_alias = "hft", value_name = "TOKEN")]
    pub hf_token: Option<String>,
    /// llama.cpp's `--offline`: forces use of the cache and prevents
    /// network access. A `-hf` reference resolves against the files the
    /// frink cache already holds, and one it does not hold is refused
    /// naming the cache directory.
    #[arg(long, default_value_t = false)]
    pub offline: bool,
    /// KV cache type for K, llama-bench's `-ctk`. One value per run, and
    /// only one this backend's KV store actually holds (`f16`, the
    /// default, or `f32` on CPU and Metal): a type the store would fall
    /// back from is refused, since the row would measure another one.
    #[arg(long = "cache-type-k", visible_alias = "ctk", value_name = "TYPE")]
    pub cache_type_k: Option<String>,
    /// KV cache type for V, llama-bench's `-ctv`. frink's KV store has one
    /// type for K and V, so this must equal `-ctk` (or be left out).
    #[arg(long = "cache-type-v", visible_alias = "ctv", value_name = "TYPE")]
    pub cache_type_v: Option<String>,
    /// Prompt tokens for the `pp<N>` batched-prefill row (`0` skips).
    #[arg(short = 'p', long = "n-prompt", default_value_t = 512)]
    pub n_prompt: usize,
    /// Decode steps for the `tg<N>` row (`0` skips).
    #[arg(short = 'n', long = "n-gen", default_value_t = 128)]
    pub n_gen: usize,
    /// llama-bench's `-d`: run each test with this many context tokens
    /// already in the KV cache, put there untimed before every
    /// repetition. The row is named `pp512 @ d4096`, as llama-bench
    /// names it. One value per run.
    #[arg(short = 'd', long = "n-depth", default_value_t = 0)]
    pub n_depth: usize,
    /// llama-bench's `-pg pp,tg`: also run one combined test, a prompt of
    /// `pp` tokens and then `tg` generated ones timed as a unit and named
    /// `pp512+tg128`. One pair per run.
    #[arg(long = "pg", value_name = "PP,TG", value_parser = parse_pg)]
    pub pg: Option<(usize, usize)>,
    /// llama-bench's `-b`: the logical batch, prompt tokens submitted per
    /// call. With `-ub`, the two resolve to one physical size as
    /// llama.cpp resolves them (the smaller; either alone stands for
    /// both), and the `pp` and `pp+tg` rows submit their prompt in pieces
    /// of that size. Neither given is the whole prompt in one pass. One
    /// value per run.
    #[arg(long = "batch-size", visible_alias = "b", value_name = "N",
          value_parser = clap::value_parser!(u64).range(1..))]
    pub batch_size: Option<u64>,
    /// llama-bench's `-ub`: the physical batch. See `-b`.
    #[arg(long = "ubatch-size", visible_alias = "ub", value_name = "N",
          value_parser = clap::value_parser!(u64).range(1..))]
    pub ubatch_size: Option<u64>,
    /// Timed repetitions per row; one extra warmup is discarded.
    #[arg(short = 'r', long = "repetitions", default_value_t = 3)]
    pub reps: usize,
    /// CPU threads (`0` = performance-core default)
    #[arg(short = 't', long, default_value_t = 0)]
    pub threads: usize,
    /// GPU layers, llama-bench's `-ngl`: `0` forces CPU, the model's
    /// layer count or more offloads all of them, and a partial count
    /// in between is refused (frink has no partial placement).
    #[arg(long = "n-gpu-layers", visible_alias = "ngl", default_value_t = 0)]
    pub n_gpu_layers: usize,
    /// Context size (`0` = GGUF default)
    #[arg(short = 'c', long, default_value_t = 0)]
    pub ctx_size: usize,
    #[arg(long, default_value_t = 4096)]
    pub hidden: usize,
    #[arg(long, default_value_t = 14336)]
    pub ffn_dim: usize,
    #[arg(long, default_value_t = 20)]
    pub iters: usize,
    /// Also run `llama-bench` on the same GGUF and print the gap.
    #[arg(long)]
    pub compare: bool,
    /// Run every entry in `benchmarks/suite.json` (each in a fresh
    /// child process), write engine receipts, then re-render the
    /// engine table in `benchmarks/RESULTS.md`.
    #[arg(long)]
    pub suite: bool,
    /// Re-render the engine table from existing receipts only.
    #[arg(long)]
    pub render: bool,
    /// Restrict `--suite` to one suite id.
    #[arg(long)]
    pub id: Option<String>,
    /// Restrict `--suite` to one backend.
    #[arg(long)]
    pub backend: Option<String>,
    /// Skip suite entries whose estimated RAM exceeds ~75% of host RAM.
    #[arg(long)]
    pub fit_host: bool,
    /// Skip suite entries whose GGUF is not present.
    #[arg(long)]
    pub skip_missing: bool,
    /// benchmarks/ directory.
    #[arg(long, default_value = "benchmarks")]
    pub bench_dir: String,
    /// Internal (`--suite` children): suite id to record in the receipt.
    #[arg(long)]
    pub suite_id: Option<String>,
    /// Internal (`--suite` children): backend label for the receipt.
    #[arg(long, default_value = "cpu")]
    pub backend_label: String,
    /// Write a JSON receipt to this path.
    #[arg(long)]
    pub receipt: Option<String>,
    /// Refuse to start a timed run when the host's 1-minute load
    /// average is at or above this. `0` disables the check and
    /// marks the receipt as not quiet-host.
    #[arg(long, default_value_t = host_state::DEFAULT_MAX_LOAD)]
    pub max_load: f64,
    /// Flash attention, llama-bench's `-fa` (`on`, `off`, `auto`; the
    /// default is `auto` on both). `on` and `auto` are what frink does
    /// wherever the backend has a fused kernel; `off` is refused, and so
    /// is llama-bench's comma-separated sweep, since one `frink bench`
    /// run measures one configuration.
    #[arg(long = "flash-attn", visible_alias = "fa", value_name = "MODE")]
    pub flash_attn: Option<String>,
    /// Print the devices this build can run on and exit, llama-bench's
    /// `--list-devices`.
    #[arg(long = "list-devices", default_value_t = false)]
    pub list_devices: bool,
    /// llama-bench's `--no-warmup`: time every repetition, with no
    /// discarded warmup first. Refused with `--receipt`, whose
    /// measurement contract requires the warmup.
    #[arg(long = "no-warmup", default_value_t = false)]
    pub no_warmup: bool,
    /// llama-bench's `--delay`: seconds to sleep before each test, to
    /// let the host cool off between them.
    #[arg(long, default_value_t = 0, value_name = "SECONDS")]
    pub delay: u64,
    /// llama-bench's `--prio`: process priority, `-1` low, `0` normal,
    /// `1` medium, `2` high, `3` realtime. Applied before any worker
    /// thread exists, as `nice` 5, 0, -5, -10, -20 (llama.cpp's
    /// `set_process_priority`); a priority the OS refuses is an error.
    #[arg(long, default_value_t = 0, allow_negative_numbers = true,
          value_parser = clap::value_parser!(i32).range(-1..=3))]
    pub prio: i32,
    /// llama-bench's `--progress`: print each test's progress to stderr.
    #[arg(long, default_value_t = false)]
    pub progress: bool,
    /// llama-bench's `-o`: `md` (the table, the default), `csv`, `json`,
    /// `jsonl` or `sql` on stdout, with llama-bench's field names. Under
    /// anything but `md`, every other line `frink bench` prints goes to
    /// stderr so stdout stays parseable.
    #[arg(
        short = 'o',
        long = "output",
        default_value = "md",
        value_name = "FORMAT"
    )]
    pub output: String,
    /// llama-bench's `-oe`: the same formats (or `none`, the default) on
    /// stderr.
    #[arg(
        long = "output-err",
        visible_alias = "oe",
        default_value = "none",
        value_name = "FORMAT"
    )]
    pub output_err: String,
}

/// `frink bench -fa VALUE`: one value through the shared
/// [`frink_core::argv::check_flash_attn`], with llama-bench's sweep
/// (`-fa 0,1`) refused by name rather than read as an unknown value.
fn check_bench_flash_attn(value: &str) -> anyhow::Result<()> {
    if value.contains(',') {
        anyhow::bail!(
            "--flash-attn {value}: frink bench measures one configuration per run;              llama-bench's comma-separated sweep is not implemented. Run once per value"
        );
    }
    frink_core::argv::check_flash_attn(value).map_err(|e| anyhow::anyhow!(e))
}

/// llama-bench's `-pg pp,tg`: exactly two counts, not both zero (an
/// instance llama-bench drops, `llama-bench.cpp:1432`).
fn parse_pg(value: &str) -> Result<(usize, usize), String> {
    let (pp, tg) = value
        .split_once(',')
        .ok_or_else(|| format!("-pg {value}: expected PP,TG"))?;
    let n = |s: &str| {
        s.trim()
            .parse::<usize>()
            .map_err(|_| format!("-pg {value}: `{s}` is not a token count"))
    };
    let pair = (n(pp)?, n(tg)?);
    if pair == (0, 0) {
        return Err(format!(
            "-pg {value}: a test of zero tokens measures nothing"
        ));
    }
    Ok(pair)
}

/// One `-ctk` / `-ctv` value, through the same parser `frink run` and
/// `frink-server` use, with llama-bench's sweep refused by name.
fn check_cache_type(flag: &str, value: &str) -> anyhow::Result<String> {
    if value.contains(',') {
        anyhow::bail!(
            "{flag} {value}: frink bench measures one configuration per run; llama-bench's \
             comma-separated sweep is not implemented. Run once per value"
        );
    }
    frink_models::ctk::parse_value(value).map_err(|e| anyhow::anyhow!("{flag}: {e}"))
}

impl BenchCmd {
    /// The llama-bench flags settled before any worker thread exists
    /// (`main` calls this ahead of `bench_model::apply_env`): `-ctk` /
    /// `-ctv` checked and written to `FRINK_CTK`, `-hft` to `HF_TOKEN`,
    /// and `-hf` resolved to a local path, as `frink run` resolves it
    /// before its own backend setup.
    pub fn apply_llama_flags(&mut self) -> anyhow::Result<()> {
        let k = match &self.cache_type_k {
            Some(v) => Some(check_cache_type("--cache-type-k", v)?),
            None => None,
        };
        if let Some(v) = &self.cache_type_v {
            let v = check_cache_type("--cache-type-v", v)?;
            let k_or_default = k.clone().unwrap_or_else(|| "f16".to_string());
            if v != k_or_default {
                anyhow::bail!(
                    "--cache-type-v {v} with K at {k_or_default}: frink's KV store holds K and \
                     V in one type, so a V type different from K's cannot be measured"
                );
            }
        }
        // SAFETY: called from `main` while the process is single-threaded,
        // before the download below or any worker pool starts.
        unsafe {
            if let Some(k) = &k {
                std::env::set_var("FRINK_CTK", k);
            }
            if let Some(token) = &self.hf_token {
                std::env::set_var("HF_TOKEN", token);
            }
        }
        self.cache_type_k = k;
        if let Some(spec) = self.hf_repo.take() {
            self.model = Some(crate::hf::resolve(
                &spec,
                self.hf_file.as_deref(),
                self.offline,
            )?);
        }
        Ok(())
    }

    pub fn run(self) -> anyhow::Result<()> {
        let Self {
            model,
            hf_repo: _,
            hf_file: _,
            hf_token: _,
            offline: _,
            cache_type_k,
            cache_type_v: _,
            n_prompt,
            n_gen,
            n_depth,
            pg,
            batch_size,
            ubatch_size,
            reps,
            threads,
            n_gpu_layers,
            ctx_size,
            hidden,
            ffn_dim,
            iters,
            compare,
            suite,
            render,
            id,
            backend,
            fit_host,
            skip_missing,
            bench_dir,
            suite_id,
            backend_label,
            receipt,
            max_load,
            flash_attn,
            list_devices,
            no_warmup,
            delay,
            prio: _, // applied in `main`, before any worker thread
            progress,
            output,
            output_err,
        } = self;
        let output = bench_model::OutputFormat::parse(&output, false)?
            .unwrap_or(bench_model::OutputFormat::Md);
        let output_err = bench_model::OutputFormat::parse(&output_err, true)?;
        if list_devices {
            frink_models::devices::print_available_devices();
            return Ok(());
        }
        if let Some(mode) = &flash_attn {
            check_bench_flash_attn(mode)?;
        }
        if render {
            return bench_render::render(std::path::Path::new(&bench_dir));
        }
        if suite {
            return bench_suite::run_suite(bench_suite::SuiteArgs {
                bench_dir: bench_dir.into(),
                n_prompt,
                n_gen,
                reps,
                only_id: id,
                only_backend: backend,
                fit_host,
                skip_missing,
                max_load,
            });
        }
        if let Some(model) = model {
            // Already applied above, before `claim_instance` could
            // freeze the backend. Kept as a no-op call rather than
            // deleted so a future caller of this arm cannot get an
            // unconfigured process.
            bench_model::apply_env(threads, n_gpu_layers, Some(&model))?;
            return bench_model::run(bench_model::BenchArgs {
                model,
                n_prompt,
                n_gen,
                depth: n_depth,
                pg,
                chunk: frink_core::argv::effective_ubatch(
                    batch_size.map(|b| b as usize),
                    ubatch_size.map(|u| u as usize),
                ),
                reps,
                ctx_size,
                compare,
                backend: backend_label,
                receipt: receipt.map(Into::into),
                id: suite_id,
                max_load,
                run: bench_model::RunOpts {
                    warmup: if no_warmup {
                        0
                    } else {
                        crate::bench_guard::WARMUP_REPS
                    },
                    delay_s: delay,
                    progress,
                },
                n_gpu_layers,
                output,
                output_err,
                cache_type_k,
            });
        }
        synthetic(hidden, ffn_dim, iters);
        Ok(())
    }
}

/// With no `-m`: fused quantized matvec vs. dequant-then-matmul, at a
/// realistic single-expert-FFN matrix size, measuring both wall
/// time and resident memory. Also benchmarks end-to-end decode
/// throughput (tokens/sec) for each preset at synthetic-but-full-
/// scale-shape dimensions.
fn synthetic(hidden: usize, ffn_dim: usize, iters: usize) {
    use frink_core::weight_matrix::{QuantKind, WeightBytes, WeightMatrix};
    use std::time::Instant;

    println!("=== matvec microbenchmark: [{ffn_dim} x {hidden}] weight, {iters} iterations ===");

    let mut rng_state: u64 = 12345;
    let mut next = || {
        rng_state ^= rng_state << 13;
        rng_state ^= rng_state >> 7;
        rng_state ^= rng_state << 17;
        ((rng_state >> 40) as f32 / (1u64 << 24) as f32) - 0.5
    };
    let weights: Vec<f32> = (0..ffn_dim * hidden).map(|_| next() * 0.1).collect();
    let x: Vec<f32> = (0..hidden).map(|_| next() * 0.1).collect();

    let f32_matrix = WeightMatrix::F32(frink_core::tensor::Tensor::new(
        weights.clone(),
        vec![ffn_dim, hidden],
    ));
    let mut packed = Vec::new();
    for row in weights.chunks(hidden) {
        packed.extend(frink_quant::quantize_q8_0(row));
    }
    let packed_for_scalar_bench = packed.clone();
    let quant_matrix = WeightMatrix::Quantized {
        data: WeightBytes::Owned(packed),
        rows: ffn_dim,
        cols: hidden,
        kind: QuantKind::Q8_0,
    };

    // warm-up
    let _ = f32_matrix.apply(&x);
    let _ = quant_matrix.apply(&x);

    let t0 = Instant::now();
    for _ in 0..iters {
        std::hint::black_box(f32_matrix.apply(&x));
    }
    let f32_elapsed = t0.elapsed();

    let t1 = Instant::now();
    for _ in 0..iters {
        std::hint::black_box(quant_matrix.apply(&x));
    }
    let quant_elapsed = t1.elapsed();

    // This isolates the *scalar* kernel cost as a single-
    // threaded direct loop, to compare against "dispatched"
    // below (which goes through WeightMatrix::apply, i.e. both
    // rayon row-parallelism AND AVX2/FMA SIMD dispatch if the
    // host supports it). On an AVX2-capable x86_64 host, most
    // of that gap is genuinely SIMD; on an ARM host without a
    // NEON kernel for this format, the "dispatched" path
    // silently falls back to the same scalar kernel per row,
    // so the entire gap here is multi-core parallelism, not
    // SIMD -- confirmed by comparing this against the explicit
    // 1-thread-vs-all-cores section below, which isolates
    // parallelism on its own. Don't read this ratio as "SIMD
    // speedup" without checking which case you're in.
    let row_bytes = (hidden / frink_quant::Q8_0_BLOCK_ELEMS) * frink_quant::Q8_0_BLOCK_BYTES;
    let scalar_rows: Vec<&[u8]> = packed_for_scalar_bench.chunks_exact(row_bytes).collect();
    let t2 = Instant::now();
    for _ in 0..iters {
        let mut acc = 0f32;
        for row in &scalar_rows {
            acc += frink_quant::dot_q8_0_f32_scalar(row, &x);
        }
        std::hint::black_box(acc);
    }
    let scalar_elapsed = t2.elapsed();

    let f32_bytes = f32_matrix.resident_bytes();
    let quant_bytes = quant_matrix.resident_bytes();

    println!(
        "  f32 dequant-resident matmul : {:>8.3} ms/call  ({} bytes resident)",
        f32_elapsed.as_secs_f64() * 1000.0 / iters as f64,
        f32_bytes
    );
    println!(
        "  fused Q8_0 (scalar, no SIMD, single-threaded) : {:>8.3} ms/call",
        scalar_elapsed.as_secs_f64() * 1000.0 / iters as f64
    );
    println!(
        "  fused Q8_0 (dispatched, row-parallel)          : {:>8.3} ms/call  ({} bytes resident)  <- rayon row parallelism + AVX2/FMA (x86_64) or NEON (aarch64) if host supports it",
        quant_elapsed.as_secs_f64() * 1000.0 / iters as f64,
        quant_bytes
    );
    println!(
        "  dispatched is {:.2}x the single-threaded scalar path's time (see \"multi-core scaling\" below to separate the SIMD and parallelism contributions to this number)",
        quant_elapsed.as_secs_f64() / scalar_elapsed.as_secs_f64()
    );
    println!(
        "  memory reduction: {:.2}x smaller resident",
        f32_bytes as f64 / quant_bytes as f64
    );
    println!(
        "  speed ratio: fused Q8_0 (dispatched) is {:.2}x the f32 path's time (<1.0 = fused is faster; with AVX2+FMA this is usually both faster AND smaller, not a memory-for-speed tradeoff)",
        quant_elapsed.as_secs_f64() / f32_elapsed.as_secs_f64()
    );

    println!(
        "\n=== Q4_0 matvec microbenchmark: [{ffn_dim} x {hidden}] weight, {iters} iterations ==="
    );
    let q4_row_bytes = (hidden / frink_quant::Q4_0_BLOCK_ELEMS) * frink_quant::Q4_0_BLOCK_BYTES;
    let mut q4_packed = Vec::with_capacity(ffn_dim * q4_row_bytes);
    for row in weights.chunks(hidden) {
        for block in row.chunks(frink_quant::Q4_0_BLOCK_ELEMS) {
            let amax = block.iter().fold(0f32, |a, &b| a.max(b.abs()));
            let scale = if amax == 0.0 { 1.0 } else { amax / 7.0 };
            q4_packed.extend_from_slice(&half::f16::from_f32(scale).to_le_bytes());
            for i in 0..16 {
                let lo = ((block.get(i).copied().unwrap_or(0.0) / scale)
                    .round()
                    .clamp(-8.0, 7.0) as i32
                    + 8) as u8;
                let hi = ((block.get(i + 16).copied().unwrap_or(0.0) / scale)
                    .round()
                    .clamp(-8.0, 7.0) as i32
                    + 8) as u8;
                q4_packed.push(lo | (hi << 4));
            }
        }
    }
    let q4_rows: Vec<&[u8]> = q4_packed.chunks_exact(q4_row_bytes).collect();

    let t3 = Instant::now();
    for _ in 0..iters {
        let mut acc = 0f32;
        for row in &q4_rows {
            acc += frink_quant::dot_q4_0_f32_scalar(row, &x);
        }
        std::hint::black_box(acc);
    }
    let q4_scalar_elapsed = t3.elapsed();

    // Route through WeightMatrix::apply, not a direct
    // dot_q4_0_f32 loop -- same rayon row-parallel dispatch the
    // Q8_0 "dispatched" number above uses. An earlier version of
    // this benchmark called dot_q4_0_f32 directly in a plain
    // sequential loop here, which meant it never exercised
    // multi-core parallelism at all and wasn't measuring the
    // same thing as the Q8_0 number above -- caught by actually
    // comparing RAYON_NUM_THREADS=1 vs default on real multi-
    // core hardware and finding the two numbers didn't move
    // together the way they should have.
    let q4_quant_matrix = WeightMatrix::Quantized {
        data: WeightBytes::Owned(q4_packed.clone()),
        rows: ffn_dim,
        cols: hidden,
        kind: QuantKind::Q4_0,
    };
    let _ = q4_quant_matrix.apply(&x); // warm-up
    let t4 = Instant::now();
    for _ in 0..iters {
        std::hint::black_box(q4_quant_matrix.apply(&x));
    }
    let q4_dispatched_elapsed = t4.elapsed();

    println!(
        "  Q4_0 (scalar, no SIMD, single-threaded) : {:>8.3} ms/call  ({} bytes resident)",
        q4_scalar_elapsed.as_secs_f64() * 1000.0 / iters as f64,
        q4_packed.len()
    );
    println!(
        "  Q4_0 (dispatched, row-parallel)          : {:>8.3} ms/call  <- rayon row parallelism + AVX2/FMA (x86_64) or NEON (aarch64) if host supports it",
        q4_dispatched_elapsed.as_secs_f64() * 1000.0 / iters as f64
    );
    println!(
        "  Q4_0 dispatched is {:.2}x the single-threaded scalar path's time",
        q4_dispatched_elapsed.as_secs_f64() / q4_scalar_elapsed.as_secs_f64()
    );
    println!(
        "  Q4_0 memory reduction vs f32: {:.2}x smaller resident",
        f32_bytes as f64 / q4_packed.len() as f64
    );

    println!("\n=== multi-core scaling: fused Q8_0 matvec, [{ffn_dim} x {hidden}], {iters} iterations ===");
    let available_cores = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1);
    let single_thread_pool = rayon::ThreadPoolBuilder::new()
        .num_threads(1)
        .build()
        .expect("building a 1-thread rayon pool must not fail");
    let t5 = Instant::now();
    single_thread_pool.install(|| {
        for _ in 0..iters {
            std::hint::black_box(quant_matrix.apply(&x));
        }
    });
    let single_thread_elapsed = t5.elapsed();
    let single_thread_ms = single_thread_elapsed.as_secs_f64() * 1000.0 / iters as f64;
    let all_cores_ms = quant_elapsed.as_secs_f64() * 1000.0 / iters as f64;
    println!("  available cores (std::thread::available_parallelism): {available_cores}");
    println!("  1 thread            : {single_thread_ms:>8.3} ms/call");
    println!("  {available_cores} threads (default) : {all_cores_ms:>8.3} ms/call");
    println!(
        "  measured speedup: {:.2}x (ideal linear speedup would be {:.2}x for {} cores)",
        single_thread_ms / all_cores_ms,
        available_cores,
        available_cores
    );

    println!("\n=== end-to-end decode throughput (synthetic weights, capped layer count for sandbox runtime) ===");
    for (name, preset) in [
        ("glm-5.2", glm_5_2()),
        ("deepseek-v4-pro", deepseek_v4_pro()),
        ("kimi-k3", kimi_k3()),
    ] {
        let mut cfg = preset;
        cfg.hidden_dim = 512;
        cfg.n_heads = 8;
        cfg.n_kv_heads = 2;
        cfg.head_dim = 64;
        cfg.moe.hidden_dim = 512;
        cfg.moe.n_experts = cfg.moe.n_experts.min(32);
        cfg.moe.expert_ffn_dim = 512;
        let n_layers = 4;
        let vocab = 256;

        let decoder = Decoder::new_random_small(cfg, n_layers, vocab);
        let mut caches: Vec<frink_core::cache::KvCache> = decoder.config.new_kv_caches();

        let n_tokens = 32;
        let t0 = Instant::now();
        for pos in 0..n_tokens {
            std::hint::black_box(decoder.forward_token(pos % vocab, pos, &mut caches));
        }
        let elapsed = t0.elapsed();
        let toks_per_sec = n_tokens as f64 / elapsed.as_secs_f64();
        println!(
            "  {name:<16} {n_layers} layers, hidden=512, {} experts ({} active): {:>7.1} tok/s ({:.2} ms/token, CPU reference, single thread pool)",
            decoder.config.moe.n_experts,
            decoder.config.moe.n_experts_active,
            toks_per_sec,
            elapsed.as_secs_f64() * 1000.0 / n_tokens as f64
        );
    }
    println!("\nNote: these are CPU-reference numbers on this sandbox's vCPUs, not GPU numbers.");
    println!(
        "They demonstrate the pipeline's relative cost structure (attention vs MoE FFN, memory"
    );
    println!("footprint of quantized vs f32 weights), not absolute performance on target hardware");
    println!("like a DGX Spark. See benchmarks/RESULTS.md for methodology and caveats.");
}

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

    #[test]
    fn bench_flash_attn_takes_one_llama_value_and_refuses_off_and_sweeps() {
        for ok in ["on", "auto", "1", "enabled", "-1"] {
            check_bench_flash_attn(ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
        }
        for (bad, says) in [
            ("off", "backend property"),
            ("0", "backend property"),
            ("0,1", "sweep"),
            ("maybe", "expected on"),
        ] {
            let err = check_bench_flash_attn(bad).unwrap_err().to_string();
            assert!(err.contains(says), "{bad}: {err}");
        }
    }
}