[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

+8 -1
View File
@@ -11,7 +11,7 @@ fn usage() {
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds"); eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)"); eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)"); eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it)"); eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it; [--max-context N])");
eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)"); eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
eprintln!(" vetta-infer version Print version & build info"); eprintln!(" vetta-infer version Print version & build info");
} }
@@ -101,6 +101,13 @@ fn main() -> ExitCode {
usage(); usage();
return ExitCode::from(2); return ExitCode::from(2);
}; };
// Optional resident window override (like strata --max-context):
// `serve <dir> --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::<usize>().ok()) {
unsafe { std::env::set_var("VETTA_MAX_CONTEXT", v.to_string()) };
}
}
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
{ {
match vetta_infer_gw::serve::run_serve(dir) { match vetta_infer_gw::serve::run_serve(dir) {
+56 -10
View File
@@ -51,6 +51,16 @@ const SITU_LB: f32 = 25.0;
/// not limited by the 64 KB LDS cap. /// not limited by the 64 KB LDS cap.
const MAX_CONTEXT: usize = 32768; 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 /// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in
/// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries /// 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 /// 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. /// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
states: RefCell<Vec<Option<LayerState>>>, states: RefCell<Vec<Option<LayerState>>>,
states_cap: Cell<usize>, 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 { impl InklingEngine {
@@ -207,6 +220,10 @@ impl InklingEngine {
lb: SITU_LB, lb: SITU_LB,
swa_win: t.swa_win as i32, 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 { Ok(Self {
cache: WeightCache::new(ar), cache: WeightCache::new(ar),
d, d,
@@ -221,6 +238,7 @@ impl InklingEngine {
prefix: RefCell::new(PrefixCache::new()), prefix: RefCell::new(PrefixCache::new()),
states: RefCell::new(Vec::new()), states: RefCell::new(Vec::new()),
states_cap: Cell::new(0), states_cap: Cell::new(0),
max_context,
}) })
} }
@@ -228,6 +246,10 @@ impl InklingEngine {
self.vocab self.vocab
} }
pub fn max_context(&self) -> usize {
self.max_context
}
fn forward( fn forward(
&self, &self,
token: i32, token: i32,
@@ -286,15 +308,18 @@ pub fn serve_gen(
} }
let n_prompt = g.ids.len(); let n_prompt = g.ids.len();
let max_seq = (n_prompt + g.max_new + 2).min(MAX_CONTEXT); let max_context = eng.max_context();
if n_prompt + g.max_new + 2 > MAX_CONTEXT { // Clamp the budget to the window (reviewer 2026-12-02): only a prompt that
emit_all(emit, sess.on_error("prompt + max_new exceeds context window")); // 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; 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 // 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 // across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when
// a request crosses the bucket. // 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 { 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.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
eng.states_cap.set(need); eng.states_cap.set(need);
@@ -358,7 +383,7 @@ pub fn serve_gen(
let t0 = Instant::now(); let t0 = Instant::now();
let mut pos = start as i32; let mut pos = start as i32;
let mut history: Vec<i32> = g.ids[..start].to_vec(); 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 mut logits: Option<DeviceBuf> = None;
let chunk = prefill_chunk_size(); let chunk = prefill_chunk_size();
let suffix = &g.ids[start..]; let suffix = &g.ids[start..];
@@ -440,7 +465,7 @@ pub fn serve_gen(
eprintln!("[prefix] prompt-boundary save seq={pos}"); eprintln!("[prefix] prompt-boundary save seq={pos}");
} }
} }
if g.max_new == 0 { if effective_max_new == 0 {
stop.store(false, Ordering::Relaxed); stop.store(false, Ordering::Relaxed);
return; return;
} }
@@ -459,7 +484,7 @@ pub fn serve_gen(
} }
}; };
let mut finish = "length"; let mut finish = "length";
for step in 0..g.max_new { for step in 0..effective_max_new {
if stop.load(Ordering::Relaxed) { if stop.load(Ordering::Relaxed) {
sess.on_stop(); sess.on_stop();
let ms = t1.elapsed().as_secs_f64() * 1000.0; let ms = t1.elapsed().as_secs_f64() * 1000.0;
@@ -501,7 +526,7 @@ pub fn serve_gen(
break; break;
} }
history.push(rep.token); history.push(rep.token);
if step + 1 == g.max_new { if step + 1 == effective_max_new {
finish = "length"; finish = "length";
break; break;
} }
@@ -596,7 +621,7 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
let _ = writeln!(out, "{line}"); let _ = writeln!(out, "{line}");
let _ = out.flush(); 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 { loop {
if quit.load(Ordering::Relaxed) { if quit.load(Ordering::Relaxed) {
@@ -621,6 +646,27 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
mod tests { mod tests {
use super::*; 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 /// 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 /// "The capital of France is" (ids from the tokenizer) and check the emitted
/// lines: first `T` is 152717 (" Paris", exact reference match) and the /// lines: first `T` is 152717 (" Paris", exact reference match) and the