diff --git a/crates/vetta-infer-gw/src/chat.rs b/crates/vetta-infer-gw/src/chat.rs index 0a852f5..05b8e4d 100644 --- a/crates/vetta-infer-gw/src/chat.rs +++ b/crates/vetta-infer-gw/src/chat.rs @@ -125,6 +125,7 @@ mod tests { #[test] #[ignore] fn chat_turn_paris() { + crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap(); let history = [ChatMessage::new("user", "What is the capital of France? Answer in one word.")]; @@ -133,5 +134,6 @@ mod tests { eprintln!("[chat] reply={reply:?} streamed={streamed:?}"); assert_eq!(reply, streamed, "streamed text must equal the full reply"); assert!(reply.to_lowercase().contains("paris"), "reply should name Paris: {reply:?}"); + }); } } \ No newline at end of file diff --git a/crates/vetta-infer-gw/src/lib.rs b/crates/vetta-infer-gw/src/lib.rs index d8f180d..279adf7 100644 --- a/crates/vetta-infer-gw/src/lib.rs +++ b/crates/vetta-infer-gw/src/lib.rs @@ -20,6 +20,26 @@ pub mod serve; #[cfg(feature = "hip")] pub mod chat; +/// Serializes the heavy full-model GPU integration tests. Each loads the whole +/// Inkling engine (weights + KV), so running them concurrently exhausts GPU +/// memory; only one engine is resident at a time. +#[cfg(all(test, feature = "hip"))] +pub(crate) static GPU_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Run a heavy GPU test body under the serial lock with the buffer pool OFF. +/// Two isolation guarantees: (1) only one full-model engine is resident at a +/// time (concurrent engines exhaust GPU memory); (2) the DeviceBuf pool is +/// disabled process-wide so every drop calls hipFree and device memory is +/// actually released between tests — the thread-local pool otherwise retains +/// buffers for the lifetime of each libtest worker thread and OOMs the GPU by +/// the fifth test. Safe: no env mutation, no `unsafe` in the gw crate. +#[cfg(all(test, feature = "hip"))] +pub(crate) fn gpu_isolated(f: F) { + let _serial = GPU_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + vetta_infer_hip::set_buf_pool_enabled(false); + f(); +} + /// Python-repr float spelling (always a decimal point), as `strata-ctl` emits. fn fmt_float(v: f64) -> String { let s = format!("{v}"); diff --git a/crates/vetta-infer-gw/src/main.rs b/crates/vetta-infer-gw/src/main.rs index 103d121..686865d 100644 --- a/crates/vetta-infer-gw/src/main.rs +++ b/crates/vetta-infer-gw/src/main.rs @@ -11,6 +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!(" vetta-infer chat [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)"); eprintln!(" vetta-infer version Print version & build info"); } @@ -94,7 +95,7 @@ fn main() -> ExitCode { } } } - Some("serve") => { + Some("serve") | Some("--serve") => { let Some(dir) = args.get(1) else { eprintln!("error: missing "); usage(); diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 7e3622d..6854f6e 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -243,10 +243,10 @@ pub fn serve_gen( finish = "nonfinite"; break; } - if rep.token == eng.eos { - finish = "stop"; - break; - } + // Emit the EOS token as `T ` before closing, exactly like the + // reference strata-inkling --serve: strata-ctl's Inkling dialect decoder + // reads the end-of-sampling channel token to close the model turn. + let is_eos = rep.token == eng.eos; match sess.on_token(rep.token as u32) { Ok(lines) => emit_all(emit, lines), Err(e) => { @@ -255,6 +255,10 @@ pub fn serve_gen( return; } } + if is_eos { + finish = "stop"; + break; + } history.push(rep.token); if step + 1 == g.max_new { finish = "length"; @@ -366,6 +370,7 @@ mod tests { #[test] #[ignore] fn serve_gen_paris_wire() { + crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 4 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, @@ -381,12 +386,14 @@ mod tests { let dones: Vec<&String> = lines.iter().filter(|l| l.starts_with("DONE ")).collect(); assert_eq!(dones.len(), 1, "exactly one DONE per request"); assert!(dones[0].ends_with("length") || dones[0].ends_with("stop")); + }); } /// GPU integration: `GEN 0` pre-warm emits DONE with zero tokens (Theorem 7). #[test] #[ignore] fn serve_gen_prewarm_no_tokens() { + crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 0 371,151451", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, @@ -397,6 +404,7 @@ mod tests { serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); assert!(!lines.iter().any(|l| l.starts_with("T ")), "pre-warm emits no tokens"); assert!(lines.iter().any(|l| l.starts_with("DONE 0 2")), "DONE 0 2 ..."); + }); } /// GPU regression: multi-token decode must match the reference EXACTLY. This @@ -408,6 +416,7 @@ mod tests { #[test] #[ignore] fn serve_gen_multi_token_parity() { + crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, @@ -422,5 +431,33 @@ mod tests { .collect(); let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014]; assert_eq!(tokens, want, "multi-token decode must match reference exactly"); + }); + } + + /// GPU regression: the EOS token must be emitted as `T ` before + /// `DONE ... stop` (wire-compatible with strata-inkling --serve, whose + /// dialect decoder in strata-ctl reads the end-of-sampling channel token). + /// Sequence measured against the reference for the effort-0 capital chat. + #[test] + #[ignore] + fn serve_gen_emits_eos_then_stop() { + crate::gpu_isolated(|| { + let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); + let ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,1775,149884,149876,151451,149879,151194,30,154710,149881,150011,151290,13,200010,200001,200004"; + let g = match parse_serve_line(&format!("GEN 8 temperature=0 {ids}"), eng.vocab()).unwrap() { + ServeCommand::Gen(g) => g, + _ => panic!("expected Gen"), + }; + let stop = AtomicBool::new(false); + let mut lines: Vec = Vec::new(); + serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); + let tokens: Vec = lines.iter() + .filter(|l| l.starts_with("T ")) + .map(|l| l[2..].trim().parse().unwrap()) + .collect(); + assert_eq!(tokens, [3967, 198, 200010, 200006], "EOS must be emitted as the last T"); + let done = lines.iter().find(|l| l.starts_with("DONE ")).expect("one DONE"); + assert!(done.ends_with(" stop"), "finish must be stop, got {done}"); + }); } } \ No newline at end of file diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 6c3c6d3..726dc87 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -151,9 +151,23 @@ thread_local! { std::cell::RefCell::new(std::collections::HashMap::new()); } +#[cfg(feature = "hip")] +static POOL_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// Process-wide buffer-pool switch (safe; no env mutation). The resident serve +/// keeps the pool ON for speed. GPU integration tests turn it OFF so every +/// `DeviceBuf` drop calls `hipFree` and device memory is released between tests: +/// the thread-local pool otherwise retains buffers for the lifetime of each +/// libtest worker thread, exhausting the GPU across several full-model tests. +#[cfg(feature = "hip")] +pub fn set_buf_pool_enabled(on: bool) { + POOL_ENABLED.store(on, std::sync::atomic::Ordering::Relaxed); +} + #[cfg(feature = "hip")] fn pool_enabled() -> bool { - std::env::var("VETTA_NO_BUF_POOL").is_err() + POOL_ENABLED.load(std::sync::atomic::Ordering::Relaxed) + && std::env::var("VETTA_NO_BUF_POOL").is_err() } #[cfg(feature = "hip")] diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 41ca0df..c56487a 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -38,10 +38,10 @@ pub struct LayerWeights { /// Persistent per-layer decode state. pub struct LayerState { // KV cache is PER-VISIT (exact strata visit_kv_slot: every core pass owns a - // distinct SWA/global KV pool, 40 SWA + 8 global). Index by pass: prelude/coda - // use pass 0; the core's 3 passes use pass 0/1/2. Sharing one cache across - // passes corrupts multi-token attention (the systematic token-2+ parity gap). - pub k_cache: [DeviceBuf; 3], pub v_cache: [DeviceBuf; 3], // [n_kv, max_seq, hd] each + // distinct SWA/global KV pool, 40 SWA + 8 global). One cache per pass the + // layer actually runs: core layers 3 (pass 0/1/2), prelude/coda 1 (pass 0). + // Sharing one cache across passes corrupts multi-token attention. + pub k_cache: Vec, pub v_cache: Vec, // per-pass [n_kv, max_seq, hd] // ShortConv history is PER-VISIT (exact strata hist_pool_all + visit*stride): // each core pass has its own history ring, NOT shared across passes. Index // by pass (prelude/coda use pass 0; core uses pass 0/1/2). @@ -179,7 +179,7 @@ pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result Result { +pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result { let zero = |n: usize| -> Result { let b = DeviceBuf::alloc(n * 4)?; b.h2d(&vec![0f32; n])?; Ok(b) }; // KV cache dtype: F32 by default (the verified CPU-oracle baseline); FP16 via // VETTA_F16_KV=1 matches the strata default (KvDtype::FP16) and its @@ -192,9 +192,10 @@ pub fn new_state(d: &Dims, max_seq: usize) -> Result { let b = DeviceBuf::alloc(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b) } }; + let kv_vec = || -> Result, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() }; Ok(LayerState { - k_cache: [kv_buf()?, kv_buf()?, kv_buf()?], - v_cache: [kv_buf()?, kv_buf()?, kv_buf()?], + k_cache: kv_vec()?, + v_cache: kv_vec()?, hist_k: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?], hist_v: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?], hist_a: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?], @@ -405,7 +406,7 @@ pub fn forward_swa_layers( let mut blocks: Vec = Vec::new(); for &ip in schedule { let w = cache.swa_layer(ip)?; - let mut st = new_state(d, max_seq)?; + let mut st = new_state(d, max_seq, 1)?; layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?; } Ok((cur, blocks)) @@ -490,7 +491,11 @@ fn run_layer( states: &mut [Option], max_seq: usize, pos: i32, pass: usize, ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ) -> Result<(), String> { - if states[ip].is_none() { states[ip] = Some(new_state(d, max_seq)?); } + if states[ip].is_none() { + // Core layers run 3 loop passes (3 distinct KV pools); prelude/coda run 1. + let n_passes = if (6..18).contains(&ip) { 3 } else { 1 }; + states[ip] = Some(new_state(d, max_seq, n_passes)?); + } let st = states[ip].as_mut().unwrap(); let r = if is_swa(ip) { let w = cache.swa_layer(ip)?; @@ -880,7 +885,7 @@ mod tests { let mut seed = vec![0f32; d.hidden]; cur.d2h(&mut seed).unwrap(); let b0 = DeviceBuf::alloc(d.hidden * 4).unwrap(); b0.h2d(&seed).unwrap(); blocks.push(b0); let w = load_full_layer(&ar, 5, &d).unwrap(); - let mut st = new_state(&d, 1).unwrap(); + let mut st = new_state(&d, 1, 3).unwrap(); layer_forward_full(&cache, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap(); assert_eq!(blocks.len(), 1, "ip=5 does not snapshot (5%6!=0)"); let mut out = vec![0f32; d.hidden]; cur.d2h(&mut out).unwrap(); diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index bb2885e..e3951f8 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -713,7 +713,7 @@ mod tests { // === GPU full layer via the reusable layer forward (ld::layer) === let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 }; let lw = crate::layer::load_layer(&ar, 0, true).unwrap(); - let mut st = crate::layer::new_state(&dims, steps).unwrap(); + let mut st = crate::layer::new_state(&dims, steps, 3).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let mut blocks: Vec = Vec::new(); let cache = crate::layer::WeightCache::new(&ar); @@ -836,7 +836,7 @@ mod tests { let x: Vec = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect(); let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 }; let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap(); - let mut st = crate::layer::new_state(&dims, 1).unwrap(); + let mut st = crate::layer::new_state(&dims, 1, 3).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let mut blocks: Vec = Vec::new(); let cache = crate::layer::WeightCache::new(&ar);