inky-engine 2.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! Test-only observation of the step selected by the serving scheduler, including its
//! runnable inputs, the ages and share credit either side of the call, and every step-time
//! charge. The standalone TLC gate compiles this module and the same production planning
//! entry points on hosts without Metal.
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner, StepClass};
use std::cell::RefCell;
use std::io::{BufWriter, Write};

thread_local! {
    static FRAMES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}

/// Planner state before a plan call: wait ticks and share credit.
pub(super) struct Before {
    ages: Vec<u32>,
    credit: i64,
}

pub(super) fn snapshot(planner: &ServeStepPlanner, lanes: usize) -> Option<Before> {
    FRAMES.with_borrow(|frames| {
        frames.as_ref().map(|_| Before {
            ages: (0..lanes).map(|i| planner.wait_ticks(i)).collect(),
            credit: planner.credit(),
        })
    })
}

/// Planner state before a charge: share credit and the class awaiting its step time.
pub(super) fn charge_snapshot(planner: &ServeStepPlanner) -> Option<(i64, Option<StepClass>)> {
    FRAMES.with_borrow(|frames| frames.as_ref().map(|_| (planner.credit(), planner.pending())))
}

fn class_name(class: Option<StepClass>) -> &'static str {
    match class {
        None => "none",
        Some(StepClass::Decode) => "decode",
        Some(StepClass::Prefill) => "prefill",
    }
}

fn push(frame: impl FnOnce(usize) -> String) {
    FRAMES.with_borrow_mut(|frames| {
        let frames = frames.as_mut().unwrap();
        let seq = frames.len();
        frames.push(frame(seq));
    });
}

pub(super) fn record(
    planner: &ServeStepPlanner,
    inputs: &[ServeLaneInput],
    budget: usize,
    align: usize,
    before: &Before,
    plan: Option<&ServeStepPlan>,
) {
    let lanes = inputs.len();
    let mut spans = vec![0; lanes];
    let mut starts = vec![0; lanes];
    let mut select = |i: usize, p0: usize, len: usize| {
        assert!(
            len > 0 && spans[i] == 0,
            "invalid or duplicate span in the step"
        );
        spans[i] = len;
        starts[i] = p0;
    };
    let mode = match plan {
        None => "idle",
        Some(ServeStepPlan::Decode(chosen)) => {
            for &i in chosen {
                select(i, inputs[i].n_past, 1);
            }
            "decode"
        }
        Some(ServeStepPlan::Prefill(chosen)) => {
            for &(i, p0, len) in chosen {
                select(i, p0, len);
            }
            "prefill"
        }
    };
    let runnable: Vec<_> = inputs.iter().map(|i| i.runnable).collect();
    let pending: Vec<_> = inputs.iter().map(|i| i.has_pending_decode).collect();
    let pos: Vec<_> = inputs.iter().map(|i| i.n_past).collect();
    let end: Vec<_> = inputs.iter().map(|i| i.pf_end).collect();
    let after: Vec<_> = (0..lanes).map(|i| planner.wait_ticks(i)).collect();
    let ages = &before.ages;
    // All interpolated arrays contain integers or booleans. Keep this gate usable with rustc alone.
    push(|seq| {
        format!(
            r#"{{"version":3,"kind":"plan","seq":{seq},"runnable":{runnable:?},"pending":{pending:?},"pos":{pos:?},"endPos":{end:?},"before":{ages:?},"after":{after:?},"starts":{starts:?},"spans":{spans:?},"mode":"{mode}","budget":{budget},"align":{align},"ceiling":{},"share":{},"credit":{},"creditAfter":{},"cls":"{}"}}"#,
            planner.max_bypass(),
            planner.prefill_share(),
            before.credit,
            planner.credit(),
            class_name(planner.pending()),
        )
    });
}

pub(super) fn record_charge(
    planner: &ServeStepPlanner,
    elapsed_us: u64,
    (credit, class): (i64, Option<StepClass>),
) {
    push(|seq| {
        format!(
            r#"{{"version":3,"kind":"charge","seq":{seq},"share":{},"cls":"{}","elapsed":{elapsed_us},"credit":{credit},"creditAfter":{},"cap":{}}}"#,
            planner.prefill_share(),
            class_name(class),
            planner.credit(),
            crate::scheduler::SHARE_CHARGE_CAP_US,
        )
    });
}

fn capture(work: impl FnOnce()) -> Vec<String> {
    FRAMES.with_borrow_mut(|frames| assert!(frames.replace(Vec::new()).is_none()));
    work();
    let frames = FRAMES.with_borrow_mut(Option::take).unwrap();
    assert!(
        !frames.is_empty(),
        "workload did not reach the serving planner"
    );
    frames
}

fn write_trace(frames: &[String]) {
    let path = std::env::var_os("INKY_SCHED_TRACE_OUT").expect("set INKY_SCHED_TRACE_OUT");
    let mut out = BufWriter::new(std::fs::File::create(path).unwrap());
    for frame in frames {
        writeln!(out, "{frame}").unwrap();
    }
    out.flush().unwrap();
}

/// Capture the real GPU-backed scheduler only when the hardware test requests a trace.
pub(super) fn capture_if_requested(work: impl FnOnce()) {
    if std::env::var_os("INKY_SCHED_TRACE_OUT").is_some() {
        write_trace(&capture(work));
    } else {
        work();
    }
}

/// Seeds `0, 2, 4, ...` keep the pure tick policy (share 0); odd seeds exercise the share.
fn share_for(seed: u64) -> u32 {
    match seed % 8 {
        1 | 5 => super::step::SERVE_PREFILL_SHARE,
        3 => 100,
        7 => 35,
        _ => 0,
    }
}

const SEEDS: [u64; 33] = {
    let mut seeds = [u64::MAX; 33];
    let mut i = 0;
    while i < 32 {
        seeds[i] = i as u64;
        i += 1;
    }
    seeds
};

fn walk(mut seed: u64) -> Vec<String> {
    use super::step::{charge, plan, SERVE_STEP_MAX_BYPASS};
    use std::time::Duration;
    const LANES: usize = 4;
    const ALIGN: usize = 64;
    let share = share_for(seed);
    let mut next = || {
        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
        (seed >> 32) as usize
    };
    capture(|| {
        let mut planner = ServeStepPlanner::new(LANES, SERVE_STEP_MAX_BYPASS).with_prefill_share(share);
        let mut inputs = [ServeLaneInput {
            runnable: true,
            n_past: 0,
            pf_end: 0,
            has_pending_decode: true,
        }; LANES];
        for (i, input) in inputs.iter_mut().enumerate() {
            planner.on_admit(i);
            if i >= 2 {
                input.pf_end = 512 + next() % 256;
            }
        }
        for tick in 0..64 {
            // A full W=16 burst followed by two urgent prefillers, then variable
            // backpressure and token budgets. Restart some lanes as new prompts.
            let random = tick > SERVE_STEP_MAX_BYPASS;
            for (i, lane) in inputs.iter_mut().enumerate() {
                lane.runnable = tick != 63 && (!random || next() % 4 != 0);
                if random && lane.n_past >= lane.pf_end && next() % 5 == 0 {
                    planner.on_finish(i);
                    planner.on_admit(i);
                    lane.n_past = next() % ALIGN;
                    lane.pf_end = lane.n_past + 1 + next() % 256;
                }
                lane.has_pending_decode =
                    lane.n_past >= lane.pf_end && (!random || next() % 4 != 0);
            }
            let budget = if random { next() % 160 } else { 128 };
            // Synthetic step wall times: decode is a fixed pass plus a per-lane cost, prefill
            // grows with its tokens. Some steps take no measurable time or exceed the charge cap,
            // and some fail before charging.
            let mut cost = |base: u64, per: u64, work: usize| match next() % 16 {
                0 => 0,
                1 => 2 * crate::scheduler::SHARE_CHARGE_CAP_US,
                _ => base + per * work as u64 + (next() % 5000) as u64,
            };
            let elapsed = match plan(&mut planner, &inputs, budget, ALIGN) {
                Some(ServeStepPlan::Decode(chosen)) => {
                    for &i in &chosen {
                        inputs[i].n_past += 1;
                    }
                    Some(cost(40_000, 500, chosen.len()))
                }
                Some(ServeStepPlan::Prefill(spans)) => {
                    let tokens: usize = spans.iter().map(|&(_, _, len)| len).sum();
                    for (i, _, len) in spans {
                        inputs[i].n_past += len;
                    }
                    Some(cost(20_000, 250, tokens))
                }
                None => None,
            };
            if let Some(us) = elapsed.filter(|_| next() % 10 != 0) {
                charge(&mut planner, Duration::from_micros(us));
            }
            planner.complete_step();
        }
    })
}

/// Seed of the arrivals workload: W + 2 lanes, so a prefill step can leave a prefiller at W - 1
/// while the decoder reaches W - 1 (the reserve at W - 1 the four-lane walk never needs).
const ARRIVALS_SEED: u64 = u64::MAX - 1;

/// Stella Codex's arrival pattern on 15d7e83, at W = 16 with 18 lanes: a decoder and a prefiller,
/// then 16 more prefillers at once. Prefill steps take one long chunk each under the share, so
/// the decoder ages to W - 1 with unserved prefillers at W - 1.
fn arrivals() -> Vec<String> {
    use super::step::{charge, plan, SERVE_STEP_MAX_BYPASS};
    use std::time::Duration;
    const LANES: usize = SERVE_STEP_MAX_BYPASS as usize + 2;
    const ALIGN: usize = 64;
    capture(|| {
        let mut planner = ServeStepPlanner::new(LANES, SERVE_STEP_MAX_BYPASS)
            .with_prefill_share(super::step::SERVE_PREFILL_SHARE);
        let mut inputs = [ServeLaneInput {
            runnable: false,
            n_past: 0,
            pf_end: 200_000,
            has_pending_decode: false,
        }; LANES];
        inputs[0] = ServeLaneInput {
            runnable: false,
            n_past: 9,
            pf_end: 1,
            has_pending_decode: true,
        };
        for tick in 0..64 {
            for (i, lane) in inputs.iter_mut().enumerate() {
                if (tick == 0 && i < 2) || (tick == 2 && i >= 2) {
                    planner.on_admit(i);
                    lane.runnable = true;
                }
            }
            let elapsed = match plan(&mut planner, &inputs, 4096, ALIGN) {
                Some(ServeStepPlan::Decode(chosen)) => {
                    for &i in &chosen {
                        inputs[i].n_past += 1;
                    }
                    100_000
                }
                Some(ServeStepPlan::Prefill(spans)) => {
                    for (i, _, len) in spans {
                        inputs[i].n_past += len;
                    }
                    1_000
                }
                None => unreachable!("lanes 0 and 1 are always runnable"),
            };
            charge(&mut planner, Duration::from_micros(elapsed));
            planner.complete_step();
        }
    })
}

fn plans(frames: &[String]) -> Vec<&String> {
    frames.iter().filter(|f| f.contains(r#""kind":"plan""#)).collect()
}

#[test]
fn seeded_decisions_are_repeatable() {
    for seed in SEEDS {
        let frames = walk(seed);
        let plan_frames = plans(&frames);
        assert_eq!(plan_frames.len(), 64);
        let burst = super::step::SERVE_STEP_MAX_BYPASS as usize;
        if share_for(seed) == 0 {
            // The tick policy bursts W decodes before the first prefill.
            assert!(plan_frames[..burst]
                .iter()
                .all(|f| f.contains(r#""mode":"decode""#)));
            assert!(plan_frames[burst].contains(r#""mode":"prefill""#));
        } else {
            // With a share, a new contention starts owed to prefill.
            assert!(plan_frames[0].contains(r#""mode":"prefill""#));
        }
        assert!(plan_frames.last().unwrap().contains(r#""mode":"idle""#));
        assert!(frames.iter().any(|f| f.contains(r#""kind":"charge""#)));
        assert_eq!(frames, walk(seed));
    }
}

#[test]
fn arrivals_are_repeatable_and_bounded() {
    let frames = arrivals();
    let plan_frames = plans(&frames);
    assert_eq!(plan_frames.len(), 64);
    // The decoder ages to W - 1 under the share while prefillers wait, so the reserve applies.
    assert!(plan_frames.iter().any(|f| f.contains(r#""mode":"prefill""#)));
    assert!(plan_frames.iter().any(|f| f.contains(r#""mode":"decode""#)));
    assert_eq!(frames, arrivals());
}

#[test]
#[ignore = "writes serve planner observations to INKY_SCHED_TRACE_OUT"]
fn dump() {
    let out = match std::env::var("INKY_SCHED_TRACE_SEED") {
        Ok(seed) => match seed.parse().expect("seed must be a u64") {
            ARRIVALS_SEED => arrivals(),
            seed => walk(seed),
        },
        Err(_) => SEEDS.into_iter().flat_map(walk).collect(),
    };
    write_trace(&out);
}