use crate::gguf::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OffKind {
OptOut,
Default,
Mode,
Missing,
}
impl OffKind {
pub const fn name(self) -> &'static str {
match self {
OffKind::OptOut => "opt_out",
OffKind::Default => "default_off",
OffKind::Mode => "mode",
OffKind::Missing => "missing",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gate {
On,
Off(OffKind, &'static str),
}
impl Gate {
pub const fn is_on(self) -> bool {
matches!(self, Gate::On)
}
}
pub const fn mpp_gate(no_mpp_flag: bool, disable_mpp_env: bool, no_tensor_env: bool, tuning_use_mpp: bool) -> Gate {
if no_mpp_flag {
Gate::Off(OffKind::OptOut, "--no-mpp")
} else if disable_mpp_env {
Gate::Off(OffKind::OptOut, "INKY_DISABLE_MPP")
} else if no_tensor_env {
Gate::Off(OffKind::OptOut, "INK_NO_TENSOR")
} else if !tuning_use_mpp {
Gate::Off(OffKind::Mode, "this machine's tuning has no Metal 4 tensor kernels (use_mpp = false)")
} else {
Gate::On
}
}
pub const fn hgemm_gate(use_mpp: bool, no_hgemm_env: bool, layout_ok: bool) -> Gate {
if !use_mpp {
Gate::Off(OffKind::Mode, "Metal 4 tensor kernels are off (mpp_tensor)")
} else if no_hgemm_env {
Gate::Off(OffKind::OptOut, "INK_NO_HGEMM")
} else if !layout_ok {
Gate::Off(OffKind::Mode, "the tensor accumulator layout probe failed on this GPU/OS")
} else {
Gate::On
}
}
pub const fn tc_prefill_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool) -> Gate {
if !hgemm {
Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
} else if exact {
Gate::Off(OffKind::Mode, "--exact: prefill must write decode's bits")
} else if no_tc_attn_env {
Gate::Off(OffKind::OptOut, "INK_NO_TC_ATTN")
} else {
Gate::On
}
}
pub const fn tc_decode_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool, kv8: bool, tc_attn_dec_env: bool) -> Gate {
if !tc_attn_dec_env {
return Gate::Off(OffKind::Default, "off by default (measured slower at 32-64 lanes); INK_TC_ATTN_DEC=1 opts in");
}
match tc_prefill_attn_gate(hgemm, exact, no_tc_attn_env) {
Gate::On if kv8 => Gate::Off(OffKind::Missing, "--kv8: no tensor-core KV8 decode kernels"),
g => g,
}
}
pub const fn tail_trim_gate(hgemm: bool, tail: bool) -> Gate {
if !hgemm {
Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
} else if !tail {
Gate::Off(OffKind::OptOut, "INK_NO_TAIL")
} else {
Gate::On
}
}
pub const TAIL_ROWS: usize = 8;
pub const TAIL_MIN_T: usize = 16;
pub const fn tail_trim_step(hgemm: bool, tail: bool, dec: bool, verify: bool) -> bool {
tail_trim_gate(hgemm, tail).is_on() && !dec && !verify
}
pub const fn tail_trim_start(t: usize) -> usize {
if t > TAIL_MIN_T {
t - TAIL_ROWS
} else {
0
}
}
pub const fn sep_comb_gate(sep_comb: bool) -> Gate {
if sep_comb {
Gate::On
} else {
Gate::Off(OffKind::OptOut, "INK_FUSE_COMB")
}
}
pub const fn fused_topk_gate(sep_topk: bool) -> Gate {
if sep_topk {
Gate::Off(OffKind::OptOut, "INK_SEP_TOPK")
} else {
Gate::On
}
}
pub const fn grouped_decode_attn_gate(no_grp_dec: bool) -> Gate {
if no_grp_dec {
Gate::Off(OffKind::OptOut, "INK_NO_GRP_DEC")
} else {
Gate::On
}
}
pub const fn grouped_moe_decode_gate(hgemm: bool, old_moe_dec_env: bool) -> Gate {
if !hgemm {
Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
} else if old_moe_dec_env {
Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
} else {
Gate::On
}
}
pub const fn grouped_moe_tiles_gate(no_grp_moe: bool) -> Gate {
if no_grp_moe {
Gate::Off(OffKind::OptOut, "INK_NO_GRP_MOE")
} else {
Gate::On
}
}
pub const fn decode_gemm_gate(old_moe_dec_env: bool) -> Gate {
if old_moe_dec_env {
Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
} else {
Gate::On
}
}
pub const fn batched_mix_gate(old_mixb_env: bool) -> Gate {
if old_mixb_env {
Gate::Off(OffKind::OptOut, "INK_OLD_MIXB")
} else {
Gate::On
}
}
pub const fn tc_attn_row_blocks_gate(full_attn_budget: bool) -> Gate {
if full_attn_budget {
Gate::Off(OffKind::Missing, "--full-attn-budget: one query row per threadgroup")
} else {
Gate::On
}
}
pub const fn default_sparse_topk_dropped_by(exact: bool, full_attn_budget: bool) -> Option<Gate> {
if exact {
Some(Gate::Off(OffKind::Mode, "--exact: sparse retrieval is approximate"))
} else if full_attn_budget {
Some(Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time"))
} else {
None
}
}
pub const fn sparse_topk_gate(sparse_topk: bool, exact: bool, full_attn_budget: bool) -> Gate {
if sparse_topk {
return Gate::On;
}
match default_sparse_topk_dropped_by(exact, full_attn_budget) {
Some(g) => g,
None => Gate::Off(OffKind::OptOut, "--sparse-topk off"),
}
}
pub const fn sparse_prefill_gate(on_env: bool, tc_prefill_attn: bool, sparse_topk: bool, full_attn_budget: bool) -> Gate {
if !on_env {
Gate::Off(OffKind::Default, "off by default (not measured on M5 yet); INK_SPARSE_PREFILL=1 opts in")
} else if !tc_prefill_attn {
Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the mask lives in that kernel")
} else if !sparse_topk {
Gate::Off(OffKind::Mode, "--sparse-topk is off: no block sketches to select by")
} else if full_attn_budget {
Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time")
} else {
Gate::On
}
}
pub const fn tc_exp2_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
tc_softmax_reorder_gate(
on_env,
kv8,
tc_prefill_attn,
"off by default (inexact: reorders the softmax float math); INK_TC_EXP2=1 opts in under --kv8",
)
}
pub const fn tc_lazy_rescale_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
tc_softmax_reorder_gate(
on_env,
kv8,
tc_prefill_attn,
"off by default (inexact: reorders the softmax float math); INK_TC_LAZY_RESCALE=1 opts in under --kv8",
)
}
const fn tc_softmax_reorder_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool, default_off: &'static str) -> Gate {
if !on_env {
Gate::Off(OffKind::Default, default_off)
} else if !kv8 {
Gate::Off(OffKind::Mode, "KV8 only: FP16 and KV4 keep the exact softmax order, the switch is refused")
} else if !tc_prefill_attn {
Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the reordering lives in that kernel")
} else {
Gate::On
}
}
pub const fn kv_stitch_gate(kv_stitch: bool, exact: bool) -> Gate {
if kv_stitch {
Gate::On
} else if exact {
Gate::Off(OffKind::Mode, "--exact: stitched K/V is approximate")
} else {
Gate::Off(OffKind::OptOut, "--no-kv-stitch")
}
}
pub const fn attn_proj_plain_gate(lora: bool) -> Gate {
if lora {
Gate::Off(OffKind::OptOut, "INK_LORA: y += scale * B (A x) beside q/k/v/o, two extra dispatches per projection group")
} else {
Gate::On
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EnvFlags {
pub disable_mpp: bool,
pub no_tensor: bool,
pub no_hgemm: bool,
pub no_tc_attn: bool,
pub tc_attn_dec: bool,
pub old_moe_dec: bool,
pub old_mixb: bool,
pub generic_moe: bool,
pub tc_exp2: bool,
pub tc_lazy_rescale: bool,
}
fn truthy(v: Option<String>) -> bool {
v.is_some_and(|v| !v.is_empty() && v != "0")
}
impl EnvFlags {
pub fn read(get: impl Fn(&str) -> Option<String>) -> EnvFlags {
EnvFlags {
disable_mpp: truthy(get("INKY_DISABLE_MPP")),
no_tensor: get("INK_NO_TENSOR").is_some(),
no_hgemm: get("INK_NO_HGEMM").is_some(),
no_tc_attn: get("INK_NO_TC_ATTN").is_some(),
tc_attn_dec: get("INK_TC_ATTN_DEC").is_some(),
old_moe_dec: get("INK_OLD_MOE_DEC").is_some(),
old_mixb: get("INK_OLD_MIXB").is_some(),
generic_moe: truthy(get("INK_GENERIC_MOE")),
tc_exp2: truthy(get("INK_TC_EXP2")),
tc_lazy_rescale: truthy(get("INK_TC_LAZY_RESCALE")),
}
}
pub fn from_process() -> EnvFlags {
Self::read(|name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inputs {
pub no_mpp_flag: bool,
pub tuning_use_mpp: bool,
pub use_mpp: bool,
pub hgemm: bool,
pub exact: bool,
pub kv8: bool,
pub sep_comb: bool,
pub sep_topk: bool,
pub tail: bool,
pub no_grp_dec: bool,
pub no_grp_moe: bool,
pub full_attn_budget: bool,
pub sparse_topk: bool,
pub sparse_prefill: bool,
pub kv_stitch: bool,
pub lora: bool,
pub expert_types: Vec<(u32, u32)>,
pub env: EnvFlags,
}
impl Inputs {
#[cfg(test)]
pub fn serve_default() -> Inputs {
Inputs {
no_mpp_flag: false,
tuning_use_mpp: true,
use_mpp: true,
hgemm: true,
exact: false,
kv8: false,
sep_comb: true,
sep_topk: false,
tail: true,
no_grp_dec: false,
no_grp_moe: false,
full_attn_budget: false,
sparse_topk: true,
sparse_prefill: false,
kv_stitch: true,
lora: false,
expert_types: vec![(T_Q4_K, T_Q8_0); 2],
env: EnvFlags::default(),
}
}
}
impl crate::engine::Engine {
pub fn fast_path_inputs(&self, kv_stitch: bool) -> Inputs {
let (chip, mem) = crate::tuning::this_machine();
Inputs {
no_mpp_flag: crate::engine::DISABLE_MPP.load(std::sync::atomic::Ordering::Relaxed),
tuning_use_mpp: crate::tuning::select(&chip, mem).use_mpp,
use_mpp: self.use_mpp,
hgemm: self.hgemm,
exact: self.exact,
kv8: self.kv8,
sep_comb: self.sep_comb,
sep_topk: self.sep_topk,
tail: self.tail.get(),
no_grp_dec: self.no_grp_dec.get(),
no_grp_moe: self.no_grp_moe.get(),
full_attn_budget: self.full_attn_budget().is_some(),
sparse_topk: self.sparse_topk().is_some(),
sparse_prefill: self.sparse_prefill().is_some(),
kv_stitch,
lora: !self.lora.is_empty(),
expert_types: self.layers.iter().map(|l| (l.gu.ty, l.dn.ty)).collect(),
env: EnvFlags::from_process(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FastPath {
pub id: &'static str,
pub what: &'static str,
pub on: bool,
pub kind: Option<OffKind>,
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Report {
pub paths: Vec<FastPath>,
}
pub const IDS: [&str; 21] = [
"mpp_tensor",
"hgemm",
"tc_prefill_attn",
"tc_decode_attn",
"tail_trim",
"sep_comb",
"fused_topk",
"grouped_decode_attn",
"grouped_moe_decode",
"grouped_moe_tiles",
"decode_gemm",
"batched_mix",
"moe_prefill_specialised",
"moe_decode_specialised",
"tc_attn_row_blocks",
"sparse_topk",
"sparse_prefill",
"kv_stitch",
"attn_proj_plain",
"tc_exp2",
"tc_lazy_rescale",
];
fn path(id: &'static str, what: &'static str, gate: Gate) -> FastPath {
match gate {
Gate::On => FastPath { id, what, on: true, kind: None, reason: None },
Gate::Off(kind, why) => FastPath { id, what, on: false, kind: Some(kind), reason: Some(why.to_string()) },
}
}
fn type_name(ty: u32) -> String {
match ty {
T_Q4_K => "Q4_K".into(),
T_Q5_0 => "Q5_0".into(),
T_Q6_K => "Q6_K".into(),
T_Q8_0 => "Q8_0".into(),
T_Q2_K => "Q2_K".into(),
T_Q3_K => "Q3_K".into(),
T_Q3_0 => "Q3_0".into(),
T_NV4 => "NV4".into(),
T_MX8 => "MX8".into(),
T_BF16 => "BF16".into(),
other => format!("type {other}"),
}
}
fn generic_formats(types: &[(u32, u32)], kernel: impl Fn(u32, bool) -> &'static str, generic: &str) -> Option<String> {
let mut hits: Vec<String> = Vec::new();
for &(gu, dn) in types {
for (ty, situ, part) in [(gu, true, "gate/up"), (dn, false, "down")] {
if kernel(ty, situ) == generic {
let s = format!("{part} {}", type_name(ty));
if !hits.contains(&s) {
hits.push(s);
}
}
}
}
(!hits.is_empty()).then(|| hits.join(", "))
}
pub fn report(i: &Inputs) -> Report {
let env = i.env;
let mut paths = vec![
path("mpp_tensor", "Metal 4 tensor kernels", mpp_gate(i.no_mpp_flag, env.disable_mpp, env.no_tensor, i.tuning_use_mpp)),
];
let layout_ok = i.hgemm || !i.use_mpp || env.no_hgemm;
paths.push(path("hgemm", "fp16 prefill GEMMs and half attention I/O", hgemm_gate(i.use_mpp, env.no_hgemm, layout_ok)));
paths.push(path(
"tc_prefill_attn",
"tensor-core prefill attention",
tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn),
));
paths.push(path(
"tc_decode_attn",
"tensor-core decode attention",
tc_decode_attn_gate(i.hgemm, i.exact, env.no_tc_attn, i.kv8, env.tc_attn_dec),
));
paths.push(path("tail_trim", "last-layer tail trim (prefill, one or many spans)", tail_trim_gate(i.hgemm, i.tail)));
paths.push(path("sep_comb", "separate split-attention combine", sep_comb_gate(i.sep_comb)));
paths.push(path("fused_topk", "router top-k fused into the router", fused_topk_gate(i.sep_topk)));
paths.push(path("grouped_decode_attn", "shared-K/V grouped decode attention", grouped_decode_attn_gate(i.no_grp_dec)));
paths.push(path(
"grouped_moe_decode",
"grouped single-read MoE decode",
grouped_moe_decode_gate(i.hgemm, env.old_moe_dec),
));
paths.push(path("grouped_moe_tiles", "multi-token grouped MoE decode tiles", grouped_moe_tiles_gate(i.no_grp_moe)));
paths.push(path("decode_gemm", "decode-sized dense fp16 GEMMs", decode_gemm_gate(env.old_moe_dec)));
paths.push(path("batched_mix", "concurrent batched mixer jobs", batched_mix_gate(env.old_mixb)));
let prefill_moe = if !i.hgemm {
path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)"))
} else if env.generic_moe {
path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::OptOut, "INK_GENERIC_MOE"))
} else {
let generic = crate::engine::moe_sg_kernel_for(1, u32::MAX, true, false);
match generic_formats(&i.expert_types, |ty, situ| crate::engine::moe_sg_kernel_for(1, ty, situ, false), generic) {
None => path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::On),
Some(fmts) => FastPath {
id: "moe_prefill_specialised",
what: "format-specialised prefill MoE",
on: false,
kind: Some(OffKind::Missing),
reason: Some(format!("no specialised prefill MoE kernel for experts {fmts}")),
},
}
};
paths.push(prefill_moe);
let decode_moe = if !grouped_moe_decode_gate(i.hgemm, env.old_moe_dec).is_on() {
path(
"moe_decode_specialised",
"format-specialised grouped MoE decode",
Gate::Off(OffKind::Mode, "grouped MoE decode is off (grouped_moe_decode)"),
)
} else {
let generic = crate::engine::moe_dec_sg4_kernel(u32::MAX, true);
match generic_formats(&i.expert_types, crate::engine::moe_dec_sg4_kernel, generic) {
None => path("moe_decode_specialised", "format-specialised grouped MoE decode", Gate::On),
Some(fmts) => FastPath {
id: "moe_decode_specialised",
what: "format-specialised grouped MoE decode",
on: false,
kind: Some(OffKind::Missing),
reason: Some(format!("no specialised decode MoE kernel for experts {fmts}")),
},
}
};
paths.push(decode_moe);
paths.push(path(
"tc_attn_row_blocks",
"16 query rows per tensor-core attention threadgroup",
tc_attn_row_blocks_gate(i.full_attn_budget),
));
paths.push(path(
"sparse_topk",
"sparse top-k full attention past --sparse-min-ctx",
sparse_topk_gate(i.sparse_topk, i.exact, i.full_attn_budget),
));
paths.push(path(
"sparse_prefill",
"sparse top-k prefill attention past INK_SPARSE_PREFILL_MIN_CTX",
sparse_prefill_gate(
i.sparse_prefill,
tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn).is_on(),
i.sparse_topk,
i.full_attn_budget,
),
));
paths.push(path("kv_stitch", "stitched K/V reuse", kv_stitch_gate(i.kv_stitch, i.exact)));
paths.push(path("attn_proj_plain", "attention projections without runtime-LoRA side kernels", attn_proj_plain_gate(i.lora)));
let tc_prefill = tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn).is_on();
paths.push(path(
"tc_exp2",
"exp2 softmax in tensor-core prefill attention (inexact, KV8)",
tc_exp2_gate(env.tc_exp2, i.kv8, tc_prefill),
));
paths.push(path(
"tc_lazy_rescale",
"lazy O rescale in tensor-core prefill attention (inexact, KV8)",
tc_lazy_rescale_gate(env.tc_lazy_rescale, i.kv8, tc_prefill),
));
Report { paths }
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Policy {
pub require: bool,
pub opt_out: Vec<String>,
}
impl Policy {
pub fn read(get: impl Fn(&str) -> Option<String>) -> Result<Policy, String> {
let require = match get("INK_REQUIRE_FAST_PATHS").as_deref() {
None | Some("") | Some("0") => false,
Some("1") => true,
Some(_) => return Err("INK_REQUIRE_FAST_PATHS must be 0 or 1".into()),
};
let mut opt_out = Vec::new();
for id in get("INK_FAST_PATH_OPT_OUT").unwrap_or_default().split(',').map(str::trim).filter(|s| !s.is_empty()) {
if !IDS.contains(&id) {
return Err(format!("INK_FAST_PATH_OPT_OUT: unknown fast path {id:?} (known: {})", IDS.join(", ")));
}
opt_out.push(id.to_string());
}
Ok(Policy { require, opt_out })
}
}
impl Report {
#[cfg(test)]
pub fn get(&self, id: &str) -> Option<&FastPath> {
self.paths.iter().find(|p| p.id == id)
}
pub fn unaccepted<'a>(&'a self, policy: &Policy) -> Vec<&'a FastPath> {
self.paths
.iter()
.filter(|p| !p.on)
.filter(|p| !matches!(p.kind, Some(OffKind::OptOut | OffKind::Default)))
.filter(|p| !policy.opt_out.iter().any(|o| o == p.id))
.collect()
}
pub fn to_json(&self, policy: &Policy) -> serde_json::Value {
let mut paths = serde_json::Map::new();
for p in &self.paths {
let mut o = serde_json::Map::new();
o.insert("on".into(), serde_json::json!(p.on));
if let Some(k) = p.kind {
o.insert("kind".into(), serde_json::json!(k.name()));
}
if let Some(r) = &p.reason {
o.insert("reason".into(), serde_json::json!(r));
}
paths.insert(p.id.into(), serde_json::Value::Object(o));
}
let unaccepted: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
serde_json::json!({
"paths": paths,
"off": self.paths.iter().filter(|p| !p.on).count(),
"unaccepted": unaccepted,
"require": policy.require,
"opt_out": policy.opt_out,
})
}
pub fn log_lines(&self, policy: &Policy) -> Vec<String> {
let bad: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
let off = self.paths.iter().filter(|p| !p.on).count();
let mut out = vec![format!(
"[fast-paths] {} of {} on, {} off, {} off without an opt-out{}",
self.paths.len() - off,
self.paths.len(),
off,
bad.len(),
if policy.require { " (INK_REQUIRE_FAST_PATHS=1)" } else { "" }
)];
for p in &self.paths {
if p.on {
out.push(format!("[fast-paths] ON {:<24} {}", p.id, p.what));
} else {
let mark = if bad.contains(&p.id) { "!!" } else { " " };
out.push(format!(
"[fast-paths] {mark} OFF {:<24} {} -- {} ({})",
p.id,
p.what,
p.reason.as_deref().unwrap_or(""),
p.kind.map_or("", OffKind::name)
));
}
}
if !bad.is_empty() && !policy.require {
out.push(format!(
"[fast-paths] WARNING: {} switched off by another setting: {}. Name them in INK_FAST_PATH_OPT_OUT to accept, INK_REQUIRE_FAST_PATHS=1 refuses to start",
if bad.len() == 1 { "a fast path is" } else { "fast paths are" },
bad.join(", ")
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn off(r: &Report, id: &str) -> (OffKind, String) {
let p = r.get(id).unwrap_or_else(|| panic!("no {id}"));
assert!(!p.on, "{id} should be off");
(p.kind.unwrap(), p.reason.clone().unwrap())
}
fn on(r: &Report, id: &str) -> bool {
r.get(id).unwrap_or_else(|| panic!("no {id}")).on
}
#[test]
fn every_id_is_reported_once_in_order() {
let r = report(&Inputs::serve_default());
let ids: Vec<&str> = r.paths.iter().map(|p| p.id).collect();
assert_eq!(ids, IDS);
}
#[test]
fn serve_default_keeps_every_path_but_measured_tc_decode() {
let r = report(&Inputs::serve_default());
let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "tc_exp2", "tc_lazy_rescale"]);
for id in offs {
assert_eq!(off(&r, id).0, OffKind::Default, "{id}");
}
assert!(r.unaccepted(&Policy::default()).is_empty());
}
#[test]
fn sparse_prefill_is_default_off_and_names_what_blocks_it_when_on() {
let mut i = Inputs::serve_default();
i.sparse_prefill = true;
assert!(on(&report(&i), "sparse_prefill"));
i.env.no_tc_attn = true;
assert_eq!(off(&report(&i), "sparse_prefill").0, OffKind::Mode);
i.env.no_tc_attn = false;
i.exact = true;
assert!(off(&report(&i), "sparse_prefill").1.contains("tc_prefill_attn"));
i.exact = false;
i.sparse_topk = false;
assert!(off(&report(&i), "sparse_prefill").1.contains("--sparse-topk"));
i.sparse_topk = true;
i.full_attn_budget = true;
assert!(off(&report(&i), "sparse_prefill").1.contains("--full-attn-budget"));
}
#[test]
fn kv8_keeps_tc_prefill_and_blocks_tc_decode_only_when_asked_for() {
let mut i = Inputs::serve_default();
i.kv8 = true;
let r = report(&i);
assert!(on(&r, "tc_prefill_attn"), "#234: KV8 prefill is on the tensor cores");
assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default);
i.env.tc_attn_dec = true;
let r = report(&i);
let (kind, why) = off(&r, "tc_decode_attn");
assert_eq!(kind, OffKind::Missing);
assert!(why.contains("--kv8"), "{why}");
assert_eq!(r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect::<Vec<_>>(), ["tc_decode_attn"]);
i.kv8 = false;
let r = report(&i);
assert!(on(&r, "tc_decode_attn"));
}
#[test]
fn tc_softmax_reorderings_are_kv8_opt_ins_refused_elsewhere() {
for (id, env) in [("tc_exp2", "INK_TC_EXP2"), ("tc_lazy_rescale", "INK_TC_LAZY_RESCALE")] {
let mut i = Inputs::serve_default();
i.kv8 = true;
let (kind, why) = off(&report(&i), id);
assert_eq!(kind, OffKind::Default, "{id}");
assert!(why.contains(env), "{id}: {why}");
i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
assert!(on(&report(&i), id), "{id}: {env}=1 under --kv8");
i.env = EnvFlags::read(|name| (name == env).then(|| "0".to_string()));
assert_eq!(off(&report(&i), id).0, OffKind::Default, "{id}: {env}=0 is off");
i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
i.kv8 = false;
let r = report(&i);
let (kind, why) = off(&r, id);
assert_eq!(kind, OffKind::Mode, "{id}");
assert!(why.contains("KV8 only"), "{id}: {why}");
assert_eq!(r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect::<Vec<_>>(), [id]);
i.kv8 = true;
i.env.no_tc_attn = true;
assert!(off(&report(&i), id).1.contains("tc_prefill_attn"), "{id}");
}
}
#[test]
fn tc_softmax_defines_follow_the_gates() {
for bits in 0u32..8 {
let b = |n: u32| bits & (1 << n) != 0;
let (kv8, exp2, lazy) = (b(0), b(1), b(2));
let d = crate::engine::tc_softmax_defines(kv8, exp2, lazy);
assert_eq!(d.contains("#define TC_ATT_EXP2 1"), tc_exp2_gate(exp2, kv8, true).is_on());
assert_eq!(d.contains("#define TC_ATT_LAZY_RESCALE 1"), tc_lazy_rescale_gate(lazy, kv8, true).is_on());
}
}
#[test]
fn exact_turns_off_tc_prefill_sparse_and_stitch_as_mode() {
let mut i = Inputs::serve_default();
i.exact = true;
i.sparse_topk = false;
i.kv_stitch = false;
let r = report(&i);
for id in ["tc_prefill_attn", "sparse_topk", "kv_stitch"] {
let (kind, why) = off(&r, id);
assert_eq!(kind, OffKind::Mode, "{id}");
assert!(why.contains("--exact"), "{id}: {why}");
}
assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default);
let ids: Vec<&str> = r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect();
assert_eq!(ids, ["tc_prefill_attn", "sparse_topk", "kv_stitch"]);
let accepted = Policy { require: true, opt_out: ids.iter().map(|s| s.to_string()).collect() };
assert!(r.unaccepted(&accepted).is_empty());
}
#[test]
fn dspark_keeps_sparse_and_only_exact_or_budget_drop_it() {
assert!(default_sparse_topk_dropped_by(false, false).is_none());
let i = Inputs::serve_default();
assert!(on(&report(&i), "sparse_topk"));
let mut i = Inputs::serve_default();
i.sparse_topk = false;
assert_eq!(off(&report(&i), "sparse_topk").0, OffKind::OptOut);
}
#[test]
fn ink_lora_is_reported_as_an_accepted_opt_out_and_costs_no_other_path() {
let mut i = Inputs::serve_default();
i.lora = true;
let r = report(&i);
let (kind, why) = off(&r, "attn_proj_plain");
assert_eq!(kind, OffKind::OptOut);
assert!(why.contains("INK_LORA"), "{why}");
let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "attn_proj_plain", "tc_exp2", "tc_lazy_rescale"]);
assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
}
#[test]
fn full_attn_budget_loses_row_blocks_and_sparse() {
let mut i = Inputs::serve_default();
i.full_attn_budget = true;
i.sparse_topk = false;
let r = report(&i);
assert_eq!(off(&r, "tc_attn_row_blocks").0, OffKind::Missing);
assert_eq!(off(&r, "sparse_topk").0, OffKind::Mode);
}
#[test]
fn no_mpp_cascades_to_every_fp16_path() {
let mut i = Inputs::serve_default();
i.no_mpp_flag = true;
i.use_mpp = false;
i.hgemm = false;
let r = report(&i);
assert_eq!(off(&r, "mpp_tensor"), (OffKind::OptOut, "--no-mpp".into()));
for id in ["hgemm", "tc_prefill_attn", "tail_trim", "grouped_moe_decode", "moe_prefill_specialised", "moe_decode_specialised"] {
assert_eq!(off(&r, id).0, OffKind::Mode, "{id}");
}
}
#[test]
fn tail_trim_step_is_the_gate_on_prefill_steps() {
for (hgemm, tail) in [(true, true), (true, false), (false, true), (false, false)] {
let on = tail_trim_gate(hgemm, tail).is_on();
assert_eq!(tail_trim_step(hgemm, tail, false, false), on);
assert!(!tail_trim_step(hgemm, tail, true, false), "a decode step");
assert!(!tail_trim_step(hgemm, tail, false, true), "verify needs every row");
}
assert_eq!(tail_trim_start(1), 0);
assert_eq!(tail_trim_start(TAIL_MIN_T), 0);
assert_eq!(tail_trim_start(TAIL_MIN_T + 1), TAIL_MIN_T + 1 - TAIL_ROWS);
assert_eq!(tail_trim_start(4096), 4096 - TAIL_ROWS);
}
#[test]
fn layout_probe_failure_is_named() {
let mut i = Inputs::serve_default();
i.hgemm = false;
let (kind, why) = off(&report(&i), "hgemm");
assert_eq!(kind, OffKind::Mode);
assert!(why.contains("layout"), "{why}");
i.env.no_hgemm = true;
assert_eq!(off(&report(&i), "hgemm"), (OffKind::OptOut, "INK_NO_HGEMM".into()));
}
#[test]
fn dev_switches_are_named_opt_outs() {
let mut i = Inputs::serve_default();
i.env = EnvFlags::read(|name| {
matches!(name, "INK_NO_TC_ATTN" | "INK_OLD_MOE_DEC" | "INK_OLD_MIXB" | "INK_GENERIC_MOE").then(|| "1".to_string())
});
i.no_grp_dec = true;
i.no_grp_moe = true;
i.tail = false;
i.sep_topk = true;
let r = report(&i);
for (id, why) in [
("tc_prefill_attn", "INK_NO_TC_ATTN"),
("grouped_moe_decode", "INK_OLD_MOE_DEC"),
("decode_gemm", "INK_OLD_MOE_DEC"),
("batched_mix", "INK_OLD_MIXB"),
("moe_prefill_specialised", "INK_GENERIC_MOE"),
("grouped_decode_attn", "INK_NO_GRP_DEC"),
("grouped_moe_tiles", "INK_NO_GRP_MOE"),
("tail_trim", "INK_NO_TAIL"),
("fused_topk", "INK_SEP_TOPK"),
] {
assert_eq!(off(&r, id), (OffKind::OptOut, why.to_string()), "{id}");
}
i.env.tc_attn_dec = true;
assert_eq!(off(&report(&i), "tc_decode_attn"), (OffKind::OptOut, "INK_NO_TC_ATTN".into()));
}
#[test]
fn expert_formats_without_specialised_kernels_are_named() {
let mut i = Inputs::serve_default();
i.expert_types = vec![(T_Q4_K, T_Q8_0), (T_NV4, T_NV4), (T_Q3_K, T_Q5_0)];
let r = report(&i);
let (kind, why) = off(&r, "moe_decode_specialised");
assert_eq!(kind, OffKind::Missing);
assert!(why.contains("gate/up NV4") && why.contains("down NV4") && why.contains("gate/up Q3_K"), "{why}");
assert!(!why.contains("Q4_K") && !why.contains("Q8_0") && !why.contains("Q5_0"), "{why}");
let (_, why) = off(&r, "moe_prefill_specialised");
assert!(why.contains("Q3_K") && !why.contains("NV4"), "prefill has NV4 kernels: {why}");
i.expert_types = vec![(T_MX8, T_MX8)];
assert!(on(&report(&i), "moe_prefill_specialised"));
}
#[test]
fn gates_agree_with_the_engine_predicates() {
for bits in 0u32..32 {
let b = |n: u32| bits & (1 << n) != 0;
let (hgemm, exact, no_tc, kv8, dec) = (b(0), b(1), b(2), b(3), b(4));
assert_eq!(tc_prefill_attn_gate(hgemm, exact, no_tc).is_on(), crate::engine::prefill_tc_attn(hgemm, exact, no_tc));
assert_eq!(
tc_decode_attn_gate(hgemm, exact, no_tc, kv8, dec).is_on(),
crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && !kv8 && dec
);
assert_eq!(hgemm_gate(b(0), b(1), b(2)).is_on(), crate::engine::Engine::resolve_effective_hgemm(b(0), b(1), b(2)));
let set = |name: &str| (name == "INK_NO_TC_ATTN" && no_tc) || (name == "INK_TC_ATTN_DEC" && dec);
assert_eq!(
crate::engine::split_attn(hgemm, exact, kv8, set),
crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && (kv8 || !dec)
);
}
}
#[test]
fn policy_reads_and_validates() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string())
};
assert_eq!(Policy::read(env(&[])).unwrap(), Policy::default());
let p = Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "1"), ("INK_FAST_PATH_OPT_OUT", "sparse_topk, kv_stitch")])).unwrap();
assert!(p.require);
assert_eq!(p.opt_out, ["sparse_topk", "kv_stitch"]);
assert!(Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "yes")])).unwrap_err().contains("0 or 1"));
assert!(Policy::read(env(&[("INK_FAST_PATH_OPT_OUT", "tc_attn")])).unwrap_err().contains("unknown fast path"));
}
#[test]
fn json_and_log_block_name_every_off_path() {
let mut i = Inputs::serve_default();
i.full_attn_budget = true;
i.sparse_topk = false;
let r = report(&i);
let policy = Policy::default();
let j = r.to_json(&policy);
assert_eq!(j["paths"]["sparse_topk"]["on"], false);
assert_eq!(j["paths"]["sparse_topk"]["kind"], "mode");
assert_eq!(j["paths"]["tc_attn_row_blocks"]["kind"], "missing");
assert_eq!(j["paths"]["tc_prefill_attn"]["on"], true);
assert_eq!(j["off"], 6);
assert_eq!(j["unaccepted"], serde_json::json!(["tc_attn_row_blocks", "sparse_topk"]));
let lines = r.log_lines(&policy);
assert!(lines[0].contains("6 off, 2 off without an opt-out"), "{}", lines[0]);
assert!(lines.iter().any(|l| l.contains("!! OFF sparse_topk") && l.contains("--full-attn-budget")), "{lines:?}");
assert!(lines.last().unwrap().contains("WARNING") && lines.last().unwrap().contains("sparse_topk"));
}
}