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
//! Sparse prefill (`INK_SPARSE_PREFILL`) on a GPU, with no model file: the masked tensor-core prefill attention
//! (`k_attn_tc_fixed_blk` with `sel_words != 0`) and the selection pipeline (`k_sparse_pf_prep`, the sparse-decode
//! scorers, `k_sparse_pf_mask`). Like the rest of `kv8_tc_tests` these need Metal 4 and MetalPerformancePrimitives
//! (an M3 Ultra runs them on its ALUs); they read no clock, open no socket and write no file.

use super::*;
use crate::engine::sparse_prefill::{SparsePfMaskArgs, SparsePfPrepArgs};

/// the pass the tests point the kernels at (a slot holds `FULL_PASSES` passes, as the pool's does)
const PASS: u32 = 3;

/// FP16, KV8 and KV4 builds of the kernels: (name, defines, row bytes)
const FORMATS: [(&str, &str, usize); 3] = [
    ("fp16", "", 2 * HD),
    ("kv8", "#define KV8 1\n", HD),
    ("kv4", "#define KV4 1\n#define KV4_DC_OFF 256u\n", crate::blocks::KV4_ROW_BYTES as usize),
];

fn gpu_for(defines: &str, kernels: &[&str]) -> Gpu {
    Gpu::new(&format!("{defines}{}\n{}", include_str!("../../kernels.metal"), include_str!("../../prefill.metal")), kernels)
}

/// A full lane's cache in one slab of pool slots, `FULL_PASSES` passes per slot, block `b` in slot
/// `n_blks - 1 - b` (no two neighbouring blocks neighbours in memory).
struct Slab {
    buf: Buf,
    bt: Buf,
    n_blks: usize,
    row_b: usize,
}

impl Slab {
    fn pass_bytes(row_b: usize) -> usize {
        2 * NKV * BLOCK * row_b
    }
    fn new(gpu: &Gpu, n: usize, row_b: usize, mut fill: impl FnMut(usize, usize, usize, &mut [u8])) -> Slab {
        let n_blks = n.div_ceil(BLOCK);
        let slot_bytes = crate::blocks::FULL_PASSES * Slab::pass_bytes(row_b);
        let buf = gpu.buffer(n_blks * slot_bytes);
        let bt = gpu.buffer(n_blks * 8);
        unsafe {
            let table = std::slice::from_raw_parts_mut(bt.contents().as_ptr().cast::<u64>(), n_blks);
            let bytes = std::slice::from_raw_parts_mut(buf.contents().as_ptr().cast::<u8>(), n_blks * slot_bytes);
            for b in 0..n_blks {
                let slot = n_blks - 1 - b;
                table[b] = (slot * slot_bytes) as u64;
                let base = slot * slot_bytes + PASS as usize * Slab::pass_bytes(row_b);
                for plane in 0..2 {
                    for g in 0..NKV {
                        for ib in 0..BLOCK {
                            let at = base + ((plane * NKV + g) * BLOCK + ib) * row_b;
                            if b * BLOCK + ib < n {
                                fill(plane, g, b * BLOCK + ib, &mut bytes[at..at + row_b]);
                            }
                        }
                    }
                }
            }
        }
        Slab { buf, bt, n_blks, row_b }
    }
    fn bind(&self, e: &Enc) {
        e.buf(&self.buf, 0, 3);
        e.buf(&self.bt, 0, 8);
        for i in [10, 11, 12] {
            e.buf(&self.buf, 0, i);
        }
    }
    /// FP16 only: the value of row `pos` of `plane`, head `g`
    fn fp16(&self, plane: usize, g: usize, pos: usize) -> Vec<f64> {
        assert_eq!(self.row_b, 2 * HD);
        let slot_bytes = crate::blocks::FULL_PASSES * Slab::pass_bytes(self.row_b);
        let (b, ib) = (pos / BLOCK, pos % BLOCK);
        let at = (self.n_blks - 1 - b) * slot_bytes
            + PASS as usize * Slab::pass_bytes(self.row_b)
            + ((plane * NKV + g) * BLOCK + ib) * self.row_b;
        assert!(at + self.row_b <= self.buf.length());
        let bytes = unsafe { std::slice::from_raw_parts(self.buf.contents().as_ptr().cast::<u8>().add(at), self.row_b) };
        bytes.chunks(2).map(|h| f64::from(f16_bits_to_f32(u16::from_le_bytes([h[0], h[1]])))).collect()
    }
}

/// The activation arena of one batch: half queries, relative features, sinks, then `parts` partial regions.
struct Act {
    buf: Buf,
    case: Case,
    nsplit: usize,
    q_words: usize,
    r_off: usize,
    sink_off: usize,
    part_words: usize,
}

impl Act {
    fn new(gpu: &Gpu, case: Case, parts: usize, q: impl Fn(usize, usize, usize) -> f32, rng: &mut Rng) -> Act {
        let nsplit = case.nsplit();
        let q_words = case.nrows * NH * HD / 2;
        let (r_off, sink_off) = (q_words, q_words + case.nrows * NH * NREL);
        let part0 = sink_off + case.nrows * NH;
        let part_words = case.nrows * NH * nsplit * (HD + 2);
        let buf = gpu.buffer((part0 + parts * part_words) * 4);
        unsafe {
            let a = std::slice::from_raw_parts_mut(buf.contents().as_ptr().cast::<u32>(), part0 + parts * part_words);
            let qh = std::slice::from_raw_parts_mut(buf.contents().as_ptr().cast::<u16>(), 2 * q_words);
            for row in 0..case.nrows {
                for h in 0..NH {
                    for d in 0..HD {
                        qh[(row * NH + h) * HD + d] = f32_to_f16_bits(q(row, h, d));
                    }
                }
            }
            a[r_off..sink_off].iter_mut().for_each(|w| *w = (rng.unit() * 0.5).to_bits());
            a[sink_off..part0].iter_mut().for_each(|w| *w = (rng.unit() * 0.7).to_bits());
            a[part0..].fill(UNWRITTEN);
        }
        Act { buf, case, nsplit, q_words, r_off, sink_off, part_words }
    }
    fn part_off(&self, part: usize) -> usize {
        self.sink_off + self.case.nrows * NH + part * self.part_words
    }
    fn part(&self, part: usize) -> &[f32] {
        unsafe { std::slice::from_raw_parts(self.buf.contents().as_ptr().cast::<f32>().add(self.part_off(part)), self.part_words) }
    }
    fn q(&self, row: usize, h: usize) -> Vec<f64> {
        let qh = unsafe { std::slice::from_raw_parts(self.buf.contents().as_ptr().cast::<u16>(), 2 * self.q_words) };
        qh[(row * NH + h) * HD..][..HD].iter().map(|&b| f64::from(f16_bits_to_f32(b))).collect()
    }
    fn word(&self, i: usize) -> f32 {
        unsafe { *self.buf.contents().as_ptr().cast::<f32>().add(i) }
    }
    fn args(&self, part: usize, sel: Option<(usize, usize)>) -> PreparedAttnArgs {
        PreparedAttnArgs {
            pos0: self.case.pos0 as u32,
            window: 0,
            cap: 0,
            idx0: 0,
            k_base: PASS,
            v_base: 0,
            q_off: 0,
            r_off: self.r_off as u32,
            sink_off: self.sink_off as u32,
            gate_off: 0,
            out_off: 0,
            relbias_w: RELB_AT as u32,
            part_off: self.part_off(part) as u32,
            kps: self.case.kps() as u32,
            nsplit: self.nsplit as u32,
            half_io: 1,
            ring: 0,
            full_budget: 0,
            kv4_slot: 0,
            tg_rows: TC_ATT_TG_ROWS as u32,
            nrows: self.case.nrows as u32,
            pad: sel.map_or([0; 3], |(w, qb0)| [w as u32, qb0 as u32, 0]),
        }
    }
}

/// `k_attn_tc_fixed_blk` into partial region `part`: dense (`masks = None`) or with `(buffer, word offset,
/// sel_words, qb0)` masks bound at 14, on the grid the engine dispatches for the format.
fn attend_tc(gpu: &Gpu, kv4: bool, pb: &Buf, act: &Act, slab: &Slab, part: usize, masks: Option<(&Buf, usize, usize, usize)>) {
    let case = &act.case;
    let (tg_rows, grid_x) = prefill_attn_grid(true, false, case.end(), 0, act.nsplit);
    assert_eq!(tg_rows, TC_ATT_TG_ROWS);
    let args = act.args(part, masks.map(|(_, _, w, qb0)| (w, qb0)));
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(pb, 0, 1);
    e.buf(&act.buf, 0, 2);
    slab.bind(&e);
    if let Some((m, off, _, _)) = masks {
        e.buf(m, off * 4, 14);
    }
    e.bytes(&args, 5);
    e.pso(&gpu.pso("k_attn_tc_fixed_blk"));
    e.dispatch(tc_attn_dispatch_grid(kv4, grid_x, case.nrows, tg_rows), 96);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, "k_attn_tc_fixed_blk (sparse prefill)");
}

/// Masks for the query blocks of `case`, one row of `words` per (query block, KV head), from `keep(qb, g, kb)`.
fn masks_of(gpu: &Gpu, case: &Case, keep: impl Fn(usize, usize, usize) -> bool) -> (Buf, usize, usize) {
    let qb0 = case.pos0 / BLOCK;
    let n_qb = (case.end() - 1) / BLOCK - qb0 + 1;
    let words = case.end().div_ceil(BLOCK).div_ceil(32);
    let mut m = vec![0u32; n_qb * NKV * words];
    for q in 0..n_qb {
        for g in 0..NKV {
            for kb in 0..words * 32 {
                if keep(qb0 + q, g, kb) {
                    m[(q * NKV + g) * words + kb / 32] |= 1 << (kb % 32);
                }
            }
        }
    }
    (gpu.buffer_with(unsafe { std::slice::from_raw_parts(m.as_ptr().cast::<u8>(), m.len() * 4) }), words, qb0)
}

fn random_slab(gpu: &Gpu, n: usize, row_b: usize, rng: &mut Rng) -> Slab {
    Slab::new(gpu, n, row_b, |_, _, _, row| match row.len() {
        r if r == 2 * HD => row.chunks_mut(2).for_each(|h| h.copy_from_slice(&f32_to_f16_bits(rng.unit()).to_le_bytes())),
        r if r == HD => {
            // random bytes under one of 24 realistic scale codes (the KV8 row format)
            row.iter_mut().for_each(|b| *b = rng.next() as u8);
            let code = 88 + (rng.next() % 24) as u32;
            for (i, b) in row[..8].iter_mut().enumerate() {
                *b = (*b & !1) | ((code >> (7 - i)) & 1) as u8;
            }
        }
        _ => {
            row[..64].iter_mut().for_each(|b| *b = rng.next() as u8);
            row[64..].copy_from_slice(&f32_to_f16_bits(0.02 + 0.06 * rng.unit().abs()).to_le_bytes());
        }
    })
}

/// Shapes: unaligned starts, threadgroups straddling two query blocks, rows at block edges, many splits.
const SHAPES: [(usize, usize); 5] = [(250, 17), (1023, 2), (3006, 70), (5000, 40), (8190, 66)];

/// Requirement: with every key block kept the sparse kernel is the dense kernel, bit for bit, in every cache format.
/// Also with only the causal blocks kept (what a query block that keeps everything selects), and with the extra
/// bits past the causal edge set (they must change nothing).
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn sparse_prefill_with_every_block_kept_is_bit_identical_to_dense() {
    let mut rng = Rng::new(0x5ba5_e9f1);
    for (name, defines, row_b) in FORMATS {
        let gpu = gpu_for(defines, &["k_attn_tc_fixed_blk"]);
        let kv4 = name == "kv4";
        for (pos0, nrows) in SHAPES {
            let case = Case::full("sparse", pos0, nrows);
            let relb = random_relbias(&mut rng);
            let pb = relbias_buffer(&gpu, &relb);
            let slab = random_slab(&gpu, case.end(), row_b, &mut rng);
            let mut qr = Rng::new(0x7a + pos0 as u64);
            let qv: Vec<f32> = (0..nrows * NH * HD).map(|_| qr.unit() * 0.25).collect();
            let act = Act::new(&gpu, case, 3, |row, h, d| qv[(row * NH + h) * HD + d], &mut rng);
            attend_tc(&gpu, kv4, &pb, &act, &slab, 0, None);
            let (all, words, qb0) = masks_of(&gpu, &case, |_, _, _| true);
            attend_tc(&gpu, kv4, &pb, &act, &slab, 1, Some((&all, 0, words, qb0)));
            let (causal, words, qb0) = masks_of(&gpu, &case, |qb, _, kb| kb <= qb);
            attend_tc(&gpu, kv4, &pb, &act, &slab, 2, Some((&causal, 0, words, qb0)));
            assert_slots_written(name, &case, act.part(0), act.nsplit);
            for part in [1, 2] {
                let n = differing_values(&case, act.part(0), act.part(part), act.nsplit);
                assert_eq!(n, 0, "{name} {pos0}+{nrows}: {n} partial values differ from dense (mask {part})");
            }
            eprintln!("[sparse-prefill] {name} {pos0}+{nrows}: all-kept and causal-kept masks bit-identical to dense");
        }
    }
}

/// Requirement: off is the kernel as it was. The dense dispatch (`sel_words = 0`, nothing bound at 14) of the
/// engine's build against the build with the sparse path compiled out (`NO_SPARSE_PF`), every cache format: every
/// partial bit-identical.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn sparse_prefill_off_is_bit_identical_to_the_kernel_without_it() {
    let mut rng = Rng::new(0x0ff_5a1e);
    for (name, defines, row_b) in FORMATS {
        let now = gpu_for(defines, &["k_attn_tc_fixed_blk"]);
        let was = gpu_for(&format!("{defines}#define NO_SPARSE_PF 1\n"), &["k_attn_tc_fixed_blk"]);
        let kv4 = name == "kv4";
        for (pos0, nrows) in SHAPES {
            let case = Case::full("off", pos0, nrows);
            let relb = random_relbias(&mut rng);
            let pb = relbias_buffer(&now, &relb);
            let slab = random_slab(&now, case.end(), row_b, &mut rng);
            let mut qr = Rng::new(0x0ff + pos0 as u64);
            let qv: Vec<f32> = (0..nrows * NH * HD).map(|_| qr.unit() * 0.25).collect();
            let act = Act::new(&now, case, 2, |row, h, d| qv[(row * NH + h) * HD + d], &mut rng);
            attend_tc(&was, kv4, &pb, &act, &slab, 0, None);
            attend_tc(&now, kv4, &pb, &act, &slab, 1, None);
            assert_slots_written(name, &case, act.part(1), act.nsplit);
            let n = differing_values(&case, act.part(0), act.part(1), act.nsplit);
            assert_eq!(n, 0, "{name} {pos0}+{nrows}: {n} partial values differ from the kernel without sparse prefill");
        }
        eprintln!("[sparse-prefill] {name}: off path bit-identical to the kernel without sparse prefill");
    }
}

/// Requirement: the row-parallel softmax with its skipped passes (#271) is the per-row softmax, bit for bit, under
/// masks: random per-(query block, KV head) selections leave rows of a threadgroup (on both sides of a query-block
/// boundary) with no visible key in a tile while the other rows see keys, rows that see their first key only in a
/// later tile, and tiles no row sees. Every cache format against its `TC_ATT_EAGER_SOFTMAX` build.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn sparse_prefill_softmax_is_bit_identical_to_the_per_row_softmax() {
    let mut rng = Rng::new(0x50f7_0271);
    for (name, defines, row_b) in FORMATS {
        let now = gpu_for(defines, &["k_attn_tc_fixed_blk"]);
        let was = gpu_for(&format!("{defines}{}", super::EAGER_SOFTMAX), &["k_attn_tc_fixed_blk"]);
        let kv4 = name == "kv4";
        for (pos0, nrows) in SHAPES {
            let case = Case::full("softmax", pos0, nrows);
            let relb = random_relbias(&mut rng);
            let pb = relbias_buffer(&now, &relb);
            let slab = random_slab(&now, case.end(), row_b, &mut rng);
            let mut qr = Rng::new(0x271 + pos0 as u64);
            let qv: Vec<f32> = (0..nrows * NH * HD).map(|_| qr.unit() * 0.25).collect();
            let act = Act::new(&now, case, 2, |row, h, d| qv[(row * NH + h) * HD + d], &mut rng);
            // about a third of the blocks, the diagonal block kept only for odd query blocks: a query block whose
            // causal blocks all drop has rows with no visible key at all (their partials stay at the empty state)
            let keep = |qb: usize, g: usize, kb: usize| {
                let x = (qb as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
                    ^ ((g as u64) << 40)
                    ^ (kb as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
                (kb == qb && !qb.is_multiple_of(2)) || (x >> 29).is_multiple_of(3)
            };
            let (m, words, qb0) = masks_of(&now, &case, keep);
            attend_tc(&now, kv4, &pb, &act, &slab, 0, Some((&m, 0, words, qb0)));
            attend_tc(&was, kv4, &pb, &act, &slab, 1, Some((&m, 0, words, qb0)));
            let n = differing_values(&case, act.part(0), act.part(1), act.nsplit);
            assert_eq!(n, 0, "{name} {pos0}+{nrows}: {n} partial values differ from the per-row softmax under masks");
        }
        eprintln!("[sparse-prefill] {name}: masked softmax bit-identical to the per-row softmax");
    }
}

/// The attention output in double precision over the keys `keep(row_pos, g, key_pos)` lets each row see (FP16 cache).
fn reference_kept(act: &Act, slab: &Slab, relb: &[f32], keep: impl Fn(usize, usize, usize) -> bool) -> Vec<f64> {
    let case = &act.case;
    let mut out = vec![0.0f64; case.nrows * NH * HD];
    let k: Vec<Vec<Vec<f64>>> = (0..NKV).map(|g| (0..case.end()).map(|p| slab.fp16(0, g, p)).collect()).collect();
    let v: Vec<Vec<Vec<f64>>> = (0..NKV).map(|g| (0..case.end()).map(|p| slab.fp16(1, g, p)).collect()).collect();
    for row in 0..case.nrows {
        let pos = case.pos0 + row;
        for h in 0..NH {
            let g = h / 3;
            let q = act.q(row, h);
            let r: Vec<f64> = (0..NREL).map(|i| f64::from(act.word(act.r_off + (row * NH + h) * NREL + i))).collect();
            let sink = f64::from(act.word(act.sink_off + row * NH + h));
            let keys: Vec<usize> = (0..=pos).filter(|&kp| keep(pos, g, kp)).collect();
            let scores: Vec<f64> = keys
                .iter()
                .map(|&kp| {
                    let mut s: f64 = q.iter().zip(&k[g][kp]).map(|(a, b)| a * b).sum();
                    if pos - kp < EXT {
                        s += r.iter().zip(&relb[(pos - kp) * NREL..]).map(|(&a, &b)| a * f64::from(b)).sum::<f64>();
                    }
                    s - sink
                })
                .collect();
            let m = scores.iter().fold(0.0f64, |m, &s| m.max(s));
            let mut l = (-m).exp();
            let o = &mut out[(row * NH + h) * HD..][..HD];
            for (&kp, &s) in keys.iter().zip(&scores) {
                let w = (s - m).exp();
                l += w;
                o.iter_mut().zip(&v[g][kp]).for_each(|(o, &x)| *o += w * x);
            }
            o.iter_mut().for_each(|o| *o /= l);
        }
    }
    out
}

/// Requirement: sparse attention is exact attention over the selected keys. Random per-(query block, KV head)
/// masks against a double-precision reference that sees only the kept blocks' keys, within the tolerance of the
/// dense tensor-core kernel's own reference check; and a mask that drops blocks must change the output (control).
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn sparse_prefill_attention_is_exact_over_the_selected_keys() {
    let gpu = gpu_for("", &["k_attn_tc_fixed_blk"]);
    let mut rng = Rng::new(0x55a_0001);
    // the double-precision reference is the cost here: the shapes up to 5,040 keys
    for (pos0, nrows) in SHAPES[..4].iter().copied() {
        let case = Case::full("sparse", pos0, nrows);
        let relb = random_relbias(&mut rng);
        let pb = relbias_buffer(&gpu, &relb);
        let slab = random_slab(&gpu, case.end(), 2 * HD, &mut rng);
        let mut qr = Rng::new(0x9e1 + pos0 as u64);
        let qv: Vec<f32> = (0..nrows * NH * HD).map(|_| qr.unit() * 0.25).collect();
        let act = Act::new(&gpu, case, 2, |row, h, d| qv[(row * NH + h) * HD + d], &mut rng);
        // a seeded hash per (query block, head, key block): about half the blocks, the diagonal block always
        let keep_blk = |qb: usize, g: usize, kb: usize| {
            let x = (qb as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ ((g as u64) << 40) ^ (kb as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            kb == qb || (x >> 29) & 1 == 1
        };
        let (m, words, qb0) = masks_of(&gpu, &case, keep_blk);
        attend_tc(&gpu, false, &pb, &act, &slab, 0, Some((&m, 0, words, qb0)));
        attend_tc(&gpu, false, &pb, &act, &slab, 1, None);
        assert_slots_written("sparse", &case, act.part(0), act.nsplit);
        let got = combine(&case, act.part(0), act.nsplit);
        let want = reference_kept(&act, &slab, &relb, |pos, g, kp| keep_blk(pos / BLOCK, g, kp / BLOCK));
        let (abs, rel) = difference(&got, &want);
        assert!(abs <= MAX_ABS && rel <= MAX_REL, "{pos0}+{nrows}: sparse vs reference over the kept keys {abs:.3e} abs {rel:.3e} rel");
        let dense = combine(&case, act.part(1), act.nsplit);
        let (dabs, _) = difference(&got, &dense);
        if pos0 >= BLOCK {
            assert!(dabs > 1e-3, "{pos0}+{nrows}: dropping blocks must change the output (control): {dabs:.3e}");
        }
        eprintln!("[sparse-prefill] {pos0}+{nrows}: sparse vs kept-key reference {abs:.2e} abs {rel:.2e} rel; vs dense {dabs:.2e}");
    }
}

/// The whole selection pipeline of one pass, as `Engine::encode_sparse_prefill_select` encodes it, then the masked
/// attention. Returns the scratch.
#[allow(clippy::too_many_arguments)]
fn select(
    gpu: &Gpu,
    act: &Act,
    slab: &Slab,
    sketch: &Buf,
    plan: &SparsePrefillPlan,
    anchors: usize,
    cfg: SparsePrefillCfg,
    scorer: &str,
) -> Buf {
    let scr = gpu.buffer(plan.total_u32 * 4);
    let case = &act.case;
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(&act.buf, 0, 2);
    slab.bind(&e);
    e.buf(sketch, 0, 13);
    e.buf(&scr, 0, 14);
    let pa = SparsePfPrepArgs {
        q_pos0: case.pos0 as u32,
        q_rows: case.nrows as u32,
        qp_off: 0,
        sink_off: act.sink_off as u32,
        half_io: 1,
        n_qb: plan.n_qb as u32,
        qb0: plan.qb0 as u32,
        anchors: anchors as u32,
        recent: SPARSE_RECENT_BLOCKS as u32,
        top_k: cfg.top_k as u32,
        min_ctx: cfg.min_ctx as u32,
        qm_off: plan.qm_off as u32,
        sm_off: plan.sm_off as u32,
        sel_stride: plan.sel_stride as u32,
        pad: [0; 2],
    };
    e.bytes(&pa, 5);
    e.pso(&gpu.pso("k_sparse_pf_prep"));
    e.dispatch((plan.n_qb, NH, 1), 128);
    e.barrier();
    e.buf(&scr, 0, 2);
    let sa = ScoreFullSketchArgs {
        pass_idx: PASS,
        slots_per_slab: slab.n_blks as u32,
        n_tasks: plan.n_qb as u32,
        is_paged: 1,
        tasks_u32_off: 0,
        sel_u32_base: plan.sel_off as u32,
        pass_sel_stride: 0,
        pad0: 0,
    };
    e.bytes(&sa, 5);
    e.pso(&gpu.pso(scorer));
    e.dispatch((NKV, plan.n_qb, 1), 256);
    e.barrier();
    let ma = SparsePfMaskArgs {
        n_qb: plan.n_qb as u32,
        sel_u32_base: plan.sel_off as u32,
        mask_off: plan.mask_off as u32,
        sel_words: plan.sel_words as u32,
    };
    e.bytes(&ma, 5);
    e.pso(&gpu.pso("k_sparse_pf_mask"));
    e.dispatch((NKV, plan.n_qb, 1), 256);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, "sparse prefill selection");
    scr
}

/// Requirement: the selection is content-dependent and its geometry is the CPU's. Three "needle" key blocks far from
/// every query block carry the direction every query points in; with top-k 3 each query block must select exactly
/// the anchors, the needles and its 16 recent blocks, in every KV head, through each of the three sparse-decode
/// scorers. The tasks must equal `sparse_prefill_task_cpu` and the summary queries the CPU's float means, bit for
/// bit. Then the masked attention against the kept-key reference.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn sparse_prefill_selection_finds_planted_needles_and_matches_the_cpu_geometry() {
    let kernels = [
        "k_build_full_sketch_blk",
        "k_sparse_pf_prep",
        "k_sparse_pf_mask",
        "k_score_full_sketch_dec_1k",
        "k_score_full_sketch_dec",
        "k_score_full_sketch_dec_wide",
        "k_attn_tc_fixed_blk",
    ];
    let gpu = gpu_for("", &kernels);
    let mut rng = Rng::new(0x5e1e_c7);
    let dir: Vec<f32> = {
        let v: Vec<f32> = (0..HD).map(|_| rng.unit()).collect();
        let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();
        v.iter().map(|x| x / n).collect()
    };
    let needles = [4usize, 11, 19];
    let anchors = 2usize;
    // the last two spans straddle the context floor: their early query blocks keep every causal block, and those
    // lists (up to 40 blocks) are wider than the selecting blocks' budget (2 + 16 + 3 = 21)
    for (pos0, nrows, min_ctx) in [(2304usize, 768usize, 0usize), (2300, 772, 0), (2900, 100, 0), (2304, 768, 2560), (2300, 772, 2600)] {
        let cfg = SparsePrefillCfg { top_k: needles.len(), min_ctx };
        let case = Case::full("needles", pos0, nrows);
        let n = case.end();
        let mut kr = Rng::new(n as u64 ^ 0xabc);
        let slab = Slab::new(&gpu, n, 2 * HD, |plane, _g, pos, row| {
            let needle = plane == 0 && needles.contains(&(pos / BLOCK));
            for (d, h) in row.chunks_mut(2).enumerate() {
                let x = if needle { 4.0 * dir[d] + 0.05 * kr.unit() } else { 0.3 * kr.unit() };
                h.copy_from_slice(&f32_to_f16_bits(x).to_le_bytes());
            }
        });
        let mut qr = Rng::new(0x51 + pos0 as u64);
        let qv: Vec<f32> = (0..nrows * NH * HD).map(|i| 4.0 * dir[i % HD] + 0.1 * qr.unit()).collect();
        let act = Act::new(&gpu, case, 1, |row, h, d| qv[(row * NH + h) * HD + d], &mut rng);
        let relb = random_relbias(&mut rng);
        let pb = relbias_buffer(&gpu, &relb);
        // the sketches of every block of the pass, by the prefill sketch builder
        let sketch = gpu.buffer(slab.n_blks * crate::blocks::FULL_SKETCH_BYTES);
        {
            let cb = gpu.cmd();
            let e = Enc::new(&cb);
            slab.bind(&e);
            e.buf(&sketch, 0, 13);
            let ba = BuildSketchBlkArgs { pass_idx: PASS, slots_per_slab: slab.n_blks as u32, lo_blk: 0, n_blks: slab.n_blks as u32, end_pos: n as u32, pad: [0; 3] };
            e.bytes(&ba, 5);
            e.pso(&gpu.pso("k_build_full_sketch_blk"));
            e.dispatch((slab.n_blks, NKV, 1), 128);
            e.end();
            cb.commit();
            cb.waitUntilCompleted();
            Engine::assert_cmd_ok(&cb, "k_build_full_sketch_blk");
        }
        let plan = sparse_prefill_plan(pos0, nrows, anchors, cfg).expect("past the budget: sparse");
        let mut first: Option<Vec<u32>> = None;
        for scorer in ["k_score_full_sketch_dec_1k", "k_score_full_sketch_dec", "k_score_full_sketch_dec_wide"] {
            let scr = select(&gpu, &act, &slab, &sketch, &plan, anchors, cfg, scorer);
            let words = unsafe { std::slice::from_raw_parts(scr.contents().as_ptr().cast::<u32>(), plan.total_u32) };
            // tasks: the CPU geometry
            for q in 0..plan.n_qb {
                let qb = plan.qb0 + q;
                let t = &words[q * 20..q * 20 + 20];
                let c = sparse_prefill_task_cpu(qb, anchors, cfg);
                let got = [t[3], t[4], t[5], t[6], t[7], t[8], t[9]].map(|x| x as usize);
                let want = [c.anchor_blks, c.far_start_blk, c.n_far_blks, c.recent_start_blk, c.total_blks, c.top_k, c.total_sel_blks];
                assert_eq!(got, want, "{pos0}+{nrows} qb {qb}: task (anchor, far start, far, recent start, total, k, kept)");
                assert_eq!(t[12] as usize, q * NKV * plan.sel_stride, "qb {qb}: list base");
            }
            // summary queries and sinks: the float mean of the block's live rows, in row order
            for q in 0..plan.n_qb {
                let qb = plan.qb0 + q;
                let (lo, hi) = (pos0.max(qb * BLOCK) - pos0, (pos0 + nrows).min(qb * BLOCK + BLOCK) - pos0);
                for h in [0usize, 7, 23] {
                    for d in [0usize, 63, 127] {
                        let mut s = 0.0f32;
                        for r in lo..hi {
                            s += act.q(r, h)[d] as f32;
                        }
                        let want = s / (hi - lo) as f32;
                        let got = f32::from_bits(words[plan.qm_off + (q * NH + h) * HD + d]);
                        assert_eq!(got.to_bits(), want.to_bits(), "{pos0}+{nrows} qb {qb} head {h} dim {d}: summary query");
                    }
                    let mut s = 0.0f32;
                    for r in lo..hi {
                        s += act.word(act.sink_off + r * NH + h);
                    }
                    let got = f32::from_bits(words[plan.sm_off + q * NH + h]);
                    assert_eq!(got.to_bits(), (s / (hi - lo) as f32).to_bits(), "qb {qb} head {h}: summary sink");
                }
            }
            // masks: anchors + needles + recent, exactly
            let masks = &words[plan.mask_off..plan.mask_off + plan.n_qb * NKV * plan.sel_words];
            for q in 0..plan.n_qb {
                let qb = plan.qb0 + q;
                let c = sparse_prefill_task_cpu(qb, anchors, cfg);
                for g in 0..NKV {
                    let row = &masks[(q * NKV + g) * plan.sel_words..][..plan.sel_words];
                    let got: Vec<usize> = (0..plan.sel_words * 32).filter(|&b| (row[b / 32] >> (b % 32)) & 1 == 1).collect();
                    let want: Vec<usize> = if c.keeps_all() {
                        (0..=qb).collect()
                    } else {
                        let mut w: Vec<usize> = (0..anchors).chain(needles).chain(c.recent_start_blk..=qb).collect();
                        w.sort_unstable();
                        w.dedup();
                        w
                    };
                    assert_eq!(got, want, "{pos0}+{nrows} {scorer}: qb {qb} head {g}: kept blocks");
                }
            }
            match &first {
                None => first = Some(masks.to_vec()),
                Some(f) => assert_eq!(f.as_slice(), masks, "{scorer}: masks differ from the 1K scorer's"),
            }
            if scorer == "k_score_full_sketch_dec" {
                attend_tc(&gpu, false, &pb, &act, &slab, 0, Some((&scr, plan.mask_off, plan.sel_words, plan.qb0)));
                let got = combine(&case, act.part(0), act.nsplit);
                let keep = |pos: usize, _g: usize, kp: usize| {
                    let (qb, kb) = (pos / BLOCK, kp / BLOCK);
                    let c = sparse_prefill_task_cpu(qb, anchors, cfg);
                    c.keeps_all() || kb < anchors || needles.contains(&kb) || kb >= c.recent_start_blk
                };
                let want = reference_kept(&act, &slab, &relb, keep);
                let (abs, rel) = difference(&got, &want);
                assert!(abs <= MAX_ABS && rel <= MAX_REL, "{pos0}+{nrows}: selected attention vs reference {abs:.3e} abs {rel:.3e} rel");
                eprintln!("[sparse-prefill] needles {pos0}+{nrows}: {} query blocks select anchors+needles+recent; attention {abs:.2e} abs", plan.n_qb);
            }
        }
    }
}