pub const BLOCK: usize = 64;
#[cfg(not(standalone_checkpoint))]
const _: () = assert!(BLOCK == crate::blocks::BLOCK);
pub const EARLY_EVERY_TOKENS: usize = 2048;
pub const LATE_EVERY_TOKENS: usize = 4096;
pub const EARLY_EVERY_LIMIT: usize = 16384;
pub const PROMPT: u8 = 1;
pub const EVERY: u8 = 2;
#[cfg(not(standalone_checkpoint))]
const _: () = assert!(PROMPT == crate::blockbook::PROMPT && EVERY == crate::blockbook::EVERY);
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)
}
}
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)
}
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)
}
}
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;
}
}
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;
}
if !approx_path && is_every_checkpoint(end) {
reasons |= EVERY;
}
reasons
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateAt {
Kept(usize),
End,
}
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() {
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)]
);
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)]
);
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)]);
assert_eq!(step_pf_target(9856, 9860, true), 9860);
assert_eq!(step_pf_target(9856, 9860, false), 9860);
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);
}
#[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);
}
}
}
}
}
#[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
}
}
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);
let mut lanes: Vec<(usize, usize, bool)> = (0..n)
.map(|_| {
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");
}
}