inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! On/off `INK_*` switches that pick a performance path or a serve behaviour (internal experiment and dev switches,
//! AGENTS.md rule 2), parsed one way. The bench, gate and test-only switches of single subcommands (`INK_DEC`,
//! `INK_VARY`, `INK_DB_*`, `*_SABOTAGE`, `INK_NO_POISON`, `INK_PROF_KERNELS`, ...) are not in this table and keep
//! their own readers.
//!
//! Each switch takes `0` or `1`. Unset is the switch's default from [`SWITCHES`]; any other value (empty, `yes`,
//! `true`, ...) is refused: [`check`] runs before any command (`main`) and names every bad variable, so `=0` always
//! means off and `=1` always means on. Before this, several switches were read by presence (`var_os(..).is_some()`),
//! so `INK_TC_ATTN_DEC=0` turned tensor-core decode on.
//!
//! A path that is on by default has a positive switch whose `0` is its explicit opt-out (`INK_TC_ATTN_DEC=0`); the
//! older dev switches are negative (`INK_NO_TC_ATTN=1` takes a path off) and default to `0`. Flipping a default is
//! one entry in [`SWITCHES`].

/// One on/off switch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Switch {
    pub name: &'static str,
    /// The value when the variable is unset.
    pub default: bool,
    pub what: &'static str,
}

const fn sw(name: &'static str, default: bool, what: &'static str) -> Switch {
    Switch { name, default, what }
}

/// Every on/off switch the engine and serve read.
pub const SWITCHES: [Switch; 31] = [
    // performance paths that are on by default: `0` is the explicit opt-out
    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)"),
    // measured off by default (an M5 quality gate or timing pair lost with them on): `1` opts in
    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)"),
    // dev opt-outs: `1` takes a path off
    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)"),
];

/// `0` is off, `1` is on, unset is `None`; anything else is an error naming the variable.
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:?})")),
    }
}

/// The default of a switch in [`SWITCHES`].
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)"),
    }
}

/// The switch's state for `value`: unset is its default. A value [`check`] would refuse also reads as the default
/// (production never gets here with one: `main` refuses to start).
pub fn value(name: &str, value: Option<&str>) -> bool {
    parse(name, value).ok().flatten().unwrap_or_else(|| default_of(name))
}

/// The switch's explicit setting: `None` unset (or a value [`check`] refuses), else `0`/`1`. For a switch whose
/// default depends on the configuration (`INK_TC_ATTN_DEC` under `--kv4`).
pub fn setting(name: &str, value: Option<&str>) -> Option<bool> {
    parse(name, value).ok().flatten()
}

/// [`setting`] in the process environment.
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())
}

/// The switch's state in the process environment.
pub fn env(name: &str) -> bool {
    value(name, std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()).as_deref())
}

/// Every switch in [`SWITCHES`] read through `get`: `Err` names each one set to something other than `0` or `1`.
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("; "))
    }
}

/// [`check`] on the process environment.
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}");
        }
    }

    /// Every registered switch has a production reader (the flaw class of the retired `INK_FILE_REUSE`, a switch
    /// nothing honoured): a call that reads its value in engine or serve code, not only the fast-path report.
    /// `INK_NO_TENSOR` and `INKY_DISABLE_MPP` reach the engine through `EnvFlags::from_process` in
    /// `Engine::effective_use_mpp_for_tuning`; the KV8 reorderings through the `reorderings` array in `model.rs`.
    /// `src` without comment lines and without `#[cfg(test)]` items (a braced item to its closing brace, an unbraced
    /// one to its `;` or `,`; an attribute with its item on the same line drops that line only), so a reader only in test code or a comment does not count.
    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)]") {
                // on the same line as its item (`#[cfg(test)] mut x: T,`): that line alone is the item
                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('{');
                    // a braced item ends at its closing brace; an unbraced one (`mod x;`, a struct-literal field
                    // `x: Cell::new(0),`) at its `;` or `,`
                    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");
        // the scheduler loop (after `#[cfg(test)]` parameters) stays in
        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");
    }
}