Files
vetta-infer/crates/vetta-infer-gw/src/lib.rs
T
adm 7790f48c27 [GW][HIP][LD] Link vetta-infer to strata-ctl; isolate GPU tests; size KV per pass
End-to-end verified: strata-ctl --serve spawns vetta-infer and serves the
OpenAI-compatible API. Live: 'capital of France' -> Paris (finish stop), and
Italian multi-turn context -> Napoli. Two wire-compat gaps closed:
- accept '--serve <dir>' alias (strata-ctl engine_argv prepends --serve).
- emit the EOS token as 'T <eos>' before 'DONE ... stop', matching the
  reference strata-inkling --serve (strata-ctl's dialect decoder reads the
  end-of-sampling channel token). chat parity now EXACT incl. EOS.

GPU test isolation (the 5th full-model test OOM'd): HIP-visible VRAM is 48 GiB
(model 18 GiB; one live instance peaks ~15 GiB and releases cleanly). The OOM
was the harness, not a leak: the thread-local DeviceBuf pool retains buffers
for each libtest worker thread's lifetime, so 5 engines' weights accumulated
past 48 GiB. Fix: gw gpu_isolated() runs heavy tests under a serial lock with
the pool disabled via a new safe hip::set_buf_pool_enabled (no env mutation,
gw stays unsafe-free), so every drop hipFrees between tests.

KV sizing: LayerState.k_cache/v_cache are now Vec sized to the passes a layer
actually runs (core 3, prelude/coda 1) instead of 3 for every layer, removing
~1.6 GiB of unused KV at max context. Parity unchanged (EXACT 16 tok).

Suite: workspace -D warnings green; 18 ld + 18 hip + 5 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:26:18 +01:00

171 lines
5.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `vetta-infer-gw`: gateway & CLI (docs/ARCHITECTURE.md §2, §6).
//!
//! Engine → consumer wire emitters, matching `strata-ctl/src/engine/protocol.rs`
//! (`EngineLine::parse`) field for field:
//! `READY <ctx> [stop] [hold] [holdb]`, `INFO k=v …`, `T <id>`,
//! `PP <read> <total> [ms] [tok_s]`, `RESUME <n>`,
//! `DONE <gen> <prompt> <prompt_ms> <decode_ms> <finish> [extra…]`, `ERR <msg>`.
//!
//! `DONE` fields 1–5 are stable; the tail is kept raw by the consumer, so new
//! statistics can be appended without breaking it. Floats use Python-repr
//! spelling (`1.0`), which the consumer's parser expects.
pub mod session;
pub mod chat_template;
#[cfg(feature = "hip")]
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: FnOnce()>(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}");
if s.contains('.') {
s
} else {
format!("{s}.0")
}
}
/// First meaningful line after startup. `INFO` may precede it; the consumer
/// treats any other pre-`READY` line as startup chatter and `ERR` as refusal.
pub fn ready_line(max_context: u32, can_stop: bool, can_hold: bool, can_hold_batch: bool) -> String {
let mut s = format!("READY {max_context}");
if can_stop {
s.push_str(" stop");
}
if can_hold {
s.push_str(" hold");
}
if can_hold_batch {
s.push_str(" holdb");
}
s
}
pub fn info_line(pairs: &[(&str, &str)]) -> String {
let mut s = String::from("INFO");
for (k, v) in pairs {
s.push(' ');
s.push_str(k);
s.push('=');
s.push_str(v);
}
s
}
pub fn token_line(id: u32) -> String {
format!("T {id}")
}
/// Prefill progress, one per chunk. `tok_s_mean` is optional (4th field).
pub fn pp_line(read: u32, total: u32, ms: f64, tok_s_mean: Option<f64>) -> String {
match tok_s_mean {
Some(ts) => format!("PP {read} {total} {} {}", fmt_float(ms), fmt_float(ts)),
None => format!("PP {read} {total} {}", fmt_float(ms)),
}
}
pub fn resume_line(n: u32) -> String {
format!("RESUME {n}")
}
/// End of request. Fields 1–5 stable across versions; `extra` is the raw tail
/// (draft stats, cache hits, expert tiers, …) the consumer preserves verbatim.
pub fn done_line(
generated: u32,
prompt_tokens: u32,
prompt_ms: f64,
decode_ms: f64,
finish: &str,
extra: &[String],
) -> String {
let mut s = format!(
"DONE {generated} {prompt_tokens} {} {} {finish}",
fmt_float(prompt_ms),
fmt_float(decode_ms)
);
for e in extra {
s.push(' ');
s.push_str(e);
}
s
}
pub fn err_line(msg: &str) -> String {
format!("ERR {msg}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ready_flags_match_consumer_parse() {
assert_eq!(ready_line(262144, true, true, false), "READY 262144 stop hold");
assert_eq!(ready_line(4096, false, false, false), "READY 4096");
assert_eq!(ready_line(8192, true, false, true), "READY 8192 stop holdb");
}
#[test]
fn info_and_token_shapes() {
assert_eq!(
info_line(&[("version", "0.1.0"), ("expert_slots", "64")]),
"INFO version=0.1.0 expert_slots=64"
);
assert_eq!(token_line(151645), "T 151645");
assert_eq!(resume_line(512), "RESUME 512");
}
#[test]
fn prefill_progress_optional_mean() {
assert_eq!(pp_line(1024, 8192, 431.5, Some(2373.2)), "PP 1024 8192 431.5 2373.2");
assert_eq!(pp_line(128, 512, 90.0, None), "PP 128 512 90.0");
}
#[test]
fn done_five_stable_fields_and_raw_tail() {
assert_eq!(
done_line(41, 128, 90.5, 310.25, "stop", &[]),
"DONE 41 128 90.5 310.25 stop"
);
let extra: Vec<String> = ["7", "10", "55", "chunk=2048"].iter().map(|s| s.to_string()).collect();
assert_eq!(
done_line(41, 128, 90.5, 310.25, "length", &extra),
"DONE 41 128 90.5 310.25 length 7 10 55 chunk=2048"
);
// Integral floats keep the Python-repr ".0" spelling.
assert_eq!(done_line(1, 2, 3.0, 4.0, "stop", &[]), "DONE 1 2 3.0 4.0 stop");
}
#[test]
fn err_shape() {
assert_eq!(
err_line("GEN: unknown/unsupported key pen_from"),
"ERR GEN: unknown/unsupported key pen_from"
);
}
}