inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! CPU-only trace projection of the actual serving cache. Check claims about
//! these observations in specs/ServeCacheTrace.tla.

use super::*;
use std::fmt::Write as _;

const TABLE_BLOCKS: u32 = 36;

fn tuple(items: impl IntoIterator<Item = impl ToString>) -> String {
    let items: Vec<_> = items.into_iter().map(|item| item.to_string()).collect();
    format!("<<{}>>", items.join(", "))
}

fn set(items: impl IntoIterator<Item = String>) -> String {
    let mut items: Vec<_> = items.into_iter().collect();
    items.sort_unstable();
    format!("{{{}}}", items.join(", "))
}

fn id_number(id: SealedId) -> u64 {
    id.index() + 1
}

fn kind_number(kind: BlockKind) -> u8 {
    match kind {
        BlockKind::Full => 1,
        BlockKind::Window => 2,
    }
}

fn handle(entry: BlockEntry) -> String {
    tuple([entry.slot().get(), entry.generation()])
}

fn entry_row(index: BlockIndex, entry: BlockEntry) -> String {
    tuple([
        kind_number(entry.kind()).to_string(),
        index.get().to_string(),
        handle(entry),
    ])
}

#[derive(Default)]
struct Lane {
    state: LaneBlockState,
    prompt: Vec<u32>,
}

struct Trace {
    cache: ServeBlockCache,
    pools: BlockPools,
    tables: [BlockTable; 2],
    lanes: [Lane; 2],
    rows: Vec<String>,
}

impl Trace {
    fn new(full_slots: usize, window_slots: usize) -> Self {
        Self {
            cache: ServeBlockCache::new(),
            pools: BlockPools::with_capacities(full_slots, window_slots, 2).unwrap(),
            tables: std::array::from_fn(|_| BlockTable::new(TABLE_BLOCKS).unwrap()),
            lanes: std::array::from_fn(|_| Lane::default()),
            rows: Vec::new(),
        }
    }

    fn row(&mut self, op: &str, lane: usize, arg: u64, cs: usize) {
        let pools = tuple([BlockKind::Full, BlockKind::Window].map(|kind| {
            let pool = self.pools.of(kind);
            tuple((1..=pool.len()).map(|slot| {
                let rec = pool.record(Slot::new(slot as u32).unwrap()).unwrap();
                tuple([
                    rec.generation(),
                    rec.length(),
                    rec.refs(),
                    if rec.sealed() { 1 } else { 0 },
                ])
            }))
        }));
        let lanes = tuple(self.lanes.iter().zip(&self.tables).map(|(lane, table)| {
            tuple([
                lane.state.written.to_string(),
                lane.state.prompt_len.to_string(),
                tuple(
                    lane.prompt
                        .chunks_exact(BLOCK)
                        .map(|block| block[BLOCK - 1]),
                ),
                tuple(lane.state.sealed.iter().copied().map(id_number)),
                set(table
                    .entries()
                    .map(|(index, entry)| entry_row(index, entry))),
            ])
        }));
        let tree = set(self.cache.tree.entries().into_iter().map(|(id, handles)| {
            let (parent, tokens) = self.cache.tree.trace_block(id).unwrap();
            tuple([
                id_number(id).to_string(),
                parent.map_or(0, id_number).to_string(),
                tokens[BLOCK - 1].to_string(),
                self.cache.tree.pin_count(id).to_string(),
                self.cache.tree.start_holders(id).to_string(),
                handle(handles.full()),
                handles.window().map_or("<<0, 0>>".to_string(), handle),
            ])
        }));
        let starts = set(self.cache.starts.iter().map(|(&id, start)| {
            tuple([
                id_number(id).to_string(),
                start.pos.to_string(),
                start.reasons.to_string(),
                decode_cs(&start.cs).to_string(),
                set(start
                    .entries
                    .iter()
                    .map(|&(_, index, entry)| entry_row(index, entry))),
            ])
        }));
        let ranks = set(self.cache.starts.iter().map(|(&id, start)| {
            let rank = self.cache.eviction_rank(id, start, false); // no card lease in this replay
            let reuse = &start.reuse;
            format!(
                "[id |-> {}, epoch |-> {}, cur |-> {}, prev |-> {}, born |-> {}, saved |-> {}, recent |-> {}, live |-> {}, bytes |-> {}, host |-> {}]",
                id_number(rank.sid), reuse.epoch, reuse.current, reuse.previous,
                start.created_tick.map_or_else(|| "-1".to_string(), |t| t.to_string()), rank.saved_tokens,
                if rank.recent { "TRUE" } else { "FALSE" }, if rank.live { "TRUE" } else { "FALSE" },
                rank.bytes, start.host_bytes(),
            )
        }));
        self.rows.push(format!(
            "[op |-> \"{op}\", lane |-> {}, arg |-> {arg}, cs |-> {cs}, pools |-> {pools}, lanes |-> {lanes}, tree |-> {tree}, starts |-> {starts}, ranks |-> {ranks}, tick |-> {}]",
            lane + 1, self.cache.tick,
        ));
    }

    fn bind(&mut self, i: usize, tags: &[u32], tail: usize) {
        let lane = &mut self.lanes[i];
        // Every block shares its first 63 tokens. A first-token-only walk
        // would match the wrong history at the very last token of a block.
        lane.prompt = tags
            .iter()
            .flat_map(|&tag| (0..63).chain(std::iter::once(tag)))
            .chain(std::iter::repeat_n(999, tail))
            .collect();
        let hit = self.cache.match_and_bind(
            &mut self.pools,
            &mut self.tables[i],
            &mut lane.state,
            &lane.prompt,
        );
        let (pos, cs) = hit.map_or((0, 0), |(pos, cs)| (pos, decode_cs(&cs)));
        self.row("bind", i, pos as u64, cs);
    }

    fn prefill(&mut self, i: usize, end: usize) {
        self.prefill_observed(i, end, "prefill");
    }

    fn prefill_observed(&mut self, i: usize, end: usize, op: &str) {
        let lane = &mut self.lanes[i];
        let start = lane.state.written;
        self.cache
            .ensure_span_blocks(&mut self.pools, &mut self.tables[i], start, end - start)
            .unwrap();
        self.cache.finish_prefill_span(
            &mut self.pools,
            &mut self.tables[i],
            &mut lane.state,
            &lane.prompt,
            start,
            end - start,
            || (end as u32).to_le_bytes().to_vec(),
        );
        self.row(op, i, end as u64, 0);
    }

    fn decode(&mut self, i: usize) {
        let lane = &mut self.lanes[i];
        let pos = lane.state.written;
        self.cache
            .ensure_span_blocks(&mut self.pools, &mut self.tables[i], pos, 1)
            .unwrap();
        self.cache
            .finish_decode_span(&mut self.pools, &mut self.tables[i], &mut lane.state, pos);
        self.row("decode", i, (pos + 1) as u64, 0);
    }

    fn release(&mut self, i: usize) {
        let lane = &mut self.lanes[i];
        self.cache
            .release_lane(&mut self.pools, &mut self.tables[i], &mut lane.state);
        lane.prompt.clear();
        self.row("release", i, 0, 0);
    }

    fn evict(&mut self, id: SealedId) {
        assert!(self.cache.evict_start(&mut self.pools, id));
        self.row("evict", 0, id_number(id), 0);
    }
}

fn decode_cs(cs: &[u8]) -> usize {
    u32::from_le_bytes(cs.try_into().unwrap()) as usize
}

pub(crate) fn generate(path: &std::path::Path) {
    let long: Vec<u32> = (100..133).collect();
    let fork = [long[0], 700];
    let mut t = Trace::new(44, 40);
    t.row("init", 0, 0, 0);

    t.bind(0, &long, 62);
    t.prefill(0, 2048);
    t.prefill(0, 2112);
    t.prefill(0, 2174);
    t.decode(0); // With one new token, the oldest block crosses the window boundary.
    let every = t.lanes[0].state.sealed[31];
    let deep = t.lanes[0].state.sealed[32];
    t.release(0);

    let mut wrong_history = long.clone();
    wrong_history[1] = fork[1];
    t.bind(1, &wrong_history, 62); // A same-length prompt with the wrong history must miss.
    t.release(1);

    // Serving a divergent prompt must replace an expired early window handle
    // while sharing the still-live full handle of the common first block.
    t.bind(1, &fork, 1);
    t.prefill(1, 128);
    let fork_tip = t.lanes[1].state.sealed[1];
    t.release(1);
    t.bind(0, &fork, 1);
    t.evict(fork_tip); // The live lane still pins this branch.
    t.release(0);
    t.bind(0, &fork, 1); // The evicted start must miss.
    t.release(0);

    t.bind(0, &long, 62);
    t.bind(1, &long, 0); // Exact checkpoint must leave the final prompt token unwritten.
    t.release(1);
    t.evict(deep);
    t.release(0); // Removes the deep tip, leaving the EVERY prefix.
    t.bind(1, &long, 62);
    t.release(1);
    t.evict(every); // Final eviction prunes the surviving ancestor chain.

    // A two-block checkpoint binds twice (256 saved); a one-block checkpoint
    // binds three times (192 saved). Both are recent and idle. The first has
    // more raw credit but less credit per byte. The next write needs one
    // Full and one Window slot from the completely occupied three-slot pools.
    let mut pressure = Trace::new(3, 3);
    pressure.row("init", 0, 0, 0);
    for (tags, binds) in [(&[800, 801][..], 2), (&[900][..], 3)] {
        pressure.bind(0, tags, 1);
        pressure.prefill(0, tags.len() * BLOCK);
        pressure.release(0);
        for _ in 0..binds {
            pressure.bind(0, tags, 1);
            pressure.release(0);
        }
    }
    pressure.bind(0, &[1000], 1);
    pressure.prefill_observed(0, 1, "pressure");
    pressure.release(0);

    let mut out = String::from("---- MODULE ServeCacheTraceData ----\nEXTENDS Integers\n");
    writeln!(out, "EpochTicks == {REUSE_EPOCH_TICKS}").unwrap();
    writeln!(out, "SlotBytes == {}", tuple([pressure.pools.full.stride_bytes(), pressure.pools.window.stride_bytes()])).unwrap();
    writeln!(out, "Traces == <<\n<<{}>>,\n<<{}>>\n>>\n====", t.rows.join(",\n"), pressure.rows.join(",\n")).unwrap();
    std::fs::write(path, out).unwrap();
}

/// Replay a host-only trim with one start a live lane pins and two idle starts whose
/// credit densities order differently under host and pool pressure.
pub(crate) fn generate_host_trim(path: &std::path::Path) {
    let mut cache = ServeBlockCache::new();
    let mut pools = BlockPools::with_capacities(6, 6, 1).unwrap();
    let mut table = BlockTable::new(4).unwrap();
    let mut lane = LaneBlockState::default();
    for (tag, blocks, binds, keep_lane) in [(1000, 1, 3, false), (2000, 2, 2, false), (4000, 1, 0, true)] {
        let end = blocks * BLOCK;
        let prompt: Vec<_> = (tag..=tag + end as u32).collect();
        lane.prompt_len = prompt.len();
        cache.ensure_span_blocks(&mut pools, &mut table, 0, end).unwrap();
        cache.finish_prefill_span(&mut pools, &mut table, &mut lane, &prompt, 0, end, || vec![0; 4096]);
        if !keep_lane {
            cache.release_lane(&mut pools, &mut table, &mut lane);
        }
        for _ in 0..binds {
            cache.match_and_bind(&mut pools, &mut table, &mut lane, &prompt);
            cache.release_lane(&mut pools, &mut table, &mut lane);
        }
    }

    let before = set(cache.starts.iter().map(|(&id, st)| {
        let rank = cache.host_eviction_rank(id, st, false);
        let refs = set(st.entries.iter().map(|&(kind, _, e)| {
            let count = pools.of(kind).record(e.slot()).unwrap().refs();
            let from_starts = cache.starts.values().flat_map(|s| &s.entries)
                .filter(|&&(k, _, other)| k == kind && other == e).count();
            tuple([u64::from(count), from_starts as u64])
        }));
        format!(
            "[id |-> {}, pins |-> {}, refs |-> {}, live |-> {}, recent |-> {}, saved |-> {}, bytes |-> {}, host |-> {}, slots |-> {}]",
            id_number(id), cache.tree.pin_count(id), refs, if rank.live { "TRUE" } else { "FALSE" },
            if rank.recent { "TRUE" } else { "FALSE" }, rank.saved_tokens, rank.bytes, st.host_bytes(), st.slot_bytes,
        )
    }));
    let cap = cache.retained_host_bytes() - 1;
    cache.set_max_retained_host_bytes(cap);
    let selected = cache.host_trim_victim(None).map_or(0, |(id, _)| id_number(id));
    cache.enforce_retained_host_budget(&mut pools, None);
    let survivors = set(cache.starts.keys().map(|&id| id_number(id).to_string()));
    let bytes_after = cache.retained_host_bytes();
    std::fs::write(path, format!(
        "---- MODULE ServeHostTrimTraceData ----\nBefore == {before}\nSelected == {selected}\nSurvivors == {survivors}\nCap == {cap}\nBytesAfter == {bytes_after}\n====\n"
    )).unwrap();
}