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
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! Speculative verify with `--sparse-topk` (DSpark, prompt lookup, and the 1-token decode lanes of a verify step).
//!
//! A decode step at position `p` past the sparse activation attends over the anchor, recent and top-k blocks its
//! own query picks from the far blocks' sketches. A verify row at `p` used to attend densely, so a speculation was a
//! speculation of a different model than the one decoding without drafts. Verify rows now attend on the decode
//! kernels with the decode plan of their position (`plan_verify_sparse_rows`, `encode_verify_sparse_rows`).
//!
//! Evidence, cheapest first:
//! 1. The row plan on the CPU: every row gets the plan a decode step at its position uses, sparse rows are a suffix,
//!    selected-block lists never overlap, split partials fit the arena (CI).
//! 2. The sketch protocol on the CPU: verify steps that rebuild the blocks they write, accepts and rejects
//!    (`rollback_verify` restores rows and marks the block dirty), decode catch-up of dirty blocks: every block's
//!    sketch equals a recompute from its final rows, and no recorded valid length over-claims (CI).
//! 3. The new combine kernel against the decode combine on random partials, bit for bit (any Metal GPU).
//! 4. The controller-down GEMM's decode-sized kernel against the prefill kernel it replaces on verify rows (M5).
//! 5. The model: greedy speculative generation with accepted and rejected drafts, Layer 2 and Layer 3, against
//!    non-speculative sparse decode: the same tokens and the same logits bits, and every finished block's sketch
//!    equal to the CPU recompute (M5).

use super::*;
use crate::blocks::{compute_full_slot_wht2_sketch_cpu, BlockIndex, BlockKind, FULL_SKETCH_BYTES};

// ---------------------------------------------------------------------------------------------------------------
// 1. The row plan

fn plan(pos: usize, max_ctx: usize, topk: usize, anchors: usize, min_ctx: usize) -> SparseDecodePlan {
    sparse_full_decode_plan_with_min_ctx(pos, max_ctx, Some(topk), anchors, min_ctx)
}

#[test]
fn verify_sparse_rows_take_the_decode_plan_of_their_position_as_a_suffix() {
    let (max_ctx, topk, anchors) = (262_144usize, 4usize, 4usize);
    // (4 anchors + 16 recent + 4 top-k) * 64 = 1,536 keys pass through
    let at = |p| plan(p, max_ctx, topk, anchors, 0);
    assert!(at(1535).passthrough && !at(1536).passthrough);
    let spans = [(1500usize, 9usize), (1530, 9), (1600, 5), (10, 1), (2000, 1)];
    let (rows, layout, stride) = plan_verify_sparse_rows(&spans, at, 4096);
    assert_eq!(layout.len(), spans.len());
    assert_eq!(layout[0], VerifySparseSpan { dense_rows: 9, chunks: vec![] });
    assert_eq!(layout[1].dense_rows, 6, "rows at 1530..1536 stay dense, 1536.. are sparse");
    assert_eq!(layout[2].dense_rows, 0);
    assert_eq!(layout[3], VerifySparseSpan { dense_rows: 1, chunks: vec![] });
    assert_eq!(layout[4].dense_rows, 0, "a 1-token decode lane of a verify step is sparse too");
    assert_eq!(rows.len(), 3 + 5 + 1);
    let mut sel = 0usize;
    for (i, r) in rows.iter().enumerate() {
        let (p0, t) = spans[r.span];
        assert!(r.row < t);
        assert_eq!(r.plan, at(p0 + r.row), "task {i} must carry the decode plan of position {}", p0 + r.row);
        assert!(!r.plan.passthrough);
        assert_eq!(r.sel_out_base, sel, "selected-block lists are laid end to end, never overlapping");
        sel += NKV * r.plan.total_sel_blocks;
    }
    assert_eq!(stride, sel);
    // tasks of each span are contiguous and in row order, covering exactly its sparse rows
    for (si, sp) in layout.iter().enumerate() {
        let tasks: Vec<usize> = sp.chunks.iter().flat_map(|c| c.task_lo..c.task_lo + c.n_tasks).collect();
        let want: Vec<usize> = rows.iter().enumerate().filter(|(_, r)| r.span == si).map(|(i, _)| i).collect();
        assert_eq!(tasks, want, "span {si}");
        for (j, &ti) in tasks.iter().enumerate() {
            assert_eq!(rows[ti].row, sp.dense_rows + j);
        }
    }
}

#[test]
fn verify_sparse_chunks_fit_the_split_partials_and_report_their_widest_task() {
    let at = |p| plan(p, 262_144, 128, 16, 0);
    let p0 = 200_000usize;
    let nsplit = at(p0).nsplit;
    assert!(nsplit > 1);
    for slots in [nsplit, 2 * nsplit, 3 * nsplit + 1, 64 * nsplit] {
        let (rows, layout, _) = plan_verify_sparse_rows(&[(p0, 33), (p0 + 100, 2)], at, slots);
        for sp in &layout {
            for c in &sp.chunks {
                let mine = &rows[c.task_lo..c.task_lo + c.n_tasks];
                let used: usize = mine.iter().map(|r| r.plan.nsplit).sum();
                assert!(used <= slots, "chunk uses {used} split slots of {slots}");
                assert_eq!(c.max_nsplit, mine.iter().map(|r| r.plan.nsplit).max().unwrap());
                assert_eq!(c.max_total_blks, mine.iter().map(|r| r.plan.total_blocks).max().unwrap());
                // partial regions of one chunk are disjoint and inside the arena
                let mut at_slot = 0usize;
                for r in mine {
                    assert_eq!(r.part_slot, at_slot);
                    at_slot += r.plan.nsplit;
                }
            }
        }
        let n_chunks: usize = layout.iter().map(|s| s.chunks.len()).sum();
        let per = slots / nsplit;
        assert_eq!(n_chunks, 33usize.div_ceil(per) + 2usize.div_ceil(per), "slots {slots}");
    }
}

#[test]
fn verify_sparse_rows_respect_the_min_ctx_floor() {
    let at = |p| plan(p, 262_144, 128, 16, 65_536);
    let (rows, layout, _) = plan_verify_sparse_rows(&[(65_530, 9)], at, 4096);
    assert_eq!(layout[0].dense_rows, 6);
    assert_eq!(rows.len(), 3);
    assert!(rows.iter().all(|r| r.plan == at(65_530 + r.row)));
    // no sparse top-k: every row dense, no tasks
    let (rows, layout, stride) = plan_verify_sparse_rows(
        &[(300_000, 9)],
        |p| sparse_full_decode_plan_with_min_ctx(p, 400_000, None, 16, 0),
        4096,
    );
    assert!(rows.is_empty() && stride == 0 && layout[0].dense_rows == 9);
}

// ---------------------------------------------------------------------------------------------------------------
// 2. The sketch protocol on the CPU
//
// One lane's `Full` blocks in a host pool. The steps mirror what the engine encodes:
// - prefill / verify write rows `p0..p0 + t` and rebuild every block they touch from its rows up to `p0 + t`
//   (`k_build_full_sketch_blk`), recording `valid = p0 + t - blk_start` (staged; applied unless the epoch moved);
// - `rollback_verify` restores the rejected rows to their pre-verify bytes and marks their blocks dirty;
// - a decode step at `pos` (or a sparse verify step at `p0`) first rebuilds every block before it whose recorded
//   valid length is short (the dirty-slot catch-up), then recomputes the sub-block it writes.
// Invariant: once the sequence is past a block, its sketch is the recompute from its final rows; and whatever valid
// length a block records, the sketch equals the recompute of that many rows.

struct Model {
    pools: crate::blocks::BlockPools,
    slots: Vec<crate::blocks::Slot>,
    kvb: u32,
    /// Planted fault: apply staged valid lengths even after a rollback moved the epoch.
    ignore_epoch: bool,
}

impl Model {
    fn new(n_blocks: usize) -> Model {
        let mut pools = crate::blocks::BlockPools::with_capacities_and_sketches(n_blocks, 1, 2, true).unwrap();
        let slots = (1..=n_blocks)
            .map(|i| {
                let s = crate::blocks::Slot::new(i as u32).unwrap();
                pools.full.take(s).unwrap();
                s
            })
            .collect();
        Model { pools, slots, kvb: 2, ignore_epoch: false }
    }
    fn row_bytes(&self) -> usize {
        HD * 2
    }
    /// Write the key and value rows of `pos` in every pass and head with values derived from `tag`.
    fn write_row(&mut self, pos: usize, tag: u32) {
        let (blk, ib) = (pos / BLOCK_T, pos % BLOCK_T);
        let rb = self.row_bytes();
        let head = BLOCK_T * rb;
        let plane = NKV * head;
        let pass = 2 * plane;
        let bytes = self.pools.full.slot_bytes_mut(self.slots[blk]).unwrap();
        for p in 0..crate::blocks::FULL_PASSES {
            for pl in 0..2 {
                for g in 0..NKV {
                    let off = p * pass + pl * plane + g * head + ib * rb;
                    for d in 0..HD {
                        let x = (tag.wrapping_mul(2_654_435_761) ^ ((p * 131 + g * 17 + d) as u32)) % 2001;
                        let v = crate::blocks::f32_to_f16_bits((x as f32 - 1000.0) / 500.0);
                        bytes[off + 2 * d..off + 2 * d + 2].copy_from_slice(&v.to_le_bytes());
                    }
                }
            }
        }
    }
    fn row_snapshot(&self, pos: usize) -> Vec<u8> {
        self.pools.full.slot_bytes(self.slots[pos / BLOCK_T]).unwrap().to_vec()
    }
    fn recompute(&self, blk: usize, valid: usize) -> Vec<u8> {
        let mut out = vec![0u8; FULL_SKETCH_BYTES];
        compute_full_slot_wht2_sketch_cpu(
            self.pools.full.slot_bytes(self.slots[blk]).unwrap(),
            self.kvb,
            valid,
            &mut out,
        );
        out
    }
    fn set_sketch(&mut self, blk: usize, valid: usize) {
        let sk = self.recompute(blk, valid);
        self.pools.full.slot_sketch_bytes_mut(self.slots[blk]).unwrap().copy_from_slice(&sk);
    }
    fn valid(&self, blk: usize) -> u8 {
        self.pools.full.slot_sketch_valid_len(self.slots[blk]).unwrap()
    }
    /// A span write (prefill or verify): rows, then every touched block rebuilt up to `p0 + t`; the staged valid
    /// lengths, as `(slot, epoch, valid)`, applied by the caller once the "GPU" completes.
    fn span(&mut self, p0: usize, toks: &[u32]) -> Vec<(crate::blocks::Slot, u64, u8)> {
        let end = p0 + toks.len();
        for (i, &tok) in toks.iter().enumerate() {
            self.write_row(p0 + i, tok);
        }
        let mut staged = Vec::new();
        for blk in p0 / BLOCK_T..=(end - 1) / BLOCK_T {
            let valid = (end - blk * BLOCK_T).min(BLOCK_T);
            self.set_sketch(blk, valid);
            let s = self.slots[blk];
            staged.push((s, self.pools.full.slot_sketch_epoch(s).unwrap(), valid as u8));
        }
        staged
    }
    fn apply(&mut self, staged: &[(crate::blocks::Slot, u64, u8)]) {
        for &(s, epoch, valid) in staged {
            if (self.ignore_epoch || self.pools.full.slot_sketch_epoch(s).unwrap() == epoch)
                && valid > self.pools.full.slot_sketch_valid_len(s).unwrap()
            {
                self.pools.full.set_slot_sketch_valid_len(s, valid).unwrap();
            }
        }
    }
    /// The catch-up of a decode (or sparse verify) step at `pos`: blocks before `pos`'s block short of 64.
    fn catch_up(&mut self, pos: usize) {
        for blk in 0..pos / BLOCK_T {
            if usize::from(self.valid(blk)) < BLOCK_T {
                self.set_sketch(blk, BLOCK_T);
                self.pools.full.set_slot_sketch_valid_len(self.slots[blk], BLOCK_T as u8).unwrap();
            }
        }
    }
    /// A decode step at `pos`: catch-up, the row, its sub-block recomputed (`k_update_full_sketch_dec`, which also
    /// zeroes the later sub-blocks on a block's first row), the valid length advanced contiguously.
    fn decode(&mut self, pos: usize, tok: u32) {
        self.catch_up(pos);
        self.write_row(pos, tok);
        let blk = pos / BLOCK_T;
        let ib = pos % BLOCK_T;
        let sub = crate::blocks::WHT2_SUB_TOKS;
        let fresh = self.recompute(blk, ib + 1);
        let hsk = crate::blocks::WHT2_HEAD_SKETCH_BYTES;
        let sb = ib / sub;
        let dst = self.pools.full.slot_sketch_bytes_mut(self.slots[blk]).unwrap();
        for h in 0..crate::blocks::FULL_PASSES * NKV {
            let base = h * hsk;
            let lo_sb = sb;
            let hi_sb = if ib == 0 { crate::blocks::WHT2_NSUB } else { sb + 1 };
            for s in lo_sb..hi_sb {
                let (w0, w1) = (base + s * 32, base + s * 32 + 32);
                dst[w0..w1].copy_from_slice(&fresh[w0..w1]);
                let (c0, c1) = (base + 256 + s * 2, base + 256 + s * 2 + 2);
                dst[c0..c1].copy_from_slice(&fresh[c0..c1]);
            }
        }
        let prev = self.valid(blk);
        let next = crate::blocks::advance_contiguous_sketch_valid_len(prev, ib);
        self.pools.full.set_slot_sketch_valid_len(self.slots[blk], next).unwrap();
    }
    fn check(&self, end: usize, what: &str) {
        self.check_from(0, end, what)
    }
    fn check_from(&self, from_blk: usize, end: usize, what: &str) {
        for blk in from_blk..end.div_ceil(BLOCK_T) {
            let s = self.pools.full.slot_sketch_bytes(self.slots[blk]).unwrap();
            let v = usize::from(self.valid(blk));
            assert!(v <= (end - blk * BLOCK_T).min(BLOCK_T), "{what}: block {blk} records {v} valid rows past {end}");
            // The sub-blocks holding the recorded rows are the recompute's; later ones are free (rebuilt on entry).
            let want = self.recompute(blk, v);
            let hsk = crate::blocks::WHT2_HEAD_SKETCH_BYTES;
            for h in 0..crate::blocks::FULL_PASSES * NKV {
                for sb in 0..v.div_ceil(crate::blocks::WHT2_SUB_TOKS) {
                    let (w, c) = (h * hsk + sb * 32, h * hsk + 256 + sb * 2);
                    assert!(
                        s[w..w + 32] == want[w..w + 32] && s[c..c + 2] == want[c..c + 2],
                        "{what}: block {blk} sub-block {sb} is not the recompute of its {v} recorded rows"
                    );
                }
            }
            if v == BLOCK_T {
                assert!(s == want.as_slice(), "{what}: finished block {blk} sketch differs");
            }
        }
    }
}

const BLOCK_T: usize = crate::blocks::BLOCK;

/// Greedy speculation on the model: the "true" continuation is `truth(pos)`; drafts are right up to `bad` and
/// wrong after. Every verify writes its whole span (drafts included), then rejects past the first wrong draft.
#[test]
fn verify_accepts_and_rejects_keep_every_sketch_equal_to_its_recompute() {
    speculate_on_the_model(false);
    // Witness: a staged valid length applied across a rollback's epoch bump over-claims the rejected rows.
    let planted = std::panic::catch_unwind(|| speculate_on_the_model(true));
    assert!(planted.is_err(), "the check must catch a valid length applied across a rollback");
}

fn speculate_on_the_model(ignore_epoch: bool) {
    let truth = |pos: usize| (pos as u32).wrapping_mul(7919) % 50_000 + 1;
    let n_blocks = 4usize;
    let mut m = Model::new(n_blocks);
    m.ignore_epoch = ignore_epoch;
    let prompt: Vec<u32> = (0..100).map(truth).collect();
    let staged = m.span(0, &prompt);
    m.apply(&staged);
    m.check(100, "prefill");
    // (k, index of the first wrong draft or k for all right, verify vs decode, apply before or after rollback)
    let rounds = [
        (4usize, 4usize, true, true),
        (4, 0, true, false),
        (8, 3, true, true),
        (1, 1, false, true),
        (8, 8, true, false),
        (4, 2, true, false),
        (8, 7, true, true),
        (3, 0, true, true),
        (8, 8, true, true),
        (8, 5, true, false),
    ];
    let mut pos = 100usize;
    let mut round = 0usize;
    while pos + 9 < n_blocks * BLOCK_T {
        let (k, bad, verify, apply_first) = rounds[round % rounds.len()];
        round += 1;
        if !verify {
            m.decode(pos, truth(pos));
            pos += 1;
            m.check_from((pos / BLOCK_T).saturating_sub(1), pos, "decode");
            continue;
        }
        // a sparse verify step brings the far blocks up first, like decode
        m.catch_up(pos);
        let before: Vec<Vec<u8>> = (pos..pos + 1 + k).map(|p| m.row_snapshot(p)).collect();
        let mut toks = vec![truth(pos)];
        toks.extend((1..=k).map(|j| if j - 1 < bad { truth(pos + j) } else { truth(pos + j) ^ 0x5a5a }));
        let staged = m.span(pos, &toks);
        let n_keep = 1 + bad.min(k);
        let rollback = |m: &mut Model| {
            // rollback_verify: rejected rows back to their pre-verify bytes, their blocks marked dirty
            for p in pos + n_keep..pos + 1 + k {
                let blk = p / BLOCK_T;
                let snap = &before[p - pos];
                let rb = m.row_bytes();
                let s = m.slots[blk];
                let ib = p % BLOCK_T;
                let bytes = m.pools.full.slot_bytes_mut(s).unwrap();
                let head = BLOCK_T * rb;
                for pass in 0..crate::blocks::FULL_PASSES * 2 * NKV {
                    let off = pass * head + ib * rb;
                    bytes[off..off + rb].copy_from_slice(&snap[off..off + rb]);
                }
                m.pools.full.mark_slot_sketch_dirty(s);
            }
        };
        if apply_first {
            m.apply(&staged);
            rollback(&mut m);
        } else {
            rollback(&mut m);
            m.apply(&staged);
        }
        pos += n_keep;
        m.check_from((pos / BLOCK_T).saturating_sub(1), pos, &format!("verify round {round} (k {k}, keep {n_keep})"));
    }
    // the next step catches every finished block up: all of them are then the recompute of 64 final rows
    m.catch_up(pos);
    for blk in 0..pos / BLOCK_T {
        assert_eq!(usize::from(m.valid(blk)), BLOCK_T);
    }
    m.check(pos, "final catch-up");
}

// ---------------------------------------------------------------------------------------------------------------
// 3. The verify-row combine against the decode combine

fn combine_gpu(defines: &str) -> Gpu {
    let src = format!("{defines}{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    Gpu::new(&src, &["k_attn_combine_dec", "k_attn_combine_sparse_rows"])
}

#[test]
#[ignore = "requires a Metal GPU"]
fn verify_row_combine_matches_the_decode_combine_bit_for_bit() {
    use objc2_metal::{MTLBuffer, MTLCommandBuffer};
    let mut seed = 0x9e37_79b9_7f4a_7c15u64;
    let mut rnd = move || {
        seed ^= seed << 13;
        seed ^= seed >> 7;
        seed ^= seed << 17;
        seed
    };
    for (mode, defines, slot) in [("fp16", "", 0u32), ("kv4", "#define KV4 1\n#define KV4_DC_OFF 0u\n", 5)] {
        let gpu = combine_gpu(defines);
        let nsplits = [1usize, 2, 7, 32, 17, 5];
        let n = nsplits.len();
        let row = NH * HD;
        let part_floats: Vec<usize> = nsplits.iter().map(|&s| NH * s * (HD + 2)).collect();
        let desc_off = 0usize;
        let desc_floats = n * std::mem::size_of::<DecodeSpanDesc>() / 4;
        let part0 = desc_floats.div_ceil(64) * 64;
        let gate_off = part0 + part_floats.iter().sum::<usize>();
        let out_off = gate_off + n * row;
        let total = out_off + n * row + 64;
        for hout in 0..4u32 {
            let mut a = vec![0u32; total];
            let mut descs = vec![DecodeSpanDesc::default(); n];
            let mut tasks = vec![SparseDecTask::default(); n];
            let mut at = part0;
            for i in 0..n {
                descs[i].part_off = at as u32;
                descs[i].full_nsplit = nsplits[i] as u32;
                tasks[i].part_off = at as u32;
                tasks[i].nsplit = nsplits[i] as u32;
                tasks[i].pos = (7000 + i) as u32;
                for (j, w) in a[at..at + part_floats[i]].iter_mut().enumerate() {
                    let r = (rnd() >> 11) as f64 / (1u64 << 53) as f64;
                    let v = match j % (HD + 2) {
                        0 => (r * 12.0 - 4.0) as f32,
                        1 => (r * 30.0 + 0.01) as f32,
                        _ => (r * 2.0 - 1.0) as f32,
                    };
                    *w = v.to_bits();
                }
                at += part_floats[i];
            }
            for w in a[gate_off..gate_off + n * row].iter_mut() {
                let r = ((rnd() >> 11) as f64 / (1u64 << 53) as f64 * 8.0 - 4.0) as f32;
                *w = if hout & 2 != 0 {
                    let h = crate::blocks::f32_to_f16_bits(r) as u32;
                    h | (h << 16)
                } else {
                    r.to_bits()
                };
            }
            unsafe {
                std::ptr::copy_nonoverlapping(descs.as_ptr() as *const u32, a.as_mut_ptr().add(desc_off), desc_floats);
            }
            let run = |kernel: &str| -> Vec<u32> {
                let abuf = gpu.buffer_with(unsafe { std::slice::from_raw_parts(a.as_ptr() as *const u8, a.len() * 4) });
                let tbuf = gpu.buffer_with(unsafe {
                    std::slice::from_raw_parts(tasks.as_ptr() as *const u8, n * std::mem::size_of::<SparseDecTask>())
                });
                let cb = gpu.cmd();
                let e = Enc::new(&cb);
                e.pso(&gpu.pso(kernel));
                e.buf(&abuf, 0, 2);
                e.buf(&tbuf, 0, 14);
                if kernel == "k_attn_combine_dec" {
                    let ca = CombineDecArgs {
                        desc_off: desc_off as u32,
                        gate_off: gate_off as u32,
                        out_off: out_off as u32,
                        swa: 0,
                        hout,
                        pad: [slot, 0, 0],
                    };
                    e.bytes(&ca, 5);
                } else {
                    let ca = CombineSparseRowsArgs {
                        tasks_u32_off: 0,
                        n_tasks: n as u32,
                        pos0: 7000,
                        gate_off: gate_off as u32,
                        out_off: out_off as u32,
                        hout,
                        pad0: slot,
                        pad1: 0,
                    };
                    e.bytes(&ca, 5);
                }
                e.dispatch((NH, n, 1), 128);
                e.end();
                cb.commit();
                cb.waitUntilCompleted();
                Engine::assert_cmd_ok(&cb, kernel);
                let p = abuf.contents().as_ptr() as *const u32;
                unsafe { std::slice::from_raw_parts(p.add(out_off), n * row).to_vec() }
            };
            let want = run("k_attn_combine_dec");
            let got = run("k_attn_combine_sparse_rows");
            assert!(want.iter().any(|&w| w != 0), "{mode} hout {hout}: the decode combine wrote nothing");
            let differ = want.iter().zip(&got).filter(|(a, b)| a != b).count();
            assert_eq!(differ, 0, "{mode} hout {hout}: {differ} output words differ from k_attn_combine_dec");
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------
// 4. The controller-down GEMM of a verify step

/// `ctrl_b` on a verify step: the down projection (BF16 weights in the parameter buffer, 64 rows, `2 * E` inputs)
/// of `t` rows now takes `gemm_h_dec`'s decode-sized kernel instead of `gemm_h`'s. Each output row of both is that
/// row's dot products alone, so the swap must not move a bit: checked for every `t` a verify step can have.
#[test]
#[ignore = "requires Apple M5 Metal 4 GPU"]
fn verify_controller_down_gemm_decode_sized_matches_prefill_bit_for_bit() {
    use objc2_metal::{MTLBuffer, MTLCommandBuffer, MTLDevice};
    let dev = objc2_metal::MTLCreateSystemDefaultDevice().expect("Metal device required");
    if !dev.name().to_string().contains("M5") {
        eprintln!("skipping the M5 tensor GEMM parity test on `{}`", dev.name());
        return;
    }
    let dec_kernel = gemm_dec_sg4_kernel(T_BF16, true);
    let src = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    let gpu = Gpu::new_with_lang(&src, &["k_gemm_sg4", "k_gemm_sg8", "k_gemm_dec_sg8", dec_kernel], true);
    let (rows, k) = (64usize, 2 * E);
    let mut seed = 0x2545_f491_4f6c_dd1du64;
    let mut rnd = move || {
        seed ^= seed << 13;
        seed ^= seed >> 7;
        seed ^= seed << 17;
        seed
    };
    let w: Vec<u8> = (0..rows * k)
        .flat_map(|_| (0x3dc0u16.wrapping_add((rnd() & 0x3f) as u16) | (((rnd() >> 8) as u16 & 1) << 15)).to_le_bytes())
        .collect();
    let wbuf = gpu.buffer_with(&w);
    for t in [1usize, 2, 4, 5, 9, 17, 33, 64, 65, 100, 128] {
        for hout in [0u32, 1] {
            let x_words = (t * k).div_ceil(2);
            let n_out = if hout != 0 { (t * rows).div_ceil(2) } else { t * rows };
            let mut arena = vec![0u32; x_words + n_out + 64];
            for v in arena.iter_mut().take(x_words) {
                *v = (0x3400u32 | (rnd() as u32 & 0x3ff)) | ((0x3400u32 | ((rnd() >> 16) as u32 & 0x3ff)) << 16);
            }
            let run = |kernel: &str, tile_rows: usize, grid_x: usize, tg: usize| -> Vec<u32> {
                let abuf = gpu
                    .buffer_with(unsafe { std::slice::from_raw_parts(arena.as_ptr() as *const u8, arena.len() * 4) });
                let mut ga = GemmHArgs { nseg: 1, t: t as u32, ..Default::default() };
                ga.seg[0] = HSeg {
                    w_lo: 0,
                    w_hi: 0,
                    row_bytes: (k * 2) as u32,
                    wtype: T_BF16,
                    nrows: rows as u32,
                    k: k as u32,
                    xh_off: 0,
                    out_off: x_words as u32,
                    ldo: rows as u32,
                    wsrc: 1,
                    hout,
                    tile_start: 0,
                };
                let cb = gpu.cmd();
                let e = Enc::new(&cb);
                e.pso(&gpu.pso(kernel));
                e.buf(&wbuf, 0, 0);
                e.buf(&wbuf, 0, 1);
                e.buf(&abuf, 0, 2);
                e.bytes(&ga, 5);
                e.dispatch((grid_x, rows.div_ceil(tile_rows), 1), tg);
                e.end();
                cb.commit();
                cb.waitUntilCompleted();
                Engine::assert_cmd_ok(&cb, kernel);
                let p = abuf.contents().as_ptr() as *const u32;
                unsafe { std::slice::from_raw_parts(p.add(x_words), n_out).to_vec() }
            };
            // gemm_h (what a verify step ran) and gemm_h_dec (what it runs now)
            let want = if t > 64 { run("k_gemm_sg8", 64, t.div_ceil(128), 256) } else { run("k_gemm_sg4", 64, 1, 128) };
            let got =
                if t > 64 { run("k_gemm_dec_sg8", 16, t.div_ceil(128), 256) } else { run(dec_kernel, 16, 1, 128) };
            assert!(got == want, "controller-down t={t} hout={hout}: decode-sized GEMM differs from the prefill GEMM");
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------
// 5. The model

/// One finished block's sketch on the GPU against the CPU recompute from its rows.
fn sketch_matches(gpu_sketch: &[u8], slot_kv: &[u8], kvb: u32) -> bool {
    let mut want = vec![0u8; FULL_SKETCH_BYTES];
    compute_full_slot_wht2_sketch_cpu(slot_kv, kvb, BLOCK_T, &mut want);
    gpu_sketch == want.as_slice()
}

/// Greedy speculative generation with `--sparse-topk` active on every verify row, on a Layer 2 and a Layer 3 lane,
/// against non-speculative sparse decode (`encode_decode`) of the same lane kind: drafts are the decode's own
/// tokens, corrupted at a different index each round, so rounds accept all, some and none. Under the crosspath
/// arithmetic (`--exact`: prefill attention on the decode kernels) a verify row must be the decode row: the same
/// emitted tokens and the same logits bits. Every finished block's sketch must equal the CPU recompute.
#[test]
#[ignore = "loads full Inkling-2-Mini GGUF on M5 GPU; run in nightly M5 qualification"]
fn sparse_verify_is_lossless_against_sparse_decode_and_keeps_sketches_exact_on_m5() {
    use crate::scheduler::logit_hash;
    use crate::verify::{verify_step, PagedVerifyLane, VerifyIn};
    use objc2_metal::{MTLBuffer, MTLDevice};
    let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    std::env::set_var("INK_NO_WARM", "1");
    let m5 = objc2_metal::MTLCreateSystemDefaultDevice().is_some_and(|d| d.name().to_string().contains("M5"));
    let mut failures: Vec<String> = Vec::new();
    // The two crosspath configurations: FP16 `--exact`, and KV4 with prefill attention off the tensor cores
    // (`ArithKnobs::CROSSPATH_KV4`, `INK_NO_TC_ATTN=1`), the serve default's cache format.
    for (mode, exact) in [(crate::blocks::KvMode::Fp16, true), (crate::blocks::KvMode::Kv4, false)] {
        let _mode = crate::engine::ExactScope::set(exact);
        if exact {
            std::env::remove_var("INK_NO_TC_ATTN");
        } else {
            std::env::set_var("INK_NO_TC_ATTN", "1");
        }
        let ctx = 4096usize;
        let eng = Engine::prepare_model(&model, ctx, LaneStore::Contiguous)
            .expect("prepare Inkling-2-Mini")
            .into_engine_mode(mode, 1024)
            .expect("load Inkling-2-Mini");
        eng.ensure_batch(1024);
        eng.ensure_dbatch(1);
        eng.set_sparse_anchors(4);
        eng.set_sparse_topk(Some(4));
        let kvb = eng.kv_mode().kvb_tag();
        let tk = crate::tokenizer::Tokenizer::load(&eng.g);
        // Real, varied text (this crate's block-pool source), so the top-k picks matter to the next token.
        let mut prompt = tk.encode("Explain this code.\n", true);
        prompt.extend(tk.encode(include_str!("../blocks.rs"), false));
        prompt.truncate(1700);
        let pf_end = prompt.len() - 1;
        // (4 anchors + 4 top-k + 16 recent) * 64 = 1,536 keys pass through; every row below is past that.
        assert!(!eng.sparse_plan_at(pf_end).passthrough);
        const GEN: usize = 96;
        let argmax = |v: &[f32]| crate::sampler::checked_argmax(v).unwrap();

        for paged in [false, true] {
            let layer = format!("{mode:?} {}", if paged { "Layer 3" } else { "Layer 2" });
            // A lane of the kind, its prompt prefilled to `pf_end` (the token at `pf_end` not yet run).
            let new_lane = || -> (Option<PagedVerifyLane<'_>>, Option<Lane>) {
                if paged {
                    let mut pl = PagedVerifyLane::new(&eng, ctx);
                    eng.on(&pl.lane).set_tokens(0, &prompt);
                    let _ = pl.ensure_span_blocks(0, pf_end);
                    let mut p = 0;
                    while p < pf_end {
                        let c = (pf_end - p).min(1024);
                        let cb = eng.gpu.cmd();
                        eng.encode_spans(&cb, &[Span { lane: &pl.lane, p0: p, t: c }], false, false);
                        cb.commit();
                        eng.wait_step(&cb, "prefill", p).unwrap();
                        p += c;
                    }
                    set_paged_lengths(&eng, &pl.lane, pf_end);
                    pl.written = pf_end;
                    pl.prune_expired_window(pf_end);
                    (Some(pl), None)
                } else {
                    let lane = Lane::new(&eng);
                    eng.on(&lane).reserve(ctx, false);
                    eng.on(&lane).set_tokens(0, &prompt);
                    let mut p = 0;
                    while p < pf_end {
                        let c = (pf_end - p).min(1024);
                        let cb = eng.gpu.cmd();
                        eng.encode_spans(&cb, &[Span { lane: &lane, p0: p, t: c }], false, false);
                        cb.commit();
                        eng.wait_step(&cb, "prefill", p).unwrap();
                        p += c;
                    }
                    (None, Some(lane))
                }
            };

            // Reference: non-speculative sparse decode, one token a step.
            let (ref_pl, ref_l2) = new_lane();
            let ref_lane: &Lane = ref_pl.as_ref().map(|p| &p.lane).or(ref_l2.as_ref()).unwrap();
            let mut ref_tok = vec![0u32; pf_end + GEN + 2];
            let mut ref_hash = vec![0u64; pf_end + GEN + 2];
            let mut ref_logits: Vec<Vec<f32>> = vec![Vec::new(); pf_end + GEN + 2];
            ref_tok[pf_end] = prompt[pf_end];
            for pos in pf_end..pf_end + GEN + 1 {
                if paged {
                    let _ = ref_pl.as_ref().unwrap().ensure_span_blocks(pos, 1);
                }
                let cb = eng.gpu.cmd();
                eng.encode_decode(&cb, &[Span { lane: ref_lane, p0: pos, t: 1 }], true, false);
                cb.commit();
                eng.wait_step(&cb, "decode", pos).unwrap();
                if paged {
                    set_paged_lengths(&eng, ref_lane, pos + 1);
                }
                let lg = eng.span_logits(0).to_vec();
                ref_hash[pos] = logit_hash(&lg);
                ref_logits[pos] = lg.clone();
                ref_tok[pos + 1] = argmax(&lg);
                eng.on(ref_lane).set_tokens(pos + 1, &[ref_tok[pos + 1]]);
            }

            // Speculative: drafts from the reference, corrupted at a moving index.
            let (mut spec_pl, spec_l2) = new_lane();
            fn lane_of<'a>(pl: &'a Option<PagedVerifyLane<'_>>, l2: &'a Option<Lane>) -> &'a Lane {
                pl.as_ref().map(|p| &p.lane).or(l2.as_ref()).unwrap()
            }
            let mut p0 = pf_end;
            let mut cs_before = eng.on(lane_of(&spec_pl, &spec_l2)).get_cs();
            let (mut rounds, mut accepted_all, mut rejected_first, mut emitted_n, mut hash_diff, mut tok_diff) =
                (0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
            let mut max_dlogit = 0.0f32;
            while p0 < pf_end + GEN - 9 {
                let k = [4usize, 8, 3, 8, 1, 6][rounds % 6];
                let bad = [k, 0, 1, k, 0, 4, 2, k][rounds % 8];
                let drafts: Vec<u32> = (0..k)
                    .map(|j| if j < bad { ref_tok[p0 + 1 + j] } else { (ref_tok[p0 + 1 + j] + 1) % eng.n_vocab as u32 })
                    .collect();
                let (pre_written, allocated) = match &spec_pl {
                    Some(pl) => (pl.written, pl.ensure_span_blocks(p0, 1 + k)),
                    None => (0, Vec::new()),
                };
                let kept = verify_step(
                    &eng,
                    &[VerifyIn {
                        lane: lane_of(&spec_pl, &spec_l2),
                        p0,
                        cs_before: &cs_before,
                        drafts: &drafts,
                        ban: None,
                    }],
                    &[],
                )
                .pop()
                .unwrap()
                .transpose()
                .expect("verify")
                .expect("verify ran");
                assert_eq!(kept.k, k, "{layer}: the planner clamped k");
                if let Some(pl) = spec_pl.as_mut() {
                    pl.finish_verify_rollback(&allocated, pre_written, p0 + kept.n_keep);
                }
                for (i, (&tok, &h)) in kept.emitted.iter().zip(&kept.hashes).enumerate() {
                    tok_diff += usize::from(tok != ref_tok[p0 + 1 + i]);
                    hash_diff += usize::from(h != ref_hash[p0 + i]);
                    // the verify rows are still in `b.lg` (rollback does not touch them)
                    let row = eng.span_logits(i);
                    let d = row.iter().zip(&ref_logits[p0 + i]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
                    max_dlogit = max_dlogit.max(d);
                }
                accepted_all += usize::from(kept.n_keep == 1 + k);
                rejected_first += usize::from(kept.n_keep == 1);
                emitted_n += kept.emitted.len();
                rounds += 1;
                let next = p0 + kept.n_keep;
                let spec_lane = lane_of(&spec_pl, &spec_l2);
                eng.on(spec_lane).set_tokens(next, &[kept.bonus.expect("bonus")]);
                cs_before = eng.on(spec_lane).get_cs();
                p0 = next;
            }
            eprintln!(
            "[sparse_verify {layer}] {rounds} rounds, {emitted_n} tokens, {accepted_all} all accepted, {rejected_first} first rejected; \
             {tok_diff} tokens and {hash_diff} logit rows differ from sparse decode, largest logit difference {max_dlogit:.3e}"
        );
            assert!(
                accepted_all > 0 && rejected_first > 0,
                "{layer}: rounds must both accept all and reject the first"
            );
            // Off the M5 (no `hgemm`), a decode step attends to its own row from the float32 `kv_cur` and a verify row
            // from the cache, so only the M5 is held to the bits (and the tokens they make).
            if m5 && tok_diff != 0 {
                failures.push(format!("{layer}: {tok_diff} emitted tokens differ from sparse decode"));
            }
            if m5 && hash_diff != 0 {
                failures
                    .push(format!("{layer}: {hash_diff} verify logit rows differ in bits from the sparse decode rows"));
            }

            // Every block finished by the end, on both lanes, equals the CPU recompute from its rows.
            let spec_lane = lane_of(&spec_pl, &spec_l2);
            for (who, lane, end) in [("decode", ref_lane, pf_end + GEN + 1), ("verify", spec_lane, p0)] {
                let mut bad_blocks = Vec::new();
                for blk in 0..end / BLOCK_T {
                    let ok = if paged {
                        let tbl = lane.block_table.borrow();
                        let pools = eng.block_pool.borrow();
                        let e = tbl.get(BlockKind::Full, BlockIndex::new(blk as u32)).unwrap().unwrap();
                        sketch_matches(
                            pools.full.slot_sketch_bytes(e.slot()).unwrap(),
                            pools.full.slot_bytes(e.slot()).unwrap(),
                            kvb,
                        )
                    } else {
                        let mut page = vec![0u8; crate::blocks::FULL_PASSES * 2 * NKV * BLOCK_T * eng.kv_row_bytes];
                        eng.on(lane).extract_full_page_into(blk * BLOCK_T, BLOCK_T, &mut page);
                        let sk = lane.full_sketch.borrow();
                        let sk = sk.as_ref().expect("Layer 2 sketch");
                        let all =
                            unsafe { std::slice::from_raw_parts(sk.contents().as_ptr() as *const u8, sk.length()) };
                        sketch_matches(&all[blk * FULL_SKETCH_BYTES..(blk + 1) * FULL_SKETCH_BYTES], &page, kvb)
                    };
                    if !ok {
                        bad_blocks.push(blk);
                    }
                }
                if !bad_blocks.is_empty() {
                    failures
                        .push(format!("{layer} {who}: finished blocks {bad_blocks:?} differ from the CPU recompute"));
                }
            }
            if let Some(pl) = spec_pl {
                pl.release();
            }
            if let Some(pl) = ref_pl {
                pl.release();
            }
        }
    }
    std::env::remove_var("INK_NO_TC_ATTN");
    assert!(failures.is_empty(), "{failures:#?}");
}

/// Record that every `Full` and `Window` block of a Layer 3 lane holds its rows below `end`.
fn set_paged_lengths(eng: &Engine, lane: &Lane, end: usize) {
    let tbl = lane.block_table.borrow();
    let mut pools = eng.block_pool.borrow_mut();
    for b in 0..end.div_ceil(BLOCK_T) {
        let bi = BlockIndex::new(b as u32);
        let len = (end - b * BLOCK_T).min(BLOCK_T) as u32;
        for kind in [BlockKind::Full, BlockKind::Window] {
            if let Some(e) = tbl.get(kind, bi).ok().flatten() {
                let rec = pools.of_mut(kind).record_mut(e.slot()).unwrap();
                if rec.length() < len {
                    rec.set_length(len).unwrap();
                }
            }
        }
    }
}

/// A verify row's arithmetic does not depend on the rows beside it: greedy generation by 1-row verify steps and the
/// same tokens re-verified 8 rows a step (chunks, task offsets, split partials and selected-block lists shared by
/// the rows of one step) give the same logits bits, past the sparse activation, in FP16 (`--exact`), KV8 and KV4
/// (the serve default). Both lanes start from one prefill (`copy_lane`), so the tensor-core prefill attention of the
/// default modes, which need not repeat its bits run to run, cannot tell them apart. Holds on any Metal GPU.
#[test]
#[ignore = "loads full Inkling-2-Mini GGUF on a Metal GPU"]
fn sparse_verify_rows_are_bit_identical_however_many_share_a_step() {
    let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    std::env::set_var("INK_NO_WARM", "1");
    const N: usize = 48;
    let mut failures = Vec::new();
    for mode in [crate::blocks::KvMode::Fp16, crate::blocks::KvMode::Kv8, crate::blocks::KvMode::Kv4] {
        let _exact = crate::engine::ExactScope::set(mode == crate::blocks::KvMode::Fp16);
        let ctx = 4096usize;
        let eng =
            Engine::prepare_model(&model, ctx, LaneStore::Contiguous).unwrap().into_engine_mode(mode, 1024).unwrap();
        eng.ensure_batch(1024);
        eng.set_sparse_anchors(4);
        eng.set_sparse_topk(Some(4));
        let tk = crate::tokenizer::Tokenizer::load(&eng.g);
        let mut prompt = tk.encode("Explain this code.\n", true);
        prompt.extend(tk.encode(include_str!("../blocks.rs"), false));
        prompt.truncate(1700);
        let pf_end = prompt.len() - 1;
        assert!(!eng.sparse_plan_at(pf_end).passthrough);
        let new_lane = || {
            let lane = Lane::new(&eng);
            eng.on(&lane).reserve(ctx, false);
            eng.on(&lane).set_tokens(0, &prompt);
            lane
        };
        let src = new_lane();
        for (p, t) in [(0usize, 1024usize), (1024, pf_end - 1024)] {
            let cb = eng.gpu.cmd();
            eng.encode_spans(&cb, &[Span { lane: &src, p0: p, t }], false, false);
            cb.commit();
            eng.wait_step(&cb, "prefill", p).unwrap();
        }
        let (a, b) = (new_lane(), new_lane());
        eng.copy_lane(&src, &a);
        eng.copy_lane(&src, &b);
        let mut toks = vec![prompt[pf_end]];
        let mut chain = Vec::new();
        for pos in pf_end..pf_end + N {
            let cb = eng.gpu.cmd();
            eng.encode_verify(&cb, &[Span { lane: &a, p0: pos, t: 1 }], 0);
            cb.commit();
            eng.wait_step(&cb, "verify 1", pos).unwrap();
            let lg = eng.span_logits(0).to_vec();
            eng.rollback_verify(&a, 0, 1);
            let t = crate::sampler::checked_argmax(&lg).unwrap();
            eng.on(&a).set_tokens(pos + 1, &[t]);
            toks.push(t);
            chain.push(lg);
        }
        let mut differ = Vec::new();
        for p0 in (pf_end..pf_end + N).step_by(8) {
            eng.on(&b).set_tokens(p0, &toks[p0 - pf_end..p0 - pf_end + 8]);
            let cb = eng.gpu.cmd();
            eng.encode_verify(&cb, &[Span { lane: &b, p0, t: 8 }], 7);
            cb.commit();
            eng.wait_step(&cb, "verify 8", p0).unwrap();
            for r in 0..8 {
                if *eng.span_logits(r) != *chain[p0 - pf_end + r] {
                    differ.push(p0 + r);
                }
            }
            eng.rollback_verify(&b, 0, 8);
        }
        eprintln!("[sparse_verify_invariance {mode:?}] {} of {N} rows differ", differ.len());
        if !differ.is_empty() {
            failures.push(format!("{mode:?}: 8-row verify rows differ from 1-row verify rows at {differ:?}"));
        }
    }
    assert!(failures.is_empty(), "{failures:#?}");
}