inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! `inky sparsecheck`: the long-context quality gate of sparse attention, for sparse *prefill*
//! (`INK_SPARSE_PREFILL`) and for the sparse *decode* that ships (`--sparse-topk` past `--sparse-min-ctx`).
//!
//! Every arm is compared with a dense reference on the same engine, the same blocked lane layout and the same
//! chunking; only the attention path differs:
//!
//! | arm       | prefill         | decode                     |
//! |-----------|-----------------|----------------------------|
//! | `dense`   | dense           | dense (decode floor raised past the context) |
//! | `prefill` | sparse prefill  | dense                      |
//! | `decode`  | dense           | sparse decode (the configured `--sparse-*`)   |
//! | `both`    | sparse prefill  | sparse decode              |
//!
//! Two checks (`INK_CHECK_MODE=kl,needle`, both by default):
//!
//! - `kl`: the haystack text (`-f`) cut to each length of `INK_CHECK_CTXS`; per-position KL(dense || arm) of the
//!   next-token distribution at `INK_CHECK_PF_PROBES` prefill rows (the ends of `INK_CHECK_PF_STRIDE`-token chunks
//!   at the end of the prompt) and `INK_CHECK_PROBES` teacher-forced decode positions after it. Reported per arm:
//!   mean, p99.9, max, the count of positions over the per-position bound, and argmax agreement. An arm passes when
//!   mean <= `INK_CHECK_KL_MEAN` (0.01 nats), p99.9 <= `INK_CHECK_KL_P999` (0.05), max <= `INK_CHECK_KL_MAX` (0.1),
//!   no position is over `INK_CHECK_KL_POS` (0.05) beyond 0.1% of positions, and argmax agreement >= 98%.
//! - `needle`: one fact planted at each depth of `INK_CHECK_DEPTHS` in the haystack, then a question only the fact
//!   answers. Per arm: the greedy answer (`INK_CHECK_GEN` tokens) and whether it contains the expected answer, and
//!   the logit margin (the answer token's logit minus the best other logit) at each token of the answer in the dense
//!   greedy continuation, teacher-forced. An arm fails a needle when dense finds it and the arm does not, or when
//!   its smallest answer margin is not positive (another token would be chosen).
//!
//! Path exposure: each sparse arm must show its path ran: the sparse prefill counters (span passes, query blocks,
//! kept/causal blocks) and the key-block density of the last pass read back from the GPU masks, and the count of
//! sparse decode tasks. An arm whose path never ran fails, whatever its KL.

use crate::engine::{Span, SparsePrefillCfg, SparsePrefillStats};
use crate::*;

/// Pass thresholds of the KL check (nats).
#[derive(Clone, Copy, Debug)]
pub(crate) struct KlGate {
    pub mean: f64,
    pub p999: f64,
    pub max: f64,
    pub per_pos: f64,
    pub min_agree: f64,
}

impl Default for KlGate {
    fn default() -> Self {
        KlGate { mean: 0.01, p999: 0.05, max: 0.1, per_pos: 0.05, min_agree: 0.98 }
    }
}

/// `KL(p || q)` in nats of the softmax distributions of two logit rows.
pub(crate) fn kl_nats(p_logits: &[f32], q_logits: &[f32]) -> f64 {
    let lse = |v: &[f32]| {
        let m = v.iter().fold(f64::NEG_INFINITY, |m, &x| m.max(f64::from(x)));
        m + v.iter().map(|&x| (f64::from(x) - m).exp()).sum::<f64>().ln()
    };
    let (lp, lq) = (lse(p_logits), lse(q_logits));
    p_logits
        .iter()
        .zip(q_logits)
        .map(|(&a, &b)| {
            let la = f64::from(a) - lp;
            let w = la.exp();
            if w == 0.0 { 0.0 } else { w * (la - (f64::from(b) - lq)) }
        })
        .sum::<f64>()
        .max(0.0)
}

pub(crate) fn argmax(v: &[f32]) -> usize {
    v.iter().enumerate().fold((0, f32::NEG_INFINITY), |b, (i, &x)| if x > b.1 { (i, x) } else { b }).0
}

/// The logit of `tok` minus the largest logit of any other token (positive: `tok` is the argmax).
pub(crate) fn margin(v: &[f32], tok: usize) -> f32 {
    let other = v.iter().enumerate().filter(|&(i, _)| i != tok).fold(f32::NEG_INFINITY, |m, (_, &x)| m.max(x));
    v[tok] - other
}

/// The `q` quantile (nearest rank) of `xs`.
pub(crate) fn quantile(xs: &[f64], q: f64) -> f64 {
    if xs.is_empty() {
        return 0.0;
    }
    let mut s = xs.to_vec();
    s.sort_by(f64::total_cmp);
    let rank = ((q * s.len() as f64).ceil() as usize).clamp(1, s.len());
    s[rank - 1]
}

#[derive(Clone, Debug)]
pub(crate) struct KlSummary {
    pub n: usize,
    pub mean: f64,
    pub p999: f64,
    pub max: f64,
    pub over: usize,
    pub agree: f64,
}

impl KlSummary {
    pub(crate) fn of(kls: &[f64], agree: usize, per_pos: f64) -> KlSummary {
        let n = kls.len();
        KlSummary {
            n,
            mean: if n == 0 { 0.0 } else { kls.iter().sum::<f64>() / n as f64 },
            p999: quantile(kls, 0.999),
            max: kls.iter().cloned().fold(0.0, f64::max),
            over: kls.iter().filter(|&&k| k > per_pos).count(),
            agree: if n == 0 { 1.0 } else { agree as f64 / n as f64 },
        }
    }
    /// The reasons the summary fails `g` (empty: pass).
    pub(crate) fn failures(&self, g: &KlGate) -> Vec<String> {
        let mut f = Vec::new();
        if self.n == 0 {
            f.push("no positions".into());
        }
        if self.mean > g.mean {
            f.push(format!("mean {:.4} > {}", self.mean, g.mean));
        }
        if self.p999 > g.p999 {
            f.push(format!("p99.9 {:.4} > {}", self.p999, g.p999));
        }
        if self.max > g.max {
            f.push(format!("max {:.4} > {}", self.max, g.max));
        }
        let allowed = self.n / 1000;
        if self.over > allowed {
            f.push(format!("{} positions over {} (allowed {allowed})", self.over, g.per_pos));
        }
        if self.agree < g.min_agree {
            f.push(format!("argmax agreement {:.3} < {}", self.agree, g.min_agree));
        }
        f
    }
}

/// Why a sparse prefill arm over an `n`-token prompt did not exercise its path (empty: it did). A prompt whose last
/// query block keeps every causal block (below the floor or within anchors + recent + top-k) cannot select at all,
/// so its arm is the dense path and its KL says nothing about sparse prefill; a span that fell back to dense ran
/// only part of the path.
pub(crate) fn prefill_exposure_failures(s: &SparsePrefillStats, n: usize, anchors: usize, cfg: SparsePrefillCfg) -> Vec<String> {
    let mut f = Vec::new();
    if n == 0 || crate::engine::sparse_prefill_task_cpu((n - 1) / blocks::BLOCK, anchors, cfg).keeps_all() {
        f.push(format!(
            "sparse prefill cannot select at {n} tokens (floor {}, anchors {anchors} + recent + top-k {}): not exercised",
            cfg.min_ctx, cfg.top_k
        ));
    } else if s.sparse_passes == 0 {
        f.push("sparse prefill path never ran".into());
    } else if s.kept_blocks >= s.causal_blocks {
        f.push(format!("sparse prefill kept every causal block ({}/{})", s.kept_blocks, s.causal_blocks));
    }
    if s.fallbacks > 0 {
        f.push(format!("{} sparse prefill passes fell back to dense", s.fallbacks));
    }
    f
}

/// `hay_a + fact + hay_b + question`: the haystack split at the character nearest `depth` (0..=1) that starts a
/// line or a sentence, the fact on its own line.
pub(crate) fn needle_text(hay: &str, fact: &str, question: &str, depth: f64) -> String {
    let want = ((hay.len() as f64) * depth.clamp(0.0, 1.0)) as usize;
    let mut cut = hay.len();
    for (i, c) in hay.char_indices() {
        if i >= want && (c == '\n' || c == '.') {
            cut = i + c.len_utf8();
            break;
        }
    }
    format!("{}\n{fact}\n{}\n\n{question}", &hay[..cut], &hay[cut..])
}

/// Token indices of `toks` (decoded to `pieces`) whose text overlaps the first occurrence of `answer`.
pub(crate) fn answer_span(pieces: &[String], answer: &str) -> Option<std::ops::Range<usize>> {
    let text: String = pieces.concat();
    let at = text.find(answer)?;
    let end = at + answer.len();
    let (mut lo, mut hi, mut off) = (None, 0, 0);
    for (i, p) in pieces.iter().enumerate() {
        let (a, b) = (off, off + p.len());
        if b > at && a < end {
            lo.get_or_insert(i);
            hi = i + 1;
        }
        off = b;
    }
    lo.map(|lo| lo..hi)
}

fn env_list<T: std::str::FromStr>(name: &str, default: &str) -> Vec<T> {
    std::env::var(name)
        .unwrap_or_else(|_| default.into())
        .split(',')
        .filter(|s| !s.trim().is_empty())
        .map(|v| v.trim().parse().unwrap_or_else(|_| cli_error(format!("{name}: bad value {v:?}"))))
        .collect()
}

fn env_num<T: std::str::FromStr>(name: &str, default: T) -> T {
    std::env::var(name).ok().map_or(default, |v| v.trim().parse().unwrap_or_else(|_| cli_error(format!("{name}: bad value {v:?}"))))
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Arm {
    Dense,
    Prefill,
    Decode,
    Both,
}

impl Arm {
    fn parse(s: &str) -> Arm {
        match s {
            "dense" => Arm::Dense,
            "prefill" => Arm::Prefill,
            "decode" => Arm::Decode,
            "both" => Arm::Both,
            _ => cli_error(format!("INK_CHECK_ARMS: unknown arm {s:?} (prefill|decode|both)")),
        }
    }
    fn name(self) -> &'static str {
        match self {
            Arm::Dense => "dense",
            Arm::Prefill => "prefill",
            Arm::Decode => "decode",
            Arm::Both => "both",
        }
    }
    fn sparse_prefill(self) -> bool {
        matches!(self, Arm::Prefill | Arm::Both)
    }
    fn sparse_decode(self) -> bool {
        matches!(self, Arm::Decode | Arm::Both)
    }
}

struct Ctx<'a> {
    eng: &'a Engine,
    tk: &'a Tokenizer,
    max_len: usize,
    sp_cfg: SparsePrefillCfg,
    dec_min_ctx: usize,
}

impl Ctx<'_> {
    fn softcapped(&self, v: &[f32]) -> Vec<f32> {
        v.iter().map(|&x| softcap(x, self.eng.softcap)).collect()
    }

    /// Prefill `toks` into a fresh blocked lane, sparse or dense; the last `pf_probes` chunks are `stride` tokens and
    /// return their last row's logits (the final chunk's always). Prints the sparse prefill exposure.
    fn prefill(
        &self,
        toks: &[u32],
        sparse: bool,
        pf_probes: usize,
        stride: usize,
    ) -> (Lane, Vec<Vec<f32>>, Vec<usize>, SparsePrefillStats) {
        let eng = self.eng;
        let n = toks.len();
        eng.set_sparse_prefill(sparse.then_some(self.sp_cfg));
        eng.reset_sparse_prefill_stats();
        let lane = Lane::new_blocked(eng, self.max_len);
        eng.on(&lane).set_tokens(0, toks);
        let tail = (pf_probes * stride).min(n.saturating_sub(1));
        let (mut p, mut retired) = (0usize, 0usize);
        let (mut logits, mut at) = (Vec::new(), Vec::new());
        let t0 = std::time::Instant::now();
        while p < n {
            let t = if p < n - tail { (n - tail - p).min(eng.chunk) } else { stride.min(n - p).min(eng.chunk) };
            let want = p >= n - tail || p + t == n;
            {
                let mut pools = eng.block_pool().borrow_mut();
                let mut tbl = lane.block_table().borrow_mut();
                BlockedBenchHelper::ensure_span(&mut pools, &mut tbl, p, t);
            }
            let cb = eng.gpu.cmd();
            eng.encode_spans(&cb, &[Span { lane: &lane, p0: p, t }], want, false);
            cb.commit();
            cb.waitUntilCompleted();
            {
                let mut pools = eng.block_pool().borrow_mut();
                let mut tbl = lane.block_table().borrow_mut();
                BlockedBenchHelper::finish_span(&mut pools, &mut tbl, &mut retired, p, t);
            }
            p += t;
            if want {
                logits.push(self.softcapped(&eng.logits()));
                at.push(p - 1);
            }
        }
        let dt = t0.elapsed().as_secs_f64();
        let s = eng.sparse_prefill_stats();
        if sparse {
            let density = eng.sparse_prefill_last_masks().map(|(qb0, words, m)| {
                let n_qb = m.len() / (engine::NKV * words);
                let kept: u64 = m.iter().map(|w| u64::from(w.count_ones())).sum();
                let causal: u64 = (0..n_qb).map(|q| (qb0 + q + 1) as u64).sum::<u64>() * engine::NKV as u64;
                kept as f64 / causal.max(1) as f64
            });
            println!(
                "  exposure sparse prefill @{n}: {} span passes, {} query blocks, kept {}/{} causal blocks ({:.1}%), \
                 last pass GPU mask density {}, {} dense fallbacks, prefill {dt:.1} s",
                s.sparse_passes,
                s.qblocks,
                s.kept_blocks,
                s.causal_blocks,
                100.0 * s.kept_blocks as f64 / s.causal_blocks.max(1) as f64,
                density.map_or("n/a".into(), |d| format!("{:.1}%", 100.0 * d)),
                s.fallbacks
            );
        } else {
            println!("  dense prefill @{n}: {dt:.1} s");
        }
        eng.set_sparse_prefill(None);
        (lane, logits, at, s)
    }

    /// Decode on a clone of `src` (prefilled to `c`): token `c + i` is `next(i, logits of c + i - 1)`; returns the
    /// logits of positions `c ..` (each predicting the next token) and the tokens fed.
    fn decode(&self, src: &Lane, toks: &[u32], c: usize, steps: usize, sparse: bool, first: &[f32], mut next: impl FnMut(usize, &[f32]) -> u32) -> (Vec<Vec<f32>>, Vec<u32>, u64) {
        let eng = self.eng;
        eng.set_sparse_min_ctx(if sparse { self.dec_min_ctx } else { usize::MAX / 2 });
        let mut seq: Vec<u32> = toks[..c].to_vec();
        seq.resize(c + steps + 1, 0);
        let lane = BlockedBenchHelper::clone_lane_at(eng, src, self.max_len, c, steps, 0, &seq);
        let tasks0 = eng.sparse_decode_tasks();
        let (mut out, mut fed) = (Vec::new(), Vec::new());
        let mut prev = first.to_vec();
        for i in 0..steps {
            let tok = next(i, &prev);
            fed.push(tok);
            eng.on(&lane).set_tokens(c + i, &[tok]);
            let cb = eng.gpu.cmd();
            eng.encode_decode(&cb, &[Span { lane: &lane, p0: c + i, t: 1 }], true, false);
            cb.commit();
            cb.waitUntilCompleted();
            prev = self.softcapped(&eng.span_logits(0));
            out.push(prev.clone());
        }
        let tasks = eng.sparse_decode_tasks() - tasks0;
        BlockedBenchHelper::release_lane(eng, &lane);
        eng.set_sparse_min_ctx(self.dec_min_ctx);
        (out, fed, tasks)
    }

    fn piece(&self, t: u32) -> String {
        String::from_utf8_lossy(&self.tk.decode_bytes(t)).into_owned()
    }
}

fn kl_check(cx: &Ctx, hay: &[u32], n: usize, arms: &[Arm], gate: &KlGate, verdict: &mut Vec<String>) {
    let probes: usize = env_num("INK_CHECK_PROBES", 128);
    let pf_probes: usize = env_num("INK_CHECK_PF_PROBES", 8);
    let stride: usize = env_num("INK_CHECK_PF_STRIDE", 512);
    if hay.len() < n + probes + 1 {
        cli_error(format!("kl @{n}: the haystack has {} tokens, needs {}", hay.len(), n + probes + 1));
    }
    let toks = &hay[..n + probes + 1];
    println!("kl @{n}: {pf_probes} prefill probes every {stride} tokens, {probes} teacher-forced decode probes");
    let (dense_lane, dense_pf, pf_at, _) = cx.prefill(&toks[..n], false, pf_probes, stride);
    let sparse = arms.iter().any(|a| a.sparse_prefill()).then(|| cx.prefill(&toks[..n], true, pf_probes, stride));
    let forced = |i: usize, _: &[f32]| toks[n + i];
    let last = dense_pf.last().unwrap().clone();
    let (ref_dec, _, _) = cx.decode(&dense_lane, toks, n, probes, false, &last, forced);
    for &arm in arms {
        let (lane, pf) = if arm.sparse_prefill() {
            let s = sparse.as_ref().unwrap();
            (&s.0, &s.1)
        } else {
            (&dense_lane, &dense_pf)
        };
        let (dec, _, tasks) = cx.decode(lane, toks, n, probes, arm.sparse_decode(), pf.last().unwrap(), forced);
        let mut kls = Vec::new();
        let mut agree = 0;
        let mut worst = (0.0f64, 0usize);
        for ((r, a), pos) in dense_pf.iter().zip(pf).zip(pf_at.iter().copied()).chain(ref_dec.iter().zip(&dec).zip(n..)) {
            let k = kl_nats(r, a);
            if k > worst.0 {
                worst = (k, pos);
            }
            kls.push(k);
            agree += usize::from(argmax(r) == argmax(a));
        }
        let s = KlSummary::of(&kls, agree, gate.per_pos);
        let mut fails = s.failures(gate);
        if arm.sparse_prefill() {
            fails.extend(prefill_exposure_failures(&sparse.as_ref().unwrap().3, n, cx.eng.sparse_anchors(), cx.sp_cfg));
        }
        if arm.sparse_decode() && tasks == 0 && n > cx.dec_min_ctx {
            fails.push("sparse decode path never ran (0 tasks)".into());
        }
        let line = format!(
            "kl @{n} {:<8} positions {:>4}  mean {:.5}  p99.9 {:.5}  max {:.5} (pos {})  over {}: {:>3}  argmax {:.3}  sparse decode tasks {tasks}  {}",
            arm.name(),
            s.n,
            s.mean,
            s.p999,
            s.max,
            worst.1,
            gate.per_pos,
            s.over,
            s.agree,
            if fails.is_empty() { "PASS".to_string() } else { format!("FAIL ({})", fails.join("; ")) }
        );
        println!("{line}");
        for (i, k) in kls.iter().enumerate() {
            if std::env::var_os("INK_CHECK_PER_POS").is_some() {
                let pos = if i < pf_at.len() { pf_at[i] } else { n + i - pf_at.len() };
                println!("  kl-pos @{n} {} {pos} {k:.6}", arm.name());
            }
        }
        if !fails.is_empty() {
            verdict.push(line);
        }
    }
    BlockedBenchHelper::release_lane(cx.eng, &dense_lane);
    if let Some((l, _, _, _)) = sparse {
        BlockedBenchHelper::release_lane(cx.eng, &l);
    }
}

fn needle_check(cx: &Ctx, o: &Opts, hay: &[u32], n: usize, arms: &[Arm], verdict: &mut Vec<String>) {
    let fact = std::env::var("INK_CHECK_FACT").unwrap_or_else(|_| "The secret passphrase for the vault is MAGENTA-4471.".into());
    let question = std::env::var("INK_CHECK_QUESTION")
        .unwrap_or_else(|_| "What is the secret passphrase for the vault? Reply with the passphrase only.".into());
    let answer = std::env::var("INK_CHECK_ANSWER").unwrap_or_else(|_| "MAGENTA-4471".into());
    let gen: usize = env_num("INK_CHECK_GEN", 48);
    let depths: Vec<f64> = env_list("INK_CHECK_DEPTHS", "0.1,0.5,0.9");
    // the haystack cut to `n` prompt tokens in all: measure the template and the question once, then cut the text
    let overhead = first_turn_tokens(cx.tk, o, &needle_text("", &fact, &question, 0.0)).len();
    let body = n.saturating_sub(overhead + 2);
    if hay.len() < body {
        cli_error(format!("needle @{n}: the haystack has {} tokens, needs {body}", hay.len()));
    }
    let body_text: String = hay[..body].iter().map(|&t| cx.piece(t)).collect();
    for &depth in &depths {
        let text = needle_text(&body_text, &fact, &question, depth);
        let prompt = first_turn_tokens(cx.tk, o, &text);
        let c = prompt.len();
        println!("needle @{n} depth {depth}: {c} prompt tokens");
        let (dense_lane, dense_pf, _, _) = cx.prefill(&prompt, false, 0, 512);
        let greedy = |_: usize, lg: &[f32]| argmax(lg) as u32;
        let (_, ref_toks, _) = cx.decode(&dense_lane, &prompt, c, gen, false, dense_pf.last().unwrap(), greedy);
        let ref_pieces: Vec<String> = ref_toks.iter().map(|&t| cx.piece(t)).collect();
        let span = answer_span(&ref_pieces, &answer);
        let ref_text = ref_pieces.concat();
        println!("  dense    answer {:?} found {}", ref_text.trim(), span.is_some());
        let sparse = arms.iter().any(|a| a.sparse_prefill()).then(|| cx.prefill(&prompt, true, 0, 512));
        for &arm in arms {
            let (lane, pf) = if arm.sparse_prefill() {
                let s = sparse.as_ref().unwrap();
                (&s.0, &s.1)
            } else {
                (&dense_lane, &dense_pf)
            };
            let first = pf.last().unwrap();
            let (_, toks, tasks) = cx.decode(lane, &prompt, c, gen, arm.sparse_decode(), first, greedy);
            let text: String = toks.iter().map(|&t| cx.piece(t)).collect();
            let found = text.contains(&answer);
            // the margins at the answer tokens of the dense continuation, teacher-forced
            let margins: Vec<(f32, f32)> = match &span {
                Some(sp) => {
                    let forced = |i: usize, _: &[f32]| ref_toks[i];
                    let steps = sp.end;
                    let (arm_lg, _, _) = cx.decode(lane, &prompt, c, steps, arm.sparse_decode(), first, forced);
                    let (ref_lg, _, _) = cx.decode(&dense_lane, &prompt, c, steps, false, dense_pf.last().unwrap(), forced);
                    // logits predicting token i: the first from the prefill, then decode step i - 1
                    let at = |lg: &[Vec<f32>], f: &[f32], i: usize| if i == 0 { f.to_vec() } else { lg[i - 1].clone() };
                    sp.clone()
                        .map(|i| {
                            let t = ref_toks[i] as usize;
                            (margin(&at(&ref_lg, dense_pf.last().unwrap(), i), t), margin(&at(&arm_lg, first, i), t))
                        })
                        .collect()
                }
                None => Vec::new(),
            };
            let min_arm = margins.iter().map(|m| m.1).fold(f32::INFINITY, f32::min);
            let min_ref = margins.iter().map(|m| m.0).fold(f32::INFINITY, f32::min);
            let mut fails = Vec::new();
            if span.is_some() && !found {
                fails.push("dense finds the needle, this arm does not".to_string());
            }
            if span.is_some() && min_arm <= 0.0 {
                fails.push(format!("answer margin {min_arm:.3} <= 0"));
            }
            if arm.sparse_prefill() {
                fails.extend(prefill_exposure_failures(&sparse.as_ref().unwrap().3, c, cx.eng.sparse_anchors(), cx.sp_cfg));
            }
            if arm.sparse_decode() && tasks == 0 && c > cx.dec_min_ctx {
                fails.push("sparse decode path never ran (0 tasks)".into());
            }
            let line = format!(
                "needle @{n} depth {depth} {:<8} found {found}  answer margin min {} (dense {})  sparse decode tasks {tasks}  {:?}  {}",
                arm.name(),
                if margins.is_empty() { "n/a".into() } else { format!("{min_arm:.3}") },
                if margins.is_empty() { "n/a".into() } else { format!("{min_ref:.3}") },
                text.trim(),
                if fails.is_empty() { "PASS".to_string() } else { format!("FAIL ({})", fails.join("; ")) }
            );
            println!("{line}");
            if !fails.is_empty() {
                verdict.push(line);
            }
        }
        if span.is_none() {
            println!("  note: dense did not find the needle at depth {depth}; the arms are reported, not judged");
        }
        BlockedBenchHelper::release_lane(cx.eng, &dense_lane);
        if let Some((l, _, _, _)) = sparse {
            BlockedBenchHelper::release_lane(cx.eng, &l);
        }
    }
}

/// `inky sparsecheck`.
pub(crate) fn sparsecheck(o: &Opts) {
    let ctxs: Vec<usize> = env_list("INK_CHECK_CTXS", "70000,100000");
    let modes: Vec<String> = env_list("INK_CHECK_MODE", "kl,needle");
    let arms: Vec<Arm> = env_list::<String>("INK_CHECK_ARMS", "prefill,decode,both").iter().map(|s| Arm::parse(s)).collect();
    let gate = KlGate {
        mean: env_num("INK_CHECK_KL_MEAN", KlGate::default().mean),
        p999: env_num("INK_CHECK_KL_P999", KlGate::default().p999),
        max: env_num("INK_CHECK_KL_MAX", KlGate::default().max),
        per_pos: env_num("INK_CHECK_KL_POS", KlGate::default().per_pos),
        min_agree: env_num("INK_CHECK_AGREE", KlGate::default().min_agree),
    };
    let sp_cfg = engine::sparse_prefill_cfg_from(|k| if k == "INK_SPARSE_PREFILL" { Some("1".into()) } else { std::env::var(k).ok() })
        .unwrap_or_else(|e| cli_error(e))
        .expect("forced on");
    let last = *ctxs.iter().max().unwrap_or_else(|| cli_error("INK_CHECK_CTXS is empty".into()));
    let slack = 1024 + env_num::<usize>("INK_CHECK_PROBES", 128) + env_num::<usize>("INK_CHECK_GEN", 48);
    let max_len = last + slack;
    let load_ctx = o.ctx.max(max_len.div_ceil(64) * 64).min(MAX_CONTEXT);
    let eng = Engine::load_pooled(&o.model, load_ctx);
    if eng.exact || eng.sparse_topk().is_none() {
        cli_error("sparsecheck needs the default mode with --sparse-topk (the sketches both sparse paths read)".into());
    }
    eng.ensure_batch(eng.chunk);
    eng.ensure_dbatch(1);
    // a pool for two prefilled lanes and one decode clone
    let blks = max_len.div_ceil(blocks::BLOCK);
    let win_per_lane = (blocks::WINDOW / blocks::BLOCK) + 3;
    let nw = 5 * win_per_lane + blocks::span_bound(eng.chunk) + 16;
    eng.init_block_pools_exact(nw, 3 * blks + 256);
    let tk = Tokenizer::load(&eng.g);
    let hay = tk.encode(&o.prompt, false);
    println!(
        "sparsecheck: {} haystack tokens; ctxs {ctxs:?}; arms {:?}; sparse prefill top-k {} floor {}; sparse decode top-k {:?} anchors {} floor {}",
        hay.len(),
        arms.iter().map(|a| a.name()).collect::<Vec<_>>(),
        sp_cfg.top_k,
        sp_cfg.min_ctx,
        eng.sparse_topk(),
        eng.sparse_anchors(),
        eng.sparse_min_ctx()
    );
    println!(
        "kl gate: mean <= {} p99.9 <= {} max <= {} at most 0.1% of positions over {} argmax >= {}",
        gate.mean, gate.p999, gate.max, gate.per_pos, gate.min_agree
    );
    let cx = Ctx { eng: &eng, tk: &tk, max_len, sp_cfg, dec_min_ctx: eng.sparse_min_ctx() };
    let mut verdict = Vec::new();
    for &n in &ctxs {
        if modes.iter().any(|m| m == "kl") {
            kl_check(&cx, &hay, n, &arms, &gate, &mut verdict);
        }
        if modes.iter().any(|m| m == "needle") {
            needle_check(&cx, o, &hay, n, &arms, &mut verdict);
        }
    }
    if verdict.is_empty() {
        println!("SPARSECHECK PASS");
    } else {
        println!("SPARSECHECK FAIL ({} checks):", verdict.len());
        for v in &verdict {
            println!("  {v}");
        }
        std::process::exit(1);
    }
}

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

    #[test]
    fn kl_is_zero_on_equal_rows_and_positive_otherwise() {
        let a = [1.0f32, 2.0, 3.0, -1.0];
        assert!(kl_nats(&a, &a).abs() < 1e-12);
        // a shift of every logit is the same distribution
        let b: Vec<f32> = a.iter().map(|x| x + 5.0).collect();
        assert!(kl_nats(&a, &b) < 1e-9);
        let c = [3.0f32, 2.0, 1.0, -1.0];
        let k = kl_nats(&a, &c);
        // by hand: p = softmax(a), q = softmax(c)
        let sm = |v: &[f32]| {
            let s: f64 = v.iter().map(|&x| f64::from(x).exp()).sum();
            v.iter().map(|&x| f64::from(x).exp() / s).collect::<Vec<_>>()
        };
        let (p, q) = (sm(&a), sm(&c));
        let want: f64 = p.iter().zip(&q).map(|(p, q)| p * (p / q).ln()).sum();
        assert!((k - want).abs() < 1e-9, "{k} vs {want}");
    }

    #[test]
    fn tail_metrics_see_one_bad_position_the_mean_hides() {
        // the needle problem: 9,999 perfect positions and one that lost its block
        let mut kls = vec![0.0f64; 9_999];
        kls.push(2.0);
        let s = KlSummary::of(&kls, 9_999, 0.05);
        assert!(s.mean < 0.01, "the mean barely moves: {}", s.mean);
        assert_eq!(s.max, 2.0);
        assert_eq!(s.over, 1);
        let f = s.failures(&KlGate::default());
        assert!(f.iter().any(|r| r.starts_with("max")), "{f:?}");
        assert!(!f.iter().any(|r| r.starts_with("mean")), "{f:?}");
        // the 99.9th percentile of 10,000 positions is the 9,990th smallest
        assert_eq!(quantile(&kls, 0.999), 0.0);
        let mut many = vec![0.0f64; 9_980];
        many.extend(std::iter::repeat_n(0.2, 20));
        let s = KlSummary::of(&many, 10_000, 0.05);
        assert_eq!(s.p999, 0.2);
        assert!(s.failures(&KlGate::default()).iter().any(|r| r.contains("positions over")));
        // a clean run passes
        assert!(KlSummary::of(&[0.001; 300], 300, 0.05).failures(&KlGate::default()).is_empty());
        assert!(!KlSummary::of(&[], 0, 0.05).failures(&KlGate::default()).is_empty(), "no positions is a failure");
    }

    #[test]
    fn prefill_exposure_names_an_arm_that_did_not_run_sparse() {
        let cfg = SparsePrefillCfg { top_k: 256, min_ctx: 65_536 };
        let ran = SparsePrefillStats { sparse_passes: 8, qblocks: 128, kept_blocks: 300, causal_blocks: 9_000, fallbacks: 0, sketch_catchup_slots: 0 };
        assert!(prefill_exposure_failures(&ran, 100_000, 16, cfg).is_empty());
        // below the floor the arm is dense whatever its counters say
        let f = prefill_exposure_failures(&ran, 60_000, 16, cfg);
        assert!(f.len() == 1 && f[0].contains("not exercised"), "{f:?}");
        // past the floor but within the budget (anchors + 16 + top-k blocks): still cannot select
        let wide = SparsePrefillCfg { top_k: 4095, min_ctx: 0 };
        assert!(prefill_exposure_failures(&ran, 100_000, 16, wide)[0].contains("not exercised"));
        let none = SparsePrefillStats::default();
        assert_eq!(prefill_exposure_failures(&none, 100_000, 16, cfg), ["sparse prefill path never ran"]);
        let all = SparsePrefillStats { kept_blocks: 9_000, ..ran };
        assert!(prefill_exposure_failures(&all, 100_000, 16, cfg)[0].contains("kept every causal block"));
        let fb = SparsePrefillStats { fallbacks: 2, ..ran };
        assert!(prefill_exposure_failures(&fb, 100_000, 16, cfg)[0].contains("fell back"));
    }

    #[test]
    fn margin_is_the_gap_to_the_best_other_token() {
        let v = [0.5f32, 3.0, 2.25, -4.0];
        assert_eq!(margin(&v, 1), 0.75);
        assert_eq!(margin(&v, 2), -0.75);
        assert_eq!(argmax(&v), 1);
    }

    #[test]
    fn the_needle_lands_at_its_depth_on_a_boundary() {
        let hay = "Alpha one. Beta two. Gamma three.\nDelta four. Epsilon five.";
        let t = needle_text(hay, "FACT.", "Q?", 0.5);
        assert!(t.ends_with("\n\nQ?"));
        let at = t.find("\nFACT.\n").unwrap();
        assert!(at >= hay.len() / 2 && at < hay.len(), "{at}");
        assert!(t[..at].ends_with('.') || t[..at].ends_with('\n'));
        assert!(needle_text(hay, "F", "Q", 0.0).starts_with("Alpha one.\nF\n"));
        assert!(needle_text(hay, "F", "Q", 1.0).starts_with(&format!("{hay}\nF\n")));
        // every haystack character survives, in order
        let t2 = needle_text(hay, "F", "Q", 0.3).replacen("\nF\n", "", 1);
        assert!(t2.starts_with(hay));
    }

    #[test]
    fn answer_span_covers_the_tokens_of_the_answer() {
        let pieces: Vec<String> = ["The", " pass", "phrase", " is", " MAG", "ENTA", "-", "44", "71", "."].iter().map(|s| s.to_string()).collect();
        assert_eq!(answer_span(&pieces, "MAGENTA-4471"), Some(4..9));
        assert_eq!(answer_span(&pieces, "passphrase"), Some(1..3));
        assert_eq!(answer_span(&pieces, "CYAN"), None);
    }
}