inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! Start-point checkpoints of a prefill, and the prefill target of one serving step. Pure arithmetic: the block cache
//! retains start points at these positions (`ServeBlockCache::finish_prefill_span`), serve slices its steps by them
//! (`step_pf_target`), and the standalone trace gate (`scripts/check-checkpoint-span-traces.sh`, specs
//! `ServeCheckpointSpan.tla` and `ServeCheckpointSpanTrace.tla`) compiles this file with the step planner alone.

/// Tokens per cache block (`crate::blocks::BLOCK`, asserted equal below).
pub const BLOCK: usize = 64;
#[cfg(not(standalone_checkpoint))]
const _: () = assert!(BLOCK == crate::blocks::BLOCK);

/// Periodic checkpoint stride for the first `EARLY_EVERY_LIMIT` tokens so shared system+tools
/// prompts (e.g. OpenCode ~8,500 tokens) are cached in large 2048-token tensor chunks.
pub const EARLY_EVERY_TOKENS: usize = 2048;
/// Above `EARLY_EVERY_LIMIT`, periodic checkpoints widen to 4096 tokens for full-chunk prefill.
pub const LATE_EVERY_TOKENS: usize = 4096;
pub const EARLY_EVERY_LIMIT: usize = 16384;

/// Start-point reasons (`crate::blockbook::{PROMPT, EVERY}`).
pub const PROMPT: u8 = 1;
pub const EVERY: u8 = 2;
#[cfg(not(standalone_checkpoint))]
const _: () = assert!(PROMPT == crate::blockbook::PROMPT && EVERY == crate::blockbook::EVERY);

/// True when `end` (a multiple of `BLOCK`) is a periodic `EVERY` checkpoint boundary.
pub fn is_every_checkpoint(end: usize) -> bool {
    if end == 0 || !end.is_multiple_of(BLOCK) {
        return false;
    }
    if end <= EARLY_EVERY_LIMIT {
        end.is_multiple_of(EARLY_EVERY_TOKENS)
    } else {
        end.is_multiple_of(LATE_EVERY_TOKENS)
    }
}

/// Compute the capped prefill target for the current step so `finish_prefill_span` lands
/// cleanly on checkpoint boundaries (`2048`-token / `4096`-token `EVERY` boundaries and the
/// prompt's final `((pf_end - 1) / 64) * 64` `PROMPT` boundary) where `get_cs()` matches `end`.
pub fn effective_pf_target(n_past: usize, pf_end: usize) -> usize {
    if n_past >= pf_end || pf_end == 0 {
        return pf_end;
    }
    let prompt_ckpt = ((pf_end - 1) / BLOCK) * BLOCK;
    if n_past >= prompt_ckpt {
        return pf_end;
    }
    let stride = if n_past < EARLY_EVERY_LIMIT { EARLY_EVERY_TOKENS } else { LATE_EVERY_TOKENS };
    let next_every = ((n_past / stride) + 1) * stride;
    next_every.min(prompt_ckpt)
}

/// The prefill target of one step. With `through`, a span runs through start-point checkpoints to the prompt's end (the
/// step budget still bounds it): the engine keeps the conv state at each checkpoint it crosses inside the step
/// ([`span_checkpoints`]), and `ServeBlockCache::finish_prefill_span_through` retains the starts there as if the span had
/// stopped at each. Without `through` it is [`effective_pf_target`]: every span stops at the next checkpoint, and a
/// prompt's last partial block becomes a step of its own (most often a step alone, while every decoder waits).
pub fn step_pf_target(n_past: usize, pf_end: usize, through: bool) -> usize {
    if through {
        pf_end
    } else {
        effective_pf_target(n_past, pf_end)
    }
}

/// The start-point checkpoints a prefill span `[p0, p0 + t)` of a prompt ending at `pf_end` runs through, in order: each
/// one [`effective_pf_target`] would have stopped it at, strictly inside the span.
pub fn span_checkpoints(p0: usize, t: usize, pf_end: usize) -> Vec<usize> {
    let mut out = Vec::new();
    let mut p = p0;
    loop {
        let c = effective_pf_target(p, pf_end);
        if c <= p || c >= p0 + t {
            return out;
        }
        out.push(c);
        p = c;
    }
}

/// Why a start point is retained where a sealing prefill span ends (`0`: none). Only on a block boundary: `PROMPT` at
/// the prompt's last block boundary or its end, `EVERY` on the periodic stride for a lane off the approximate path.
pub fn start_reasons(end: usize, prompt_len: usize, approx_path: bool) -> u8 {
    if end == 0 || !end.is_multiple_of(BLOCK) {
        return 0;
    }
    let prompt_ckpt = (prompt_len.saturating_sub(1) / BLOCK) * BLOCK;
    let mut reasons = 0u8;
    if (prompt_ckpt > 0 && end == prompt_ckpt) || end == prompt_len {
        reasons |= PROMPT;
    }
    // An approximate lane keeps only its PROMPT start (and the turn-end start `seal_decode_block` saves):
    // intermediate EVERY starts would pin 16 Window blocks each across the card's tool gap, and Window
    // slots, not Full, run out first on the MacBook.
    if !approx_path && is_every_checkpoint(end) {
        reasons |= EVERY;
    }
    reasons
}

/// Whose conv state a finished part of a span leaves at its end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateAt {
    /// The state the engine kept inside the step after this many rows of the span (`Engine::kept_span_state`).
    Kept(usize),
    /// The lane's state at the end of the step (`get_cs`).
    End,
}

/// The parts a prefill span `[p0, p0 + t)` that ran through the checkpoints `ckpts` (in order, from
/// [`span_checkpoints`]) is finished as: the spans the checkpoints used to split it into, each ending at a checkpoint
/// with the state kept there, and the last with the state at the end. Without a checkpoint, the span itself. Each part
/// is `(start, end, state)`.
pub fn finish_parts(p0: usize, t: usize, ckpts: &[usize]) -> Vec<(usize, usize, StateAt)> {
    let mut parts = Vec::with_capacity(ckpts.len() + 1);
    let mut lo = p0;
    for &c in ckpts {
        assert!(c > lo && c < p0 + t, "checkpoint {c} is not inside the span [{lo}, {})", p0 + t);
        parts.push((lo, c, StateAt::Kept(c - p0)));
        lo = c;
    }
    parts.push((lo, p0 + t, StateAt::End));
    parts
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_span_runs_through_its_checkpoints_and_finishes_as_the_split_spans() {
        // A tool result after an aligned restore: the body stops at the prompt checkpoint without `through`.
        assert_eq!(effective_pf_target(8448, 9860), 9856);
        assert_eq!(step_pf_target(8448, 9860, false), 9856);
        assert_eq!(step_pf_target(8448, 9860, true), 9860);
        assert_eq!(span_checkpoints(8448, 9860 - 8448, 9860), vec![9856]);
        assert_eq!(
            finish_parts(8448, 9860 - 8448, &[9856]),
            vec![(8448, 9856, StateAt::Kept(1408)), (9856, 9860, StateAt::End)]
        );
        // Two checkpoints inside one span (EVERY at 10240, PROMPT at 12224): both kept.
        assert_eq!(span_checkpoints(8448, 12230 - 8448, 12230), vec![10240, 12224]);
        assert_eq!(
            finish_parts(8448, 12230 - 8448, &[10240, 12224]),
            vec![(8448, 10240, StateAt::Kept(1792)), (10240, 12224, StateAt::Kept(3776)), (12224, 12230, StateAt::End)]
        );
        // A span that stops short of, or at, the checkpoint crosses nothing.
        assert!(span_checkpoints(8448, 9856 - 8448, 9860).is_empty());
        assert!(span_checkpoints(8448, 512, 9860).is_empty());
        assert_eq!(finish_parts(8448, 512, &[]), vec![(8448, 8960, StateAt::End)]);
        // Already past the prompt checkpoint: the target is the end either way.
        assert_eq!(step_pf_target(9856, 9860, true), 9860);
        assert_eq!(step_pf_target(9856, 9860, false), 9860);
        // Start reasons: PROMPT at the last block boundary, EVERY off the approximate path only.
        assert_eq!(start_reasons(9856, 9860, true), PROMPT);
        assert_eq!(start_reasons(10240, 12230, false), EVERY);
        assert_eq!(start_reasons(10240, 12230, true), 0);
        assert_eq!(start_reasons(9860, 9860, false), 0);
        assert_eq!(start_reasons(2048, 2048, false), PROMPT | EVERY);
    }

    /// Exhaustive over small prompts: with `through`, the starts retained over a whole prefill are the split's, each at
    /// the state of its own position, in no more steps, and no step is left with only the last partial block that the
    /// span before it had room for.
    #[test]
    fn through_keeps_every_start_in_no_more_steps_and_the_tail_rides() {
        for budget in [64usize, 128, 2048, 4096] {
            for pf_end in (1..=9000).step_by(61) {
                for restore in [0usize, 64, 1024, 2048] {
                    if restore >= pf_end {
                        continue;
                    }
                    let walk = |through: bool| {
                        let (mut p, mut starts, mut steps) = (restore, Vec::new(), 0usize);
                        let mut spare = 0usize;
                        while p < pf_end {
                            let target = step_pf_target(p, pf_end, through);
                            let room = budget.min(target - p);
                            let t = if room < target - p { room / BLOCK * BLOCK } else { room };
                            assert!(t > 0);
                            if through && p + t == pf_end && pf_end % BLOCK != 0 && t < BLOCK {
                                assert!(spare < t, "the last partial block ran alone though the span before had room");
                            }
                            spare = budget - t;
                            let c = span_checkpoints(p, t, pf_end);
                            assert!(through || c.is_empty(), "the split never crosses a checkpoint");
                            for (lo, hi, state) in finish_parts(p, t, &c) {
                                assert!(lo < hi);
                                if start_reasons(hi, pf_end, false) != 0 {
                                    let at = match state {
                                        StateAt::Kept(m) => p + m,
                                        StateAt::End => p + t,
                                    };
                                    starts.push((hi, at));
                                }
                            }
                            p += t;
                            steps += 1;
                        }
                        (starts, steps)
                    };
                    let (split, split_steps) = walk(false);
                    let (thr, thr_steps) = walk(true);
                    assert_eq!(split, thr, "budget {budget} end {pf_end} restore {restore}");
                    assert!(thr.iter().all(|&(at, state)| at == state));
                    assert!(thr_steps <= split_steps);
                }
            }
        }
    }
}

/// Observations of the production checkpoint rules over real step-planner decisions, for the TLC trace gate
/// (`scripts/check-checkpoint-span-traces.sh`, `specs/ServeCheckpointSpanTrace.tla`). Each step plans the lanes'
/// prefills with `ServeStepPlanner` on `step_pf_target` inputs; every span it hands out is finished by
/// `span_checkpoints` and `finish_parts`, and the starts `start_reasons` keeps are recorded with the position whose conv
/// state each part leaves (`p0 + m` kept inside the step, or the span's end).
#[cfg(test)]
pub(crate) mod trace {
    use super::*;
    use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn below(&mut self, n: u64) -> usize {
            (self.next() % n) as usize
        }
    }

    /// One frame per runnable lane per step: the lane's position, prompt end, approximate path, its planner input, the
    /// span planned for it (0: none), the checkpoints the span runs through, and the starts its parts keep.
    pub(crate) fn walk(seed: u64) -> Vec<String> {
        let mut rng = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);
        let through = seed % 4 != 3;
        let budget = [64usize, 128, 512, 2048, 4096][rng.below(5)];
        let n = 1 + rng.below(4);
        // Prompts the 400 steps below can finish at this budget.
        let mut lanes: Vec<(usize, usize, bool)> = (0..n)
            .map(|_| {
                // Prompt ends across the early (2048) and late (4096) strides; restores on block boundaries, near
                // the end (a tool result) or far from it (a first turn).
                let end = 1 + rng.below((budget * 150 / n).min(24_000) as u64);
                let restore = match rng.below(3) {
                    0 => 0,
                    1 => end.saturating_sub(1 + rng.below(1200)) / BLOCK * BLOCK,
                    _ => rng.below(end as u64) / BLOCK * BLOCK,
                };
                (restore, end, rng.below(2) == 0)
            })
            .collect();
        let mut planner = ServeStepPlanner::new(n, 16);
        for i in 0..n {
            planner.on_admit(i);
        }
        let mut frames = Vec::new();
        for step in 0..400 {
            let inputs: Vec<ServeLaneInput> = lanes
                .iter()
                .map(|&(p, end, _)| ServeLaneInput {
                    runnable: p < end,
                    n_past: p,
                    pf_end: step_pf_target(p, end, through),
                    has_pending_decode: false,
                })
                .collect();
            let Some(plan) = planner.plan_and_begin_step(&inputs, budget, BLOCK) else { break };
            let ServeStepPlan::Prefill(spans) = plan else { panic!("a prefill-only walk planned {plan:?}") };
            for (i, &(p, end, approx)) in lanes.iter().enumerate() {
                if p >= end {
                    continue;
                }
                let t = spans.iter().find(|s| s.0 == i).map_or(0, |s| s.2);
                let (ckpts, starts) = if t == 0 {
                    (Vec::new(), Vec::new())
                } else {
                    let ckpts = span_checkpoints(p, t, end);
                    let starts: Vec<String> = finish_parts(p, t, &ckpts)
                        .into_iter()
                        .filter(|&(_, hi, _)| start_reasons(hi, end, approx) != 0)
                        .map(|(_, hi, at)| {
                            let st = match at {
                                StateAt::Kept(m) => p + m,
                                StateAt::End => p + t,
                            };
                            format!("[{hi},{st}]")
                        })
                        .collect();
                    (ckpts, starts)
                };
                frames.push(format!(
                    r#"{{"seed":"{seed}","step":{step},"lane":{i},"through":{through},"budget":{budget},"pos":{p},"end":{end},"approx":{approx},"target":{},"span":{t},"ckpts":{:?},"starts":[{}]}}"#,
                    inputs[i].pf_end,
                    ckpts,
                    starts.join(",")
                ));
            }
            for &(i, p0, t) in &spans {
                assert_eq!(lanes[i].0, p0);
                lanes[i].0 += t;
            }
            planner.complete_step();
        }
        assert!(lanes.iter().all(|&(p, end, _)| p == end), "seed {seed}: every prompt is prefilled");
        frames
    }

    #[test]
    fn walk_prefills_every_prompt_and_runs_through_checkpoints() {
        let frames: Vec<String> = (0..64).flat_map(walk).collect();
        assert!(frames.iter().any(|f| f.contains(r#""through":true"#) && f.contains(r#""ckpts":[2048"#) || f.contains(r#""ckpts":[4096"#)));
        assert!(frames.iter().any(|f| f.contains(r#""through":false"#)));
        assert!(frames.iter().all(|f| !f.contains(r#""through":false"#) || f.contains(r#""ckpts":[]"#)));
    }

    #[test]
    #[ignore = "writes checkpoint observations to INKY_CKPT_TRACE_OUT"]
    fn dump() {
        let seed: u64 = std::env::var("INKY_CKPT_TRACE_SEED").expect("INKY_CKPT_TRACE_SEED").parse().expect("a u64 seed");
        let path = std::env::var("INKY_CKPT_TRACE_OUT").expect("INKY_CKPT_TRACE_OUT");
        let mut text = walk(seed).join("\n");
        text.push('\n');
        std::fs::write(path, text).expect("write the trace");
    }
}