use super::*;
pub const SPARSE_PREFILL_DEFAULT_TOPK: usize = 256;
pub const SPARSE_PREFILL_DEFAULT_MIN_CTX: usize = SPARSE_DEFAULT_MIN_CTX;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SparsePrefillCfg {
pub top_k: usize,
pub min_ctx: usize,
}
pub fn sparse_prefill_cfg_from(get: impl Fn(&str) -> Option<String>) -> Result<Option<SparsePrefillCfg>, String> {
let on = super::switches::value("INK_SPARSE_PREFILL", get("INK_SPARSE_PREFILL").as_deref());
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 }))
}
#[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 {
pub fn keeps_all(&self) -> bool {
self.total_sel_blks == self.total_blks
}
}
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,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SparsePrefillPlan {
pub qb0: usize,
pub n_qb: usize,
pub total_blks_max: usize,
pub sel_words: usize,
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
}
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;
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);
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 })
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SparsePrefillStats {
pub sparse_passes: u64,
pub qblocks: u64,
pub kept_blocks: u64,
pub causal_blocks: u64,
pub fallbacks: u64,
pub sketch_catchup_slots: u64,
}
#[derive(Default)]
pub(crate) struct SparsePrefillState {
pub(crate) cfg: Cell<Option<SparsePrefillCfg>>,
buf: RefCell<Option<Buf>>,
retired: RefCell<Vec<Buf>>,
stats: Cell<SparsePrefillStats>,
last_plan: Cell<Option<SparsePrefillPlan>>,
warned: Cell<bool>,
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,
}
pub(crate) struct SparsePrefillRows {
pub(crate) q_pos0: usize,
pub(crate) q_rows: usize,
pub(crate) qp_off: u32,
pub(crate) sink_off: u32,
pub(crate) half_io: bool,
}
impl Engine {
pub fn sparse_prefill(&self) -> Option<SparsePrefillCfg> {
self.sparse_prefill.cfg.get()
}
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()
}
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());
}
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()
}
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();
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);
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);
}
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);
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;
}
super::fast_paths::EXPOSURE.sparse_prefill_passes.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
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_by_default_and_one_turns_it_on() {
assert_eq!(cfg_of(&[]).unwrap(), None, "unset is off (measured on the M5)");
assert_eq!(SPARSE_PREFILL_DEFAULT_MIN_CTX, 65_536, "dense below 65,536 tokens of context");
assert_eq!(cfg_of(&[("INK_SPARSE_PREFILL", "0")]).unwrap(), None);
assert_eq!(
cfg_of(&[("INK_SPARSE_PREFILL", "0"), ("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));
}
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);
assert!(t.recent_start_blk <= 400 && t.total_blks == 401);
}
#[test]
fn plan_is_dense_until_the_last_query_block_selects() {
let anchors = 16;
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);
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));
assert_eq!(p.sel_stride, 1024);
let p2 = sparse_prefill_plan(65_536 + 4096, 8192, anchors, CFG).unwrap();
assert_eq!(p2.sel_stride, anchors + SPARSE_RECENT_BLOCKS + CFG.top_k);
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));
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);
}
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() {
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);
}
}