[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

+1
View File
@@ -6,3 +6,4 @@
*.tmp *.tmp
*.tmp.* *.tmp.*
.DS_Store .DS_Store
.idea/
+11 -4
View File
@@ -5,7 +5,8 @@ Rules and engineering standards for working on `vetta-infer`.
## Architecture & Scope ## Architecture & Scope
- **MoE-first microkernel engine** in Rust (edition 2024) with minimal AMD ROCm HIP kernels (`gfx1150` / RDNA 3.5 primary target; UMA `96 GiB` + dual NVMe). - **MoE-first microkernel engine** in Rust (edition 2024) with minimal AMD ROCm HIP kernels (`gfx1150` / RDNA 3.5 primary target; UMA `96 GiB` + dual NVMe).
- **Clear boundary:** all control flow, parsing, caching, scheduling, speculative verification, protocol handling, and telemetry stay in safe, CPU-testable Rust crates. `unsafe` is isolated to `vetta-hip` (FFI/DMA fence wrappers) and `vetta-io` (`io_uring` / `pread` syscalls). - **Authoritative design:** `docs/ARCHITECTURE.md` (approved 2026-11-29) — pure microkernel `vetta-infer-kn` + services (`abi/kn/ld/cc/rt/lab/sp/nt/tm/gw`), dual-step loader → `.vbundle/`, `.vplan` → `CompiledPlan` at boot. The crate realignment completed 2026-11-30 (M0 crates dissolved into `vetta-infer-*`); behavior is ported from the measured strata engines (`../strata*` worktrees), never re-invented from summaries.
- **Clear boundary:** all control flow, parsing, caching, scheduling, speculative verification, protocol handling, and telemetry stay in safe, CPU-testable Rust crates. `unsafe` is isolated to `rt` (HIP FFI/DMA fence wrappers) and `cc` (`io_uring` / `pread` syscalls).
- **No silent regressions or unmeasured claims:** every performance or quality claim must carry real measurements and the exact hardware/model/flags used. - **No silent regressions or unmeasured claims:** every performance or quality claim must carry real measurements and the exact hardware/model/flags used.
## Hard Invariants (Eliminate Past Audit Classes By Construction) ## Hard Invariants (Eliminate Past Audit Classes By Construction)
@@ -15,10 +16,16 @@ Rules and engineering standards for working on `vetta-infer`.
3. **Write-Once / `O_RDONLY` NVMe Caches:** caches are written atomically via `.tmp.<pid>` + `fsync` + `rename` only on miss, and opened strictly `O_RDONLY` on every reload (0 SSD writes). 3. **Write-Once / `O_RDONLY` NVMe Caches:** caches are written atomically via `.tmp.<pid>` + `fsync` + `rename` only on miss, and opened strictly `O_RDONLY` on every reload (0 SSD writes).
4. **Typestate Prefix / MTP / Checkpoint Validity:** never rely on loose integer pairs (`prefix_len`, `mtp_prefix_len`) to infer device buffer initialization. Represent state via explicit enums (`PrefixState`), and commit pool metadata only after GPU allocations/copies succeed. 4. **Typestate Prefix / MTP / Checkpoint Validity:** never rely on loose integer pairs (`prefix_len`, `mtp_prefix_len`) to infer device buffer initialization. Represent state via explicit enums (`PrefixState`), and commit pool metadata only after GPU allocations/copies succeed.
5. **Zero-Allocation Hot-Path Sampling & Explicit Non-Finite Tracking:** no per-token `O(V)` heap allocations, no silent `256`-cap truncation when `top_k == 0` with `top_p`/`min_p`, centralized `mask_token_id` suppression, and explicit reporting of non-finite logits. 5. **Zero-Allocation Hot-Path Sampling & Explicit Non-Finite Tracking:** no per-token `O(V)` heap allocations, no silent `256`-cap truncation when `top_k == 0` with `top_p`/`min_p`, centralized `mask_token_id` suppression, and explicit reporting of non-finite logits.
6. **Formal Verification with Lean 4:** model non-trivial state machines, ring buffers, checkpoint pools, and speculative/rollback invariants in `proofs/*.lean` (`0 sorryAx`, verified with `lean`) before writing the implementation. 6. **Formal Verification with Lean 4 (Federico's rule):** simple correctness logic is written directly with ordinary CPU tests; complex logic (non-trivial state machines, ring buffers, checkpoint pools, speculative/rollback invariants, memory-arena plans) is modeled in `proofs/*.lean` and verified by the Lean kernel (`0 sorryAx`, standard axioms only) **before** writing the implementation.
## Tandem & Review Workflow
- **Principal consumer:** `strata-ctl` (`../strata-ctl`), developed by a peer coder in tandem. The living wire contract is `strata-ctl/src/engine/protocol.rs` + `supervisor.rs`; engine-side guarantees and known deltas are tracked in `docs/ARCHITECTURE.md` §6.
- **Mutual reviews:** each coder periodically reviews the other's work; an external reviewer audits both. Wire-protocol changes land in coordinated review cycles across the two repos — never unilaterally.
- **Parity discipline:** every policy/kernel ported from strata ships a parity test against the measured reference behavior (e.g. Adaptive-K must match `clover_policy.h`, not a simplified sketch).
## Verification Commands ## Verification Commands
- Proofs: `lean proofs/slab_ring_dma.lean` - Proofs: `lean proofs/slab_ring_dma.lean`, `lean proofs/bus_lifecycle.lean`, `lean proofs/serve_session.lean`
- CPU workspace tests: `cargo test --workspace` - CPU workspace tests: `cargo test --workspace`
- Commit prefixes: `[Core]`, `[IO]`, `[HIP]`, `[Proto]`, `[Telemetry]`, `[Proofs]`, `[Docs]` - Commit prefixes: `[ABI]`, `[KN]`, `[LD]`, `[CC]`, `[RT]`, `[LAB]`, `[SP]`, `[NT]`, `[TM]`, `[GW]`, `[Proofs]`, `[Docs]`
Generated
+40 -20
View File
@@ -3,44 +3,64 @@
version = 4 version = 4
[[package]] [[package]]
name = "vetta-cli" name = "vetta-infer-abi"
version = "0.1.0"
dependencies = [
"vetta-core",
"vetta-hip",
"vetta-io",
"vetta-proto",
"vetta-telemetry",
]
[[package]]
name = "vetta-core"
version = "0.1.0" version = "0.1.0"
[[package]] [[package]]
name = "vetta-hip" name = "vetta-infer-cc"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"vetta-core", "vetta-infer-abi",
"vetta-infer-ld",
] ]
[[package]] [[package]]
name = "vetta-io" name = "vetta-infer-gw"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"vetta-core", "vetta-infer-abi",
"vetta-infer-ld",
] ]
[[package]] [[package]]
name = "vetta-proto" name = "vetta-infer-kn"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"vetta-core", "vetta-infer-abi",
] ]
[[package]] [[package]]
name = "vetta-telemetry" name = "vetta-infer-lab"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"vetta-core", "vetta-infer-rt",
]
[[package]]
name = "vetta-infer-ld"
version = "0.1.0"
dependencies = [
"vetta-infer-abi",
]
[[package]]
name = "vetta-infer-nt"
version = "0.1.0"
[[package]]
name = "vetta-infer-rt"
version = "0.1.0"
dependencies = [
"vetta-infer-abi",
]
[[package]]
name = "vetta-infer-sp"
version = "0.1.0"
[[package]]
name = "vetta-infer-tm"
version = "0.1.0"
dependencies = [
"vetta-infer-abi",
] ]
+10 -6
View File
@@ -1,12 +1,16 @@
[workspace] [workspace]
resolver = "3" resolver = "3"
members = [ members = [
"crates/vetta-core", "crates/vetta-infer-abi",
"crates/vetta-io", "crates/vetta-infer-kn",
"crates/vetta-proto", "crates/vetta-infer-ld",
"crates/vetta-telemetry", "crates/vetta-infer-cc",
"crates/vetta-hip", "crates/vetta-infer-rt",
"crates/vetta-cli", "crates/vetta-infer-lab",
"crates/vetta-infer-sp",
"crates/vetta-infer-nt",
"crates/vetta-infer-tm",
"crates/vetta-infer-gw",
] ]
[workspace.package] [workspace.package]
+13 -8
View File
@@ -18,19 +18,24 @@ Built from the measured hardware physics and engineering lessons of our hardened
| Path | Responsibility | | Path | Responsibility |
| --- | --- | | --- | --- |
| `crates/vetta-core` | Domain types, `WeightStore` / `DraftProvider` / `PrefetchAdvisor` traits, `SlabRing` DMA state machine, `PrefixState` typestate, zero-alloc sampler & Leviathan verifier, Hot/Cold MoE cache policy | | `crates/vetta-infer-abi` | Shared contracts: domain types, bus messages, `.vplan` opcodes, wire parsing, checked JSON/VTC1 parsers, zero-alloc sampler & Leviathan verifier, `DraftProvider`/`PrefetchAdvisor` traits (zero deps) |
| `crates/vetta-io` | Overflow-safe `.safetensors` reader (`index.json`, `pread`, strict bounds) and unified write-once `O_RDONLY` NVMe disk cache | | `crates/vetta-infer-kn` | Pure microkernel: control bus, service registry & lifecycle (Lean-verified), UMA/DMA broker (`SlabRing` + `UmaSlabPool`) |
| `crates/vetta-proto` | Wire protocol (`--serve`, compatible with `strata-ctl`: `INFO/READY/GEN/RESUME/PP/T/DONE/ERR/STOP/QUIT`, `GEN 0` pre-warm) + Lyra RPC message schemas | | `crates/vetta-infer-ld` | Loader & compiler: checked `.safetensors` reader, write-once `VTC1` atomic writer; dual-step → `.vbundle/` (M1) |
| `crates/vetta-telemetry` | Lock-free inference telemetry collector (MoE routing histograms, `L -> L+1` transition matrix, speculative stats, JSONL sink) | | `crates/vetta-infer-cc` | Cache & storage: Hot/Cold MoE expert policy, `O_RDONLY` cache reload; `io_uring O_DIRECT` streaming (M2) |
| `crates/vetta-hip` | Thin HIP FFI + `PinnedUmaBuf` fence-guarded ownership + CPU mock backend for headless unit tests | | `crates/vetta-infer-rt` | Operational runtime: `PrefixState` typestate + hybrid checkpoint pool; `CompiledPlan` executor + HIP FFI (M1) |
| `crates/vetta-cli` | `vetta-infer` CLI binary (`info`, `serve`, `bench`, `stats`) | | `crates/vetta-infer-lab` | Laboratory runtime: same executor core as `rt` + `probe.vplan` hooks |
| `crates/vetta-infer-sp` | Speculative coordinator: faithful throughput-aware Adaptive-K (port of `clover_policy.h`) |
| `crates/vetta-infer-nt` | Lyra LAN bridge: `LyraRpc` (remote drafting, domain hints) |
| `crates/vetta-infer-tm` | Telemetry: lock-free routing/Zipf/domain/spec stats, async JSONL sink |
| `crates/vetta-infer-gw` | Gateway & CLI: `strata-ctl`-compatible wire emitters, `vetta-infer` binary (`info`, `version`; `serve`/`bench`/`stats` with M1) |
| `kernels/hip` | Minimal reusable RDNA 3.5 HIP microkernels (`Q8_G64_T16`, `Q4_G64_T16` SWAR, Chunkwise GDN, FlashAttn/GQA, MoE route/WMMA, GPU top-64 sampling) | | `kernels/hip` | Minimal reusable RDNA 3.5 HIP microkernels (`Q8_G64_T16`, `Q4_G64_T16` SWAR, Chunkwise GDN, FlashAttn/GQA, MoE route/WMMA, GPU top-64 sampling) |
| `proofs/` | Lean 4 formal contracts (`0 sorryAx`, audited axioms) | | `proofs/` | Lean 4 formal contracts (`0 sorryAx`, audited axioms) |
## Milestones ## Milestones
- **M0 (Foundation — current):** Workspace, Lean 4 contracts (`slab_ring_dma.lean`), `vetta-core`, `vetta-io`, `vetta-proto`, `vetta-telemetry`, HIP ABI skeleton, full CPU test suite. - **M0 (Foundation — done):** Workspace skeleton, Lean contracts (`slab_ring_dma.lean`), checked IO, serve parsing, telemetry, HIP ABI, full CPU test suite.
- **M1 (Resident MoE End-to-End — Target 1: `Inkling-2-Mini`):** `vetta-hip` RDNA 3.5 microkernels, NVFP4/MXFP8 + `Q8_G64_T16` trunk, Vision WMMA, write-once NVMe cache, `strata-ctl` drop-in `--serve` parity & speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload). - **M0.5 (Architecture realignment — done):** approved microkernel design fixed in `docs/ARCHITECTURE.md`; crates realigned to `vetta-infer-*` (abi/kn/ld/cc/rt/lab/sp/nt/tm/gw); bus lifecycle Lean-verified (`bus_lifecycle.lean`); faithful Adaptive-K port; `strata-ctl` wire emitters + `image=` key.
- **M1 (Resident MoE End-to-End — Target 1: `Inkling-2-Mini`):** `rt` HIP RDNA 3.5 microkernels, NVFP4/MXFP8 + `Q8_G64_T16` trunk, Vision WMMA, write-once `.vbundle`, `strata-ctl` drop-in `--serve` parity & speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload).
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch. - **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming. - **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "vetta-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "vetta-infer"
path = "src/main.rs"
[dependencies]
vetta-core = { path = "../vetta-core" }
vetta-io = { path = "../vetta-io" }
vetta-proto = { path = "../vetta-proto" }
vetta-telemetry = { path = "../vetta-telemetry" }
vetta-hip = { path = "../vetta-hip" }
-9
View File
@@ -1,9 +0,0 @@
//! `vetta-core`: pure-Rust domain types, state machines, sampling, MoE cache policies, and traits.
//!
//! Zero external dependencies; 100% testable on CPU without a GPU.
pub mod moe;
pub mod prefix;
pub mod sampler;
pub mod slab;
pub mod traits;
-155
View File
@@ -1,155 +0,0 @@
//! Hot/Cold MoE expert cache policy for UMA + NVMe zero-copy DMA streaming.
//!
//! Tracks LFU/LRU expert residency in UMA memory and accepts domain pre-warm hints
//! from local telemetry or a remote control-plane router (Lyra).
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExpertKey {
pub layer: u16,
pub expert: u16,
}
#[derive(Debug, Clone, Copy)]
struct ResidentMeta {
slot: usize,
hits: u64,
last_tick: u64,
pinned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheLookup {
Hit { slot: usize },
Miss,
}
/// Manages a fixed pool of UMA resident expert slots (`capacity` experts).
#[derive(Debug, Clone)]
pub struct HotColdExpertCache {
capacity: usize,
tick: u64,
map: HashMap<ExpertKey, ResidentMeta>,
free_slots: Vec<usize>,
pub total_hits: u64,
pub total_misses: u64,
}
impl HotColdExpertCache {
pub fn new(capacity: usize) -> Self {
let cap = capacity.max(1);
let free_slots = (0..cap).rev().collect();
Self {
capacity: cap,
tick: 0,
map: HashMap::with_capacity(cap),
free_slots,
total_hits: 0,
total_misses: 0,
}
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn resident_count(&self) -> usize {
self.map.len()
}
pub fn hit_rate(&self) -> f64 {
let tot = self.total_hits + self.total_misses;
if tot == 0 { 0.0 } else { self.total_hits as f64 / tot as f64 }
}
pub fn lookup(&mut self, key: ExpertKey) -> CacheLookup {
self.tick += 1;
if let Some(m) = self.map.get_mut(&key) {
m.hits += 1;
m.last_tick = self.tick;
self.total_hits += 1;
CacheLookup::Hit { slot: m.slot }
} else {
self.total_misses += 1;
CacheLookup::Miss
}
}
/// Picks a target slot to load `key` into (free slot or LFU+LRU unpinned victim).
/// Does not mutate residency until `commit_load` succeeds.
pub fn plan_load(&self, key: ExpertKey) -> Option<(usize, Option<ExpertKey>)> {
if let Some(m) = self.map.get(&key) {
return Some((m.slot, None));
}
if let Some(&slot) = self.free_slots.last() {
return Some((slot, None));
}
// Evict lowest-hit, oldest unpinned resident expert.
self.map
.iter()
.filter(|(_, m)| !m.pinned)
.min_by_key(|(_, m)| (m.hits, m.last_tick))
.map(|(&k, m)| (m.slot, Some(k)))
}
pub fn commit_load(&mut self, key: ExpertKey, slot: usize, evicted: Option<ExpertKey>, pinned: bool) {
self.tick += 1;
if let Some(ev) = evicted {
self.map.remove(&ev);
} else if let Some(pos) = self.free_slots.iter().position(|&s| s == slot) {
self.free_slots.swap_remove(pos);
}
self.map.insert(
key,
ResidentMeta {
slot,
hits: 1,
last_tick: self.tick,
pinned,
},
);
}
/// Returns the subset of domain-recommended experts not currently resident (candidates for NVMe pre-warm).
pub fn missing_for_prewarm(&self, recommended: &[ExpertKey]) -> Vec<ExpertKey> {
recommended
.iter()
.copied()
.filter(|k| !self.map.contains_key(k))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lfu_lru_eviction_and_domain_prewarm() {
let mut c = HotColdExpertCache::new(2);
let k0 = ExpertKey { layer: 0, expert: 1 };
let k1 = ExpertKey { layer: 0, expert: 2 };
let k2 = ExpertKey { layer: 0, expert: 3 };
assert_eq!(c.lookup(k0), CacheLookup::Miss);
let (s0, ev0) = c.plan_load(k0).unwrap();
assert!(ev0.is_none());
c.commit_load(k0, s0, ev0, false);
// Make k0 hot
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
let (s1, ev1) = c.plan_load(k1).unwrap();
c.commit_load(k1, s1, ev1, false);
// k2 should evict cold k1, keeping hot k0
let (s2, ev2) = c.plan_load(k2).unwrap();
assert_eq!(ev2, Some(k1));
assert_eq!(s2, s1);
c.commit_load(k2, s2, ev2, false);
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.missing_for_prewarm(&[k0, k1, k2]), vec![k1]);
}
}
-105
View File
@@ -1,105 +0,0 @@
//! Core pluggable traits for WeightStore, Speculative Drafting (local or Lyra LAN), and Prefetching.
use crate::moe::ExpertKey;
#[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>;
}
/// Throughput-aware Adaptive-K speculative controller (prevents K=16 prose traps).
#[derive(Debug, Clone)]
pub struct AdaptiveKController {
k_max: usize,
cur_k: usize,
ema_ms_per_tok: [f64; 5], // index: 0->K=1, 1->K=4, 2->K=8, 3->K=12, 4->K=16
full_k8_streak: u32,
}
impl AdaptiveKController {
pub fn new(k_max: usize) -> Self {
let km = k_max.max(1);
Self {
k_max: km,
cur_k: km.min(8),
ema_ms_per_tok: [0.0; 5],
full_k8_streak: 0,
}
}
pub fn next_k(&self, rem_tokens: usize, ctx_room: usize) -> usize {
self.cur_k.min(self.k_max).min(rem_tokens.max(1)).min(ctx_room.max(1))
}
fn bucket(k: usize) -> usize {
match k {
0..=1 => 0,
2..=4 => 1,
5..=8 => 2,
9..=12 => 3,
_ => 4,
}
}
pub fn observe(&mut self, k_used: usize, accepted: usize, step_ms: f64) {
let mpt = step_ms / (accepted.max(1) as f64);
let b = Self::bucket(k_used);
self.ema_ms_per_tok[b] = if self.ema_ms_per_tok[b] == 0.0 {
mpt
} else {
0.7 * self.ema_ms_per_tok[b] + 0.3 * mpt
};
if k_used >= 8 && accepted >= k_used {
self.full_k8_streak += 1;
} else {
self.full_k8_streak = 0;
}
if accepted <= 2 && self.cur_k > 4 {
self.cur_k = 4;
} else if self.full_k8_streak >= 2 && self.k_max >= 16 {
// Only promote to K=16 if K=16 isn't demonstrably slower per token than K=8
if self.ema_ms_per_tok[4] == 0.0
|| self.ema_ms_per_tok[2] == 0.0
|| self.ema_ms_per_tok[4] <= self.ema_ms_per_tok[2] * 1.02
{
self.cur_k = 16;
}
} else if accepted >= 4 && self.cur_k < 8 && self.k_max >= 8 {
self.cur_k = 8;
} else if k_used >= 16 && accepted < 10 {
self.cur_k = 8;
}
}
}
+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;
@@ -2,6 +2,7 @@
//! //!
//! Eliminates F-07 (centralized `mask_token_id` suppression) and F-09 (no 1 MiB/token heap churn, //! 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). //! 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::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap}; use std::collections::{BinaryHeap, HashMap};
@@ -470,4 +471,4 @@ mod tests {
assert_eq!(rep.nonfinite_logits, 1); assert_eq!(rep.nonfinite_logits, 1);
assert_eq!(rep.token, 3); // token 2 was suppressed assert_eq!(rep.token, 3); // token 2 was suppressed
} }
} }
@@ -1,7 +1,13 @@
//! `vetta-proto`: unified `--serve` wire protocol (`strata-ctl` compatible, including `GEN 0` pre-warm) //! `--serve` wire protocol parsing — `strata-ctl` compatible (docs/ARCHITECTURE.md §6).
//! and lightweight Lyra LAN control-plane message schemas. //!
//! 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 vetta_core::sampler::SamplingOpts; use crate::sampler::SamplingOpts;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum ServeCommand { pub enum ServeCommand {
@@ -19,6 +25,8 @@ pub struct ParsedGen {
pub spec_mode: Option<usize>, pub spec_mode: Option<usize>,
pub draft_top_k: Option<usize>, pub draft_top_k: Option<usize>,
pub domain_hint: Option<String>, pub domain_hint: Option<String>,
/// `image=<encoded path>` keys in prompt order (strata-ctl Vision).
pub images: Vec<String>,
pub ids: Vec<i32>, pub ids: Vec<i32>,
} }
@@ -63,6 +71,7 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
let mut spec_mode = None; let mut spec_mode = None;
let mut draft_top_k = None; let mut draft_top_k = None;
let mut domain_hint = None; let mut domain_hint = None;
let mut images = Vec::new();
for &kv in &toks[2..toks.len() - 1] { for &kv in &toks[2..toks.len() - 1] {
let (k, v) = kv let (k, v) = kv
@@ -122,6 +131,9 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
let n: usize = v.parse().map_err(|_| format!("GEN: bad {k}"))?; let n: usize = v.parse().map_err(|_| format!("GEN: bad {k}"))?;
draft_top_k = Some(n.min(16)); draft_top_k = Some(n.min(16));
} }
"image" => {
images.push(v.to_string());
}
_ => return Err(format!("GEN: unknown key '{k}'")), _ => return Err(format!("GEN: unknown key '{k}'")),
} }
} }
@@ -133,6 +145,7 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
spec_mode, spec_mode,
draft_top_k, draft_top_k,
domain_hint, domain_hint,
images,
ids, ids,
})) }))
} }
@@ -145,14 +158,6 @@ fn parse_finite_f32(v: &str, key: &str) -> Result<f32, String> {
Ok(f) Ok(f)
} }
/// Compact LAN RPC messages for Sogliola <-> Lyra (`< 1 KB/step` on 2.5 Gbps Ethernet).
#[derive(Debug, Clone, PartialEq)]
pub enum LyraRpc {
DraftRequest { session_id: u64, accepted_tail: Vec<i32>, max_k: u8 },
DraftResponse { session_id: u64, proposed: Vec<i32>, probs: Vec<f32> },
DomainHint { session_id: u64, domain: String, confidence: f32 },
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -172,4 +177,35 @@ mod tests {
assert!(parse_serve_line("GEN 16 temperature=nan 1,2", 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()); 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());
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "vetta-infer-cc"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
[dev-dependencies]
vetta-infer-ld = { path = "../vetta-infer-ld" }
+272
View File
@@ -0,0 +1,272 @@
//! `vetta-infer-cc`: cache & storage (docs/ARCHITECTURE.md §2, §9).
//!
//! Hot/Cold MoE expert residency policy (LFU/LRU + domain pre-warm) and the
//! strictly `O_RDONLY` `VTC1` cache reader (0 SSD writes on every reload).
//! NVMe `io_uring O_DIRECT` zero-copy streaming into the `kn` SlabRing lands
//! with M2 (the only `unsafe` syscall surface of the engine).
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::Path;
use vetta_infer_abi::vtc1::{
deserialize_meta, CacheRecord, CACHE_MAGIC, CACHE_VERSION, HEADER_SIZE,
};
use vetta_infer_abi::ExpertKey;
// ============================================================================
// 1. Hot/Cold MoE Expert Cache Policy
// ============================================================================
#[derive(Debug, Clone, Copy)]
struct ResidentMeta {
slot: usize,
hits: u64,
last_tick: u64,
pinned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheLookup {
Hit { slot: usize },
Miss,
}
/// Manages a fixed pool of UMA resident expert slots (`capacity` experts).
#[derive(Debug, Clone)]
pub struct HotColdExpertCache {
capacity: usize,
tick: u64,
map: HashMap<ExpertKey, ResidentMeta>,
free_slots: Vec<usize>,
pub total_hits: u64,
pub total_misses: u64,
}
impl HotColdExpertCache {
pub fn new(capacity: usize) -> Self {
let cap = capacity.max(1);
let free_slots = (0..cap).rev().collect();
Self {
capacity: cap,
tick: 0,
map: HashMap::with_capacity(cap),
free_slots,
total_hits: 0,
total_misses: 0,
}
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn resident_count(&self) -> usize {
self.map.len()
}
pub fn hit_rate(&self) -> f64 {
let tot = self.total_hits + self.total_misses;
if tot == 0 { 0.0 } else { self.total_hits as f64 / tot as f64 }
}
pub fn lookup(&mut self, key: ExpertKey) -> CacheLookup {
self.tick += 1;
if let Some(m) = self.map.get_mut(&key) {
m.hits += 1;
m.last_tick = self.tick;
self.total_hits += 1;
CacheLookup::Hit { slot: m.slot }
} else {
self.total_misses += 1;
CacheLookup::Miss
}
}
/// Picks a target slot to load `key` into (free slot or LFU+LRU unpinned victim).
/// Does not mutate residency until `commit_load` succeeds.
pub fn plan_load(&self, key: ExpertKey) -> Option<(usize, Option<ExpertKey>)> {
if let Some(m) = self.map.get(&key) {
return Some((m.slot, None));
}
if let Some(&slot) = self.free_slots.last() {
return Some((slot, None));
}
// Evict lowest-hit, oldest unpinned resident expert.
self.map
.iter()
.filter(|(_, m)| !m.pinned)
.min_by_key(|(_, m)| (m.hits, m.last_tick))
.map(|(&k, m)| (m.slot, Some(k)))
}
pub fn commit_load(&mut self, key: ExpertKey, slot: usize, evicted: Option<ExpertKey>, pinned: bool) {
self.tick += 1;
if let Some(ev) = evicted {
self.map.remove(&ev);
} else if let Some(pos) = self.free_slots.iter().position(|&s| s == slot) {
self.free_slots.swap_remove(pos);
}
self.map.insert(
key,
ResidentMeta {
slot,
hits: 1,
last_tick: self.tick,
pinned,
},
);
}
/// Returns the subset of domain-recommended experts not currently resident (candidates for NVMe pre-warm).
pub fn missing_for_prewarm(&self, recommended: &[ExpertKey]) -> Vec<ExpertKey> {
recommended
.iter()
.copied()
.filter(|k| !self.map.contains_key(k))
.collect()
}
}
// ============================================================================
// 2. Strictly `O_RDONLY` VTC1 Cache Reader (0 SSD writes on reload)
// ============================================================================
pub struct DiskCacheReader {
file: File,
pub file_size: u64,
pub records: Vec<CacheRecord>,
}
impl DiskCacheReader {
pub fn open_and_validate(path: impl AsRef<Path>, expected_fp: u64) -> Result<Self, String> {
let path = path.as_ref();
let file = OpenOptions::new()
.read(true)
.open(path)
.map_err(|e| format!("open cache {}: {e}", path.display()))?;
let file_size = file.metadata().map_err(|e| format!("stat cache: {e}"))?.len();
if file_size < HEADER_SIZE as u64 {
return Err("cache file too small".into());
}
let mut hdr = [0u8; HEADER_SIZE];
file.read_exact_at(&mut hdr, 0)
.map_err(|e| format!("read cache hdr: {e}"))?;
if hdr[0..8] != CACHE_MAGIC {
return Err("cache bad magic".into());
}
let version = u32::from_le_bytes(hdr[8..12].try_into().unwrap());
if version != CACHE_VERSION {
return Err(format!("cache version mismatch: {version}"));
}
let count = u32::from_le_bytes(hdr[12..16].try_into().unwrap());
let fp = u64::from_le_bytes(hdr[16..24].try_into().unwrap());
if fp != expected_fp {
return Err("cache fingerprint mismatch".into());
}
let meta_off = u64::from_le_bytes(hdr[24..32].try_into().unwrap());
let meta_bytes = u64::from_le_bytes(hdr[32..40].try_into().unwrap());
let total_bytes = u64::from_le_bytes(hdr[40..48].try_into().unwrap());
if total_bytes != file_size {
return Err("cache file size mismatch (incomplete)".into());
}
if meta_off < HEADER_SIZE as u64
|| meta_off > file_size
|| meta_bytes > file_size - meta_off
|| meta_bytes > 64 * 1024 * 1024
{
return Err("cache metadata out of bounds".into());
}
let mut mblob = vec![0u8; meta_bytes as usize];
file.read_exact_at(&mut mblob, meta_off)
.map_err(|e| format!("read cache meta: {e}"))?;
let records = deserialize_meta(&mblob, count)?;
for r in &records {
if r.data_offset > file_size || r.data_bytes > file_size - r.data_offset {
return Err(format!("cache record '{}' payload OOB", r.name));
}
}
Ok(Self { file, file_size, records })
}
pub fn read_slice(&self, off: u64, dst: &mut [u8]) -> Result<(), String> {
let len = dst.len() as u64;
if off > self.file_size || len > self.file_size - off {
return Err("cache read_slice OOB".into());
}
self.file
.read_exact_at(dst, off)
.map_err(|e| format!("cache pread: {e}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lfu_lru_eviction_and_domain_prewarm() {
let mut c = HotColdExpertCache::new(2);
let k0 = ExpertKey { layer: 0, expert: 1 };
let k1 = ExpertKey { layer: 0, expert: 2 };
let k2 = ExpertKey { layer: 0, expert: 3 };
assert_eq!(c.lookup(k0), CacheLookup::Miss);
let (s0, ev0) = c.plan_load(k0).unwrap();
assert!(ev0.is_none());
c.commit_load(k0, s0, ev0, false);
// Make k0 hot
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
let (s1, ev1) = c.plan_load(k1).unwrap();
c.commit_load(k1, s1, ev1, false);
// k2 should evict cold k1, keeping hot k0
let (s2, ev2) = c.plan_load(k2).unwrap();
assert_eq!(ev2, Some(k1));
assert_eq!(s2, s1);
c.commit_load(k2, s2, ev2, false);
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.missing_for_prewarm(&[k0, k1, k2]), vec![k1]);
}
#[test]
fn disk_cache_roundtrip_readonly_and_fingerprint() {
let p = std::env::temp_dir().join(format!("vetta_cc_cache_{}.bin", std::process::id()));
let _ = std::fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = vetta_infer_ld::DiskCacheWriter::begin(&p, fp).unwrap();
wr.write_record(
CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 0,
data_bytes: 0,
name: "layer.0.q8".into(),
},
&payload,
)
.unwrap();
wr.commit().unwrap();
let rd = DiskCacheReader::open_and_validate(&p, fp).unwrap();
assert_eq!(rd.records.len(), 1);
let mut got = vec![0u8; payload.len()];
rd.read_slice(rd.records[0].data_offset, &mut got).unwrap();
assert_eq!(got, payload);
assert!(DiskCacheReader::open_and_validate(&p, fp ^ 1).is_err());
assert!(rd.read_slice(u64::MAX, &mut got).is_err());
let _ = std::fs::remove_file(&p);
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vetta-infer-gw"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "vetta-infer"
path = "src/main.rs"
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
vetta-infer-ld = { path = "../vetta-infer-ld" }
+143
View File
@@ -0,0 +1,143 @@
//! `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;
/// 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"
);
}
}
@@ -1,9 +1,9 @@
//! `vetta-infer` CLI entrypoint. //! `vetta-infer` CLI entrypoint (gateway crate).
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::env; use std::env;
use std::process::ExitCode; use std::process::ExitCode;
use vetta_io::SafetensorsArchive; use vetta_infer_ld::SafetensorsArchive;
fn usage() { fn usage() {
eprintln!("vetta-infer {} — MoE-first microkernel inference engine (Rust + HIP)", env!("CARGO_PKG_VERSION")); eprintln!("vetta-infer {} — MoE-first microkernel inference engine (Rust + HIP)", env!("CARGO_PKG_VERSION"));
@@ -62,4 +62,4 @@ fn main() -> ExitCode {
ExitCode::from(2) ExitCode::from(2)
} }
} }
} }
+263
View File
@@ -0,0 +1,263 @@
//! `--serve` request lifecycle — implements `proofs/serve_session.lean`.
//!
//! The engine-side spine that talks to `strata-ctl` (docs/ARCHITECTURE.md §6):
//! GEN/STOP/QUIT, `GEN 0` pre-warm, and the STOP→DONE drain guarantee. Pure
//! state machine emitting wire lines via the `gw` emitters; the GPU backend
//! feeds it events, so the whole contract is CPU-testable without a device.
use vetta_infer_abi::serve::ParsedGen;
use crate::{done_line, err_line, pp_line, resume_line, token_line};
/// Mirrors `ReqState` in `proofs/serve_session.lean`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionState {
Idle,
Prefilling,
Decoding,
Stopping,
Done,
}
#[derive(Debug, Clone)]
pub struct ServeSession {
state: SessionState,
max_new: usize,
generated: u32,
prompt_tokens: u32,
reused: u32,
prompt_ms: f64,
decode_ms: f64,
finish: String,
}
impl Default for ServeSession {
fn default() -> Self {
Self::new()
}
}
impl ServeSession {
pub fn new() -> Self {
Self {
state: SessionState::Idle,
max_new: 0,
generated: 0,
prompt_tokens: 0,
reused: 0,
prompt_ms: 0.0,
decode_ms: 0.0,
finish: String::new(),
}
}
pub fn state(&self) -> SessionState {
self.state
}
pub fn generated(&self) -> u32 {
self.generated
}
fn done(&mut self, finish: &str, decode_ms: f64) -> Vec<String> {
self.decode_ms = decode_ms;
self.finish = finish.to_string();
self.state = SessionState::Done;
vec![done_line(
self.generated,
self.prompt_tokens,
self.prompt_ms,
self.decode_ms,
&self.finish,
&[],
)]
}
/// `ReqStep.gen`: Idle -> Prefilling. Wrong state is an explicit error.
pub fn on_gen(&mut self, g: &ParsedGen) -> Result<Vec<String>, String> {
if self.state != SessionState::Idle {
return Err(format!("GEN while {:?}", self.state));
}
self.max_new = g.max_new;
self.prompt_tokens = g.ids.len() as u32;
self.generated = 0;
self.reused = 0;
self.prompt_ms = 0.0;
self.decode_ms = 0.0;
self.finish.clear();
self.state = SessionState::Prefilling;
Ok(Vec::new()) // PP lines arrive per chunk via on_prefill_chunk
}
/// Prefill progress (Prefilling only): one `PP` line per chunk.
pub fn on_prefill_chunk(&mut self, read: u32, total: u32, ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Prefilling {
return Err(format!("PP while {:?}", self.state));
}
Ok(vec![pp_line(read, total, ms, None)])
}
/// `ReqStep.prefillComplete` (max_new > 0) or `ReqStep.prewarm` (max_new == 0).
pub fn on_prefill_complete(&mut self, reused: u32, prompt_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Prefilling {
return Err(format!("prefill-complete while {:?}", self.state));
}
self.reused = reused;
self.prompt_ms = prompt_ms;
let mut out = Vec::new();
if reused > 0 {
out.push(resume_line(reused));
}
if self.max_new == 0 {
// GEN 0 pre-warm: DONE immediately, never enters decode (Theorem 7).
out.extend(self.done("stop", 0.0));
} else {
self.state = SessionState::Decoding;
}
Ok(out)
}
/// Token emission is gated to Decoding (Theorem 9).
pub fn on_token(&mut self, id: u32) -> Result<Vec<String>, String> {
if self.state != SessionState::Decoding {
return Err(format!("T while {:?}", self.state));
}
self.generated += 1;
Ok(vec![token_line(id)])
}
/// `ReqStep.stopPrefill` / `stopDecode`. STOP in Idle/Done is a no-op
/// (Theorem 2); STOP while already Stopping is idempotent.
pub fn on_stop(&mut self) -> Vec<String> {
match self.state {
SessionState::Prefilling | SessionState::Decoding => {
self.state = SessionState::Stopping;
}
_ => {}
}
Vec::new()
}
/// `ReqStep.drain`: Stopping -> Done. The STOP guarantee (Theorem 4):
/// a drained request always ends in exactly one DONE, with no tokens.
pub fn on_drain_complete(&mut self, decode_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Stopping {
return Err(format!("drain while {:?}", self.state));
}
Ok(self.done("stop", decode_ms))
}
/// `ReqStep.finish`: Decoding -> Done (stop / length / nonfinite).
pub fn on_finish(&mut self, reason: &str, decode_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Decoding {
return Err(format!("finish while {:?}", self.state));
}
Ok(self.done(reason, decode_ms))
}
/// Failure: emit `ERR`, and a trailing `DONE` if a request was in flight
/// (the consumer swallows it — `swallow_trailing_done`).
pub fn on_error(&mut self, msg: &str) -> Vec<String> {
let mut out = vec![err_line(msg)];
if matches!(self.state, SessionState::Prefilling | SessionState::Decoding | SessionState::Stopping) {
out.extend(self.done("error", self.decode_ms));
}
out
}
/// `ReqStep.nextRequest`: Done -> Idle (clean request boundary, Theorem 8/10).
pub fn on_next(&mut self) -> Result<(), String> {
if self.state != SessionState::Done {
return Err(format!("next while {:?}", self.state));
}
self.state = SessionState::Idle;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use vetta_infer_abi::serve::parse_serve_line;
fn gen_cmd(line: &str) -> ParsedGen {
match parse_serve_line(line, 1000).unwrap() {
vetta_infer_abi::serve::ServeCommand::Gen(g) => g,
_ => panic!("expected GEN"),
}
}
#[test]
fn gen_zero_prewarm_emits_done_without_tokens() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 0 1,2,3")).unwrap();
assert_eq!(s.state(), SessionState::Prefilling);
let out = s.on_prefill_complete(0, 12.0).unwrap();
assert_eq!(s.state(), SessionState::Done);
assert!(out.iter().any(|l| l.starts_with("DONE 0 3")));
assert!(!out.iter().any(|l| l.starts_with("T ")));
assert!(s.on_token(5).is_err()); // never entered decode
}
#[test]
fn normal_flow_prefill_decode_finish() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 3 1,2")).unwrap();
let pp = s.on_prefill_chunk(2, 2, 8.0).unwrap();
assert_eq!(pp, vec!["PP 2 2 8.0"]);
let out = s.on_prefill_complete(1, 8.0).unwrap();
assert_eq!(out, vec!["RESUME 1"]);
assert_eq!(s.state(), SessionState::Decoding);
assert_eq!(s.on_token(10).unwrap(), vec!["T 10"]);
assert_eq!(s.on_token(11).unwrap(), vec!["T 11"]);
let done = s.on_finish("length", 40.0).unwrap();
assert_eq!(done, vec!["DONE 2 2 8.0 40.0 length"]);
assert_eq!(s.state(), SessionState::Done);
assert!(s.on_gen(&gen_cmd("GEN 1 1")).is_err()); // must pass through idle
s.on_next().unwrap();
assert_eq!(s.state(), SessionState::Idle);
}
#[test]
fn stop_mid_decode_drains_to_done_no_more_tokens() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 8 1,2")).unwrap();
s.on_prefill_complete(0, 5.0).unwrap();
s.on_token(10).unwrap();
assert!(s.on_stop().is_empty());
assert_eq!(s.state(), SessionState::Stopping);
assert!(s.on_token(11).is_err()); // no tokens while draining
let done = s.on_drain_complete(20.0).unwrap();
assert_eq!(done, vec!["DONE 1 2 5.0 20.0 stop"]);
assert_eq!(s.state(), SessionState::Done);
}
#[test]
fn stop_in_idle_is_noop_and_stop_prefill_drains() {
let mut s = ServeSession::new();
assert!(s.on_stop().is_empty());
assert_eq!(s.state(), SessionState::Idle);
s.on_gen(&gen_cmd("GEN 4 1,2,3")).unwrap();
s.on_stop();
assert_eq!(s.state(), SessionState::Stopping);
let done = s.on_drain_complete(0.0).unwrap();
assert_eq!(done, vec!["DONE 0 3 0.0 0.0 stop"]);
}
#[test]
fn error_emits_err_and_trailing_done_when_active() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 4 1")).unwrap();
let out = s.on_error("boom");
assert_eq!(out[0], "ERR boom");
assert!(out[1].starts_with("DONE "));
assert_eq!(s.state(), SessionState::Done);
// ERR in idle: no trailing DONE (nothing in flight)
let mut s2 = ServeSession::new();
let out2 = s2.on_error("bad command");
assert_eq!(out2, vec!["ERR bad command"]);
assert_eq!(s2.state(), SessionState::Idle);
}
}
@@ -1,8 +1,8 @@
[package] [package]
name = "vetta-proto" name = "vetta-infer-kn"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
vetta-core = { path = "../vetta-core" } vetta-infer-abi = { path = "../vetta-infer-abi" }
+133
View File
@@ -0,0 +1,133 @@
//! Typed control bus — delivery gated on lifecycle state (`proofs/bus_lifecycle.lean`,
//! Theorems 13–14). In-process routing for now; the contract allows out-of-process
//! or Lyra transports later without changing message semantics.
//!
//! The bus carries control-plane messages only. Tensor data never crosses it:
//! the data plane uses UMA handles granted by the `SlabRing` broker.
use vetta_infer_abi::bus::{BusMsg, BusPayload, ServiceId, ServiceState};
use crate::registry::{Registry, RegistryError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BusError {
Registry(RegistryError),
/// Destination exists but is not in a state that accepts this payload.
NotDeliverable { dst: ServiceId, state: ServiceState },
}
impl std::fmt::Display for BusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for BusError {}
impl From<RegistryError> for BusError {
fn from(e: RegistryError) -> Self {
Self::Registry(e)
}
}
#[derive(Debug, Default)]
pub struct ControlBus {
registry: Registry,
delivered: Vec<BusMsg>,
}
impl ControlBus {
pub fn new() -> Self {
Self::default()
}
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn registry_mut(&mut self) -> &mut Registry {
&mut self.registry
}
/// Routes one message, enforcing the verified delivery rules:
/// - `Stop` is accepted only by a `Running` service and starts its drain;
/// - `StopAck` is accepted only from a `Stopping` service and completes it;
/// - every other payload is deliverable only to `Running`.
pub fn send(&mut self, msg: BusMsg) -> Result<(), BusError> {
let state = self.registry.state(msg.dst)?;
match &msg.payload {
BusPayload::Stop => {
if state != ServiceState::Running {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
self.registry.request_stop(msg.dst)?;
}
BusPayload::StopAck => {
if state != ServiceState::Stopping {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
self.registry.drain_done(msg.dst)?;
}
_ => {
if state != ServiceState::Running {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
}
}
self.delivered.push(msg);
Ok(())
}
/// In-order log of accepted messages (transport seam: a real transport
/// replaces this with per-service queues without changing `send` rules).
pub fn delivered(&self) -> &[BusMsg] {
&self.delivered
}
}
#[cfg(test)]
mod tests {
use super::*;
use vetta_infer_abi::bus::ServiceKind;
fn running_bus() -> (ControlBus, ServiceId) {
let mut bus = ControlBus::new();
let id = bus.registry().prepare();
bus.registry_mut().commit(id, ServiceKind::Cache).unwrap();
bus.registry_mut().start(id).unwrap();
(bus, id)
}
#[test]
fn stop_drains_to_stopped_and_blocks_further_delivery() {
let (mut bus, id) = running_bus();
let hint = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::DomainHint("lean4".into()) };
bus.send(hint.clone()).unwrap();
let stop = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::Stop };
bus.send(stop).unwrap();
assert_eq!(bus.registry().state(id).unwrap(), ServiceState::Stopping);
// Draining service accepts no new work
assert!(bus.send(hint).is_err());
// Nor a second STOP
assert!(bus.send(BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::Stop }).is_err());
let ack = BusMsg { src: id, dst: id, payload: BusPayload::StopAck };
bus.send(ack).unwrap();
assert_eq!(bus.registry().state(id).unwrap(), ServiceState::Stopped);
assert!(bus.send(BusMsg { src: id, dst: id, payload: BusPayload::StopAck }).is_err());
assert_eq!(bus.delivered().len(), 3); // hint, stop, ack — rejected msgs never logged
}
#[test]
fn no_delivery_to_registered_or_unknown() {
let mut bus = ControlBus::new();
let id = bus.registry().prepare();
bus.registry_mut().commit(id, ServiceKind::Net).unwrap();
let msg = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::DomainHint("dante".into()) };
assert!(bus.send(msg.clone()).is_err()); // Registered is not deliverable
assert!(bus.send(BusMsg { src: ServiceId(0), dst: ServiceId(77), payload: BusPayload::Stop }).is_err());
assert!(bus.delivered().is_empty());
}
}
+16
View File
@@ -0,0 +1,16 @@
//! `vetta-infer-kn`: the pure microkernel (docs/ARCHITECTURE.md §2).
//!
//! Three responsibilities, zero model logic:
//! 1. Service registry & lifecycle (two-phase commit, STOP/cancellation drain)
//! — verified in `proofs/bus_lifecycle.lean`.
//! 2. Typed control bus (delivery gated on lifecycle state).
//! 3. Memory/DMA broker (`SlabRing` fence-guarded UMA slot ownership)
//! — verified in `proofs/slab_ring_dma.lean`.
//!
//! The data plane never crosses this crate: services exchange UMA handles,
//! the bus carries only control-plane messages.
pub mod bus;
pub mod registry;
pub mod slab;
pub mod uma;
+168
View File
@@ -0,0 +1,168 @@
//! Service registry & lifecycle — implements `proofs/bus_lifecycle.lean`.
//!
//! Two-phase registration (prepare/commit): a failed resource allocation that
//! never calls `commit` leaves zero ghost entries (Theorem 12). Transitions
//! mirror `SvcStep`: no resurrection, no skipping the drain phase.
use vetta_infer_abi::bus::{ServiceId, ServiceKind, ServiceState};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
UnknownService(ServiceId),
/// `commit` called with an id that is not the currently prepared one.
NotPrepared { expected: ServiceId, got: ServiceId },
InvalidTransition { id: ServiceId, state: ServiceState, op: &'static str },
}
impl std::fmt::Display for RegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for RegistryError {}
#[derive(Debug, Clone)]
pub struct ServiceEntry {
pub id: ServiceId,
pub kind: ServiceKind,
pub state: ServiceState,
}
/// Committed entries only — a prepared-but-uncommitted entry is unobservable.
#[derive(Debug, Clone, Default)]
pub struct Registry {
entries: Vec<ServiceEntry>,
next_id: u32,
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
/// Phase 1 (pure peek): the candidate id for a new service. No mutation.
pub fn prepare(&self) -> ServiceId {
ServiceId(self.next_id)
}
/// Phase 2: commit the prepared entry. Call ONLY after the service's
/// resources were successfully allocated.
pub fn commit(&mut self, id: ServiceId, kind: ServiceKind) -> Result<(), RegistryError> {
let expected = self.prepare();
if id != expected {
return Err(RegistryError::NotPrepared { expected, got: id });
}
self.entries.push(ServiceEntry { id, kind, state: ServiceState::Registered });
self.next_id += 1;
Ok(())
}
pub fn entries(&self) -> &[ServiceEntry] {
&self.entries
}
pub fn state(&self, id: ServiceId) -> Result<ServiceState, RegistryError> {
self.entries
.iter()
.find(|e| e.id == id)
.map(|e| e.state)
.ok_or(RegistryError::UnknownService(id))
}
fn entry_mut(&mut self, id: ServiceId) -> Result<&mut ServiceEntry, RegistryError> {
self.entries
.iter_mut()
.find(|e| e.id == id)
.ok_or(RegistryError::UnknownService(id))
}
fn transition(
&mut self,
id: ServiceId,
from: ServiceState,
to: ServiceState,
op: &'static str,
) -> Result<(), RegistryError> {
let e = self.entry_mut(id)?;
if e.state != from {
return Err(RegistryError::InvalidTransition { id, state: e.state, op });
}
e.state = to;
Ok(())
}
/// `SvcStep.start`: Registered -> Running.
pub fn start(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Registered, ServiceState::Running, "start")
}
/// `SvcStep.stop`: Running -> Stopping (drain begins, no new work).
pub fn request_stop(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Running, ServiceState::Stopping, "request_stop")
}
/// `SvcStep.drain`: Stopping -> Stopped (drain ack observed).
pub fn drain_done(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Stopping, ServiceState::Stopped, "drain_done")
}
/// `SvcStep.cancelReady`: Registered -> Stopped (cancelled before start).
pub fn cancel_ready(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Registered, ServiceState::Stopped, "cancel_ready")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_phase_commit_no_ghost_entries() {
let mut r = Registry::new();
let id = r.prepare();
assert!(r.entries().is_empty()); // failed alloc before commit: zero ghosts
assert_eq!(r.prepare(), id); // prepare is pure
assert!(r.commit(ServiceId(99), ServiceKind::Cache).is_err()); // not prepared
assert!(r.entries().is_empty());
r.commit(id, ServiceKind::Cache).unwrap();
assert_eq!(r.entries().len(), 1);
assert_eq!(r.state(id).unwrap(), ServiceState::Registered);
assert_eq!(r.prepare(), ServiceId(1)); // fresh id, never collides
}
#[test]
fn lifecycle_happy_path_and_cancellation() {
let mut r = Registry::new();
let a = r.prepare();
r.commit(a, ServiceKind::Runtime).unwrap();
r.start(a).unwrap();
r.request_stop(a).unwrap();
assert_eq!(r.state(a).unwrap(), ServiceState::Stopping);
r.drain_done(a).unwrap();
assert_eq!(r.state(a).unwrap(), ServiceState::Stopped);
let b = r.prepare();
r.commit(b, ServiceKind::Lab).unwrap();
r.cancel_ready(b).unwrap(); // cancelled before ever running
assert_eq!(r.state(b).unwrap(), ServiceState::Stopped);
}
#[test]
fn illegal_transitions_rejected() {
let mut r = Registry::new();
let id = r.prepare();
r.commit(id, ServiceKind::Spec).unwrap();
assert!(r.request_stop(id).is_err()); // not running yet
assert!(r.drain_done(id).is_err()); // not stopping
r.start(id).unwrap();
assert!(r.start(id).is_err()); // already running
assert!(r.drain_done(id).is_err()); // must pass through Stopping
r.request_stop(id).unwrap();
assert!(r.start(id).is_err()); // no resurrection while draining
r.drain_done(id).unwrap();
assert!(r.start(id).is_err()); // stopped is terminal
assert!(r.request_stop(id).is_err());
assert!(r.state(ServiceId(42)).is_err()); // unknown service
}
}
@@ -160,4 +160,4 @@ mod tests {
ring.complete_gpu(s0, 42).unwrap(); ring.complete_gpu(s0, 42).unwrap();
assert_eq!(ring.state(s0).unwrap(), SlotState::Free); assert_eq!(ring.state(s0).unwrap(), SlotState::Free);
} }
} }
@@ -1,23 +1,12 @@
//! `vetta-hip`: thin HIP microkernel boundary & fence-guarded zero-copy UMA ring buffers. //! UMA slab pool — the broker's buffer ownership surface.
//! //!
//! All unsafe GPU/DMA lifetime invariants are mediated by `vetta_core::slab::SlabRing` //! In M2 this wraps `mmap` + `hipHostRegisterMapped` + `io_uring` fixed buffers;
//! (formally verified in `proofs/slab_ring_dma.lean`). //! today it runs on CPU aligned buffers with the exact same `SlabRing` state
//! machine verified in `proofs/slab_ring_dma.lean`. The HIP FFI side lands in `rt`.
use vetta_core::slab::{SlabError, SlabRing, SlotState}; use crate::slab::{SlabError, SlabRing, SlotState};
#[derive(Debug, Clone)]
pub struct DeviceInfo {
pub name: String,
pub gcn_arch: String,
pub cu_count: u32,
pub wave_size: u32,
pub total_vram_bytes: u64,
pub is_uma: bool,
}
/// Page-aligned host/UMA ring backing `SlabRing` transitions. /// Page-aligned host/UMA ring backing `SlabRing` transitions.
/// In Milestone 2 this wraps `mmap` + `hipHostRegisterMapped` + `io_uring` fixed buffers;
/// in Milestone 0/tests it runs directly on CPU aligned buffers with the exact same state machine.
pub struct UmaSlabPool { pub struct UmaSlabPool {
ring: SlabRing, ring: SlabRing,
buffers: Vec<Vec<u8>>, buffers: Vec<Vec<u8>>,
@@ -102,4 +91,4 @@ mod tests {
pool.abort_io(s1, req1).unwrap(); pool.abort_io(s1, req1).unwrap();
assert_eq!(pool.slot_state(s1).unwrap(), SlotState::Free); assert_eq!(pool.slot_state(s1).unwrap(), SlotState::Free);
} }
} }
@@ -1,8 +1,8 @@
[package] [package]
name = "vetta-io" name = "vetta-infer-lab"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
vetta-core = { path = "../vetta-core" } vetta-infer-rt = { path = "../vetta-infer-rt" }
+20
View File
@@ -0,0 +1,20 @@
//! `vetta-infer-lab`: laboratory runtime (docs/ARCHITECTURE.md §5).
//!
//! Executes the *identical* `CompiledPlan` as `rt` — the executor core is
//! shared by construction, not duplicated. `lab` only interleaves the
//! observation points declared in `probe.vplan`; `rt` runs with an empty
//! probe table (zero probes, zero debug branching on the hot path).
//!
//! The probe-hook table and the shared plan executor land with M1; this crate
//! already pins the structural guarantee: lab depends on rt's executor.
#[cfg(test)]
mod tests {
#[test]
fn shares_executor_core_with_rt() {
// Structural guarantee: lab sees the exact same prefix/state machinery
// as rt (no forked executor).
let st = vetta_infer_rt::prefix::PrefixState::target_only(4);
assert_eq!(st.len(), 4);
}
}
@@ -1,8 +1,8 @@
[package] [package]
name = "vetta-hip" name = "vetta-infer-ld"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
vetta-core = { path = "../vetta-core" } vetta-infer-abi = { path = "../vetta-infer-abi" }
+421
View File
@@ -0,0 +1,421 @@
//! `vetta-infer-ld`: loader & compiler (docs/ARCHITECTURE.md §3, §9).
//!
//! Checked `.safetensors` reader (index.json + directory fallback + `pread` +
//! overflow-safe slice checks) and the write-once `VTC1` atomic cache writer
//! (`.tmp.<pid>` + `fsync` + `rename`). The dual-step ModelImporter → IR →
//! BackendPacker pipeline lands here with M1; `cc` owns the `O_RDONLY` reload.
//!
//! Eliminates audit-05 F-02 (shard bounds, u64 slice overflow, missing
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use vetta_infer_abi::json::parse_json;
use vetta_infer_abi::vtc1::{
align_up, serialize_meta, CacheRecord, CACHE_ALIGN, CACHE_MAGIC, CACHE_VERSION, HEADER_SIZE,
};
// ============================================================================
// 1. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
// ============================================================================
#[derive(Debug, Clone)]
pub struct TensorInfo {
pub shard_idx: usize,
pub dtype: String,
pub shape: Vec<u64>,
pub begin: u64,
pub end: u64,
}
impl TensorInfo {
pub fn byte_len(&self) -> u64 {
self.end - self.begin
}
}
pub struct SafetensorsShard {
pub path: PathBuf,
pub file: File,
pub file_size: u64,
pub data_start: u64,
}
pub struct SafetensorsArchive {
pub dir: PathBuf,
pub shards: Vec<SafetensorsShard>,
pub tensors: HashMap<String, TensorInfo>,
}
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
impl SafetensorsArchive {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let dir = dir.as_ref().to_path_buf();
let shard_paths = discover_shards(&dir)?;
if shard_paths.is_empty() {
return Err(format!("no .safetensors shards found in {}", dir.display()));
}
let mut shards = Vec::with_capacity(shard_paths.len());
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
let raw = fs::read_to_string(&idx_path)
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
let root = parse_json(&raw)?;
let wm = root
.as_obj()
.and_then(|o| o.get("weight_map"))
.and_then(|v| v.as_obj())
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
let mut uniq = BTreeSet::new();
for v in wm.values() {
if let Some(fname) = v.as_str() {
if !fname.is_empty() {
uniq.insert(dir.join(fname));
}
}
}
return Ok(uniq.into_iter().collect());
}
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
let mut out = Vec::new();
for entry in entries {
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
let p = e.path();
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
out.push(p);
}
}
out.sort();
Ok(out)
}
// ============================================================================
// 2. Write-Once `VTC1` Atomic Cache Writer (`.tmp.<pid>` + fsync + rename)
// ============================================================================
pub struct DiskCacheWriter {
final_path: PathBuf,
tmp_path: PathBuf,
file: Option<File>,
fingerprint: u64,
cursor: u64,
records: Vec<CacheRecord>,
}
impl DiskCacheWriter {
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
let final_path = final_path.as_ref().to_path_buf();
if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
}
let pid = std::process::id();
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&tmp_path)
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
Ok(Self {
final_path,
tmp_path,
file: Some(file),
fingerprint,
cursor: CACHE_ALIGN,
records: Vec::new(),
})
}
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
rec.data_bytes = payload.len() as u64;
self.cursor = align_up(
rec.data_offset
.checked_add(rec.data_bytes)
.ok_or_else(|| "cache offset overflow".to_string())?,
CACHE_ALIGN,
)?;
f.write_all_at(payload, rec.data_offset)
.map_err(|e| format!("write payload: {e}"))?;
let off = rec.data_offset;
self.records.push(rec);
Ok(off)
}
pub fn commit(mut self) -> Result<PathBuf, String> {
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
let meta = serialize_meta(&self.records);
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
f.write_all_at(&meta, meta_off)
.map_err(|e| format!("write meta: {e}"))?;
let total_bytes = meta_off
.checked_add(meta.len() as u64)
.ok_or_else(|| "total_bytes overflow".to_string())?;
let mut hdr = [0u8; HEADER_SIZE];
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
drop(f);
fs::rename(&self.tmp_path, &self.final_path)
.map_err(|e| format!("rename cache: {e}"))?;
Ok(self.final_path.clone())
}
}
impl Drop for DiskCacheWriter {
fn drop(&mut self) {
if self.file.take().is_some() {
let _ = fs::remove_file(&self.tmp_path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
let hdr = format!(
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
data.len() / 4
);
let mut f = File::create(path).unwrap();
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
f.write_all(hdr.as_bytes()).unwrap();
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
f.write_all(&data[..take]).unwrap();
}
#[test]
fn safetensors_bounds_overflow_and_index_json() {
let root = std::env::temp_dir().join(format!("vetta_ld_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
// Non-existent dir fails cleanly
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
// Truncated shard rejected
let d_trunc = root.join("trunc");
fs::create_dir_all(&d_trunc).unwrap();
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
assert!(SafetensorsArchive::open(&d_trunc).is_err());
// Inverted offsets rejected
let d_inv = root.join("inv");
fs::create_dir_all(&d_inv).unwrap();
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
assert!(SafetensorsArchive::open(&d_inv).is_err());
// Valid + index.json ignoring stray backup + u64 overflow slice check
let d_ok = root.join("ok");
fs::create_dir_all(&d_ok).unwrap();
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
fs::write(
d_ok.join("model.safetensors.index.json"),
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
)
.unwrap();
let ar = SafetensorsArchive::open(&d_ok).unwrap();
assert_eq!(ar.shards.len(), 1);
let mut got = [0u8; 4];
ar.read_slice("w", 4, &mut got).unwrap();
assert_eq!(got, [50, 60, 70, 80]);
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn writer_atomic_commit_and_drop_cleanup() {
let p = std::env::temp_dir().join(format!("vetta_ld_cache_{}.bin", std::process::id()));
let _ = fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = DiskCacheWriter::begin(&p, fp).unwrap();
wr.write_record(
CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 0,
data_bytes: 0,
name: "layer.0.q8".into(),
},
&payload,
)
.unwrap();
let committed = wr.commit().unwrap();
assert_eq!(committed, p);
assert!(p.is_file());
assert!(!PathBuf::from(format!("{}.tmp.{}", p.display(), std::process::id())).exists());
// An abandoned writer cleans up its .tmp (no ghost final file)
let p2 = std::env::temp_dir().join(format!("vetta_ld_cache2_{}.bin", std::process::id()));
{
let mut wr2 = DiskCacheWriter::begin(&p2, fp).unwrap();
wr2.write_record(
CacheRecord {
kind: 1, i0: 0, i1: 0, i2: 0, flags: 0, u0: 0, u1: 0,
data_offset: 0, data_bytes: 0, name: "x".into(),
},
&payload,
).unwrap();
}
assert!(!p2.exists());
let _ = fs::remove_file(&p);
}
}
@@ -1,7 +1,7 @@
[package] [package]
name = "vetta-core" name = "vetta-infer-nt"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
+32
View File
@@ -0,0 +1,32 @@
//! `vetta-infer-nt`: LAN bridge to Lyra (docs/ARCHITECTURE.md §2, "Lyra control/co-processor split").
//!
//! Compact RPC messages for Sogliola <-> Lyra (`< 1 KB/step` on 2.5 Gbps Ethernet):
//! remote drafting (same tokenizer as the target), domain routing hints, and
//! lightweight Vision/RAG offload. The TCP transport lands with M3; the message
//! contract is fixed here so both ends can be built and tested independently.
/// Compact LAN RPC messages for Sogliola <-> Lyra (`< 1 KB/step`, `~0.3 ms` RTT).
#[derive(Debug, Clone, PartialEq)]
pub enum LyraRpc {
DraftRequest { session_id: u64, accepted_tail: Vec<i32>, max_k: u8 },
DraftResponse { session_id: u64, proposed: Vec<i32>, probs: Vec<f32> },
DomainHint { session_id: u64, domain: String, confidence: f32 },
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn draft_roundtrip_shapes() {
let req = LyraRpc::DraftRequest { session_id: 1, accepted_tail: vec![10, 20], max_k: 8 };
let resp = LyraRpc::DraftResponse {
session_id: 1,
proposed: vec![30, 40, 50],
probs: vec![0.6, 0.3, 0.1],
};
let LyraRpc::DraftResponse { proposed, probs, .. } = resp else { panic!("shape") };
assert_eq!(proposed.len(), probs.len()); // lossless Leviathan needs one q(x) per proposal
assert!(matches!(req, LyraRpc::DraftRequest { max_k: 8, .. }));
}
}
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vetta-infer-rt"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
+8
View File
@@ -0,0 +1,8 @@
//! `vetta-infer-rt`: operational runtime (docs/ARCHITECTURE.md §2, §5).
//!
//! Executes the boot-lowered `CompiledPlan` on the HIP backend at full speed,
//! zero probes on the hot path. `lab` shares this executor core. Today it
//! hosts the hybrid prefix/checkpoint state; the HIP FFI and plan executor
//! land with M1.
pub mod prefix;
@@ -171,4 +171,4 @@ mod tests {
pool.invalidate_above(2); pool.invalidate_above(2);
assert!(pool.entries().is_empty()); assert!(pool.entries().is_empty());
} }
} }
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "vetta-infer-sp"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
+378
View File
@@ -0,0 +1,378 @@
//! Throughput-aware Adaptive-K controller — FAITHFUL port of the measured
//! `strata-clover/engine/src/clover/clover_policy.h` `AdaptiveKController`
//! (the policy behind 21.0 tok/s prose / 42.1 tok/s code, 100% exact vs AR).
//!
//! Ported elements (the M0 sketch lacked all of them):
//! - cooldowns: `ar_cooldown` (8), `k8_cooldown` (12), `k16_cooldown` (12);
//! - `just_probed` one-shot sensitivity after an AR->K=4 probe;
//! - per-band throughput guards (EMA ms/tok ratios 1.06 / 1.06 / 1.05);
//! - promotion to K=16 only on a full 8/8 streak x2 AND `k16_cooldown == 0`
//! (the prose trap fix, commit `f2a79ada4`);
//! - EMA smoothing 0.65/0.35 over K buckets {1, 4, 8, 16}.
//!
//! Lossless exactness vs AR for every K is inherited from the verification
//! machine (see `strata-clover/proofs/clover_gdn_ckpt.lean`,
//! `adaptive_spec_exact_vs_ar`); this controller only chooses K.
/// Mirrors `clamp_adaptive_k`.
fn clamp_k(k: usize, k_max: usize) -> usize {
if k_max <= 1 {
return 1;
}
k.max(1).min(k_max)
}
#[derive(Debug, Clone)]
pub struct AdaptiveKController {
k_max: usize,
cur_k: usize,
/// Plain AR (K=1) steps remaining before the next K=4 probe.
ar_cooldown: u32,
/// K=8 steps remaining before re-trying K=16 after throughput demotion.
k16_cooldown: u32,
/// K=4 steps remaining before re-trying K=8 after throughput demotion.
k8_cooldown: u32,
low_streak: u32,
high_streak: u32,
just_probed: bool,
/// Empirical ms/tok EMA for K buckets {1, 4, 8, 16}.
ema_mpt: [f64; 4],
}
impl AdaptiveKController {
pub fn new(k_max: usize) -> Self {
let km = k_max.max(1);
Self {
k_max: km,
cur_k: clamp_k(if km >= 8 { 8 } else if km >= 4 { 4 } else { 1 }, km),
ar_cooldown: 0,
k16_cooldown: 0,
k8_cooldown: 0,
low_streak: 0,
high_streak: 0,
just_probed: false,
ema_mpt: [0.0; 4],
}
}
pub fn reset(&mut self, k_max: usize) {
*self = Self::new(k_max);
}
pub fn k_max(&self) -> usize {
self.k_max
}
pub fn cur_k(&self) -> usize {
self.cur_k
}
fn bucket(k: usize) -> usize {
if k <= 1 {
0
} else if k <= 4 {
1
} else if k <= 8 {
2
} else {
3
}
}
/// Mirrors `next_k(rem_tokens, ctx_room)`.
pub fn next_k(&self, rem_tokens: usize, ctx_room: usize) -> usize {
let cap = self.k_max.min(rem_tokens.min(ctx_room));
if cap <= 1 {
return 1;
}
if self.ar_cooldown > 0 {
return 1;
}
clamp_k(self.cur_k, cap)
}
/// Mirrors `observe(used_k, accepted_tokens, step_ms)` branch by branch.
pub fn observe(&mut self, used_k: usize, accepted_tokens: usize, step_ms: f64) {
if self.k_max <= 1 {
self.cur_k = 1;
return;
}
let acc = accepted_tokens.max(1);
let b = Self::bucket(used_k);
if step_ms > 0.0 {
let mpt = step_ms / acc as f64;
self.ema_mpt[b] = if self.ema_mpt[b] <= 0.0 {
mpt
} else {
0.65 * self.ema_mpt[b] + 0.35 * mpt
};
}
if used_k <= 1 {
if self.ar_cooldown > 0 {
self.ar_cooldown -= 1;
}
if self.ar_cooldown == 0 {
self.cur_k = clamp_k(4, self.k_max);
self.just_probed = true;
self.low_streak = 0;
self.high_streak = 0;
}
return;
}
if used_k <= 4 {
if self.k8_cooldown > 0 {
self.k8_cooldown -= 1;
}
// Throughput guard: K=4 measurably slower than observed AR -> AR cooldown.
if self.ema_mpt[1] > 0.0
&& self.ema_mpt[0] > 0.0
&& self.ema_mpt[1] > self.ema_mpt[0] * 1.06
{
self.low_streak += 1;
self.high_streak = 0;
if self.just_probed || self.low_streak >= 2 {
self.cur_k = 1;
self.ar_cooldown = 8;
self.low_streak = 0;
self.just_probed = false;
return;
}
}
if accepted_tokens >= 3 {
if self.k8_cooldown == 0 {
self.cur_k = clamp_k(8, self.k_max);
self.low_streak = 0;
self.high_streak = 0;
self.just_probed = false;
} else {
self.low_streak = 0;
self.just_probed = false;
}
} else if accepted_tokens <= 2 {
self.low_streak += 1;
self.high_streak = 0;
if self.just_probed || self.low_streak >= 2 {
self.cur_k = 1;
self.ar_cooldown = 8;
self.low_streak = 0;
self.just_probed = false;
}
} else {
self.just_probed = false;
}
return;
}
if used_k <= 8 {
self.just_probed = false;
if self.k16_cooldown > 0 {
self.k16_cooldown -= 1;
}
// Throughput guard: K=8 measurably slower than observed K=4 -> step back.
if self.ema_mpt[2] > 0.0
&& self.ema_mpt[1] > 0.0
&& self.ema_mpt[2] > self.ema_mpt[1] * 1.06
{
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(4, self.k_max);
self.k8_cooldown = 12;
self.low_streak = 0;
return;
}
}
// Promote to K=16 only on full 8/8 acceptance streak (prose trap fix).
if accepted_tokens >= 8 {
self.high_streak += 1;
self.low_streak = 0;
if self.high_streak >= 2 && self.k_max >= 16 && self.k16_cooldown == 0 {
self.cur_k = clamp_k(16, self.k_max);
self.high_streak = 0;
}
} else if accepted_tokens <= 3 {
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(4, self.k_max);
self.low_streak = 0;
}
} else {
self.high_streak = 0;
self.low_streak = 0;
}
return;
}
// used_k > 8 (e.g. 16): require >= 10 accepted AND competitive ms/tok to stay.
self.just_probed = false;
if self.ema_mpt[3] > 0.0
&& self.ema_mpt[2] > 0.0
&& self.ema_mpt[3] > self.ema_mpt[2] * 1.05
{
self.cur_k = clamp_k(8, self.k_max);
self.k16_cooldown = 12;
self.low_streak = 0;
self.high_streak = 0;
return;
}
if accepted_tokens <= 9 {
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(8, self.k_max);
self.k16_cooldown = 12;
self.low_streak = 0;
}
} else {
self.low_streak = 0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Scenario parity tests: expected values derived by hand from the C++
// reference (clover_policy.h), branch by branch.
#[test]
fn initial_state_and_caps() {
let c = AdaptiveKController::new(16);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
assert_eq!(c.next_k(3, 100), 3); // rem_tokens cap
assert_eq!(c.next_k(100, 1), 1); // ctx_room cap <= 1
let c4 = AdaptiveKController::new(4);
assert_eq!(c4.cur_k(), 4);
let c1 = AdaptiveKController::new(1);
assert_eq!(c1.cur_k(), 1);
assert_eq!(c1.next_k(100, 100), 1);
}
#[test]
fn k_max_one_forces_ar() {
let mut c = AdaptiveKController::new(1);
c.observe(16, 16, 10.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn promotion_requires_two_full_streaks_and_no_cooldown() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0); // high_streak = 1, not yet 16
assert_eq!(c.cur_k(), 8);
c.observe(8, 8, 80.0); // high_streak = 2 -> promote
assert_eq!(c.cur_k(), 16);
assert_eq!(c.next_k(100, 100), 16);
}
#[test]
fn prose_trap_k16_slower_than_k8_demotes_with_cooldown() {
let mut c = AdaptiveKController::new(16);
// Establish K=8 at 10 ms/tok, then promote to 16.
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 16);
// K=16 step: 16 accepted in 200 ms = 12.5 ms/tok > 10 * 1.05 -> demote.
c.observe(16, 16, 200.0);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
// During the 12-step cooldown, full 8/8 streaks must NOT re-promote.
for _ in 0..11 {
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 8, "promotion must wait out k16_cooldown");
}
// 12th observe drains the cooldown; the accumulated full-acceptance
// streak (never reset while cooling down) immediately re-promotes.
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 16);
}
#[test]
fn k16_low_acceptance_demotes_after_two_strikes() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0); // now K=16
c.observe(16, 5, 0.0); // low_streak = 1, stays 16
assert_eq!(c.cur_k(), 16);
c.observe(16, 5, 0.0); // low_streak = 2 -> demote + cooldown
assert_eq!(c.cur_k(), 8);
}
#[test]
fn ar_probe_cycle_and_one_shot_probe_sensitivity() {
let mut c = AdaptiveKController::new(16);
// Two weak K=4 steps -> drop to AR with cooldown 8.
c.observe(4, 1, 0.0);
c.observe(4, 1, 0.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1); // ar_cooldown forces K=1
// Drain the 8 AR steps; the 8th re-probes K=4 with just_probed.
for _ in 0..8 {
c.observe(1, 1, 0.0);
}
assert_eq!(c.cur_k(), 4);
// A single weak probe step immediately drops back (just_probed).
c.observe(4, 1, 0.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn k4_promotes_to_k8_on_three_accepted() {
let mut c = AdaptiveKController::new(16);
c.observe(4, 3, 0.0);
assert_eq!(c.cur_k(), 8);
}
#[test]
fn k8_throughput_guard_steps_back_to_k4_with_cooldown() {
let mut c = AdaptiveKController::new(16);
// K=4 at 5 ms/tok promotes to K=8.
c.observe(4, 4, 20.0);
assert_eq!(c.cur_k(), 8);
// One weak K=8 step (no timing): low_streak = 1, survives (no demotion yet).
c.observe(8, 3, 0.0);
assert_eq!(c.cur_k(), 8);
// K=8 at 10 ms/tok (> 5 * 1.06): guard sees low_streak 1 -> 2 -> demote + cooldown.
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 4);
// During k8_cooldown, good K=4 acceptance must not re-promote to 8.
for _ in 0..11 {
c.observe(4, 4, 20.0);
assert_eq!(c.cur_k(), 4);
}
c.observe(4, 4, 20.0); // cooldown drained, accepted >= 3 -> promote
assert_eq!(c.cur_k(), 8);
}
#[test]
fn k4_throughput_guard_vs_ar_one_shot_probe() {
let mut c = AdaptiveKController::new(16);
// AR at 5 ms/tok; cooldown == 0 re-probes K=4 with just_probed.
c.observe(1, 1, 5.0);
assert_eq!(c.cur_k(), 4);
// K=4 at 10 ms/tok (> 5 * 1.06): a single weak probe step drops back
// immediately (just_probed), with the 8-step AR cooldown.
c.observe(4, 4, 40.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn reset_restores_initial_state() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0);
c.observe(16, 5, 0.0);
c.observe(16, 5, 0.0);
c.reset(16);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
}
}
+8
View File
@@ -0,0 +1,8 @@
//! `vetta-infer-sp`: speculative coordinator (docs/ARCHITECTURE.md §2).
//!
//! Lossless verification (Leviathan, in `abi`), throughput-aware Adaptive-K,
//! local MTP/Block-Diffusion drafting or remote via `nt`. Every policy here is
//! a faithful port of the measured strata reference, with scenario parity
//! tests — never a simplified re-interpretation.
pub mod adaptive_k;
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vetta-infer-tm"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
@@ -1,8 +1,9 @@
//! `vetta-telemetry`: first-class, low-overhead inference statistics & MoE routing analytics. //! `vetta-infer-tm`: first-class, low-overhead inference statistics & MoE routing analytics.
//! //!
//! Tracks per-layer expert activation Zipf curves, `L -> L+1` co-activation transitions, //! Tracks per-layer expert activation Zipf curves, `L -> L+1` co-activation transitions,
//! domain-tagged expert profiles (for NVMe Hot/Cold pre-warming and Lyra domain routing), //! domain-tagged expert profiles (for NVMe Hot/Cold pre-warming and Lyra domain routing),
//! speculative acceptance histograms, and exports structured JSONL asynchronously. //! speculative acceptance histograms, and exports structured JSONL asynchronously.
//! Writes the updatable `stats/` profiles of the `.vbundle` (docs/ARCHITECTURE.md §3).
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::OpenOptions; use std::fs::OpenOptions;
@@ -10,7 +11,7 @@ use std::io::{BufWriter, Write};
use std::path::Path; use std::path::Path;
use std::sync::mpsc::{self, SyncSender, TrySendError}; use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::thread::{self, JoinHandle}; use std::thread::{self, JoinHandle};
use vetta_core::moe::ExpertKey; use vetta_infer_abi::ExpertKey;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum TelemetryEvent { pub enum TelemetryEvent {
@@ -235,7 +236,7 @@ mod tests {
#[test] #[test]
fn domain_expert_profile_and_async_jsonl() { fn domain_expert_profile_and_async_jsonl() {
let p = std::env::temp_dir().join(format!("vetta_tel_{}.jsonl", std::process::id())); let p = std::env::temp_dir().join(format!("vetta_tm_{}.jsonl", std::process::id()));
let _ = std::fs::remove_file(&p); let _ = std::fs::remove_file(&p);
let mut h = TelemetryHandle::start(Some(&p), 128).unwrap(); let mut h = TelemetryHandle::start(Some(&p), 128).unwrap();
for _ in 0..5 { for _ in 0..5 {
@@ -267,4 +268,4 @@ mod tests {
assert!(std::fs::read_to_string(&p).unwrap().contains("\"ev\":\"spec\"")); assert!(std::fs::read_to_string(&p).unwrap().contains("\"ev\":\"spec\""));
let _ = std::fs::remove_file(&p); let _ = std::fs::remove_file(&p);
} }
} }
-804
View File
@@ -1,804 +0,0 @@
//! `vetta-io`: unified checked `.safetensors` reader and write-once `O_RDONLY` NVMe disk cache.
//!
//! Eliminates audit-05 F-02 (shard bounds, u64 slice overflow, missing index.json) and F-05
//! (pre-reserve OOM on corrupt count, PID-isolated `.tmp.<pid>` atomic commit) by construction.
use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
// ============================================================================
// 1. Minimal Checked JSON Parser (zero external deps, strict UTF-8/escapes)
// ============================================================================
#[derive(Debug, Clone, PartialEq)]
pub enum JsonVal {
Null,
Bool(bool),
Num(f64),
Int(u64),
Str(String),
Arr(Vec<JsonVal>),
Obj(HashMap<String, JsonVal>),
}
impl JsonVal {
pub fn as_obj(&self) -> Option<&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 = 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)
}
// ============================================================================
// 2. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
// ============================================================================
#[derive(Debug, Clone)]
pub struct TensorInfo {
pub shard_idx: usize,
pub dtype: String,
pub shape: Vec<u64>,
pub begin: u64,
pub end: u64,
}
impl TensorInfo {
pub fn byte_len(&self) -> u64 {
self.end - self.begin
}
}
pub struct SafetensorsShard {
pub path: PathBuf,
pub file: File,
pub file_size: u64,
pub data_start: u64,
}
pub struct SafetensorsArchive {
pub dir: PathBuf,
pub shards: Vec<SafetensorsShard>,
pub tensors: HashMap<String, TensorInfo>,
}
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
impl SafetensorsArchive {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let dir = dir.as_ref().to_path_buf();
let shard_paths = discover_shards(&dir)?;
if shard_paths.is_empty() {
return Err(format!("no .safetensors shards found in {}", dir.display()));
}
let mut shards = Vec::with_capacity(shard_paths.len());
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
let raw = fs::read_to_string(&idx_path)
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
let root = parse_json(&raw)?;
let wm = root
.as_obj()
.and_then(|o| o.get("weight_map"))
.and_then(|v| v.as_obj())
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
let mut uniq = BTreeSet::new();
for v in wm.values() {
if let Some(fname) = v.as_str() {
if !fname.is_empty() {
uniq.insert(dir.join(fname));
}
}
}
return Ok(uniq.into_iter().collect());
}
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
let mut out = Vec::new();
for entry in entries {
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
let p = e.path();
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
out.push(p);
}
}
out.sort();
Ok(out)
}
// ============================================================================
// 3. Unified Write-Once `O_RDONLY` NVMe Disk Cache (`VTC1`, PID `.tmp`, anti-OOM)
// ============================================================================
pub const CACHE_MAGIC: [u8; 8] = *b"VTCACHE1";
pub const CACHE_VERSION: u32 = 1;
pub const CACHE_ALIGN: u64 = 4096;
const HEADER_SIZE: usize = 48;
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)
}
pub struct DiskCacheWriter {
final_path: PathBuf,
tmp_path: PathBuf,
file: Option<File>,
fingerprint: u64,
cursor: u64,
records: Vec<CacheRecord>,
}
impl DiskCacheWriter {
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
let final_path = final_path.as_ref().to_path_buf();
if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
}
let pid = std::process::id();
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&tmp_path)
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
Ok(Self {
final_path,
tmp_path,
file: Some(file),
fingerprint,
cursor: CACHE_ALIGN,
records: Vec::new(),
})
}
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
rec.data_bytes = payload.len() as u64;
self.cursor = align_up(
rec.data_offset
.checked_add(rec.data_bytes)
.ok_or_else(|| "cache offset overflow".to_string())?,
CACHE_ALIGN,
)?;
f.write_all_at(payload, rec.data_offset)
.map_err(|e| format!("write payload: {e}"))?;
let off = rec.data_offset;
self.records.push(rec);
Ok(off)
}
pub fn commit(mut self) -> Result<PathBuf, String> {
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
let meta = serialize_meta(&self.records);
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
f.write_all_at(&meta, meta_off)
.map_err(|e| format!("write meta: {e}"))?;
let total_bytes = meta_off
.checked_add(meta.len() as u64)
.ok_or_else(|| "total_bytes overflow".to_string())?;
let mut hdr = [0u8; HEADER_SIZE];
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
drop(f);
fs::rename(&self.tmp_path, &self.final_path)
.map_err(|e| format!("rename cache: {e}"))?;
Ok(self.final_path.clone())
}
}
impl Drop for DiskCacheWriter {
fn drop(&mut self) {
if self.file.take().is_some() {
let _ = fs::remove_file(&self.tmp_path);
}
}
}
/// Strictly `O_RDONLY` cache reader (0 SSD writes on every reload).
pub struct DiskCacheReader {
file: File,
pub file_size: u64,
pub records: Vec<CacheRecord>,
}
impl DiskCacheReader {
pub fn open_and_validate(path: impl AsRef<Path>, expected_fp: u64) -> Result<Self, String> {
let path = path.as_ref();
let file = OpenOptions::new()
.read(true)
.open(path)
.map_err(|e| format!("open cache {}: {e}", path.display()))?;
let file_size = file.metadata().map_err(|e| format!("stat cache: {e}"))?.len();
if file_size < HEADER_SIZE as u64 {
return Err("cache file too small".into());
}
let mut hdr = [0u8; HEADER_SIZE];
file.read_exact_at(&mut hdr, 0)
.map_err(|e| format!("read cache hdr: {e}"))?;
if hdr[0..8] != CACHE_MAGIC {
return Err("cache bad magic".into());
}
let version = u32::from_le_bytes(hdr[8..12].try_into().unwrap());
if version != CACHE_VERSION {
return Err(format!("cache version mismatch: {version}"));
}
let count = u32::from_le_bytes(hdr[12..16].try_into().unwrap());
let fp = u64::from_le_bytes(hdr[16..24].try_into().unwrap());
if fp != expected_fp {
return Err("cache fingerprint mismatch".into());
}
let meta_off = u64::from_le_bytes(hdr[24..32].try_into().unwrap());
let meta_bytes = u64::from_le_bytes(hdr[32..40].try_into().unwrap());
let total_bytes = u64::from_le_bytes(hdr[40..48].try_into().unwrap());
if total_bytes != file_size {
return Err("cache file size mismatch (incomplete)".into());
}
if meta_off < HEADER_SIZE as u64
|| meta_off > file_size
|| meta_bytes > file_size - meta_off
|| meta_bytes > 64 * 1024 * 1024
{
return Err("cache metadata out of bounds".into());
}
let mut mblob = vec![0u8; meta_bytes as usize];
file.read_exact_at(&mut mblob, meta_off)
.map_err(|e| format!("read cache meta: {e}"))?;
let records = deserialize_meta(&mblob, count)?;
for r in &records {
if r.data_offset > file_size || r.data_bytes > file_size - r.data_offset {
return Err(format!("cache record '{}' payload OOB", r.name));
}
}
Ok(Self { file, file_size, records })
}
pub fn read_slice(&self, off: u64, dst: &mut [u8]) -> Result<(), String> {
let len = dst.len() as u64;
if off > self.file_size || len > self.file_size - off {
return Err("cache read_slice OOB".into());
}
self.file
.read_exact_at(dst, off)
.map_err(|e| format!("cache pread: {e}"))
}
}
// Keep unused imports clean if needed
#[allow(dead_code)]
fn _touch_io(_: &mut dyn Read, _: &mut dyn Write) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
let hdr = format!(
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
data.len() / 4
);
let mut f = File::create(path).unwrap();
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
f.write_all(hdr.as_bytes()).unwrap();
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
f.write_all(&data[..take]).unwrap();
}
#[test]
fn safetensors_bounds_overflow_and_index_json() {
let root = std::env::temp_dir().join(format!("vetta_io_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
// Non-existent dir fails cleanly
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
// Truncated shard rejected
let d_trunc = root.join("trunc");
fs::create_dir_all(&d_trunc).unwrap();
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
assert!(SafetensorsArchive::open(&d_trunc).is_err());
// Inverted offsets rejected
let d_inv = root.join("inv");
fs::create_dir_all(&d_inv).unwrap();
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
assert!(SafetensorsArchive::open(&d_inv).is_err());
// Valid + index.json ignoring stray backup + u64 overflow slice check
let d_ok = root.join("ok");
fs::create_dir_all(&d_ok).unwrap();
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
fs::write(
d_ok.join("model.safetensors.index.json"),
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
)
.unwrap();
let ar = SafetensorsArchive::open(&d_ok).unwrap();
assert_eq!(ar.shards.len(), 1);
let mut got = [0u8; 4];
ar.read_slice("w", 4, &mut got).unwrap();
assert_eq!(got, [50, 60, 70, 80]);
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn disk_cache_roundtrip_and_anti_oom() {
// Absurd entry count rejected BEFORE Vec::with_capacity
assert!(deserialize_meta(&[0u8; 64], u32::MAX).is_err());
let p = std::env::temp_dir().join(format!("vetta_cache_test_{}.bin", std::process::id()));
let _ = fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = DiskCacheWriter::begin(&p, fp).unwrap();
wr.write_record(
CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 0,
data_bytes: 0,
name: "layer.0.q8".into(),
},
&payload,
)
.unwrap();
wr.commit().unwrap();
let rd = DiskCacheReader::open_and_validate(&p, fp).unwrap();
assert_eq!(rd.records.len(), 1);
let mut got = vec![0u8; payload.len()];
rd.read_slice(rd.records[0].data_offset, &mut got).unwrap();
assert_eq!(got, payload);
assert!(DiskCacheReader::open_and_validate(&p, fp ^ 1).is_err());
let _ = fs::remove_file(&p);
}
}
-8
View File
@@ -1,8 +0,0 @@
[package]
name = "vetta-telemetry"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-core = { path = "../vetta-core" }
+311 -26
View File
@@ -1,4 +1,16 @@
# vetta-infer Architecture Blueprint # vetta-infer Architecture Specification
**Status:** approved design (2026-11-29), supersedes the M0 crate layout.
The M0 skeleton (commit `63b1668`) remains the source of reusable, audit-hardened
components; this document defines the target structure they are migrated into.
**Ground truth for behavior:** the hardened strata C++/HIP engines
(`../strata`, `../strata-safetensors`, `../strata-clover`, `../strata-dense`)
and `strata/review/RELAZIONE_COMPLETA_MOTORI_HIP_2026-11-28.md`. Every ported
policy/kernel carries a parity test against the measured strata behavior.
**Principal consumer:** `strata-ctl` (`../strata-ctl`), developed in tandem
(see §6 and AGENTS.md).
## 1. Hardware Ground Truth (Measured on Sogliola) ## 1. Hardware Ground Truth (Measured on Sogliola)
@@ -9,30 +21,226 @@
| Storage | Dual Gen4 NVMe (`~4.8 GB/s` single, `~9 GB/s` striped) | `O_RDONLY | O_DIRECT` + `io_uring` into `hipHostRegister` buffers gives **zero-copy NVMe → GPU DMA** on UMA | | Storage | Dual Gen4 NVMe (`~4.8 GB/s` single, `~9 GB/s` striped) | `O_RDONLY | O_DIRECT` + `io_uring` into `hipHostRegister` buffers gives **zero-copy NVMe → GPU DMA** on UMA |
| LAN Peer | **Lyra** over `2.5 Gbps` Ethernet (`~300 MB/s`, `~0.3 ms` RTT) | Unsuitable for per-layer Tensor Parallelism; ideal for `<1 KB/step` remote drafting, domain routing, and Vision/RAG offload | | LAN Peer | **Lyra** over `2.5 Gbps` Ethernet (`~300 MB/s`, `~0.3 ms` RTT) | Unsuitable for per-layer Tensor Parallelism; ideal for `<1 KB/step` remote drafting, domain routing, and Vision/RAG offload |
## 2. Crate Graph ### Scope decision: MoE-only (Federico, 2026-11-28)
**Dense models are out of scope** — "questo non è un HW per modelli densi".
The physics is decisive: a dense >80 GB model in pure NVMe streaming reads
40–70 GB/token → `0.07–0.22 tok/s` (DRAM/NVMe bandwidth ratio `~17×` single,
`~9×` striped). The engine is designed vertically for MoE: few active
parameters (2B–6B/tok), large total capacity (35B–300B+). `strata-dense`
remains a **technique donor** (Q4 SWAR unpack, MTP lossless verification),
not a target engine.
### Residency & streaming policy
| Model footprint | Policy |
| --- | --- |
| `<= ~80 GiB` (Inkling, Clover, MoE 35B–100B) | **Fully UMA-resident zero-copy** — VRAM carveout and GTT are the same LPDDR5X; NVMe is used only for the write-once boot cache, never at runtime |
| `> ~80 GiB` MoE (120B–300B+) | Hot experts pinned in `~70 GiB` UMA (LFU/LRU, Zipf: 70–85% of hits are the same experts) + **cold misses streamed** from NVMe (`~10–25 MB/layer`, `1.3–3 ms`) hidden behind hot-expert compute → target `~3–8 tok/s` |
| Prefill / speculative verify (`B=8..128`) | GPU compute `15–60 ms/layer` hides `70–500 MB/layer` DMA almost perfectly |
**Zero-copy pipeline ("GPUDirect Storage gratis" via UMA, M2):** CPU, NVMe
controller and GPU see the same physical memory. Ring of fixed aligned pages
(`mmap`, 4 KiB or `MAP_HUGETLB` 2 MiB) registered on both sides:
`io_uring O_DIRECT + IORING_REGISTER_BUFFERS` (NVMe DMA straight into the ring,
zero page-cache, zero CPU copies) and `hipHostRegister(..., Mapped)` (GPU
device pointer to the same pages, zero `hipMemcpy`). Triple-buffering
ping-pong: while the GPU computes layer `L` on `slot[L % 3]`, the DMA of
`L+1` is already in flight. Synchronization is per-slot `hipEvent` + a
dedicated `io_uring_wait_cqe` thread — never `hipDeviceSynchronize()`.
Optional striping across both NVMe (`~4.8 → ~9 GB/s`).
**Lookahead prefetch:** while layer `L` executes, the router of `L+1` applied
to the residual predicts `~70–85%` of the cold experts of `L+1` and starts
their DMA early (`PrefetchAdvisor::on_layer_routed`).
## 2. Pure Microkernel + Services
The microkernel contains **no model logic**. It does exactly three things:
service registry & lifecycle, a typed control bus, and the memory/DMA broker.
Inference engines are services on the bus, peers of loader/cache/network/telemetry.
- **Control plane:** typed messages on the bus (commands, events, domain hints,
STOP/cancellation, telemetry). Default transport is in-process (thread/task,
sub-microsecond); the contract allows out-of-process or Lyra transports later.
- **Data plane:** the hot GPU loop **never copies tensors through the bus**.
Services exchange only memory handles/capabilities granted by the UMA broker
(`SlabRing` slots + fences). Two services can never own the same buffer.
### Crate map (`vetta-infer-*`)
| Crate | Responsibility | `unsafe` |
| --- | --- | --- |
| `vetta-infer-abi` | Shared contracts: domain types, bus message formats, `.vplan` opcodes, wire-protocol types, pure checked parsers (JSON, vplan, GEN), sampling algorithms & Leviathan verifier, `DraftProvider`/`PrefetchAdvisor` traits. Zero external dependencies. | none |
| `vetta-infer-kn` | Microkernel: control bus, registry & lifecycle, STOP/cancellation, UMA/DMA broker (`SlabRing` + fence ownership). | none |
| `vetta-infer-ld` | Loader & compiler (dual-step): `ModelImporter` per family → canonical IR → `BackendPacker` per HW target → `.vbundle/`. Checked `.safetensors` reader, write-once pack. | none (pread via std) |
| `vetta-infer-cc` | Cache & storage: UMA residency, NVMe `io_uring O_DIRECT` streaming, Hot/Cold expert cache, domain pre-warm, `.vbundle` read-only reload. | `io_uring`/`pread` syscalls |
| `vetta-infer-rt` | Operational runtime: executes `CompiledPlan` on the HIP backend at full speed, zero probes on the hot path. Thin HIP FFI + fence-guarded buffers. | HIP FFI/DMA |
| `vetta-infer-lab` | Laboratory runtime: **the same executor as `rt`** (shared crate-internal core) with the probe-hook table from `probe.vplan` populated. Zero divergence by construction, not by discipline. | via rt core |
| `vetta-infer-sp` | Speculative coordinator: lossless verification, throughput-aware Adaptive-K (faithful port of `clover_policy.h`), local MTP/BD drafter or remote via `nt`. | none |
| `vetta-infer-nt` | LAN bridge to Lyra: remote drafting, domain routing, Vision/RAG offload (`LyraRpc`). | none |
| `vetta-infer-tm` | Telemetry: passive bus observer, lock-free capture, JSONL/SQLite sink, writes `stats/` profiles. | none |
| `vetta-infer-gw` | Gateway & CLI: `--serve` (strata-ctl compatible), HTTP OpenAI/Anthropic, `vetta-infer` binary (`info`, `serve`, `bench`, `stats`). | none |
`unsafe` is confined to `cc` (syscalls) and `rt` (HIP FFI/DMA). Everything else
is safe, CPU-testable Rust. Dependency rule: zero external deps in `abi`/`kn`
and all domain logic; audited crates allowed at the edges where correctness is
harder than the dependency risk (tokenizer: `tokenizers`; `io_uring`: `libc` or
a dedicated crate).
### Lyra control/co-processor split
Sogliola = heavy MoE compute plane; Lyra = control plane / co-processor.
Only tokens, metadata and hints (`<1 KB/step`, `~0.3 ms`) cross the LAN —
never per-layer tensors (no tensor parallelism: 64–128 AllReduce/token would
burn 20–40 ms/tok in latency alone).
1. **Remote drafter** (`DraftProvider` over `nt`): accepted tokens out
(`~48 B`), K proposals + K scalar probabilities back (`~64–128 B`) for
lossless Leviathan verification. A second physical GPU means target and
drafter never contend for VRAM/DRAM bandwidth; Lyra can pipeline drafting
(prepare the next block while Sogliola verifies the current one).
Constraint: the drafter must share the target's tokenizer.
2. **Semantic domain router** (30–80 ms classification): simple requests can
be answered by Lyra directly; complex ones activate the right specialist
on Sogliola — full model swap from NVMe (`~4 s`) or domain LoRA adapter
swap (100–400 MB, `20–80 ms`) on a resident base model.
3. **Domain-aware expert prefetch** (the fusion with NVMe streaming): `tm`
records which experts activate per domain (zero training); Lyra's hint
("Dante/letteratura") preloads the historical top-64 experts of that domain
into the Hot cache *during prefill* → `85–95%` hit rate from the first
token. Model math stays 100% exact: an out-of-domain expert still triggers
a normal NVMe miss.
## 3. Dual-Step Loader → `.vbundle/`
Streaming, two stages, **zero intermediate files**:
``` ```
┌───────────────┐ [.safetensors / config.json]
│ vetta-cli │ │ ModelImporter (1 per MoE family: Inkling / Clover / Qwen-MoE…)
└───────┬───────┘ ▼ canonical IR in memory (standard names L03.moe.e042.w13, topology, logical shape/dtype)
┌─────────┬───────┼───────┬───────────┐ │ BackendPacker (1 per HW target: rdna35-t16, …)
▼ ▼ ▼ ▼ ▼ ▼ packed directly into the inference-ready layout (4 KB aligned)
vetta-proto vetta-io vetta-hip vetta-telemetry [<model>.vbundle/] written once: .tmp.<pid> + fsync + rename; always O_RDONLY afterwards
└─────────┴───────┼───────┴───────────┘
▼
vetta-core
``` ```
- **`vetta-core`:** zero external dependencies. Defines `QuantFormat`, `TensorMeta`, `SlabRing`, `PrefixState`, `HybridPrefixPool`, `SamplingOpts`, zero-alloc `build_truncated_dist`, `sample_logits_exact`, `verify_draft_exact` (Leviathan lossless), `AdaptiveKController`, `HotColdExpertCache`, `DraftProvider` and `PrefetchAdvisor` traits. - New model = write only its `ModelImporter`. New HW/layout = write only its
- **`vetta-io`:** single checked `.safetensors` reader (`model.safetensors.index.json` + directory fallback + `pread` + overflow-safe slice checks) and single write-once `O_RDONLY` NVMe cache format (`VTC1`, FNV-1a fingerprint, pre-reserve count check, PID-isolated `.tmp.<pid>` atomic commit). `BackendPacker`. No model-specific code in any service.
- **`vetta-proto`:** single `strata-ctl`-compatible line protocol (`INFO`, `READY`, `GEN` including `GEN 0` pre-warm, `RESUME`, `PP`, `T`, `DONE`, `ERR`, `STOP`, `QUIT`, `RESET`) plus compact binary/text messages for Lyra LAN RPC (`DraftReq/DraftResp`, `DomainHint`). - `manifest.json` carries: model identity, source fingerprint (FNV-1a),
- **`vetta-telemetry`:** lock-free ring buffer + background JSONL writer collecting: **packer fingerprint + ABI version + backend target**. A bundle produced by
- per-layer MoE expert activation counts (Zipf curves) and `L -> L+1` transition frequencies; an incompatible packer/ABI is rejected explicitly, never misread.
- domain-tagged expert profiles (fed back to `PrefetchAdvisor` for NVMe Hot/Cold pre-warming);
- speculative acceptance histograms (`acc[0..=K]`), `ms/tok`, logit entropy, top1-top2 margin, cache hit/miss, DMA bandwidth.
- **`vetta-hip`:** thin FFI to `kernels/hip/` (compiled via ROCm `clang++ --offload-arch=gfx1150`) with RAII `DeviceBuf` / `PinnedUmaBuf` bound to HIP events/fences, plus a CPU mock backend for CI/unit testing without a GPU.
## 3. Minimal Reusable HIP Microkernel Set (`< 15` Primitives) ```
<model>.vbundle/
├── manifest.json # identity, source+packer fingerprints, ABI version, target (gfx1150)
├── weights/ # IMMUTABLE — write-once, then O_RDONLY | O_DIRECT
│ ├── trunk.vbin # always-resident: embed, norms, attn/GDN proj, router, shared, lm_head, vision
│ └── experts.vbin # MoE experts, 4 KB aligned for DMA (striping experts.0/1.vbin on dual NVMe)
├── plan/ # declarative "programs" (KB), compiled by ld for the services
│ ├── graph.vplan # flat micro-bytecode (~15–20 opcodes, 1:1 with HIP microkernels)
│ ├── memory.vplan # static arena plan (scratch/KV/GDN): exact offsets, validated before launch
│ ├── prefetch.vplan # program for cc: layer/expert preload order & priorities
│ └── probe.vplan # optional measurement program for lab
├── tokenizer/ # tokenizer + chat template + special IDs (EOS, mask, thinking)
└── stats/ # UPDATABLE (KB), never touches weights/
├── routing_zipf.bin # historical global Zipf curve → cc pins hot experts at boot
└── domains/ # per-domain profiles written by tm (lean4.json, dante.json, …)
```
The auto-optimization loop closes through `stats/`: `tm`/`lab` write profiles →
on next turn/boot `cc` (with Lyra domain hints) pre-warms the right experts.
GB-scale weights are never rewritten (0 SSD wear).
## 4. Microcode: `.vplan` → `CompiledPlan` at Boot
**Decision: lowering at boot, not interpretation, not codegen.**
- `graph.vplan` + `memory.vplan` (JSON, one uniform textual format with
manifest/stats, inspectable with `jq`) are lowered at `LoadModel` (< 2 ms)
into a flat array of `ResolvedOp`: device pointers, grids and parameters
already resolved. Zero strings, zero HashMaps, zero allocations per token.
- On decode `B=1` the resolved plan can be captured into a `hipGraphExec_t`
(critical: Inkling issues ~576 kernel launches/token).
- No runtime source generation/compiler: the AOT microkernels already reach
92.5% of DRAM bandwidth on a memory-bound part; codegen would add 10–40 s of
startup and a large debug surface for zero bandwidth gain.
- `memory.vplan` is **statically validated before the first GPU launch**:
no arena overlap, no use-before-write. The flat, non-Turing-complete opcode
set makes this formally verifiable in Lean 4 (§8).
- `rt` and `lab` execute the *identical* `CompiledPlan`; `lab` only interleaves
the observation points declared in `probe.vplan`.
### Initial opcode set (flat, fixed, 1:1 with microkernels)
`embed_bf16`, `rms_norm` (+residual/+1.0 offset flags), `quantize_x_g64`,
`gemm_q8_g64_t16`, `gemm_q4_g64_t16`, `gemm_nvfp4_mxfp8`, `rope_kv_write`,
`flash_gqa_wmma` (prefill / split-KV decode variants), `gdn_chunkwise_wy`,
`gdn_recurrent_step` (+history snapshot), `moe_route_bucket`, `moe_w13_wmma`
(fused SwiGLU+quantize), `moe_w2_wmma`, `moe_reduce`, `vit_flash_attn_wmma`,
`gpu_penalties_topk`. Control-flow opcodes are limited to `loop_layer` /
`branch_b` (batch-size dispatch) — no general computation in the plan.
## 5. Execution Engines
- **`rt` (operational):** zero probes, zero debug branching on the hot path.
- **`lab` (laboratory):** same executor core, probe hooks enabled. Used for
deep statistics collection without ever polluting `rt`.
- Both are services on the `kn` bus; a future backend (Vulkan/CUDA/RDNA4) is a
new `BackendPacker` + executor service, not a fork of the engine.
## 6. Wire Contract with strata-ctl (Principal Consumer)
Living consumer spec: `strata-ctl/src/engine/protocol.rs` + `supervisor.rs`.
The engine is a resident child process speaking lines on stdin/stdout,
**one request at a time** (FIFO, one conversation cache).
### Engine → consumer (stdout)
| Line | Semantics |
| --- | --- |
| `READY <ctx> [stop] [hold] [holdb]` | first meaningful line; real context size + honoured controls. `INFO` may precede it; `ERR` before `READY` = startup refusal |
| `INFO k=v …` | engine facts (version, expert slots, …), also mid-request |
| `T <id>` | one generated token id |
| `PP <read> <total> [ms] [tok_s]` | prefill progress, one per chunk |
| `RESUME <n>` | prompt tokens served from cache, not re-read |
| `DONE <gen> <prompt> <prompt_ms> <decode_ms> <finish> [extra…]` | fields 1–5 stable; tail raw (spec/cache/expert stats may grow without breaking the consumer) |
| `ERR <msg>` | request/command failed; may be followed by a trailing `DONE` (consumer swallows it) |
Unknown lines are preserved verbatim by the consumer (`Other`): the protocol
may grow forward-compatibly.
### Consumer → engine (stdin)
`GEN <max_new> [key=value …] <id,id,…>`, `STOP`, `QUIT` (also `BGEN <slot> …`
reserved). Keys emitted today by `Sampling::keys()`: `temperature` (>0 only),
`top_p` (<1 only), `top_k` (clamped 1..64, **0→64**), `min_p`,
`penalty_repeat/freq/present`, `penalty_last_n`, `seed` (>0), `image=<path>`
(repeatable, Vision). Floats use Python-repr spelling (`1.0`).
### Engine guarantees
1. `STOP` always terminates the in-flight request with a drainable `DONE`.
2. `GEN 0` = prefill + immediate `DONE` (pre-warm), never `ERR`.
3. `QUIT` exits the process promptly (clean shutdown, no hang).
4. Strict numeric/bounds parsing; unknown keys → `ERR` (explicit, never silent).
5. Non-finite logits are reported (`finish=nonfinite` / explicit count), never
silently masked.
### Known deltas to close in tandem (tracked, not silent)
- **`image=` key:** CLOSED on the parsing side (2026-11-30): `abi::serve`
accepts repeatable `image=<path>` keys in prompt order; `gw` emits the
consumer-compatible lines. Routing to GPU Vision lands with M1.
- **`top_k` clamp:** strata-ctl maps 0→64 and clamps to 64 (legacy engine
path). vetta-infer supports full-vocab `top_k=0` (F-09 fix) and GPU top-64
extraction; once `k_gpu_penalties_topk` lands, the consumer can drop the
clamp. Coordinate the change in both repos in the same review cycle.
- **`spec`/`domain`/`draft_top_k` keys:** engine-side extensions already
parsed by `abi`; strata-ctl does not emit them yet (its Python CLI sibling
did). Additive, no breakage.
## 7. Minimal Reusable HIP Microkernel Set (`< 15` Primitives)
1. `k_embed_bf16` — BF16 embedding gather 1. `k_embed_bf16` — BF16 embedding gather
2. `k_rms_norm` — fused RMSNorm (+ optional residual add / `+1.0` weight offset) 2. `k_rms_norm` — fused RMSNorm (+ optional residual add / `+1.0` weight offset)
@@ -42,15 +250,92 @@
6. `k_gemm_nvfp4_mxfp8` — direct Inkling NVFP4 / MXFP8 expert & trunk GEMM 6. `k_gemm_nvfp4_mxfp8` — direct Inkling NVFP4 / MXFP8 expert & trunk GEMM
7. `k_rope_kv_write` — rotary embedding + FP8/FP16 KV cache write (SWA ring or linear) 7. `k_rope_kv_write` — rotary embedding + FP8/FP16 KV cache write (SWA ring or linear)
8. `k_flash_gqa_wmma` — fused FlashAttention-2 / GQA prefill (`B >= 16`) & Split-KV decode (`B <= 2`) 8. `k_flash_gqa_wmma` — fused FlashAttention-2 / GQA prefill (`B >= 16`) & Split-KV decode (`B <= 2`)
9. `k_gdn_chunkwise_wy` — **Chunkwise Parallel GDN (WY-representation)** for `250–350+ ppts` prefill 9. `k_gdn_chunkwise_wy` — **Chunkwise Parallel GDN (WY-representation)** for `250–350+ ppts` prefill (new engineering; strata's sequential GDN is the measured bottleneck at ~95 ppts)
10. `k_gdn_recurrent_step` — 0-spill GDN decode + history snapshot for `<1 ms` speculative rollback 10. `k_gdn_recurrent_step` — 0-spill GDN decode + history snapshot for `<1 ms` speculative rollback
11. `k_moe_route_bucket` — 100% GPU MoE routing + bitonic coreset + NaN/mask-safe compaction (`0` host sync) 11. `k_moe_route_bucket` — 100% GPU MoE routing + bitonic coreset + NaN/mask-safe compaction (`0` host sync)
12. `k_moe_grouped_wmma` — compacted active-expert `w13` (fused SwiGLU + quantize) & `w2` + `k_moe_reduce` 12. `k_moe_grouped_wmma` — compacted active-expert `w13` (fused SwiGLU + quantize) & `w2` + `k_moe_reduce`
13. `k_vit_flash_attn_wmma` — `64×64` FP16 WMMA Vision encoder attention 13. `k_vit_flash_attn_wmma` — `64×64` FP16 WMMA Vision encoder attention
14. `k_gpu_penalties_topk` — GPU penalties + `top-64` extraction (`<= 512 B` D2H per row instead of `6–16 MB` with `temp > 0`!) 14. `k_gpu_penalties_topk` — GPU penalties + `top-64` extraction (`<= 512 B` D2H per row instead of `6–16 MB` with `temp > 0`)
## 4. Formal Contracts (`proofs/slab_ring_dma.lean`) Porting rule: strata kernels are the reference implementation; each ported
kernel ships a bit-exact parity test (as `clover_gpu_parity_test` did).
Verified with Lean `4.36.0` (`0 sorryAx`): ## 8. Formal Contracts (Lean 4)
- **`SlabRing` DMA safety:** mutual exclusion between `io_uring` host DMA writes and GPU kernel reads, mandatory fence completion before slot reclaim, conservation of slot count.
- **`PrefixState` & Checkpoint Grid:** strict soundness of multi-turn `RESUME` with/without MTP (`sc_mtp_hid_` can never be read uninitialized), and guaranteed checkpoint trigger on non-aligned post-`RESUME` prefill chunks. **Rule (Federico):** simple logic is written directly with CPU tests; complex
logic (state machines, rings, pools, speculative/rollback, arena plans) is
verified by the Lean kernel **before** implementation. `0 sorryAx`, standard
axioms only, `lean proofs/<file>.lean`.
Verified today (`proofs/slab_ring_dma.lean`, 10 theorems):
- **`SlabRing` DMA safety:** mutual exclusion `io_uring` writes / GPU reads,
fence-gated reclaim, slot isolation (eliminates audit F-01 by construction).
- **`PrefixState` soundness:** no uninitialized MTP hidden-state reuse (F-03).
- **Checkpoint grid:** guaranteed trigger on non-aligned post-`RESUME` chunks (F-06).
New obligations before the corresponding implementation:
- **`memory.vplan` arena safety:** no overlap, no use-before-write, offsets
within declared arenas (flat opcodes make this decidable). *(pending, M1)*
- **Bus lifecycle:** STOP/cancellation drains to a terminal state; no service
observes a half-committed registry entry. **VERIFIED** (`bus_lifecycle.lean`,
14 theorems) and implemented in `kn`.
- **Serve session lifecycle:** STOP always drains to DONE, `GEN 0` pre-warm
skips decode, tokens only while decoding, one DONE per request cycle.
**VERIFIED** (`serve_session.lean`, 10 theorems) and implemented in `gw`.
- **Adaptive-K exactness:** port `adaptive_spec_exact_vs_ar` from
`strata-clover/proofs/clover_gdn_ckpt.lean` to the faithful Rust controller.
*(controller ported with scenario parity tests; formal port pending)*
- **Hybrid GDN+KV restore:** port `restore_then_continue_equiv` /
`kv_only_restore_unsound` when the unified prefix pool lands (M2).
## 9. Migration Map (M0 → target)
**Status: completed 2026-11-30.** The M0 crates were dissolved into the target
crates below; the workspace is `vetta-infer-*` only, all CPU tests and Lean
proofs green, and the `vetta-infer` binary (now in `gw`) verified live on
Inkling (1244 tensors, 18.18 GiB, checked bounds).
| M0 source | Destination | Note |
| --- | --- | --- |
| `vetta-core::slab` | `kn` (broker) | state machine already Lean-verified |
| `vetta-core::prefix` | `rt` (pool) + `abi` (types) | extend to unified SWA+Full-KV+GDN pool in M2 |
| `vetta-core::sampler` | `abi` (pure algorithms) | used by rt/sp/gw; GPU path added by `k_gpu_penalties_topk` |
| `vetta-core::moe` | `cc` | Hot/Cold + pre-warm |
| `vetta-core::traits` (`AdaptiveKController`) | `sp` | **rewrite as faithful port of `clover_policy.h`** (cooldowns, probes, throughput guards) + parity tests |
| `vetta-core::traits` (`DraftProvider`, `PrefetchAdvisor`) | `abi` | unchanged |
| `vetta-io` (safetensors reader, VTC1 cache) | `ld` (pack) / `cc` (reload+stream) | checked parsers move to `abi` as pure functions |
| `vetta-proto` (serve parsing) | `abi` (types/parsers) + `gw` (emitter/lifecycle) | add `image=`, DONE/PP/RESUME emitters, STOP→DONE guarantee |
| `vetta-proto` (`LyraRpc`) | `nt` | unchanged |
| `vetta-telemetry` | `tm` | add `stats/` profile writer |
| `vetta-hip` (`UmaSlabPool`) | `kn` (ownership) + `rt` (FFI) | M2: real `mmap` + `hipHostRegister` + `io_uring` |
| `vetta-cli` | `gw` | binary stays `vetta-infer` |
| `kernels/hip/vetta_kernels.h` | unchanged | ABI grows with M1/M2 kernels |
## 10. Milestones
- **M0 (done):** workspace skeleton, Lean contracts, checked IO, serve parsing,
telemetry, HIP ABI — all audit-hardened, 11/11 CPU tests, 10/10 theorems.
- **M0.5 (current):** this specification + crate realignment to `vetta-infer-*`,
faithful policy ports with parity tests, wire-contract deltas closed.
- **M1 (Resident MoE End-to-End — Inkling-2-Mini):** HIP microkernels,
NVFP4/MXFP8 + `Q8_G64_T16` trunk, GPU Vision (`image=` key), write-once
`.vbundle`, strata-ctl drop-in `--serve` parity & speed vs C++ baseline
(`>= 18 tok/s`, `< 4 s` reload).
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN
(WY, `250–350+ ppts`), Clover-35B-A3B & MTP support, `io_uring O_DIRECT` +
`hipHostRegister` `SlabRing` ping-pong, Hot/Cold cache + lookahead prefetch,
unified hybrid prefix pool (Lean-verified restore). Goal: giant MoE
(120B–300B+) running on 96 GiB UMA via cold-expert streaming (`~3–8 tok/s`).
- **M3 (Distributed Control Plane — Lyra):** remote `DraftProvider` + domain
`PrefetchAdvisor` over LAN, telemetry-driven domain pre-warming.
## 11. Verification & Review Workflow
- Proofs: `lean proofs/<file>.lean` (0 `sorryAx`). CPU: `cargo test --workspace`
with `-D warnings`. GPU parity tests on Sogliola for every ported kernel.
- **Tandem:** the strata-ctl coder and the vetta-infer coder periodically
review each other's work; an external reviewer audits both. Wire-protocol
changes land in coordinated review cycles (§6 deltas).
- No silent regressions, no unmeasured claims: every performance number carries
hardware/model/flags. Commit prefixes: `[ABI]`, `[KN]`, `[LD]`, `[CC]`,
`[RT]`, `[LAB]`, `[SP]`, `[NT]`, `[TM]`, `[GW]`, `[Proofs]`, `[Docs]`.
+165
View File
@@ -0,0 +1,165 @@
/-!
proofs/bus_lifecycle.lean
Formal contracts for the `vetta-infer-kn` microkernel (docs/ARCHITECTURE.md §2, §8):
1. Service lifecycle: STOP/cancellation always drains to a terminal state,
never resurrects, never skips the draining phase.
2. Registry two-phase commit: a prepared id is fresh, a failed allocation
leaves zero ghost entries, commit only adds the prepared entry.
3. Bus delivery: messages are deliverable only to a `running` service.
Zero `sorryAx`; checked with `lean proofs/bus_lifecycle.lean`.
-/
namespace Vetta.Proofs.Bus
-- ============================================================================
-- 1. Service Lifecycle State Machine
-- ============================================================================
/-- Lifecycle of one registered service. `stopping` = STOP issued, draining
in-flight work; the service must reach `stopped` via an explicit drain ack. -/
inductive SvcState where
| registered -- entry committed, not yet started
| running -- accepting bus messages
| stopping -- STOP issued, draining (no new work accepted)
| stopped -- terminal: resources released
deriving DecidableEq, Repr
/-- Legal single-service transitions (mirrors `vetta_infer_kn::registry`). -/
inductive SvcStep : SvcState → SvcState → Prop where
| start : SvcStep .registered .running
| stop : SvcStep .running .stopping
| drain : SvcStep .stopping .stopped
| cancelReady : SvcStep .registered .stopped -- cancelled before start
/-- Reflexive-transitive closure of `SvcStep`. -/
inductive Steps : SvcState → SvcState → Prop where
| refl (s : SvcState) : Steps s s
| tail {s s' s'' : SvcState} : SvcStep s s' → Steps s' s'' → Steps s s''
/-- Theorem 1: `stopped` is terminal — no transition ever leaves it. -/
theorem stopped_terminal {s : SvcState} : ¬ SvcStep .stopped s := by
intro h; cases h
/-- Theorem 2: a draining service can never go back to `running`. -/
theorem no_resurrect_stopping : ¬ SvcStep .stopping .running := by
intro h; cases h
/-- Theorem 3: a stopped service can never go back to `running`. -/
theorem no_resurrect_stopped : ¬ SvcStep .stopped .running := by
intro h; cases h
/-- Theorem 4: `running` cannot jump straight to `stopped`: the drain phase
is mandatory (in-flight work is always observed before release). -/
theorem no_skip_drain : ¬ SvcStep .running .stopped := by
intro h; cases h
/-- Theorem 5: entering `stopping` is only possible from `running`
(STOP is only meaningful on a live service). -/
theorem stop_only_from_running {s : SvcState} (h : SvcStep s .stopping) :
s = .running := by
cases h; rfl
/-- Theorem 6: leaving `stopping` can only land in `stopped` (drain ack). -/
theorem drain_only_to_stopped {s : SvcState} (h : SvcStep .stopping s) :
s = .stopped := by
cases h; rfl
/-- Theorem 7 (progress): a running service always has a path to `stopped`. -/
theorem running_reaches_stopped : Steps .running .stopped :=
.tail .stop (.tail .drain (.refl .stopped))
/-- Theorem 8 (progress): a registered-but-not-started service can be
cancelled to `stopped` without ever running. -/
theorem registered_reaches_stopped : Steps .registered .stopped :=
.tail .cancelReady (.refl .stopped)
/-- Theorem 9 (progress): a draining service always has a path to `stopped`. -/
theorem stopping_reaches_stopped : Steps .stopping .stopped :=
.tail .drain (.refl .stopped)
-- ============================================================================
-- 2. Registry Two-Phase Commit (no ghost entries, fresh ids)
-- ============================================================================
/-- Committed registry entries only. A pending (prepared but not committed)
entry lives OUTSIDE this structure, so it is unobservable by construction. -/
structure Registry where
entries : List (Nat × SvcState)
nextId : Nat
/-- Well-formedness: every committed id was handed out before `nextId`. -/
def Registry.wf (r : Registry) : Prop :=
∀ p ∈ r.entries, p.1 < r.nextId
/-- Phase 1 (pure peek): the candidate id for a new service. No mutation. -/
def prepare (r : Registry) : Nat := r.nextId
/-- Phase 2: commit the prepared entry. Called ONLY after the service's
resources were successfully allocated (mirrors `commit_slot` discipline). -/
def commit (r : Registry) : Registry :=
{ entries := (r.nextId, .registered) :: r.entries, nextId := r.nextId + 1 }
/-- Theorem 10: the prepared id is fresh — it never collides with a committed entry. -/
theorem prepare_id_fresh (r : Registry) (hwf : r.wf) :
∀ p ∈ r.entries, p.1 ≠ prepare r := by
intro p hp heq
have hlt := hwf p hp
simp [prepare] at heq
omega
/-- Theorem 11: committing the prepared entry preserves well-formedness. -/
theorem commit_preserves_wf (r : Registry) (hwf : r.wf) : (commit r).wf := by
intro p hp
simp [commit] at hp ⊢
rcases hp with ⟨rfl, rfl⟩ | hp
· omega
· have := hwf p hp
omega
/-- Theorem 12: commit only ADDS the prepared entry; every pre-existing entry
is preserved untouched (a failed allocation that never calls `commit`
leaves the registry bit-identical — no half-committed state is observable). -/
theorem commit_only_adds (r : Registry) :
(commit r).entries = (r.nextId, .registered) :: r.entries := rfl
-- ============================================================================
-- 3. Bus Delivery Rules
-- ============================================================================
/-- A bus message is deliverable only to a running service. -/
def deliverable : SvcState → Bool
| .running => true
| _ => false
/-- Theorem 13: deliverability implies `running` — no message ever reaches a
registered, draining, or stopped service. -/
theorem deliver_only_running {s : SvcState} (h : deliverable s = true) :
s = .running := by
cases s <;> simp [deliverable] at h ⊢
/-- Theorem 14: STOP itself is accepted only where delivery is legal,
and it is exactly the transition into draining. -/
theorem stop_is_delivery_gated {s s' : SvcState} (h : SvcStep s s')
(hs : s' = .stopping) : deliverable s = true := by
subst hs
cases h
rfl
-- Axiom audit (all theorems must rely only on standard core axioms, 0 sorryAx)
#print axioms stopped_terminal
#print axioms no_resurrect_stopping
#print axioms no_resurrect_stopped
#print axioms no_skip_drain
#print axioms stop_only_from_running
#print axioms drain_only_to_stopped
#print axioms running_reaches_stopped
#print axioms registered_reaches_stopped
#print axioms stopping_reaches_stopped
#print axioms prepare_id_fresh
#print axioms commit_preserves_wf
#print axioms commit_only_adds
#print axioms deliver_only_running
#print axioms stop_is_delivery_gated
end Vetta.Proofs.Bus
+105
View File
@@ -0,0 +1,105 @@
/-!
proofs/serve_session.lean
Formal contract for the `vetta-infer-gw` `--serve` request lifecycle
(docs/ARCHITECTURE.md §6, consumer: strata-ctl/src/engine/supervisor.rs):
1. STOP from any active phase always drains to a DONE (never hangs).
2. `GEN 0` pre-warm reaches DONE without ever entering decode (no tokens).
3. Tokens are emitted only while decoding; a draining request emits none.
4. DONE is exited only to idle (one request cycle = one DONE).
Zero `sorryAx`; checked with `lean proofs/serve_session.lean`.
-/
namespace Vetta.Proofs.Serve
/-- Per-request lifecycle on the engine side. `done` = DONE emitted, awaiting
the next request; `stopping` = STOP received, draining in-flight work. -/
inductive ReqState where
| idle -- waiting for a command (prefix may be resident)
| prefilling -- GEN accepted, processing prompt chunks (PP/RESUME)
| decoding -- emitting T tokens
| stopping -- STOP received, draining to DONE
| done -- DONE emitted for this request
deriving DecidableEq, Repr
/-- Legal transitions (mirrors `vetta_infer_gw::session`). -/
inductive ReqStep : ReqState → ReqState → Prop where
| gen : ReqStep .idle .prefilling
| prefillComplete : ReqStep .prefilling .decoding -- max_new > 0
| prewarm : ReqStep .prefilling .done -- max_new == 0: DONE immediately
| finish : ReqStep .decoding .done -- stop / length / nonfinite
| stopPrefill : ReqStep .prefilling .stopping
| stopDecode : ReqStep .decoding .stopping
| drain : ReqStep .stopping .done
| nextRequest : ReqStep .done .idle
inductive Steps : ReqState → ReqState → Prop where
| refl (s : ReqState) : Steps s s
| tail {s s' s'' : ReqState} : ReqStep s s' → Steps s' s'' → Steps s s''
/-- Theorem 1: STOP is only meaningful on an active request (prefill/decode). -/
theorem stop_only_from_active {s : ReqState} (h : ReqStep s .stopping) :
s = .prefilling ∨ s = .decoding := by
cases h with
| stopPrefill => exact Or.inl rfl
| stopDecode => exact Or.inr rfl
/-- Theorem 2: STOP in idle is a no-op — it never enters draining. -/
theorem no_stop_in_idle : ¬ ReqStep .idle .stopping := by
intro h; cases h
/-- Theorem 3: leaving `stopping` can only land in `done` (the drain ack). -/
theorem drain_only_to_done {s : ReqState} (h : ReqStep .stopping s) :
s = .done := by
cases h; rfl
/-- Theorem 4 (STOP guarantee): a draining request always reaches DONE. -/
theorem stopping_reaches_done : Steps .stopping .done :=
.tail .drain (.refl .done)
/-- Theorem 5: a prefilling request always has a path to DONE (pre-warm direct). -/
theorem prefilling_reaches_done : Steps .prefilling .done :=
.tail .prewarm (.refl .done)
/-- Theorem 6: a decoding request always has a path to DONE. -/
theorem decoding_reaches_done : Steps .decoding .done :=
.tail .finish (.refl .done)
/-- Theorem 7 (GEN 0 pre-warm): prefill can reach DONE directly, skipping decode. -/
theorem prewarm_skips_decode : ReqStep .prefilling .done := .prewarm
/-- Theorem 8: DONE is exited only to idle — one request cycle yields one DONE. -/
theorem done_only_to_idle {s : ReqState} (h : ReqStep .done s) :
s = .idle := by
cases h; rfl
/-- Token emission is enabled only while decoding. -/
def emitsTokens : ReqState → Bool
| .decoding => true
| _ => false
/-- Theorem 9: tokens are emitted only in `decoding` — never while prefilling,
draining, or done. Combined with Theorem 3, a STOP'd request emits no token
between STOP and its DONE. -/
theorem tokens_only_decoding {s : ReqState} (h : emitsTokens s = true) :
s = .decoding := by
cases s <;> simp [emitsTokens] at h ⊢
/-- Theorem 10: idle is re-entered only from done (clean request boundary). -/
theorem idle_only_from_done {s : ReqState} (h : ReqStep s .idle) :
s = .done := by
cases h; rfl
-- Axiom audit (standard core axioms only, 0 sorryAx)
#print axioms stop_only_from_active
#print axioms no_stop_in_idle
#print axioms drain_only_to_done
#print axioms stopping_reaches_done
#print axioms prefilling_reaches_done
#print axioms decoding_reaches_done
#print axioms prewarm_skips_decode
#print axioms done_only_to_idle
#print axioms tokens_only_decoding
#print axioms idle_only_from_done
end Vetta.Proofs.Serve