inky-engine 3.0.2

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
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! KV8 tensor-core decode attention (`k_attn_tc_dec`, `k_attn_tc_dec_solo`, `k_attn_tc_grp_dec`,
//! `k_attn_tc_sparse_dec` compiled with `KV8`, reached with `INK_TC_ATTN_DEC`).
//!
//! Each kernel runs on random caches next to the simdgroup decode kernel the engine runs without
//! `INK_TC_ATTN_DEC` (`k_attn`, `k_attn_dec_solo`, `k_attn_grp_dec`, `k_attn_sparse_dec`), on the same inputs, and
//! the combined attention outputs must agree within the bounds the KV8 tensor-core prefill kernels are held to
//! against the simdgroup kernels (`kv8_tc_tests`: 5e-5 abs and rel). FP16 runs the same comparisons as a control.
//!
//! Dry steps (a verify or peel that must not touch the cache) keep the current token's K/V in the `kv_cur` buffer
//! only. Those runs plant stale codes in the current row's cache slot, check the outputs still match the clean
//! run, and check a run that does read the slot (not dry) moves, so the comparison can see the slot.
//!
//! No model file. These run wherever Metal 4 and MetalPerformancePrimitives run (an M3 Ultra executes the
//! tensor ops on its ALUs) and on the M5:
//!   cargo test --release --bin inky kv8_tc_dec -- --ignored --nocapture

use super::*;
use crate::blocks::{f16_bits_to_f32, f32_to_f16_bits, kv8_vscale_cpu};

const MAX_ABS: f64 = 5e-5;
const MAX_REL: f64 = 5e-5;

const KERNELS: [&str; 8] = [
    "k_attn_tc_dec_solo",
    "k_attn_tc_grp_dec",
    "k_attn_dec_solo",
    "k_attn_grp_dec",
    "k_attn_tc_dec",
    "k_attn",
    "k_attn_tc_sparse_dec",
    "k_attn_sparse_dec",
];

#[derive(Clone, Copy, PartialEq, Debug)]
enum Fmt {
    Fp16,
    Kv8,
}

impl Fmt {
    fn row_bytes(self) -> usize {
        match self {
            Fmt::Fp16 => HD * 2,
            Fmt::Kv8 => HD,
        }
    }
    fn gpu(self) -> Gpu {
        let base = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
        let src = match self {
            Fmt::Fp16 => base,
            Fmt::Kv8 => format!("#define KV8 1\n{base}"),
        };
        Gpu::new(&src, &KERNELS)
    }
}

struct Rng(u64);

impl Rng {
    fn f(&mut self) -> f32 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^= z >> 31;
        ((z >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
    }
}

/// One stored cache row (its bytes) and the vector it stands for.
fn cache_row(fmt: Fmt, rng: &mut Rng) -> (Vec<u8>, Vec<f32>) {
    let mag = 0.2 + 1.5 * rng.f().abs();
    scaled_row(fmt, rng, mag)
}

/// A stored row of random values within `mag` (a planted stale row uses a large one, so reading it shows).
fn scaled_row(fmt: Fmt, rng: &mut Rng, mag: f32) -> (Vec<u8>, Vec<f32>) {
    let x: Vec<f32> = (0..HD).map(|_| rng.f() * mag).collect();
    match fmt {
        Fmt::Fp16 => {
            let bits: Vec<u16> = x.iter().map(|&v| f32_to_f16_bits(v)).collect();
            let bytes = bits.iter().flat_map(|b| b.to_le_bytes()).collect();
            (bytes, bits.iter().map(|&b| f16_bits_to_f32(b)).collect())
        }
        Fmt::Kv8 => {
            let q = super::kv8_tc_tests::kv8_quant_row(&x);
            let bytes: Vec<u8> = q.iter().map(|&v| v as u8).collect();
            let s = kv8_vscale_cpu(&bytes);
            (bytes, q.iter().map(|&v| f32::from(v) * s).collect())
        }
    }
}

/// `n` floats of a shared-storage buffer from word `off` (the GPU is idle between dispatches here).
#[allow(clippy::mut_from_ref)]
fn floats(b: &Buf, off: usize, n: usize) -> &mut [f32] {
    unsafe { std::slice::from_raw_parts_mut(b.contents().as_ptr().cast::<f32>().add(off), n) }
}

#[allow(clippy::mut_from_ref)]
fn bytes_of(b: &Buf, off: usize, n: usize) -> &mut [u8] {
    unsafe { std::slice::from_raw_parts_mut(b.contents().as_ptr().cast::<u8>().add(off), n) }
}

fn put<T: Copy>(b: &Buf, off_words: usize, items: &[T]) {
    unsafe {
        let dst = b.contents().as_ptr().cast::<f32>().add(off_words).cast::<T>();
        std::ptr::copy_nonoverlapping(items.as_ptr(), dst, items.len());
    }
}

fn run(gpu: &Gpu, what: &str, f: impl FnOnce(&Enc)) {
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    f(&e);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, what);
}

/// The attention output of `slots` split partials (`m`, `l`, `O[HD]` each) with the zero-logit sink, as
/// `k_attn_combine_dec` folds them.
fn combine(slots: &[f32]) -> Vec<f64> {
    let parts: Vec<&[f32]> = slots.chunks(HD + 2).collect();
    let m = parts.iter().fold(0.0f64, |m, p| m.max(f64::from(p[0])));
    let mut l = (-m).exp();
    let mut o = vec![0.0f64; HD];
    for p in &parts {
        let w = (f64::from(p[0]) - m).exp();
        l += w * f64::from(p[1]);
        for (o, &v) in o.iter_mut().zip(&p[2..]) {
            *o += w * f64::from(v);
        }
    }
    o.iter().map(|o| o / l).collect()
}

/// Worst `(abs, rel)` difference over HD-long output vectors, rel against the larger magnitude of `b`.
fn difference(a: &[f64], b: &[f64]) -> (f64, f64) {
    let (mut abs, mut rel) = (0.0f64, 0.0f64);
    for (a, b) in a.chunks(HD).zip(b.chunks(HD)) {
        let d = a.iter().zip(b).fold(0.0f64, |m, (a, b)| m.max((a - b).abs()));
        let scale = b.iter().fold(0.0f64, |m, b| m.max(b.abs()));
        assert!(d.is_finite() && scale.is_finite(), "non-finite attention output");
        abs = abs.max(d);
        rel = rel.max(d / scale.max(1e-3));
    }
    (abs, rel)
}

fn within(what: &str, (abs, rel): (f64, f64)) {
    eprintln!("[kv8-tc-dec] {what:<72} {abs:.2e} abs {rel:.2e} rel");
    assert!(abs <= MAX_ABS && rel <= MAX_REL, "{what}: {abs:.3e} abs, {rel:.3e} rel exceeds {MAX_ABS:.0e} / {MAX_REL:.0e}");
}

fn moved(what: &str, (abs, _): (f64, f64)) {
    eprintln!("[kv8-tc-dec] {what:<72} {abs:.2e} abs (must move)");
    assert!(abs > 20.0 * MAX_ABS, "{what}: the planted row did not reach the output ({abs:.3e})");
}

// ---------------------------------------------------------------------------------------------------------------
// Layer 3 paged decode: `k_attn_tc_dec_solo` + `k_attn_tc_grp_dec` against `k_attn_dec_solo` + `k_attn_grp_dec`.

struct L3 {
    gpu: Gpu,
    fmt: Fmt,
    swa: bool,
    kps: usize,
    pos0: usize,
    nrows: usize,
    nsplit: usize,
    kv: Buf,
    bt: Buf,
    pb: Buf,
    act: Buf,
    pass_blk_bytes: usize,
    q_words: usize,
    r_words: usize,
    cur_off: usize,
    part_words: usize,
    desc_off: usize,
    grp_off: usize,
    part0: usize,
}

impl L3 {
    fn new(fmt: Fmt, swa: bool, pos0: usize, kps: usize, rng: &mut Rng) -> L3 {
        let gpu = fmt.gpu();
        let nrows = 17usize;
        let total = pos0 + nrows;
        let n_blks = total.div_ceil(64);
        let rb = fmt.row_bytes();
        let pass_blk_bytes = 2 * NKV * 64 * rb;
        let nsplit = fixed_attn_nsplit(swa, total);
        let kv = gpu.buffer(n_blks * pass_blk_bytes);
        let bt = gpu.buffer(n_blks * 8);
        let pb = gpu.buffer(4096 + EXT * NREL * 4);
        let q_words = (nrows * NH * HD).div_ceil(2);
        let r_words = nrows * NH * NREL;
        let sink_words = nrows * NH;
        let cur_words = nrows * 2 * NKV * HD;
        let part_words = nrows * NH * nsplit * (HD + 2);
        let desc_words = (nrows * std::mem::size_of::<DecodeSpanDesc>()).div_ceil(4);
        let grp_words = (nrows * (nsplit + 2) * std::mem::size_of::<DecAttnGroup>()).div_ceil(4);
        let cur_off = q_words + r_words + sink_words;
        let part0 = cur_off + cur_words;
        let desc_off = part0 + 2 * part_words;
        let grp_off = desc_off + desc_words;
        let act = gpu.buffer((grp_off + grp_words + 64) * 4);
        let l3 = L3 {
            gpu,
            fmt,
            swa,
            kps,
            pos0,
            nrows,
            nsplit,
            kv,
            bt,
            pb,
            act,
            pass_blk_bytes,
            q_words,
            r_words,
            cur_off,
            part_words,
            desc_off,
            grp_off,
            part0,
        };
        let bt: Vec<u64> = (0..n_blks).map(|b| (b * pass_blk_bytes) as u64).collect();
        put(&l3.bt, 0, &bt);
        for x in floats(&l3.pb, 1024, EXT * NREL) {
            *x = rng.f() * 0.25;
        }
        for plane in 0..2 {
            for g in 0..NKV {
                for pos in 0..total {
                    let (row, deq) = cache_row(fmt, rng);
                    bytes_of(&l3.kv, l3.row_at(plane, g, pos), rb).copy_from_slice(&row);
                    if pos >= pos0 {
                        // the current token's K/V as `k_kvprep_dec` leaves it in `kv_cur` (dequantized floats)
                        let off = cur_off + (pos - pos0) * 2 * NKV * HD + plane * NKV * HD + g * HD;
                        floats(&l3.act, off, HD).copy_from_slice(&deq);
                    }
                }
            }
        }
        let q: Vec<u16> = (0..nrows * NH * HD).map(|_| f32_to_f16_bits(rng.f() * 1.1)).collect();
        put(&l3.act, 0, &q);
        for x in floats(&l3.act, q_words, r_words) {
            *x = rng.f() * 0.5;
        }
        for x in floats(&l3.act, q_words + r_words, sink_words) {
            *x = rng.f() * 0.7;
        }
        l3
    }

    fn row_at(&self, plane: usize, g: usize, pos: usize) -> usize {
        let rb = self.fmt.row_bytes();
        (pos / 64) * self.pass_blk_bytes + plane * NKV * 64 * rb + (g * 64 + pos % 64) * rb
    }

    fn range(&self, r: usize) -> (usize, usize) {
        let pos = self.pos0 + r;
        (if self.swa { (pos + 1).saturating_sub(EXT) } else { 0 }, pos)
    }

    /// Decode attention for every row into partial region `region` (0 or 1); returns the combined outputs.
    fn decode(&self, tc: bool, dry: bool, no_grp: bool, region: usize) -> Vec<f64> {
        let part_off = self.part0 + region * self.part_words;
        let descs: Vec<DecodeSpanDesc> = (0..self.nrows)
            .map(|r| {
                let (first, pos) = self.range(r);
                DecodeSpanDesc {
                    pos: pos as u32,
                    part_off: (part_off + r * NH * self.nsplit * (HD + 2)) as u32,
                    swa_nkeys: (pos + 1 - first) as u32,
                    swa_first_pos: first as u32,
                    swa_kps: 64,
                    swa_nsplit: self.nsplit as u32,
                    full_nkeys: (pos + 1) as u32,
                    full_kps: 256,
                    full_nsplit: self.nsplit as u32,
                    full_tau: 1.0,
                    swa_tau: 1.0,
                    ..Default::default()
                }
            })
            .collect();
        put(&self.act, self.desc_off, &descs);
        let ranges: Vec<(usize, usize)> = (0..self.nrows).map(|r| self.range(r)).collect();
        let groups = build_decode_groups(&ranges, self.kps, no_grp, |_, bi| Some((bi as u32 + 1, 1)));
        let solo: Vec<DecAttnGroup> = groups.iter().copied().filter(|g| g.count == 1).collect();
        let shared: Vec<DecAttnGroup> = groups.iter().copied().filter(|g| g.count > 1).collect();
        assert!(!dry || shared.is_empty(), "dry steps run every split solo");
        put(&self.act, self.grp_off, &solo);
        put(&self.act, self.grp_off + solo.len() * std::mem::size_of::<DecAttnGroup>() / 4, &shared);
        floats(&self.act, part_off, self.part_words).fill(f32::NAN);
        let ga = AttnGrpDecArgs {
            desc_off: self.desc_off as u32,
            grp_off: self.grp_off as u32,
            qp_off: 0,
            rp_off: self.q_words as u32,
            kv_cur_off: self.cur_off as u32,
            sink_off: (self.q_words + self.r_words) as u32,
            relbias_w: 4096,
            pass_idx: 0,
            kps: self.kps as u32,
            swa: (self.swa as u32) | ((dry as u32) << 1) | 4,
            pad0: 0,
            pad1: 0,
        };
        let (k_solo, t_solo, k_grp, t_grp) =
            if tc { ("k_attn_tc_dec_solo", crate::engine::tc_dec_solo_threads(self.fmt == Fmt::Kv8), "k_attn_tc_grp_dec", 96) } else { ("k_attn_dec_solo", 128, "k_attn_grp_dec", 512) };
        run(&self.gpu, k_solo, |e| {
            e.buf(&self.pb, 0, 1);
            e.buf(&self.act, 0, 2);
            e.buf(&self.kv, 0, 3);
            e.buf(&self.bt, 0, 8);
            for i in [10, 11, 12] {
                e.buf(&self.kv, 0, i);
            }
            e.bytes(&ga, 5);
            e.pso(&self.gpu.pso(k_solo));
            e.dispatch((solo.len(), NKV, 1), t_solo);
            if !shared.is_empty() {
                let ga_sh = AttnGrpDecArgs {
                    grp_off: (self.grp_off + solo.len() * std::mem::size_of::<DecAttnGroup>() / 4) as u32,
                    ..ga
                };
                e.bytes(&ga_sh, 5);
                e.pso(&self.gpu.pso(k_grp));
                e.dispatch((shared.len(), NKV, 1), t_grp);
            }
        });
        let part = floats(&self.act, 0, self.part0 + 2 * self.part_words);
        let mut out = Vec::with_capacity(self.nrows * NH * HD);
        for r in 0..self.nrows {
            let (first, pos) = self.range(r);
            let count = fixed_split_count(first, pos + 1, self.kps);
            for h in 0..NH {
                let base = part_off + (r * NH * self.nsplit + h * self.nsplit) * (HD + 2);
                out.extend(combine(&part[base..base + count * (HD + 2)]));
            }
        }
        out
    }

    /// Stale codes in the last row's current-token slot (no other row reads it: it is the deepest position).
    fn plant_stale_current_row(&self, rng: &mut Rng) {
        let pos = self.pos0 + self.nrows - 1;
        for plane in 0..2 {
            for g in 0..NKV {
                let (row, _) = scaled_row(self.fmt, rng, 12.0);
                bytes_of(&self.kv, self.row_at(plane, g, pos), self.fmt.row_bytes()).copy_from_slice(&row);
            }
        }
    }

    fn last_row(&self, out: &[f64]) -> Vec<f64> {
        out[(self.nrows - 1) * NH * HD..].to_vec()
    }
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_dec_layer3_solo_and_grouped_match_the_simdgroup_kernels() {
    for fmt in [Fmt::Fp16, Fmt::Kv8] {
        for (case, swa, pos0, kps) in [("full", false, 250usize, 256usize), ("full deep", false, 1500, 256), ("window", true, 2040, 64)] {
            let mut rng = Rng(0x6b76_3874_6463 ^ pos0 as u64 ^ ((fmt == Fmt::Kv8) as u64) << 40);
            let l3 = L3::new(fmt, swa, pos0, kps, &mut rng);
            let name = format!("{fmt:?} {case}");
            let tc = l3.decode(true, false, false, 0);
            let simd = l3.decode(false, false, false, 1);
            within(&format!("{name}: L3 tensor cores vs simdgroups"), difference(&tc, &simd));
            let tc_solo = l3.decode(true, false, true, 1);
            within(&format!("{name}: L3 tensor cores, every split solo vs grouped"), difference(&tc_solo, &tc));

            l3.plant_stale_current_row(&mut rng);
            let tc_dry = l3.decode(true, true, true, 1);
            within(&format!("{name}: L3 tensor cores dry (kv_cur) vs clean cache"), difference(&tc_dry, &tc));
            let simd_dry = l3.decode(false, true, true, 1);
            within(&format!("{name}: L3 tensor cores dry vs simdgroups dry"), difference(&tc_dry, &simd_dry));
            let tc_stale = l3.decode(true, false, true, 1);
            moved(&format!("{name}: L3 tensor cores reading the planted slot"), difference(&l3.last_row(&tc_stale), &l3.last_row(&tc)));
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------
// Layer 2 contiguous decode: `k_attn_tc_dec` against `k_attn`, both preparing and storing the token's own K/V.

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_dec_layer2_matches_k_attn_and_stores_the_same_row() {
    for fmt in [Fmt::Fp16, Fmt::Kv8] {
        let gpu = fmt.gpu();
        let rb = fmt.row_bytes();
        for (case, pos, window, kps) in [("full", 777usize, false, 256usize), ("window", 2100, true, 64)] {
            let mut rng = Rng(0x004c_3264_6563 ^ pos as u64 ^ ((fmt == Fmt::Kv8) as u64) << 40);
            let first_pos = if window { pos + 1 - EXT } else { 0 };
            let cap = (pos + 1).div_ceil(64) * 64;
            let nsplit = pos / kps - first_pos / kps + 1;
            // parameters: relative bias, K/V conv taps, Q and R clips
            let relbias_w = 4096usize;
            let kconv_w = relbias_w + EXT * NREL * 4;
            let vconv_w = kconv_w + NKV * HD * 16;
            let qclip_w = vconv_w + NKV * HD * 16;
            let relclip_w = qclip_w + NH * HD * 4;
            let pb = gpu.buffer(relclip_w + NH * NREL * 4);
            for x in floats(&pb, relbias_w / 4, EXT * NREL) {
                *x = rng.f() * 0.25;
            }
            for x in floats(&pb, kconv_w / 4, 2 * NKV * HD * 4) {
                *x = rng.f() * 0.5;
            }
            for x in floats(&pb, qclip_w / 4, NH * HD + NH * NREL) {
                *x = 0.5 + rng.f().abs();
            }
            // activations: q (half), k, v, r, sink, then one partial region per run
            let q_off = 0usize;
            let k_off = (NH * HD).div_ceil(2);
            let v_off = k_off + NKV * HD;
            let r_off = v_off + NKV * HD;
            let sink_off = r_off + NH * NREL;
            let part_off = sink_off + NH;
            let part_words = NH * nsplit * (HD + 2);
            let act = gpu.buffer((part_off + part_words + 64) * 4);
            let q: Vec<u16> = (0..NH * HD).map(|_| f32_to_f16_bits(rng.f() * 1.5)).collect();
            put(&act, q_off, &q);
            for x in floats(&act, k_off, 2 * NKV * HD + NH * NREL + NH) {
                *x = rng.f();
            }
            let cs: Vec<f32> = (0..2 * NKV * HD * 3).map(|_| rng.f()).collect();
            let kv_bytes = 2 * NKV * cap * rb;
            let mut kv0 = vec![0u8; kv_bytes];
            for plane in 0..2 {
                for g in 0..NKV {
                    for p in 0..pos {
                        let (row, _) = cache_row(fmt, &mut rng);
                        let off = ((plane * NKV + g) * cap + p) * rb;
                        kv0[off..off + rb].copy_from_slice(&row);
                    }
                    // stale codes in the token's own slot: the kernels must store over it or, dry, never read it
                    let (row, _) = cache_row(fmt, &mut rng);
                    let off = ((plane * NKV + g) * cap + pos) * rb;
                    kv0[off..off + rb].copy_from_slice(&row);
                }
            }
            let ctr = gpu.buffer(4096);
            let attend = |kernel: &str, dry: bool| -> (Vec<f64>, Vec<u8>, Vec<f32>) {
                let kv = gpu.buffer_with(&kv0);
                let csb = gpu.buffer(cs.len() * 4);
                put(&csb, 0, &cs);
                floats(&act, part_off, part_words).fill(f32::NAN);
                let a = AttnArgs {
                    pos: pos as u32,
                    nkeys: (pos + 1 - first_pos) as u32,
                    first_pos: first_pos as u32,
                    ring: 0,
                    cap: cap as u32,
                    k_base: 0,
                    v_base: (NKV * cap * HD) as u32,
                    cs_off: 0,
                    q_off: q_off as u32,
                    k_off: k_off as u32,
                    v_off: v_off as u32,
                    r_off: r_off as u32,
                    sink_off: sink_off as u32,
                    kdyn_off: -1,
                    vdyn_off: -1,
                    part_off: part_off as u32,
                    kconv_w: kconv_w as u32,
                    vconv_w: vconv_w as u32,
                    qclip_w: qclip_w as u32,
                    relclip_w: relclip_w as u32,
                    relbias_w: relbias_w as u32,
                    tau: 1.0,
                    kps: kps as u32,
                    nsplit: nsplit as u32,
                    // partials only (no in-kernel combine), half_io, dry on request
                    pad: 1 | 8 | ((dry as u32) << 1),
                    gstr: (cap * HD) as u32,
                    istr: HD as u32,
                    log_alpha: 0.0,
                    log_floor: 1.0,
                    ..Default::default()
                };
                run(&gpu, kernel, |e| {
                    e.buf(&pb, 0, 1);
                    e.buf(&act, 0, 2);
                    e.buf(&kv, 0, 3);
                    e.buf(&csb, 0, 4);
                    e.bytes(&a, 5);
                    e.buf(&ctr, 0, 7);
                    e.pso(&gpu.pso(kernel));
                    e.dispatch((nsplit, NKV, 1), 128);
                });
                let part = floats(&act, part_off, part_words);
                let out = (0..NH).flat_map(|h| combine(&part[h * nsplit * (HD + 2)..(h + 1) * nsplit * (HD + 2)])).collect();
                (out, bytes_of(&kv, 0, kv_bytes).to_vec(), floats(&csb, 0, cs.len()).to_vec())
            };
            let name = format!("{fmt:?} {case}");
            let (tc, tc_kv, tc_cs) = attend("k_attn_tc_dec", false);
            let (simd, simd_kv, simd_cs) = attend("k_attn", false);
            within(&format!("{name}: L2 k_attn_tc_dec vs k_attn"), difference(&tc, &simd));
            assert!(tc_kv == simd_kv, "{name}: k_attn_tc_dec must store the token's K/V rows byte for byte as k_attn");
            assert!(tc_kv != kv0, "{name}: the token's K/V rows were not stored");
            assert!(
                tc_cs.iter().zip(&simd_cs).all(|(a, b)| a.to_bits() == b.to_bits()),
                "{name}: conv state must advance identically"
            );
            let (tc_dry, tc_dry_kv, tc_dry_cs) = attend("k_attn_tc_dec", true);
            within(&format!("{name}: L2 k_attn_tc_dec dry vs not dry"), difference(&tc_dry, &tc));
            assert!(tc_dry_kv == kv0, "{name}: a dry k_attn_tc_dec must not write the cache");
            assert!(tc_dry_cs.iter().zip(&cs).all(|(a, b)| a.to_bits() == b.to_bits()), "{name}: a dry step must not advance the conv state");
            let (simd_dry, _, _) = attend("k_attn", true);
            within(&format!("{name}: L2 k_attn_tc_dec dry vs k_attn dry"), difference(&tc_dry, &simd_dry));
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------
// Sparse decode: `k_attn_tc_sparse_dec` against `k_attn_sparse_dec` over selected 64-key blocks of a paged cache.

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_dec_sparse_matches_k_attn_sparse_dec() {
    for fmt in [Fmt::Fp16, Fmt::Kv8] {
        let gpu = fmt.gpu();
        let rb = fmt.row_bytes();
        let mut rng = Rng(0x5370_6172_7365 ^ ((fmt == Fmt::Kv8) as u64) << 40);
        let n_blks = 20usize;
        let pos = n_blks * 64 - 23;
        let sel: [u32; 5] = [0, 5, 6, 11, (n_blks - 1) as u32];
        let (blks_per_split, nsplit) = (2usize, 3usize);
        let pass_blk_bytes = 2 * NKV * 64 * rb;
        let row_at = |plane: usize, g: usize, p: usize| (p / 64) * pass_blk_bytes + plane * NKV * 64 * rb + (g * 64 + p % 64) * rb;
        let kv = gpu.buffer(n_blks * pass_blk_bytes);
        let bt = gpu.buffer(n_blks * 8);
        put(&bt, 0, &(0..n_blks).map(|b| (b * pass_blk_bytes) as u64).collect::<Vec<_>>());
        let pb = gpu.buffer(4096 + EXT * NREL * 4);
        for x in floats(&pb, 1024, EXT * NREL) {
            *x = rng.f() * 0.25;
        }
        let qp_off = 0usize;
        let rp_off = (NH * HD).div_ceil(2);
        let sink_off = rp_off + NH * NREL;
        let cur_off = sink_off + NH;
        let part_off = cur_off + 2 * NKV * HD;
        let part_words = NH * nsplit * (HD + 2);
        let act = gpu.buffer((part_off + part_words + 64) * 4);
        for plane in 0..2 {
            for g in 0..NKV {
                for p in 0..=pos {
                    let (row, deq) = cache_row(fmt, &mut rng);
                    bytes_of(&kv, row_at(plane, g, p), rb).copy_from_slice(&row);
                    if p == pos {
                        floats(&act, cur_off + plane * NKV * HD + g * HD, HD).copy_from_slice(&deq);
                    }
                }
            }
        }
        put(&act, qp_off, &(0..NH * HD).map(|_| f32_to_f16_bits(rng.f() * 1.1)).collect::<Vec<_>>());
        for x in floats(&act, rp_off, NH * NREL + NH) {
            *x = rng.f() * 0.5;
        }
        let sparse = gpu.buffer(4096);
        let sel_base = 32usize;
        let sel_all: Vec<u32> = (0..NKV).flat_map(|_| sel).collect();
        unsafe {
            let dst = sparse.contents().as_ptr().cast::<u32>().add(sel_base);
            std::ptr::copy_nonoverlapping(sel_all.as_ptr(), dst, sel_all.len());
        }
        let attend = |tc: bool, flags: u32| -> Vec<f64> {
            let task = SparseDecTask {
                pos: pos as u32,
                total_sel_blks: sel.len() as u32,
                blks_per_split: blks_per_split as u32,
                nsplit: nsplit as u32,
                qp_off: qp_off as u32,
                rp_off: rp_off as u32,
                sink_off: sink_off as u32,
                kv_cur_off: cur_off as u32,
                part_off: part_off as u32,
                flags,
                ..Default::default()
            };
            put(&sparse, 0, &[task]);
            floats(&act, part_off, part_words).fill(f32::NAN);
            let a = AttnSparseDecArgs {
                pass_idx: 0,
                n_tasks: 1,
                is_paged: 1,
                relbias_w: 4096,
                tasks_u32_off: 0,
                sel_u32_base: sel_base as u32,
                pass_sel_stride: 0,
                pad0: 0,
            };
            let (kernel, threads) = if tc { ("k_attn_tc_sparse_dec", 96) } else { ("k_attn_sparse_dec", 128) };
            run(&gpu, kernel, |e| {
                e.buf(&pb, 0, 1);
                e.buf(&act, 0, 2);
                e.buf(&kv, 0, 3);
                e.bytes(&a, 5);
                e.buf(&bt, 0, 8);
                for i in [10, 11, 12] {
                    e.buf(&kv, 0, i);
                }
                e.buf(&sparse, 0, 14);
                e.pso(&gpu.pso(kernel));
                e.dispatch((nsplit, NKV, 1), threads);
            });
            let part = floats(&act, part_off, part_words);
            (0..NH).flat_map(|h| combine(&part[h * nsplit * (HD + 2)..(h + 1) * nsplit * (HD + 2)])).collect()
        };
        let name = format!("{fmt:?} sparse");
        let tc = attend(true, 1);
        within(&format!("{name}: k_attn_tc_sparse_dec vs k_attn_sparse_dec"), difference(&tc, &attend(false, 1)));
        for plane in 0..2 {
            for g in 0..NKV {
                let (row, _) = scaled_row(fmt, &mut rng, 12.0);
                bytes_of(&kv, row_at(plane, g, pos), rb).copy_from_slice(&row);
            }
        }
        let tc_buf = attend(true, 3);
        within(&format!("{name}: tensor cores, current row from kv_cur vs clean cache"), difference(&tc_buf, &tc));
        within(&format!("{name}: tensor cores vs simdgroups, current row from kv_cur"), difference(&tc_buf, &attend(false, 3)));
        moved(&format!("{name}: tensor cores reading the planted slot"), difference(&attend(true, 1), &tc));
    }
}

// ---------------------------------------------------------------------------------------------------------------
// The real model on the M5: `--kv8` decode with and without `INK_TC_ATTN_DEC`, teacher-forced on one token stream.

/// Sets `INK_TC_ATTN_DEC` while it lives and puts the previous value back on drop.
struct TcAttnDecScope(Option<std::ffi::OsString>);

impl TcAttnDecScope {
    fn set() -> Self {
        let previous = std::env::var_os("INK_TC_ATTN_DEC");
        std::env::set_var("INK_TC_ATTN_DEC", "1");
        Self(previous)
    }
}

impl Drop for TcAttnDecScope {
    fn drop(&mut self) {
        match self.0.take() {
            Some(v) => std::env::set_var("INK_TC_ATTN_DEC", v),
            None => std::env::remove_var("INK_TC_ATTN_DEC"),
        }
    }
}

fn softmax(lg: &[f32]) -> (usize, Vec<f64>) {
    let (best, mx) = lg.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |(bi, m), (i, &v)| if v > m { (i, v) } else { (bi, m) });
    let mut p: Vec<f64> = lg.iter().map(|&v| f64::from(v - mx).exp()).collect();
    let sum: f64 = p.iter().sum();
    p.iter_mut().for_each(|x| *x /= sum);
    (best, p)
}

fn kl(p: &[f64], q: &[f64]) -> f64 {
    p.iter().zip(q).filter(|(&p, _)| p > 1e-12).map(|(&p, &q)| p * (p / q.max(1e-30)).ln()).sum()
}

/// The strict per-step KL bound where the reference is confident (top-1 probability above `CONFIDENT`): the
/// repo's bound for KV8 tensor-core vs scalar prefill (`kv8_tc_prefill_matches_scalar_kv8_kl_and_interior_tile_invariants_on_m5`).
const STRICT_KL: f64 = 1e-4;
const CONFIDENT: f64 = 0.99;

/// Real-model `--kv8` decode with `INK_TC_ATTN_DEC` against the default simdgroup decode, teacher-forced on the
/// simdgroup run's greedy tokens (6000-token prompt, 48 steps). An absolute KL bound does not fit this comparison:
/// two half-precision orderings of the same attention move a logit by ~1e-3, which is invisible where the model is
/// sure and shows as KL up to a few 1e-2 at near-tie tokens (#268: KV8 TC decode worst 1.70e-2, FP16 TC decode
/// 1.28e-2, both only at the 3 of 48 steps with top-1 probability 0.96 to 0.98; the default tensor-core prefill
/// against the scalar prefill, two paths inky already accepts, reaches 6.07e-2 at the same steps; a single decode
/// step from an identical cache gives 6.8e-3 and 8.9e-3 there and ~1e-15 next to them, so it does not compound).
/// So the bound is relative, step by step, to that accepted pair on the same prompt and steps:
/// - every step: KL(simd || tc) <= max(KL(simd || scalar-prefill), STRICT_KL),
/// - every step where the simdgroup run's top-1 probability is above CONFIDENT: KL(simd || tc) < STRICT_KL,
/// - top-1 agrees on all but at most one step, and the simdgroup run repeats bit for bit (so the reference is real).
#[test]
#[ignore = "requires Apple M5 Metal 4 tensor-core GPU and local GGUF"]
fn kv8_tc_dec_real_model_kl_against_simdgroup_decode_on_m5() {
    use crate::blocks::KvMode;
    use crate::poolgate::{Layer3Pool, StepPath};
    let dev = objc2_metal::MTLCreateSystemDefaultDevice().expect("Metal device required");
    assert!(dev.name().to_string().contains("M5"), "M5 GPU required (tensor-core prefill and decode), got `{}`", dev.name());
    let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    let ctx = 8192usize;
    let eng = Engine::prepare_model(&model, ctx, LaneStore::Pooled)
        .and_then(|p| p.into_engine_mode(KvMode::Kv8, ctx))
        .expect("load model in Kv8 mode");
    eng.ensure_batch(eng.chunk);
    assert!(eng.arith_knobs().split_attn, "the default --kv8 decode runs the simdgroup kernels");
    let tk = crate::tokenizer::Tokenizer::load(&eng.g);
    let base = tk.encode("Explain how unified memory bandwidth and matrix coprocessors interact during transformer decode. ", true);
    let prompt: Vec<u32> = base.iter().copied().cycle().take(6000).collect();
    let steps = 48usize;

    // greedy tokens of the simdgroup run, replayed into the other runs
    let arm = |forced: Option<&[u32]>| -> (Vec<u32>, Vec<Vec<f32>>) {
        let pool = Layer3Pool::new(&eng, 1);
        let lane = pool.new_lane(&prompt, ctx);
        let mut p0 = 0usize;
        while p0 < prompt.len() {
            let n = (prompt.len() - p0).min(eng.chunk);
            pool.prefill(&[(lane, p0, n)]);
            p0 += n;
        }
        let mut toks = Vec::with_capacity(steps);
        let mut logits = Vec::with_capacity(steps);
        let mut lg = pool.logits(0);
        for step in 0..steps {
            let tok = forced.map_or_else(|| crate::sampler::checked_argmax(&lg).unwrap() as u32, |f| f[step]);
            toks.push(tok);
            pool.set_token(lane, prompt.len() + step, tok);
            pool.decode(&[(lane, prompt.len() + step)]);
            lg = pool.logits(0);
            assert!(lg.iter().all(|x| x.is_finite()), "non-finite logit at decode step {step}");
            logits.push(lg.clone());
        }
        (toks, logits)
    };
    let (toks, simd) = arm(None);
    let rerun = arm(Some(&toks)).1;
    let tc = {
        let _tc = TcAttnDecScope::set();
        assert!(!eng.arith_knobs().split_attn, "INK_TC_ATTN_DEC puts --kv8 decode on the tensor cores");
        arm(Some(&toks)).1
    };
    // the accepted reference pair: the same simdgroup decode after the scalar prefill instead of the tensor-core one
    let scalar = {
        let _no_tc = crate::engine::NoTcAttnScope::set();
        arm(Some(&toks)).1
    };
    for (step, (a, b)) in simd.iter().zip(&rerun).enumerate() {
        assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "the simdgroup run does not repeat at step {step}");
    }
    let (mut worst, mut worst_ref, mut top1, mut series) = (0.0f64, 0.0f64, 0usize, String::new());
    let mut failures = Vec::new();
    for (step, ((a, b), r)) in simd.iter().zip(&tc).zip(&scalar).enumerate() {
        let ((ta, pa), (tb, pb), (_, pr)) = (softmax(a), softmax(b), softmax(r));
        let (d, d_ref, p1) = (kl(&pa, &pb), kl(&pa, &pr), pa[ta]);
        worst = worst.max(d);
        worst_ref = worst_ref.max(d_ref);
        top1 += usize::from(ta == tb);
        series += &format!(" {step}:{d:.1e}/{d_ref:.1e}@{p1:.3}");
        if d > d_ref.max(STRICT_KL) {
            failures.push(format!("step {step}: KL {d:.3e} above the scalar-prefill reference {d_ref:.3e} (top-1 p {p1:.3})"));
        }
        if p1 > CONFIDENT && d >= STRICT_KL {
            failures.push(format!("step {step}: KL {d:.3e} >= {STRICT_KL:e} where the reference is confident (top-1 p {p1:.4})"));
        }
    }
    eprintln!(
        "[kv8-tc-dec m5] {} prompt tokens, {steps} teacher-forced steps: KL(simd || tc) worst {worst:.3e}, \
         KL(simd || scalar prefill) worst {worst_ref:.3e}, top-1 {top1}/{steps}\n[kv8-tc-dec m5] step:tc/ref@p1{series}",
        prompt.len()
    );
    assert!(failures.is_empty(), "KV8 tensor-core decode KL out of bounds:\n{}", failures.join("\n"));
    assert!(top1 + 1 >= steps, "KV8 tensor-core decode top-1 agrees on {top1}/{steps} steps");
}

/// The body of `kernel void name(` in `src`: up to the next top-level kernel, or the end.
fn kernel_body<'a>(src: &'a str, name: &str) -> &'a str {
    let start = src.find(&format!("kernel void {name}(")).unwrap_or_else(|| panic!("{name} is in prefill.metal"));
    let rest = &src[start..];
    let end = rest[1..].find("\nkernel void ").map_or(rest.len(), |i| i + 1);
    &rest[..end]
}

/// #276: a `last_tg` reader sees other threadgroups' stores only through `coherent(device)` pointers. The tensor-core
/// decode kernels have no `last_tg` reduction to give that qualifier to: each split threadgroup writes its own
/// partial (`m`, `l`, `O` at `part_off`), and `k_attn_combine` / `k_attn_combine_dec` read them in a later dispatch
/// behind `e.barrier()` (the engine asserts `sep_comb` on decode steps), which orders and publishes device stores.
/// If a fused combine is ever added to one of these kernels, this fails and points at #276's pattern.
#[test]
fn tc_decode_kernels_combine_in_a_separate_dispatch_not_in_a_last_threadgroup() {
    let src = include_str!("../prefill.metal");
    assert!(!src.contains("last_tg("), "prefill.metal has a last_tg reader: its shared stores need coherent(device) (#276)");
    for name in ["k_attn_tc_dec", "k_attn_tc_dec_solo", "k_attn_tc_grp_dec", "k_attn_tc_sparse_dec"] {
        let body = kernel_body(src, name);
        for word in ["last_tg(", "atomic_fetch", "atomic_load", "atomic_store", "atomic_exchange"] {
            assert!(!body.contains(word), "{name} uses {word}: a cross-threadgroup reduction needs coherent(device) (#276)");
        }
        assert!(body.contains("part_off"), "{name} writes its split's partial for the combine pass");
    }
}