[ABI][KN][LD][CC][RT][LAB][SP][NT][TM][GW][Proofs][Docs] M0.5: realign workspace to vetta-infer-* microkernel architecture

Dissolve the M0 crates (core/io/proto/telemetry/hip/cli) into the approved
service layout abi/kn/ld/cc/rt/lab/sp/nt/tm/gw (docs/ARCHITECTURE.md).

- kn: Lean-verified control bus + service registry (bus_lifecycle.lean, 14 thms)
  and SlabRing/UMA broker; rt: PrefixState + hybrid checkpoint pool.
- sp: faithful throughput-aware Adaptive-K port of clover_policy.h
  (cooldowns, probes, throughput guards) with scenario parity tests.
- gw: strata-ctl-compatible wire emitters + serve session FSM
  (serve_session.lean, 10 thms); abi::serve accepts image= (Vision delta closed).
- abi: pure contracts, checked JSON/VTC1/GEN parsers, zero-alloc sampler.
- ld/cc: checked safetensors reader + write-once VTC1 writer / O_RDONLY reader.
- tm: lock-free telemetry; nt: LyraRpc; lab shares the rt executor core.
- Docs: ARCHITECTURE.md decision-complete spec (MoE-only scope, .vbundle,
  .vplan->CompiledPlan, wire contract, migration map); AGENTS.md Lean rule
  + tandem/review workflow.

Verified live: cargo test --workspace -D warnings = 46/46 PASS;
lean proofs = 34 theorems (slab_ring_dma 10, bus_lifecycle 14, serve_session 10),
0 sorryAx, standard axioms only; vetta-infer info on Inkling = 1244 tensors,
18.18 GiB, checked bounds.
This commit is contained in:
adm committed 2026-11-30 00:54:00 +01:00
1 parent 63b1668a92
commit 7b50f1c07c
49 files changed
+3211 -1208

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
[package]
name = "vetta-infer-abi"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
+77
View File
@@ -0,0 +1,77 @@
//! Control-bus contracts: service identity, lifecycle states and message formats.
//!
//! Lifecycle transitions are verified in `proofs/bus_lifecycle.lean` and
//! enforced by `vetta-infer-kn` (registry + bus). These are the shared types
//! every service speaks; the bus carries control-plane messages only — the
//! data plane exchanges UMA memory handles, never tensor copies.
/// Stable identity of a registered service (handed out by the registry, two-phase).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ServiceId(pub u32);
/// The service kinds of the approved architecture (docs/ARCHITECTURE.md §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ServiceKind {
/// `ld` — loader & compiler (dual-step → `.vbundle/`)
Loader,
/// `cc` — cache & storage (UMA residency, NVMe streaming, Hot/Cold experts)
Cache,
/// `rt` — operational runtime (CompiledPlan on HIP, zero probes)
Runtime,
/// `lab` — laboratory runtime (same executor + probe hooks)
Lab,
/// `sp` — speculative coordinator (lossless verification, Adaptive-K)
Spec,
/// `nt` — LAN bridge to Lyra
Net,
/// `tm` — telemetry observer
Telemetry,
/// `gw` — gateway & CLI (`--serve`, HTTP, `vetta-infer`)
Gateway,
}
/// Lifecycle of one service — mirrors `SvcState` in `proofs/bus_lifecycle.lean`.
/// `Stopping` = STOP issued, draining in-flight work; `Stopped` is terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceState {
Registered,
Running,
Stopping,
Stopped,
}
/// Typed control-plane payloads. Extended additively as services land;
/// unknown-to-a-service payloads are rejected explicitly, never silently.
#[derive(Debug, Clone, PartialEq)]
pub enum BusPayload {
/// Kernel → service: stop accepting new work and drain.
Stop,
/// Service → kernel: drain complete, resources released (acks `Stop`).
StopAck,
/// Domain routing hint (e.g. `"lean4"`, `"dante"`) for cache pre-warm.
DomainHint(String),
}
/// One routed control-plane message.
#[derive(Debug, Clone, PartialEq)]
pub struct BusMsg {
pub src: ServiceId,
pub dst: ServiceId,
pub payload: BusPayload,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn msg_shape() {
let m = BusMsg {
src: ServiceId(0),
dst: ServiceId(1),
payload: BusPayload::DomainHint("lean4".into()),
};
assert_eq!(m.dst, ServiceId(1));
assert_eq!(m.payload, BusPayload::DomainHint("lean4".into()));
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Minimal checked JSON parser (zero external deps, strict UTF-8/escapes).
//! Pure parsing shared by `ld` (safetensors headers, index.json), `cc` and `gw`
//! (manifest, `.vplan`). No IO here.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonVal {
Null,
Bool(bool),
Num(f64),
Int(u64),
Str(String),
Arr(Vec<JsonVal>),
Obj(std::collections::HashMap<String, JsonVal>),
}
impl JsonVal {
pub fn as_obj(&self) -> Option<&std::collections::HashMap<String, JsonVal>> {
match self {
JsonVal::Obj(m) => Some(m),
_ => None,
}
}
pub fn as_arr(&self) -> Option<&[JsonVal]> {
match self {
JsonVal::Arr(v) => Some(v),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
JsonVal::Str(s) => Some(s),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
JsonVal::Int(n) => Some(*n),
JsonVal::Num(f) if *f >= 0.0 && f.fract() == 0.0 && *f <= (u64::MAX as f64) => Some(*f as u64),
_ => None,
}
}
}
struct JsonParser<'a> {
b: &'a [u8],
i: usize,
}
impl<'a> JsonParser<'a> {
fn skip_ws(&mut self) {
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\r' | b'\t') {
self.i += 1;
}
}
fn parse_str(&mut self) -> Result<String, String> {
if self.b.get(self.i) != Some(&b'"') {
return Err("expected '\"'".into());
}
self.i += 1;
let mut out = Vec::new();
while self.i < self.b.len() {
let c = self.b[self.i];
self.i += 1;
if c == b'"' {
return String::from_utf8(out).map_err(|_| "invalid UTF-8 in JSON string".into());
}
if c == b'\\' {
if self.i >= self.b.len() {
return Err("truncated JSON escape".into());
}
let e = self.b[self.i];
self.i += 1;
match e {
b'"' => out.push(b'"'),
b'\\' => out.push(b'\\'),
b'/' => out.push(b'/'),
b'b' => out.push(0x08),
b'f' => out.push(0x0C),
b'n' => out.push(b'\n'),
b'r' => out.push(b'\r'),
b't' => out.push(b'\t'),
b'u' => {
if self.i + 4 > self.b.len() {
return Err("truncated \\u escape".into());
}
let hex = std::str::from_utf8(&self.b[self.i..self.i + 4])
.map_err(|_| "bad \\u hex")?;
let code = u32::from_str_radix(hex, 16).map_err(|_| "bad \\u hex")?;
self.i += 4;
let ch = char::from_u32(code).unwrap_or('\u{FFFD}');
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
}
_ => return Err("unsupported JSON escape".into()),
}
} else {
out.push(c);
}
}
Err("unterminated JSON string".into())
}
fn parse_val(&mut self, depth: usize) -> Result<JsonVal, String> {
if depth > 64 {
return Err("JSON nesting too deep".into());
}
self.skip_ws();
let &c = self.b.get(self.i).ok_or_else(|| "unexpected EOF in JSON".to_string())?;
match c {
b'"' => Ok(JsonVal::Str(self.parse_str()?)),
b'{' => {
self.i += 1;
let mut map = std::collections::HashMap::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b'}') {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
loop {
self.skip_ws();
let k = self.parse_str()?;
self.skip_ws();
if self.b.get(self.i) != Some(&b':') {
return Err("expected ':'".into());
}
self.i += 1;
let v = self.parse_val(depth + 1)?;
map.insert(k, v);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b'}') => {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
}
b'[' => {
self.i += 1;
let mut arr = Vec::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b']') {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
loop {
arr.push(self.parse_val(depth + 1)?);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b']') => {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
_ => return Err("expected ',' or ']'".into()),
}
}
}
b't' if self.b[self.i..].starts_with(b"true") => {
self.i += 4;
Ok(JsonVal::Bool(true))
}
b'f' if self.b[self.i..].starts_with(b"false") => {
self.i += 5;
Ok(JsonVal::Bool(false))
}
b'n' if self.b[self.i..].starts_with(b"null") => {
self.i += 4;
Ok(JsonVal::Null)
}
b'-' | b'0'..=b'9' => {
let start = self.i;
if self.b[self.i] == b'-' {
self.i += 1;
}
let mut is_float = false;
while self.i < self.b.len() {
match self.b[self.i] {
b'0'..=b'9' => self.i += 1,
b'.' | b'e' | b'E' | b'+' | b'-' => {
is_float = true;
self.i += 1;
}
_ => break,
}
}
let s = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| "bad number")?;
if !is_float && !s.starts_with('-') {
if let Ok(u) = s.parse::<u64>() {
return Ok(JsonVal::Int(u));
}
}
let f = s.parse::<f64>().map_err(|_| format!("invalid number '{s}'"))?;
Ok(JsonVal::Num(f))
}
_ => Err(format!("unexpected char '{}' in JSON", c as char)),
}
}
}
pub fn parse_json(text: &str) -> Result<JsonVal, String> {
let mut p = JsonParser { b: text.as_bytes(), i: 0 };
let v = p.parse_val(0)?;
p.skip_ws();
if p.i != p.b.len() {
return Err("trailing characters in JSON".into());
}
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strict_parsing() {
assert!(parse_json("{\"a\":[1,2.5,true,null]}").is_ok());
assert!(parse_json("{\"a\":1} trailing").is_err());
assert!(parse_json("\"\\u0041\"").unwrap().as_str() == Some("A"));
assert!(parse_json("[1,2").is_err());
}
}
+16
View File
@@ -0,0 +1,16 @@
//! `vetta-infer-abi`: shared contracts between the microkernel and all services.
//!
//! Domain types, bus message formats, `.vplan` opcodes, wire-protocol parsing,
//! pure checked parsers (JSON, VTC1 metadata) and sampling algorithms
//! (docs/ARCHITECTURE.md §2, §4, §6, §9).
//! Zero external dependencies; pure data and pure functions only — no IO, no syscalls.
pub mod bus;
pub mod json;
pub mod sampler;
pub mod serve;
pub mod traits;
pub mod vplan;
pub mod vtc1;
pub use traits::ExpertKey;
+474
View File
@@ -0,0 +1,474 @@
//! Deterministic zero-allocation top-K sampler, exact penalties, and Leviathan speculative verifier.
//!
//! Eliminates F-07 (centralized `mask_token_id` suppression) and F-09 (no 1 MiB/token heap churn,
//! no silent 256-token truncation for `top_k == 0`, explicit non-finite logit count).
//! Pure algorithms shared by `rt`, `sp` and `gw` (docs/ARCHITECTURE.md §9).
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SamplingOpts {
pub temperature: f32,
pub top_k: usize,
pub top_p: f32,
pub min_p: f32,
pub penalty_repeat: f32,
pub penalty_freq: f32,
pub penalty_present: f32,
pub penalty_last_n: usize,
pub seed: u64,
}
impl Default for SamplingOpts {
fn default() -> Self {
Self {
temperature: 0.0,
top_k: 0,
top_p: 1.0,
min_p: 0.0,
penalty_repeat: 1.0,
penalty_freq: 0.0,
penalty_present: 0.0,
penalty_last_n: 64,
seed: 42,
}
}
}
impl SamplingOpts {
pub fn is_greedy(&self) -> bool {
self.temperature <= 0.0
}
pub fn has_penalties(&self) -> bool {
self.penalty_last_n > 0
&& (self.penalty_repeat != 1.0
|| self.penalty_freq != 0.0
|| self.penalty_present != 0.0)
}
}
/// SplitMix64 deterministic RNG (zero external crate deps, fast & reproducible).
#[derive(Debug, Clone)]
pub struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
pub fn new(seed: u64) -> Self {
Self { state: if seed == 0 { 0x9E37_79B9_7F4A_7C15 } else { seed } }
}
pub fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// Uniform float in `[0, 1)`.
pub fn next_f64(&mut self) -> f64 {
(self.next_u64() >> 11) as f64 * (1.0 / ((1u64 << 53) as f64))
}
}
#[derive(Debug, Clone, Copy)]
struct Cand {
val: f32,
id: i32,
}
impl PartialEq for Cand {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.val.to_bits() == other.val.to_bits()
}
}
impl Eq for Cand {}
/// Reverse order so `BinaryHeap<MinCand>` keeps the WORST candidate on top (min-heap of top-K).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MinCand(Cand);
impl Ord for MinCand {
fn cmp(&self, other: &Self) -> Ordering {
// Better = higher val, or equal val with smaller id.
// For min-heap, `other` better than `self` => self > other (so worst is popped first).
match other.0.val.total_cmp(&self.0.val) {
Ordering::Equal => self.0.id.cmp(&other.0.id),
ord => ord,
}
}
}
impl PartialOrd for MinCand {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn cand_desc(a: &Cand, b: &Cand) -> Ordering {
match b.val.total_cmp(&a.val) {
Ordering::Equal => a.id.cmp(&b.id),
ord => ord,
}
}
#[derive(Debug, Default, Clone)]
pub struct SamplerScratch {
pub idx: Vec<i32>,
pub prob: Vec<f64>,
cands: Vec<Cand>,
counts: HashMap<i32, u32>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SampleReport {
pub token: i32,
pub confidence: f32,
pub nonfinite_logits: usize,
pub entropy_nats: f32,
}
pub fn suppress_token(logits: &mut [f32], banned: Option<i32>) {
if let Some(id) = banned {
if id >= 0 && (id as usize) < logits.len() {
logits[id as usize] = f32::NEG_INFINITY;
}
}
}
pub fn apply_penalties(logits: &mut [f32], opts: &SamplingOpts, history: &[i32], scratch: &mut SamplerScratch) {
if !opts.has_penalties() || history.is_empty() || logits.is_empty() {
return;
}
scratch.counts.clear();
let win = history.len().min(opts.penalty_last_n);
for &id in &history[history.len() - win..] {
if id >= 0 && (id as usize) < logits.len() {
*scratch.counts.entry(id).or_insert(0) += 1;
}
}
for (&id, &cnt) in &scratch.counts {
let v = &mut logits[id as usize];
if !v.is_finite() {
continue;
}
if opts.penalty_repeat != 1.0 {
*v = if *v > 0.0 { *v / opts.penalty_repeat } else { *v * opts.penalty_repeat };
}
if opts.penalty_freq != 0.0 {
*v -= opts.penalty_freq * (cnt as f32);
}
if opts.penalty_present != 0.0 {
*v -= opts.penalty_present;
}
}
}
/// Builds a normalized/unnormalized truncated distribution into `scratch.{idx, prob}`.
/// Returns the number of non-finite logits encountered.
pub fn build_truncated_dist(
logits: &mut [f32],
opts: &SamplingOpts,
history: &[i32],
banned: Option<i32>,
scratch: &mut SamplerScratch,
) -> usize {
scratch.idx.clear();
scratch.prob.clear();
if logits.is_empty() {
return 0;
}
suppress_token(logits, banned);
apply_penalties(logits, opts, history, scratch);
let v = logits.len();
let mut nonfinite = 0usize;
let mut mx = f32::NEG_INFINITY;
for &val in logits.iter() {
if !val.is_finite() {
if val.is_nan() || val.is_infinite() && val.is_sign_positive() {
nonfinite += 1;
}
} else if val > mx {
mx = val;
}
}
if !mx.is_finite() {
scratch.idx.push(0);
scratch.prob.push(1.0);
return nonfinite;
}
let inv_t = 1.0f64 / (opts.temperature as f64).max(1e-6);
scratch.cands.clear();
if opts.top_k > 0 && opts.top_k < v && opts.top_k <= 512 {
let mut heap: BinaryHeap<MinCand> = BinaryHeap::with_capacity(opts.top_k + 1);
for (i, &val) in logits.iter().enumerate() {
if !val.is_finite() {
continue;
}
let c = MinCand(Cand { val, id: i as i32 });
if heap.len() < opts.top_k {
heap.push(c);
} else if let Some(&top) = heap.peek() {
if cand_desc(&c.0, &top.0) == Ordering::Less {
heap.pop();
heap.push(c);
}
}
}
scratch.cands.extend(heap.into_iter().map(|m| m.0));
scratch.cands.sort_unstable_by(cand_desc);
} else {
let logit_floor = if opts.min_p > 0.0 && opts.min_p < 1.0 && opts.top_k == 0 {
(mx as f64 + (opts.min_p as f64).ln() / inv_t) as f32
} else {
f32::NEG_INFINITY
};
for (i, &val) in logits.iter().enumerate() {
if !val.is_finite() {
continue;
}
if val < logit_floor && val < mx {
continue;
}
scratch.cands.push(Cand { val, id: i as i32 });
}
if scratch.cands.is_empty() {
scratch.idx.push(0);
scratch.prob.push(1.0);
return nonfinite;
}
let need_sort = (opts.top_k > 0 && opts.top_k < scratch.cands.len())
|| (opts.top_p > 0.0 && opts.top_p < 1.0);
if opts.top_k > 0 && opts.top_k < scratch.cands.len() {
scratch.cands.select_nth_unstable_by(opts.top_k, cand_desc);
scratch.cands.truncate(opts.top_k);
scratch.cands.sort_unstable_by(cand_desc);
} else if need_sort {
scratch.cands.sort_unstable_by(cand_desc);
}
}
let mut p_max = 0.0f64;
let mut z = 0.0f64;
for c in &scratch.cands {
let w = (((c.val as f64) - (mx as f64)) * inv_t).exp();
if w > p_max {
p_max = w;
}
scratch.idx.push(c.id);
scratch.prob.push(w);
z += w;
}
if z <= 0.0 {
let first = scratch.idx.first().copied().unwrap_or(0);
scratch.idx.clear();
scratch.prob.clear();
scratch.idx.push(first);
scratch.prob.push(1.0);
return nonfinite;
}
if opts.min_p > 0.0 && opts.min_p < 1.0 {
let thresh = (opts.min_p as f64) * p_max;
let mut keep = 0usize;
for i in 0..scratch.idx.len() {
if i == 0 || scratch.prob[i] >= thresh {
scratch.idx[keep] = scratch.idx[i];
scratch.prob[keep] = scratch.prob[i];
keep += 1;
}
}
scratch.idx.truncate(keep);
scratch.prob.truncate(keep);
}
if opts.top_p > 0.0 && opts.top_p < 1.0 && scratch.idx.len() > 1 {
let z2: f64 = scratch.prob.iter().sum();
let inv_z2 = 1.0 / z2.max(1e-30);
let mut cum = 0.0f64;
let mut keep = scratch.idx.len();
for i in 0..scratch.idx.len() {
cum += scratch.prob[i] * inv_z2;
if cum >= opts.top_p as f64 {
keep = i + 1;
break;
}
}
scratch.idx.truncate(keep);
scratch.prob.truncate(keep);
}
nonfinite
}
pub fn sample_logits_exact(
logits: &mut [f32],
opts: &SamplingOpts,
history: &[i32],
banned: Option<i32>,
rng: &mut SplitMix64,
scratch: &mut SamplerScratch,
) -> SampleReport {
if logits.is_empty() {
return SampleReport { token: 0, confidence: 1.0, nonfinite_logits: 0, entropy_nats: 0.0 };
}
if opts.is_greedy() {
suppress_token(logits, banned);
apply_penalties(logits, opts, history, scratch);
let mut best_id = 0i32;
let mut mx = f32::NEG_INFINITY;
let mut nonfinite = 0usize;
for (i, &val) in logits.iter().enumerate() {
if !val.is_finite() {
if val.is_nan() || (val.is_infinite() && val.is_sign_positive()) {
nonfinite += 1;
}
} else if val > mx {
mx = val;
best_id = i as i32;
}
}
let mut z = 0.0f64;
let mut h = 0.0f64;
if mx.is_finite() {
for &val in logits.iter() {
if val.is_finite() {
let w = ((val - mx) as f64).exp();
z += w;
}
}
if z > 0.0 {
for &val in logits.iter() {
if val.is_finite() {
let p = ((val - mx) as f64).exp() / z;
if p > 1e-12 {
h -= p * p.ln();
}
}
}
}
}
return SampleReport {
token: best_id,
confidence: if z > 0.0 { (1.0 / z) as f32 } else { 1.0 },
nonfinite_logits: nonfinite,
entropy_nats: h as f32,
};
}
let nonfinite = build_truncated_dist(logits, opts, history, banned, scratch);
let z: f64 = scratch.prob.iter().sum();
let inv_z = 1.0 / z.max(1e-30);
let mut h = 0.0f64;
for &w in &scratch.prob {
let p = w * inv_z;
if p > 1e-12 {
h -= p * p.ln();
}
}
let r = rng.next_f64() * z;
let mut c = 0.0f64;
let mut chosen = scratch.idx[0];
let mut chosen_p = scratch.prob[0] * inv_z;
for i in 0..scratch.idx.len() {
c += scratch.prob[i];
if r <= c {
chosen = scratch.idx[i];
chosen_p = scratch.prob[i] * inv_z;
break;
}
}
SampleReport {
token: chosen,
confidence: chosen_p as f32,
nonfinite_logits: nonfinite,
entropy_nats: h as f32,
}
}
/// Lossless Leviathan speculative verification (exact target distribution `p(x)`).
/// Returns `(emitted_token, accepted)`.
pub fn verify_draft_exact(
logits: &mut [f32],
opts: &SamplingOpts,
history: &[i32],
banned: Option<i32>,
rng: &mut SplitMix64,
draft_tok: i32,
scratch: &mut SamplerScratch,
) -> (i32, bool) {
if opts.is_greedy() {
let rep = sample_logits_exact(logits, opts, history, banned, rng, scratch);
return (rep.token, rep.token == draft_tok);
}
let _ = build_truncated_dist(logits, opts, history, banned, scratch);
let z: f64 = scratch.prob.iter().sum();
if z <= 0.0 || scratch.idx.is_empty() {
return (draft_tok, true);
}
let dpos = scratch.idx.iter().position(|&id| id == draft_tok);
let p_draft = dpos.map(|i| scratch.prob[i] / z).unwrap_or(0.0);
if dpos.is_some() && (scratch.idx.len() == 1 || rng.next_f64() < p_draft) {
return (draft_tok, true);
}
let z_rem = z - dpos.map(|i| scratch.prob[i]).unwrap_or(0.0);
if z_rem <= 0.0 {
return match dpos {
Some(_) => (draft_tok, true),
None => (scratch.idx[0], false),
};
}
let r = rng.next_f64() * z_rem;
let mut c = 0.0f64;
let mut last_valid = scratch.idx[0];
for i in 0..scratch.idx.len() {
if Some(i) == dpos {
continue;
}
last_valid = scratch.idx[i];
c += scratch.prob[i];
if r <= c {
return (scratch.idx[i], false);
}
}
(last_valid, false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn top_k_tie_break_and_no_256_cap_for_top_p() {
let mut sc = SamplerScratch::default();
let mut lg = vec![0.0f32; 600];
lg[500] = 5.0;
lg[10] = 5.0;
lg[300] = 4.0;
let opts = SamplingOpts { temperature: 1.0, top_k: 3, ..Default::default() };
let nf = build_truncated_dist(&mut lg, &opts, &[], None, &mut sc);
assert_eq!(nf, 0);
assert_eq!(sc.idx, vec![10, 500, 300]);
// 400 uniform tokens with top_k=0, top_p=0.9 -> keeps ~360 tokens (not truncated at 256!)
let mut unif = vec![1.0f32; 400];
let opts_u = SamplingOpts { temperature: 1.0, top_k: 0, top_p: 0.9, ..Default::default() };
build_truncated_dist(&mut unif, &opts_u, &[], None, &mut sc);
assert!((359..=361).contains(&sc.idx.len()));
}
#[test]
fn nonfinite_reported_and_mask_suppressed() {
let mut sc = SamplerScratch::default();
let mut rng = SplitMix64::new(7);
let mut lg = vec![1.0, f32::NAN, 9.0, 5.0];
let rep = sample_logits_exact(&mut lg, &SamplingOpts::default(), &[], Some(2), &mut rng, &mut sc);
assert_eq!(rep.nonfinite_logits, 1);
assert_eq!(rep.token, 3); // token 2 was suppressed
}
}
+211
View File
@@ -0,0 +1,211 @@
//! `--serve` wire protocol parsing — `strata-ctl` compatible (docs/ARCHITECTURE.md §6).
//!
//! Living consumer spec: `strata-ctl/src/engine/protocol.rs` (`Sampling::keys`,
//! `gen_line`). Accepted keys include everything the consumer emits today:
//! `temperature`, `top_p`, `top_k`, `min_p`, `penalty_*`, `seed`, `image=`
//! (repeatable, Vision), plus engine extensions `spec`, `domain`, `draft_top_k`.
//! Unknown keys are rejected explicitly (`ERR`), never silently ignored.
//! `GEN 0` = prefill + immediate `DONE` (pre-warm), never an error.
use crate::sampler::SamplingOpts;
#[derive(Debug, Clone, PartialEq)]
pub enum ServeCommand {
Gen(ParsedGen),
Reset,
Stop,
Quit,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedGen {
pub max_new: usize,
pub sampling: SamplingOpts,
/// `None` = engine default, `Some(0)` = AR off, `Some(1)` = adaptive, `Some(k)` = fixed k
pub spec_mode: Option<usize>,
pub draft_top_k: Option<usize>,
pub domain_hint: Option<String>,
/// `image=<encoded path>` keys in prompt order (strata-ctl Vision).
pub images: Vec<String>,
pub ids: Vec<i32>,
}
pub fn parse_id_csv(csv: &str, vocab_size: usize) -> Result<Vec<i32>, String> {
if csv.is_empty() {
return Err("empty token id list".into());
}
let mut out = Vec::new();
for piece in csv.split(',') {
if piece.is_empty() {
return Err("empty token id in CSV".into());
}
let id: u64 = piece
.parse()
.map_err(|_| format!("invalid token id '{piece}'"))?;
if id >= vocab_size as u64 {
return Err(format!("token id {id} out of vocab bounds [0, {vocab_size})"));
}
out.push(id as i32);
}
Ok(out)
}
pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, String> {
let trimmed = line.trim();
match trimmed {
"QUIT" | "EXIT" => return Ok(ServeCommand::Quit),
"RESET" | "CLEAR" => return Ok(ServeCommand::Reset),
"STOP" => return Ok(ServeCommand::Stop),
_ => {}
}
let toks: Vec<&str> = trimmed.split_whitespace().collect();
if toks.len() < 3 || toks[0] != "GEN" {
return Err("GEN: expected 'GEN <max_new> [key=val ...] <ids>'".into());
}
let max_new: u64 = toks[1].parse().map_err(|_| "GEN: bad max_new".to_string())?;
if max_new > 1_000_000 {
return Err("GEN: max_new out of range".into());
}
let mut sampling = SamplingOpts::default();
let mut spec_mode = None;
let mut draft_top_k = None;
let mut domain_hint = None;
let mut images = Vec::new();
for &kv in &toks[2..toks.len() - 1] {
let (k, v) = kv
.split_once('=')
.ok_or_else(|| format!("GEN: bad key=value '{kv}'"))?;
if k.is_empty() || v.is_empty() {
return Err(format!("GEN: bad key=value '{kv}'"));
}
match k {
"spec" => {
spec_mode = Some(match v {
"auto" | "adapt" => 1,
"off" | "ar" | "0" => 0,
_ => {
let n: usize = v.parse().map_err(|_| format!("GEN: bad spec={v}"))?;
if n > 32 {
return Err(format!("GEN: spec={v} > 32"));
}
n
}
});
}
"domain" => {
domain_hint = Some(v.to_string());
}
"seed" => {
sampling.seed = v.parse().map_err(|_| "GEN: bad seed".to_string())?;
}
"temperature" | "temp" => {
let d = parse_finite_f32(v, k)?;
sampling.temperature = d.max(0.0);
}
"top_p" => {
sampling.top_p = parse_finite_f32(v, k)?.clamp(0.0, 1.0);
}
"top_k" => {
let n: i64 = v.parse().map_err(|_| format!("GEN: bad {k}"))?;
sampling.top_k = if n <= 0 { 0 } else { n as usize };
}
"min_p" => {
sampling.min_p = parse_finite_f32(v, k)?.clamp(0.0, 1.0);
}
"penalty_repeat" | "repetition_penalty" => {
sampling.penalty_repeat = parse_finite_f32(v, k)?;
}
"penalty_freq" | "frequency_penalty" => {
sampling.penalty_freq = parse_finite_f32(v, k)?;
}
"penalty_present" | "presence_penalty" => {
sampling.penalty_present = parse_finite_f32(v, k)?;
}
"penalty_last_n" => {
let n: i64 = v.parse().map_err(|_| format!("GEN: bad {k}"))?;
sampling.penalty_last_n = n.max(0) as usize;
}
"draft_top_k" => {
let n: usize = v.parse().map_err(|_| format!("GEN: bad {k}"))?;
draft_top_k = Some(n.min(16));
}
"image" => {
images.push(v.to_string());
}
_ => return Err(format!("GEN: unknown key '{k}'")),
}
}
let ids = parse_id_csv(toks[toks.len() - 1], vocab_size)?;
Ok(ServeCommand::Gen(ParsedGen {
max_new: max_new as usize,
sampling,
spec_mode,
draft_top_k,
domain_hint,
images,
ids,
}))
}
fn parse_finite_f32(v: &str, key: &str) -> Result<f32, String> {
let f: f32 = v.parse().map_err(|_| format!("GEN: bad numeric value for {key}"))?;
if !f.is_finite() {
return Err(format!("GEN: non-finite value for {key}"));
}
Ok(f)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gen_zero_prewarm_and_strict_validation() {
let cmd = parse_serve_line("GEN 0 domain=lean4 1,2,3", 100).unwrap();
match cmd {
ServeCommand::Gen(g) => {
assert_eq!(g.max_new, 0);
assert_eq!(g.domain_hint.as_deref(), Some("lean4"));
assert_eq!(g.ids, vec![1, 2, 3]);
}
_ => panic!("expected Gen"),
}
assert!(parse_serve_line("GEN 16 1,100", 100).is_err());
assert!(parse_serve_line("GEN 16 temperature=nan 1,2", 100).is_err());
assert!(parse_serve_line("GEN 16 unknown=1 1,2", 100).is_err());
}
#[test]
fn strata_ctl_exact_lines_parse() {
// Verbatim shapes emitted by strata-ctl `Sampling::keys` + `gen_line`.
let cmd = parse_serve_line("GEN 512 temperature=0.8 image=%2Fmnt%2Fpic.png 1,2,300", 1000).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.max_new, 512);
assert_eq!(g.sampling.temperature, 0.8);
assert_eq!(g.images, vec!["%2Fmnt%2Fpic.png"]);
assert_eq!(g.ids, vec![1, 2, 300]);
// top_k=0 maps to 64 on the consumer side; penalties drag the window.
let cmd = parse_serve_line("GEN 128 top_k=64 penalty_repeat=1.1 penalty_last_n=64 seed=42 7,8", 1000).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.sampling.top_k, 64);
assert_eq!(g.sampling.penalty_repeat, 1.1);
assert_eq!(g.sampling.penalty_last_n, 64);
assert_eq!(g.sampling.seed, 42);
// Multiple images keep prompt order.
let cmd = parse_serve_line("GEN 16 image=a.png image=b.png 1", 100).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.images, vec!["a.png", "b.png"]);
}
#[test]
fn lifecycle_commands() {
assert_eq!(parse_serve_line("STOP", 10).unwrap(), ServeCommand::Stop);
assert_eq!(parse_serve_line("QUIT", 10).unwrap(), ServeCommand::Quit);
assert_eq!(parse_serve_line("RESET", 10).unwrap(), ServeCommand::Reset);
}
}
+44
View File
@@ -0,0 +1,44 @@
//! Core pluggable traits and shared domain types: WeightStore quantization formats,
//! Speculative Drafting (local or Lyra LAN), and Prefetching.
/// `(layer, expert)` identity of one MoE expert (shared by cc, tm, sp).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExpertKey {
pub layer: u16,
pub expert: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantFormat {
Bf16,
Fp32,
Q8G64T16,
Q4G64T16,
NvFp4,
MxFp8,
}
#[derive(Debug, Clone)]
pub struct DraftProposal {
pub tokens: Vec<i32>,
/// Optional scalar draft probabilities `q(x_j)` for lossless non-greedy Leviathan verification.
pub draft_probs: Option<Vec<f32>>,
}
/// Pluggable speculative drafter:
/// - Local MTP (1-layer) / Block-Diffusion preview
/// - Remote LAN drafter on **Lyra** (`~128 B/step`, `~0.3 ms` RTT on 2.5 Gbps Ethernet)
pub trait DraftProvider: Send {
fn name(&self) -> &'static str;
fn propose(&mut self, prefix_tail: &[i32], max_k: usize) -> Result<DraftProposal, String>;
fn notify_accepted(&mut self, accepted_tokens: &[i32]) -> Result<(), String>;
fn reset(&mut self);
}
/// Pluggable MoE prefetch advisor:
/// - Local router lookahead (`h_{L-1} -> W_router[L]`)
/// - Remote domain classifier on **Lyra** (`Dante/letteratura` vs `Lean 4/matematica` -> NVMe pre-warm)
pub trait PrefetchAdvisor: Send {
fn on_prompt_domain(&mut self, domain_tag: &str) -> Vec<ExpertKey>;
fn on_layer_routed(&mut self, layer: u16, active_experts: &[u16]) -> Vec<ExpertKey>;
}
+53
View File
@@ -0,0 +1,53 @@
//! `.vplan` micro-bytecode opcodes (docs/ARCHITECTURE.md §4).
//!
//! Flat, fixed, non-Turing-complete: each compute opcode maps 1:1 to a HIP
//! microkernel in `kernels/hip/vetta_kernels.h`. Control flow is limited to
//! `LoopLayer` / `BranchB` so `memory.vplan` arena safety stays decidable
//! in Lean 4. Operands are resolved at boot into `CompiledPlan` (rt), never
//! looked up per token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VplanOp {
// Compute opcodes (1:1 with the <15 microkernel set)
EmbedBf16,
RmsNorm,
QuantizeXG64,
GemmQ8G64T16,
GemmQ4G64T16,
GemmNvfp4Mxfp8,
RopeKvWrite,
FlashGqaWmma,
GdnChunkwiseWy,
GdnRecurrentStep,
MoeRouteBucket,
MoeW13Wmma,
MoeW2Wmma,
MoeReduce,
VitFlashAttnWmma,
GpuPenaltiesTopk,
// Restricted control flow
/// Repeat the enclosed layer body for each model layer.
LoopLayer,
/// Batch-size dispatch (e.g. prefill `B >= 16` vs Split-KV decode `B <= 2`).
BranchB,
}
impl VplanOp {
/// True for the two restricted control-flow opcodes.
pub fn is_control(self) -> bool {
matches!(self, Self::LoopLayer | Self::BranchB)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn control_vs_compute() {
assert!(VplanOp::LoopLayer.is_control());
assert!(VplanOp::BranchB.is_control());
assert!(!VplanOp::GemmQ8G64T16.is_control());
assert!(!VplanOp::GdnChunkwiseWy.is_control());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! `VTC1` write-once NVMe cache format — pure metadata contracts shared by
//! `ld` (atomic writer) and `cc` (`O_RDONLY` reader).
//!
//! Eliminates audit-05 F-05 (pre-reserve OOM on corrupt count) by construction:
//! the record count is validated against the blob size BEFORE any allocation.
pub const CACHE_MAGIC: [u8; 8] = *b"VTCACHE1";
pub const CACHE_VERSION: u32 = 1;
pub const CACHE_ALIGN: u64 = 4096;
pub const HEADER_SIZE: usize = 48;
pub const MIN_REC_BYTES: usize = 1 + 4 * 4 + 4 * 8 + 4; // 53 B minimum per serialized record
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheRecord {
pub kind: u8,
pub i0: i32,
pub i1: i32,
pub i2: i32,
pub flags: u32,
pub u0: u64,
pub u1: u64,
pub data_offset: u64,
pub data_bytes: u64,
pub name: String,
}
pub fn fnv1a_u64(bytes: &[u8], seed: u64) -> u64 {
let mut h = seed;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01B3);
}
h
}
pub fn align_up(v: u64, align: u64) -> Result<u64, String> {
let rem = v % align;
if rem == 0 {
Ok(v)
} else {
v.checked_add(align - rem).ok_or_else(|| "align_up overflow".into())
}
}
pub fn serialize_meta(recs: &[CacheRecord]) -> Vec<u8> {
let mut out = Vec::new();
for r in recs {
out.push(r.kind);
out.extend_from_slice(&r.i0.to_le_bytes());
out.extend_from_slice(&r.i1.to_le_bytes());
out.extend_from_slice(&r.i2.to_le_bytes());
out.extend_from_slice(&r.flags.to_le_bytes());
out.extend_from_slice(&r.u0.to_le_bytes());
out.extend_from_slice(&r.u1.to_le_bytes());
out.extend_from_slice(&r.data_offset.to_le_bytes());
out.extend_from_slice(&r.data_bytes.to_le_bytes());
let nlen = r.name.len() as u32;
out.extend_from_slice(&nlen.to_le_bytes());
out.extend_from_slice(r.name.as_bytes());
}
out
}
pub fn deserialize_meta(blob: &[u8], count: u32) -> Result<Vec<CacheRecord>, String> {
// Anti-OOM check BEFORE `Vec::with_capacity(count)` (audit-05 F-05)
if (count as usize) > blob.len() / MIN_REC_BYTES {
return Err(format!(
"corrupt cache metadata: count={count} exceeds blob capacity ({} B)",
blob.len()
));
}
let mut out = Vec::with_capacity(count as usize);
let mut pos = 0usize;
let take = |pos: &mut usize, n: usize| -> Result<&[u8], String> {
if n > blob.len().saturating_sub(*pos) {
return Err("truncated cache metadata".into());
}
let s = &blob[*pos..*pos + n];
*pos += n;
Ok(s)
};
for _ in 0..count {
let kind = take(&mut pos, 1)?[0];
let i0 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i1 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i2 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let flags = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let u0 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let u1 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_offset = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_bytes = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let nlen = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap()) as usize;
if nlen > 4096 {
return Err("cache record name too long".into());
}
let nbytes = take(&mut pos, nlen)?;
let name = std::str::from_utf8(nbytes)
.map_err(|_| "non-UTF-8 cache record name")?
.to_string();
out.push(CacheRecord {
kind,
i0,
i1,
i2,
flags,
u0,
u1,
data_offset,
data_bytes,
name,
});
}
if pos != blob.len() {
return Err("trailing bytes in cache metadata".into());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn anti_oom_before_reserve() {
// Absurd entry count rejected BEFORE Vec::with_capacity
assert!(deserialize_meta(&[0u8; 64], u32::MAX).is_err());
}
#[test]
fn meta_roundtrip_and_alignment() {
let rec = CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 4096,
data_bytes: 8192,
name: "layer.0.q8".into(),
};
let blob = serialize_meta(&[rec.clone()]);
let back = deserialize_meta(&blob, 1).unwrap();
assert_eq!(back, vec![rec]);
assert_eq!(align_up(4097, CACHE_ALIGN).unwrap(), 8192);
assert_eq!(align_up(4096, CACHE_ALIGN).unwrap(), 4096);
assert!(align_up(u64::MAX, CACHE_ALIGN).is_err());
}
}