Federico hypothesis 'fix drafter at 5, see if it rises' -> MEASURED NO. Sweep on real capital prompt GEN 96 (gfx1150), decode tok/s: nd=1 5.25, nd=2 6.09, nd=3 5.78, nd=4 5.54, nd=5 4.58, nd=7 5.15. At ~30-50% acceptance a larger verify batch (B=nd+1) wastes compute on rejected drafts; nd=2 is the optimum. Retune the EMA governor to start at n_draft=2 and escalate only at very high acceptance (>=0.75 -> 4, >=0.9 -> 7). Adaptive run now lands nd=2: decode 6.10 tok/s, ON 4.59 vs OFF 3.97 tok/s total (~1.16x). VETTA_SPEC_ND fixes n_draft for A/B measurement. serve_gen_spec_multi_token_parity still EXACT (16 reference tokens). CPU -D warnings clean, gw GPU 22/22.
973 lines
44 KiB
Rust
973 lines
44 KiB
Rust
//! 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 <id>` 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::cell::RefCell;
|
|
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_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
|
use vetta_infer_ld::SafetensorsArchive;
|
|
#[cfg(feature = "hip")]
|
|
use vetta_infer_ld::layer::forward_batch_taps;
|
|
#[cfg(feature = "hip")]
|
|
use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkWeights, DS_HIDDEN};
|
|
|
|
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). Sized to accommodate the
|
|
/// consumer's default generation budget (strata-ctl max_new=16384) plus a large
|
|
/// agent prompt; KV is allocated per request at prompt+max_new, well within the
|
|
/// 48 GiB HIP-visible VRAM. Flash scores live in global memory, so full-attn is
|
|
/// not limited by the 64 KB LDS cap.
|
|
const MAX_CONTEXT: usize = 32768;
|
|
|
|
/// Clamp the generation budget to the resident window instead of hard-erroring.
|
|
/// strata-ctl always sends the default budget max_new=16384, so a prompt longer
|
|
/// than MAX_CONTEXT-16386 (e.g. 16504/16686 seen live) must still run with a
|
|
/// reduced budget rather than return 0 tokens and kill the agent mid-window.
|
|
/// `None` = the prompt itself no longer fits (true overflow, hard error).
|
|
fn clamp_max_new(n_prompt: usize, max_new: usize, max_context: usize) -> Option<usize> {
|
|
if n_prompt + 2 >= max_context { return None; }
|
|
Some(max_new.min(max_context - n_prompt - 2))
|
|
}
|
|
|
|
/// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in
|
|
/// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries
|
|
/// so a new request whose prompt extends a cached prefix restores it and prefills
|
|
/// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never
|
|
/// evicted (I3); otherwise LRU eviction at the cap.
|
|
const PREFIX_CACHE_CAP: usize = 8;
|
|
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
|
|
/// Grid checkpoints (multiples of 512) are the STABLE prefixes that survive the
|
|
/// turn-tag tail divergence; boundary/full-sequence checkpoints rarely hit again.
|
|
/// Eviction prefers dropping non-grid entries so the useful grid is protected.
|
|
fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
|
|
|
|
struct Checkpoint {
|
|
tokens: Vec<i32>,
|
|
layers: Vec<Option<LayerSnapshot>>,
|
|
lru: u64,
|
|
}
|
|
|
|
/// Resident pool of prefix checkpoints (interior mutability: serve_gen holds
|
|
/// `&InklingEngine`). Single conversation slot (FIFO serve).
|
|
pub struct PrefixCache {
|
|
pool: Vec<Checkpoint>,
|
|
tick: u64,
|
|
}
|
|
|
|
impl PrefixCache {
|
|
pub fn new() -> Self { Self { pool: Vec::new(), tick: 0 } }
|
|
|
|
/// Index + length of the longest checkpoint whose tokens are a STRICT prefix
|
|
/// of ids (l < ids.len()). The suffix must be non-empty: the final logits come
|
|
/// from a real forward of the last prompt token, which a full-length restore
|
|
/// (l == ids.len()) would not produce. Longer next-turn prompts still match.
|
|
fn best_match(&self, ids: &[i32]) -> Option<(usize, usize)> {
|
|
let mut best: Option<(usize, usize)> = None;
|
|
for (i, ck) in self.pool.iter().enumerate() {
|
|
let l = ck.tokens.len();
|
|
if l == 0 || l >= ids.len() { continue; }
|
|
if ck.tokens[..] == ids[..l] && best.map_or(true, |(_, bl)| l > bl) {
|
|
best = Some((i, l));
|
|
}
|
|
}
|
|
best
|
|
}
|
|
|
|
/// Allocate + restore every checkpointed layer into `states` at `max_seq`.
|
|
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
|
|
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
|
|
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
|
|
fn restore(&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
|
|
{
|
|
let ck = &self.pool[idx];
|
|
// A usable checkpoint must cover EVERY layer: a partially-restored state
|
|
// would cold-start the missing layers and break prefix equivalence.
|
|
if ck.layers.len() != states.len() || ck.layers.iter().any(|s| s.is_none()) {
|
|
return Err("incomplete prefix checkpoint".into());
|
|
}
|
|
for (ip, snap) in ck.layers.iter().enumerate() {
|
|
if let Some(s) = snap {
|
|
// Reuse the persistent state when it is already sized for this
|
|
// request (same cap + pass count); restore overwrites its KV
|
|
// prefix + hist rings. The stale KV tail beyond seq_len is never
|
|
// read (causal attention), so reuse is exact (restore_equiv).
|
|
let want = if is_swa(ip) { vetta_infer_ld::layer::swa_ring(d) } else { max_seq };
|
|
let reuse = states[ip].as_ref()
|
|
.map_or(false, |st| st.max_seq == want && st.k_cache.len() == s.k_cache.len());
|
|
if !reuse {
|
|
states[ip] = Some(new_state(d, want, s.k_cache.len())?);
|
|
}
|
|
states[ip].as_mut().unwrap().restore(d, s)?;
|
|
}
|
|
}
|
|
}
|
|
self.tick += 1;
|
|
self.pool[idx].lru = self.tick;
|
|
Ok(self.pool[idx].tokens.len())
|
|
}
|
|
|
|
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
|
|
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean.
|
|
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
|
|
let seq = tokens.len();
|
|
if seq == 0 { return Ok(()); }
|
|
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
|
|
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
|
|
.collect::<Result<_, _>>()?;
|
|
self.tick += 1;
|
|
let lru = self.tick;
|
|
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) {
|
|
ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
|
|
return Ok(());
|
|
}
|
|
if self.pool.len() < PREFIX_CACHE_CAP {
|
|
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
|
|
return Ok(());
|
|
}
|
|
let victim = self.pool.iter().enumerate()
|
|
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
|
|
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
|
|
if let Some(i) = victim {
|
|
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// A loaded Inkling model ready to run autoregressive forwards.
|
|
pub struct InklingEngine {
|
|
cache: WeightCache,
|
|
d: Dims,
|
|
vocab: usize,
|
|
n_layers: usize,
|
|
eos: i32,
|
|
cap: f32,
|
|
prefix: RefCell<PrefixCache>,
|
|
/// Persistent per-layer KV/ShortConv states reused across requests, sized to
|
|
/// `states_cap` (a 4096-bucket >= prompt+max_new). Eliminates the per-request
|
|
/// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
|
|
states: RefCell<Vec<Option<LayerState>>>,
|
|
/// Resident context window (advertised in READY). Defaults to MAX_CONTEXT;
|
|
/// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents.
|
|
max_context: usize,
|
|
/// DSpark drafter weights (resident), loaded only when VETTA_SPEC=1 and
|
|
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
|
|
#[cfg(feature = "hip")]
|
|
spec_dw: Option<DsparkWeights>,
|
|
}
|
|
|
|
impl InklingEngine {
|
|
/// Load the archive + `config.json` and derive the forward dimensions.
|
|
pub fn new(dir: &str) -> Result<Self, String> {
|
|
// Production KV dtype: FP16 (exact strata default, parity-verified EXACT,
|
|
// half the VRAM of the F32 CPU-oracle baseline). The ld parity tests keep
|
|
// the F32 default; the resident serve opts in here.
|
|
vetta_infer_ld::layer::set_kv_f16(true);
|
|
// Batched prefill uses the device-resident f16 MoE (moe_batched). Align the
|
|
// M=1 decode to the same f16 device path (moe_device, bit-identical math) so
|
|
// prefill and decode share one expert precision (verified EXACT greedy).
|
|
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
|
|
let ar = Arc::new(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,
|
|
};
|
|
let max_context = std::env::var("VETTA_MAX_CONTEXT").ok()
|
|
.and_then(|s| s.parse::<usize>().ok())
|
|
.filter(|&v| v >= 4096)
|
|
.unwrap_or(MAX_CONTEXT);
|
|
// Opt-in DSpark drafter: load resident weights iff VETTA_SPEC=1 and the
|
|
// mtp shard passes the strict layout check (else disable, never guess).
|
|
#[cfg(feature = "hip")]
|
|
let spec_dw = if std::env::var("VETTA_SPEC").is_ok() {
|
|
let mtp = ar.dir.join("mtp.safetensors");
|
|
match SafetensorsArchive::open_file(mtp.to_str().unwrap_or_default()) {
|
|
Ok(mar) if layout_check(&mar).is_ok() => DsparkWeights::load(&mar).ok(),
|
|
_ => None,
|
|
}
|
|
} else { None };
|
|
Ok(Self {
|
|
cache: WeightCache::new(ar),
|
|
d,
|
|
// The served/logit vocab is the UNPADDED size (exact strata
|
|
// k_unembed_softcap V = vocab_unpadded): rows >= unpadded are padding
|
|
// tokens whose arbitrary logits must never win the argmax. Using the
|
|
// padded vocab let padding tokens (e.g. 200193) outrank real ones.
|
|
vocab: t.unpadded_vocab,
|
|
n_layers: t.n_layers,
|
|
eos: cfg.eos_token_id as i32,
|
|
cap: t.final_logit_softcapping as f32,
|
|
prefix: RefCell::new(PrefixCache::new()),
|
|
states: RefCell::new(Vec::new()),
|
|
max_context,
|
|
#[cfg(feature = "hip")]
|
|
spec_dw,
|
|
})
|
|
}
|
|
|
|
pub fn vocab(&self) -> usize {
|
|
self.vocab
|
|
}
|
|
|
|
pub fn max_context(&self) -> usize {
|
|
self.max_context
|
|
}
|
|
|
|
fn forward(
|
|
&self,
|
|
token: i32,
|
|
pos: i32,
|
|
max_seq: usize,
|
|
states: &mut [Option<LayerState>],
|
|
) -> Result<DeviceBuf, String> {
|
|
forward_inkling_with_state(&self.cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
|
|
}
|
|
|
|
/// Batched prefill chunk (M=B): one forward over B tokens, logits for the last.
|
|
fn forward_batched(
|
|
&self,
|
|
tokens: &[i32],
|
|
pos: i32,
|
|
max_seq: usize,
|
|
states: &mut [Option<LayerState>],
|
|
) -> Result<DeviceBuf, String> {
|
|
forward_batch(&self.cache, &self.d, tokens, self.vocab, max_seq, pos, self.cap, states)
|
|
}
|
|
}
|
|
|
|
/// Prefill chunk size (M=B per batched forward). Default 256 amortizes weight
|
|
/// streaming + kernel launches across 256 tokens vs the old M=1 per-token path.
|
|
/// VETTA_PREFILL_CHUNK overrides; 1 forces the sequential path (A/B parity).
|
|
fn prefill_chunk_size() -> usize {
|
|
std::env::var("VETTA_PREFILL_CHUNK").ok()
|
|
.and_then(|s| s.parse::<usize>().ok())
|
|
.filter(|&c| c >= 1)
|
|
.unwrap_or(256)
|
|
}
|
|
|
|
fn emit_all(emit: &mut dyn FnMut(String), lines: Vec<String>) {
|
|
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 restores the longest cached prefix of its prompt (if any) and
|
|
/// prefills only the new suffix tokens; with no match it cold-prefills the whole
|
|
/// prompt. Both paths are observationally identical (proofs/prefix_cache.lean).
|
|
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_context = eng.max_context();
|
|
// Clamp the budget to the window (reviewer 2026-12-02): only a prompt that
|
|
// itself overflows is a hard error; otherwise generate up to the room left.
|
|
let Some(effective_max_new) = clamp_max_new(n_prompt, g.max_new, max_context) else {
|
|
emit_all(emit, sess.on_error("prompt exceeds context window"));
|
|
return;
|
|
};
|
|
// KV capacities are FIXED per layer kind (SWA ring = swa_win+chunk_cap, global
|
|
// = max_context), allocated once and never resized across requests: no
|
|
// drop+realloc when a session crosses a 4096 multiple (reviewer punto 2).
|
|
if eng.states.borrow().len() != eng.n_layers {
|
|
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
|
|
}
|
|
let cap = max_context;
|
|
let mut states = eng.states.borrow_mut();
|
|
|
|
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
|
|
// the longest cached strict prefix of this prompt and prefill only the NEW
|
|
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
|
|
let mut start = 0usize;
|
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
|
|
let matched = eng.prefix.borrow().best_match(&g.ids);
|
|
if let Some((idx, _l)) = matched {
|
|
match eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap) {
|
|
Ok(n) => start = n,
|
|
Err(_) => {
|
|
// Incomplete/failed restore: fall back to a clean cold prefill.
|
|
*states = (0..eng.n_layers).map(|_| None).collect();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Cold request (no prefix restored): the persistent states carry the previous
|
|
// conversation's ShortConv history. Reset the hist rings (the KV prefix is
|
|
// overwritten by prefill before any causal read) so a fresh conversation starts
|
|
// empty. A restored request instead overwrites hist via the checkpoint.
|
|
if start == 0 {
|
|
for st in states.iter_mut().flatten() {
|
|
if let Err(e) = st.reset_history() {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
|
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
|
|
if start == 0 {
|
|
// No match: show each cached checkpoint's length and how many leading
|
|
// tokens it shares with this prompt, to pinpoint a token divergence
|
|
// (common < len => the re-rendered prompt differs at that position).
|
|
let p = eng.prefix.borrow();
|
|
for (i, ck) in p.pool.iter().enumerate() {
|
|
let common = ck.tokens.iter().zip(g.ids.iter()).take_while(|(a, b)| a == b).count();
|
|
eprintln!("[prefix] ck[{i}] len={} common_prefix={common}", ck.tokens.len());
|
|
}
|
|
}
|
|
}
|
|
|
|
// Weights are resident in eng.cache (loaded once at boot, reused across all
|
|
// requests): no per-request NVMe re-read or re-upload.
|
|
|
|
// Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps
|
|
// during prefill to build the drafter context rings, then run a batched
|
|
// speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft).
|
|
#[cfg(feature = "hip")]
|
|
let spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties();
|
|
#[cfg(not(feature = "hip"))]
|
|
let spec_enabled = false;
|
|
#[cfg(feature = "hip")]
|
|
let mut dctx: Option<DsparkContext> = None;
|
|
#[cfg(feature = "hip")]
|
|
if spec_enabled {
|
|
match DsparkContext::new(cap, DS_HIDDEN) {
|
|
Ok(c) => dctx = Some(c),
|
|
Err(e) => {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. ---
|
|
// Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel
|
|
// launches amortized across B), growing KV/history; logits come from the last
|
|
// token of the final chunk. VETTA_PREFILL_CHUNK=1 restores the M=1 path (A/B).
|
|
let t0 = Instant::now();
|
|
let mut pos = start as i32;
|
|
let mut history: Vec<i32> = g.ids[..start].to_vec();
|
|
history.reserve(n_prompt - start + effective_max_new);
|
|
let mut logits: Option<DeviceBuf> = None;
|
|
let chunk = prefill_chunk_size().min(vetta_infer_ld::layer::SWA_CHUNK_CAP);
|
|
let suffix = &g.ids[start..];
|
|
let mut done = 0usize;
|
|
// Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary
|
|
// so a checkpoint always lands on every multiple of 512 regardless of `start`
|
|
// (pos % 512 == 0 would miss boundaries when start/suffix aren't aligned).
|
|
let mut next_grid = ((start / 512) + 1) * 512;
|
|
while done < suffix.len() {
|
|
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;
|
|
}
|
|
let mut take = chunk.min(suffix.len() - done);
|
|
let pos_now = start + done;
|
|
if pos_now < next_grid && pos_now + take > next_grid {
|
|
take = next_grid - pos_now;
|
|
}
|
|
let toks = &suffix[done..done + take];
|
|
let lg = if spec_enabled {
|
|
#[cfg(feature = "hip")]
|
|
{
|
|
(|| -> Result<DeviceBuf, String> {
|
|
let h = eng.d.hidden;
|
|
let mut taps = [DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?];
|
|
let l = forward_batch_taps(&eng.cache, &eng.d, toks, eng.vocab, cap, pos, eng.cap, &mut states[..], &mut taps)?;
|
|
let pb = DeviceBuf::alloc(take * 4)?;
|
|
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
|
|
let dw = eng.spec_dw.as_ref().unwrap();
|
|
let dc = dctx.as_mut().unwrap();
|
|
dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?;
|
|
dc.len = (pos + take as i32) as usize;
|
|
Ok(l)
|
|
})()
|
|
}
|
|
#[cfg(not(feature = "hip"))]
|
|
{ Err("spec requires hip".into()) }
|
|
} else if take == 1 {
|
|
eng.forward(toks[0], pos, cap, &mut states[..])
|
|
} else {
|
|
eng.forward_batched(toks, pos, cap, &mut states[..])
|
|
};
|
|
match lg {
|
|
Ok(l) => logits = Some(l),
|
|
Err(e) => {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
}
|
|
history.extend_from_slice(toks);
|
|
pos += take as i32;
|
|
done += take;
|
|
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
|
|
// checkpoint on every 512 boundary so the next turn can restore a stable
|
|
// prefix even when the prompt's trailing turn-tag tokens re-render
|
|
// differently. best_match picks the longest grid checkpoint that is a full
|
|
// prefix; grid entries are protected from eviction (is_grid) and refreshed
|
|
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
|
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
|
|
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
|
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
|
eprintln!("[prefix] grid save seq={pos}");
|
|
}
|
|
next_grid += 512;
|
|
}
|
|
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
|
if let Ok(pp) = sess.on_prefill_chunk((start + done) 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).
|
|
// `start` is the restored prefix length: >0 emits RESUME <start> (wire-compatible
|
|
// with strata, so strata-ctl reports the reused/cached prompt tokens).
|
|
match sess.on_prefill_complete(start as u32, prompt_ms) {
|
|
Ok(lines) => emit_all(emit, lines),
|
|
Err(e) => {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
}
|
|
// Checkpoint the PROMPT boundary. This is the prefix that stays token-identical
|
|
// across turns: strata-ctl re-renders the same system+history text each turn,
|
|
// while the assistant reply round-trips through detokenize/re-encode (special
|
|
// tokens stripped) and is NOT token-identical to the generated ids. Saving here
|
|
// — not only at the post-decode `pos` — is what lets the next turn restore the
|
|
// stable prefix and prefill only the new dialogue suffix. Mirrors strata
|
|
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
|
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
|
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
|
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
|
eprintln!("[prefix] prompt-boundary save seq={pos}");
|
|
}
|
|
}
|
|
if effective_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;
|
|
}
|
|
};
|
|
// --- Opt-in DSpark speculative decode (greedy, lossless vs batched B=1). ---
|
|
#[cfg(feature = "hip")]
|
|
if spec_enabled {
|
|
let dw = eng.spec_dw.as_ref().unwrap();
|
|
let mut dc = dctx.take().unwrap();
|
|
let t1 = Instant::now();
|
|
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 argmax = |v: &[f32]| -> i32 {
|
|
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
|
|
for (i, &z) in v.iter().enumerate() { if z > bz { bz = z; best = i; } }
|
|
best as i32
|
|
};
|
|
let tok0 = argmax(&lg);
|
|
let mut finish = "length";
|
|
let mut generated = 0usize;
|
|
let emit_tok = |t: i32, emit: &mut dyn FnMut(String), sess: &mut ServeSession, history: &mut Vec<i32>, generated: &mut usize| -> bool {
|
|
match sess.on_token(t as u32) {
|
|
Ok(lines) => emit_all(emit, lines),
|
|
Err(e) => { emit_all(emit, sess.on_error(&e)); return false; }
|
|
}
|
|
history.push(t); *generated += 1;
|
|
true
|
|
};
|
|
if !emit_tok(tok0, emit, &mut sess, &mut history, &mut generated) {
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
let mut cur_pos = pos; let mut next_tok = tok0;
|
|
// Measured optimum on real text (gfx1150, GEN 96): n_draft=2 gives the best
|
|
// decode tok/s (6.09) vs 3=5.78, 4=5.54, 5=4.58, 7=5.15, 1=5.25 — at ~30-50%
|
|
// acceptance a larger verify batch wastes compute on rejected drafts. Start
|
|
// at 2 and escalate only when acceptance is very high (cost-aware governor).
|
|
let mut ema = 0.5f32; let mut n_draft = 2usize;
|
|
// VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement.
|
|
let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::<usize>().ok());
|
|
let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize;
|
|
if tok0 == eng.eos {
|
|
finish = "stop";
|
|
} else {
|
|
while generated < effective_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 left = effective_max_new - generated;
|
|
let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1));
|
|
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, &mut dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
};
|
|
let mut hit_eos = false;
|
|
for &t in &em {
|
|
if !emit_tok(t, emit, &mut sess, &mut history, &mut generated) {
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
if t == eng.eos { hit_eos = true; break; }
|
|
if generated >= effective_max_new { break; }
|
|
}
|
|
if nd > 0 {
|
|
let acc = (em.len().saturating_sub(1)) as f32 / nd as f32;
|
|
ema = 0.9 * ema + 0.1 * acc;
|
|
n_draft = if ema >= 0.9 { 7 } else if ema >= 0.75 { 4 } else { 2 };
|
|
offered += nd; accepted += em.len().saturating_sub(1);
|
|
}
|
|
rounds += 1;
|
|
cur_pos = nc; next_tok = nt; pos = nc;
|
|
if hit_eos { finish = "stop"; break; }
|
|
if done || generated >= effective_max_new { finish = "length"; break; }
|
|
}
|
|
}
|
|
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
|
|
if std::env::var("VETTA_DBG_SPEC").is_ok() {
|
|
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema={ema:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0));
|
|
}
|
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
|
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
|
}
|
|
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
let mut finish = "length";
|
|
for step in 0..effective_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 std::env::var("VETTA_DBG_LOGITS").is_ok() {
|
|
let mut idx: Vec<usize> = (0..eng.vocab).collect();
|
|
idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap());
|
|
let top: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect();
|
|
eprintln!("[dbg] step={step} pos={pos} top5={top:?}");
|
|
}
|
|
if rep.nonfinite_logits == eng.vocab {
|
|
finish = "nonfinite";
|
|
break;
|
|
}
|
|
// Emit the EOS token as `T <eos>` 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) => {
|
|
emit_all(emit, sess.on_error(&e));
|
|
stop.store(false, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
}
|
|
if is_eos {
|
|
finish = "stop";
|
|
break;
|
|
}
|
|
history.push(rep.token);
|
|
if step + 1 == effective_max_new {
|
|
finish = "length";
|
|
break;
|
|
}
|
|
match eng.forward(rep.token, pos, cap, &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;
|
|
// Also checkpoint the full processed sequence (prompt + generated tokens). This
|
|
// is a bonus reuse when the next prompt IS token-identical (e.g. a retry); the
|
|
// prompt-boundary checkpoint above is the robust one for normal chat. `pos`
|
|
// counts tokens actually folded into `states` (history[..pos]); a sampled token
|
|
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
|
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
|
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
|
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
|
eprintln!("[prefix] full-sequence save seq={pos}");
|
|
}
|
|
}
|
|
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)?;
|
|
// Default: eager full-model residency at boot — VRAM is populated immediately
|
|
// (like the reference) and no request pays NVMe reads/uploads. The cache is
|
|
// resident across requests either way. VETTA_LAZY_LOAD=1 defers to first use.
|
|
if std::env::var("VETTA_LAZY_LOAD").is_err() {
|
|
eng.cache.prewarm(&eng.d, eng.n_layers)?;
|
|
}
|
|
let vocab = eng.vocab();
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let quit = Arc::new(AtomicBool::new(false));
|
|
let (tx, rx) = mpsc::channel::<Msg>();
|
|
|
|
{
|
|
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(eng.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::*;
|
|
|
|
/// CPU: the budget clamp must keep long agent prompts runnable (strata-ctl
|
|
/// always sends max_new=16384) instead of hard-erroring past 16382 tokens, and
|
|
/// only reject a prompt that itself overflows the window.
|
|
#[test]
|
|
fn clamp_max_new_budget() {
|
|
// live agent prompts 16504/16686 with the default 16384 budget: clamp, run.
|
|
assert_eq!(clamp_max_new(16504, 16384, 32768), Some(32768 - 16504 - 2));
|
|
assert_eq!(clamp_max_new(16686, 16384, 32768), Some(32768 - 16686 - 2));
|
|
// small prompt keeps the full budget.
|
|
assert_eq!(clamp_max_new(2648, 16384, 32768), Some(16384));
|
|
// exactly at the last usable prompt position: 1 token of room.
|
|
assert_eq!(clamp_max_new(32765, 16384, 32768), Some(1));
|
|
// prompt itself overflows: hard error (None).
|
|
assert_eq!(clamp_max_new(32766, 16384, 32768), None);
|
|
assert_eq!(clamp_max_new(40000, 16384, 32768), None);
|
|
// configurable larger window accepts the same long prompt unclamped.
|
|
assert_eq!(clamp_max_new(16504, 16384, 65536), Some(16384));
|
|
// GEN 0 pre-warm stays 0 regardless of prompt.
|
|
assert_eq!(clamp_max_new(2648, 0, 32768), Some(0));
|
|
}
|
|
|
|
/// GPU integration: drive `serve_gen` over the wire for the canonical prompt
|
|
/// "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() {
|
|
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,
|
|
_ => panic!("expected Gen"),
|
|
};
|
|
let stop = AtomicBool::new(false);
|
|
let mut lines: Vec<String> = 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() {
|
|
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,
|
|
_ => panic!("expected Gen"),
|
|
};
|
|
let stop = AtomicBool::new(false);
|
|
let mut lines: Vec<String> = 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 ...");
|
|
});
|
|
}
|
|
|
|
/// GPU regression: multi-token decode must match the reference EXACTLY. This
|
|
/// locks in the two correctness fixes that eliminated the systematic token-2+
|
|
/// divergence: (1) per-pass KV cache (each core pass owns a distinct KV pool,
|
|
/// exact strata visit_kv_slot) and (2) unpadded logit vocab (padding tokens
|
|
/// >= unpadded_vocab_size must never win the argmax). Sequence measured against
|
|
/// strata-inkling --native model.gguf for "The capital of France is" (greedy).
|
|
#[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,
|
|
_ => panic!("expected Gen"),
|
|
};
|
|
let stop = AtomicBool::new(false);
|
|
let mut lines: Vec<String> = Vec::new();
|
|
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
|
let tokens: Vec<i32> = lines.iter()
|
|
.filter(|l| l.starts_with("T "))
|
|
.map(|l| l[2..].trim().parse().unwrap())
|
|
.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 <eos>` 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<String> = Vec::new();
|
|
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
|
let tokens: Vec<i32> = 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}");
|
|
});
|
|
}
|
|
|
|
/// GPU: the opt-in DSpark speculative serve path (VETTA_SPEC=1, batched
|
|
/// verify + rollback + EMA) must emit EXACTLY the same reference tokens as
|
|
/// the default M=1 decode for the canonical capital prompt. Verifies the
|
|
/// serve orchestration (pos/history/EOS/length) AND that the batched decode
|
|
/// path is greedy-vs-reference exact.
|
|
#[test]
|
|
#[ignore]
|
|
fn serve_gen_spec_multi_token_parity() {
|
|
crate::gpu_isolated(|| {
|
|
unsafe { std::env::set_var("VETTA_SPEC", "1"); }
|
|
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
|
assert!(eng.spec_dw.is_some(), "drafter weights must load with VETTA_SPEC=1");
|
|
let g = match parse_serve_line("GEN 16 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<String> = Vec::new();
|
|
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
|
let tokens: Vec<i32> = lines.iter()
|
|
.filter(|l| l.starts_with("T "))
|
|
.map(|l| l[2..].trim().parse().unwrap())
|
|
.collect();
|
|
let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014];
|
|
unsafe { std::env::remove_var("VETTA_SPEC"); }
|
|
assert_eq!(tokens, want, "speculative serve path must match reference exactly");
|
|
});
|
|
}
|
|
|
|
/// GPU perf probe: spec-on vs spec-off decode tok/s + acceptance on a real
|
|
/// prompt (GEN 96). Prints measured numbers; no speedup claim without them.
|
|
#[test]
|
|
#[ignore]
|
|
fn serve_gen_spec_perf() {
|
|
crate::gpu_isolated(|| {
|
|
let ids = "371,151451,149879,151194,149884";
|
|
let run = |spec: bool| -> (f64, usize) {
|
|
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
|
|
unsafe { std::env::set_var("VETTA_DBG_SPEC", "1"); }
|
|
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
|
let g = match parse_serve_line(&format!("GEN 96 temperature=0 {ids}"), eng.vocab()).unwrap() {
|
|
ServeCommand::Gen(g) => g,
|
|
_ => panic!("expected Gen"),
|
|
};
|
|
let stop = AtomicBool::new(false);
|
|
let mut lines: Vec<String> = Vec::new();
|
|
let t = Instant::now();
|
|
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
|
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
|
let n = lines.iter().filter(|l| l.starts_with("T ")).count();
|
|
unsafe { std::env::remove_var("VETTA_SPEC"); std::env::remove_var("VETTA_DBG_SPEC"); }
|
|
(ms, n)
|
|
};
|
|
let (off_ms, off_n) = run(false);
|
|
let (on_ms, on_n) = run(true);
|
|
eprintln!("spec_perf: OFF {off_n} tok {off_ms:.1}ms {:.2} tok/s | ON {on_n} tok {on_ms:.1}ms {:.2} tok/s", off_n as f64 / (off_ms / 1000.0), on_n as f64 / (on_ms / 1000.0));
|
|
assert_eq!(off_n, on_n, "spec must emit the same token count");
|
|
});
|
|
}
|
|
} |