diff --git a/crates/aien-inference-abi/src/bin/own30b_wp_gate.rs b/crates/aien-inference-abi/src/bin/own30b_wp_gate.rs index 062a190e..8ecfdb63 100644 --- a/crates/aien-inference-abi/src/bin/own30b_wp_gate.rs +++ b/crates/aien-inference-abi/src/bin/own30b_wp_gate.rs @@ -26,7 +26,10 @@ //! the experts (`x_out`), the chosen experts, and every op of `--ops-layer`: //! OFF the engine's per-token OFF kernels, f32 activations (`control_step`, mode Off); //! CTRL the same, with the ON path's activation quantiser at every GEMM input (mode W8A8); -//! ON the whole-prompt path (`set_whole_prompt(true)`), recorder installed. +//! ON the whole-prompt path (`set_whole_prompt(true)`), recorder installed, one pass. +//! CHUNK the same ON path with the pass split in half, so the recorder is filled at each +//! pass's `from` row. CHUNK vs ON must stay inside the same budget B as ON vs CTRL, +//! and the first-step top-1 token must match. A trace no longer forces one pass. //! Then per layer the relative error (L2 over all tokens) of ON vs OFF, CTRL vs OFF and ON vs //! CTRL, the expert-set flips, the first-step logits, and the per-op errors at `--ops-layer`. //! @@ -233,6 +236,7 @@ fn on_run( ids: &[u32], mutant: WpMutant, ops_layer: usize, + chunk: usize, ) -> Run { engine .set_whole_prompt(true) @@ -240,6 +244,7 @@ fn on_run( engine .set_whole_prompt_device_host(DEVHOST.load(Ordering::Relaxed)) .expect("device router / combine refused"); + engine.set_whole_prompt_chunk(chunk); engine.whole_prompt_set_mutant(mutant).expect("mutant"); engine .whole_prompt_set_trace(Some(WpTrace::new(Some(ops_layer)))) @@ -271,8 +276,13 @@ fn on_run( "{name}: the whole-prompt path did not run (recorder empty)" ); let st = engine.whole_prompt_stats().cloned().unwrap_or_default(); + let passes = if chunk == 0 { + 1 + } else { + ids.len().div_ceil(chunk) + }; let want = if DEVHOST.load(Ordering::Relaxed) { - st.layers + st.layers.saturating_mul(passes) } else { 0 }; @@ -438,7 +448,7 @@ fn main() { "len {n} CTRL (OFF kernels + the ON quantiser at every GEMM input): {:.1} s", ctrl.secs )); - let on = on_run(&mut engine, "ON", &ids, WpMutant::None, ops_layer); + let on = on_run(&mut engine, "ON", &ids, WpMutant::None, ops_layer, 0); say(format!( "len {n} ON (whole-prompt path): {:.1} s", on.secs @@ -517,12 +527,73 @@ fn main() { "FAIL (ON differs from the W8A8 control beyond the rounding budget)" } )); + // Chunked arm: split the prompt so pass 2 reads the KV pass 1 wrote. The trace is + // indexed by `from`, so this is the path a recorder used to skip (it forced chunk 0). + let split = (n / 2).max(1); + let (chunk_pass, chunk_worst, chunk_top1) = if split < n { + let chunked = on_run( + &mut engine, + "ON_CHUNK", + &ids, + WpMutant::None, + ops_layer, + split, + ); + engine.set_whole_prompt_chunk(0); + let worst = max_out(&compare_layers(&chunked, &on)); + let same_top1 = argmax(&chunked.logits0) == argmax(&on.logits0); + let ok = worst <= budget && same_top1; + say(format!( + "len {n} CHUNK vs ON (chunk {split}): max_l relerr {worst:.3e} ({:.2} x B), top-1 {} vs {}: {}", + worst / budget, + argmax(&chunked.logits0), + argmax(&on.logits0), + if ok { + "PASS (chunked within the same budget, same top-1)" + } else { + "FAIL (chunked leaves the one-pass budget or the top-1 token)" + } + )); + (ok, worst, argmax(&chunked.logits0)) + } else { + say(format!( + "len {n} CHUNK: skipped (prompt shorter than two passes)" + )); + (true, 0.0, argmax(&on.logits0)) + }; + all_pass &= chunk_pass; + // Negative controls on the chunked arm. The chunk-0 mutants below do not exercise + // pass 2 reading pass-1 KV. Caught means the chunk rule fails: relerr above B, or + // a different first-step top-1. The bound is the same B, not a wider one. + if mutants && split < n { + for (mutant, name) in [ + (WpMutant::Routing, "MUT_ROUTING_CHUNK"), + (WpMutant::GateUpScales, "MUT_GUSCALES_CHUNK"), + ] { + let mu = on_run(&mut engine, name, &ids, mutant, ops_layer, split); + engine.set_whole_prompt_chunk(0); + let worst = max_out(&compare_layers(&mu, &on)); + let caught = worst > budget || argmax(&mu.logits0) != argmax(&on.logits0); + all_pass &= caught; + say(format!( + "len {n} NEGATIVE CONTROL {name} vs ON (chunk {split}): max_l relerr {worst:.3e} ({:.1} x B), top-1 {} vs {}: {}", + worst / budget, + argmax(&mu.logits0), + argmax(&on.logits0), + if caught { + "CAUGHT (chunk rule fails it)" + } else { + "NOT CAUGHT: the chunk rule is too loose" + } + )); + } + } let mut doc = serde_json::json!({ "len": n, "ops_layer": ops_layer, "secs": {"off": off.secs, "ctrl": ctrl.secs, "on": on.secs}, "layers": runs.iter().map(|r| (r.0, &r.3)).collect::>(), "ops": runs.iter().map(|r| (r.0, &r.4)).collect::>(), "logits0": {"cos_on_off": c_on_off, "cos_ctrl_off": c_ctrl_off, "cos_on_ctrl": c_on_ctrl, "top1_off": argmax(&off.logits0), "top1_ctrl": argmax(&ctrl.logits0), "top1_on": argmax(&on.logits0)}, - "rule": {"budget": budget, "on_ctrl": on_ctrl, "ratio": on_ctrl / budget, "ops": ops_ok, "pass": pass}, + "rule": {"budget": budget, "on_ctrl": on_ctrl, "ratio": on_ctrl / budget, "ops": ops_ok, "pass": pass, "chunk_vs_on": chunk_worst, "chunk_pass": chunk_pass, "chunk_top1": chunk_top1}, }); if mutants { let mut mres = Vec::new(); @@ -530,7 +601,7 @@ fn main() { (WpMutant::Routing, "MUT_ROUTING"), (WpMutant::GateUpScales, "MUT_GUSCALES"), ] { - let mu = on_run(&mut engine, name, &ids, mutant, ops_layer); + let mu = on_run(&mut engine, name, &ids, mutant, ops_layer, 0); let layers = compare_layers(&mu, &ctrl); let worst = max_out(&layers); let caught = worst > budget; diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega.rs b/crates/aien-inference-abi/src/qwen3_moe_omega.rs index d51e7499..8f6b88d1 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega.rs @@ -46,6 +46,9 @@ use crate::resident::transpose_bf16_for_upload; mod forward_pass; pub mod w8a8_control; mod whole_prompt; +pub use whole_prompt::{ + estimate_growth, PrefillGrowth, WholePromptFootprint, DEFAULT_CHUNK, SCRATCH_BYTES_PER_TOKEN, +}; /// The one-list decode token (OWN-30B L2 cut 2), off unless `OWN30B_DECODE_GRAPH=1`. #[path = "qwen3_moe_omega_dgraph.rs"] @@ -3344,6 +3347,16 @@ pub struct Qwen3MoeOmegaEngine { history: Vec, /// Whole-prompt prefill driver (OFF = None; `set_whole_prompt`). See `whole_prompt.rs`. whole_prompt: Option>, + /// Tokens per whole-prompt pass (0 = the whole prompt at once). Bounds the prompt-sized + /// scratch the driver keeps resident. See `whole_prompt::DEFAULT_CHUNK`. + whole_prompt_chunk: usize, + /// A whole-prompt pass has run: omega's per-layer KV mirror (one cache-sized copy of the KV, + /// allocated by the first pass and kept) exists. + whole_prompt_mirror_live: bool, + /// This request skips the whole-prompt driver and uses the classic `prefill_chunk` loop. + /// The door sets it when the KV mirror is not live and does not fit, so a cold server can + /// still answer and a later request can warm the mirror. Cleared when the request returns. + whole_prompt_suspended: bool, /// The host head (ADR 0004 adapter): the last forward call's final hidden state, unread. /// `None` once read or forgotten. Empty on the decode graph, whose head is its pending token. head_hidden: Option>, @@ -3380,6 +3393,9 @@ impl Qwen3MoeOmegaEngine { pos: 0, history: Vec::new(), whole_prompt: None, + whole_prompt_chunk: whole_prompt::DEFAULT_CHUNK, + whole_prompt_mirror_live: false, + whole_prompt_suspended: false, head_hidden: None, head_logits: Vec::new(), kv_lent: false, @@ -3427,6 +3443,13 @@ impl Qwen3MoeOmegaEngine { self.draft_allowed.is_some() } + /// Skips the whole-prompt driver for the next `generate_with` when `yes` (the classic + /// prefill loop runs instead, and does not allocate the KV mirror). The door clears it + /// when the request returns. + pub fn suspend_whole_prompt(&mut self, yes: bool) { + self.whole_prompt_suspended = yes; + } + /// Whether every layer runs attention and experts on the FP8 grouped GEMV (the only /// kernels that take one activation row per group, which batched prefill needs). pub fn batched_prefill_possible(&self) -> bool { diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega/whole_prompt.rs b/crates/aien-inference-abi/src/qwen3_moe_omega/whole_prompt.rs index b8b15041..d52a5bd6 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega/whole_prompt.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega/whole_prompt.rs @@ -87,6 +87,30 @@ impl Qwen3MoeOmegaEngine { .is_some_and(|w| w.device_host_work()) } + /// What the whole-prompt path holds now, copied out so a caller can price the next prefill + /// ([`WholePromptFootprint::growth`]) without waiting for the engine lock during a generation. + pub fn whole_prompt_footprint(&mut self) -> WholePromptFootprint { + let kv_bytes = self.kv.fused_kv().map_or(0, |f| f.kv_bytes() as u64); + WholePromptFootprint { + on: self.whole_prompt.is_some(), + mirror_live: self.whole_prompt_mirror_live, + scratch_tokens: self.whole_prompt.as_ref().map_or(0, |w| w.scratch_tokens()), + kv_bytes, + chunk: self.whole_prompt_chunk, + } + } + + /// Tokens per whole-prompt pass (0 = the whole prompt in one pass). Takes effect on the next + /// prompt; scratch already sized for a longer pass stays until the switch is turned off. + pub fn set_whole_prompt_chunk(&mut self, tokens: usize) { + self.whole_prompt_chunk = tokens; + } + + /// Tokens per whole-prompt pass (0 = unbounded). + pub fn whole_prompt_chunk(&self) -> usize { + self.whole_prompt_chunk + } + /// Whether `generate_with` will take the whole-prompt path. pub fn whole_prompt_on(&self) -> bool { self.whole_prompt.is_some() @@ -121,69 +145,303 @@ impl Qwen3MoeOmegaEngine { Ok(()) } - /// The last whole-prompt call's counters (launches, chip and host time). + /// The last whole-prompt call's counters (launches, chip and host time), summed over all of + /// its chunked passes, so they describe the whole prompt for any `whole_prompt_chunk`. pub fn whole_prompt_stats(&self) -> Option<&crate::qwen3_moe_omega_prefill::PrefillStats> { self.whole_prompt.as_ref().map(|w| &w.stats) } /// Called by `generate_with` before its chunk loop. When the switch is on and the path - /// applies, runs `tokens` (positions `self.pos ..`) as one whole prompt, stores them as - /// history, sets `hidden` and adds the timing; returns how many tokens it consumed (all or 0). + /// applies, runs `tokens` (positions `self.pos ..`) as whole-prompt passes of at most + /// `whole_prompt_chunk` tokens each, stores them as history, sets `hidden` and adds the + /// timing; returns how many tokens it consumed (all or 0). + /// + /// The passes are sequential and each one starts at the KV of the earlier ones, the same + /// start as prefix reuse. Whether that matches one pass is the W-L1G gate's chunked arm + /// (`own30b_wp_gate`), not an assumption. What this bounds is memory: the driver's scratch is + /// sized by the tokens of one pass (about 0.22 MB per token on the 30B). The served default + /// is one pass (`DEFAULT_CHUNK == 0`) until that gate has a chip receipt. pub(super) fn whole_prompt_prefill( &mut self, tokens: &[u32], hidden: &mut Vec, timing: &mut StepTiming, ) -> Result { - if tokens.is_empty() + if self.whole_prompt_suspended + || tokens.is_empty() || !self.trace_layers.is_empty() || self.routing_mutant || self.draft_on() { return Ok(0); } + let chunk = self.whole_prompt_chunk; + // Captured before the driver borrow: a traced chunked call sizes one recorder for the + // whole prompt, then each pass writes at its `from` row (`WpTrace::row0`). + let (n_layers, hidden_dim, top_k) = ( + self.weights.layers.len(), + self.weights.config.hidden, + self.weights.config.top_k, + ); let Some(wp) = self.whole_prompt.as_mut() else { return Ok(0); }; let Some(fused) = self.kv.fused_kv() else { return Ok(0); }; - let (pos0, m) = (self.pos, tokens.len()); - if pos0 + m > fused.capacity() { + let (start, m) = (self.pos, tokens.len()); + if start + m > fused.capacity() { return Err(format!( - "whole-prompt prefill: {pos0} + {m} tokens > context {}", + "whole-prompt prefill: {start} + {m} tokens > context {}", fused.capacity() )); } - let t = Instant::now(); - let out = wp.run(&self.weights, &mut fused.prefill_attention(), tokens, pos0); - let wall = t.elapsed().as_nanos() as u64; - // On failure the cache rows past pos0 are unspecified: forget them before reporting. - let h = match out { - Ok(h) => h, - Err(e) => { - self.rewind(pos0); - return Err(e); + let mut total = crate::qwen3_moe_omega_prefill::PrefillStats::default(); + if let Some(t) = wp.trace.as_mut() { + t.begin(m, n_layers, hidden_dim, top_k); + } + for (from, to) in chunk_spans(m, chunk) { + let pos0 = start + from; + if let Some(t) = wp.trace.as_mut() { + t.row0 = from; } - }; - fused.mark_filled(pos0 + m); - self.pos = pos0 + m; - self.history.extend_from_slice(tokens); - let st = &wp.stats; - timing.add(&StepTiming { - total_ns: wall, - attention_ns: st.attn_ns, - experts_ns: 0, - lm_head_ns: 0, - host_ns: st.host_ns, - chip_ns: st.chip_ns + st.attn_ns, - launches: st.launches() as u64, - route_ns: 0, - moe_host_ns: 0, - // Decode-graph counters (decode-mega): the prefill never runs the one-list decode. - ..StepTiming::default() - }); - *hidden = h; + let t = Instant::now(); + let out = wp.run( + &self.weights, + &mut fused.prefill_attention(), + &tokens[from..to], + pos0, + ); + let wall = t.elapsed().as_nanos() as u64; + // On failure the cache rows past `start` are unspecified: forget them before reporting. + let h = match out { + Ok(h) => h, + Err(e) => { + self.rewind(start); + return Err(e); + } + }; + fused.mark_filled(start + to); + // Only a pass that returned. A pass that allocates the mirror and then errors + // leaves this false, so the door keeps over-charging the mirror (the safe direction). + self.whole_prompt_mirror_live = true; + self.pos = start + to; + self.history.extend_from_slice(&tokens[from..to]); + let st = &wp.stats; + total.absorb(st); + timing.add(&StepTiming { + total_ns: wall, + attention_ns: st.attn_ns, + experts_ns: 0, + lm_head_ns: 0, + host_ns: st.host_ns, + chip_ns: st.chip_ns + st.attn_ns, + launches: st.launches() as u64, + route_ns: 0, + moe_host_ns: 0, + // Decode-graph counters (decode-mega): the prefill never runs the one-list decode. + ..StepTiming::default() + }); + *hidden = h; + } + if let Some(t) = wp.trace.as_mut() { + t.row0 = 0; + } + wp.stats = total; Ok(m) } } + +/// Served tokens per whole-prompt pass. `0` is one pass: chunking is opt-in. +/// +/// A chip compare of chunked vs one-pass outputs (the W-L1G gate's chunked arm, within that +/// gate's rounding budget) was not run for this default. Set `AIEN_SERVE_WP_CHUNK=8192` to opt +/// in. 8192 tokens bounds scratch near 1.8 GB (ledger L884: 5.9 GB for a 26,793-token pass, +/// about 0.22 MB per token, kept after the request) and still gives the prefill GEMMs thousands +/// of rows each. +pub const DEFAULT_CHUNK: usize = 0; + +/// `(from, to)` token ranges of the passes for `m` tokens: `chunk` tokens each, the last one +/// shorter; `chunk == 0` means one pass over everything. +pub(super) fn chunk_spans(m: usize, chunk: usize) -> impl Iterator { + let step = if chunk == 0 { m.max(1) } else { chunk }; + (0..m) + .step_by(step) + .map(move |from| (from, (from + step).min(m))) +} + +#[cfg(test)] +mod tests { + use super::{ + chunk_spans, estimate_growth, PrefillGrowth, DEFAULT_CHUNK, SCRATCH_BYTES_PER_TOKEN, + }; + + #[test] + fn served_default_is_one_pass_until_a_chip_compare_is_recorded() { + assert_eq!( + DEFAULT_CHUNK, 0, + "chunking is opt-in via AIEN_SERVE_WP_CHUNK until own30b_wp_gate's chunked arm has a chip receipt" + ); + } + + #[test] + fn spans_cover_every_token_once_in_order() { + for (m, chunk) in [ + (1, 8), + (8, 8), + (9, 8), + (26_793, 8192), + (66_000, 8192), + (5, 1), + ] { + let spans: Vec<_> = chunk_spans(m, chunk).collect(); + assert_eq!(spans.first().map(|s| s.0), Some(0), "m {m} chunk {chunk}"); + assert_eq!(spans.last().map(|s| s.1), Some(m), "m {m} chunk {chunk}"); + assert!(spans.windows(2).all(|w| w[0].1 == w[1].0), "contiguous"); + assert!( + spans.iter().all(|&(a, b)| a < b && b - a <= chunk), + "bounded" + ); + assert_eq!(spans.len(), m.div_ceil(chunk), "m {m} chunk {chunk}"); + } + } + + #[test] + fn zero_chunk_is_one_pass_and_empty_input_has_no_pass() { + assert_eq!( + chunk_spans(30_000, 0).collect::>(), + vec![(0, 30_000)] + ); + assert_eq!(chunk_spans(0, 8192).count(), 0); + assert_eq!(chunk_spans(0, 0).count(), 0); + } + + #[test] + fn chunked_stats_sum_to_the_whole_prompt() { + use crate::qwen3_moe_omega_prefill::PrefillStats; + let pass = |tokens, attn_dev| PrefillStats { + tokens, + layers: 48, + quant: 2, + attn: 48, + attn_dev, + chip_ns: 10, + router: 48, + ..Default::default() + }; + let mut total = PrefillStats::default(); + for (from, to) in chunk_spans(20_000, 8192) { + total.absorb(&pass(to - from, true)); + } + assert_eq!(total.tokens, 20_000); + assert_eq!(total.layers, 48); + assert_eq!((total.quant, total.attn, total.router), (6, 144, 144)); + assert_eq!(total.chip_ns, 30); + assert!(total.attn_dev); + total.absorb(&pass(1, false)); + assert!(!total.attn_dev, "one host-attention pass clears attn_dev"); + } + + const KV_128K: u64 = 48 * 256 * 1024 * 1024 + 48 * 20 * 1024; + + #[test] + fn first_prefill_pays_the_mirror_and_one_pass_of_scratch() { + let g = estimate_growth(false, KV_128K, 0, 66_000, 8192); + assert_eq!(g.mirror_bytes, KV_128K); + assert_eq!(g.scratch_bytes, 8192 * SCRATCH_BYTES_PER_TOKEN); + assert_eq!(g.total(), g.mirror_bytes + g.scratch_bytes); + } + + #[test] + fn a_66k_prompt_costs_no_more_than_an_8k_one_once_chunked() { + let long = estimate_growth(true, KV_128K, 0, 66_000, 8192); + let short = estimate_growth(true, KV_128K, 0, 8192, 8192); + assert_eq!(long, short); + // Unchunked it is the 14+ GB the live server grew by (ledger L884). + let unchunked = estimate_growth(true, KV_128K, 0, 66_000, 0); + assert!(unchunked.scratch_bytes > 15_000_000_000); + } + + #[test] + fn warm_driver_grows_only_past_its_high_water_mark() { + assert_eq!( + estimate_growth(true, KV_128K, 8192, 30_000, 8192), + PrefillGrowth::default() + ); + let g = estimate_growth(true, KV_128K, 100, 200, 8192); + assert_eq!(g.scratch_bytes, 100 * SCRATCH_BYTES_PER_TOKEN); + assert_eq!(g.mirror_bytes, 0); + } +} + +/// Bytes of prompt-sized scratch per token of a pass, 30B device-host path: measured on the live +/// server (ledger L884) as 5.9 GB for 26,793 tokens = 236 KB; the buffers add up to 231 KB +/// (qkv/out/oproj/xin/xq 74 KB, MoE act/aq 18 KB, `down` 64 KB twice-ish, router/combine 17 KB). +pub const SCRATCH_BYTES_PER_TOKEN: u64 = 240 * 1024; + +/// Memory a prefill adds to the process beyond the load footprint. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PrefillGrowth { + /// omega's KV mirror (one cache-sized copy of the KV, GPU-cached), allocated by the first + /// pass of the process and kept. Measured on the live 30B: 48 x 256 MiB at 131,072 positions. + pub mirror_bytes: u64, + /// Prompt-sized scratch beyond what the driver already holds. + pub scratch_bytes: u64, +} + +impl PrefillGrowth { + pub fn total(self) -> u64 { + self.mirror_bytes + self.scratch_bytes + } +} + +/// What a prefill of `new_tokens` uncached tokens allocates: the mirror if no pass has run yet, +/// and scratch for one pass (`chunk` tokens at most, 0 = all) above the `held_tokens` the driver +/// is already sized for. +pub fn estimate_growth( + mirror_live: bool, + kv_bytes: u64, + held_tokens: usize, + new_tokens: usize, + chunk: usize, +) -> PrefillGrowth { + let pass = if chunk == 0 { + new_tokens + } else { + new_tokens.min(chunk) + }; + PrefillGrowth { + mirror_bytes: if mirror_live { 0 } else { kv_bytes }, + scratch_bytes: pass.saturating_sub(held_tokens) as u64 * SCRATCH_BYTES_PER_TOKEN, + } +} + +/// The whole-prompt path's resident memory state, see `Qwen3MoeOmegaEngine::whole_prompt_footprint`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct WholePromptFootprint { + pub on: bool, + /// The KV mirror exists (a pass has run). + pub mirror_live: bool, + /// Tokens the prompt-sized scratch is sized for. + pub scratch_tokens: usize, + /// Bytes of the KV cache (the mirror is a copy of it). + pub kv_bytes: u64, + /// Tokens per pass (0 = unbounded). + pub chunk: usize, +} + +impl WholePromptFootprint { + /// Memory a prefill of `new_tokens` uncached tokens adds on top of this footprint. + pub fn growth(&self, new_tokens: usize) -> PrefillGrowth { + if !self.on { + return PrefillGrowth::default(); + } + estimate_growth( + self.mirror_live, + self.kv_bytes, + self.scratch_tokens, + new_tokens, + self.chunk, + ) + } +} diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill.rs b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill.rs index f0b7e7fc..b1304526 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill.rs @@ -233,6 +233,42 @@ impl PrefillStats { pub fn launches(&self) -> usize { self.quant + self.qkv + self.attn + self.o + self.gate_up + self.down } + + /// Adds the counters of one more pass over the same prompt (chunked prefill): counts and + /// times sum, `layers` is the per-pass depth, `attn_dev` holds only if every pass used it. + pub fn absorb(&mut self, p: &PrefillStats) { + let first = self.tokens == 0 && self.layers == 0; + self.tokens += p.tokens; + self.layers = self.layers.max(p.layers); + self.quant += p.quant; + self.qkv += p.qkv; + self.attn += p.attn; + self.o += p.o; + self.gate_up += p.gate_up; + self.down += p.down; + self.attn_dev = if first { + p.attn_dev + } else { + self.attn_dev && p.attn_dev + }; + self.chip_ns += p.chip_ns; + self.attn_ns += p.attn_ns; + self.host_ns += p.host_ns; + let (a, b) = (&mut self.prof, &p.prof); + a.embed_ns += b.embed_ns; + a.norm_in_ns += b.norm_in_ns; + a.resid_ns += b.resid_ns; + a.norm_post_ns += b.norm_post_ns; + a.router_ns += b.router_ns; + a.plan_ns += b.plan_ns; + a.tiles_ns += b.tiles_ns; + a.combine_ns += b.combine_ns; + a.final_ns += b.final_ns; + a.dev_ns += b.dev_ns; + a.wall_ns += b.wall_ns; + self.router += p.router; + self.combine += p.combine; + } } fn as_f32(b: &[u8]) -> Result<&[f32], String> { @@ -415,6 +451,12 @@ impl WholePromptPrefill { Ok(total) } + /// Tokens the prompt-sized scratch is sized for (0 before the first pass). The scratch is + /// kept between passes and only regrown, so this is its high-water mark. + pub fn scratch_tokens(&self) -> usize { + self.bufs.as_ref().map_or(0, |b| b.m) + } + fn ensure(&mut self, c: &Qwen3MoeConfig, m: usize, dev_attn: bool) -> Result<(), String> { let bm = self.dev.qgemm_bm(); if let Some(b) = &self.bufs { @@ -572,7 +614,7 @@ impl WholePromptPrefill { let mutant = self.mutant; let mut tr = self.trace.as_mut(); if let Some(t) = tr.as_deref_mut() { - t.begin(m, weights.layers.len(), h, top_k); + t.note_pass(m, weights.layers.len(), h, top_k); } for (l, layer) in weights.layers.iter().enumerate() { @@ -589,8 +631,10 @@ impl WholePromptPrefill { lap!(norm_in_ns); } st.host_ns += t.elapsed().as_nanos() as u64; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.x_norm = host(&b.xin, "xin")?[..m * h].to_vec(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let src = host(&b.xin, "xin")?[..m * h].to_vec(); + let t = tr.as_deref_mut().expect("trace"); + WpTrace::store_op(t.row0, &mut t.ops.x_norm, &src); } st.chip_ns += dev .quant(h, QuantIn::F32, m, b.xin.va(), b.xq.va(), b.xs.va()) @@ -665,17 +709,21 @@ impl WholePromptPrefill { b.xin.va() }; st.attn += 1; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.qkv = match (&b.qkv_dev, &b.qkv_host) { + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let qkv = match (&b.qkv_dev, &b.qkv_host) { (Some(d), _) => read_dev(&mut *dev, d.va(), m * qkv_n)?, (None, Some(hb)) => host(hb, "q|k|v")?[..m * qkv_n].to_vec(), (None, None) => Vec::new(), }; - t.ops.attn = if b.att_dev.is_some() { + let attn = if b.att_dev.is_some() { read_dev(&mut *dev, att_va, m * qd)? } else { host(&b.xin, "xin")?[..m * qd].to_vec() }; + let t = tr.as_deref_mut().expect("trace"); + let row0 = t.row0; + WpTrace::store_op(row0, &mut t.ops.qkv, &qkv); + WpTrace::store_op(row0, &mut t.ops.attn, &attn); } st.chip_ns += dev .quant(qd, QuantIn::F32, m, att_va, b.xq.va(), b.xs.va()) @@ -708,8 +756,10 @@ impl WholePromptPrefill { .qgemm(&call) .map_err(|err| format!("layer {l} o gemm x{m}: {err}"))?; st.o += 1; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.oproj = host(&b.oproj, "o projection")?[..m * h].to_vec(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let src = host(&b.oproj, "o projection")?[..m * h].to_vec(); + let t = tr.as_deref_mut().expect("trace"); + WpTrace::store_op(t.row0, &mut t.ops.oproj, &src); } // --- residual, post norm (into the quantiser input), routing, sort --- @@ -725,7 +775,8 @@ impl WholePromptPrefill { } }); if let Some(t) = tr.as_deref_mut() { - t.x_mid[l].copy_from_slice(&x); + let (row0, width) = (t.row0, t.hidden); + WpTrace::copy_f32(row0, &mut t.x_mid[l], &x, width); } lap!(resid_ns); let post = host_mut(&mut b.xin, "xin")?; @@ -739,15 +790,20 @@ impl WholePromptPrefill { if mutant == WpMutant::Routing { rotate_logits(&mut logits, e); } - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.post = post[..m * h].to_vec(); - t.ops.logits = logits.clone(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let post_rows = post[..m * h].to_vec(); + let logits_rows = logits.clone(); + let t = tr.as_deref_mut().expect("trace"); + let row0 = t.row0; + WpTrace::store_op(row0, &mut t.ops.post, &post_rows); + WpTrace::store_op(row0, &mut t.ops.logits, &logits_rows); } let plan = MoeBatchPlan::from_logits(&logits, m, e, top_k) .map_err(|err| format!("layer {l} routing: {err}"))?; let sort = ExpertSort::from_plan(&plan); if let Some(t) = tr.as_deref_mut() { - t.experts[l].copy_from_slice(&plan.topk_experts); + let (row0, k) = (t.row0, t.top_k); + WpTrace::copy_u32(row0, &mut t.experts[l], &plan.topk_experts, k); } as_u32_mut( b.rowidx @@ -846,10 +902,16 @@ impl WholePromptPrefill { ); lap!(combine_ns); if let Some(t) = tr.as_deref_mut() { - t.x_out[l].copy_from_slice(&x); + let (row0, width) = (t.row0, t.hidden); + WpTrace::copy_f32(row0, &mut t.x_out[l], &x, width); if t.ops_layer == Some(l) { - let moe: Vec = x.iter().zip(&t.x_mid[l]).map(|(a, b)| a - b).collect(); - t.ops.moe_out = moe; + let off = row0 * width; + let moe: Vec = x + .iter() + .zip(&t.x_mid[l][off..off + x.len()]) + .map(|(a, b)| a - b) + .collect(); + WpTrace::store_op(row0, &mut t.ops.moe_out, &moe); } } st.host_ns += t.elapsed().as_nanos() as u64; @@ -953,6 +1015,10 @@ pub struct WpTrace { pub m: usize, pub hidden: usize, pub top_k: usize, + /// First token row of the pass being recorded. `0` for a single pass. A chunked prefill + /// sizes the trace for the whole prompt (`begin`) and sets this to each pass's `from`, so + /// the W-L1G gate records every token instead of only the last pass. + pub row0: usize, /// Per layer `m x hidden`. pub x_mid: Vec>, pub x_out: Vec>, @@ -976,12 +1042,51 @@ impl WpTrace { self.m = m; self.hidden = hidden; self.top_k = top_k; + self.row0 = 0; self.x_mid = vec![vec![0.0f32; m * hidden]; layers]; self.x_out = vec![vec![0.0f32; m * hidden]; layers]; self.experts = vec![vec![0u32; m * top_k]; layers]; self.ops = WpOps::default(); } + /// Prepares this pass of `m_pass` tokens. A trace already sized (by [`Self::begin`]) for + /// every row through `row0 + m_pass` keeps those rows. A direct `run` sizes itself to this + /// pass, which replaces whatever the previous direct call recorded. + pub fn note_pass(&mut self, m_pass: usize, layers: usize, hidden: usize, top_k: usize) { + let end = self.row0.saturating_add(m_pass); + let ready = self.m > 0 + && end <= self.m + && self.layers() == layers + && self.hidden == hidden + && self.top_k == top_k; + if !ready { + self.begin(m_pass, layers, hidden, top_k); + } + } + + /// Copies one pass of `width`-wide rows into `dst` at [`Self::row0`]. + pub fn copy_f32(row0: usize, dst: &mut [f32], src: &[f32], width: usize) { + let off = row0.saturating_mul(width); + let n = src.len(); + dst[off..off + n].copy_from_slice(src); + } + + /// Copies one pass of `width`-wide rows into `dst` at `row0`. + pub fn copy_u32(row0: usize, dst: &mut [u32], src: &[u32], width: usize) { + let off = row0.saturating_mul(width); + let n = src.len(); + dst[off..off + n].copy_from_slice(src); + } + + /// Ops of one pass, in pass order. `row0 == 0` starts the vector (a new prompt or a + /// direct single pass). Later passes append. + pub fn store_op(row0: usize, dst: &mut Vec, src: &[f32]) { + if row0 == 0 { + dst.clear(); + } + dst.extend_from_slice(src); + } + pub fn layers(&self) -> usize { self.x_out.len() } diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/devhost.rs b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/devhost.rs index bccfca5a..e16ab600 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/devhost.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/devhost.rs @@ -47,7 +47,7 @@ use rayon::prelude::*; use super::{ as_u32_mut, host, host_mut, read_dev, rotate_logits, ExpertSort, PrefillStats, Region, - WholePromptPrefill, WpMutant, ATTN_OUT_SCALE, + WholePromptPrefill, WpMutant, WpTrace, ATTN_OUT_SCALE, }; use crate::moe_plan::{MoeBatchPlan, MoePlanError}; use crate::qwen3_moe_omega::{Qwen3MoeConfig, Qwen3MoeOmegaWeights}; @@ -250,7 +250,7 @@ impl WholePromptPrefill { let mutant = self.mutant; let mut tr = self.trace.as_mut(); if let Some(t) = tr.as_deref_mut() { - t.begin(m, weights.layers.len(), h, top_k); + t.note_pass(m, weights.layers.len(), h, top_k); } for (l, layer) in weights.layers.iter().enumerate() { @@ -267,8 +267,10 @@ impl WholePromptPrefill { lap!(norm_in_ns); } st.host_ns += t.elapsed().as_nanos() as u64; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.x_norm = host(&b.xin, "xin")?[..m * h].to_vec(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let src = host(&b.xin, "xin")?[..m * h].to_vec(); + let t = tr.as_deref_mut().expect("trace"); + WpTrace::store_op(t.row0, &mut t.ops.x_norm, &src); } st.chip_ns += dev .quant(h, QuantIn::F32, m, b.xin.va(), b.xq.va(), b.xs.va()) @@ -341,17 +343,21 @@ impl WholePromptPrefill { b.xin.va() }; st.attn += 1; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.qkv = match (&b.qkv_dev, &b.qkv_host) { + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let qkv = match (&b.qkv_dev, &b.qkv_host) { (Some(d), _) => read_dev(&mut *dev, d.va(), m * qkv_n)?, (None, Some(hb)) => host(hb, "q|k|v")?[..m * qkv_n].to_vec(), (None, None) => Vec::new(), }; - t.ops.attn = if b.att_dev.is_some() { + let attn = if b.att_dev.is_some() { read_dev(&mut *dev, att_va, m * qd)? } else { host(&b.xin, "xin")?[..m * qd].to_vec() }; + let t = tr.as_deref_mut().expect("trace"); + let row0 = t.row0; + WpTrace::store_op(row0, &mut t.ops.qkv, &qkv); + WpTrace::store_op(row0, &mut t.ops.attn, &attn); } st.chip_ns += dev .quant(qd, QuantIn::F32, m, att_va, b.xq.va(), b.xs.va()) @@ -382,8 +388,10 @@ impl WholePromptPrefill { .qgemm(&call) .map_err(|err| format!("layer {l} o gemm x{m}: {err}"))?; st.o += 1; - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.oproj = host(&b.oproj, "o projection")?[..m * h].to_vec(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let src = host(&b.oproj, "o projection")?[..m * h].to_vec(); + let t = tr.as_deref_mut().expect("trace"); + WpTrace::store_op(t.row0, &mut t.ops.oproj, &src); } lap!(dev_ns); @@ -400,7 +408,8 @@ impl WholePromptPrefill { }); } if let Some(t) = tr.as_deref_mut() { - t.x_mid[l].copy_from_slice(&x); + let (row0, width) = (t.row0, t.hidden); + WpTrace::copy_f32(row0, &mut t.x_mid[l], &x, width); } lap!(resid_ns); { @@ -423,9 +432,13 @@ impl WholePromptPrefill { if mutant == WpMutant::Routing { rotate_logits(&mut logits, e); } - if let Some(t) = tr.as_deref_mut().filter(|t| t.ops_layer == Some(l)) { - t.ops.post = host(&d.post, "post")?[..m * h].to_vec(); - t.ops.logits = logits.clone(); + if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { + let post_rows = host(&d.post, "post")?[..m * h].to_vec(); + let logits_rows = logits.clone(); + let t = tr.as_deref_mut().expect("trace"); + let row0 = t.row0; + WpTrace::store_op(row0, &mut t.ops.post, &post_rows); + WpTrace::store_op(row0, &mut t.ops.logits, &logits_rows); } lap!(router_ns); // --- routing plan and sort (host, token-parallel exact replica) --- @@ -433,7 +446,8 @@ impl WholePromptPrefill { .map_err(|err| format!("layer {l} routing: {err}"))?; let sort = ExpertSort::from_plan(&plan); if let Some(t) = tr.as_deref_mut() { - t.experts[l].copy_from_slice(&plan.topk_experts); + let (row0, k) = (t.row0, t.top_k); + WpTrace::copy_u32(row0, &mut t.experts[l], &plan.topk_experts, k); } as_u32_mut( b.rowidx @@ -537,9 +551,16 @@ impl WholePromptPrefill { }); } if let Some(t) = tr.as_deref_mut() { - t.x_out[l].copy_from_slice(&x); + let (row0, width) = (t.row0, t.hidden); + WpTrace::copy_f32(row0, &mut t.x_out[l], &x, width); if t.ops_layer == Some(l) { - t.ops.moe_out = x.iter().zip(&t.x_mid[l]).map(|(a, b)| a - b).collect(); + let off = row0 * width; + let moe: Vec = x + .iter() + .zip(&t.x_mid[l][off..off + x.len()]) + .map(|(a, b)| a - b) + .collect(); + WpTrace::store_op(row0, &mut t.ops.moe_out, &moe); } } st.host_ns += t.elapsed().as_nanos() as u64; diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests.rs b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests.rs index 38e36a9d..d0c8e53e 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests.rs @@ -923,5 +923,99 @@ fn cache_weights_refusal_leaves_the_in_place_path_working() { assert!(max_rel_diff(&got, &reference(&tm, &TOKENS)) <= TOL); } +fn traces_agree(a: &WpTrace, b: &WpTrace) { + assert_eq!(a.m, b.m, "recorder length"); + assert_eq!((a.hidden, a.top_k), (b.hidden, b.top_k)); + assert_eq!(a.experts, b.experts, "routing"); + for (i, (x, y)) in a.x_mid.iter().zip(&b.x_mid).enumerate() { + let d = max_rel_diff(x, y); + assert!(d <= TOL, "x_mid layer {i}: {d}"); + } + for (i, (x, y)) in a.x_out.iter().zip(&b.x_out).enumerate() { + let d = max_rel_diff(x, y); + assert!(d <= TOL, "x_out layer {i}: {d}"); + } + for (x, y, name) in [ + (&a.ops.x_norm, &b.ops.x_norm, "x_norm"), + (&a.ops.qkv, &b.ops.qkv, "qkv"), + (&a.ops.attn, &b.ops.attn, "attn"), + (&a.ops.oproj, &b.ops.oproj, "oproj"), + (&a.ops.post, &b.ops.post, "post"), + (&a.ops.logits, &b.ops.logits, "logits"), + (&a.ops.moe_out, &b.ops.moe_out, "moe_out"), + ] { + let d = max_rel_diff(x, y); + assert!(d <= TOL, "{name}: {d}"); + } +} + +/// The W-L1G recorder used to be sized per pass, so a chunked prompt kept only the last pass +/// and the gate forced one pass. Chunked rows land at `row0` and match one pass within [`TOL`]. +#[test] +fn chunked_trace_matches_one_pass_within_the_host_bound() { + let (tm, mut one, mut a1, _) = setup(4, false); + one.trace = Some(WpTrace::new(Some(1))); + let h1 = one.run(&tm.weights, &mut a1, &TOKENS, 0).unwrap(); + let t1 = one.trace.take().unwrap(); + + let (tm2, mut ch, mut a2, _) = setup(4, false); + let c = &tm2.weights.config; + let mut trace = WpTrace::new(Some(1)); + trace.begin(TOKENS.len(), tm2.weights.layers.len(), c.hidden, c.top_k); + ch.trace = Some(trace); + ch.run(&tm2.weights, &mut a2, &TOKENS[..3], 0).unwrap(); + ch.trace.as_mut().unwrap().row0 = 3; + let h2 = ch.run(&tm2.weights, &mut a2, &TOKENS[3..], 3).unwrap(); + let mut t2 = ch.trace.take().unwrap(); + t2.row0 = 0; + assert_eq!( + t2.m, + TOKENS.len(), + "the chunked recorder must cover the whole prompt" + ); + let d = max_rel_diff(&h1, &h2); + assert!(d <= TOL, "chunked vs one pass final hidden: {d}"); + traces_agree(&t1, &t2); + assert!(max_rel_diff(&h2, &reference(&tm2, &TOKENS)) <= TOL); +} + +/// Pass 2 that does not read pass-1 KV must leave the one-pass result. This is the chunked +/// arm's negative control: the host bound [`TOL`] is not widened to hide it. +#[test] +fn chunked_pass_that_ignores_prior_kv_is_outside_the_host_bound() { + let (tm, mut one, mut a1, _) = setup(4, false); + let h1 = one.run(&tm.weights, &mut a1, &TOKENS, 0).unwrap(); + let (tm2, mut bad, _, _) = setup(4, false); + let c = tm2.weights.config.clone(); + let mut fresh = FakeAttn { + core: AttnCore::new(&c), + log: Rc::new(RefCell::new(Vec::new())), + dev: None, + qkv_n: c.qkv_n(), + qd: c.q_dim(), + }; + let h2 = bad.run(&tm2.weights, &mut fresh, &TOKENS[3..], 0).unwrap(); + let d = max_rel_diff(&h1, &h2); + assert!( + d > TOL, + "ignoring pass-1 KV must leave the host bound, diff {d}" + ); +} + +#[test] +fn chunked_routing_mutant_leaves_the_one_pass_bound() { + let (tm, mut one, mut a1, _) = setup(4, false); + let h1 = one.run(&tm.weights, &mut a1, &TOKENS, 0).unwrap(); + let (tm2, mut bad, mut a2, _) = setup(4, false); + bad.mutant = WpMutant::Routing; + bad.run(&tm2.weights, &mut a2, &TOKENS[..3], 0).unwrap(); + let h2 = bad.run(&tm2.weights, &mut a2, &TOKENS[3..], 3).unwrap(); + let d = max_rel_diff(&h1, &h2); + assert!( + d > TOL, + "a chunked routing mutant must leave the host bound, diff {d}" + ); +} + /// W-L1G-D: the device router logits + combine path (fake device in tests/devhost.rs). mod devhost; diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests/devhost.rs b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests/devhost.rs index 5beb775e..c3deb753 100644 --- a/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests/devhost.rs +++ b/crates/aien-inference-abi/src/qwen3_moe_omega_prefill/tests/devhost.rs @@ -172,6 +172,31 @@ fn traced( (out, drv.trace.take().unwrap()) } +#[test] +fn chunked_device_trace_matches_one_pass_within_the_host_bound() { + let (tm, mut one, mut a1, _) = setup_dh(4, true, Some(3)); + one.set_device_host_work(&tm.weights, true).unwrap(); + one.trace = Some(WpTrace::new(Some(1))); + let h1 = one.run(&tm.weights, &mut a1, &TOKENS, 0).unwrap(); + let t1 = one.trace.take().unwrap(); + + let (tm2, mut ch, mut a2, _) = setup_dh(4, true, Some(3)); + ch.set_device_host_work(&tm2.weights, true).unwrap(); + let c = &tm2.weights.config; + let mut trace = WpTrace::new(Some(1)); + trace.begin(TOKENS.len(), tm2.weights.layers.len(), c.hidden, c.top_k); + ch.trace = Some(trace); + ch.run(&tm2.weights, &mut a2, &TOKENS[..3], 0).unwrap(); + ch.trace.as_mut().unwrap().row0 = 3; + let h2 = ch.run(&tm2.weights, &mut a2, &TOKENS[3..], 3).unwrap(); + let mut t2 = ch.trace.take().unwrap(); + t2.row0 = 0; + assert_eq!(t2.m, TOKENS.len()); + let d = max_rel_diff(&h1, &h2); + assert!(d <= TOL, "chunked vs one pass final hidden: {d}"); + super::traces_agree(&t1, &t2); +} + #[test] fn device_router_and_combine_equal_the_host_path_bit_for_bit() { for (bm, dev_attn, t, split) in [ diff --git a/crates/aien-serve-http/src/engine.rs b/crates/aien-serve-http/src/engine.rs index 2a5abade..fd6fbb6f 100644 --- a/crates/aien-serve-http/src/engine.rs +++ b/crates/aien-serve-http/src/engine.rs @@ -81,6 +81,9 @@ pub enum EngineError { Failed(String), /// The shared chip is held by another job; the server answers 503 and the client retries. Busy(String), + /// Memory admission refused the prompt (it would need more host memory than is free); the + /// server answers 413 `prompt_exceeds_memory_budget`, the same as a refusal in `prepare`. + MemoryExceeded(String), } impl fmt::Display for EngineError { @@ -92,6 +95,7 @@ impl fmt::Display for EngineError { "prompt of {len} tokens exceeds the context window of {max}" ) } + Self::MemoryExceeded(m) => write!(f, "{m}"), Self::Failed(m) => write!(f, "engine failed: {m}"), Self::Busy(m) => write!(f, "GPU busy with another job: {m}"), } @@ -116,6 +120,12 @@ pub trait Engine: Send + Sync { params: &GenerateParams, on_token: &mut dyn FnMut(u32) -> bool, ) -> Result; + /// Memory admission, asked before the generation lock: `Err(why)` when `prompt` would need + /// more host memory than the machine has free, so the server can answer with a clear 4xx + /// instead of letting the kernel OOM-kill the process. The default admits everything. + fn admit(&self, _prompt: &[u32]) -> Result<(), String> { + Ok(()) + } /// Persistent KV status and counters for `/health` (sc#505). `None` (the default, and the /// omega door with `AIEN_KV_STORE_DIR` unset) leaves `/health` exactly as it was. fn persistence_status(&self) -> Option { @@ -314,6 +324,11 @@ pub struct StubEngine { reply: Vec, per_token_delay: Duration, max_context: usize, + /// `Some(why)`: [`Engine::admit`] refuses every prompt (tests the memory-refusal answer). + admit_refusal: Option, + /// `Some(why)`: `generate` refuses with [`EngineError::MemoryExceeded`] after `admit` passed + /// (memory fell between the server's check and the engine's own, as in the omega door). + generate_refusal: Option, } impl StubEngine { @@ -322,6 +337,8 @@ impl StubEngine { reply, per_token_delay: Duration::ZERO, max_context: 4096, + admit_refusal: None, + generate_refusal: None, } } @@ -334,6 +351,16 @@ impl StubEngine { self.max_context = max_context; self } + + pub fn with_admit_refusal(mut self, why: &str) -> Self { + self.admit_refusal = Some(why.to_string()); + self + } + + pub fn with_generate_refusal(mut self, why: &str) -> Self { + self.generate_refusal = Some(why.to_string()); + self + } } impl Engine for StubEngine { @@ -341,6 +368,10 @@ impl Engine for StubEngine { "stub" } + fn admit(&self, _prompt: &[u32]) -> Result<(), String> { + self.admit_refusal.clone().map_or(Ok(()), Err) + } + fn max_context_tokens(&self) -> usize { self.max_context } @@ -354,6 +385,9 @@ impl Engine for StubEngine { if prompt.is_empty() { return Err(EngineError::Failed("empty prompt".into())); } + if let Some(why) = &self.generate_refusal { + return Err(EngineError::MemoryExceeded(why.clone())); + } if prompt.len() >= self.max_context { return Err(EngineError::PromptTooLong { len: prompt.len(), diff --git a/crates/aien-serve-http/src/omega_engine.rs b/crates/aien-serve-http/src/omega_engine.rs index 3cfaa429..d8202a99 100644 --- a/crates/aien-serve-http/src/omega_engine.rs +++ b/crates/aien-serve-http/src/omega_engine.rs @@ -25,10 +25,15 @@ use std::fs::{File, OpenOptions}; use std::os::fd::AsRawFd; use std::path::{Path, PathBuf}; +#[cfg(test)] +use std::sync::atomic::AtomicBool; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use aien_inference_abi::qwen3_moe_omega::{self as omega, LoadReport, OmegaEngine, WeightFormat}; +use aien_inference_abi::qwen3_moe_omega::{ + PrefillGrowth, WholePromptFootprint, SCRATCH_BYTES_PER_TOKEN, +}; use crate::engine::{Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams}; use crate::kv_persist::PersistState; @@ -41,6 +46,101 @@ pub const LOCK_WAIT: Duration = Duration::from_secs(30); /// Host memory the load needs free (the model is 30.5 GB resident plus the KV pool and /// loader transients; the rule leaves room for another 30 GB job). pub const LOAD_MIN_FREE_GB: f64 = 45.0; +/// Host memory a prefill must leave free (the box also runs the other model, builds and tests). +pub const ADMIT_RESERVE_BYTES: u64 = 6 << 30; +/// Environment override of tokens per whole-prompt pass. Unset keeps the engine default +/// ([`aien_inference_abi::qwen3_moe_omega::DEFAULT_CHUNK`], one pass). `8192` opts into +/// chunked prefill. `0` is one pass. +pub const WP_CHUNK_ENV: &str = "AIEN_SERVE_WP_CHUNK"; + +/// `MemAvailable` from `/proc/meminfo` text, bytes. +pub fn parse_mem_available(meminfo: &str) -> Option { + let line = meminfo.lines().find(|l| l.starts_with("MemAvailable:"))?; + let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + Some(kb * 1024) +} + +/// Admission rule: the prefill's growth plus [`ADMIT_RESERVE_BYTES`] must fit `available`. +/// `Err` names the numbers and the longest prompt that would pass right now. `None` (meminfo +/// unreadable) admits, and so does a prefill that adds nothing (a warm chunked path, or the +/// whole-prompt path off): refusing it would not keep a byte free. +pub fn admit_growth( + growth: PrefillGrowth, + available: Option, + prompt_tokens: usize, +) -> Result<(), String> { + let Some(avail) = available else { + return Ok(()); + }; + if growth.total() == 0 { + return Ok(()); + } + let gb = |b: u64| b as f64 / 1e9; + if avail >= growth.total().saturating_add(ADMIT_RESERVE_BYTES) { + return Ok(()); + } + let room = avail + .saturating_sub(ADMIT_RESERVE_BYTES) + .saturating_sub(growth.mirror_bytes); + let fits = room / SCRATCH_BYTES_PER_TOKEN; + // `fits == 0` is not a length the client can send. Saying "at most about 0 tokens" left a + // cold server with no request that could ever warm the KV mirror. + let advice = if fits == 0 { + "retry when memory is free (nothing shorter fits beside the KV mirror and the reserve)" + .to_string() + } else { + format!("retry when memory is free or send at most about {fits} tokens now") + }; + Err(format!( + "prompt of {prompt_tokens} tokens needs {:.1} GB more host memory ({:.1} GB KV mirror + {:.1} GB prompt scratch) but only {:.1} GB is available and {:.0} GB must stay free; {advice}", + gb(growth.total()), + gb(growth.mirror_bytes), + gb(growth.scratch_bytes), + gb(avail), + gb(ADMIT_RESERVE_BYTES), + )) +} + +/// What the door runs after admission. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrefillAdmit { + /// The whole-prompt driver, including its KV mirror on the first pass. + WholePrompt, + /// Whole-prompt does not fit and the mirror is not live. The classic prefill loop does + /// not allocate the mirror, at every free-memory reading: a tighter box must not be + /// served while a looser one is refused. + Classic, +} + +/// Tokens the engine prefills: `prompt[reused..]`. `reused` is the reusable prefix +/// (common history, at most `prompt_len - 1`, because the last prompt token is always stepped). +pub fn priced_tokens(prompt_len: usize, reused: usize) -> usize { + let kept = reused.min(prompt_len.saturating_sub(1)); + prompt_len.saturating_sub(kept) +} + +/// Admission for one prompt. `prompt_tokens` is the uncached suffix ([`priced_tokens`]), not +/// the whole prompt. More free memory never turns a serve into a refusal: when whole-prompt +/// fits it is used; when it does not and the mirror is not live, the classic path serves at +/// every reading (11 GB and 20 GB alike). A live mirror prices scratch only, so a refusal +/// there stays a refusal at every lower reading. +pub fn admit_request( + fp: &WholePromptFootprint, + available: Option, + prompt_tokens: usize, +) -> Result { + if !fp.on { + return Ok(PrefillAdmit::WholePrompt); + } + let growth = fp.growth(prompt_tokens); + if admit_growth(growth, available, prompt_tokens).is_ok() { + return Ok(PrefillAdmit::WholePrompt); + } + if !fp.mirror_live && growth.mirror_bytes > 0 { + return Ok(PrefillAdmit::Classic); + } + admit_growth(growth, available, prompt_tokens).map(|()| PrefillAdmit::WholePrompt) +} /// Prefill path of the door (OWN-30B release candidate, W-RC 2026-10-14). Both switches are ON /// by default: the whole prompt goes through omega's prefill GEMMs and attention in one pass @@ -116,7 +216,38 @@ impl PrefillMode { /// An exclusive hold of the hive's GPU lock (released on drop), or nothing at all when an /// ancestor verifiably holds it for this process's life ([`crate::chip_reservation`]). -pub struct GpuLock(#[allow(dead_code)] Option); +pub struct GpuLock { + #[allow(dead_code)] + file: Option, + /// Runs while the flock is still held, before the file drops. Tests sample + /// suspension here: the next request cannot take the lock until this returns. + #[cfg(test)] + on_release: Option>, +} + +impl GpuLock { + fn new(file: Option) -> Self { + Self { + file, + #[cfg(test)] + on_release: None, + } + } + + #[cfg(test)] + fn on_release(&mut self, hook: impl FnOnce() + Send + 'static) { + self.on_release = Some(Box::new(hook)); + } +} + +impl Drop for GpuLock { + fn drop(&mut self) { + #[cfg(test)] + if let Some(hook) = self.on_release.take() { + hook(); + } + } +} impl GpuLock { /// Takes the hive's lock ([`GPU_LOCK_PATH`]), polling until `wait` has passed. @@ -127,7 +258,7 @@ impl GpuLock { /// Under a verified inherited reservation there is nothing to take: `Some(lock)`. fn inherited() -> Option { - crate::chip_reservation::inherited().then_some(Self(None)) + crate::chip_reservation::inherited().then_some(Self::new(None)) } /// [`Self::acquire`] on the lock file at `path` (tests pass a private file). @@ -147,7 +278,7 @@ impl GpuLock { // SAFETY: flock on a valid open descriptor; non-blocking so the wait is bounded. let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if rc == 0 { - return Ok(Self(Some(file))); + return Ok(Self::new(Some(file))); } let err = std::io::Error::last_os_error(); if err.raw_os_error() != Some(libc::EWOULDBLOCK) { @@ -183,7 +314,7 @@ impl GpuLock { .map_err(|e| format!("{}: {e}", path.display()))?; // SAFETY: flock on a valid open descriptor; non-blocking fast path. if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { - return Ok(Self(Some(file))); + return Ok(Self::new(Some(file))); } let (tx, rx) = mpsc::channel(); let gave_up = Arc::new(AtomicBool::new(false)); @@ -205,7 +336,7 @@ impl GpuLock { } }); match rx.recv_timeout(wait) { - Ok(r) => r.map(|f| Self(Some(f))), + Ok(r) => r.map(|f| Self::new(Some(f))), Err(_) => { gave_up.store(true, Ordering::SeqCst); // The helper may have sent just before the flag: take and drop it. @@ -243,18 +374,106 @@ pub struct OmegaDoor { lock_path: PathBuf, /// Prompt tokens the last generation reused (RAM or restored prefix). reused_last: AtomicUsize, + /// The whole-prompt path's resident state after the last generation, for [`Engine::admit`]. + footprint: std::sync::Mutex, + /// Test seam: bytes `admit` treats as `MemAvailable`. `None` reads `/proc/meminfo`. + #[cfg(test)] + available_probe: Option Option + Send + Sync>>, + /// Test seam: runs where the persistent-KV fetch returns, before the GPU lock. The race + /// test drops the probe's available bytes here, the way a fetched payload drops + /// `MemAvailable`. + #[cfg(test)] + fetch_probe: Option>, + /// Mirrors `whole_prompt_suspended` for the lock-drop hook. Set with the suspension, + /// cleared by [`ResumeWholePrompt`]. + #[cfg(test)] + suspend_visible: std::sync::Arc, + /// Called from [`GpuLock`]'s drop, while the flock is still held. + #[cfg(test)] + lock_release_hook: Option>, } impl OmegaDoor { /// A door over an already built engine, taking the GPU lock at `lock_path` around each /// generation (tests: a private lock file and the host test engine). Persistence off. pub fn from_parts(engine: OmegaEngine, lock_path: PathBuf, lock_wait: Duration) -> Self { + let footprint = engine + .with_engine(|e| e.whole_prompt_footprint()) + .unwrap_or_default(); Self { persist: PersistState::Off, engine, lock_wait, lock_path, reused_last: AtomicUsize::new(0), + footprint: std::sync::Mutex::new(footprint), + #[cfg(test)] + available_probe: None, + #[cfg(test)] + fetch_probe: None, + #[cfg(test)] + suspend_visible: std::sync::Arc::new(AtomicBool::new(false)), + #[cfg(test)] + lock_release_hook: None, + } + } + + /// Uncached suffix `generate_inner` prefills (`prompt[reused..]`), after any restore + /// already imported into the engine. + fn prefill_len(&self, prompt: &[u32]) -> usize { + let reused = self + .engine + .with_engine(|e| e.reusable_prefix(prompt)) + .unwrap_or(0); + priced_tokens(prompt.len(), reused) + } + + fn current_available(&self) -> Option { + #[cfg(test)] + if let Some(p) = &self.available_probe { + return p(); + } + std::fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|m| parse_mem_available(&m)) + } + + fn decide(&self, prompt_tokens: usize) -> Result { + let fp = self.footprint.lock().map_err(|e| e.to_string())?; + admit_request(&fp, self.current_available(), prompt_tokens) + } + + /// Copies the engine footprint after `generate_with` returns, including on error. + /// `whole_prompt_mirror_live` is set only after a pass returns, so a pass that allocates + /// the mirror and then errors still reads cold. The next request over-charges that mirror. + /// The over-charge is the safe direction: this copy does not mark a mirror the engine has + /// not recorded. + fn note_footprint(&self) { + if let Ok(fp) = self.engine.with_engine(|e| e.whole_prompt_footprint()) { + if let Ok(mut slot) = self.footprint.lock() { + *slot = fp; + } + } + } + + /// Drops the suspension guard, then the GPU lock. The guard's drop clears + /// `suspend_whole_prompt` while the flock is still held. + fn release_lock(&self, resume: ResumeWholePrompt<'_>, lock: GpuLock) { + #[cfg(test)] + { + let mut lock = lock; + if let Some(hook) = self.lock_release_hook.clone() { + lock.on_release(move || hook()); + } + drop(resume); + drop(lock); + return; + } + #[cfg(not(test))] + { + drop(resume); + let _ = self; + drop(lock); } } @@ -361,6 +580,10 @@ impl OmegaDoor { engine.with_engine(|e| -> Result<(), String> { e.set_whole_prompt(prefill.whole_prompt) .map_err(|m| format!("{m} (start with --whole-prompt off to use the chunked prefill)"))?; + if let Ok(v) = std::env::var(WP_CHUNK_ENV) { + let n: usize = v.trim().parse().map_err(|_| format!("{WP_CHUNK_ENV} must be a token count (0 = one pass), got {v:?}"))?; + e.set_whole_prompt_chunk(n); + } if prefill.whole_prompt { e.set_whole_prompt_device_host(prefill.device_host) .map_err(|m| format!("{m} (start with --prefill-device-host off to keep routing on the host)"))?; @@ -419,6 +642,24 @@ impl OmegaDoor { } } +/// Clears a one-request classic-prefill suspension. Drop it before the GPU lock: the next +/// request can take the lock only after that drop has run. +struct ResumeWholePrompt<'a> { + engine: &'a omega::OmegaEngine, + #[cfg(test)] + visible: Option>, +} + +impl Drop for ResumeWholePrompt<'_> { + fn drop(&mut self) { + let _ = self.engine.with_engine(|e| e.suspend_whole_prompt(false)); + #[cfg(test)] + if let Some(v) = &self.visible { + v.store(false, Ordering::SeqCst); + } + } +} + impl Engine for OmegaDoor { fn kind(&self) -> &str { self.engine.kind() @@ -428,6 +669,12 @@ impl Engine for OmegaDoor { self.engine.max_context_tokens() } + fn admit(&self, prompt: &[u32]) -> Result<(), String> { + // Early check, before the generation lock. Prices the uncached suffix already in + // RAM. `generate` restores persistent KV, then prices `prompt[reused..]` again. + self.decide(self.prefill_len(prompt)).map(|_| ()) + } + fn generate( &self, prompt: &[u32], @@ -465,41 +712,86 @@ impl Engine for OmegaDoor { .unwrap_or(0); pk.fetch(prompt, in_ram) }); + #[cfg(test)] + if let Some(p) = &self.fetch_probe { + p(); + } let t_lock = Instant::now(); let lock = GpuLock::acquire_at(&self.lock_path, self.lock_wait).map_err(EngineError::Busy)?; let lock_wait_ms = t_lock.elapsed().as_millis(); + // Restore before admission so the reusable prefix includes the imported tokens. + // `note_restored` waits until admission succeeds: a 413 must not count a restore. + let mut restored = false; if let (Some(pk), Some(f)) = (persist, fetched.as_ref()) { // All or nothing: on error the engine is reset and the prompt is prefilled. match self .engine .with_engine(|e| e.restore_kv(&prompt[..f.tokens], &f.payload)) { - Ok(Ok(())) => pk.note_restored(f), + Ok(Ok(())) => restored = true, Ok(Err(m)) | Err(m) => { pk.note_import_failed(); eprintln!("aien-serve-http: persistent KV: restore of {} tokens refused ({m}); prefilling", f.tokens); } } } + // The payload is still resident here, and the lock wait has already happened, so this + // reading sees both. The length is the uncached suffix, not the whole prompt. + let admission = match self.decide(self.prefill_len(prompt)) { + Ok(a) => a, + Err(m) => { + if restored { + let _ = self.engine.with_engine(|e| e.reset()); + } + return Err(EngineError::MemoryExceeded(m)); + } + }; + if restored { + if let (Some(pk), Some(f)) = (persist, fetched.as_ref()) { + pk.note_restored(f); + } + } + let classic = matches!(admission, PrefillAdmit::Classic); + #[cfg(test)] + self.suspend_visible.store(classic, Ordering::SeqCst); + self.engine + .with_engine(|e| e.suspend_whole_prompt(classic)) + .map_err(EngineError::Failed)?; + let resume = ResumeWholePrompt { + engine: &self.engine, + #[cfg(test)] + visible: Some(std::sync::Arc::clone(&self.suspend_visible)), + }; drop(fetched); // The server's own sampler, so CPU and Omega engines pick tokens the same way. let mut observer = SamplingObserver::new(p); let mut sampler = |logits: &[f32], step: usize| observer.sample(logits, step); - let o = self + let generated = self .engine - .generate_with(prompt, &q, &mut sampler, on_token) - .map_err(EngineError::Failed)?; + .generate_with(prompt, &q, &mut sampler, on_token); + // Copy the footprint the engine recorded. A pass that errors before it sets + // `whole_prompt_mirror_live` still reads cold (see `note_footprint`). + self.note_footprint(); + let o = generated.map_err(EngineError::Failed)?; let sampling = observer.record(); self.reused_last .store(o.reused_prompt_tokens, Ordering::Relaxed); - // Park: export under the chip lock, write after it is released. - let parked = persist.map(|pk| { - self.engine - .with_engine(|e| pk.snapshot(e)) - .unwrap_or_default() - }); - drop(lock); + // Park: export under the chip lock, write after it is released. A classic fallback did + // not run the configured whole-prompt path, so its KV is not stored under that identity. + let parked = if classic { + None + } else { + persist.map(|pk| { + self.engine + .with_engine(|e| pk.snapshot(e)) + .unwrap_or_default() + }) + }; + // Clear the suspension while the flock is still held, then drop the lock. + // The other order lets the next request set suspend(true) and then lose it + // when this guard drops. + self.release_lock(resume, lock); if let (Some(pk), Some(items)) = (persist, parked) { pk.submit(items); } @@ -639,4 +931,348 @@ mod tests { assert!(parse_switch("--whole-prompt", "maybe").is_err()); assert!(parse_switch("--whole-prompt", " TRUE ").unwrap()); } + + const GB: u64 = 1 << 30; + /// 30B at 131,072 positions: 48 layers x 256 MiB (live smaps, ledger L884). + const KV_BYTES: u64 = 48 * 256 * (1 << 20); + + fn cold() -> WholePromptFootprint { + WholePromptFootprint { + on: true, + mirror_live: false, + scratch_tokens: 0, + kv_bytes: KV_BYTES, + chunk: 8192, + } + } + + #[test] + fn mem_available_is_read_from_meminfo_text() { + let t = "MemTotal: 126000000 kB\nMemFree: 1 kB\nMemAvailable: 39000000 kB\nBuffers: 1 kB\n"; + assert_eq!(parse_mem_available(t), Some(39_000_000 * 1024)); + assert_eq!(parse_mem_available("MemTotal: 1 kB\n"), None); + assert_eq!(parse_mem_available("MemAvailable: lots kB\n"), None); + } + + #[test] + fn the_live_incident_names_the_shortfall_without_a_zero_token_limit() { + // 14:24Z: a 66k-token prompt arrived with ~11 GB available and nothing warm yet. + // The mirror alone does not fit, so "send at most about 0 tokens" is not a limit a + // client can use. The door takes the classic path instead of 413ing forever. + let g = cold().growth(66_000); + let err = admit_growth(g, Some(11 * GB), 66_000).unwrap_err(); + assert!(err.contains("66000 tokens"), "{err}"); + assert!(err.contains("KV mirror"), "{err}"); + assert!(err.contains("6 GB must stay free"), "{err}"); + assert!( + !err.contains("about 0 tokens"), + "a zero token limit cannot warm the server: {err}" + ); + assert!(err.contains("retry when memory is free"), "{err}"); + assert_eq!( + admit_request(&cold(), Some(11 * GB), 4), + Ok(PrefillAdmit::Classic) + ); + assert_eq!( + admit_request(&cold(), Some(11 * GB), 66_000), + Ok(PrefillAdmit::Classic) + ); + let warm = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 8192, + ..cold() + }; + assert_eq!( + admit_request(&warm, Some(11 * GB), 120_000), + Ok(PrefillAdmit::WholePrompt), + "once the mirror is live a chunked prompt adds nothing and is admitted" + ); + } + + #[test] + fn a_warm_server_still_refuses_scratch_it_cannot_pay_for() { + let warm = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 0, + chunk: 0, + ..cold() + }; + assert!(matches!( + admit_request(&warm, Some(GB), 66_000), + Err(ref e) if !e.contains("about 0 tokens") + )); + } + + #[test] + fn a_warm_server_admits_any_chunked_prompt_even_when_memory_is_low() { + let warm = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 8192, + ..cold() + }; + assert_eq!(warm.growth(120_000), PrefillGrowth::default()); + assert!(admit_growth(warm.growth(120_000), Some(7 * GB), 120_000).is_ok()); + // Below the reserve too: the prefill adds nothing, so refusing it frees nothing. + assert!(admit_growth(warm.growth(120_000), Some(GB), 120_000).is_ok()); + } + + #[test] + fn admission_keeps_the_reserve_and_names_how_many_tokens_fit() { + let g = cold().growth(8192); + let need = g.total() + ADMIT_RESERVE_BYTES; + assert!(admit_growth(g, Some(need), 8192).is_ok()); + let err = admit_growth(g, Some(need - 1), 8192).unwrap_err(); + assert!(err.contains("retry when memory is free"), "{err}"); + // 19 GB free, mirror takes 12: (19 - 6 - 12) GB / 240 KiB per token. + let err = admit_growth(g, Some(19 * GB), 8192).unwrap_err(); + let fits = GB / SCRATCH_BYTES_PER_TOKEN; + assert!(err.contains(&format!("about {fits} tokens")), "{err}"); + } + + #[test] + fn unreadable_meminfo_and_a_switched_off_path_admit() { + assert!(admit_growth(cold().growth(66_000), None, 66_000).is_ok()); + let off = WholePromptFootprint { + on: false, + ..cold() + }; + assert_eq!(off.growth(66_000), PrefillGrowth::default()); + assert!(admit_growth(off.growth(66_000), Some(GB), 66_000).is_ok()); + } + + fn greedy_one() -> GenerateParams { + GenerateParams { + max_new_tokens: 1, + temperature: 0.0, + top_p: 1.0, + top_k: 0, + seed: 1, + stop_token_ids: Vec::new(), + } + } + + fn host_door(tag: &str) -> (OmegaDoor, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!( + "admit-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("lock"); + let engine = aien_inference_abi::qwen3_moe_omega::host_test_engine::engine( + WeightFormat::Fp8All, + 256, + ) + .expect("tiny host engine"); + let door = OmegaDoor::from_parts(engine, path.clone(), Duration::from_secs(5)); + (door, path) + } + + #[test] + fn cold_door_serves_and_a_warm_door_still_serves_on_the_same_tight_box() { + let (mut door, _path) = host_door("cold"); + let tight = 11 * GB; + door.available_probe = Some(std::sync::Arc::new(move || Some(tight))); + *door.footprint.lock().unwrap() = cold(); + let prompt = [1u32, 2, 3, 4]; + assert_eq!(door.decide(prompt.len()).unwrap(), PrefillAdmit::Classic); + assert!( + door.admit(&prompt).is_ok(), + "the server's early admit must not 413 a cold box the classic path can serve" + ); + let got = door.generate(&prompt, &greedy_one(), &mut |_| true); + assert!( + got.is_ok(), + "cold below the mirror must recover by serving, not 413 forever: {got:?}" + ); + *door.footprint.lock().unwrap() = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 8192, + ..cold() + }; + assert_eq!( + door.decide(prompt.len()).unwrap(), + PrefillAdmit::WholePrompt + ); + let again = door.generate(&[1, 2, 3, 5], &greedy_one(), &mut |_| true); + assert!( + again.is_ok(), + "once warm the same tight box admits a chunked prompt: {again:?}" + ); + } + + #[test] + fn admission_sees_the_kv_payload_and_a_drop_during_the_lock_wait() { + assert!( + !crate::chip_reservation::inherited(), + "this test needs a real flock; an inherited reservation skips the lock" + ); + let (mut door, path) = host_door("race"); + // Warm mirror, no scratch yet, one pass: growth is the prompt scratch plus the reserve. + // 20 GiB admits. The fetch's 8 GiB and the 8 GiB that disappear while the lock is waited + // for, together, do not. Either drop alone still admits, so the check has to run after both. + *door.footprint.lock().unwrap() = WholePromptFootprint { + on: true, + mirror_live: true, + scratch_tokens: 0, + kv_bytes: KV_BYTES, + chunk: 0, + }; + let avail = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(20 * GB)); + let fetched = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + door.available_probe = Some({ + let avail = std::sync::Arc::clone(&avail); + std::sync::Arc::new(move || Some(avail.load(Ordering::SeqCst))) + }); + door.fetch_probe = Some({ + let avail = std::sync::Arc::clone(&avail); + let fetched = std::sync::Arc::clone(&fetched); + std::sync::Arc::new(move || { + avail.fetch_sub(8 * GB, Ordering::SeqCst); + fetched.store(true, Ordering::SeqCst); + }) + }); + let held = GpuLock::acquire_at(&path, Duration::from_secs(2)).expect("test holds the lock"); + let prompt: Vec = (0..200).map(|i| (i % 64) as u32).collect(); + let params = greedy_one(); + let got = std::thread::scope(|scope| { + let worker = scope.spawn(|| door.generate(&prompt, ¶ms, &mut |_| true)); + let start = Instant::now(); + while !fetched.load(Ordering::SeqCst) { + if start.elapsed() > Duration::from_secs(15) { + drop(held); + panic!("generate did not reach the KV fetch before taking the lock"); + } + std::thread::sleep(Duration::from_millis(10)); + } + avail.fetch_sub(8 * GB, Ordering::SeqCst); + drop(held); + worker.join().expect("generate thread") + }); + match got { + Err(EngineError::MemoryExceeded(m)) => { + assert!( + m.contains("4.3 GB is available"), + "admission must see the post-fetch, post-wait memory, not the earlier reading: {m}" + ); + } + other => panic!("expected a 413 after the lock, got {other:?}"), + } + } + + #[test] + fn more_free_memory_never_refuses_a_prompt_a_tighter_box_serves() { + let one_pass = WholePromptFootprint { chunk: 0, ..cold() }; + let low = admit_request(&one_pass, Some(11 * GB), 66_000).unwrap(); + let high = admit_request(&one_pass, Some(20 * GB), 66_000).unwrap(); + assert_eq!(low, PrefillAdmit::Classic); + assert!( + matches!(high, PrefillAdmit::Classic | PrefillAdmit::WholePrompt), + "20 GB refused a 66k one-pass prompt that 11 GB served: {high:?}" + ); + let warm = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 0, + chunk: 0, + ..cold() + }; + for fp in [cold(), one_pass, warm] { + for n in [4usize, 8192, 66_000] { + let mut served = false; + for gb in [1u64, 8, 11, 16, 20, 40, 80] { + let ok = admit_request(&fp, Some(gb * GB), n).is_ok(); + if served { + assert!( + ok, + "{n} tokens served below {gb} GiB and refused at {gb} GiB" + ); + } + served = ok; + } + } + } + } + + #[test] + fn admission_prices_the_uncached_suffix_not_the_whole_prompt() { + assert_eq!(priced_tokens(66_000, 65_000), 1_000); + assert_eq!(priced_tokens(66_000, 66_000), 1); + assert_eq!(priced_tokens(66_000, 0), 66_000); + let warm = WholePromptFootprint { + mirror_live: true, + scratch_tokens: 0, + chunk: 0, + ..cold() + }; + let suffix = priced_tokens(66_000, 65_000); + let tight = Some(ADMIT_RESERVE_BYTES + suffix as u64 * SCRATCH_BYTES_PER_TOKEN); + assert!(admit_request(&warm, tight, priced_tokens(66_000, 0)).is_err()); + assert!(admit_request(&warm, tight, suffix).is_ok()); + } + + #[test] + fn a_reused_prefix_is_not_priced_as_a_cold_prompt() { + let (mut door, _) = host_door("reuse"); + let prompt: Vec = (0..80).map(|i| (i % 64) as u32).collect(); + door.available_probe = Some(std::sync::Arc::new(|| Some(80 * GB))); + let first = door.generate(&prompt, &greedy_one(), &mut |_| true); + assert!(first.is_ok(), "{first:?}"); + let reused = door + .engine + .with_engine(|e| e.reusable_prefix(&prompt)) + .unwrap(); + assert_eq!(reused, prompt.len() - 1, "reused {reused}"); + let tight = ADMIT_RESERVE_BYTES + 2 * SCRATCH_BYTES_PER_TOKEN; + door.available_probe = Some(std::sync::Arc::new(move || Some(tight))); + *door.footprint.lock().unwrap() = WholePromptFootprint { + on: true, + mirror_live: true, + scratch_tokens: 0, + kv_bytes: KV_BYTES, + chunk: 0, + }; + assert!(door.admit(&prompt).is_ok(), "the uncached suffix must fit"); + let second = door.generate(&prompt, &greedy_one(), &mut |_| true); + assert!( + second.is_ok(), + "a reused prompt was priced as the full length: {second:?}" + ); + + let (mut fresh, _) = host_door("reuse-full"); + fresh.available_probe = Some(std::sync::Arc::new(move || Some(tight))); + *fresh.footprint.lock().unwrap() = WholePromptFootprint { + on: true, + mirror_live: true, + scratch_tokens: 0, + kv_bytes: KV_BYTES, + chunk: 0, + }; + let refused = fresh.generate(&prompt, &greedy_one(), &mut |_| true); + assert!( + matches!(refused, Err(EngineError::MemoryExceeded(_))), + "the same prompt with no prefix must be refused: {refused:?}" + ); + } + + #[test] + fn suspension_is_cleared_before_the_lock_is_released() { + let (mut door, _) = host_door("drop-order"); + let seen = std::sync::Arc::new(AtomicBool::new(true)); + let vis = std::sync::Arc::clone(&door.suspend_visible); + let seen_h = std::sync::Arc::clone(&seen); + door.lock_release_hook = Some(std::sync::Arc::new(move || { + seen_h.store(vis.load(Ordering::SeqCst), Ordering::SeqCst); + })); + door.available_probe = Some(std::sync::Arc::new(|| Some(11 * GB))); + *door.footprint.lock().unwrap() = cold(); + let got = door.generate(&[1, 2, 3, 4], &greedy_one(), &mut |_| true); + assert!(got.is_ok(), "{got:?}"); + assert!( + !seen.load(Ordering::SeqCst), + "the lock dropped while classic suspension was still set" + ); + } } diff --git a/crates/aien-serve-http/src/server.rs b/crates/aien-serve-http/src/server.rs index c926c548..b4d54405 100644 --- a/crates/aien-serve-http/src/server.rs +++ b/crates/aien-serve-http/src/server.rs @@ -157,6 +157,14 @@ impl ApiError { } } + /// The prompt would not fit the free host memory (413, the limit is in the message). + fn memory_exceeded(msg: impl Into) -> Self { + let mut e = Self::bad_request(msg); + e.status = StatusCode::PAYLOAD_TOO_LARGE; + e.body.error.code = Some("prompt_exceeds_memory_budget".into()); + e + } + fn context_exceeded(msg: impl Into) -> Self { let mut e = Self::bad_request(msg); e.body.error.code = Some("context_length_exceeded".into()); @@ -259,6 +267,9 @@ enum Ev { test: Option>, }, Error(String), + /// Memory admission refused a prompt inside the engine: 413 `prompt_exceeds_memory_budget` + /// while nothing has been sent, an error event with that code once a stream is open. + MemoryExceeded(String), /// The engine could not get the shared chip: 503 before any token. Busy(String), /// Readers, streaming: the reading has started (the response goes out; nothing is sent). @@ -791,6 +802,12 @@ fn run_readers( let _ = tx.blocking_send(Ev::Busy(m)); return; } + Err(EngineError::MemoryExceeded(m)) => { + eprintln!("aien-serve-http: {id}: reader {} refused: {m}", k + 1); + let _ = + tx.blocking_send(Ev::MemoryExceeded(format!("reader {} of {n}: {m}", k + 1))); + return; + } Err(e) => { eprintln!("aien-serve-http: {id}: reader {} failed: {e}", k + 1); let _ = tx.blocking_send(Ev::Error(format!("reader {} of {n}: {e}", k + 1))); @@ -822,12 +839,23 @@ fn run_readers( drop(permit); let body = readers::connect_body(&raw, &plan, ¬es, &state.cfg.model_id); let connect = match serde_json::from_value::(body) - .map_err(|e| e.to_string()) - .and_then(|r| prepare(&state, r).map_err(|e| e.body.error.message)) - { + .map_err(|e| (false, e.to_string())) + .and_then(|r| { + prepare(&state, r).map_err(|e| { + ( + e.body.error.code.as_deref() == Some("prompt_exceeds_memory_budget"), + e.body.error.message, + ) + }) + }) { Ok(p) => p, - Err(m) => { - let _ = tx.blocking_send(Ev::Error(format!("readers: connect request: {m}"))); + Err((memory, m)) => { + let m = format!("readers: connect request: {m}"); + let _ = tx.blocking_send(if memory { + Ev::MemoryExceeded(m) + } else { + Ev::Error(m) + }); return; } }; @@ -896,8 +924,10 @@ async fn respond( // The first event decides the status: a busy chip is a 503 in the OpenAI error envelope, // before any headers go out (streaming included). Everything else is forwarded unchanged. let first = rx.recv().await; - if let Some(Ev::Busy(m)) = &first { - return Err(ApiError::gpu_busy(m)); + match &first { + Some(Ev::Busy(m)) => return Err(ApiError::gpu_busy(m)), + Some(Ev::MemoryExceeded(m)) => return Err(ApiError::memory_exceeded(m.clone())), + _ => {} } let (ftx, frx) = mpsc::channel::(64); tokio::spawn(async move { @@ -1039,6 +1069,10 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { ctx ))); } + state + .engine + .admit(&prompt_tokens) + .map_err(ApiError::memory_exceeded)?; let requested = match req.max_tokens.or(req.max_completion_tokens) { Some(v) if v < 1 => return Err(ApiError::bad_request("max_tokens must be at least 1")), Some(v) => v as usize, @@ -1277,6 +1311,10 @@ fn run_generation( eprintln!("aien-serve-http: {id}: GPU busy: {m}"); let _ = tx.blocking_send(Ev::Busy(m)); } + Err(EngineError::MemoryExceeded(m)) => { + eprintln!("aien-serve-http: {id}: memory admission refused: {m}"); + let _ = tx.blocking_send(Ev::MemoryExceeded(m)); + } Err(e) => { eprintln!("aien-serve-http: {id}: {e}"); let _ = tx.blocking_send(Ev::Error(e.to_string())); @@ -1403,6 +1441,7 @@ async fn collect_response( // Not the first event on the readers' path (`Ev::Readers` goes before the connect // generation); nothing has been sent yet, so it is the same 503 as a busy first event. Ev::Busy(m) => return Err(ApiError::gpu_busy(&m)), + Ev::MemoryExceeded(m) => return Err(ApiError::memory_exceeded(m)), } } Err(ApiError::internal("generation ended without a result")) @@ -1556,6 +1595,16 @@ fn stream_response( let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; return; } + Ev::MemoryExceeded(m) => { + let mut body = ErrorBody::new("invalid_request_error", m); + body.error.code = Some("prompt_exceeds_memory_budget".into()); + let err = serde_json::to_value(body).expect("error serializes"); + if etx.send(data(err)).await.is_err() { + return; + } + let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; + return; + } }; if etx.send(item).await.is_err() { return; diff --git a/crates/aien-serve-http/tests/loopback.rs b/crates/aien-serve-http/tests/loopback.rs index d2708c5d..8b9cb176 100644 --- a/crates/aien-serve-http/tests/loopback.rs +++ b/crates/aien-serve-http/tests/loopback.rs @@ -510,6 +510,38 @@ fn prompt_that_fills_the_context_is_refused() { assert_eq!(json(&r)["error"]["code"], "context_length_exceeded"); } +#[test] +fn prompt_the_memory_cannot_hold_is_refused_with_413_and_the_limit() { + let why = "prompt of 66000 tokens needs 13.9 GB more host memory but only 9.0 GB is available; send at most about 0 tokens now"; + let srv = start(stub("x").with_admit_refusal(why), ServerConfig::default()); + let r = chat(srv.addr, PROMPT); + assert_eq!(r.status, 413, "{}", r.body); + let j = json(&r); + assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); + assert_eq!(j["error"]["message"], why); +} + +/// The engine's own admission (omega door: `generate` re-checks memory after the server's +/// `admit` passed) refusing is the same 413, streaming included (nothing has been sent yet). +#[test] +fn a_memory_refusal_inside_the_engine_is_the_same_413() { + let why = "prompt of 66000 tokens needs 13.9 GB more host memory but only 9.0 GB is available; send at most about 0 tokens now"; + let srv = start( + stub("x").with_generate_refusal(why), + ServerConfig::default(), + ); + for body in [ + PROMPT, + r#"{"messages":[{"role":"user","content":"hi"}],"stream":true}"#, + ] { + let r = chat(srv.addr, body); + assert_eq!(r.status, 413, "{body}: {}", r.body); + let j = json(&r); + assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); + assert_eq!(j["error"]["message"], why); + } +} + #[test] fn non_loopback_bind_is_refused() { let rt = tokio::runtime::Runtime::new().unwrap(); diff --git a/crates/aien-serve-http/tests/readers.rs b/crates/aien-serve-http/tests/readers.rs index db1f82b2..2b3a8e54 100644 --- a/crates/aien-serve-http/tests/readers.rs +++ b/crates/aien-serve-http/tests/readers.rs @@ -156,9 +156,16 @@ fn readers_cfg() -> ReadersConfig { } fn start_spy(slots: usize, reply: &str) -> (Server, Arc>>>) { + start_spy_on( + slots, + StubEngine::new(reply.bytes().map(u32::from).collect()).with_max_context(1 << 16), + ) +} + +fn start_spy_on(slots: usize, inner: StubEngine) -> (Server, Arc>>>) { let groups = Arc::new(Mutex::new(Vec::new())); let spy = Spy { - inner: StubEngine::new(reply.bytes().map(u32::from).collect()).with_max_context(1 << 16), + inner, slots, groups: Arc::clone(&groups), }; @@ -283,6 +290,60 @@ fn show_notes_puts_a_collapsed_preface_before_the_answer() { assert_eq!(c.matches("NOTE").count(), 9); } +const REFUSAL: &str = "prompt of 66000 tokens needs 13.9 GB more host memory but only 9.0 GB is available; send at most about 0 tokens now"; + +/// The engine's own memory admission (inside `generate`, after the server's `admit` passed) +/// refusing a reader: the same 413 `prompt_exceeds_memory_budget` as a refusal in `prepare`, +/// not a 500. +#[test] +fn a_reader_refused_for_memory_inside_the_engine_is_a_413() { + let (srv, groups) = start_spy_on( + 8, + StubEngine::new(b"NOTE".iter().map(|&b| u32::from(b)).collect()) + .with_max_context(1 << 16) + .with_generate_refusal(REFUSAL), + ); + let r = chat(srv.addr, &body("test-model-readers", &long_doc(), "")); + assert_eq!(r.status, 413, "{}", r.body); + let j = json(&r); + assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); + let m = j["error"]["message"].as_str().unwrap(); + assert!( + m.starts_with("reader 1 of 8: ") && m.ends_with(REFUSAL), + "{m}" + ); + assert_eq!( + groups.lock().unwrap().len(), + 1, + "the refusal came from the group run" + ); +} + +/// Streaming readers open the response before reading, so the refusal is the stream's error +/// event, carrying the same code. +#[test] +fn a_streaming_reader_refused_for_memory_ends_with_the_memory_error_event() { + let (srv, _) = start_spy_on( + 8, + StubEngine::new(b"NOTE".iter().map(|&b| u32::from(b)).collect()) + .with_max_context(1 << 16) + .with_generate_refusal(REFUSAL), + ); + let r = chat( + srv.addr, + &body("test-model-readers", &long_doc(), r#","stream":true"#), + ); + assert_eq!(r.status, 200); + let ev = sse_data(&r.body); + assert_eq!(ev.last().unwrap(), "[DONE]"); + let err: Value = serde_json::from_str(&ev[ev.len() - 2]).unwrap(); + assert_eq!( + err["error"]["code"], "prompt_exceeds_memory_budget", + "{err}" + ); + assert!(err["error"]["message"].as_str().unwrap().ends_with(REFUSAL)); +} + #[test] fn streaming_sends_progress_then_the_notes_then_the_answer() { let (srv, _) = start_spy(8, "NOTE");