inky-engine 3.0.1

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
//! Sparse prefill (`INK_SPARSE_PREFILL=1`, an undocumented developer diagnostic, off by default).
//!
//! SSA-style content-dependent attention for prompt reading, built from the sparse-decode machinery: on every full
//! pass of a Layer 3 (blocked) prefill span past the context floor, each 64-row query block picks the key blocks it
//! attends to and the tensor-core prefill kernel computes exact attention over just those blocks' keys.
//!
//! - Summary query: the float mean of the block's live query rows (and of their sinks), per head.
//! - Block scores: the WHT-2bit block sketches and scorer of `--sparse-topk` decode (`k_score_full_sketch_dec*`),
//!   unchanged: max over the block's eight sub-block sketches and the three GQA heads, exact radix top-k.
//! - Always kept: the `sparse_anchors` sink blocks at the start of the context and the `SPARSE_RECENT_BLOCKS` (16)
//!   most recent blocks, which include the query block's own (causal-diagonal) block.
//! - A query block below the context floor, or with no more causal blocks than anchors + recent + top-k, keeps
//!   every causal block, which is bit-identical to dense attention.
//!
//! Exact vs approximate: attention over the selected keys is exact (the same tiles, the same online softmax, the same
//! split partials and combine as dense; a skipped tile leaves the running max, sum and output untouched bit for bit),
//! so the only approximation is *which* keys are visible: the keys of unselected far blocks are dropped.
//!
//! Knobs (read once at `Engine::load`; `Engine::set_sparse_prefill` changes them at run time):
//! - `INK_SPARSE_PREFILL=1` turns it on (unset, empty or `0`: off; off is the unchanged dense path).
//! - `INK_SPARSE_PREFILL_TOPK` far blocks per query block and KV head (default 256 = 16K keys, `2..=4095`).
//! - `INK_SPARSE_PREFILL_MIN_CTX` context floor in tokens (default 65,536): query blocks whose last row is below it
//!   stay dense.
//!
//! It needs the sketches `--sparse-topk` builds (the serve default) and the tensor-core prefill attention kernel
//! (`k_attn_tc_fixed_blk`, outside `--exact`); a span without them runs dense and counts a fallback.

use super::*;

/// Default `INK_SPARSE_PREFILL_TOPK`: far blocks selected per query block and KV head.
pub const SPARSE_PREFILL_DEFAULT_TOPK: usize = 256;
/// Default `INK_SPARSE_PREFILL_MIN_CTX`: the context floor (tokens) below which a query block stays dense.
pub const SPARSE_PREFILL_DEFAULT_MIN_CTX: usize = SPARSE_DEFAULT_MIN_CTX;

/// Sparse prefill settings (`None` on the engine = off).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SparsePrefillCfg {
    pub top_k: usize,
    pub min_ctx: usize,
}

/// Parse the `INK_SPARSE_PREFILL*` variables through `get` (the process environment in production, a map in tests).
pub fn sparse_prefill_cfg_from(get: impl Fn(&str) -> Option<String>) -> Result<Option<SparsePrefillCfg>, String> {
    let on = get("INK_SPARSE_PREFILL").is_some_and(|v| !v.is_empty() && v != "0");
    if !on {
        return Ok(None);
    }
    let num = |name: &str, default: usize| -> Result<usize, String> {
        match get(name) {
            None => Ok(default),
            Some(v) if v.is_empty() => Ok(default),
            Some(v) => v.trim().parse::<usize>().map_err(|_| format!("{name} must be a non-negative integer (got {v:?})")),
        }
    };
    let top_k = num("INK_SPARSE_PREFILL_TOPK", SPARSE_PREFILL_DEFAULT_TOPK)?;
    if !(SPARSE_MIN_TOPK..=SPARSE_MAX_TOPK).contains(&top_k) {
        return Err(format!("INK_SPARSE_PREFILL_TOPK must be in {SPARSE_MIN_TOPK}..={SPARSE_MAX_TOPK} (got {top_k})"));
    }
    let min_ctx = num("INK_SPARSE_PREFILL_MIN_CTX", SPARSE_PREFILL_DEFAULT_MIN_CTX)?;
    Ok(Some(SparsePrefillCfg { top_k, min_ctx }))
}

/// The selection geometry of one query block (`SparseDecTask` fields `k_sparse_pf_prep` writes).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SparsePrefillTask {
    pub total_blks: usize,
    pub anchor_blks: usize,
    pub far_start_blk: usize,
    pub n_far_blks: usize,
    pub recent_start_blk: usize,
    pub top_k: usize,
    pub total_sel_blks: usize,
}

impl SparsePrefillTask {
    /// Whether the block keeps every causal key block (dense).
    pub fn keeps_all(&self) -> bool {
        self.total_sel_blks == self.total_blks
    }
}

/// CPU mirror of `k_sparse_pf_prep`'s task for query block `qb`: the decode plan
/// (`blocks::sparse_block_window_plan`) at the block's last row, with a passthrough plan turned into "keep every
/// causal block" (the scorer pins `[0, total)`).
pub fn sparse_prefill_task_cpu(qb: usize, anchors: usize, cfg: SparsePrefillCfg) -> SparsePrefillTask {
    let pos = qb * crate::blocks::BLOCK + crate::blocks::BLOCK - 1;
    let eff_topk = if pos < cfg.min_ctx { None } else { Some(cfg.top_k) };
    let bp = crate::blocks::sparse_block_window_plan(pos, anchors, SPARSE_RECENT_BLOCKS, eff_topk);
    if bp.passthrough {
        let t = bp.total_blocks;
        return SparsePrefillTask {
            total_blks: t,
            anchor_blks: t,
            far_start_blk: t,
            n_far_blks: 0,
            recent_start_blk: t,
            top_k: 0,
            total_sel_blks: t,
        };
    }
    SparsePrefillTask {
        total_blks: bp.total_blocks,
        anchor_blks: bp.anchor_blocks,
        far_start_blk: bp.far_start_blk,
        n_far_blks: bp.n_far_blocks,
        recent_start_blk: bp.recent_start_blk,
        top_k: bp.top_k,
        total_sel_blks: bp.total_sel_blocks,
    }
}

/// The scratch layout (u32 words) of one sparse span on one full pass.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SparsePrefillPlan {
    /// absolute index of the first query block
    pub qb0: usize,
    /// query blocks the span's query rows touch
    pub n_qb: usize,
    /// causal key blocks of the last query block (the scorer kernel is chosen by it)
    pub total_blks_max: usize,
    /// u32 words of one (query block, KV head) mask
    pub sel_words: usize,
    /// selected-list words reserved per (query block, KV head)
    pub sel_stride: usize,
    pub qm_off: usize,
    pub sm_off: usize,
    pub sel_off: usize,
    pub mask_off: usize,
    pub total_u32: usize,
}

const fn align64(x: usize) -> usize {
    x.div_ceil(64) * 64
}

/// The plan of query rows `[q_pos0, q_pos0 + q_rows)`, or `None` when every one of their query blocks keeps every
/// causal block (the span runs the dense path, bit-identical).
pub fn sparse_prefill_plan(q_pos0: usize, q_rows: usize, anchors: usize, cfg: SparsePrefillCfg) -> Option<SparsePrefillPlan> {
    if q_rows == 0 {
        return None;
    }
    let bk = crate::blocks::BLOCK;
    let qb0 = q_pos0 / bk;
    let qb_last = (q_pos0 + q_rows - 1) / bk;
    // Monotone in the block index: if the last block keeps everything, every earlier one does too.
    if sparse_prefill_task_cpu(qb_last, anchors, cfg).keeps_all() {
        return None;
    }
    let n_qb = qb_last - qb0 + 1;
    let total_blks_max = qb_last + 1;
    let sel_words = total_blks_max.div_ceil(32);
    // The scorer writes `total_sel_blks` list entries per (query block, KV head), and a keep-everything block (below
    // the floor or within the budget) lists every causal block, which can exceed anchors + recent + top-k when the
    // span straddles the floor: reserve the widest list of the span.
    let sel_stride = (qb0..=qb_last).map(|qb| sparse_prefill_task_cpu(qb, anchors, cfg).total_sel_blks).max().unwrap_or(0);
    let task_words = std::mem::size_of::<SparseDecTask>() / 4;
    let qm_off = align64(n_qb * task_words);
    let sm_off = align64(qm_off + n_qb * NH * HD);
    let sel_off = align64(sm_off + n_qb * NH);
    let mask_off = align64(sel_off + n_qb * NKV * sel_stride);
    let total_u32 = align64(mask_off + n_qb * NKV * sel_words);
    Some(SparsePrefillPlan { qb0, n_qb, total_blks_max, sel_words, sel_stride, qm_off, sm_off, sel_off, mask_off, total_u32 })
}

/// Counters of the sparse prefill path, cumulative since load or the last [`Engine::reset_sparse_prefill_stats`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SparsePrefillStats {
    /// (span, full pass) attention dispatches that ran sparse
    pub sparse_passes: u64,
    /// query blocks those dispatches selected for
    pub qblocks: u64,
    /// key blocks the selections keep, summed over query blocks (per KV head; the CPU mirror of the GPU geometry)
    pub kept_blocks: u64,
    /// causal key blocks of the same query blocks (what dense attention reads)
    pub causal_blocks: u64,
    /// (span, full pass) dispatches past the floor that ran dense because the path was unavailable
    pub fallbacks: u64,
    /// stale block sketches below a sparse span rebuilt before its selection (restored or failed slots)
    pub sketch_catchup_slots: u64,
}

/// Engine state of sparse prefill.
#[derive(Default)]
pub(crate) struct SparsePrefillState {
    pub(crate) cfg: Cell<Option<SparsePrefillCfg>>,
    buf: RefCell<Option<Buf>>,
    /// Scratch buffers replaced by a larger one; command buffers hold unretained references, so they stay alive.
    retired: RefCell<Vec<Buf>>,
    stats: Cell<SparsePrefillStats>,
    /// the plan of the most recent sparse dispatch (for [`Engine::sparse_prefill_last_masks`])
    last_plan: Cell<Option<SparsePrefillPlan>>,
    warned: Cell<bool>,
    /// sparse *decode* tasks (`--sparse-topk` lane-steps that ran the top-k scorer), counted at encode time: the
    /// exposure counter `inky sparsecheck` reads for the decode arms
    decode_tasks: Cell<u64>,
}

impl SparsePrefillState {
    pub(crate) fn count_decode_tasks(&self, n: usize) {
        self.decode_tasks.set(self.decode_tasks.get() + n as u64);
    }
    pub(crate) fn from_env() -> SparsePrefillState {
        let cfg = sparse_prefill_cfg_from(|k| std::env::var(k).ok()).unwrap_or_else(|e| panic!("{e}"));
        if let Some(c) = cfg {
            eprintln!("[inky] sparse prefill on: top-k {} blocks, context floor {} tokens (INK_SPARSE_PREFILL)", c.top_k, c.min_ctx);
        }
        let s = SparsePrefillState::default();
        s.cfg.set(cfg);
        s
    }
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct SparsePfPrepArgs {
    pub(crate) q_pos0: u32,
    pub(crate) q_rows: u32,
    pub(crate) qp_off: u32,
    pub(crate) sink_off: u32,
    pub(crate) half_io: u32,
    pub(crate) n_qb: u32,
    pub(crate) qb0: u32,
    pub(crate) anchors: u32,
    pub(crate) recent: u32,
    pub(crate) top_k: u32,
    pub(crate) min_ctx: u32,
    pub(crate) qm_off: u32,
    pub(crate) sm_off: u32,
    pub(crate) sel_stride: u32,
    pub(crate) pad: [u32; 2],
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct SparsePfMaskArgs {
    pub(crate) n_qb: u32,
    pub(crate) sel_u32_base: u32,
    pub(crate) mask_off: u32,
    pub(crate) sel_words: u32,
}

/// Where a span's query rows live in the batch arena.
pub(crate) struct SparsePrefillRows {
    pub(crate) q_pos0: usize,
    pub(crate) q_rows: usize,
    /// float-word offset of the first query row's `qp`
    pub(crate) qp_off: u32,
    /// float-word offset of the first query row's sinks
    pub(crate) sink_off: u32,
    pub(crate) half_io: bool,
}

impl Engine {
    /// Sparse prefill settings (`None` = off).
    pub fn sparse_prefill(&self) -> Option<SparsePrefillCfg> {
        self.sparse_prefill.cfg.get()
    }
    /// Turn sparse prefill on (`Some`) or off (`None`) for spans encoded from now on.
    pub fn set_sparse_prefill(&self, cfg: Option<SparsePrefillCfg>) {
        if let Some(c) = cfg {
            assert!((SPARSE_MIN_TOPK..=SPARSE_MAX_TOPK).contains(&c.top_k), "sparse prefill top-k out of range");
        }
        self.sparse_prefill.cfg.set(cfg);
    }
    pub fn sparse_prefill_stats(&self) -> SparsePrefillStats {
        self.sparse_prefill.stats.get()
    }
    /// Sparse decode tasks encoded since load (one per lane-step that ran the `--sparse-topk` scorer).
    pub fn sparse_decode_tasks(&self) -> u64 {
        self.sparse_prefill.decode_tasks.get()
    }
    pub fn reset_sparse_prefill_stats(&self) {
        self.sparse_prefill.stats.set(SparsePrefillStats::default());
    }
    /// The key-block masks of the most recent sparse dispatch, read back from the GPU scratch (call after its command
    /// buffer completed): `(qb0, sel_words, masks[(query block * NKV + kv head) * sel_words + word])`.
    pub fn sparse_prefill_last_masks(&self) -> Option<(usize, usize, Vec<u32>)> {
        let plan = self.sparse_prefill.last_plan.get()?;
        let buf = self.sparse_prefill.buf.borrow();
        let buf = buf.as_ref()?;
        let n = plan.n_qb * NKV * plan.sel_words;
        assert!((plan.mask_off + n) * 4 <= buf.length());
        let words = unsafe { std::slice::from_raw_parts(buf.contents().as_ptr().cast::<u32>().add(plan.mask_off), n) };
        Some((plan.qb0, plan.sel_words, words.to_vec()))
    }

    fn ensure_sparse_prefill_buf(&self, need_u32: usize) -> Buf {
        let need = need_u32 * 4;
        let mut slot = self.sparse_prefill.buf.borrow_mut();
        if slot.as_ref().is_none_or(|b| b.length() < need) {
            if let Some(old) = slot.take() {
                self.sparse_prefill.retired.borrow_mut().push(old);
            }
            *slot = Some(self.gpu.buffer(need.next_power_of_two()));
        }
        slot.as_ref().unwrap().clone()
    }

    /// Before a prefill step whose full passes select (sparse prefill on), rebuild the sketches of the span lanes'
    /// complete blocks below the span (`[0, p0 / 64)`) that are not current: slots restored from a session or the
    /// SSD block cache (`take_unzeroed`), or whose sketch update failed, have `sketch_valid_len < 64` and stale
    /// sketch bytes, and the scorer would rank those blocks by garbage. The span's own blocks are rebuilt per pass by
    /// `k_build_full_sketch_blk`; staged updates of in-flight steps count as current (the queue runs them first).
    /// Mirrors sparse decode's dirty-slot catch-up (`k_build_full_sketch_slots`); returns the slots it rebuilt.
    pub(crate) fn encode_sparse_prefill_sketch_catchup(
        &self,
        e: &Enc,
        spans: &[Span],
        paged_sketch_updates: &mut Vec<PagedSketchUpd>,
    ) -> usize {
        let Some(cfg) = self.sparse_prefill() else { return 0 };
        if self.sparse_topk().is_none() {
            return 0;
        }
        let anchors = self.sparse_anchors();
        let bk = crate::blocks::BLOCK;
        let full = bk as u8;
        let mut dirty: Vec<[u32; 2]> = Vec::new();
        {
            let pools = self.block_pool.borrow();
            // valid lengths staged by in-flight steps (current epoch only)
            let mut staged: std::collections::HashMap<u32, u8> = std::collections::HashMap::new();
            for b in self.pending_sketch_batches.borrow().iter() {
                for &(slot, gen, ep, _, valid) in &b.paged_updates {
                    if pools.full.record(slot).is_ok_and(|r| r.generation() == gen)
                        && pools.full.slot_sketch_epoch(slot).ok() == Some(ep)
                    {
                        let v = staged.entry(slot.get()).or_insert(0);
                        *v = (*v).max(valid);
                    }
                }
            }
            let mut seen = std::collections::HashSet::new();
            for sp in spans {
                if sp.t == 0 || sparse_prefill_plan(sp.p0, sp.t, anchors, cfg).is_none() {
                    continue;
                }
                let tbl = sp.lane.block_table.borrow();
                for blk in 0..sp.p0 / bk {
                    let bi = crate::blocks::BlockIndex::new(blk as u32);
                    let Some(entry) = tbl.get(crate::blocks::BlockKind::Full, bi).ok().flatten() else { continue };
                    let slot = entry.slot();
                    let cur = pools.full.slot_sketch_valid_len(slot).unwrap_or(0);
                    let cur = cur.max(staged.get(&slot.get()).copied().unwrap_or(0));
                    if cur < full && seen.insert(slot.get()) {
                        dirty.push([slot.pool_index().get(), u32::from(full)]);
                        let ep = pools.full.slot_sketch_epoch(slot).unwrap_or(0);
                        paged_sketch_updates.push((slot, entry.generation(), ep, 0, full));
                    }
                }
            }
        }
        if dirty.is_empty() {
            return 0;
        }
        let (slots_per_slab, sketch_buf) = {
            let pools = self.block_pool.borrow();
            (
                pools.full.slots_per_slab() as u32,
                pools.full.gpu_sketch_buffer().expect("Layer 3 Full pool missing GPU sketch buffer").clone(),
            )
        };
        self.bind_pool_slabs(e, false);
        e.buf(&sketch_buf, 0, 13);
        // slot lists go inline (setBytes, at most 4 KB a dispatch): no CPU-written scratch shared with in-flight steps
        for chunk in dirty.chunks(512) {
            e.bytes_slice(chunk, 14);
            let ba = BuildSketchSlotsArgs { n_slots: chunk.len() as u32, slots_per_slab, pad: [0; 2] };
            self.go(e, C_KVPREP, "k_build_full_sketch_slots", &ba, (chunk.len(), NKV, crate::blocks::FULL_PASSES), 128);
        }
        e.buf(&self.act.borrow(), 0, 3);
        self.bump_sparse_prefill_stats(|s| s.sketch_catchup_slots += dirty.len() as u64);
        dirty.len()
    }

    fn bump_sparse_prefill_stats(&self, f: impl FnOnce(&mut SparsePrefillStats)) {
        let mut s = self.sparse_prefill.stats.get();
        f(&mut s);
        self.sparse_prefill.stats.set(s);
    }

    /// Encode the selection of one blocked span's full pass and bind its masks at buffer 14; returns the
    /// `(sel_words, sel_qb0)` the attention dispatches carry in `PreparedAttnArgs::pad[0..2]`, or `None` to run
    /// dense. `available` is whether this dispatch can run sparse at all (blocked lane, tensor-core attention,
    /// sketches built for this pass). Expects the act arena at buffer 2, the lane's full block table at 8 and the
    /// sketches at 13; leaves the act arena at 2.
    pub(crate) fn encode_sparse_prefill_select(
        &self,
        e: &Enc,
        pass_idx: u32,
        rows: &SparsePrefillRows,
        available: bool,
    ) -> Option<(u32, u32)> {
        let cfg = self.sparse_prefill()?;
        let anchors = self.sparse_anchors();
        let plan = sparse_prefill_plan(rows.q_pos0, rows.q_rows, anchors, cfg)?;
        if !available {
            self.bump_sparse_prefill_stats(|s| s.fallbacks += 1);
            if !self.sparse_prefill.warned.replace(true) {
                eprintln!(
                    "[inky] sparse prefill: a span past the floor runs dense (needs a blocked lane, tensor-core \
                     prefill attention and --sparse-topk sketches)"
                );
            }
            return None;
        }
        let buf = self.ensure_sparse_prefill_buf(plan.total_u32);
        let slots_per_slab = self.block_pool.borrow().full.slots_per_slab() as u32;
        e.buf(&buf, 0, 14);
        let pa = SparsePfPrepArgs {
            q_pos0: rows.q_pos0 as u32,
            q_rows: rows.q_rows as u32,
            qp_off: rows.qp_off,
            sink_off: rows.sink_off,
            half_io: rows.half_io as u32,
            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.min(u32::MAX as usize) 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],
        };
        self.go(e, C_KVPREP, "k_sparse_pf_prep", &pa, (plan.n_qb, NH, 1), 128);
        // the scorer reads its queries and sinks from `A`: point buffer 2 at the scratch for this one dispatch
        e.buf(&buf, 0, 2);
        let sa = ScoreFullSketchArgs {
            pass_idx,
            slots_per_slab,
            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,
        };
        self.go(e, C_KVPREP, self.sparse_scorer_kernel(plan.total_blks_max), &sa, (NKV, plan.n_qb, 1), 256);
        e.buf(&self.act.borrow(), 0, 2);
        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,
        };
        self.go(e, C_KVPREP, "k_sparse_pf_mask", &ma, (NKV, plan.n_qb, 1), 256);
        e.buf(&buf, plan.mask_off * 4, 14);
        let (mut kept, mut causal) = (0u64, 0u64);
        for qb in plan.qb0..plan.qb0 + plan.n_qb {
            let t = sparse_prefill_task_cpu(qb, anchors, cfg);
            kept += t.total_sel_blks as u64;
            causal += t.total_blks as u64;
        }
        self.bump_sparse_prefill_stats(|s| {
            s.sparse_passes += 1;
            s.qblocks += plan.n_qb as u64;
            s.kept_blocks += kept;
            s.causal_blocks += causal;
        });
        self.sparse_prefill.last_plan.set(Some(plan));
        Some((plan.sel_words as u32, plan.qb0 as u32))
    }
}

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

    fn cfg_of(pairs: &[(&str, &str)]) -> Result<Option<SparsePrefillCfg>, String> {
        let m: HashMap<String, String> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
        sparse_prefill_cfg_from(|k| m.get(k).cloned())
    }

    const CFG: SparsePrefillCfg = SparsePrefillCfg { top_k: 256, min_ctx: 65_536 };

    #[test]
    fn sparse_prefill_is_off_unless_the_flag_is_set() {
        assert_eq!(cfg_of(&[]).unwrap(), None);
        assert_eq!(cfg_of(&[("INK_SPARSE_PREFILL", "")]).unwrap(), None);
        assert_eq!(cfg_of(&[("INK_SPARSE_PREFILL", "0")]).unwrap(), None);
        // knobs alone do not turn it on
        assert_eq!(cfg_of(&[("INK_SPARSE_PREFILL_TOPK", "64"), ("INK_SPARSE_PREFILL_MIN_CTX", "0")]).unwrap(), None);
        assert_eq!(
            cfg_of(&[("INK_SPARSE_PREFILL", "1")]).unwrap(),
            Some(SparsePrefillCfg { top_k: SPARSE_PREFILL_DEFAULT_TOPK, min_ctx: SPARSE_PREFILL_DEFAULT_MIN_CTX })
        );
        assert_eq!(
            cfg_of(&[("INK_SPARSE_PREFILL", "1"), ("INK_SPARSE_PREFILL_TOPK", "64"), ("INK_SPARSE_PREFILL_MIN_CTX", "0")]).unwrap(),
            Some(SparsePrefillCfg { top_k: 64, min_ctx: 0 })
        );
        assert!(cfg_of(&[("INK_SPARSE_PREFILL", "1"), ("INK_SPARSE_PREFILL_TOPK", "1")]).is_err());
        assert!(cfg_of(&[("INK_SPARSE_PREFILL", "1"), ("INK_SPARSE_PREFILL_TOPK", "4096")]).is_err());
        assert!(cfg_of(&[("INK_SPARSE_PREFILL", "1"), ("INK_SPARSE_PREFILL_MIN_CTX", "-1")]).is_err());
    }

    #[test]
    fn query_blocks_below_the_floor_or_within_the_budget_keep_every_causal_block() {
        let anchors = 16;
        for qb in [0usize, 1, 15, 100, 1023] {
            let t = sparse_prefill_task_cpu(qb, anchors, CFG);
            assert!(t.keeps_all(), "qb {qb} is below the 64K floor");
            assert_eq!((t.total_blks, t.anchor_blks, t.n_far_blks, t.top_k), (qb + 1, qb + 1, 0, 0));
        }
        // floor 0: within anchors + recent + top-k (288 blocks) everything is kept, past it selection starts
        let c0 = SparsePrefillCfg { min_ctx: 0, ..CFG };
        assert!(sparse_prefill_task_cpu(287, anchors, c0).keeps_all());
        let t = sparse_prefill_task_cpu(400, anchors, c0);
        assert!(!t.keeps_all());
        assert_eq!(t.total_blks, 401);
        assert_eq!(t.anchor_blks, anchors);
        assert_eq!(t.recent_start_blk, 401 - SPARSE_RECENT_BLOCKS);
        assert_eq!((t.far_start_blk, t.n_far_blks), (anchors, 401 - SPARSE_RECENT_BLOCKS - anchors));
        assert_eq!(t.top_k, 256);
        assert_eq!(t.total_sel_blks, anchors + 256 + SPARSE_RECENT_BLOCKS);
        // the recent window always holds the block's own (diagonal) block
        assert!(t.recent_start_blk <= 400 && t.total_blks == 401);
    }

    #[test]
    fn plan_is_dense_until_the_last_query_block_selects() {
        let anchors = 16;
        // a chunk wholly below the floor: dense, nothing to encode
        assert_eq!(sparse_prefill_plan(0, 8192, anchors, CFG), None);
        assert_eq!(sparse_prefill_plan(65_536 - 8192, 8192, anchors, CFG), None);
        assert_eq!(sparse_prefill_plan(70_000, 0, anchors, CFG), None);
        // a chunk across the floor runs sparse; its early blocks keep everything
        let p = sparse_prefill_plan(65_536 - 4096, 8192, anchors, CFG).expect("past the floor");
        assert_eq!(p.qb0, (65_536 - 4096) / 64);
        assert_eq!(p.n_qb, 128);
        assert_eq!(p.total_blks_max, (65_536 + 4096) / 64);
        assert_eq!(p.sel_words, p.total_blks_max.div_ceil(32));
        // its widest list is the last block below the floor (block 1023 keeps all 1024), not the budget
        assert_eq!(p.sel_stride, 1024);
        // past the floor every block selects: the stride is the budget
        let p2 = sparse_prefill_plan(65_536 + 4096, 8192, anchors, CFG).unwrap();
        assert_eq!(p2.sel_stride, anchors + SPARSE_RECENT_BLOCKS + CFG.top_k);
        // an unaligned span: query rows 100_000..100_100 touch blocks 1562..=1564
        let p = sparse_prefill_plan(100_000, 100, anchors, CFG).unwrap();
        assert_eq!((p.qb0, p.n_qb, p.total_blks_max), (1562, 3, 1565));
        // regions are disjoint, in order and 64-word aligned
        let task_words = std::mem::size_of::<SparseDecTask>() / 4;
        assert!(p.n_qb * task_words <= p.qm_off);
        assert!(p.qm_off + p.n_qb * NH * HD <= p.sm_off);
        assert!(p.sm_off + p.n_qb * NH <= p.sel_off);
        assert!(p.sel_off + p.n_qb * NKV * p.sel_stride <= p.mask_off);
        assert!(p.mask_off + p.n_qb * NKV * p.sel_words <= p.total_u32);
        for off in [p.qm_off, p.sm_off, p.sel_off, p.mask_off, p.total_u32] {
            assert_eq!(off % 64, 0);
        }
        // every block's kept list fits its stride
        for qb in p.qb0..p.qb0 + p.n_qb {
            assert!(sparse_prefill_task_cpu(qb, anchors, CFG).total_sel_blks <= p.sel_stride);
        }
    }

    #[test]
    fn plan_scales_to_the_widest_context() {
        let anchors = SPARSE_DEFAULT_ANCHORS;
        let end = MAX_POOLED_CONTEXT;
        let p = sparse_prefill_plan(end - 8192, 8192, anchors, CFG).unwrap();
        assert_eq!(p.total_blks_max, crate::blocks::SPARSE_MAX_BLKS);
        assert!(p.sel_words <= crate::blocks::SPARSE_MAX_BLKS / 32, "masks fit k_sparse_pf_mask's threadgroup words");
        assert!(p.total_u32 * 4 < 64 << 20, "scratch stays small: {} bytes", p.total_u32 * 4);
    }

    #[test]
    fn selection_density_falls_with_context() {
        // the share of causal blocks a query block keeps at 64K, 128K, 256K with the defaults
        let anchors = 16;
        let share = |pos: usize| {
            let t = sparse_prefill_task_cpu(pos / 64, anchors, CFG);
            t.total_sel_blks as f64 / t.total_blks as f64
        };
        assert!(share(65_536 + 63) > share(131_072 + 63));
        assert!(share(131_072 + 63) > share(262_144 - 1));
        assert!((share(131_072 + 63) - 288.0 / 2049.0).abs() < 1e-12);
    }
}