commit 63b1668a92ebb1ad3e0df6fda606fff3059f5948 Author: iz0eyj Date: Sun Nov 29 21:32:44 2026 +0100 [Core] M0 foundation: workspace, Lean 4 SlabRing/PrefixState contracts, checked safetensors/cache IO, serve proto, telemetry, and HIP ABI diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fd91af7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target +**/*.rs.bk +*.o +*.a +*.so +*.tmp +*.tmp.* +.DS_Store diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..647e097 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,24 @@ +# AGENTS.md — vetta-infer + +Rules and engineering standards for working on `vetta-infer`. + +## 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). +- **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). +- **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) + +1. **DMA / Async Transfer Ownership:** never pass a stack variable or short-lived `Vec` to `hipMemcpyAsync` or `io_uring`. Every in-flight transfer owns or pins its `SlabSlot` until its completion fence/CQE is observed (verified in `proofs/slab_ring_dma.lean`). +2. **Checked Bounds Everywhere:** all `.safetensors` header offsets, slices, and NVMe disk-cache metadata counts MUST use checked integer arithmetic (`checked_add`, `checked_sub`, `count <= blob.len() / MIN_REC_BYTES`) before any allocation. +3. **Write-Once / `O_RDONLY` NVMe Caches:** caches are written atomically via `.tmp.` + `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. +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. + +## Verification Commands + +- Proofs: `lean proofs/slab_ring_dma.lean` +- CPU workspace tests: `cargo test --workspace` +- Commit prefixes: `[Core]`, `[IO]`, `[HIP]`, `[Proto]`, `[Telemetry]`, `[Proofs]`, `[Docs]` diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..61e58e4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "vetta-cli" +version = "0.1.0" +dependencies = [ + "vetta-core", + "vetta-hip", + "vetta-io", + "vetta-proto", + "vetta-telemetry", +] + +[[package]] +name = "vetta-core" +version = "0.1.0" + +[[package]] +name = "vetta-hip" +version = "0.1.0" +dependencies = [ + "vetta-core", +] + +[[package]] +name = "vetta-io" +version = "0.1.0" +dependencies = [ + "vetta-core", +] + +[[package]] +name = "vetta-proto" +version = "0.1.0" +dependencies = [ + "vetta-core", +] + +[[package]] +name = "vetta-telemetry" +version = "0.1.0" +dependencies = [ + "vetta-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..16910e6 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,21 @@ +[workspace] +resolver = "3" +members = [ + "crates/vetta-core", + "crates/vetta-io", + "crates/vetta-proto", + "crates/vetta-telemetry", + "crates/vetta-hip", + "crates/vetta-cli", +] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MIT" +authors = ["Federico"] + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 diff --git a/README.md b/README.md new file mode 100644 index 0000000..402329f --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# vetta-infer + +**MoE-first microkernel inference engine in Rust + minimal AMD ROCm HIP kernels.** + +Built from the measured hardware physics and engineering lessons of our hardened C++/HIP baseline ([`strata`](http://192.168.50.18:3000/iz0eyj/strata)), targeting unified-memory AMD RDNA 3.5 APUs (**Sogliola**: Ryzen AI 9 HX 370 / Radeon 890M `gfx1150`, 48 GiB VRAM carveout + 96 GiB UMA, 81.7 GB/s DRAM, 44 TFLOP/s INT8 WMMA, dual Gen4 NVMe) with optional LAN co-processing on **Lyra** (2.5 Gbps Ethernet). + +## Core Design Principles + +1. **MoE-first on UMA (`gfx1150`):** designed vertically around sparse Mixture-of-Experts architectures (Transformer SWA/Full + Vision, Hybrid GDN+GQA, native MTP / Block-Diffusion). +2. **Direct `.safetensors` + Write-Once `O_RDONLY` NVMe Cache:** zero GGUF conversion, zero SSD wear after initial atomic pack (`.tmp.` + `fsync` + `rename`), checked `u64` bounds everywhere. +3. **Zero-Copy UMA + NVMe DMA Streaming (`SlabRing`):** `io_uring O_DIRECT` into page-aligned buffers mapped directly to GPU via `hipHostRegister` (zero CPU copy, zero `hipMemcpy`), with Hot/Cold expert caching + lookahead prefetch for 100B–300B+ MoE models. +4. **Pure-Rust Control Plane + `<15` Reusable HIP Microkernels:** all scheduling, safetensors/cache I/O, wire protocol (`strata-ctl` compatible, including `GEN 0` pre-warm), deterministic zero-alloc sampling, speculative verification, and telemetry live in 100% CPU-testable Rust; GPU compute is isolated behind a thin C/HIP microkernel ABI. +5. **First-Class Inference Telemetry:** lock-free statistics capture (per-layer expert routing Zipf curves, `L -> L+1` co-activation transitions, domain profiles, speculative acceptance histograms, logit entropy, cache hit/miss, GPU phase timings) exported to JSONL with negligible runtime overhead. +6. **Lean 4 Verified State Machines:** every critical concurrency/lifetime/prefix invariant is modeled and machine-checked in Lean 4 (`proofs/`, 0 `sorryAx`) before implementation. +7. **LAN Control/Compute Split (Sogliola + Lyra):** pluggable `DraftProvider` and `PrefetchAdvisor` traits allow running remote speculative drafting, domain routing, or lightweight Vision/RAG on Lyra over 2.5 Gbps LAN (`< 1 KB/step`, `~0.3 ms` RTT). + +## Workspace Layout + +| 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-io` | Overflow-safe `.safetensors` reader (`index.json`, `pread`, strict bounds) and unified write-once `O_RDONLY` NVMe disk cache | +| `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-telemetry` | Lock-free inference telemetry collector (MoE routing histograms, `L -> L+1` transition matrix, speculative stats, JSONL sink) | +| `crates/vetta-hip` | Thin HIP FFI + `PinnedUmaBuf` fence-guarded ownership + CPU mock backend for headless unit tests | +| `crates/vetta-cli` | `vetta-infer` CLI binary (`info`, `serve`, `bench`, `stats`) | +| `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) | + +## 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. +- **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). +- **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. + +## Quick Verification + +```sh +# Lean 4 formal proofs (0 sorryAx) +lean proofs/slab_ring_dma.lean + +# Pure-Rust workspace tests (no GPU required) +cargo test --workspace +``` diff --git a/crates/vetta-cli/Cargo.toml b/crates/vetta-cli/Cargo.toml new file mode 100644 index 0000000..7a7bfba --- /dev/null +++ b/crates/vetta-cli/Cargo.toml @@ -0,0 +1,16 @@ +[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" } diff --git a/crates/vetta-cli/src/main.rs b/crates/vetta-cli/src/main.rs new file mode 100644 index 0000000..1b9d89c --- /dev/null +++ b/crates/vetta-cli/src/main.rs @@ -0,0 +1,65 @@ +//! `vetta-infer` CLI entrypoint. + +use std::collections::BTreeMap; +use std::env; +use std::process::ExitCode; +use vetta_io::SafetensorsArchive; + +fn usage() { + eprintln!("vetta-infer {} — MoE-first microkernel inference engine (Rust + HIP)", env!("CARGO_PKG_VERSION")); + eprintln!("Usage:"); + eprintln!(" vetta-infer info Inspect shards, dtypes, and checked bounds"); + eprintln!(" vetta-infer version Print version & build info"); +} + +fn cmd_info(dir: &str) -> Result<(), String> { + let t0 = std::time::Instant::now(); + let ar = SafetensorsArchive::open(dir)?; + let dt_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let mut by_dtype: BTreeMap = BTreeMap::new(); + for t in ar.tensors.values() { + let entry = by_dtype.entry(t.dtype.clone()).or_insert((0, 0)); + entry.0 += 1; + entry.1 += t.byte_len(); + } + + let tot_gib = ar.total_tensor_bytes() as f64 / (1024.0 * 1024.0 * 1024.0); + println!("dir: {}", ar.dir.display()); + println!("shards: {}", ar.shards.len()); + println!("tensors: {} (all bounds checked in {:.1} ms)", ar.tensors.len(), dt_ms); + println!("payload: {:.2} GiB", tot_gib); + println!("dtypes:"); + for (dt, (cnt, bytes)) in by_dtype { + println!(" {:10} {:6} tensors ({:6.2} GiB)", dt, cnt, bytes as f64 / (1024.0 * 1024.0 * 1024.0)); + } + Ok(()) +} + +fn main() -> ExitCode { + let args: Vec = env::args().skip(1).collect(); + match args.first().map(|s| s.as_str()) { + Some("version") | Some("--version") | Some("-V") => { + println!("vetta-infer {} (edition 2024, MoE-first HIP microkernel)", env!("CARGO_PKG_VERSION")); + ExitCode::SUCCESS + } + Some("info") => { + let Some(dir) = args.get(1) else { + eprintln!("error: missing "); + usage(); + return ExitCode::from(2); + }; + match cmd_info(dir) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } + } + _ => { + usage(); + ExitCode::from(2) + } + } +} diff --git a/crates/vetta-core/Cargo.toml b/crates/vetta-core/Cargo.toml new file mode 100644 index 0000000..1bb9d5f --- /dev/null +++ b/crates/vetta-core/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "vetta-core" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] diff --git a/crates/vetta-core/src/lib.rs b/crates/vetta-core/src/lib.rs new file mode 100644 index 0000000..2ce4161 --- /dev/null +++ b/crates/vetta-core/src/lib.rs @@ -0,0 +1,9 @@ +//! `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; diff --git a/crates/vetta-core/src/moe.rs b/crates/vetta-core/src/moe.rs new file mode 100644 index 0000000..7bcc9ac --- /dev/null +++ b/crates/vetta-core/src/moe.rs @@ -0,0 +1,155 @@ +//! 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, + free_slots: Vec, + 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)> { + 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, 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 { + 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]); + } +} diff --git a/crates/vetta-core/src/prefix.rs b/crates/vetta-core/src/prefix.rs new file mode 100644 index 0000000..941bc1c --- /dev/null +++ b/crates/vetta-core/src/prefix.rs @@ -0,0 +1,174 @@ +//! Typestate prefix tracking and hybrid GDN+KV checkpoint pool. +//! +//! Mirrors `PrefixState` and `nextCkptBoundary` in `proofs/slab_ring_dma.lean`: +//! eliminates uninitialized MTP hidden-state reuse (F-03) and ghost/skipped checkpoints (F-06). + +/// Explicit typestate of the live engine prefix on GPU. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PrefixState { + Empty, + TargetOnly { len: usize }, + TargetWithMtp { len: usize, mtp_len: usize }, +} + +impl PrefixState { + pub fn target_only(len: usize) -> Self { + if len == 0 { Self::Empty } else { Self::TargetOnly { len } } + } + + pub fn target_with_mtp(len: usize, mtp_len: usize) -> Result { + if len == 0 || mtp_len + 1 != len { + return Err("TargetWithMtp requires len > 0 and mtp_len + 1 == len"); + } + Ok(Self::TargetWithMtp { len, mtp_len }) + } + + pub fn len(&self) -> usize { + match *self { + Self::Empty => 0, + Self::TargetOnly { len } | Self::TargetWithMtp { len, .. } => len, + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn has_valid_mtp_hid(&self) -> bool { + matches!(self, Self::TargetWithMtp { .. }) + } + + /// Returns `true` iff this state can be strictly extended by a prompt of length `prompt_len`. + pub fn can_reuse(&self, prompt_len: usize, use_mtp: bool) -> bool { + match *self { + Self::Empty => false, + Self::TargetOnly { len } => !use_mtp && len < prompt_len, + Self::TargetWithMtp { len, .. } => len < prompt_len, + } + } +} + +/// Next checkpoint boundary strictly greater than `cur` on a grid of stride `stride > 0`. +pub fn next_ckpt_boundary(cur: usize, stride: usize) -> usize { + assert!(stride > 0, "checkpoint stride must be > 0"); + ((cur / stride) + 1) * stride +} + +#[derive(Debug, Clone)] +pub struct HybridCkptEntry { + pub slot: usize, + pub lru_tick: u64, + pub prefix: Vec, +} + +/// Metadata pool for GPU hybrid (SWA / Full-KV / GDN) prefix checkpoints. +/// Separates `peek_slot` from `commit_slot` so failed GPU allocations never leave ghost entries. +#[derive(Debug, Clone)] +pub struct HybridPrefixPool { + capacity: usize, + tick: u64, + entries: Vec, +} + +impl HybridPrefixPool { + pub fn new(capacity: usize) -> Self { + Self { + capacity: capacity.max(1), + tick: 0, + entries: Vec::new(), + } + } + + pub fn clear(&mut self) { + self.entries.clear(); + } + + pub fn entries(&self) -> &[HybridCkptEntry] { + &self.entries + } + + /// Longest strict prefix (`0 < entry.prefix.len() < prompt.len()`) matching `prompt`. + pub fn find_best_strict_prefix(&self, prompt: &[i32]) -> Option<&HybridCkptEntry> { + self.entries + .iter() + .filter(|e| !e.prefix.is_empty() && e.prefix.len() < prompt.len() && prompt.starts_with(&e.prefix)) + .max_by_key(|e| e.prefix.len()) + } + + /// Drops all checkpoints deeper than `limit` (must run whenever KV/GDN diverges at `limit`). + pub fn invalidate_above(&mut self, limit: usize) { + self.entries.retain(|e| e.prefix.len() <= limit); + } + + /// Selects a backing slot without mutating pool metadata. + pub fn peek_slot(&self, prefix: &[i32]) -> Option { + if prefix.is_empty() { + return None; + } + if let Some(e) = self.entries.iter().find(|e| e.prefix == prefix) { + return Some(e.slot); + } + if self.entries.len() < self.capacity { + let mut used = vec![false; self.capacity]; + for e in &self.entries { + if e.slot < self.capacity { + used[e.slot] = true; + } + } + return used.iter().position(|&u| !u); + } + self.entries.iter().min_by_key(|e| e.lru_tick).map(|e| e.slot) + } + + /// Commits metadata ONLY after GPU snapshot allocation & copy succeeded. + pub fn commit_slot(&mut self, slot: usize, prefix: Vec) { + if slot >= self.capacity || prefix.is_empty() { + return; + } + self.tick += 1; + if let Some(e) = self.entries.iter_mut().find(|e| e.slot == slot) { + e.lru_tick = self.tick; + e.prefix = prefix; + } else { + self.entries.push(HybridCkptEntry { + slot, + lru_tick: self.tick, + prefix, + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn f03_turn1_len1_no_mtp_cannot_reuse_with_mtp() { + let st = PrefixState::target_only(1); + assert!(!st.has_valid_mtp_hid()); + assert!(!st.can_reuse(5, true)); + assert!(st.can_reuse(5, false)); + + let st_mtp = PrefixState::target_with_mtp(4, 3).unwrap(); + assert!(st_mtp.has_valid_mtp_hid()); + assert!(st_mtp.can_reuse(5, true)); + assert!(!st_mtp.can_reuse(4, true)); // must be strict prefix + } + + #[test] + fn f06_non_aligned_ckpt_grid_and_two_phase_commit() { + assert_eq!(next_ckpt_boundary(125, 512), 512); + assert_eq!(next_ckpt_boundary(512, 512), 1024); + assert_eq!(next_ckpt_boundary(637, 512), 1024); + + let mut pool = HybridPrefixPool::new(2); + let s0 = pool.peek_slot(&[1, 2, 3]).unwrap(); + assert!(pool.entries().is_empty()); // failed GPU alloc leaves zero ghost entries + pool.commit_slot(s0, vec![1, 2, 3]); + assert_eq!(pool.entries().len(), 1); + assert_eq!(pool.find_best_strict_prefix(&[1, 2, 3, 4]).unwrap().slot, s0); + pool.invalidate_above(2); + assert!(pool.entries().is_empty()); + } +} diff --git a/crates/vetta-core/src/sampler.rs b/crates/vetta-core/src/sampler.rs new file mode 100644 index 0000000..f20f51e --- /dev/null +++ b/crates/vetta-core/src/sampler.rs @@ -0,0 +1,473 @@ +//! Deterministic zero-allocation top-K sampler, exact penalties, and Leviathan speculative verifier. +//! +//! Eliminates F-07 (centralized `mask_token_id` suppression) and F-09 (no 1 MiB/token heap churn, +//! no silent 256-token truncation for `top_k == 0`, explicit non-finite logit count). + +use std::cmp::Ordering; +use std::collections::{BinaryHeap, HashMap}; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SamplingOpts { + pub temperature: f32, + pub top_k: usize, + pub top_p: f32, + pub min_p: f32, + pub penalty_repeat: f32, + pub penalty_freq: f32, + pub penalty_present: f32, + pub penalty_last_n: usize, + pub seed: u64, +} + +impl Default for SamplingOpts { + fn default() -> Self { + Self { + temperature: 0.0, + top_k: 0, + top_p: 1.0, + min_p: 0.0, + penalty_repeat: 1.0, + penalty_freq: 0.0, + penalty_present: 0.0, + penalty_last_n: 64, + seed: 42, + } + } +} + +impl SamplingOpts { + pub fn is_greedy(&self) -> bool { + self.temperature <= 0.0 + } + + pub fn has_penalties(&self) -> bool { + self.penalty_last_n > 0 + && (self.penalty_repeat != 1.0 + || self.penalty_freq != 0.0 + || self.penalty_present != 0.0) + } +} + +/// SplitMix64 deterministic RNG (zero external crate deps, fast & reproducible). +#[derive(Debug, Clone)] +pub struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + pub fn new(seed: u64) -> Self { + Self { state: if seed == 0 { 0x9E37_79B9_7F4A_7C15 } else { seed } } + } + + pub fn next_u64(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Uniform float in `[0, 1)`. + pub fn next_f64(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 * (1.0 / ((1u64 << 53) as f64)) + } +} + +#[derive(Debug, Clone, Copy)] +struct Cand { + val: f32, + id: i32, +} + +impl PartialEq for Cand { + fn eq(&self, other: &Self) -> bool { + self.id == other.id && self.val.to_bits() == other.val.to_bits() + } +} +impl Eq for Cand {} + +/// Reverse order so `BinaryHeap` keeps the WORST candidate on top (min-heap of top-K). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct MinCand(Cand); + +impl Ord for MinCand { + fn cmp(&self, other: &Self) -> Ordering { + // Better = higher val, or equal val with smaller id. + // For min-heap, `other` better than `self` => self > other (so worst is popped first). + match other.0.val.total_cmp(&self.0.val) { + Ordering::Equal => self.0.id.cmp(&other.0.id), + ord => ord, + } + } +} + +impl PartialOrd for MinCand { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +fn cand_desc(a: &Cand, b: &Cand) -> Ordering { + match b.val.total_cmp(&a.val) { + Ordering::Equal => a.id.cmp(&b.id), + ord => ord, + } +} + +#[derive(Debug, Default, Clone)] +pub struct SamplerScratch { + pub idx: Vec, + pub prob: Vec, + cands: Vec, + counts: HashMap, +} + +#[derive(Debug, Clone, Copy, Default)] +pub struct SampleReport { + pub token: i32, + pub confidence: f32, + pub nonfinite_logits: usize, + pub entropy_nats: f32, +} + +pub fn suppress_token(logits: &mut [f32], banned: Option) { + if let Some(id) = banned { + if id >= 0 && (id as usize) < logits.len() { + logits[id as usize] = f32::NEG_INFINITY; + } + } +} + +pub fn apply_penalties(logits: &mut [f32], opts: &SamplingOpts, history: &[i32], scratch: &mut SamplerScratch) { + if !opts.has_penalties() || history.is_empty() || logits.is_empty() { + return; + } + scratch.counts.clear(); + let win = history.len().min(opts.penalty_last_n); + for &id in &history[history.len() - win..] { + if id >= 0 && (id as usize) < logits.len() { + *scratch.counts.entry(id).or_insert(0) += 1; + } + } + for (&id, &cnt) in &scratch.counts { + let v = &mut logits[id as usize]; + if !v.is_finite() { + continue; + } + if opts.penalty_repeat != 1.0 { + *v = if *v > 0.0 { *v / opts.penalty_repeat } else { *v * opts.penalty_repeat }; + } + if opts.penalty_freq != 0.0 { + *v -= opts.penalty_freq * (cnt as f32); + } + if opts.penalty_present != 0.0 { + *v -= opts.penalty_present; + } + } +} + +/// Builds a normalized/unnormalized truncated distribution into `scratch.{idx, prob}`. +/// Returns the number of non-finite logits encountered. +pub fn build_truncated_dist( + logits: &mut [f32], + opts: &SamplingOpts, + history: &[i32], + banned: Option, + scratch: &mut SamplerScratch, +) -> usize { + scratch.idx.clear(); + scratch.prob.clear(); + if logits.is_empty() { + return 0; + } + suppress_token(logits, banned); + apply_penalties(logits, opts, history, scratch); + + let v = logits.len(); + let mut nonfinite = 0usize; + let mut mx = f32::NEG_INFINITY; + for &val in logits.iter() { + if !val.is_finite() { + if val.is_nan() || val.is_infinite() && val.is_sign_positive() { + nonfinite += 1; + } + } else if val > mx { + mx = val; + } + } + if !mx.is_finite() { + scratch.idx.push(0); + scratch.prob.push(1.0); + return nonfinite; + } + + let inv_t = 1.0f64 / (opts.temperature as f64).max(1e-6); + + scratch.cands.clear(); + if opts.top_k > 0 && opts.top_k < v && opts.top_k <= 512 { + let mut heap: BinaryHeap = BinaryHeap::with_capacity(opts.top_k + 1); + for (i, &val) in logits.iter().enumerate() { + if !val.is_finite() { + continue; + } + let c = MinCand(Cand { val, id: i as i32 }); + if heap.len() < opts.top_k { + heap.push(c); + } else if let Some(&top) = heap.peek() { + if cand_desc(&c.0, &top.0) == Ordering::Less { + heap.pop(); + heap.push(c); + } + } + } + scratch.cands.extend(heap.into_iter().map(|m| m.0)); + scratch.cands.sort_unstable_by(cand_desc); + } else { + let logit_floor = if opts.min_p > 0.0 && opts.min_p < 1.0 && opts.top_k == 0 { + (mx as f64 + (opts.min_p as f64).ln() / inv_t) as f32 + } else { + f32::NEG_INFINITY + }; + for (i, &val) in logits.iter().enumerate() { + if !val.is_finite() { + continue; + } + if val < logit_floor && val < mx { + continue; + } + scratch.cands.push(Cand { val, id: i as i32 }); + } + if scratch.cands.is_empty() { + scratch.idx.push(0); + scratch.prob.push(1.0); + return nonfinite; + } + let need_sort = (opts.top_k > 0 && opts.top_k < scratch.cands.len()) + || (opts.top_p > 0.0 && opts.top_p < 1.0); + if opts.top_k > 0 && opts.top_k < scratch.cands.len() { + scratch.cands.select_nth_unstable_by(opts.top_k, cand_desc); + scratch.cands.truncate(opts.top_k); + scratch.cands.sort_unstable_by(cand_desc); + } else if need_sort { + scratch.cands.sort_unstable_by(cand_desc); + } + } + + let mut p_max = 0.0f64; + let mut z = 0.0f64; + for c in &scratch.cands { + let w = (((c.val as f64) - (mx as f64)) * inv_t).exp(); + if w > p_max { + p_max = w; + } + scratch.idx.push(c.id); + scratch.prob.push(w); + z += w; + } + if z <= 0.0 { + let first = scratch.idx.first().copied().unwrap_or(0); + scratch.idx.clear(); + scratch.prob.clear(); + scratch.idx.push(first); + scratch.prob.push(1.0); + return nonfinite; + } + + if opts.min_p > 0.0 && opts.min_p < 1.0 { + let thresh = (opts.min_p as f64) * p_max; + let mut keep = 0usize; + for i in 0..scratch.idx.len() { + if i == 0 || scratch.prob[i] >= thresh { + scratch.idx[keep] = scratch.idx[i]; + scratch.prob[keep] = scratch.prob[i]; + keep += 1; + } + } + scratch.idx.truncate(keep); + scratch.prob.truncate(keep); + } + + if opts.top_p > 0.0 && opts.top_p < 1.0 && scratch.idx.len() > 1 { + let z2: f64 = scratch.prob.iter().sum(); + let inv_z2 = 1.0 / z2.max(1e-30); + let mut cum = 0.0f64; + let mut keep = scratch.idx.len(); + for i in 0..scratch.idx.len() { + cum += scratch.prob[i] * inv_z2; + if cum >= opts.top_p as f64 { + keep = i + 1; + break; + } + } + scratch.idx.truncate(keep); + scratch.prob.truncate(keep); + } + nonfinite +} + +pub fn sample_logits_exact( + logits: &mut [f32], + opts: &SamplingOpts, + history: &[i32], + banned: Option, + rng: &mut SplitMix64, + scratch: &mut SamplerScratch, +) -> SampleReport { + if logits.is_empty() { + return SampleReport { token: 0, confidence: 1.0, nonfinite_logits: 0, entropy_nats: 0.0 }; + } + if opts.is_greedy() { + suppress_token(logits, banned); + apply_penalties(logits, opts, history, scratch); + let mut best_id = 0i32; + let mut mx = f32::NEG_INFINITY; + let mut nonfinite = 0usize; + for (i, &val) in logits.iter().enumerate() { + if !val.is_finite() { + if val.is_nan() || (val.is_infinite() && val.is_sign_positive()) { + nonfinite += 1; + } + } else if val > mx { + mx = val; + best_id = i as i32; + } + } + let mut z = 0.0f64; + let mut h = 0.0f64; + if mx.is_finite() { + for &val in logits.iter() { + if val.is_finite() { + let w = ((val - mx) as f64).exp(); + z += w; + } + } + if z > 0.0 { + for &val in logits.iter() { + if val.is_finite() { + let p = ((val - mx) as f64).exp() / z; + if p > 1e-12 { + h -= p * p.ln(); + } + } + } + } + } + return SampleReport { + token: best_id, + confidence: if z > 0.0 { (1.0 / z) as f32 } else { 1.0 }, + nonfinite_logits: nonfinite, + entropy_nats: h as f32, + }; + } + + let nonfinite = build_truncated_dist(logits, opts, history, banned, scratch); + let z: f64 = scratch.prob.iter().sum(); + let inv_z = 1.0 / z.max(1e-30); + let mut h = 0.0f64; + for &w in &scratch.prob { + let p = w * inv_z; + if p > 1e-12 { + h -= p * p.ln(); + } + } + let r = rng.next_f64() * z; + let mut c = 0.0f64; + let mut chosen = scratch.idx[0]; + let mut chosen_p = scratch.prob[0] * inv_z; + for i in 0..scratch.idx.len() { + c += scratch.prob[i]; + if r <= c { + chosen = scratch.idx[i]; + chosen_p = scratch.prob[i] * inv_z; + break; + } + } + SampleReport { + token: chosen, + confidence: chosen_p as f32, + nonfinite_logits: nonfinite, + entropy_nats: h as f32, + } +} + +/// Lossless Leviathan speculative verification (exact target distribution `p(x)`). +/// Returns `(emitted_token, accepted)`. +pub fn verify_draft_exact( + logits: &mut [f32], + opts: &SamplingOpts, + history: &[i32], + banned: Option, + rng: &mut SplitMix64, + draft_tok: i32, + scratch: &mut SamplerScratch, +) -> (i32, bool) { + if opts.is_greedy() { + let rep = sample_logits_exact(logits, opts, history, banned, rng, scratch); + return (rep.token, rep.token == draft_tok); + } + let _ = build_truncated_dist(logits, opts, history, banned, scratch); + let z: f64 = scratch.prob.iter().sum(); + if z <= 0.0 || scratch.idx.is_empty() { + return (draft_tok, true); + } + let dpos = scratch.idx.iter().position(|&id| id == draft_tok); + let p_draft = dpos.map(|i| scratch.prob[i] / z).unwrap_or(0.0); + if dpos.is_some() && (scratch.idx.len() == 1 || rng.next_f64() < p_draft) { + return (draft_tok, true); + } + let z_rem = z - dpos.map(|i| scratch.prob[i]).unwrap_or(0.0); + if z_rem <= 0.0 { + return match dpos { + Some(_) => (draft_tok, true), + None => (scratch.idx[0], false), + }; + } + let r = rng.next_f64() * z_rem; + let mut c = 0.0f64; + let mut last_valid = scratch.idx[0]; + for i in 0..scratch.idx.len() { + if Some(i) == dpos { + continue; + } + last_valid = scratch.idx[i]; + c += scratch.prob[i]; + if r <= c { + return (scratch.idx[i], false); + } + } + (last_valid, false) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn top_k_tie_break_and_no_256_cap_for_top_p() { + let mut sc = SamplerScratch::default(); + let mut lg = vec![0.0f32; 600]; + lg[500] = 5.0; + lg[10] = 5.0; + lg[300] = 4.0; + let opts = SamplingOpts { temperature: 1.0, top_k: 3, ..Default::default() }; + let nf = build_truncated_dist(&mut lg, &opts, &[], None, &mut sc); + assert_eq!(nf, 0); + assert_eq!(sc.idx, vec![10, 500, 300]); + + // 400 uniform tokens with top_k=0, top_p=0.9 -> keeps ~360 tokens (not truncated at 256!) + let mut unif = vec![1.0f32; 400]; + let opts_u = SamplingOpts { temperature: 1.0, top_k: 0, top_p: 0.9, ..Default::default() }; + build_truncated_dist(&mut unif, &opts_u, &[], None, &mut sc); + assert!((359..=361).contains(&sc.idx.len())); + } + + #[test] + fn nonfinite_reported_and_mask_suppressed() { + let mut sc = SamplerScratch::default(); + let mut rng = SplitMix64::new(7); + let mut lg = vec![1.0, f32::NAN, 9.0, 5.0]; + let rep = sample_logits_exact(&mut lg, &SamplingOpts::default(), &[], Some(2), &mut rng, &mut sc); + assert_eq!(rep.nonfinite_logits, 1); + assert_eq!(rep.token, 3); // token 2 was suppressed + } +} diff --git a/crates/vetta-core/src/slab.rs b/crates/vetta-core/src/slab.rs new file mode 100644 index 0000000..ed0a339 --- /dev/null +++ b/crates/vetta-core/src/slab.rs @@ -0,0 +1,163 @@ +//! Fence-guarded `SlabRing` DMA ownership state machine. +//! +//! Directly implements the transitions verified in `proofs/slab_ring_dma.lean`: +//! `Free -> IoInFlight -> GpuReady -> GpuInUse -> Free`. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SlotState { + Free, + IoInFlight { req_id: u64 }, + GpuReady { tag: u64 }, + GpuInUse { tag: u64, fence: u64 }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SlabError { + OutOfBounds { idx: usize, cap: usize }, + InvalidTransition { idx: usize, state: SlotState, op: &'static str }, + TagMismatch { idx: usize, expected: u64, actual: u64 }, + FenceMismatch { idx: usize, expected: u64, actual: u64 }, + NoFreeSlot, +} + +impl std::fmt::Display for SlabError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} + +impl std::error::Error for SlabError {} + +/// Tracks ownership of `N` page-aligned zero-copy UMA buffers shared between `io_uring` and HIP. +#[derive(Debug, Clone)] +pub struct SlabRing { + slots: Vec, + slot_bytes: usize, +} + +impl SlabRing { + pub fn new(num_slots: usize, slot_bytes: usize) -> Self { + assert!(num_slots > 0, "SlabRing requires at least 1 slot"); + Self { + slots: vec![SlotState::Free; num_slots], + slot_bytes, + } + } + + pub fn len(&self) -> usize { + self.slots.len() + } + + pub fn is_empty(&self) -> bool { + self.slots.is_empty() + } + + pub fn slot_bytes(&self) -> usize { + self.slot_bytes + } + + pub fn state(&self, idx: usize) -> Result { + self.slots + .get(idx) + .copied() + .ok_or(SlabError::OutOfBounds { idx, cap: self.slots.len() }) + } + + pub fn find_free(&self) -> Option { + self.slots.iter().position(|&s| s == SlotState::Free) + } + + pub fn submit_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> { + let s = self.state(idx)?; + if s != SlotState::Free { + return Err(SlabError::InvalidTransition { idx, state: s, op: "submit_io" }); + } + self.slots[idx] = SlotState::IoInFlight { req_id }; + Ok(()) + } + + pub fn complete_io(&mut self, idx: usize, req_id: u64, tag: u64) -> Result<(), SlabError> { + match self.state(idx)? { + SlotState::IoInFlight { req_id: cur } if cur == req_id => { + self.slots[idx] = SlotState::GpuReady { tag }; + Ok(()) + } + other => Err(SlabError::InvalidTransition { idx, state: other, op: "complete_io" }), + } + } + + pub fn abort_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> { + match self.state(idx)? { + SlotState::IoInFlight { req_id: cur } if cur == req_id => { + self.slots[idx] = SlotState::Free; + Ok(()) + } + other => Err(SlabError::InvalidTransition { idx, state: other, op: "abort_io" }), + } + } + + pub fn launch_gpu(&mut self, idx: usize, expected_tag: u64, fence: u64) -> Result<(), SlabError> { + match self.state(idx)? { + SlotState::GpuReady { tag } if tag == expected_tag => { + self.slots[idx] = SlotState::GpuInUse { tag, fence }; + Ok(()) + } + SlotState::GpuReady { tag } => { + Err(SlabError::TagMismatch { idx, expected: expected_tag, actual: tag }) + } + other => Err(SlabError::InvalidTransition { idx, state: other, op: "launch_gpu" }), + } + } + + pub fn discard_ready(&mut self, idx: usize) -> Result<(), SlabError> { + match self.state(idx)? { + SlotState::GpuReady { .. } => { + self.slots[idx] = SlotState::Free; + Ok(()) + } + other => Err(SlabError::InvalidTransition { idx, state: other, op: "discard_ready" }), + } + } + + pub fn complete_gpu(&mut self, idx: usize, fence: u64) -> Result<(), SlabError> { + match self.state(idx)? { + SlotState::GpuInUse { fence: cur, .. } if cur == fence => { + self.slots[idx] = SlotState::Free; + Ok(()) + } + SlotState::GpuInUse { fence: cur, .. } => { + Err(SlabError::FenceMismatch { idx, expected: cur, actual: fence }) + } + other => Err(SlabError::InvalidTransition { idx, state: other, op: "complete_gpu" }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_ping_pong_lifecycle_and_safety() { + let mut ring = SlabRing::new(3, 4 * 1024 * 1024); + let s0 = ring.find_free().unwrap(); + assert_eq!(s0, 0); + + // Cannot launch GPU before DMA completes + assert!(ring.launch_gpu(s0, 10, 1).is_err()); + + ring.submit_io(s0, 100).unwrap(); + // Cannot launch GPU while IO is still in flight + assert!(ring.launch_gpu(s0, 10, 1).is_err()); + + ring.complete_io(s0, 100, 10).unwrap(); + // Cannot overwrite with new IO while GpuReady or GpuInUse + assert!(ring.submit_io(s0, 101).is_err()); + + ring.launch_gpu(s0, 10, 42).unwrap(); + assert!(ring.submit_io(s0, 102).is_err()); + assert!(ring.complete_gpu(s0, 999).is_err()); // wrong fence rejected + ring.complete_gpu(s0, 42).unwrap(); + assert_eq!(ring.state(s0).unwrap(), SlotState::Free); + } +} diff --git a/crates/vetta-core/src/traits.rs b/crates/vetta-core/src/traits.rs new file mode 100644 index 0000000..c0eba47 --- /dev/null +++ b/crates/vetta-core/src/traits.rs @@ -0,0 +1,105 @@ +//! 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, + /// Optional scalar draft probabilities `q(x_j)` for lossless non-greedy Leviathan verification. + pub draft_probs: Option>, +} + +/// 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; + 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; + fn on_layer_routed(&mut self, layer: u16, active_experts: &[u16]) -> Vec; +} + +/// 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; + } + } +} diff --git a/crates/vetta-hip/Cargo.toml b/crates/vetta-hip/Cargo.toml new file mode 100644 index 0000000..5e8845f --- /dev/null +++ b/crates/vetta-hip/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "vetta-hip" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +vetta-core = { path = "../vetta-core" } diff --git a/crates/vetta-hip/src/lib.rs b/crates/vetta-hip/src/lib.rs new file mode 100644 index 0000000..7b77491 --- /dev/null +++ b/crates/vetta-hip/src/lib.rs @@ -0,0 +1,105 @@ +//! `vetta-hip`: thin HIP microkernel boundary & fence-guarded zero-copy UMA ring buffers. +//! +//! All unsafe GPU/DMA lifetime invariants are mediated by `vetta_core::slab::SlabRing` +//! (formally verified in `proofs/slab_ring_dma.lean`). + +use vetta_core::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. +/// 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 { + ring: SlabRing, + buffers: Vec>, + next_req_id: u64, + next_fence_id: u64, +} + +impl UmaSlabPool { + pub fn new(num_slots: usize, slot_bytes: usize) -> Self { + let mut buffers = Vec::with_capacity(num_slots); + for _ in 0..num_slots { + buffers.push(vec![0u8; slot_bytes]); + } + Self { + ring: SlabRing::new(num_slots, slot_bytes), + buffers, + next_req_id: 1, + next_fence_id: 1, + } + } + + pub fn slot_state(&self, idx: usize) -> Result { + self.ring.state(idx) + } + + /// Acquires a free slot and enters `IoInFlight`, returning `(slot_idx, req_id, &mut [u8])`. + /// No GPU kernel can read this slot until `complete_io` transitions it to `GpuReady`. + pub fn begin_io(&mut self) -> Result<(usize, u64, &mut [u8]), SlabError> { + let idx = self.ring.find_free().ok_or(SlabError::NoFreeSlot)?; + let req_id = self.next_req_id; + self.next_req_id += 1; + self.ring.submit_io(idx, req_id)?; + Ok((idx, req_id, self.buffers[idx].as_mut_slice())) + } + + pub fn complete_io(&mut self, idx: usize, req_id: u64, tag: u64) -> Result<(), SlabError> { + self.ring.complete_io(idx, req_id, tag) + } + + pub fn abort_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> { + self.ring.abort_io(idx, req_id) + } + + /// Transitions a `GpuReady` slot to `GpuInUse` and returns `(fence_id, &[u8])`. + /// The slot cannot be reused for DMA until `complete_gpu(idx, fence_id)` is called. + pub fn launch_gpu(&mut self, idx: usize, expected_tag: u64) -> Result<(u64, &[u8]), SlabError> { + let fence = self.next_fence_id; + self.next_fence_id += 1; + self.ring.launch_gpu(idx, expected_tag, fence)?; + Ok((fence, self.buffers[idx].as_slice())) + } + + pub fn complete_gpu(&mut self, idx: usize, fence: u64) -> Result<(), SlabError> { + self.ring.complete_gpu(idx, fence) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uma_slab_pool_enforces_dma_gpu_exclusion() { + let mut pool = UmaSlabPool::new(2, 4096); + let (s0, req0, buf0) = pool.begin_io().unwrap(); + buf0[0] = 0xAB; + // Cannot launch GPU before IO completes + assert!(pool.launch_gpu(s0, 77).is_err()); + + pool.complete_io(s0, req0, 77).unwrap(); + let (fence, ro) = pool.launch_gpu(s0, 77).unwrap(); + assert_eq!(ro[0], 0xAB); + + // Slot 0 is GpuInUse so begin_io must hand out Slot 1 + let (s1, req1, _) = pool.begin_io().unwrap(); + assert_eq!(s1, 1); + // Pool is now full (s0=GpuInUse, s1=IoInFlight) + assert_eq!(pool.begin_io().unwrap_err(), SlabError::NoFreeSlot); + + pool.complete_gpu(s0, fence).unwrap(); + assert_eq!(pool.slot_state(s0).unwrap(), SlotState::Free); + pool.abort_io(s1, req1).unwrap(); + assert_eq!(pool.slot_state(s1).unwrap(), SlotState::Free); + } +} diff --git a/crates/vetta-io/Cargo.toml b/crates/vetta-io/Cargo.toml new file mode 100644 index 0000000..150a4a0 --- /dev/null +++ b/crates/vetta-io/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "vetta-io" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +vetta-core = { path = "../vetta-core" } diff --git a/crates/vetta-io/src/lib.rs b/crates/vetta-io/src/lib.rs new file mode 100644 index 0000000..6272d67 --- /dev/null +++ b/crates/vetta-io/src/lib.rs @@ -0,0 +1,804 @@ +//! `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.` 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), + Obj(HashMap), +} + +impl JsonVal { + pub fn as_obj(&self) -> Option<&HashMap> { + 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 { + 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 { + 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 { + 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::() { + return Ok(JsonVal::Int(u)); + } + } + let f = s.parse::().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 { + 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, + 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, + pub tensors: HashMap, +} + +const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024; + +impl SafetensorsArchive { + pub fn open(dir: impl AsRef) -> Result { + 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, 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 { + 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 { + 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, 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, + fingerprint: u64, + cursor: u64, + records: Vec, +} + +impl DiskCacheWriter { + pub fn begin(final_path: impl AsRef, fingerprint: u64) -> Result { + 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 { + 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 { + 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, +} + +impl DiskCacheReader { + pub fn open_and_validate(path: impl AsRef, expected_fp: u64) -> Result { + 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); + } +} diff --git a/crates/vetta-proto/Cargo.toml b/crates/vetta-proto/Cargo.toml new file mode 100644 index 0000000..0955e87 --- /dev/null +++ b/crates/vetta-proto/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "vetta-proto" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +vetta-core = { path = "../vetta-core" } diff --git a/crates/vetta-proto/src/lib.rs b/crates/vetta-proto/src/lib.rs new file mode 100644 index 0000000..10397be --- /dev/null +++ b/crates/vetta-proto/src/lib.rs @@ -0,0 +1,175 @@ +//! `vetta-proto`: unified `--serve` wire protocol (`strata-ctl` compatible, including `GEN 0` pre-warm) +//! and lightweight Lyra LAN control-plane message schemas. + +use vetta_core::sampler::SamplingOpts; + +#[derive(Debug, Clone, PartialEq)] +pub enum ServeCommand { + Gen(ParsedGen), + Reset, + Stop, + Quit, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ParsedGen { + pub max_new: usize, + pub sampling: SamplingOpts, + /// `None` = engine default, `Some(0)` = AR off, `Some(1)` = adaptive, `Some(k)` = fixed k + pub spec_mode: Option, + pub draft_top_k: Option, + pub domain_hint: Option, + pub ids: Vec, +} + +pub fn parse_id_csv(csv: &str, vocab_size: usize) -> Result, String> { + if csv.is_empty() { + return Err("empty token id list".into()); + } + let mut out = Vec::new(); + for piece in csv.split(',') { + if piece.is_empty() { + return Err("empty token id in CSV".into()); + } + let id: u64 = piece + .parse() + .map_err(|_| format!("invalid token id '{piece}'"))?; + if id >= vocab_size as u64 { + return Err(format!("token id {id} out of vocab bounds [0, {vocab_size})")); + } + out.push(id as i32); + } + Ok(out) +} + +pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result { + let trimmed = line.trim(); + match trimmed { + "QUIT" | "EXIT" => return Ok(ServeCommand::Quit), + "RESET" | "CLEAR" => return Ok(ServeCommand::Reset), + "STOP" => return Ok(ServeCommand::Stop), + _ => {} + } + let toks: Vec<&str> = trimmed.split_whitespace().collect(); + if toks.len() < 3 || toks[0] != "GEN" { + return Err("GEN: expected 'GEN [key=val ...] '".into()); + } + let max_new: u64 = toks[1].parse().map_err(|_| "GEN: bad max_new".to_string())?; + if max_new > 1_000_000 { + return Err("GEN: max_new out of range".into()); + } + + let mut sampling = SamplingOpts::default(); + let mut spec_mode = None; + let mut draft_top_k = None; + let mut domain_hint = None; + + for &kv in &toks[2..toks.len() - 1] { + let (k, v) = kv + .split_once('=') + .ok_or_else(|| format!("GEN: bad key=value '{kv}'"))?; + if k.is_empty() || v.is_empty() { + return Err(format!("GEN: bad key=value '{kv}'")); + } + match k { + "spec" => { + spec_mode = Some(match v { + "auto" | "adapt" => 1, + "off" | "ar" | "0" => 0, + _ => { + let n: usize = v.parse().map_err(|_| format!("GEN: bad spec={v}"))?; + if n > 32 { + return Err(format!("GEN: spec={v} > 32")); + } + n + } + }); + } + "domain" => { + domain_hint = Some(v.to_string()); + } + "seed" => { + sampling.seed = v.parse().map_err(|_| "GEN: bad seed".to_string())?; + } + "temperature" | "temp" => { + let d = parse_finite_f32(v, k)?; + sampling.temperature = d.max(0.0); + } + "top_p" => { + sampling.top_p = parse_finite_f32(v, k)?.clamp(0.0, 1.0); + } + "top_k" => { + let n: i64 = v.parse().map_err(|_| format!("GEN: bad {k}"))?; + sampling.top_k = if n <= 0 { 0 } else { n as usize }; + } + "min_p" => { + sampling.min_p = parse_finite_f32(v, k)?.clamp(0.0, 1.0); + } + "penalty_repeat" | "repetition_penalty" => { + sampling.penalty_repeat = parse_finite_f32(v, k)?; + } + "penalty_freq" | "frequency_penalty" => { + sampling.penalty_freq = parse_finite_f32(v, k)?; + } + "penalty_present" | "presence_penalty" => { + sampling.penalty_present = parse_finite_f32(v, k)?; + } + "penalty_last_n" => { + let n: i64 = v.parse().map_err(|_| format!("GEN: bad {k}"))?; + sampling.penalty_last_n = n.max(0) as usize; + } + "draft_top_k" => { + let n: usize = v.parse().map_err(|_| format!("GEN: bad {k}"))?; + draft_top_k = Some(n.min(16)); + } + _ => return Err(format!("GEN: unknown key '{k}'")), + } + } + + let ids = parse_id_csv(toks[toks.len() - 1], vocab_size)?; + Ok(ServeCommand::Gen(ParsedGen { + max_new: max_new as usize, + sampling, + spec_mode, + draft_top_k, + domain_hint, + ids, + })) +} + +fn parse_finite_f32(v: &str, key: &str) -> Result { + let f: f32 = v.parse().map_err(|_| format!("GEN: bad numeric value for {key}"))?; + if !f.is_finite() { + return Err(format!("GEN: non-finite value for {key}")); + } + Ok(f) +} + +/// 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, max_k: u8 }, + DraftResponse { session_id: u64, proposed: Vec, probs: Vec }, + DomainHint { session_id: u64, domain: String, confidence: f32 }, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gen_zero_prewarm_and_strict_validation() { + let cmd = parse_serve_line("GEN 0 domain=lean4 1,2,3", 100).unwrap(); + match cmd { + ServeCommand::Gen(g) => { + assert_eq!(g.max_new, 0); + assert_eq!(g.domain_hint.as_deref(), Some("lean4")); + assert_eq!(g.ids, vec![1, 2, 3]); + } + _ => panic!("expected Gen"), + } + assert!(parse_serve_line("GEN 16 1,100", 100).is_err()); + assert!(parse_serve_line("GEN 16 temperature=nan 1,2", 100).is_err()); + assert!(parse_serve_line("GEN 16 unknown=1 1,2", 100).is_err()); + } +} diff --git a/crates/vetta-telemetry/Cargo.toml b/crates/vetta-telemetry/Cargo.toml new file mode 100644 index 0000000..abaee39 --- /dev/null +++ b/crates/vetta-telemetry/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "vetta-telemetry" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +vetta-core = { path = "../vetta-core" } diff --git a/crates/vetta-telemetry/src/lib.rs b/crates/vetta-telemetry/src/lib.rs new file mode 100644 index 0000000..6d5acb2 --- /dev/null +++ b/crates/vetta-telemetry/src/lib.rs @@ -0,0 +1,270 @@ +//! `vetta-telemetry`: first-class, low-overhead inference statistics & MoE routing analytics. +//! +//! 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), +//! speculative acceptance histograms, and exports structured JSONL asynchronously. + +use std::collections::HashMap; +use std::fs::OpenOptions; +use std::io::{BufWriter, Write}; +use std::path::Path; +use std::sync::mpsc::{self, SyncSender, TrySendError}; +use std::thread::{self, JoinHandle}; +use vetta_core::moe::ExpertKey; + +#[derive(Debug, Clone)] +pub enum TelemetryEvent { + RoutingStep { + domain: String, + layer: u16, + prev_layer_top: Option, + active_experts: Vec, + }, + SpecStep { + k_proposed: u8, + accepted: u8, + step_ms: f32, + entropy_nats: f32, + }, + CacheAccess { + hits: u32, + misses: u32, + dma_bytes: u64, + dma_ms: f32, + }, + TurnSummary { + prompt_tokens: usize, + reused_tokens: usize, + generated_tokens: usize, + prefill_ms: f64, + decode_ms: f64, + domain: String, + }, +} + +/// In-memory statistical aggregator usable offline or updated from the telemetry background thread. +#[derive(Debug, Clone)] +pub struct RoutingStats { + /// `(layer, expert) -> total activations` + pub expert_counts: HashMap, + /// `domain -> ((layer, expert) -> activations)` for domain-aware NVMe Hot/Cold pre-warming! + pub domain_profiles: HashMap>, + /// `(layer, prev_top_expert, cur_expert) -> co-activation count` for `L -> L+1` lookahead! + pub transitions: HashMap<(u16, u16, u16), u64>, + /// Speculative accepted length histogram `acc[len]` (0..=32) + pub spec_acc_hist: [u64; 33], + pub total_cache_hits: u64, + pub total_cache_misses: u64, + pub total_dma_bytes: u64, +} + +impl Default for RoutingStats { + fn default() -> Self { + Self { + expert_counts: HashMap::new(), + domain_profiles: HashMap::new(), + transitions: HashMap::new(), + spec_acc_hist: [0u64; 33], + total_cache_hits: 0, + total_cache_misses: 0, + total_dma_bytes: 0, + } + } +} + +impl RoutingStats { + pub fn record(&mut self, ev: &TelemetryEvent) { + match ev { + TelemetryEvent::RoutingStep { + domain, + layer, + prev_layer_top, + active_experts, + } => { + let dmap = self.domain_profiles.entry(domain.clone()).or_default(); + for &e in active_experts { + let key = ExpertKey { layer: *layer, expert: e }; + *self.expert_counts.entry(key).or_insert(0) += 1; + *dmap.entry(key).or_insert(0) += 1; + if let Some(prev_e) = *prev_layer_top { + *self.transitions.entry((*layer, prev_e, e)).or_insert(0) += 1; + } + } + } + TelemetryEvent::SpecStep { accepted, .. } => { + let idx = (*accepted as usize).min(self.spec_acc_hist.len() - 1); + self.spec_acc_hist[idx] += 1; + } + TelemetryEvent::CacheAccess { hits, misses, dma_bytes, .. } => { + self.total_cache_hits += *hits as u64; + self.total_cache_misses += *misses as u64; + self.total_dma_bytes += *dma_bytes; + } + TelemetryEvent::TurnSummary { .. } => {} + } + } + + /// Top-`n` hottest experts observed for a given semantic `domain` (e.g. `"lean4"`, `"letteratura_it"`). + pub fn top_experts_for_domain(&self, domain: &str, n: usize) -> Vec<(ExpertKey, u64)> { + let Some(map) = self.domain_profiles.get(domain) else { + return Vec::new(); + }; + let mut items: Vec<(ExpertKey, u64)> = map.iter().map(|(&k, &v)| (k, v)).collect(); + items.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| (a.0.layer, a.0.expert).cmp(&(b.0.layer, b.0.expert)))); + items.truncate(n); + items + } +} + +/// Non-blocking telemetry sink: drops gracefully if saturated rather than ever stalling GPU decode. +pub struct TelemetryHandle { + tx: Option>, + worker: Option>, + pub dropped_events: u64, +} + +impl TelemetryHandle { + pub fn start(jsonl_path: Option<&Path>, channel_cap: usize) -> Result { + let (tx, rx) = mpsc::sync_channel::(channel_cap.max(64)); + let mut writer = match jsonl_path { + Some(p) => { + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("telemetry mkdir: {e}"))?; + } + let f = OpenOptions::new() + .create(true) + .append(true) + .open(p) + .map_err(|e| format!("telemetry open {}: {e}", p.display()))?; + Some(BufWriter::new(f)) + } + None => None, + }; + + let worker = thread::spawn(move || { + let mut stats = RoutingStats::default(); + while let Ok(ev) = rx.recv() { + stats.record(&ev); + if let Some(w) = writer.as_mut() { + let _ = write_event_jsonl(w, &ev); + } + } + if let Some(w) = writer.as_mut() { + let _ = w.flush(); + } + stats + }); + + Ok(Self { + tx: Some(tx), + worker: Some(worker), + dropped_events: 0, + }) + } + + /// Never blocks the decode loop. + pub fn emit(&mut self, ev: TelemetryEvent) { + if let Some(tx) = &self.tx { + if let Err(TrySendError::Full(_)) = tx.try_send(ev) { + self.dropped_events += 1; + } + } + } + + pub fn finish(mut self) -> RoutingStats { + self.tx.take(); + self.worker + .take() + .and_then(|h| h.join().ok()) + .unwrap_or_default() + } +} + +fn write_event_jsonl(w: &mut W, ev: &TelemetryEvent) -> std::io::Result<()> { + match ev { + TelemetryEvent::RoutingStep { domain, layer, prev_layer_top, active_experts } => { + writeln!( + w, + "{{\"ev\":\"route\",\"domain\":\"{}\",\"layer\":{},\"prev_top\":{},\"experts\":{:?}}}", + domain.replace('"', ""), + layer, + prev_layer_top.map(|v| v.to_string()).unwrap_or_else(|| "null".into()), + active_experts + ) + } + TelemetryEvent::SpecStep { k_proposed, accepted, step_ms, entropy_nats } => { + writeln!( + w, + "{{\"ev\":\"spec\",\"k\":{},\"acc\":{},\"ms\":{:.3},\"H\":{:.4}}}", + k_proposed, accepted, step_ms, entropy_nats + ) + } + TelemetryEvent::CacheAccess { hits, misses, dma_bytes, dma_ms } => { + writeln!( + w, + "{{\"ev\":\"cache\",\"hits\":{},\"misses\":{},\"dma_bytes\":{},\"dma_ms\":{:.3}}}", + hits, misses, dma_bytes, dma_ms + ) + } + TelemetryEvent::TurnSummary { + prompt_tokens, + reused_tokens, + generated_tokens, + prefill_ms, + decode_ms, + domain, + } => { + writeln!( + w, + "{{\"ev\":\"turn\",\"domain\":\"{}\",\"prompt\":{},\"reused\":{},\"gen\":{},\"prefill_ms\":{:.2},\"decode_ms\":{:.2}}}", + domain.replace('"', ""), + prompt_tokens, + reused_tokens, + generated_tokens, + prefill_ms, + decode_ms + ) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn domain_expert_profile_and_async_jsonl() { + let p = std::env::temp_dir().join(format!("vetta_tel_{}.jsonl", std::process::id())); + let _ = std::fs::remove_file(&p); + let mut h = TelemetryHandle::start(Some(&p), 128).unwrap(); + for _ in 0..5 { + h.emit(TelemetryEvent::RoutingStep { + domain: "lean4".into(), + layer: 3, + prev_layer_top: Some(12), + active_experts: vec![7, 42], + }); + } + h.emit(TelemetryEvent::RoutingStep { + domain: "dante".into(), + layer: 3, + prev_layer_top: Some(1), + active_experts: vec![99], + }); + h.emit(TelemetryEvent::SpecStep { + k_proposed: 8, + accepted: 6, + step_ms: 48.0, + entropy_nats: 0.42, + }); + let st = h.finish(); + let top_lean = st.top_experts_for_domain("lean4", 2); + assert_eq!(top_lean.len(), 2); + assert_eq!(top_lean[0].1, 5); + assert_eq!(st.spec_acc_hist[6], 1); + assert_eq!(*st.transitions.get(&(3, 12, 7)).unwrap(), 5); + assert!(std::fs::read_to_string(&p).unwrap().contains("\"ev\":\"spec\"")); + let _ = std::fs::remove_file(&p); + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..d7dae89 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,56 @@ +# vetta-infer Architecture Blueprint + +## 1. Hardware Ground Truth (Measured on Sogliola) + +| Resource | Measured Value | Architectural Implication | +| --- | --- | --- | +| GPU | AMD Radeon 890M (`gfx1150`, RDNA 3.5, 16 CU) | Wave32 native, `16×16×16` INT8 WMMA (`~44 TFLOP/s`), `16×16×16` FP16 WMMA (`22.14 TFLOP/s`) | +| Memory | `48 GiB` VRAM carveout + `46 GiB` GTT/RAM (`96 GiB` UMA) | VRAM and RAM share the same LPDDR5X (`81.7 GB/s` raw, `~75 GB/s` sustained GEMM). Zero-copy `hipHostRegister` avoids redundant DRAM→DRAM copies | +| 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 | + +## 2. Crate Graph + +``` + ┌───────────────┐ + │ vetta-cli │ + └───────┬───────┘ + ┌─────────┬───────┼───────┬───────────┐ + ▼ ▼ ▼ ▼ ▼ + vetta-proto vetta-io vetta-hip vetta-telemetry + └─────────┴───────┼───────┴───────────┘ + ▼ + 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. +- **`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.` atomic commit). +- **`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`). +- **`vetta-telemetry`:** lock-free ring buffer + background JSONL writer collecting: + - per-layer MoE expert activation counts (Zipf curves) and `L -> L+1` transition frequencies; + - 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) + +1. `k_embed_bf16` — BF16 embedding gather +2. `k_rms_norm` — fused RMSNorm (+ optional residual add / `+1.0` weight offset) +3. `k_quantize_x_g64` — per-64 activation INT8 quantization (fusable with SwiGLU) +4. `k_gemm_q8_g64_t16` — native RDNA 3.5 INT8 WMMA (`[N/16, K/64, 4, 16, 16]`, FP16 scales) +5. `k_gemm_q4_g64_t16` — SWAR 3-instruction INT4→INT8 WMMA (`0.5625 B/param`) +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) +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 +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) +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 +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`) + +Verified with Lean `4.36.0` (`0 sorryAx`): +- **`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. diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h new file mode 100644 index 0000000..336bbe7 --- /dev/null +++ b/kernels/hip/vetta_kernels.h @@ -0,0 +1,47 @@ +// kernels/hip/vetta_kernels.h +// Minimal C ABI for the <15 reusable RDNA 3.5 (gfx1150) HIP microkernels shared across all MoE models. +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* vetta_stream_t; +typedef void* vetta_event_t; + +typedef struct vetta_device_info_t { + char name[128]; + char gcn_arch[64]; + int multi_processor_count; + int wave_size; + uint64_t total_vram_bytes; + int is_uma; +} vetta_device_info_t; + +// Runtime & UMA zero-copy buffer lifecycle (Milestone 1+) +int vetta_hip_query_device(int dev_id, vetta_device_info_t* out_info); +int vetta_hip_register_uma_pages(void* host_aligned_ptr, size_t bytes, void** out_dev_ptr); +int vetta_hip_unregister_uma_pages(void* host_aligned_ptr); + +// Core <15 microkernel entry points (implemented progressively in M1 & M2): +// 1. k_embed_bf16 +// 2. k_rms_norm +// 3. k_quantize_x_g64 +// 4. k_gemm_q8_g64_t16 +// 5. k_gemm_q4_g64_t16 (SWAR 3-inst INT4->INT8 WMMA) +// 6. k_gemm_nvfp4_mxfp8 +// 7. k_rope_kv_write +// 8. k_flash_gqa_wmma +// 9. k_gdn_chunkwise_wy (WY-representation parallel prefill) +// 10. k_gdn_recurrent_step (0-spill decode + rollback history) +// 11. k_moe_route_bucket (100% GPU routing + bitonic coreset + NaN/mask safety) +// 12. k_moe_grouped_wmma (compacted w13 fused SwiGLU+quantize & w2 + reduce) +// 13. k_vit_flash_attn_wmma (64x64 FP16 WMMA Vision) +// 14. k_gpu_penalties_topk (GPU penalties + top-64 extraction, <=512 B D2H/row) + +#ifdef __cplusplus +} +#endif diff --git a/proofs/slab_ring_dma.lean b/proofs/slab_ring_dma.lean new file mode 100644 index 0000000..c8d4810 --- /dev/null +++ b/proofs/slab_ring_dma.lean @@ -0,0 +1,191 @@ +/-! + proofs/slab_ring_dma.lean + Formal state-machine contracts for `vetta-infer`: + 1. `SlabRing` zero-copy UMA DMA (`io_uring O_DIRECT` <-> `hipHostRegister` GPU compute) + eliminating async DMA use-after-scope / race bugs (audit-05 F-01) by construction. + 2. `PrefixState` typestate eliminating uninitialized MTP hidden-state reuse (audit-05 F-03). + 3. Non-aligned post-`RESUME` checkpoint grid guarantee (audit-05 F-06). + + Zero `sorryAx`; checked with `lean proofs/slab_ring_dma.lean`. +-/ + +namespace Vetta.Proofs + +-- ============================================================================ +-- 1. SlabRing DMA Ownership State Machine (io_uring <-> GPU Fence) +-- ============================================================================ + +/-- Exclusive ownership state of a pinned UMA page-ring slot. -/ +inductive SlotState where + | free -- Owned by ring allocator; neither DMA nor GPU touches it + | ioInFlight (reqId : Nat) -- Owned by `io_uring` O_DIRECT DMA write + | gpuReady (tag : Nat) -- DMA complete (CQE observed); immutable, ready for GPU launch + | gpuInUse (tag : Nat) (fence : Nat) -- GPU kernels reading; fence not yet signaled + deriving DecidableEq, Repr + +/-- Predicate: host/NVMe DMA is currently writing this slot. -/ +def dmaWriting : SlotState → Bool + | .ioInFlight _ => true + | _ => false + +/-- Predicate: GPU kernels are currently reading this slot. -/ +def gpuReading : SlotState → Bool + | .gpuInUse _ _ => true + | _ => false + +/-- Predicate: slot is safe to hand to GPU compute (DMA finished and payload tag matches). -/ +def readyForGpu (tag : Nat) : SlotState → Prop + | .gpuReady t => t = tag + | _ => False + +/-- Legal single-slot transitions of the `SlabRing` protocol. -/ +inductive SlotStep : SlotState → SlotState → Prop where + | submitIo (reqId : Nat) : + SlotStep .free (.ioInFlight reqId) + | completeIo (reqId tag : Nat) : + SlotStep (.ioInFlight reqId) (.gpuReady tag) + | abortIo (reqId : Nat) : + SlotStep (.ioInFlight reqId) .free + | launchGpu (tag fence : Nat) : + SlotStep (.gpuReady tag) (.gpuInUse tag fence) + | discardReady (tag : Nat) : + SlotStep (.gpuReady tag) .free + | completeGpu (tag fence : Nat) : + SlotStep (.gpuInUse tag fence) .free + +/-- Reflexive-transitive reachability from `.free`. -/ +inductive Reachable : SlotState → Prop where + | init : Reachable .free + | step {s s' : SlotState} : Reachable s → SlotStep s s' → Reachable s' + +/-- Theorem 1: No slot can EVER be simultaneously written by DMA and read by GPU. -/ +theorem no_dma_while_gpu_uses (s : SlotState) : + ¬ (dmaWriting s = true ∧ gpuReading s = true) := by + cases s <;> simp [dmaWriting, gpuReading] + +/-- Theorem 2: Launching GPU kernels is ONLY possible from `gpuReady` (DMA CQE already observed). -/ +theorem launch_requires_dma_complete {s : SlotState} {tag fence : Nat} + (h : SlotStep s (.gpuInUse tag fence)) : + s = .gpuReady tag ∧ dmaWriting s = false := by + cases h + exact ⟨rfl, rfl⟩ + +/-- Theorem 3: A `gpuInUse` slot can ONLY transition to `.free` via `completeGpu` (fence observed), + never directly to `ioInFlight` (eliminates F-01 overwrite/drop while GPU is reading). -/ +theorem no_dma_submit_while_gpu_uses {tag fence reqId : Nat} : + ¬ SlotStep (.gpuInUse tag fence) (.ioInFlight reqId) := by + intro h + cases h + +/-- Theorem 4: Reclaiming a `gpuInUse` slot into `.free` preserves the exact fence id that must be waited on. -/ +theorem reclaim_from_gpu_only_via_fence {tag fence : Nat} {s' : SlotState} + (h : SlotStep (.gpuInUse tag fence) s') : + s' = .free := by + cases h + rfl + +/-- Ring of `N` slots with an atomic transition at index `i`. -/ +structure Ring (N : Nat) where + slots : Fin N → SlotState + +def Ring.update {N : Nat} (r : Ring N) (i : Fin N) (st : SlotState) : Ring N := + ⟨fun j => if j = i then st else r.slots j⟩ + +/-- Theorem 5: Updating slot `i` never disturbs the ownership state of any other slot `j ≠ i`. -/ +theorem ring_update_isolates_others {N : Nat} (r : Ring N) (i j : Fin N) (st : SlotState) + (hne : j ≠ i) : + (r.update i st).slots j = r.slots j := by + simp [Ring.update, hne] + +/-- Theorem 6: Every slot in a reachable ring satisfies DMA/GPU mutual exclusion. -/ +theorem ring_slot_safe {N : Nat} (r : Ring N) (i : Fin N) : + ¬ (dmaWriting (r.slots i) = true ∧ gpuReading (r.slots i) = true) := + no_dma_while_gpu_uses (r.slots i) + +-- ============================================================================ +-- 2. PrefixState Typestate (Eliminates F-03 Uninitialized MTP Buffer Reuse) +-- ============================================================================ + +/-- Explicit typestate replacing loose `(prefix_len, mtp_prefix_len)` integers. -/ +inductive PrefixState where + | empty + | targetOnly (len : Nat) (hpos : len > 0) + | targetWithMtp (len : Nat) (mtpLen : Nat) (hpos : len > 0) (halign : mtpLen + 1 = len) + +/-- Whether `PrefixState` has a valid, initialized `sc_mtp_hid_` buffer ready for MTP reuse. -/ +def PrefixState.hasValidMtpHid : PrefixState → Bool + | .targetWithMtp _ _ _ _ => true + | _ => false + +def PrefixState.prefixLen : PrefixState → Nat + | .empty => 0 + | .targetOnly len _ => len + | .targetWithMtp len _ _ _ => len + +/-- Legal reuse check for a prompt of length `L` with `useMtp`. -/ +def canReusePrefix (st : PrefixState) (promptLen : Nat) (useMtp : Bool) : Bool := + match st with + | .empty => false + | .targetOnly len _ => (!useMtp) && (len < promptLen) + | .targetWithMtp len _ _ _ => len < promptLen + +/-- Theorem 7 (F-03 prevention): If `canReusePrefix st L true = true`, then `st` MUST be + `targetWithMtp` with an initialized MTP hidden buffer and `mtpLen + 1 = len < L`. -/ +theorem reuse_with_mtp_implies_valid_hid (st : PrefixState) (L : Nat) + (h : canReusePrefix st L true = true) : + st.hasValidMtpHid = true ∧ + ∃ len mtpLen, st.prefixLen = len ∧ mtpLen + 1 = len ∧ len < L := by + cases st with + | empty => simp [canReusePrefix] at h + | targetOnly len hpos => simp [canReusePrefix] at h + | targetWithMtp len mtpLen hpos halign => + simp [canReusePrefix] at h + exact ⟨rfl, len, mtpLen, rfl, halign, h⟩ + +/-- Theorem 8: A Turn-1 `targetOnly` run of length `L = 1` (the exact F-03 bug scenario) + can NEVER be reused when Turn-2 enables `useMtp = true`. -/ +theorem turn1_len1_no_mtp_cannot_reuse_with_mtp (L : Nat) : + canReusePrefix (.targetOnly 1 (by decide)) L true = false := by + rfl + +-- ============================================================================ +-- 3. Non-Aligned Post-RESUME Checkpoint Grid (Eliminates F-06) +-- ============================================================================ + +/-- Next checkpoint boundary strictly greater than `cur`, on a grid of stride `S > 0`. -/ +def nextCkptBoundary (cur S : Nat) : Nat := + ((cur / S) + 1) * S + +/-- Theorem 9: `nextCkptBoundary cur S` is strictly greater than `cur` whenever `S > 0`. -/ +theorem nextCkptBoundary_gt (cur S : Nat) (hS : S > 0) : + cur < nextCkptBoundary cur S := by + unfold nextCkptBoundary + have h1 : cur = S * (cur / S) + cur % S := (Nat.div_add_mod cur S).symm + have h2 : cur % S < S := Nat.mod_lt cur hS + have h3 : (cur / S + 1) * S = S * (cur / S) + S := by + rw [Nat.add_mul, Nat.one_mul, Nat.mul_comm] + omega + +/-- Theorem 10: `nextCkptBoundary cur S` is at most `cur + S`, so advancing by `>= S` tokens + from ANY non-aligned `RESUME` offset `cur` is guaranteed to cross and trigger a checkpoint. -/ +theorem nextCkptBoundary_le_add (cur S : Nat) : + nextCkptBoundary cur S ≤ cur + S := by + unfold nextCkptBoundary + have h1 : S * (cur / S) ≤ cur := Nat.mul_div_le cur S + have h2 : (cur / S + 1) * S = S * (cur / S) + S := by + rw [Nat.add_mul, Nat.one_mul, Nat.mul_comm] + omega + +-- Axiom audit (all theorems must rely only on standard core axioms, 0 sorryAx) +#print axioms no_dma_while_gpu_uses +#print axioms launch_requires_dma_complete +#print axioms no_dma_submit_while_gpu_uses +#print axioms reclaim_from_gpu_only_via_fence +#print axioms ring_update_isolates_others +#print axioms ring_slot_safe +#print axioms reuse_with_mtp_implies_valid_hid +#print axioms turn1_len1_no_mtp_cannot_reuse_with_mtp +#print axioms nextCkptBoundary_gt +#print axioms nextCkptBoundary_le_add + +end Vetta.Proofs