#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Switch {
pub name: &'static str,
pub default: bool,
pub what: &'static str,
}
const fn sw(name: &'static str, default: bool, what: &'static str) -> Switch {
Switch { name, default, what }
}
pub const SWITCHES: [Switch; 31] = [
sw("INK_TC_ATTN_DEC", true, "tensor-core decode attention (FP16 and KV8; KV4 off unless =1, see fast_paths)"),
sw("INK_RELEASE_SUPERSEDED_STARTS", true, "release a card's superseded approximate starts when its turn completes"),
sw("INK_MIXED_STEPS", true, "mixed prefill+decode steps: decoders ride prefill steps"),
sw("INK_MIXED_TAIL_TRIM", true, "last-layer tail trim on a mixed step's prefill spans (its decode rows kept whole)"),
sw("INK_PARALLEL_CPU_SAMPLE", true, "a step's CPU-sampled decode rows drawn on scoped threads, each lane's own RNG (same tokens)"),
sw("INK_DEC_FIXED_COST", true, "decode fixed-cost cuts: one k_mix_wave per mixer, 4 KiB sg4 GEMM ring (bit-identical)"),
sw("INK_PROMPT_LOOKUP", false, "prompt-lookup (n-gram) speculative drafting in serve (M5: output tok/s lower in both pairs)"),
sw("INK_SPARSE_PREFILL", false, "sparse top-k prefill attention past INK_SPARSE_PREFILL_MIN_CTX (slower and over the KL limit on M5)"),
sw("INK_TC_EXP2", false, "exp2 softmax in tensor-core prefill attention (KV8 only; fails the M5 confident-KL bound)"),
sw("INK_TC_LAZY_RESCALE", false, "lazy O rescale in tensor-core prefill attention (KV8 only; fails the M5 confident-KL bound)"),
sw("INK_MESSAGES_ECHO_THINKING", false, "/v1/messages renders inky's own signed thinking blocks back into the prompt (M5: cost, no benefit)"),
sw("INK_NO_TC_ATTN", false, "tensor-core attention off, prefill and decode"),
sw("INK_NO_HGEMM", false, "fp16 prefill GEMMs off"),
sw("INK_NO_TENSOR", false, "Metal 4 tensor kernels off"),
sw("INKY_DISABLE_MPP", false, "Metal 4 tensor kernels off (as --no-mpp)"),
sw("INK_OLD_MOE_DEC", false, "grouped MoE decode and decode-sized GEMMs off"),
sw("INK_OLD_MIXB", false, "concurrent batched mixer jobs off"),
sw("INK_SEP_TOPK", false, "router top-k as a separate kernel"),
sw("INK_FUSE_COMB", false, "split-attention combine fused (serve refuses it)"),
sw("INK_NO_TAIL", false, "last-layer tail trim off"),
sw("INK_NO_GRP_DEC", false, "shared-K/V grouped decode attention off"),
sw("INK_NO_GRP_MOE", false, "multi-token grouped MoE decode tiles off"),
sw("INK_NO_GEMM_DEC", false, "Metal 3 small-batch GEMMs off"),
sw("INK_GENERIC_MOE", false, "generic prefill MoE kernels for every expert format"),
sw("INK_NO_KV4_DC", false, "KV4 key DC-mean calibration off"),
sw("INK_NO_WARM", false, "skip the warm-up pass at load"),
sw("INK_KV_PREALLOC", false, "inky run: reserve the whole context up front (no cache growth)"),
sw("INK_PREFILL_CKPT_SPLIT", false, "prefill spans split at every start-point checkpoint (spans through checkpoints off)"),
sw("INK_OLD_MOE_RG", false, "grouped MoE decode class 1 on the sg4 kernels, not the register-fed ones"),
sw("INK_RETAIN_LRU", false, "retained starts evicted by plain LRU under the card lease (reuse-per-byte ranking off)"),
sw("INK_PER_SPAN_LOGITS", false, "one LM-head GEMM per span in a multi-span prefill step (batched span logits off)"),
];
pub fn parse(name: &str, value: Option<&str>) -> Result<Option<bool>, String> {
match value {
None => Ok(None),
Some("0") => Ok(Some(false)),
Some("1") => Ok(Some(true)),
Some(v) => Err(format!("{name} must be 0 or 1 (got {v:?})")),
}
}
pub fn default_of(name: &str) -> bool {
match SWITCHES.iter().find(|s| s.name == name) {
Some(s) => s.default,
None => panic!("{name} is not an on/off switch (engine::switches::SWITCHES)"),
}
}
pub fn value(name: &str, value: Option<&str>) -> bool {
parse(name, value).ok().flatten().unwrap_or_else(|| default_of(name))
}
pub fn setting(name: &str, value: Option<&str>) -> Option<bool> {
parse(name, value).ok().flatten()
}
pub fn env_setting(name: &str) -> Option<bool> {
setting(name, std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()).as_deref())
}
pub fn env(name: &str) -> bool {
value(name, std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()).as_deref())
}
pub fn check(get: impl Fn(&str) -> Option<String>) -> Result<(), String> {
let bad: Vec<String> = SWITCHES.iter().filter_map(|s| parse(s.name, get(s.name).as_deref()).err()).collect();
if bad.is_empty() {
Ok(())
} else {
Err(bad.join("; "))
}
}
pub fn check_process() -> Result<(), String> {
check(|name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
fn only(name: &'static str, v: &'static str) -> impl Fn(&str) -> Option<String> {
move |n: &str| (n == name).then(|| v.to_string())
}
#[test]
fn every_switch_is_unset_default_one_on_zero_off_and_refuses_anything_else() {
let mut names: Vec<&str> = SWITCHES.iter().map(|s| s.name).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), SWITCHES.len(), "a switch is listed twice");
for s in SWITCHES {
assert_eq!(value(s.name, None), s.default, "{} unset", s.name);
assert!(value(s.name, Some("1")), "{}=1 is on", s.name);
assert!(!value(s.name, Some("0")), "{}=0 is off", s.name);
assert!(check(only(s.name, "0")).is_ok() && check(only(s.name, "1")).is_ok(), "{}", s.name);
for bad in ["", "yes", "true", "2", " 1", "on", "off"] {
let err = check(only(s.name, bad)).unwrap_err();
assert!(err.contains(s.name) && err.contains("must be 0 or 1"), "{}={bad:?}: {err}", s.name);
}
}
assert!(check(|_| None).is_ok());
}
#[test]
fn check_names_every_bad_switch() {
let err = check(|n: &str| match n {
"INK_TC_ATTN_DEC" => Some("yes".into()),
"INK_NO_TC_ATTN" => Some(String::new()),
"INK_NO_TAIL" => Some("1".into()),
_ => None,
})
.unwrap_err();
assert!(err.contains("INK_TC_ATTN_DEC must be 0 or 1 (got \"yes\")"), "{err}");
assert!(err.contains("INK_NO_TC_ATTN must be 0 or 1 (got \"\")"), "{err}");
assert!(!err.contains("INK_NO_TAIL"), "{err}");
}
#[test]
fn performance_paths_are_on_by_default() {
for name in ["INK_TC_ATTN_DEC", "INK_RELEASE_SUPERSEDED_STARTS"] {
assert!(default_of(name), "{name}");
}
}
fn production_only(src: &str) -> String {
let mut out = String::new();
let mut lines = src.lines();
while let Some(line) = lines.next() {
let t = line.trim_start();
if t.starts_with("//") {
continue;
}
if let Some(rest) = t.strip_prefix("#[cfg(test)]") {
if !rest.trim().is_empty() {
continue;
}
let mut depth = 0i64;
let mut opened = false;
for item in lines.by_ref() {
let it = item.trim_start();
if it.starts_with("//") || it.starts_with("#[") {
continue;
}
depth += item.matches('{').count() as i64 - item.matches('}').count() as i64;
opened |= item.contains('{');
let end = item.trim_end();
if (opened && depth <= 0) || (!opened && (end.ends_with(';') || end.ends_with(','))) {
break;
}
}
continue;
}
out.push_str(line);
out.push('\n');
}
out
}
#[test]
fn production_only_drops_comments_and_test_items() {
let src = "fn a() { switches::env(\"A\"); }\n// switches::env(\"B\")\n#[cfg(test)]\nmod t {\n fn c() { switches::env(\"C\"); }\n}\n#[cfg(test)]\nmod u;\n#[cfg(test)]\nfn d() { switches::env(\"D\") }\nlet s = S {\n #[cfg(test)]\n t: switches::env(\"F\"),\n g: switches::env(\"G\"),\n};\nfn h(\n #[cfg(test)] x: u8,\n) {\n switches::env(\"H\");\n}\nfn e() {}\n";
let p = production_only(src);
assert!(p.contains("\"A\"") && p.contains("\"G\"") && p.contains("\"H\"") && p.contains("fn e()"), "{p}");
assert!(!p.contains("x: u8"), "{p}");
assert!(!p.contains("\"F\""), "{p}");
assert!(!p.contains("\"B\"") && !p.contains("\"C\"") && !p.contains("mod u") && !p.contains("\"D\""), "{p}");
}
#[test]
fn every_switch_has_a_production_reader() {
let production: Vec<String> = [
include_str!("../engine.rs"),
include_str!("model.rs"),
include_str!("sparse_prefill.rs"),
include_str!("../main.rs"),
include_str!("../serve.rs"),
]
.iter()
.map(|src| production_only(src))
.collect();
let engine_rs = &production[0];
let mpp = &engine_rs[engine_rs.find("fn effective_use_mpp_for_tuning").unwrap()..][..400];
assert!(mpp.contains("EnvFlags::from_process") && mpp.contains("env.disable_mpp, env.no_tensor"), "{mpp}");
assert!(production[1].contains("Engine::effective_use_mpp_for_tuning("), "model.rs builds use_mpp through it");
assert!(production[4].contains("live.set_mixed_tail_plans("), "serve.rs scheduler body kept");
let reorderings = &production[1];
let reorderings = reorderings[reorderings.find("let reorderings = [").unwrap()..].lines().next().unwrap();
for s in SWITCHES {
let n = s.name;
let readers = [
format!("switches::env(\"{n}\")"),
format!("switches::env_setting(\"{n}\")"),
format!("switches::value(\"{n}\""),
format!("switches::setting(\"{n}\""),
format!("ink_switch(\"{n}\""),
];
let read = production.iter().any(|src| readers.iter().any(|r| src.contains(r.as_str())))
|| matches!(n, "INK_NO_TENSOR" | "INKY_DISABLE_MPP")
|| reorderings.contains(&format!("\"{n}\""));
assert!(read, "{n} is registered but nothing in engine or serve reads it");
}
}
#[test]
#[should_panic(expected = "not an on/off switch")]
fn an_unknown_name_is_a_bug() {
default_of("INK_NOT_A_SWITCH");
}
}