inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
// `ServePoolBudget::compute` against the saved-work host budget (`INK_MAX_RETAINED_HOST_BYTES`). Host and GPU memory
// are the same physical memory on Apple silicon, so the K/V pool's budget gives up the host budget the cache will
// really fill, and model + margin + lanes + host budget + pool fits the working set, which on a tuned machine is the
// wired limit. Pure arithmetic: no engine, no Metal, no clock.

const POOL_BUDGET_GIB: u64 = 1 << 30;
const POOL_BUDGET_MIB: u64 = 1 << 20;
/// Model and scratch, 20.21 GiB, and each lane's non-KV buffers. The M5 Max run below reported a model of about 20.2;
/// what the pool it wired pins down is the sum of model, scratch and 24 lanes' buffers, 20.35 GiB. The split between
/// them was not recorded, so the lane term is a round figure and the model term is the rest.
const POOL_BUDGET_MODEL_AND_SCRATCH_BYTES: u64 = 21_698_183_168;
const POOL_BUDGET_LANE_NON_KV_BYTES: u64 = 6 * POOL_BUDGET_MIB;
/// `--kv8` paged per-lane reserve at `-c 131072`, about 0.6 GiB: lane admission's divisor, never close to binding here.
const POOL_BUDGET_LANE_RESERVE_BYTES: u64 = 640 * POOL_BUDGET_MIB;
/// tunings/m5-max-128gb.tuning and tunings/m5-pro-64gb.tuning as they stood on 2026-12-02: `wired_limit_mb`, and
/// `lane_margin_gib` in bytes.
const POOL_BUDGET_M5_MAX_128GB: (u64, u64) = (118_000, 4 * POOL_BUDGET_GIB);
const POOL_BUDGET_M5_PRO_64GB: (u64, u64) = (57_344, 4 * POOL_BUDGET_GIB);

/// The budget as `serve` computes it under `--kv8`, with Metal recommending `wired_limit_mb` as its working set.
fn pool_budget_for(
    (wired_limit_mb, margin_bytes): (u64, u64),
    lanes: usize,
    max_retained_host_bytes: Option<u64>,
    kv_pool_bytes: Option<u64>,
) -> ServePoolBudget {
    ServePoolBudget::compute(
        wired_limit_mb * POOL_BUDGET_MIB,
        POOL_BUDGET_MODEL_AND_SCRATCH_BYTES,
        margin_bytes,
        POOL_BUDGET_LANE_RESERVE_BYTES,
        crate::blocks::KVB_KV8,
        lanes,
        |lanes| lanes as u64 * POOL_BUDGET_LANE_NON_KV_BYTES,
        false,
        max_retained_host_bytes,
        kv_pool_bytes,
    )
    .unwrap()
}

/// Everything the plan asks the machine to hold at once.
fn pool_budget_sum(b: &ServePoolBudget) -> u64 {
    b.budget.model_bytes
        + b.budget.safety_headroom_bytes
        + b.effective_lanes as u64 * POOL_BUDGET_LANE_NON_KV_BYTES
        + b.retained_host_budget_bytes
        + b.kv_pool_budget_bytes
}

/// What is left for the pool and the host budget together once model, margin and lanes are taken out.
fn pool_budget_left((wired_limit_mb, margin_bytes): (u64, u64), lanes: usize) -> u64 {
    wired_limit_mb * POOL_BUDGET_MIB
        - margin_bytes
        - POOL_BUDGET_MODEL_AND_SCRATCH_BYTES
        - lanes as u64 * POOL_BUDGET_LANE_NON_KV_BYTES
}

#[test]
fn auto_kv_pool_gives_up_the_host_retention_override_on_the_m5_max() {
    // 2026-12-02, M5 Max 128 GB: `serve --kv8 -c 131072 --lanes 24`, INK_MAX_RETAINED_HOST_BYTES=28GiB, no
    // INK_KV_POOL_BYTES. The pool came out at 97,050,951,680 B, everything left less the 512 MiB recommended carve,
    // and the machine was at 4% free memory and in swap within a minute.
    let wired_limit_bytes = POOL_BUDGET_M5_MAX_128GB.0 * POOL_BUDGET_MIB;
    let left = pool_budget_left(POOL_BUDGET_M5_MAX_128GB, 24);
    assert_eq!(left - 512 * POOL_BUDGET_MIB, 97_050_951_680, "these inputs are that run's");
    // With the 28 GiB the cache was allowed beside it, that plan came to 142.7 GiB on a machine with 128.
    let plan_of_the_run = wired_limit_bytes - 512 * POOL_BUDGET_MIB + 28 * POOL_BUDGET_GIB;
    assert_eq!(plan_of_the_run, 153_259_868_160);
    assert!(plan_of_the_run > 128 * POOL_BUDGET_GIB);

    let b = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, Some(28 * POOL_BUDGET_GIB), None);
    assert_eq!(b.effective_lanes, 24);
    assert_eq!(b.retained_host_budget_bytes, 28 * POOL_BUDGET_GIB);
    assert_eq!(b.kv_pool_budget_bytes, 67_523_051_520, "62.89 GiB: everything left less the 28 GiB the cache may fill");
    assert_eq!(b.kv_pool_budget_bytes, left - 28 * POOL_BUDGET_GIB);
    assert!(
        pool_budget_sum(&b) <= wired_limit_bytes,
        "model + margin + lanes + host budget + pool is {} B, over the {wired_limit_bytes} B wired limit",
        pool_budget_sum(&b)
    );
    assert_eq!(pool_budget_sum(&b), wired_limit_bytes, "and the automatic pool leaves nothing unassigned");
    assert_eq!(b.assigned_bytes(), pool_budget_sum(&b));
}

#[test]
fn auto_kv_pool_gives_up_the_host_retention_override_on_the_mini() {
    // The mini's shape: M5 Pro 64 GB, 12 lanes, an 8 GiB host budget. Without the fix the pool takes 31.22 GiB and
    // the plan comes to 63.5 GiB on a machine with 64.
    let wired_limit_bytes = POOL_BUDGET_M5_PRO_64GB.0 * POOL_BUDGET_MIB;
    let left = pool_budget_left(POOL_BUDGET_M5_PRO_64GB, 12);
    assert_eq!(left - 512 * POOL_BUDGET_MIB, 33_524_023_296);

    let b = pool_budget_for(POOL_BUDGET_M5_PRO_64GB, 12, Some(8 * POOL_BUDGET_GIB), None);
    assert_eq!(b.effective_lanes, 12);
    assert_eq!(b.retained_host_budget_bytes, 8 * POOL_BUDGET_GIB);
    assert_eq!(b.kv_pool_budget_bytes, 25_470_959_616, "23.72 GiB");
    assert_eq!(b.kv_pool_budget_bytes, left - 8 * POOL_BUDGET_GIB);
    assert_eq!(pool_budget_sum(&b), wired_limit_bytes);
}

#[test]
fn auto_kv_pool_without_an_override_is_what_it_was() {
    // No INK_MAX_RETAINED_HOST_BYTES: the pool gives up the recommended carve, as it always has. On the M5 Max that
    // is the 97,050,951,680 B pool, which then sits beside a 512 MiB host budget instead of a 28 GiB one.
    let max = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, None, None);
    assert_eq!(max.retained_host_budget_bytes, 512 * POOL_BUDGET_MIB);
    assert_eq!(max.kv_pool_budget_bytes, 97_050_951_680);
    assert_eq!(pool_budget_sum(&max), POOL_BUDGET_M5_MAX_128GB.0 * POOL_BUDGET_MIB);
    let mini = pool_budget_for(POOL_BUDGET_M5_PRO_64GB, 12, None, None);
    assert_eq!(mini.retained_host_budget_bytes, 512 * POOL_BUDGET_MIB);
    assert_eq!(mini.kv_pool_budget_bytes, 33_524_023_296);
    assert_eq!(pool_budget_sum(&mini), POOL_BUDGET_M5_PRO_64GB.0 * POOL_BUDGET_MIB);

    // Below 16 GiB left the carve is 1/32 of it, never under 16 MiB; the pool is the rest.
    let model_and_scratch_mb = POOL_BUDGET_MODEL_AND_SCRATCH_BYTES.div_ceil(POOL_BUDGET_MIB);
    for (left_mb, carve_mb) in [(8192, 256), (1024, 32), (256, 16)] {
        let carve_bytes = carve_mb * POOL_BUDGET_MIB;
        let machine = (model_and_scratch_mb + 6 + 4096 + left_mb, 4 * POOL_BUDGET_GIB);
        let left = pool_budget_left(machine, 1);
        assert_eq!(ServeBlockCache::recommended_host_budget_bytes(left), carve_bytes, "left_mb={left_mb}");
        let b = pool_budget_for(machine, 1, None, None);
        assert_eq!(b.retained_host_budget_bytes, carve_bytes, "left_mb={left_mb}");
        assert_eq!(b.kv_pool_budget_bytes, left - carve_bytes, "left_mb={left_mb}");
    }
}

#[test]
fn explicit_kv_pool_cap_is_held_to_what_the_host_retention_leaves() {
    let wired_limit_bytes = POOL_BUDGET_M5_MAX_128GB.0 * POOL_BUDGET_MIB;
    let override_28 = Some(28 * POOL_BUDGET_GIB);
    // A cap that fits under the corrected automatic pool (62.89 GiB) is taken as given.
    let fits = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, override_28, Some(56 * POOL_BUDGET_GIB));
    assert_eq!(fits.effective_lanes, 24);
    assert_eq!(fits.kv_pool_budget_bytes, 56 * POOL_BUDGET_GIB);
    assert_eq!(wired_limit_bytes - pool_budget_sum(&fits), 67_523_051_520 - 56 * POOL_BUDGET_GIB);
    // A cap above it used to be held only to the uncorrected 90.39 GiB: 64 GiB of pool beside 28 GiB of host budget
    // is 1.1 GiB over the wired limit. It is now held to the corrected figure.
    let held = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, override_28, Some(64 * POOL_BUDGET_GIB));
    assert_eq!(held.effective_lanes, 24);
    assert_eq!(held.kv_pool_budget_bytes, 67_523_051_520);
    assert_eq!(pool_budget_sum(&held), wired_limit_bytes);
    // Without an override a cap is held to the same automatic pool as before.
    let plain = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, None, Some(100 * POOL_BUDGET_GIB));
    assert_eq!(plain.kv_pool_budget_bytes, 97_050_951_680);
    let plain_56 = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, None, Some(56 * POOL_BUDGET_GIB));
    assert_eq!(plain_56.kv_pool_budget_bytes, 56 * POOL_BUDGET_GIB);
}

#[test]
fn pool_and_host_retention_fit_the_wired_limit_on_every_tuning() {
    let machines = [("Apple M5 Max", 128u64), ("Apple M5 Pro", 64), ("Apple M3 Ultra", 192), ("Apple M3 Ultra", 512)];
    let overrides = [None, Some(64 * POOL_BUDGET_MIB), Some(8 * POOL_BUDGET_GIB), Some(28 * POOL_BUDGET_GIB)];
    let caps = [None, Some(20 * POOL_BUDGET_GIB), Some(56 * POOL_BUDGET_GIB), Some(1024 * POOL_BUDGET_GIB)];
    for (chip, memory_gib) in machines {
        let tuning = crate::tuning::select(chip, memory_gib << 30);
        assert_ne!(tuning.name, "default", "{chip} {memory_gib} GB has a tuning file");
        let machine = (tuning.wired_limit_mb, (tuning.lane_margin_gib * POOL_BUDGET_GIB as f64).round() as u64);
        let wired_limit_bytes = tuning.wired_limit_mb * POOL_BUDGET_MIB;
        for lanes in [1usize, 12, 24, 48] {
            let left = pool_budget_left(machine, lanes);
            for retained in overrides {
                for cap in caps {
                    let at = format!("{} lanes={lanes} retained={retained:?} cap={cap:?}", tuning.name);
                    let b = pool_budget_for(machine, lanes, retained, cap);
                    assert_eq!(b.effective_lanes, lanes, "{at}");
                    let host = retained.unwrap_or(ServeBlockCache::recommended_host_budget_bytes(left));
                    assert_eq!(b.retained_host_budget_bytes, host, "{at}");
                    assert_eq!(b.auto_kv_pool_budget_bytes, left - host, "{at}");
                    assert_eq!(b.kv_pool_budget_bytes, cap.map_or(left - host, |c| c.min(left - host)), "{at}");
                    assert!(pool_budget_sum(&b) <= wired_limit_bytes, "{at}: {} B", pool_budget_sum(&b));
                }
            }
        }
    }
}

#[test]
fn host_retention_larger_than_what_is_left_leaves_no_pool() {
    // The mini has 31.72 GiB left for pool and host budget. A 48 GiB host budget cannot be met, so the pool's budget
    // is zero, which the pool sizing refuses at startup; the plan never hides the excess behind a pool it cannot
    // afford, with or without an explicit cap.
    let wired_limit_bytes = POOL_BUDGET_M5_PRO_64GB.0 * POOL_BUDGET_MIB;
    for cap in [None, Some(20 * POOL_BUDGET_GIB)] {
        let b = pool_budget_for(POOL_BUDGET_M5_PRO_64GB, 12, Some(48 * POOL_BUDGET_GIB), cap);
        assert_eq!(b.retained_host_budget_bytes, 48 * POOL_BUDGET_GIB);
        assert_eq!(b.auto_kv_pool_budget_bytes, 0, "cap={cap:?}");
        assert_eq!(b.kv_pool_budget_bytes, 0, "cap={cap:?}");
        assert_eq!(b.assigned_bytes() - wired_limit_bytes, 48 * POOL_BUDGET_GIB - 34_060_894_208);
    }
}

#[test]
fn startup_line_shows_every_term_of_the_memory_budget() {
    let m5_max = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, Some(28 * POOL_BUDGET_GIB), None);
    assert_eq!(
        m5_max.breakdown_line(),
        "[serve] memory budget: model+scratch 20.21 GiB + margin 4.00 GiB + 24 lanes 0.14 GiB + host retention 28.00 GiB (INK_MAX_RETAINED_HOST_BYTES) + KV pool budget 62.89 GiB (automatic) = 115.23 GiB of the 115.23 GiB Metal working set (0.00 GiB unassigned)"
    );
    let mini = pool_budget_for(POOL_BUDGET_M5_PRO_64GB, 12, None, Some(20 * POOL_BUDGET_GIB));
    assert_eq!(
        mini.breakdown_line(),
        "[serve] memory budget: model+scratch 20.21 GiB + margin 4.00 GiB + 12 lanes 0.07 GiB + host retention 0.50 GiB (default) + KV pool budget 20.00 GiB (INK_KV_POOL_BYTES) = 44.78 GiB of the 56.00 GiB Metal working set (11.22 GiB unassigned)"
    );
    let held = pool_budget_for(POOL_BUDGET_M5_MAX_128GB, 24, Some(28 * POOL_BUDGET_GIB), Some(64 * POOL_BUDGET_GIB));
    assert_eq!(
        held.breakdown_line(),
        "[serve] memory budget: model+scratch 20.21 GiB + margin 4.00 GiB + 24 lanes 0.14 GiB + host retention 28.00 GiB (INK_MAX_RETAINED_HOST_BYTES) + KV pool budget 62.89 GiB (INK_KV_POOL_BYTES 64.00 GiB held to what is left) = 115.23 GiB of the 115.23 GiB Metal working set (0.00 GiB unassigned)"
    );
    let over = pool_budget_for(POOL_BUDGET_M5_PRO_64GB, 12, Some(48 * POOL_BUDGET_GIB), None);
    assert_eq!(
        over.breakdown_line(),
        "[serve] memory budget: model+scratch 20.21 GiB + margin 4.00 GiB + 12 lanes 0.07 GiB + host retention 48.00 GiB (INK_MAX_RETAINED_HOST_BYTES) + KV pool budget 0.00 GiB (automatic) = 72.28 GiB over the 56.00 GiB Metal working set by 16.28 GiB"
    );
}

/// `INK_KV_WINDOW_PCT` moves the window/full split of a 64 GiB `--kv8` pool (`INK_KV_POOL_BYTES=64GiB`, 24 lanes at
/// `-c 262144`, default `--sparse-topk` so each full slot carries its sketch): the window share grows with the percentage, full slots give up the bytes, and the pool stays inside
/// its budget. 15 is the tuning default, so the first row is the split every run has had.
#[test]
fn kv_window_pct_override_moves_the_64gib_kv8_pool_split() {
    use crate::blocks::{BlockKind, KvMode, KVB_KV8};
    let budget = 64 * POOL_BUDGET_GIB;
    let split = |pct: u64| {
        Engine::plan_serve_block_pools_for(budget, KVB_KV8, 4096, 262_144, 24, 32 * POOL_BUDGET_GIB, pct, true, true)
            .unwrap()
    };
    let mode = KvMode::from_kvb_tag(KVB_KV8).unwrap();
    for (pct, want) in [(15, (1_966, 54_796)), (25, (3_276, 48_353)), (30, (3_932, 45_126))] {
        let (n_window, n_full) = split(pct);
        assert_eq!((n_window, n_full), want, "pct={pct}");
        let full_slot_bytes = Engine::effective_full_slot_bytes(KVB_KV8, true).unwrap();
        let bytes = n_window as u64 * mode.stride_bytes(BlockKind::Window) + n_full as u64 * full_slot_bytes;
        assert!(bytes <= budget, "pct={pct}: {bytes} > {budget}");
    }
    assert_eq!(split(effective_kv_window_pct(None, 15)), (1_966, 54_796), "unset keeps the tuning's split");
}

/// Shares above the tuning files' old 45% ceiling reach both planners: the automatic one (`kv_pool_bytes` unset) and
/// the explicit-cap one (`INK_KV_POOL_BYTES`). 60% gives more window slots than 45%, the pool stays inside its budget,
/// and even 99% keeps each planner's full-slot floor. A return of either `clamp(1, 45)` makes 60 equal 45 and fails.
#[test]
fn kv_window_pct_above_45_reaches_auto_and_explicit_planners() {
    use crate::blocks::{BlockKind, KvMode, KVB_KV8, MIN_ROLLOVER_WINDOW_SLOTS};
    let budget = 64 * POOL_BUDGET_GIB;
    let (chunk, ctx, lanes, slab) = (4096, 262_144, 24, 32 * POOL_BUDGET_GIB);
    let mode = KvMode::from_kvb_tag(KVB_KV8).unwrap();
    let full_slot_bytes = Engine::effective_full_slot_bytes(KVB_KV8, true).unwrap();
    let auto_floor_full = Engine::serve_pool_floor_counts(chunk, ctx).1;
    for (explicit, floor_full) in [(false, auto_floor_full), (true, MIN_ROLLOVER_WINDOW_SLOTS)] {
        let planned_budget =
            if explicit { budget } else { Engine::capped_serve_kv_budget_for(budget, KVB_KV8, chunk, ctx, lanes, true) };
        let split = |pct: u64| {
            Engine::plan_serve_block_pools_for(budget, KVB_KV8, chunk, ctx, lanes, slab, pct, true, explicit).unwrap()
        };
        let (w45, f45) = split(45);
        let (w60, f60) = split(60);
        assert!(w60 > w45 && f60 < f45, "explicit={explicit}: 45% ({w45}, {f45}) vs 60% ({w60}, {f60})");
        for pct in [45, 60, 99] {
            let (n_window, n_full) = split(pct);
            let bytes = n_window as u64 * mode.stride_bytes(BlockKind::Window) + n_full as u64 * full_slot_bytes;
            assert!(bytes <= planned_budget, "explicit={explicit} pct={pct}: {bytes} > {planned_budget}");
            assert!(n_full >= floor_full, "explicit={explicit} pct={pct}: {n_full} full < floor {floor_full}");
        }
    }
}