[Proto] clamp generation budget to window instead of hard-error (reviewer)

strata-ctl always sends max_new=16384, so any prompt > MAX_CONTEXT-16386 (16504 /
16686 seen live in sessions.db) hit the hard error and returned 0 tokens, killing
the agent mid-window. Now clamp_max_new(): hard-error only when the prompt itself
overflows (n_prompt+2 >= max_context); otherwise effective_max_new =
min(g.max_new, max_context-n_prompt-2) drives max_seq, history reserve, the decode
loop and the length finish. Resident window configurable like strata:
VETTA_MAX_CONTEXT env / serve --max-context N (>=4096), advertised in READY.
CPU test clamp_max_new_budget (16504/16686 clamp, 32765->1, 32766->None, 65536 full).
MEASURED live: 16504-token prompt GEN2 now runs (2 tokens, DONE 107.6s ~6.5ms/tok)
where it previously returned ERR 0 tokens; READY 32768 default / 65536 with flag.
gw serve_gen 4/4 EXACT; CPU -D warnings green.
This commit is contained in:
adm committed 2026-12-02 04:45:16 +01:00
1 parent cfa5586447
commit ee8ac8f5df
2 files changed
+64 -11

No files matched your search

+56 -10
View File
@@ -51,6 +51,16 @@ const SITU_LB: f32 = 25.0;
/// not limited by the 64 KB LDS cap.
const MAX_CONTEXT: usize = 32768;
/// Clamp the generation budget to the resident window instead of hard-erroring.
/// strata-ctl always sends the default budget max_new=16384, so a prompt longer
/// than MAX_CONTEXT-16386 (e.g. 16504/16686 seen live) must still run with a
/// reduced budget rather than return 0 tokens and kill the agent mid-window.
/// `None` = the prompt itself no longer fits (true overflow, hard error).
fn clamp_max_new(n_prompt: usize, max_new: usize, max_context: usize) -> Option<usize> {
if n_prompt + 2 >= max_context { return None; }
Some(max_new.min(max_context - n_prompt - 2))
}
/// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in
/// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries
/// so a new request whose prompt extends a cached prefix restores it and prefills
@@ -169,6 +179,9 @@ pub struct InklingEngine {
/// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
states: RefCell<Vec<Option<LayerState>>>,
states_cap: Cell<usize>,
/// Resident context window (advertised in READY). Defaults to MAX_CONTEXT;
/// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents.
max_context: usize,
}
impl InklingEngine {
@@ -207,6 +220,10 @@ impl InklingEngine {
lb: SITU_LB,
swa_win: t.swa_win as i32,
};
let max_context = std::env::var("VETTA_MAX_CONTEXT").ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&v| v >= 4096)
.unwrap_or(MAX_CONTEXT);
Ok(Self {
cache: WeightCache::new(ar),
d,
@@ -221,6 +238,7 @@ impl InklingEngine {
prefix: RefCell::new(PrefixCache::new()),
states: RefCell::new(Vec::new()),
states_cap: Cell::new(0),
max_context,
})
}
@@ -228,6 +246,10 @@ impl InklingEngine {
self.vocab
}
pub fn max_context(&self) -> usize {
self.max_context
}
fn forward(
&self,
token: i32,
@@ -286,15 +308,18 @@ pub fn serve_gen(
}
let n_prompt = g.ids.len();
let max_seq = (n_prompt + g.max_new + 2).min(MAX_CONTEXT);
if n_prompt + g.max_new + 2 > MAX_CONTEXT {
emit_all(emit, sess.on_error("prompt + max_new exceeds context window"));
let max_context = eng.max_context();
// Clamp the budget to the window (reviewer 2026-12-02): only a prompt that
// itself overflows is a hard error; otherwise generate up to the room left.
let Some(effective_max_new) = clamp_max_new(n_prompt, g.max_new, max_context) else {
emit_all(emit, sess.on_error("prompt exceeds context window"));
return;
}
};
let max_seq = (n_prompt + effective_max_new + 2).min(max_context);
// Persistent KV states: size once to a 4096-bucket cap >= max_seq and reuse
// across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when
// a request crosses the bucket.
let need = max_seq.next_multiple_of(4096).min(MAX_CONTEXT);
let need = max_seq.next_multiple_of(4096).min(max_context);
if eng.states_cap.get() < need || eng.states.borrow().len() != eng.n_layers {
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
eng.states_cap.set(need);
@@ -358,7 +383,7 @@ pub fn serve_gen(
let t0 = Instant::now();
let mut pos = start as i32;
let mut history: Vec<i32> = g.ids[..start].to_vec();
history.reserve(n_prompt - start + g.max_new);
history.reserve(n_prompt - start + effective_max_new);
let mut logits: Option<DeviceBuf> = None;
let chunk = prefill_chunk_size();
let suffix = &g.ids[start..];
@@ -440,7 +465,7 @@ pub fn serve_gen(
eprintln!("[prefix] prompt-boundary save seq={pos}");
}
}
if g.max_new == 0 {
if effective_max_new == 0 {
stop.store(false, Ordering::Relaxed);
return;
}
@@ -459,7 +484,7 @@ pub fn serve_gen(
}
};
let mut finish = "length";
for step in 0..g.max_new {
for step in 0..effective_max_new {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
let ms = t1.elapsed().as_secs_f64() * 1000.0;
@@ -501,7 +526,7 @@ pub fn serve_gen(
break;
}
history.push(rep.token);
if step + 1 == g.max_new {
if step + 1 == effective_max_new {
finish = "length";
break;
}
@@ -596,7 +621,7 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
let _ = writeln!(out, "{line}");
let _ = out.flush();
};
emit(ready_line(MAX_CONTEXT as u32, true, false, false));
emit(ready_line(eng.max_context() as u32, true, false, false));
loop {
if quit.load(Ordering::Relaxed) {
@@ -621,6 +646,27 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
mod tests {
use super::*;
/// CPU: the budget clamp must keep long agent prompts runnable (strata-ctl
/// always sends max_new=16384) instead of hard-erroring past 16382 tokens, and
/// only reject a prompt that itself overflows the window.
#[test]
fn clamp_max_new_budget() {
// live agent prompts 16504/16686 with the default 16384 budget: clamp, run.
assert_eq!(clamp_max_new(16504, 16384, 32768), Some(32768 - 16504 - 2));
assert_eq!(clamp_max_new(16686, 16384, 32768), Some(32768 - 16686 - 2));
// small prompt keeps the full budget.
assert_eq!(clamp_max_new(2648, 16384, 32768), Some(16384));
// exactly at the last usable prompt position: 1 token of room.
assert_eq!(clamp_max_new(32765, 16384, 32768), Some(1));
// prompt itself overflows: hard error (None).
assert_eq!(clamp_max_new(32766, 16384, 32768), None);
assert_eq!(clamp_max_new(40000, 16384, 32768), None);
// configurable larger window accepts the same long prompt unclamped.
assert_eq!(clamp_max_new(16504, 16384, 65536), Some(16384));
// GEN 0 pre-warm stays 0 regardless of prompt.
assert_eq!(clamp_max_new(2648, 0, 32768), Some(0));
}
/// GPU integration: drive `serve_gen` over the wire for the canonical prompt
/// "The capital of France is" (ids from the tokenizer) and check the emitted
/// lines: first `T` is 152717 (" Paris", exact reference match) and the