//! Real GPU `--serve` request loop (feature `hip`) — the engine side of the //! `strata-ctl` wire contract (docs/ARCHITECTURE.md §6). //! //! Wires the three already-verified pieces into a resident inference service: //! * `ld::layer::forward_inkling_with_state` — the full 48-visit Inkling //! forward with persistent per-layer KV/ShortConv state (autoregressive); //! * `abi::sampler` — the hardened zero-allocation sampler (greedy/top-k/p/ //! min-p + penalties, explicit non-finite tracking); //! * `gw::session::ServeSession` — the Lean-proven request lifecycle //! (`proofs/serve_session.lean`): GEN/STOP/QUIT, `GEN 0` pre-warm, and the //! STOP→DONE drain guarantee. //! //! The protocol is token-id based (the consumer sends prompt ids and receives //! `T ` lines), so no tokenizer is needed here. `serve_gen` is a pure //! orchestration function (engine + parsed GEN + stop flag + emit closure) so it //! is callable from an integration test without spawning the binary. use std::io::{self, BufRead, Write}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc}; use std::time::Instant; use vetta_infer_abi::sampler::{ sample_logits_exact, SamplerScratch, SamplingOpts, SplitMix64, }; use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand}; use vetta_infer_hip::DeviceBuf; use vetta_infer_ld::inkling::parse_config; use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState, WeightCache}; use vetta_infer_ld::SafetensorsArchive; use crate::session::ServeSession; use crate::{err_line, ready_line}; /// Inkling-2-Mini architecture constants used by the layer kernels that are not /// carried in `TextConfig` (verified against the reference engine; same values /// as the proven `ld::layer` parity tests). `block_size` is /// `n_layers_per_attn_res_block`; `qk_clip`/`rel_clip` are the L2-clip /// thresholds; `beta`/`lb` are the SiTU double-softcap parameters. const BLOCK_SIZE: usize = 6; const QK_CLIP: f32 = 22.627416997969522; const REL_CLIP: f32 = 8.0; const SITU_BETA: f32 = 4.0; const SITU_LB: f32 = 25.0; /// Declared resident context window advertised in `READY` (SWA window is 1024; /// full-attn layers attend globally up to this cap). const MAX_CONTEXT: usize = 8192; /// A loaded Inkling model ready to run autoregressive forwards. pub struct InklingEngine { ar: SafetensorsArchive, d: Dims, vocab: usize, n_layers: usize, eos: i32, cap: f32, } impl InklingEngine { /// Load the archive + `config.json` and derive the forward dimensions. pub fn new(dir: &str) -> Result { let ar = SafetensorsArchive::open(dir)?; let cfg_path = ar.dir.join("config.json"); let raw = std::fs::read_to_string(&cfg_path) .map_err(|e| format!("read {}: {e}", cfg_path.display()))?; let cfg = parse_config(&raw)?; let t = &cfg.text; let d = Dims { hidden: t.hidden, n_head: t.n_head, n_kv: t.n_kv, hd: t.head_dim, d_rel: t.d_rel, rel_extent: t.rel_extent, inter: t.inter, n_experts: t.n_experts, top_k: t.top_k, block_size: BLOCK_SIZE, qk_clip: QK_CLIP, rel_clip: REL_CLIP, eps: t.rms_eps as f32, route_scale: t.route_scale as f32, beta: SITU_BETA, lb: SITU_LB, swa_win: t.swa_win as i32, }; Ok(Self { ar, d, vocab: t.vocab, n_layers: t.n_layers, eos: cfg.eos_token_id as i32, cap: t.final_logit_softcapping as f32, }) } pub fn vocab(&self) -> usize { self.vocab } fn fresh_states(&self, _max_seq: usize) -> Result>, String> { // States are allocated lazily per layer by run_layer; start all None. Ok((0..self.n_layers).map(|_| None).collect()) } fn forward( &self, cache: &WeightCache, token: i32, pos: i32, max_seq: usize, states: &mut [Option], ) -> Result { forward_inkling_with_state(cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states) } } fn emit_all(emit: &mut dyn FnMut(String), lines: Vec) { for l in lines { emit(l); } } /// Drive one GEN request end-to-end against the Lean-proven session FSM, emitting /// wire lines through `emit`. `stop` is set asynchronously (stdin reader thread) /// to interrupt decode; it is consumed here (drain→DONE) and reset on exit. /// /// Each request resets the per-layer state and re-prefills the prompt (prefix /// cache reuse is a later performance refinement; correctness is identical). pub fn serve_gen( eng: &InklingEngine, g: &ParsedGen, stop: &AtomicBool, emit: &mut dyn FnMut(String), ) { let mut sess = ServeSession::new(); if let Err(e) = sess.on_gen(g) { emit_all(emit, sess.on_error(&e)); return; } let n_prompt = g.ids.len(); let max_seq = (n_prompt + g.max_new + 2).min(MAX_CONTEXT); if n_prompt + g.max_new + 2 > MAX_CONTEXT { emit_all(emit, sess.on_error("prompt + max_new exceeds context window")); return; } let mut states = match eng.fresh_states(max_seq) { Ok(s) => s, Err(e) => { emit_all(emit, sess.on_error(&e)); return; } }; // Resident weight cache for this request: weights upload once and stay on // the GPU across prefill + decode (no per-token NVMe expert re-reads). let cache = WeightCache::new(&eng.ar); // --- Prefill: run the forward over every prompt token, growing KV/history. --- let t0 = Instant::now(); let mut pos = 0i32; let mut history: Vec = Vec::with_capacity(n_prompt + g.max_new); let mut logits: Option = None; for (i, &tok) in g.ids.iter().enumerate() { if stop.load(Ordering::Relaxed) { sess.on_stop(); let ms = t0.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } match eng.forward(&cache, tok, pos, max_seq, &mut states) { Ok(lg) => logits = Some(lg), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } history.push(tok); pos += 1; let ms = t0.elapsed().as_secs_f64() * 1000.0; if let Ok(pp) = sess.on_prefill_chunk((i + 1) as u32, n_prompt as u32, ms) { emit_all(emit, pp); } } let prompt_ms = t0.elapsed().as_secs_f64() * 1000.0; // GEN 0 pre-warm: on_prefill_complete emits DONE directly (never decodes). match sess.on_prefill_complete(0, prompt_ms) { Ok(lines) => emit_all(emit, lines), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } if g.max_new == 0 { stop.store(false, Ordering::Relaxed); return; } // --- Decode: sample from the last logits, emit T, advance the forward. --- let opts: SamplingOpts = g.sampling; let mut rng = SplitMix64::new(opts.seed); let mut scratch = SamplerScratch::default(); let t1 = Instant::now(); let mut logits = match logits { Some(l) => l, None => { emit_all(emit, sess.on_error("empty prompt")); stop.store(false, Ordering::Relaxed); return; } }; let mut finish = "length"; for step in 0..g.max_new { if stop.load(Ordering::Relaxed) { sess.on_stop(); let ms = t1.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } let mut lg = vec![0f32; eng.vocab]; if let Err(e) = logits.d2h(&mut lg) { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } let rep = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch); if rep.nonfinite_logits == eng.vocab { finish = "nonfinite"; break; } if rep.token == eng.eos { finish = "stop"; break; } match sess.on_token(rep.token as u32) { Ok(lines) => emit_all(emit, lines), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } history.push(rep.token); if step + 1 == g.max_new { finish = "length"; break; } match eng.forward(&cache, rep.token, pos, max_seq, &mut states) { Ok(l) => logits = l, Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } pos += 1; } let decode_ms = t1.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); } enum Msg { Gen(ParsedGen), Reset, Err(String), Quit, } /// Resident `--serve` loop: emit `READY`, then read GEN/STOP/QUIT lines from /// stdin and answer on stdout. A reader thread parses commands and raises the /// `stop`/`quit` flags so STOP can interrupt an in-flight decode (the FSM then /// drains to DONE). One request at a time (FIFO), matching the consumer. pub fn run_serve(dir: &str) -> Result<(), String> { let eng = InklingEngine::new(dir)?; let vocab = eng.vocab(); let stop = Arc::new(AtomicBool::new(false)); let quit = Arc::new(AtomicBool::new(false)); let (tx, rx) = mpsc::channel::(); { let stop = Arc::clone(&stop); let quit = Arc::clone(&quit); std::thread::spawn(move || { let stdin = io::stdin(); for line in stdin.lock().lines() { let Ok(line) = line else { break }; match parse_serve_line(&line, vocab) { Ok(ServeCommand::Gen(g)) => { if tx.send(Msg::Gen(g)).is_err() { break; } } Ok(ServeCommand::Reset) => { if tx.send(Msg::Reset).is_err() { break; } } Ok(ServeCommand::Stop) => stop.store(true, Ordering::Relaxed), Ok(ServeCommand::Quit) => { quit.store(true, Ordering::Relaxed); stop.store(true, Ordering::Relaxed); let _ = tx.send(Msg::Quit); break; } Err(e) => { if tx.send(Msg::Err(e)).is_err() { break; } } } } }); } let stdout = io::stdout(); let mut out = stdout.lock(); let mut emit = |line: String| { let _ = writeln!(out, "{line}"); let _ = out.flush(); }; emit(ready_line(MAX_CONTEXT as u32, true, false, false)); loop { if quit.load(Ordering::Relaxed) { break; } match rx.recv() { Ok(Msg::Gen(g)) => { stop.store(false, Ordering::Relaxed); serve_gen(&eng, &g, &stop, &mut emit); } Ok(Msg::Reset) => { // Per-request state is reset in serve_gen; nothing resident to clear. } Ok(Msg::Err(e)) => emit(err_line(&e)), Ok(Msg::Quit) | Err(_) => break, } } Ok(()) } #[cfg(test)] mod tests { use super::*; /// GPU integration: drive `serve_gen` over the wire for the canonical prompt /// "The capital of France is" (ids from the tokenizer) and check the emitted /// lines: first `T` is 152717 (" Paris", exact reference match) and the /// request ends in exactly one DONE. Requires GPU + /mnt/models/Inkling. #[test] #[ignore] fn serve_gen_paris_wire() { 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, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); eprintln!("[serve] lines={lines:?}"); let tokens: Vec<&String> = lines.iter().filter(|l| l.starts_with("T ")).collect(); assert!(!tokens.is_empty(), "must emit at least one token"); assert_eq!(tokens[0].as_str(), "T 152717", "first token must be ' Paris'"); 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() { 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, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); 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 ..."); } }