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 TC_DEC_KV4_DEFAULT_OFF: &str = "off by default under --kv4: it fails the M5 defaultgate (long1600:dec0 KL 2.09 vs \
limit 0.5, max_abs 16.9 vs 6.0; with INK_TC_ATTN_DEC=0 mean KL 0.095, worst 0.450, max_abs 4.90, as v3.0.2; Stella at \
241e1355); INK_TC_ATTN_DEC=1 forces it on";
pub const fn tc_decode_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool, setting: Option<bool>, kv4: bool) -> Gate {
if let Some(false) = setting {
return Gate::Off(OffKind::OptOut, "INK_TC_ATTN_DEC=0");
}
if !hgemm {
Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
} else if exact {
Gate::Off(OffKind::Mode, "--exact: decode attention stays on the deterministic simdgroup kernels")
} else if no_tc_attn_env {
Gate::Off(OffKind::OptOut, "INK_NO_TC_ATTN")
} else if setting.is_none() && kv4 {
Gate::Off(OffKind::Default, TC_DEC_KV4_DEFAULT_OFF)
} else {
Gate::On
}
}
pub struct Exposure {
pub tc_decode_attn: std::sync::atomic::AtomicU64,
pub tc_prefill_attn: std::sync::atomic::AtomicU64,
pub tc_exp2: std::sync::atomic::AtomicU64,
pub tc_lazy_rescale: std::sync::atomic::AtomicU64,
pub sparse_prefill_passes: std::sync::atomic::AtomicU64,
pub exp2_compiled: std::sync::atomic::AtomicBool,
pub lazy_rescale_compiled: std::sync::atomic::AtomicBool,
}
pub static EXPOSURE: Exposure = Exposure {
tc_decode_attn: std::sync::atomic::AtomicU64::new(0),
tc_prefill_attn: std::sync::atomic::AtomicU64::new(0),
tc_exp2: std::sync::atomic::AtomicU64::new(0),
tc_lazy_rescale: std::sync::atomic::AtomicU64::new(0),
sparse_prefill_passes: std::sync::atomic::AtomicU64::new(0),
exp2_compiled: std::sync::atomic::AtomicBool::new(false),
lazy_rescale_compiled: std::sync::atomic::AtomicBool::new(false),
};
#[inline]
pub fn count_dispatch(pso: &str) {
use std::sync::atomic::Ordering::Relaxed;
let Some(rest) = pso.strip_prefix("k_attn_tc_") else { return };
if rest.starts_with("fixed") {
EXPOSURE.tc_prefill_attn.fetch_add(1, Relaxed);
if EXPOSURE.exp2_compiled.load(Relaxed) {
EXPOSURE.tc_exp2.fetch_add(1, Relaxed);
}
if EXPOSURE.lazy_rescale_compiled.load(Relaxed) {
EXPOSURE.tc_lazy_rescale.fetch_add(1, Relaxed);
}
} else {
EXPOSURE.tc_decode_attn.fetch_add(1, Relaxed);
}
}
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 mixed_tail_trim_gate(hgemm: bool, tail: bool, mixed_steps: bool, mixed_tail_trim: bool) -> Gate {
match tail_trim_gate(hgemm, tail) {
Gate::On => {}
Gate::Off(kind, why) => return Gate::Off(kind, why),
}
if !mixed_steps {
Gate::Off(OffKind::OptOut, "INK_MIXED_STEPS=0")
} else if !mixed_tail_trim {
Gate::Off(OffKind::OptOut, "INK_MIXED_TAIL_TRIM=0")
} else {
Gate::On
}
}
pub const fn tail_trim_step(hgemm: bool, tail: bool, mixed_tail_trim: bool, n_dec: usize, n_spans: usize, verify: bool) -> bool {
tail_trim_gate(hgemm, tail).is_on() && n_dec < n_spans && (n_dec == 0 || mixed_tail_trim) && !verify
}
pub const fn tail_trim_start(t: usize) -> usize {
if t > TAIL_MIN_T {
t - TAIL_ROWS
} else {
0
}
}
pub const fn batched_span_logits_gate(hgemm: bool, per_span_env: bool) -> Gate {
if !hgemm {
Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm): the f32 LM head is one matrix-vector product per span")
} else if per_span_env {
Gate::Off(OffKind::OptOut, "INK_PER_SPAN_LOGITS=1")
} else {
Gate::On
}
}
pub const fn span_logits_batch_step(hgemm: bool, per_span: bool, spans: usize, wanted: usize) -> bool {
batched_span_logits_gate(hgemm, per_span).is_on() && spans > 1 && wanted > 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 dec_fixed_cost_gate(dec_fixed_cost: bool) -> Gate {
if dec_fixed_cost {
Gate::On
} else {
Gate::Off(OffKind::OptOut, "INK_DEC_FIXED_COST=0")
}
}
pub const CB_CHUNK_DEFAULT: usize = 8;
pub fn cb_chunk_layers(value: Option<&str>) -> Result<usize, String> {
match value {
None => Ok(CB_CHUNK_DEFAULT),
Some(v) => v.parse().map_err(|_| format!("INK_CB_CHUNK={v:?} is not a layer count")),
}
}
pub const fn chunked_decode_commits_gate(cb_chunk: usize) -> Gate {
if cb_chunk > 0 {
Gate::On
} else {
Gate::Off(OffKind::OptOut, "INK_CB_CHUNK=0")
}
}
pub const fn parallel_cpu_sample_gate(parallel_cpu_sample: bool) -> Gate {
if parallel_cpu_sample {
Gate::On
} else {
Gate::Off(OffKind::OptOut, "INK_PARALLEL_CPU_SAMPLE=0")
}
}
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, kv8: 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 if kv8 {
Some(Gate::Off(OffKind::Default, "off by default for KV8: M5 70K sparse decode K128/A16 failed KL \
(p99.9 0.09239 vs 0.05, 5 positions above 0.05, allowed 0); --sparse-topk K opts in"))
} else {
None
}
}
fn sparse_topk_gate(i: &Inputs) -> Gate {
if i.sparse_topk {
return Gate::On;
}
let implicit_kv8 = i.kv8 && !i.serve.no_sparse_topk;
match default_sparse_topk_dropped_by(i.exact, i.full_attn_budget, implicit_kv8) {
Some(g) => g,
None => Gate::Off(OffKind::OptOut, "--sparse-topk off"),
}
}
pub const SPARSE_PREFILL_DEFAULT_OFF: &str = "off by default: on the M5 (Stella, e8bca79d, 70K production-model probe; \
72 sparse passes, 27.2% of causal blocks kept, no dense fallbacks) it was slower (prefill 62.2 s vs 54.0 s dense) and \
failed long-context KL (mean 0.01314 vs limit 0.01, max 0.58772 at token 70052 vs limit 0.10, 6 positions over 0.05); \
INK_SPARSE_PREFILL=1 opts in";
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, SPARSE_PREFILL_DEFAULT_OFF)
} 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: under --kv8 it fails the M5 TC-vs-simdgroup confident-KL bound (two confident positions \
at KL ~0.0019 vs 1e-4; with both reorderings off worst 0.017 vs the scalar reference 0.061, 48/48 top-1; \
Stella at 241e1355); 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: under --kv8 it fails the M5 TC-vs-simdgroup confident-KL bound (step 17 KL 0.01277 vs \
1e-4; with both reorderings off worst 0.017 vs the scalar reference 0.061, 48/48 top-1; Stella at \
241e1355); 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 !kv8 {
Gate::Off(OffKind::Default, "KV8 only: FP16 and KV4 keep the exact softmax order")
} else if !on_env {
Gate::Off(OffKind::Default, default_off)
} 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
}
}
pub const fn mixed_steps_gate(mixed_steps: bool) -> Gate {
if mixed_steps {
Gate::On
} else {
Gate::Off(OffKind::OptOut, "INK_MIXED_STEPS=0")
}
}
pub const fn prefill_through_checkpoints_gate(ckpt_split_env: bool) -> Gate {
if ckpt_split_env {
Gate::Off(OffKind::OptOut, "INK_PREFILL_CKPT_SPLIT=1")
} else {
Gate::On
}
}
pub const MESSAGES_ECHO_THINKING_DEFAULT_OFF: &str = "off by default: on a matched M5 pair (Stella) the echo ran (messages_thinking_echoed_total 0 -> 1) but the prompt \
grew 7,783 -> 8,014 tokens with the restored prefix unchanged at 7,680, fresh rows 103 -> 334, TTFT 120 -> 209 ms, and \
the visible answers were byte-identical: cost with no reuse or answer benefit shown; INK_MESSAGES_ECHO_THINKING=1 opts in";
pub const fn messages_echo_thinking_gate(echo_thinking: bool) -> Gate {
if echo_thinking {
Gate::On
} else {
Gate::Off(OffKind::Default, MESSAGES_ECHO_THINKING_DEFAULT_OFF)
}
}
pub const fn retain_reuse_rank_gate(retain_lru: bool) -> Gate {
if retain_lru {
Gate::Off(OffKind::OptOut, "INK_RETAIN_LRU=1")
} else {
Gate::On
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServeFlags {
pub no_sparse_topk: bool,
pub mixed_steps: bool,
pub spec_verify: bool,
pub echo_thinking: bool,
pub retain_lru: bool,
}
impl Default for ServeFlags {
fn default() -> ServeFlags {
ServeFlags {
no_sparse_topk: false,
mixed_steps: true,
spec_verify: false,
echo_thinking: crate::engine::switches::default_of("INK_MESSAGES_ECHO_THINKING"),
retain_lru: crate::engine::switches::default_of("INK_RETAIN_LRU"),
}
}
}
#[derive(Clone, Copy, Debug, 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: Option<bool>,
pub old_moe_dec: bool,
pub old_moe_rg: bool,
pub old_mixb: bool,
pub generic_moe: bool,
pub tc_exp2: bool,
pub tc_lazy_rescale: bool,
pub prefill_ckpt_split: bool,
pub per_span_logits: bool,
pub mixed_tail_trim: bool,
pub parallel_cpu_sample: bool,
pub cb_chunk: usize,
pub dec_fixed_cost: bool,
}
impl Default for EnvFlags {
fn default() -> EnvFlags {
EnvFlags::read(|_| None)
}
}
impl EnvFlags {
pub fn read(get: impl Fn(&str) -> Option<String>) -> EnvFlags {
let on = |name: &str| crate::engine::switches::value(name, get(name).as_deref());
EnvFlags {
disable_mpp: on("INKY_DISABLE_MPP"),
no_tensor: on("INK_NO_TENSOR"),
no_hgemm: on("INK_NO_HGEMM"),
no_tc_attn: on("INK_NO_TC_ATTN"),
tc_attn_dec: crate::engine::switches::setting("INK_TC_ATTN_DEC", get("INK_TC_ATTN_DEC").as_deref()),
old_moe_dec: on("INK_OLD_MOE_DEC"),
old_mixb: on("INK_OLD_MIXB"),
generic_moe: on("INK_GENERIC_MOE"),
tc_exp2: on("INK_TC_EXP2"),
tc_lazy_rescale: on("INK_TC_LAZY_RESCALE"),
prefill_ckpt_split: on("INK_PREFILL_CKPT_SPLIT"),
old_moe_rg: on("INK_OLD_MOE_RG"),
per_span_logits: on("INK_PER_SPAN_LOGITS"),
mixed_tail_trim: on("INK_MIXED_TAIL_TRIM"),
parallel_cpu_sample: on("INK_PARALLEL_CPU_SAMPLE"),
cb_chunk: cb_chunk_layers(get("INK_CB_CHUNK").as_deref()).unwrap_or(CB_CHUNK_DEFAULT),
dec_fixed_cost: on("INK_DEC_FIXED_COST"),
}
}
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 kv4: 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,
pub serve: ServeFlags,
}
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,
kv4: true,
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: crate::engine::switches::default_of("INK_SPARSE_PREFILL"),
kv_stitch: true,
lora: false,
expert_types: vec![(T_Q4_K, T_Q8_0); 2],
env: EnvFlags::default(),
serve: ServeFlags::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,
kv4: self.kv4,
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(),
serve: ServeFlags::default(),
}
}
}
#[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; 31] = [
"mpp_tensor",
"hgemm",
"tc_prefill_attn",
"tc_decode_attn",
"tail_trim",
"mixed_tail_trim",
"batched_span_logits",
"sep_comb",
"fused_topk",
"grouped_decode_attn",
"grouped_moe_decode",
"grouped_moe_tiles",
"decode_gemm",
"batched_mix",
"parallel_cpu_sample",
"chunked_decode_commits",
"dec_fixed_cost",
"moe_prefill_specialised",
"moe_decode_specialised",
"moe_decode_rg",
"tc_attn_row_blocks",
"sparse_topk",
"sparse_prefill",
"kv_stitch",
"attn_proj_plain",
"tc_exp2",
"tc_lazy_rescale",
"mixed_steps",
"prefill_through_checkpoints",
"messages_echo_thinking",
"retain_reuse_rank",
];
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(", "))
}
fn sparse_prefill_report_gate(i: &Inputs) -> Gate {
let tc_prefill = tc_prefill_attn_gate(i.hgemm, i.exact, i.env.no_tc_attn);
let sparse_topk = sparse_topk_gate(i);
match sparse_prefill_gate(i.sparse_prefill, tc_prefill.is_on(), i.sparse_topk, i.full_attn_budget) {
Gate::Off(OffKind::Mode, why) => {
let kind = match (tc_prefill, sparse_topk) {
(Gate::Off(kind, _), _) | (Gate::On, Gate::Off(kind, _)) => kind,
(Gate::On, Gate::On) => OffKind::Mode,
};
Gate::Off(kind, why)
}
g => g,
}
}
fn inherit_mode(g: Gate, prerequisite: Gate) -> Gate {
match (g, prerequisite) {
(Gate::Off(OffKind::Mode, why), Gate::Off(kind, _)) => Gate::Off(kind, why),
(g, _) => g,
}
}
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, env.tc_attn_dec, i.kv4),
));
paths.push(path("tail_trim", "last-layer tail trim (prefill, one or many spans)", tail_trim_gate(i.hgemm, i.tail)));
paths.push(path(
"mixed_tail_trim",
"last-layer tail trim on mixed steps (prefill spans trimmed, decode rows whole)",
mixed_tail_trim_gate(i.hgemm, i.tail, i.serve.mixed_steps, env.mixed_tail_trim),
));
paths.push(path(
"batched_span_logits",
"one LM-head GEMM for a multi-span prefill step's logits rows",
batched_span_logits_gate(i.hgemm, env.per_span_logits),
));
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)));
paths.push(path(
"parallel_cpu_sample",
"a step's CPU-sampled decode rows drawn on scoped threads (each lane's own RNG stream)",
parallel_cpu_sample_gate(env.parallel_cpu_sample),
));
paths.push(path(
"chunked_decode_commits",
"plain decode steps committed every INK_CB_CHUNK layers (GPU starts while the CPU encodes)",
chunked_decode_commits_gate(env.cb_chunk),
));
paths.push(path(
"dec_fixed_cost",
"decode fixed-cost cuts: one k_mix_wave per mixer, 4 KiB sg4 GEMM ring, specialised uniform multi-segment GEMMs",
dec_fixed_cost_gate(env.dec_fixed_cost),
));
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);
const RG_WHAT: &str = "register-fed MoE decode (1..=64 tokens per expert)";
let rg = if !grouped_moe_decode_gate(i.hgemm, env.old_moe_dec).is_on() {
path("moe_decode_rg", RG_WHAT, Gate::Off(OffKind::Mode, "grouped MoE decode is off (grouped_moe_decode)"))
} else if env.old_moe_rg {
path("moe_decode_rg", RG_WHAT, Gate::Off(OffKind::OptOut, "INK_OLD_MOE_RG"))
} else {
let none = |ty: u32, situ: bool| match crate::engine::moe_dec_rg_kernel(crate::engine::MOE_RG_NSG, ty, situ) {
Some(_) => "",
None => "-",
};
match generic_formats(&i.expert_types, none, "-") {
None => path("moe_decode_rg", RG_WHAT, Gate::On),
Some(fmts) => FastPath {
id: "moe_decode_rg",
what: RG_WHAT,
on: false,
kind: Some(OffKind::Missing),
reason: Some(format!("no register-fed decode MoE kernel for experts {fmts}")),
},
}
};
paths.push(rg);
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),
));
paths.push(path(
"sparse_prefill",
"sparse top-k prefill attention past INK_SPARSE_PREFILL_MIN_CTX",
sparse_prefill_report_gate(i),
));
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);
paths.push(path(
"tc_exp2",
"exp2 softmax in tensor-core prefill attention (inexact, KV8)",
inherit_mode(tc_exp2_gate(env.tc_exp2, i.kv8, tc_prefill.is_on()), tc_prefill),
));
paths.push(path(
"tc_lazy_rescale",
"lazy O rescale in tensor-core prefill attention (inexact, KV8)",
inherit_mode(tc_lazy_rescale_gate(env.tc_lazy_rescale, i.kv8, tc_prefill.is_on()), tc_prefill),
));
paths.push(path(
"mixed_steps",
"mixed prefill+decode steps (decoders ride prefill steps)",
mixed_steps_gate(i.serve.mixed_steps),
));
paths.push(path(
"prefill_through_checkpoints",
"prefill spans run through start-point checkpoints (no lone tail steps)",
prefill_through_checkpoints_gate(env.prefill_ckpt_split),
));
paths.push(path(
"messages_echo_thinking",
"/v1/messages renders inky's own thinking back (whole-reply prefix reuse)",
messages_echo_thinking_gate(i.serve.echo_thinking),
));
paths.push(path(
"retain_reuse_rank",
"retained starts evicted by reuse per byte under the card lease (not plain LRU)",
retain_reuse_rank_gate(i.serve.retain_lru),
));
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 exposure_counts_tensor_core_attention_dispatches_by_family() {
use std::sync::atomic::Ordering::Relaxed;
let before = |c: &std::sync::atomic::AtomicU64| c.load(Relaxed);
let (d0, p0) = (before(&EXPOSURE.tc_decode_attn), before(&EXPOSURE.tc_prefill_attn));
for k in ["k_attn_tc_dec", "k_attn_tc_dec_solo", "k_attn_tc_grp_dec", "k_attn_tc_sparse_dec"] {
count_dispatch(k);
}
for k in ["k_attn_tc_fixed_b", "k_attn_tc_fixed_blk"] {
count_dispatch(k);
}
for k in ["k_attn", "k_attn_dec_solo", "k_attn_grp_dec", "k_attn_sparse_dec", "k_gemm_t"] {
count_dispatch(k);
}
assert!(before(&EXPOSURE.tc_decode_attn) >= d0 + 4);
assert!(before(&EXPOSURE.tc_prefill_attn) >= p0 + 2);
}
#[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_on_but_the_measured_defaults() {
let r = report(&Inputs::serve_default());
let (kind, why) = off(&r, "sparse_prefill");
assert_eq!(kind, OffKind::Default, "sparse prefill is measured off by default");
assert!(why.contains("70052") && why.contains("INK_SPARSE_PREFILL=1"), "{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", "tc_exp2", "tc_lazy_rescale", "messages_echo_thinking"]);
let (kind, why) = off(&r, "tc_decode_attn");
assert_eq!(kind, OffKind::Default);
assert!(why.contains("defaultgate") && why.contains("INK_TC_ATTN_DEC=1"), "{why}");
for id in ["tc_exp2", "tc_lazy_rescale"] {
assert_eq!(off(&r, id).0, OffKind::Default, "{id}");
}
assert!(r.unaccepted(&Policy::default()).is_empty());
let mut i = Inputs::serve_default();
i.kv8 = true;
i.kv4 = !i.kv8;
let r = report(&i);
let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
assert_eq!(offs, ["sparse_prefill", "tc_exp2", "tc_lazy_rescale", "messages_echo_thinking"]);
assert!(r.unaccepted(&Policy::default()).is_empty());
}
#[test]
fn sparse_prefill_is_measured_off_by_default_and_names_what_blocks_it_when_asked() {
let mut i = Inputs::serve_default();
assert!(!i.sparse_prefill, "INK_SPARSE_PREFILL defaults to off");
let r = report(&i);
assert_eq!(off(&r, "sparse_prefill"), (OffKind::Default, SPARSE_PREFILL_DEFAULT_OFF.into()));
assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
i.sparse_prefill = true;
assert!(on(&report(&i), "sparse_prefill"));
i.env.no_tc_attn = true;
let (kind, why) = off(&report(&i), "sparse_prefill");
assert_eq!(kind, OffKind::OptOut);
assert!(why.contains("tc_prefill_attn"), "{why}");
assert!(report(&i).unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
i.env.no_tc_attn = false;
i.exact = true;
assert_eq!(off(&report(&i), "sparse_prefill").0, OffKind::Mode, "--exact is a mode");
i.exact = false;
i.sparse_topk = false;
let (kind, why) = off(&report(&i), "sparse_prefill");
assert_eq!(kind, OffKind::OptOut, "--no-sparse-topk is the user's choice");
assert!(why.contains("--sparse-topk"), "{why}");
i.full_attn_budget = true;
let (kind, why) = off(&report(&i), "sparse_prefill");
assert_eq!(kind, OffKind::Mode);
assert!(why.contains("--sparse-topk"), "{why}");
i.sparse_topk = true;
assert!(off(&report(&i), "sparse_prefill").1.contains("--full-attn-budget"));
}
#[test]
fn tc_decode_is_on_by_default_for_kv8_and_fp16_off_for_kv4_and_switchable() {
for (kv4, kv8) in [(true, false), (false, true), (false, false)] {
let mut i = Inputs::serve_default();
i.kv8 = kv8;
i.kv4 = kv4;
let r = report(&i);
assert!(on(&r, "tc_prefill_attn"), "kv4={kv4} kv8={kv8}: #234: KV8 prefill is on the tensor cores");
if kv4 {
assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default, "KV4: off by default (M5 defaultgate)");
} else {
assert!(on(&r, "tc_decode_attn"), "kv8={kv8}: on by default");
}
assert!(r.unaccepted(&Policy::default()).is_empty());
i.env = EnvFlags::read(|name| (name == "INK_TC_ATTN_DEC").then(|| "0".to_string()));
let r = report(&i);
assert_eq!(off(&r, "tc_decode_attn"), (OffKind::OptOut, "INK_TC_ATTN_DEC=0".into()), "kv4={kv4} kv8={kv8}");
assert!(on(&r, "tc_prefill_attn"), "kv8={kv8}: the decode opt-out leaves prefill alone");
assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
for v in ["1"] {
i.env = EnvFlags::read(|name| (name == "INK_TC_ATTN_DEC").then(|| v.to_string()));
assert!(on(&report(&i), "tc_decode_attn"), "kv4={kv4} kv8={kv8}: INK_TC_ATTN_DEC={v:?} forces it on");
}
}
}
#[test]
fn tc_softmax_reorderings_are_measured_off_kv8_opt_ins_and_stay_off_elsewhere() {
for (id, env) in [("tc_exp2", "INK_TC_EXP2"), ("tc_lazy_rescale", "INK_TC_LAZY_RESCALE")] {
assert!(!crate::engine::switches::default_of(env), "{env} is off by default (M5 confident-KL bound)");
let mut i = Inputs::serve_default();
i.kv8 = true;
i.kv4 = !i.kv8;
for v in [None, Some("0")] {
i.env = EnvFlags::read(|name| if name == env { v.map(str::to_string) } else { None });
let r = report(&i);
let (kind, why) = off(&r, id);
assert_eq!(kind, OffKind::Default, "{id} {v:?}: a measured default");
assert!(why.contains("confident-KL") && why.contains(&format!("{env}=1")), "{id}: {why}");
assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty(), "{id}");
}
i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
assert!(on(&report(&i), id), "{id}: {env}=1 under --kv8 opts in");
for v in [None, Some("1")] {
i.env = EnvFlags::read(|name| if name == env { v.map(str::to_string) } else { None });
i.kv8 = false;
i.kv4 = !i.kv8;
let r = report(&i);
let (kind, why) = off(&r, id);
assert_eq!(kind, OffKind::Default, "{id} {v:?}");
assert!(why.contains("KV8 only"), "{id}: {why}");
assert!(r.unaccepted(&Policy::default()).is_empty(), "{id} {v:?}");
i.kv8 = true;
i.kv4 = !i.kv8;
}
i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
i.env.no_tc_attn = true;
let (kind, why) = off(&report(&i), id);
assert_eq!(kind, OffKind::OptOut, "{id}");
assert!(why.contains("tc_prefill_attn"), "{id}: {why}");
i.env.no_tc_attn = false;
i.exact = true;
assert_eq!(off(&report(&i), id).0, OffKind::Mode, "{id}: --exact");
}
}
#[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}");
}
let (kind, why) = off(&r, "tc_decode_attn");
assert_eq!(kind, OffKind::Mode);
assert!(why.contains("--exact"), "{why}");
let ids: Vec<&str> = r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect();
assert_eq!(ids, ["tc_prefill_attn", "tc_decode_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 sparse_decode_default_and_explicit_choices_are_reported() {
assert!(default_sparse_topk_dropped_by(false, 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);
i.kv4 = false;
i.kv8 = true;
let r = report(&i);
let (kind, why) = off(&r, "sparse_topk");
assert_eq!(kind, OffKind::Default);
assert!(why.contains("0.09239"));
assert!(r.unaccepted(&Policy::default()).iter().all(|p| p.id != "sparse_topk"));
i.serve.no_sparse_topk = true;
assert_eq!(off(&report(&i), "sparse_topk").0, OffKind::OptOut);
i.serve.no_sparse_topk = false;
i.sparse_topk = true;
assert!(on(&report(&i), "sparse_topk"));
}
#[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", "messages_echo_thinking"]);
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", "mixed_tail_trim", "grouped_moe_decode", "moe_prefill_specialised", "moe_decode_specialised", "moe_decode_rg"] {
assert_eq!(off(&r, id).0, OffKind::Mode, "{id}");
}
}
#[test]
fn batched_span_logits_needs_hgemm_several_spans_and_a_wanted_row() {
assert!(batched_span_logits_gate(true, false).is_on());
assert_eq!(batched_span_logits_gate(true, true), Gate::Off(OffKind::OptOut, "INK_PER_SPAN_LOGITS=1"));
assert!(matches!(batched_span_logits_gate(false, false), Gate::Off(OffKind::Mode, _)));
assert!(span_logits_batch_step(true, false, 2, 1));
assert!(!span_logits_batch_step(true, false, 1, 1), "one span writes ar.logits");
assert!(!span_logits_batch_step(true, false, 5, 0), "no span reads logits");
assert!(!span_logits_batch_step(true, true, 5, 5));
assert!(!span_logits_batch_step(false, false, 5, 5));
let read = EnvFlags::read(|n| (n == "INK_PER_SPAN_LOGITS").then(|| "1".to_string()));
assert!(read.per_span_logits);
let mut i = Inputs::serve_default();
assert!(report(&i).paths.iter().any(|p| p.id == "batched_span_logits" && p.on));
i.env.per_span_logits = true;
assert!(report(&i).paths.iter().any(|p| p.id == "batched_span_logits" && p.kind == Some(OffKind::OptOut)));
}
#[test]
fn tail_trim_step_is_the_gate_on_prefill_and_mixed_steps() {
for (hgemm, tail) in [(true, true), (true, false), (false, true), (false, false)] {
let on = tail_trim_gate(hgemm, tail).is_on();
for mixed_tail in [true, false] {
assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 0, 3, false), on, "a prefill step");
assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 0, 1, false), on, "a one-span prefill step");
assert!(!tail_trim_step(hgemm, tail, mixed_tail, 3, 3, false), "a decode step");
assert!(!tail_trim_step(hgemm, tail, mixed_tail, 0, 3, true), "verify needs every row");
assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 2, 3, false), on && mixed_tail, "a mixed step");
assert!(!tail_trim_step(hgemm, tail, mixed_tail, 2, 3, true));
}
}
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}");
}
assert_eq!(off(&r, "tc_decode_attn"), (OffKind::OptOut, "INK_NO_TC_ATTN".into()));
i.env.tc_attn_dec = Some(false);
assert_eq!(off(&report(&i), "tc_decode_attn"), (OffKind::OptOut, "INK_TC_ATTN_DEC=0".into()));
}
#[test]
fn mixed_tail_trim_is_on_by_default_and_opts_out_by_name() {
let mut i = Inputs::serve_default();
assert!(EnvFlags::default().mixed_tail_trim, "on by default");
assert!(on(&report(&i), "mixed_tail_trim"));
i.env = EnvFlags::read(|n| (n == "INK_MIXED_TAIL_TRIM").then(|| "0".to_string()));
assert!(!i.env.mixed_tail_trim);
assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_MIXED_TAIL_TRIM=0".into()));
assert!(on(&report(&i), "tail_trim"), "the prefill steps' trim stays on");
assert!(report(&i).unaccepted(&Policy::default()).is_empty());
let mut i = Inputs::serve_default();
i.serve.mixed_steps = false;
assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_MIXED_STEPS=0".into()));
let mut i = Inputs::serve_default();
i.tail = false;
assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_NO_TAIL".into()));
i.hgemm = false;
assert_eq!(off(&report(&i), "mixed_tail_trim").0, OffKind::Mode);
}
#[test]
fn mixed_steps_are_on_by_default_opt_out_by_name_and_on_under_speculative_verify() {
let mut i = Inputs::serve_default();
assert!(on(&report(&i), "mixed_steps"));
i.serve.mixed_steps = false;
assert_eq!(off(&report(&i), "mixed_steps"), (OffKind::OptOut, "INK_MIXED_STEPS=0".into()));
assert!(report(&i).unaccepted(&Policy::default()).is_empty());
i.serve = ServeFlags { spec_verify: true, ..ServeFlags::default() };
assert!(on(&report(&i), "mixed_steps"));
}
#[test]
fn prefill_through_checkpoints_is_on_and_the_split_is_a_named_opt_out() {
let mut i = Inputs::serve_default();
assert!(on(&report(&i), "prefill_through_checkpoints"));
i.env = EnvFlags::read(|name| (name == "INK_PREFILL_CKPT_SPLIT").then(|| "1".to_string()));
let r = report(&i);
assert_eq!(off(&r, "prefill_through_checkpoints"), (OffKind::OptOut, "INK_PREFILL_CKPT_SPLIT=1".into()));
assert!(r.unaccepted(&Policy::default()).is_empty());
i.env = EnvFlags::read(|name| (name == "INK_PREFILL_CKPT_SPLIT").then(|| "0".to_string()));
assert!(on(&report(&i), "prefill_through_checkpoints"));
}
#[test]
fn dec_fixed_cost_is_on_by_default_and_opts_out_by_name() {
let mut i = Inputs::serve_default();
assert!(EnvFlags::default().dec_fixed_cost, "on by default");
assert!(on(&report(&i), "dec_fixed_cost"));
i.env = EnvFlags::read(|n| (n == "INK_DEC_FIXED_COST").then(|| "0".to_string()));
assert_eq!(off(&report(&i), "dec_fixed_cost"), (OffKind::OptOut, "INK_DEC_FIXED_COST=0".into()));
assert!(report(&i).unaccepted(&Policy::default()).is_empty());
}
#[test]
fn chunked_decode_commits_are_on_by_default_and_opt_out_at_zero() {
assert_eq!(cb_chunk_layers(None), Ok(CB_CHUNK_DEFAULT));
assert!(CB_CHUNK_DEFAULT > 0);
assert_eq!(cb_chunk_layers(Some("0")), Ok(0));
assert_eq!(cb_chunk_layers(Some("4")), Ok(4));
assert!(cb_chunk_layers(Some("yes")).unwrap_err().contains("INK_CB_CHUNK"));
let mut i = Inputs::serve_default();
assert_eq!(EnvFlags::default().cb_chunk, CB_CHUNK_DEFAULT, "on by default");
assert!(on(&report(&i), "chunked_decode_commits"));
i.env = EnvFlags::read(|n| (n == "INK_CB_CHUNK").then(|| "0".to_string()));
assert_eq!(off(&report(&i), "chunked_decode_commits"), (OffKind::OptOut, "INK_CB_CHUNK=0".into()));
assert!(report(&i).unaccepted(&Policy::default()).is_empty());
}
#[test]
fn parallel_cpu_sample_is_on_by_default_and_opts_out_by_name() {
let mut i = Inputs::serve_default();
assert!(EnvFlags::default().parallel_cpu_sample, "on by default");
assert!(on(&report(&i), "parallel_cpu_sample"));
i.env = EnvFlags::read(|n| (n == "INK_PARALLEL_CPU_SAMPLE").then(|| "0".to_string()));
assert_eq!(off(&report(&i), "parallel_cpu_sample"), (OffKind::OptOut, "INK_PARALLEL_CPU_SAMPLE=0".into()));
assert!(report(&i).unaccepted(&Policy::default()).is_empty());
}
#[test]
fn old_moe_rg_is_a_named_opt_out_under_grouped_decode() {
let mut i = Inputs::serve_default();
assert!(on(&report(&i), "moe_decode_rg"));
i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_RG").then(|| "1".to_string()));
assert_eq!(off(&report(&i), "moe_decode_rg"), (OffKind::OptOut, "INK_OLD_MOE_RG".into()));
assert!(on(&report(&i), "grouped_moe_decode"));
i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_RG").then(|| "0".to_string()));
assert!(on(&report(&i), "moe_decode_rg"));
i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_DEC").then(|| "1".to_string()));
assert_eq!(off(&report(&i), "moe_decode_rg").0, OffKind::Mode);
}
#[test]
fn retain_reuse_rank_is_on_and_lru_is_a_named_opt_out() {
let mut i = Inputs::serve_default();
assert!(on(&report(&i), "retain_reuse_rank"));
i.serve.retain_lru = true;
let r = report(&i);
assert_eq!(off(&r, "retain_reuse_rank"), (OffKind::OptOut, "INK_RETAIN_LRU=1".into()));
assert!(r.unaccepted(&Policy::default()).is_empty());
}
#[test]
fn messages_echo_thinking_is_measured_off_by_default_and_1_opts_in() {
let mut i = Inputs::serve_default();
assert!(!i.serve.echo_thinking, "INK_MESSAGES_ECHO_THINKING defaults to off");
let r = report(&i);
let (kind, why) = off(&r, "messages_echo_thinking");
assert_eq!(kind, OffKind::Default);
assert!(why.contains("TTFT") && why.contains("INK_MESSAGES_ECHO_THINKING=1"), "{why}");
assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
i.serve.echo_thinking = true;
assert!(on(&report(&i), "messages_echo_thinking"));
}
#[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}");
let (kind, why) = off(&r, "moe_decode_rg");
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}");
i.expert_types = vec![(T_Q4_K, T_Q8_0), (T_Q4_K, T_Q5_0)];
assert!(on(&report(&i), "moe_decode_rg"));
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..16 {
let b = |n: u32| bits & (1 << n) != 0;
let (hgemm, exact, no_tc, kv4) = (b(0), b(1), b(2), b(3));
assert_eq!(tc_prefill_attn_gate(hgemm, exact, no_tc).is_on(), crate::engine::prefill_tc_attn(hgemm, exact, no_tc));
assert_eq!(hgemm_gate(b(0), b(1), b(2)).is_on(), crate::engine::Engine::resolve_effective_hgemm(b(0), b(1), b(2)));
for (dec, v) in [(None, None), (Some(true), Some("1")), (Some(false), Some("0"))] {
let want = crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && dec.unwrap_or(!kv4);
assert_eq!(tc_decode_attn_gate(hgemm, exact, no_tc, dec, kv4).is_on(), want, "kv4={kv4} {dec:?}");
let get = |name: &str| match name {
"INK_NO_TC_ATTN" => no_tc.then(|| "1".to_string()),
"INK_TC_ATTN_DEC" => v.map(str::to_string),
_ => None,
};
assert_eq!(crate::engine::tc_dec_attn(hgemm, exact, kv4, get), want);
assert_eq!(
crate::engine::split_attn(hgemm, exact, kv4, get),
crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && !want
);
}
}
}
#[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["paths"]["sparse_prefill"]["kind"], "default_off");
assert_eq!(j["off"], 7);
assert_eq!(j["unaccepted"], serde_json::json!(["tc_attn_row_blocks", "sparse_topk"]));
let lines = r.log_lines(&policy);
assert!(lines[0].contains("7 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"));
}
}