From ee8ac8f5df50b69a1563054f69bfd596a26b1b98 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 2 Dec 2026 04:45:16 +0100 Subject: [PATCH] [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. --- crates/vetta-infer-gw/src/main.rs | 9 +++- crates/vetta-infer-gw/src/serve.rs | 66 +++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/crates/vetta-infer-gw/src/main.rs b/crates/vetta-infer-gw/src/main.rs index 686865d..e204c64 100644 --- a/crates/vetta-infer-gw/src/main.rs +++ b/crates/vetta-infer-gw/src/main.rs @@ -11,7 +11,7 @@ fn usage() { eprintln!(" vetta-infer info Inspect shards, dtypes, and checked bounds"); eprintln!(" vetta-infer tensors [prefix] List tensors (name, dtype, shape, bytes)"); eprintln!(" vetta-infer serve Resident GEN/STOP/QUIT wire service (GPU, --features hip)"); - eprintln!(" (alias: --serve , as strata-ctl spawns it)"); + eprintln!(" (alias: --serve , as strata-ctl spawns it; [--max-context N])"); eprintln!(" vetta-infer chat [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)"); eprintln!(" vetta-infer version Print version & build info"); } @@ -101,6 +101,13 @@ fn main() -> ExitCode { usage(); return ExitCode::from(2); }; + // Optional resident window override (like strata --max-context): + // `serve --max-context N`. Defaults to 32768 when absent. + if let Some(i) = args.iter().position(|a| a == "--max-context") { + if let Some(v) = args.get(i + 1).and_then(|s| s.parse::().ok()) { + unsafe { std::env::set_var("VETTA_MAX_CONTEXT", v.to_string()) }; + } + } #[cfg(feature = "hip")] { match vetta_infer_gw::serve::run_serve(dir) { diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 48d0af7..58cf44b 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -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 { + 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>>, states_cap: Cell, + /// 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::().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 = 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 = 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