[Core] M0 foundation: workspace, Lean 4 SlabRing/PrefixState contracts, checked safetensors/cache IO, serve proto, telemetry, and HIP ABI
This commit is contained in:
commit
63b1668a92
25 files changed
+2991
No files matched your search
@@ -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" }
|
||||
@@ -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 <safetensors-dir> 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<String, (usize, u64)> = 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<String> = 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 <safetensors-dir>");
|
||||
usage();
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match cmd_info(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
usage();
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "vetta-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
@@ -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;
|
||||
@@ -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<ExpertKey, ResidentMeta>,
|
||||
free_slots: Vec<usize>,
|
||||
pub total_hits: u64,
|
||||
pub total_misses: u64,
|
||||
}
|
||||
|
||||
impl HotColdExpertCache {
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
let cap = capacity.max(1);
|
||||
let free_slots = (0..cap).rev().collect();
|
||||
Self {
|
||||
capacity: cap,
|
||||
tick: 0,
|
||||
map: HashMap::with_capacity(cap),
|
||||
free_slots,
|
||||
total_hits: 0,
|
||||
total_misses: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.capacity
|
||||
}
|
||||
|
||||
pub fn resident_count(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
pub fn hit_rate(&self) -> f64 {
|
||||
let tot = self.total_hits + self.total_misses;
|
||||
if tot == 0 { 0.0 } else { self.total_hits as f64 / tot as f64 }
|
||||
}
|
||||
|
||||
pub fn lookup(&mut self, key: ExpertKey) -> CacheLookup {
|
||||
self.tick += 1;
|
||||
if let Some(m) = self.map.get_mut(&key) {
|
||||
m.hits += 1;
|
||||
m.last_tick = self.tick;
|
||||
self.total_hits += 1;
|
||||
CacheLookup::Hit { slot: m.slot }
|
||||
} else {
|
||||
self.total_misses += 1;
|
||||
CacheLookup::Miss
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks a target slot to load `key` into (free slot or LFU+LRU unpinned victim).
|
||||
/// Does not mutate residency until `commit_load` succeeds.
|
||||
pub fn plan_load(&self, key: ExpertKey) -> Option<(usize, Option<ExpertKey>)> {
|
||||
if let Some(m) = self.map.get(&key) {
|
||||
return Some((m.slot, None));
|
||||
}
|
||||
if let Some(&slot) = self.free_slots.last() {
|
||||
return Some((slot, None));
|
||||
}
|
||||
// Evict lowest-hit, oldest unpinned resident expert.
|
||||
self.map
|
||||
.iter()
|
||||
.filter(|(_, m)| !m.pinned)
|
||||
.min_by_key(|(_, m)| (m.hits, m.last_tick))
|
||||
.map(|(&k, m)| (m.slot, Some(k)))
|
||||
}
|
||||
|
||||
pub fn commit_load(&mut self, key: ExpertKey, slot: usize, evicted: Option<ExpertKey>, pinned: bool) {
|
||||
self.tick += 1;
|
||||
if let Some(ev) = evicted {
|
||||
self.map.remove(&ev);
|
||||
} else if let Some(pos) = self.free_slots.iter().position(|&s| s == slot) {
|
||||
self.free_slots.swap_remove(pos);
|
||||
}
|
||||
self.map.insert(
|
||||
key,
|
||||
ResidentMeta {
|
||||
slot,
|
||||
hits: 1,
|
||||
last_tick: self.tick,
|
||||
pinned,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns the subset of domain-recommended experts not currently resident (candidates for NVMe pre-warm).
|
||||
pub fn missing_for_prewarm(&self, recommended: &[ExpertKey]) -> Vec<ExpertKey> {
|
||||
recommended
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|k| !self.map.contains_key(k))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lfu_lru_eviction_and_domain_prewarm() {
|
||||
let mut c = HotColdExpertCache::new(2);
|
||||
let k0 = ExpertKey { layer: 0, expert: 1 };
|
||||
let k1 = ExpertKey { layer: 0, expert: 2 };
|
||||
let k2 = ExpertKey { layer: 0, expert: 3 };
|
||||
|
||||
assert_eq!(c.lookup(k0), CacheLookup::Miss);
|
||||
let (s0, ev0) = c.plan_load(k0).unwrap();
|
||||
assert!(ev0.is_none());
|
||||
c.commit_load(k0, s0, ev0, false);
|
||||
|
||||
// Make k0 hot
|
||||
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
|
||||
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
|
||||
|
||||
let (s1, ev1) = c.plan_load(k1).unwrap();
|
||||
c.commit_load(k1, s1, ev1, false);
|
||||
|
||||
// k2 should evict cold k1, keeping hot k0
|
||||
let (s2, ev2) = c.plan_load(k2).unwrap();
|
||||
assert_eq!(ev2, Some(k1));
|
||||
assert_eq!(s2, s1);
|
||||
c.commit_load(k2, s2, ev2, false);
|
||||
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
|
||||
assert_eq!(c.missing_for_prewarm(&[k0, k1, k2]), vec![k1]);
|
||||
}
|
||||
}
|
||||
@@ -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<Self, &'static str> {
|
||||
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<i32>,
|
||||
}
|
||||
|
||||
/// 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<HybridCkptEntry>,
|
||||
}
|
||||
|
||||
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<usize> {
|
||||
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<i32>) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<MinCand>` keeps the WORST candidate on top (min-heap of top-K).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct MinCand(Cand);
|
||||
|
||||
impl Ord for MinCand {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
// Better = higher val, or equal val with smaller id.
|
||||
// For min-heap, `other` better than `self` => self > other (so worst is popped first).
|
||||
match other.0.val.total_cmp(&self.0.val) {
|
||||
Ordering::Equal => self.0.id.cmp(&other.0.id),
|
||||
ord => ord,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for MinCand {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
fn cand_desc(a: &Cand, b: &Cand) -> Ordering {
|
||||
match b.val.total_cmp(&a.val) {
|
||||
Ordering::Equal => a.id.cmp(&b.id),
|
||||
ord => ord,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct SamplerScratch {
|
||||
pub idx: Vec<i32>,
|
||||
pub prob: Vec<f64>,
|
||||
cands: Vec<Cand>,
|
||||
counts: HashMap<i32, u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct SampleReport {
|
||||
pub token: i32,
|
||||
pub confidence: f32,
|
||||
pub nonfinite_logits: usize,
|
||||
pub entropy_nats: f32,
|
||||
}
|
||||
|
||||
pub fn suppress_token(logits: &mut [f32], banned: Option<i32>) {
|
||||
if let Some(id) = banned {
|
||||
if id >= 0 && (id as usize) < logits.len() {
|
||||
logits[id as usize] = f32::NEG_INFINITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_penalties(logits: &mut [f32], opts: &SamplingOpts, history: &[i32], scratch: &mut SamplerScratch) {
|
||||
if !opts.has_penalties() || history.is_empty() || logits.is_empty() {
|
||||
return;
|
||||
}
|
||||
scratch.counts.clear();
|
||||
let win = history.len().min(opts.penalty_last_n);
|
||||
for &id in &history[history.len() - win..] {
|
||||
if id >= 0 && (id as usize) < logits.len() {
|
||||
*scratch.counts.entry(id).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
for (&id, &cnt) in &scratch.counts {
|
||||
let v = &mut logits[id as usize];
|
||||
if !v.is_finite() {
|
||||
continue;
|
||||
}
|
||||
if opts.penalty_repeat != 1.0 {
|
||||
*v = if *v > 0.0 { *v / opts.penalty_repeat } else { *v * opts.penalty_repeat };
|
||||
}
|
||||
if opts.penalty_freq != 0.0 {
|
||||
*v -= opts.penalty_freq * (cnt as f32);
|
||||
}
|
||||
if opts.penalty_present != 0.0 {
|
||||
*v -= opts.penalty_present;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a normalized/unnormalized truncated distribution into `scratch.{idx, prob}`.
|
||||
/// Returns the number of non-finite logits encountered.
|
||||
pub fn build_truncated_dist(
|
||||
logits: &mut [f32],
|
||||
opts: &SamplingOpts,
|
||||
history: &[i32],
|
||||
banned: Option<i32>,
|
||||
scratch: &mut SamplerScratch,
|
||||
) -> usize {
|
||||
scratch.idx.clear();
|
||||
scratch.prob.clear();
|
||||
if logits.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
suppress_token(logits, banned);
|
||||
apply_penalties(logits, opts, history, scratch);
|
||||
|
||||
let v = logits.len();
|
||||
let mut nonfinite = 0usize;
|
||||
let mut mx = f32::NEG_INFINITY;
|
||||
for &val in logits.iter() {
|
||||
if !val.is_finite() {
|
||||
if val.is_nan() || val.is_infinite() && val.is_sign_positive() {
|
||||
nonfinite += 1;
|
||||
}
|
||||
} else if val > mx {
|
||||
mx = val;
|
||||
}
|
||||
}
|
||||
if !mx.is_finite() {
|
||||
scratch.idx.push(0);
|
||||
scratch.prob.push(1.0);
|
||||
return nonfinite;
|
||||
}
|
||||
|
||||
let inv_t = 1.0f64 / (opts.temperature as f64).max(1e-6);
|
||||
|
||||
scratch.cands.clear();
|
||||
if opts.top_k > 0 && opts.top_k < v && opts.top_k <= 512 {
|
||||
let mut heap: BinaryHeap<MinCand> = BinaryHeap::with_capacity(opts.top_k + 1);
|
||||
for (i, &val) in logits.iter().enumerate() {
|
||||
if !val.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let c = MinCand(Cand { val, id: i as i32 });
|
||||
if heap.len() < opts.top_k {
|
||||
heap.push(c);
|
||||
} else if let Some(&top) = heap.peek() {
|
||||
if cand_desc(&c.0, &top.0) == Ordering::Less {
|
||||
heap.pop();
|
||||
heap.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
scratch.cands.extend(heap.into_iter().map(|m| m.0));
|
||||
scratch.cands.sort_unstable_by(cand_desc);
|
||||
} else {
|
||||
let logit_floor = if opts.min_p > 0.0 && opts.min_p < 1.0 && opts.top_k == 0 {
|
||||
(mx as f64 + (opts.min_p as f64).ln() / inv_t) as f32
|
||||
} else {
|
||||
f32::NEG_INFINITY
|
||||
};
|
||||
for (i, &val) in logits.iter().enumerate() {
|
||||
if !val.is_finite() {
|
||||
continue;
|
||||
}
|
||||
if val < logit_floor && val < mx {
|
||||
continue;
|
||||
}
|
||||
scratch.cands.push(Cand { val, id: i as i32 });
|
||||
}
|
||||
if scratch.cands.is_empty() {
|
||||
scratch.idx.push(0);
|
||||
scratch.prob.push(1.0);
|
||||
return nonfinite;
|
||||
}
|
||||
let need_sort = (opts.top_k > 0 && opts.top_k < scratch.cands.len())
|
||||
|| (opts.top_p > 0.0 && opts.top_p < 1.0);
|
||||
if opts.top_k > 0 && opts.top_k < scratch.cands.len() {
|
||||
scratch.cands.select_nth_unstable_by(opts.top_k, cand_desc);
|
||||
scratch.cands.truncate(opts.top_k);
|
||||
scratch.cands.sort_unstable_by(cand_desc);
|
||||
} else if need_sort {
|
||||
scratch.cands.sort_unstable_by(cand_desc);
|
||||
}
|
||||
}
|
||||
|
||||
let mut p_max = 0.0f64;
|
||||
let mut z = 0.0f64;
|
||||
for c in &scratch.cands {
|
||||
let w = (((c.val as f64) - (mx as f64)) * inv_t).exp();
|
||||
if w > p_max {
|
||||
p_max = w;
|
||||
}
|
||||
scratch.idx.push(c.id);
|
||||
scratch.prob.push(w);
|
||||
z += w;
|
||||
}
|
||||
if z <= 0.0 {
|
||||
let first = scratch.idx.first().copied().unwrap_or(0);
|
||||
scratch.idx.clear();
|
||||
scratch.prob.clear();
|
||||
scratch.idx.push(first);
|
||||
scratch.prob.push(1.0);
|
||||
return nonfinite;
|
||||
}
|
||||
|
||||
if opts.min_p > 0.0 && opts.min_p < 1.0 {
|
||||
let thresh = (opts.min_p as f64) * p_max;
|
||||
let mut keep = 0usize;
|
||||
for i in 0..scratch.idx.len() {
|
||||
if i == 0 || scratch.prob[i] >= thresh {
|
||||
scratch.idx[keep] = scratch.idx[i];
|
||||
scratch.prob[keep] = scratch.prob[i];
|
||||
keep += 1;
|
||||
}
|
||||
}
|
||||
scratch.idx.truncate(keep);
|
||||
scratch.prob.truncate(keep);
|
||||
}
|
||||
|
||||
if opts.top_p > 0.0 && opts.top_p < 1.0 && scratch.idx.len() > 1 {
|
||||
let z2: f64 = scratch.prob.iter().sum();
|
||||
let inv_z2 = 1.0 / z2.max(1e-30);
|
||||
let mut cum = 0.0f64;
|
||||
let mut keep = scratch.idx.len();
|
||||
for i in 0..scratch.idx.len() {
|
||||
cum += scratch.prob[i] * inv_z2;
|
||||
if cum >= opts.top_p as f64 {
|
||||
keep = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
scratch.idx.truncate(keep);
|
||||
scratch.prob.truncate(keep);
|
||||
}
|
||||
nonfinite
|
||||
}
|
||||
|
||||
pub fn sample_logits_exact(
|
||||
logits: &mut [f32],
|
||||
opts: &SamplingOpts,
|
||||
history: &[i32],
|
||||
banned: Option<i32>,
|
||||
rng: &mut SplitMix64,
|
||||
scratch: &mut SamplerScratch,
|
||||
) -> SampleReport {
|
||||
if logits.is_empty() {
|
||||
return SampleReport { token: 0, confidence: 1.0, nonfinite_logits: 0, entropy_nats: 0.0 };
|
||||
}
|
||||
if opts.is_greedy() {
|
||||
suppress_token(logits, banned);
|
||||
apply_penalties(logits, opts, history, scratch);
|
||||
let mut best_id = 0i32;
|
||||
let mut mx = f32::NEG_INFINITY;
|
||||
let mut nonfinite = 0usize;
|
||||
for (i, &val) in logits.iter().enumerate() {
|
||||
if !val.is_finite() {
|
||||
if val.is_nan() || (val.is_infinite() && val.is_sign_positive()) {
|
||||
nonfinite += 1;
|
||||
}
|
||||
} else if val > mx {
|
||||
mx = val;
|
||||
best_id = i as i32;
|
||||
}
|
||||
}
|
||||
let mut z = 0.0f64;
|
||||
let mut h = 0.0f64;
|
||||
if mx.is_finite() {
|
||||
for &val in logits.iter() {
|
||||
if val.is_finite() {
|
||||
let w = ((val - mx) as f64).exp();
|
||||
z += w;
|
||||
}
|
||||
}
|
||||
if z > 0.0 {
|
||||
for &val in logits.iter() {
|
||||
if val.is_finite() {
|
||||
let p = ((val - mx) as f64).exp() / z;
|
||||
if p > 1e-12 {
|
||||
h -= p * p.ln();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return SampleReport {
|
||||
token: best_id,
|
||||
confidence: if z > 0.0 { (1.0 / z) as f32 } else { 1.0 },
|
||||
nonfinite_logits: nonfinite,
|
||||
entropy_nats: h as f32,
|
||||
};
|
||||
}
|
||||
|
||||
let nonfinite = build_truncated_dist(logits, opts, history, banned, scratch);
|
||||
let z: f64 = scratch.prob.iter().sum();
|
||||
let inv_z = 1.0 / z.max(1e-30);
|
||||
let mut h = 0.0f64;
|
||||
for &w in &scratch.prob {
|
||||
let p = w * inv_z;
|
||||
if p > 1e-12 {
|
||||
h -= p * p.ln();
|
||||
}
|
||||
}
|
||||
let r = rng.next_f64() * z;
|
||||
let mut c = 0.0f64;
|
||||
let mut chosen = scratch.idx[0];
|
||||
let mut chosen_p = scratch.prob[0] * inv_z;
|
||||
for i in 0..scratch.idx.len() {
|
||||
c += scratch.prob[i];
|
||||
if r <= c {
|
||||
chosen = scratch.idx[i];
|
||||
chosen_p = scratch.prob[i] * inv_z;
|
||||
break;
|
||||
}
|
||||
}
|
||||
SampleReport {
|
||||
token: chosen,
|
||||
confidence: chosen_p as f32,
|
||||
nonfinite_logits: nonfinite,
|
||||
entropy_nats: h as f32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lossless Leviathan speculative verification (exact target distribution `p(x)`).
|
||||
/// Returns `(emitted_token, accepted)`.
|
||||
pub fn verify_draft_exact(
|
||||
logits: &mut [f32],
|
||||
opts: &SamplingOpts,
|
||||
history: &[i32],
|
||||
banned: Option<i32>,
|
||||
rng: &mut SplitMix64,
|
||||
draft_tok: i32,
|
||||
scratch: &mut SamplerScratch,
|
||||
) -> (i32, bool) {
|
||||
if opts.is_greedy() {
|
||||
let rep = sample_logits_exact(logits, opts, history, banned, rng, scratch);
|
||||
return (rep.token, rep.token == draft_tok);
|
||||
}
|
||||
let _ = build_truncated_dist(logits, opts, history, banned, scratch);
|
||||
let z: f64 = scratch.prob.iter().sum();
|
||||
if z <= 0.0 || scratch.idx.is_empty() {
|
||||
return (draft_tok, true);
|
||||
}
|
||||
let dpos = scratch.idx.iter().position(|&id| id == draft_tok);
|
||||
let p_draft = dpos.map(|i| scratch.prob[i] / z).unwrap_or(0.0);
|
||||
if dpos.is_some() && (scratch.idx.len() == 1 || rng.next_f64() < p_draft) {
|
||||
return (draft_tok, true);
|
||||
}
|
||||
let z_rem = z - dpos.map(|i| scratch.prob[i]).unwrap_or(0.0);
|
||||
if z_rem <= 0.0 {
|
||||
return match dpos {
|
||||
Some(_) => (draft_tok, true),
|
||||
None => (scratch.idx[0], false),
|
||||
};
|
||||
}
|
||||
let r = rng.next_f64() * z_rem;
|
||||
let mut c = 0.0f64;
|
||||
let mut last_valid = scratch.idx[0];
|
||||
for i in 0..scratch.idx.len() {
|
||||
if Some(i) == dpos {
|
||||
continue;
|
||||
}
|
||||
last_valid = scratch.idx[i];
|
||||
c += scratch.prob[i];
|
||||
if r <= c {
|
||||
return (scratch.idx[i], false);
|
||||
}
|
||||
}
|
||||
(last_valid, false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn top_k_tie_break_and_no_256_cap_for_top_p() {
|
||||
let mut sc = SamplerScratch::default();
|
||||
let mut lg = vec![0.0f32; 600];
|
||||
lg[500] = 5.0;
|
||||
lg[10] = 5.0;
|
||||
lg[300] = 4.0;
|
||||
let opts = SamplingOpts { temperature: 1.0, top_k: 3, ..Default::default() };
|
||||
let nf = build_truncated_dist(&mut lg, &opts, &[], None, &mut sc);
|
||||
assert_eq!(nf, 0);
|
||||
assert_eq!(sc.idx, vec![10, 500, 300]);
|
||||
|
||||
// 400 uniform tokens with top_k=0, top_p=0.9 -> keeps ~360 tokens (not truncated at 256!)
|
||||
let mut unif = vec![1.0f32; 400];
|
||||
let opts_u = SamplingOpts { temperature: 1.0, top_k: 0, top_p: 0.9, ..Default::default() };
|
||||
build_truncated_dist(&mut unif, &opts_u, &[], None, &mut sc);
|
||||
assert!((359..=361).contains(&sc.idx.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonfinite_reported_and_mask_suppressed() {
|
||||
let mut sc = SamplerScratch::default();
|
||||
let mut rng = SplitMix64::new(7);
|
||||
let mut lg = vec![1.0, f32::NAN, 9.0, 5.0];
|
||||
let rep = sample_logits_exact(&mut lg, &SamplingOpts::default(), &[], Some(2), &mut rng, &mut sc);
|
||||
assert_eq!(rep.nonfinite_logits, 1);
|
||||
assert_eq!(rep.token, 3); // token 2 was suppressed
|
||||
}
|
||||
}
|
||||
@@ -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<SlotState>,
|
||||
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<SlotState, SlabError> {
|
||||
self.slots
|
||||
.get(idx)
|
||||
.copied()
|
||||
.ok_or(SlabError::OutOfBounds { idx, cap: self.slots.len() })
|
||||
}
|
||||
|
||||
pub fn find_free(&self) -> Option<usize> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<i32>,
|
||||
/// Optional scalar draft probabilities `q(x_j)` for lossless non-greedy Leviathan verification.
|
||||
pub draft_probs: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
/// Pluggable speculative drafter:
|
||||
/// - Local MTP (1-layer) / Block-Diffusion preview
|
||||
/// - Remote LAN drafter on **Lyra** (`~128 B/step`, `~0.3 ms` RTT on 2.5 Gbps Ethernet)
|
||||
pub trait DraftProvider: Send {
|
||||
fn name(&self) -> &'static str;
|
||||
fn propose(&mut self, prefix_tail: &[i32], max_k: usize) -> Result<DraftProposal, String>;
|
||||
fn notify_accepted(&mut self, accepted_tokens: &[i32]) -> Result<(), String>;
|
||||
fn reset(&mut self);
|
||||
}
|
||||
|
||||
/// Pluggable MoE prefetch advisor:
|
||||
/// - Local router lookahead (`h_{L-1} -> W_router[L]`)
|
||||
/// - Remote domain classifier on **Lyra** (`Dante/letteratura` vs `Lean 4/matematica` -> NVMe pre-warm)
|
||||
pub trait PrefetchAdvisor: Send {
|
||||
fn on_prompt_domain(&mut self, domain_tag: &str) -> Vec<ExpertKey>;
|
||||
fn on_layer_routed(&mut self, layer: u16, active_experts: &[u16]) -> Vec<ExpertKey>;
|
||||
}
|
||||
|
||||
/// Throughput-aware Adaptive-K speculative controller (prevents K=16 prose traps).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AdaptiveKController {
|
||||
k_max: usize,
|
||||
cur_k: usize,
|
||||
ema_ms_per_tok: [f64; 5], // index: 0->K=1, 1->K=4, 2->K=8, 3->K=12, 4->K=16
|
||||
full_k8_streak: u32,
|
||||
}
|
||||
|
||||
impl AdaptiveKController {
|
||||
pub fn new(k_max: usize) -> Self {
|
||||
let km = k_max.max(1);
|
||||
Self {
|
||||
k_max: km,
|
||||
cur_k: km.min(8),
|
||||
ema_ms_per_tok: [0.0; 5],
|
||||
full_k8_streak: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_k(&self, rem_tokens: usize, ctx_room: usize) -> usize {
|
||||
self.cur_k.min(self.k_max).min(rem_tokens.max(1)).min(ctx_room.max(1))
|
||||
}
|
||||
|
||||
fn bucket(k: usize) -> usize {
|
||||
match k {
|
||||
0..=1 => 0,
|
||||
2..=4 => 1,
|
||||
5..=8 => 2,
|
||||
9..=12 => 3,
|
||||
_ => 4,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn observe(&mut self, k_used: usize, accepted: usize, step_ms: f64) {
|
||||
let mpt = step_ms / (accepted.max(1) as f64);
|
||||
let b = Self::bucket(k_used);
|
||||
self.ema_ms_per_tok[b] = if self.ema_ms_per_tok[b] == 0.0 {
|
||||
mpt
|
||||
} else {
|
||||
0.7 * self.ema_ms_per_tok[b] + 0.3 * mpt
|
||||
};
|
||||
|
||||
if k_used >= 8 && accepted >= k_used {
|
||||
self.full_k8_streak += 1;
|
||||
} else {
|
||||
self.full_k8_streak = 0;
|
||||
}
|
||||
|
||||
if accepted <= 2 && self.cur_k > 4 {
|
||||
self.cur_k = 4;
|
||||
} else if self.full_k8_streak >= 2 && self.k_max >= 16 {
|
||||
// Only promote to K=16 if K=16 isn't demonstrably slower per token than K=8
|
||||
if self.ema_ms_per_tok[4] == 0.0
|
||||
|| self.ema_ms_per_tok[2] == 0.0
|
||||
|| self.ema_ms_per_tok[4] <= self.ema_ms_per_tok[2] * 1.02
|
||||
{
|
||||
self.cur_k = 16;
|
||||
}
|
||||
} else if accepted >= 4 && self.cur_k < 8 && self.k_max >= 8 {
|
||||
self.cur_k = 8;
|
||||
} else if k_used >= 16 && accepted < 10 {
|
||||
self.cur_k = 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "vetta-hip"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
vetta-core = { path = "../vetta-core" }
|
||||
@@ -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<Vec<u8>>,
|
||||
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<SlotState, SlabError> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "vetta-io"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
vetta-core = { path = "../vetta-core" }
|
||||
@@ -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.<pid>` atomic commit) by construction.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ============================================================================
|
||||
// 1. Minimal Checked JSON Parser (zero external deps, strict UTF-8/escapes)
|
||||
// ============================================================================
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum JsonVal {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Num(f64),
|
||||
Int(u64),
|
||||
Str(String),
|
||||
Arr(Vec<JsonVal>),
|
||||
Obj(HashMap<String, JsonVal>),
|
||||
}
|
||||
|
||||
impl JsonVal {
|
||||
pub fn as_obj(&self) -> Option<&HashMap<String, JsonVal>> {
|
||||
match self {
|
||||
JsonVal::Obj(m) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn as_arr(&self) -> Option<&[JsonVal]> {
|
||||
match self {
|
||||
JsonVal::Arr(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn as_str(&self) -> Option<&str> {
|
||||
match self {
|
||||
JsonVal::Str(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn as_u64(&self) -> Option<u64> {
|
||||
match self {
|
||||
JsonVal::Int(n) => Some(*n),
|
||||
JsonVal::Num(f) if *f >= 0.0 && f.fract() == 0.0 && *f <= (u64::MAX as f64) => Some(*f as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct JsonParser<'a> {
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl<'a> JsonParser<'a> {
|
||||
fn skip_ws(&mut self) {
|
||||
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\r' | b'\t') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_str(&mut self) -> Result<String, String> {
|
||||
if self.b.get(self.i) != Some(&b'"') {
|
||||
return Err("expected '\"'".into());
|
||||
}
|
||||
self.i += 1;
|
||||
let mut out = Vec::new();
|
||||
while self.i < self.b.len() {
|
||||
let c = self.b[self.i];
|
||||
self.i += 1;
|
||||
if c == b'"' {
|
||||
return String::from_utf8(out).map_err(|_| "invalid UTF-8 in JSON string".into());
|
||||
}
|
||||
if c == b'\\' {
|
||||
if self.i >= self.b.len() {
|
||||
return Err("truncated JSON escape".into());
|
||||
}
|
||||
let e = self.b[self.i];
|
||||
self.i += 1;
|
||||
match e {
|
||||
b'"' => out.push(b'"'),
|
||||
b'\\' => out.push(b'\\'),
|
||||
b'/' => out.push(b'/'),
|
||||
b'b' => out.push(0x08),
|
||||
b'f' => out.push(0x0C),
|
||||
b'n' => out.push(b'\n'),
|
||||
b'r' => out.push(b'\r'),
|
||||
b't' => out.push(b'\t'),
|
||||
b'u' => {
|
||||
if self.i + 4 > self.b.len() {
|
||||
return Err("truncated \\u escape".into());
|
||||
}
|
||||
let hex = std::str::from_utf8(&self.b[self.i..self.i + 4])
|
||||
.map_err(|_| "bad \\u hex")?;
|
||||
let code = u32::from_str_radix(hex, 16).map_err(|_| "bad \\u hex")?;
|
||||
self.i += 4;
|
||||
let ch = char::from_u32(code).unwrap_or('\u{FFFD}');
|
||||
let mut buf = [0u8; 4];
|
||||
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
|
||||
}
|
||||
_ => return Err("unsupported JSON escape".into()),
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err("unterminated JSON string".into())
|
||||
}
|
||||
|
||||
fn parse_val(&mut self, depth: usize) -> Result<JsonVal, String> {
|
||||
if depth > 64 {
|
||||
return Err("JSON nesting too deep".into());
|
||||
}
|
||||
self.skip_ws();
|
||||
let &c = self.b.get(self.i).ok_or_else(|| "unexpected EOF in JSON".to_string())?;
|
||||
match c {
|
||||
b'"' => Ok(JsonVal::Str(self.parse_str()?)),
|
||||
b'{' => {
|
||||
self.i += 1;
|
||||
let mut map = HashMap::new();
|
||||
self.skip_ws();
|
||||
if self.b.get(self.i) == Some(&b'}') {
|
||||
self.i += 1;
|
||||
return Ok(JsonVal::Obj(map));
|
||||
}
|
||||
loop {
|
||||
self.skip_ws();
|
||||
let k = self.parse_str()?;
|
||||
self.skip_ws();
|
||||
if self.b.get(self.i) != Some(&b':') {
|
||||
return Err("expected ':'".into());
|
||||
}
|
||||
self.i += 1;
|
||||
let v = self.parse_val(depth + 1)?;
|
||||
map.insert(k, v);
|
||||
self.skip_ws();
|
||||
match self.b.get(self.i) {
|
||||
Some(&b',') => self.i += 1,
|
||||
Some(&b'}') => {
|
||||
self.i += 1;
|
||||
return Ok(JsonVal::Obj(map));
|
||||
}
|
||||
_ => return Err("expected ',' or '}'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
b'[' => {
|
||||
self.i += 1;
|
||||
let mut arr = Vec::new();
|
||||
self.skip_ws();
|
||||
if self.b.get(self.i) == Some(&b']') {
|
||||
self.i += 1;
|
||||
return Ok(JsonVal::Arr(arr));
|
||||
}
|
||||
loop {
|
||||
arr.push(self.parse_val(depth + 1)?);
|
||||
self.skip_ws();
|
||||
match self.b.get(self.i) {
|
||||
Some(&b',') => self.i += 1,
|
||||
Some(&b']') => {
|
||||
self.i += 1;
|
||||
return Ok(JsonVal::Arr(arr));
|
||||
}
|
||||
_ => return Err("expected ',' or ']'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
b't' if self.b[self.i..].starts_with(b"true") => {
|
||||
self.i += 4;
|
||||
Ok(JsonVal::Bool(true))
|
||||
}
|
||||
b'f' if self.b[self.i..].starts_with(b"false") => {
|
||||
self.i += 5;
|
||||
Ok(JsonVal::Bool(false))
|
||||
}
|
||||
b'n' if self.b[self.i..].starts_with(b"null") => {
|
||||
self.i += 4;
|
||||
Ok(JsonVal::Null)
|
||||
}
|
||||
b'-' | b'0'..=b'9' => {
|
||||
let start = self.i;
|
||||
if self.b[self.i] == b'-' {
|
||||
self.i += 1;
|
||||
}
|
||||
let mut is_float = false;
|
||||
while self.i < self.b.len() {
|
||||
match self.b[self.i] {
|
||||
b'0'..=b'9' => self.i += 1,
|
||||
b'.' | b'e' | b'E' | b'+' | b'-' => {
|
||||
is_float = true;
|
||||
self.i += 1;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
let s = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| "bad number")?;
|
||||
if !is_float && !s.starts_with('-') {
|
||||
if let Ok(u) = s.parse::<u64>() {
|
||||
return Ok(JsonVal::Int(u));
|
||||
}
|
||||
}
|
||||
let f = s.parse::<f64>().map_err(|_| format!("invalid number '{s}'"))?;
|
||||
Ok(JsonVal::Num(f))
|
||||
}
|
||||
_ => Err(format!("unexpected char '{}' in JSON", c as char)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_json(text: &str) -> Result<JsonVal, String> {
|
||||
let mut p = JsonParser { b: text.as_bytes(), i: 0 };
|
||||
let v = p.parse_val(0)?;
|
||||
p.skip_ws();
|
||||
if p.i != p.b.len() {
|
||||
return Err("trailing characters in JSON".into());
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 2. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
|
||||
// ============================================================================
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TensorInfo {
|
||||
pub shard_idx: usize,
|
||||
pub dtype: String,
|
||||
pub shape: Vec<u64>,
|
||||
pub begin: u64,
|
||||
pub end: u64,
|
||||
}
|
||||
|
||||
impl TensorInfo {
|
||||
pub fn byte_len(&self) -> u64 {
|
||||
self.end - self.begin
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SafetensorsShard {
|
||||
pub path: PathBuf,
|
||||
pub file: File,
|
||||
pub file_size: u64,
|
||||
pub data_start: u64,
|
||||
}
|
||||
|
||||
pub struct SafetensorsArchive {
|
||||
pub dir: PathBuf,
|
||||
pub shards: Vec<SafetensorsShard>,
|
||||
pub tensors: HashMap<String, TensorInfo>,
|
||||
}
|
||||
|
||||
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
|
||||
|
||||
impl SafetensorsArchive {
|
||||
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
|
||||
let dir = dir.as_ref().to_path_buf();
|
||||
let shard_paths = discover_shards(&dir)?;
|
||||
if shard_paths.is_empty() {
|
||||
return Err(format!("no .safetensors shards found in {}", dir.display()));
|
||||
}
|
||||
|
||||
let mut shards = Vec::with_capacity(shard_paths.len());
|
||||
let mut tensors = HashMap::new();
|
||||
|
||||
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("open {}: {e}", path.display()))?;
|
||||
let file_size = file
|
||||
.metadata()
|
||||
.map_err(|e| format!("stat {}: {e}", path.display()))?
|
||||
.len();
|
||||
if file_size < 8 {
|
||||
return Err(format!("truncated safetensors file {}", path.display()));
|
||||
}
|
||||
let mut len_buf = [0u8; 8];
|
||||
file.read_exact_at(&mut len_buf, 0)
|
||||
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
|
||||
let hlen = u64::from_le_bytes(len_buf);
|
||||
let data_start = 8u64
|
||||
.checked_add(hlen)
|
||||
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
|
||||
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
|
||||
return Err(format!(
|
||||
"invalid header length {hlen} (file_size={file_size}) in {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
let mut hbytes = vec![0u8; hlen as usize];
|
||||
file.read_exact_at(&mut hbytes, 8)
|
||||
.map_err(|e| format!("read header {}: {e}", path.display()))?;
|
||||
let hstr = std::str::from_utf8(&hbytes)
|
||||
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
|
||||
let root = parse_json(hstr)?;
|
||||
let obj = root
|
||||
.as_obj()
|
||||
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
|
||||
let avail = file_size - data_start;
|
||||
|
||||
for (name, val) in obj {
|
||||
if name == "__metadata__" {
|
||||
continue;
|
||||
}
|
||||
let to = val
|
||||
.as_obj()
|
||||
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
|
||||
let dtype = to
|
||||
.get("dtype")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
|
||||
.to_string();
|
||||
let shape_arr = to
|
||||
.get("shape")
|
||||
.and_then(|v| v.as_arr())
|
||||
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
|
||||
let mut shape = Vec::with_capacity(shape_arr.len());
|
||||
for d in shape_arr {
|
||||
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
|
||||
}
|
||||
let offs = to
|
||||
.get("data_offsets")
|
||||
.and_then(|v| v.as_arr())
|
||||
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
|
||||
if offs.len() != 2 {
|
||||
return Err(format!("tensor '{name}' data_offsets len != 2"));
|
||||
}
|
||||
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
|
||||
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
|
||||
if end < begin || end > avail {
|
||||
return Err(format!(
|
||||
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
if tensors.contains_key(name) {
|
||||
return Err(format!("duplicate tensor '{name}' across shards"));
|
||||
}
|
||||
tensors.insert(
|
||||
name.clone(),
|
||||
TensorInfo {
|
||||
shard_idx,
|
||||
dtype,
|
||||
shape,
|
||||
begin,
|
||||
end,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
shards.push(SafetensorsShard {
|
||||
path,
|
||||
file,
|
||||
file_size,
|
||||
data_start,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Self { dir, shards, tensors })
|
||||
}
|
||||
|
||||
pub fn total_tensor_bytes(&self) -> u64 {
|
||||
self.tensors.values().map(|t| t.byte_len()).sum()
|
||||
}
|
||||
|
||||
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
|
||||
let info = self
|
||||
.tensors
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("tensor not found: {name}"))?;
|
||||
let total = info.byte_len();
|
||||
let req = dst.len() as u64;
|
||||
if rel_off > total || req > total - rel_off {
|
||||
return Err(format!(
|
||||
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
|
||||
));
|
||||
}
|
||||
let sh = &self.shards[info.shard_idx];
|
||||
let file_off = sh
|
||||
.data_start
|
||||
.checked_add(info.begin)
|
||||
.and_then(|v| v.checked_add(rel_off))
|
||||
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
|
||||
sh.file
|
||||
.read_exact_at(dst, file_off)
|
||||
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let idx_path = dir.join("model.safetensors.index.json");
|
||||
if idx_path.is_file() {
|
||||
let raw = fs::read_to_string(&idx_path)
|
||||
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
|
||||
let root = parse_json(&raw)?;
|
||||
let wm = root
|
||||
.as_obj()
|
||||
.and_then(|o| o.get("weight_map"))
|
||||
.and_then(|v| v.as_obj())
|
||||
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
|
||||
let mut uniq = BTreeSet::new();
|
||||
for v in wm.values() {
|
||||
if let Some(fname) = v.as_str() {
|
||||
if !fname.is_empty() {
|
||||
uniq.insert(dir.join(fname));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(uniq.into_iter().collect());
|
||||
}
|
||||
|
||||
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
|
||||
let mut out = Vec::new();
|
||||
for entry in entries {
|
||||
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
|
||||
let p = e.path();
|
||||
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 3. Unified Write-Once `O_RDONLY` NVMe Disk Cache (`VTC1`, PID `.tmp`, anti-OOM)
|
||||
// ============================================================================
|
||||
|
||||
pub const CACHE_MAGIC: [u8; 8] = *b"VTCACHE1";
|
||||
pub const CACHE_VERSION: u32 = 1;
|
||||
pub const CACHE_ALIGN: u64 = 4096;
|
||||
const HEADER_SIZE: usize = 48;
|
||||
const MIN_REC_BYTES: usize = 1 + 4 * 4 + 4 * 8 + 4; // 53 B minimum per serialized record
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CacheRecord {
|
||||
pub kind: u8,
|
||||
pub i0: i32,
|
||||
pub i1: i32,
|
||||
pub i2: i32,
|
||||
pub flags: u32,
|
||||
pub u0: u64,
|
||||
pub u1: u64,
|
||||
pub data_offset: u64,
|
||||
pub data_bytes: u64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub fn fnv1a_u64(bytes: &[u8], seed: u64) -> u64 {
|
||||
let mut h = seed;
|
||||
for &b in bytes {
|
||||
h ^= b as u64;
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01B3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
pub fn align_up(v: u64, align: u64) -> Result<u64, String> {
|
||||
let rem = v % align;
|
||||
if rem == 0 {
|
||||
Ok(v)
|
||||
} else {
|
||||
v.checked_add(align - rem).ok_or_else(|| "align_up overflow".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize_meta(recs: &[CacheRecord]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for r in recs {
|
||||
out.push(r.kind);
|
||||
out.extend_from_slice(&r.i0.to_le_bytes());
|
||||
out.extend_from_slice(&r.i1.to_le_bytes());
|
||||
out.extend_from_slice(&r.i2.to_le_bytes());
|
||||
out.extend_from_slice(&r.flags.to_le_bytes());
|
||||
out.extend_from_slice(&r.u0.to_le_bytes());
|
||||
out.extend_from_slice(&r.u1.to_le_bytes());
|
||||
out.extend_from_slice(&r.data_offset.to_le_bytes());
|
||||
out.extend_from_slice(&r.data_bytes.to_le_bytes());
|
||||
let nlen = r.name.len() as u32;
|
||||
out.extend_from_slice(&nlen.to_le_bytes());
|
||||
out.extend_from_slice(r.name.as_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn deserialize_meta(blob: &[u8], count: u32) -> Result<Vec<CacheRecord>, String> {
|
||||
// Anti-OOM check BEFORE `Vec::with_capacity(count)` (audit-05 F-05)
|
||||
if (count as usize) > blob.len() / MIN_REC_BYTES {
|
||||
return Err(format!(
|
||||
"corrupt cache metadata: count={count} exceeds blob capacity ({} B)",
|
||||
blob.len()
|
||||
));
|
||||
}
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
let mut pos = 0usize;
|
||||
let take = |pos: &mut usize, n: usize| -> Result<&[u8], String> {
|
||||
if n > blob.len().saturating_sub(*pos) {
|
||||
return Err("truncated cache metadata".into());
|
||||
}
|
||||
let s = &blob[*pos..*pos + n];
|
||||
*pos += n;
|
||||
Ok(s)
|
||||
};
|
||||
for _ in 0..count {
|
||||
let kind = take(&mut pos, 1)?[0];
|
||||
let i0 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
|
||||
let i1 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
|
||||
let i2 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
|
||||
let flags = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
|
||||
let u0 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
|
||||
let u1 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
|
||||
let data_offset = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
|
||||
let data_bytes = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
|
||||
let nlen = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap()) as usize;
|
||||
if nlen > 4096 {
|
||||
return Err("cache record name too long".into());
|
||||
}
|
||||
let nbytes = take(&mut pos, nlen)?;
|
||||
let name = std::str::from_utf8(nbytes)
|
||||
.map_err(|_| "non-UTF-8 cache record name")?
|
||||
.to_string();
|
||||
out.push(CacheRecord {
|
||||
kind,
|
||||
i0,
|
||||
i1,
|
||||
i2,
|
||||
flags,
|
||||
u0,
|
||||
u1,
|
||||
data_offset,
|
||||
data_bytes,
|
||||
name,
|
||||
});
|
||||
}
|
||||
if pos != blob.len() {
|
||||
return Err("trailing bytes in cache metadata".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub struct DiskCacheWriter {
|
||||
final_path: PathBuf,
|
||||
tmp_path: PathBuf,
|
||||
file: Option<File>,
|
||||
fingerprint: u64,
|
||||
cursor: u64,
|
||||
records: Vec<CacheRecord>,
|
||||
}
|
||||
|
||||
impl DiskCacheWriter {
|
||||
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
|
||||
let final_path = final_path.as_ref().to_path_buf();
|
||||
if let Some(parent) = final_path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
|
||||
}
|
||||
let pid = std::process::id();
|
||||
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&tmp_path)
|
||||
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
|
||||
Ok(Self {
|
||||
final_path,
|
||||
tmp_path,
|
||||
file: Some(file),
|
||||
fingerprint,
|
||||
cursor: CACHE_ALIGN,
|
||||
records: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
|
||||
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
|
||||
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
|
||||
rec.data_bytes = payload.len() as u64;
|
||||
self.cursor = align_up(
|
||||
rec.data_offset
|
||||
.checked_add(rec.data_bytes)
|
||||
.ok_or_else(|| "cache offset overflow".to_string())?,
|
||||
CACHE_ALIGN,
|
||||
)?;
|
||||
f.write_all_at(payload, rec.data_offset)
|
||||
.map_err(|e| format!("write payload: {e}"))?;
|
||||
let off = rec.data_offset;
|
||||
self.records.push(rec);
|
||||
Ok(off)
|
||||
}
|
||||
|
||||
pub fn commit(mut self) -> Result<PathBuf, String> {
|
||||
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
|
||||
let meta = serialize_meta(&self.records);
|
||||
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
|
||||
f.write_all_at(&meta, meta_off)
|
||||
.map_err(|e| format!("write meta: {e}"))?;
|
||||
let total_bytes = meta_off
|
||||
.checked_add(meta.len() as u64)
|
||||
.ok_or_else(|| "total_bytes overflow".to_string())?;
|
||||
|
||||
let mut hdr = [0u8; HEADER_SIZE];
|
||||
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
|
||||
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
|
||||
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
|
||||
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
|
||||
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
|
||||
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
|
||||
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
|
||||
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
|
||||
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
|
||||
drop(f);
|
||||
fs::rename(&self.tmp_path, &self.final_path)
|
||||
.map_err(|e| format!("rename cache: {e}"))?;
|
||||
Ok(self.final_path.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DiskCacheWriter {
|
||||
fn drop(&mut self) {
|
||||
if self.file.take().is_some() {
|
||||
let _ = fs::remove_file(&self.tmp_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strictly `O_RDONLY` cache reader (0 SSD writes on every reload).
|
||||
pub struct DiskCacheReader {
|
||||
file: File,
|
||||
pub file_size: u64,
|
||||
pub records: Vec<CacheRecord>,
|
||||
}
|
||||
|
||||
impl DiskCacheReader {
|
||||
pub fn open_and_validate(path: impl AsRef<Path>, expected_fp: u64) -> Result<Self, String> {
|
||||
let path = path.as_ref();
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(path)
|
||||
.map_err(|e| format!("open cache {}: {e}", path.display()))?;
|
||||
let file_size = file.metadata().map_err(|e| format!("stat cache: {e}"))?.len();
|
||||
if file_size < HEADER_SIZE as u64 {
|
||||
return Err("cache file too small".into());
|
||||
}
|
||||
let mut hdr = [0u8; HEADER_SIZE];
|
||||
file.read_exact_at(&mut hdr, 0)
|
||||
.map_err(|e| format!("read cache hdr: {e}"))?;
|
||||
if hdr[0..8] != CACHE_MAGIC {
|
||||
return Err("cache bad magic".into());
|
||||
}
|
||||
let version = u32::from_le_bytes(hdr[8..12].try_into().unwrap());
|
||||
if version != CACHE_VERSION {
|
||||
return Err(format!("cache version mismatch: {version}"));
|
||||
}
|
||||
let count = u32::from_le_bytes(hdr[12..16].try_into().unwrap());
|
||||
let fp = u64::from_le_bytes(hdr[16..24].try_into().unwrap());
|
||||
if fp != expected_fp {
|
||||
return Err("cache fingerprint mismatch".into());
|
||||
}
|
||||
let meta_off = u64::from_le_bytes(hdr[24..32].try_into().unwrap());
|
||||
let meta_bytes = u64::from_le_bytes(hdr[32..40].try_into().unwrap());
|
||||
let total_bytes = u64::from_le_bytes(hdr[40..48].try_into().unwrap());
|
||||
if total_bytes != file_size {
|
||||
return Err("cache file size mismatch (incomplete)".into());
|
||||
}
|
||||
if meta_off < HEADER_SIZE as u64
|
||||
|| meta_off > file_size
|
||||
|| meta_bytes > file_size - meta_off
|
||||
|| meta_bytes > 64 * 1024 * 1024
|
||||
{
|
||||
return Err("cache metadata out of bounds".into());
|
||||
}
|
||||
let mut mblob = vec![0u8; meta_bytes as usize];
|
||||
file.read_exact_at(&mut mblob, meta_off)
|
||||
.map_err(|e| format!("read cache meta: {e}"))?;
|
||||
let records = deserialize_meta(&mblob, count)?;
|
||||
for r in &records {
|
||||
if r.data_offset > file_size || r.data_bytes > file_size - r.data_offset {
|
||||
return Err(format!("cache record '{}' payload OOB", r.name));
|
||||
}
|
||||
}
|
||||
Ok(Self { file, file_size, records })
|
||||
}
|
||||
|
||||
pub fn read_slice(&self, off: u64, dst: &mut [u8]) -> Result<(), String> {
|
||||
let len = dst.len() as u64;
|
||||
if off > self.file_size || len > self.file_size - off {
|
||||
return Err("cache read_slice OOB".into());
|
||||
}
|
||||
self.file
|
||||
.read_exact_at(dst, off)
|
||||
.map_err(|e| format!("cache pread: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
// Keep unused imports clean if needed
|
||||
#[allow(dead_code)]
|
||||
fn _touch_io(_: &mut dyn Read, _: &mut dyn Write) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
|
||||
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
|
||||
let hdr = format!(
|
||||
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
|
||||
data.len() / 4
|
||||
);
|
||||
let mut f = File::create(path).unwrap();
|
||||
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
|
||||
f.write_all(hdr.as_bytes()).unwrap();
|
||||
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
|
||||
f.write_all(&data[..take]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safetensors_bounds_overflow_and_index_json() {
|
||||
let root = std::env::temp_dir().join(format!("vetta_io_test_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
|
||||
// Non-existent dir fails cleanly
|
||||
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
|
||||
|
||||
// Truncated shard rejected
|
||||
let d_trunc = root.join("trunc");
|
||||
fs::create_dir_all(&d_trunc).unwrap();
|
||||
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
|
||||
assert!(SafetensorsArchive::open(&d_trunc).is_err());
|
||||
|
||||
// Inverted offsets rejected
|
||||
let d_inv = root.join("inv");
|
||||
fs::create_dir_all(&d_inv).unwrap();
|
||||
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
|
||||
assert!(SafetensorsArchive::open(&d_inv).is_err());
|
||||
|
||||
// Valid + index.json ignoring stray backup + u64 overflow slice check
|
||||
let d_ok = root.join("ok");
|
||||
fs::create_dir_all(&d_ok).unwrap();
|
||||
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
|
||||
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
|
||||
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
|
||||
fs::write(
|
||||
d_ok.join("model.safetensors.index.json"),
|
||||
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let ar = SafetensorsArchive::open(&d_ok).unwrap();
|
||||
assert_eq!(ar.shards.len(), 1);
|
||||
let mut got = [0u8; 4];
|
||||
ar.read_slice("w", 4, &mut got).unwrap();
|
||||
assert_eq!(got, [50, 60, 70, 80]);
|
||||
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
|
||||
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_cache_roundtrip_and_anti_oom() {
|
||||
// Absurd entry count rejected BEFORE Vec::with_capacity
|
||||
assert!(deserialize_meta(&[0u8; 64], u32::MAX).is_err());
|
||||
|
||||
let p = std::env::temp_dir().join(format!("vetta_cache_test_{}.bin", std::process::id()));
|
||||
let _ = fs::remove_file(&p);
|
||||
let fp = 0x1234_5678_ABCD_EF01u64;
|
||||
let payload = vec![0x5Au8; 8192];
|
||||
|
||||
let mut wr = DiskCacheWriter::begin(&p, fp).unwrap();
|
||||
wr.write_record(
|
||||
CacheRecord {
|
||||
kind: 1,
|
||||
i0: 128,
|
||||
i1: 256,
|
||||
i2: 0,
|
||||
flags: 0,
|
||||
u0: 4096,
|
||||
u1: 0,
|
||||
data_offset: 0,
|
||||
data_bytes: 0,
|
||||
name: "layer.0.q8".into(),
|
||||
},
|
||||
&payload,
|
||||
)
|
||||
.unwrap();
|
||||
wr.commit().unwrap();
|
||||
|
||||
let rd = DiskCacheReader::open_and_validate(&p, fp).unwrap();
|
||||
assert_eq!(rd.records.len(), 1);
|
||||
let mut got = vec![0u8; payload.len()];
|
||||
rd.read_slice(rd.records[0].data_offset, &mut got).unwrap();
|
||||
assert_eq!(got, payload);
|
||||
assert!(DiskCacheReader::open_and_validate(&p, fp ^ 1).is_err());
|
||||
|
||||
let _ = fs::remove_file(&p);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "vetta-proto"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
vetta-core = { path = "../vetta-core" }
|
||||
@@ -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<usize>,
|
||||
pub draft_top_k: Option<usize>,
|
||||
pub domain_hint: Option<String>,
|
||||
pub ids: Vec<i32>,
|
||||
}
|
||||
|
||||
pub fn parse_id_csv(csv: &str, vocab_size: usize) -> Result<Vec<i32>, String> {
|
||||
if csv.is_empty() {
|
||||
return Err("empty token id list".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for piece in csv.split(',') {
|
||||
if piece.is_empty() {
|
||||
return Err("empty token id in CSV".into());
|
||||
}
|
||||
let id: u64 = piece
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid token id '{piece}'"))?;
|
||||
if id >= vocab_size as u64 {
|
||||
return Err(format!("token id {id} out of vocab bounds [0, {vocab_size})"));
|
||||
}
|
||||
out.push(id as i32);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, String> {
|
||||
let trimmed = line.trim();
|
||||
match trimmed {
|
||||
"QUIT" | "EXIT" => return Ok(ServeCommand::Quit),
|
||||
"RESET" | "CLEAR" => return Ok(ServeCommand::Reset),
|
||||
"STOP" => return Ok(ServeCommand::Stop),
|
||||
_ => {}
|
||||
}
|
||||
let toks: Vec<&str> = trimmed.split_whitespace().collect();
|
||||
if toks.len() < 3 || toks[0] != "GEN" {
|
||||
return Err("GEN: expected 'GEN <max_new> [key=val ...] <ids>'".into());
|
||||
}
|
||||
let max_new: u64 = toks[1].parse().map_err(|_| "GEN: bad max_new".to_string())?;
|
||||
if max_new > 1_000_000 {
|
||||
return Err("GEN: max_new out of range".into());
|
||||
}
|
||||
|
||||
let mut sampling = SamplingOpts::default();
|
||||
let mut spec_mode = None;
|
||||
let mut draft_top_k = None;
|
||||
let mut domain_hint = None;
|
||||
|
||||
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<f32, String> {
|
||||
let f: f32 = v.parse().map_err(|_| format!("GEN: bad numeric value for {key}"))?;
|
||||
if !f.is_finite() {
|
||||
return Err(format!("GEN: non-finite value for {key}"));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Compact LAN RPC messages for Sogliola <-> Lyra (`< 1 KB/step` on 2.5 Gbps Ethernet).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum LyraRpc {
|
||||
DraftRequest { session_id: u64, accepted_tail: Vec<i32>, max_k: u8 },
|
||||
DraftResponse { session_id: u64, proposed: Vec<i32>, probs: Vec<f32> },
|
||||
DomainHint { session_id: u64, domain: String, confidence: f32 },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "vetta-telemetry"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
vetta-core = { path = "../vetta-core" }
|
||||
@@ -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<u16>,
|
||||
active_experts: Vec<u16>,
|
||||
},
|
||||
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<ExpertKey, u64>,
|
||||
/// `domain -> ((layer, expert) -> activations)` for domain-aware NVMe Hot/Cold pre-warming!
|
||||
pub domain_profiles: HashMap<String, HashMap<ExpertKey, u64>>,
|
||||
/// `(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<SyncSender<TelemetryEvent>>,
|
||||
worker: Option<JoinHandle<RoutingStats>>,
|
||||
pub dropped_events: u64,
|
||||
}
|
||||
|
||||
impl TelemetryHandle {
|
||||
pub fn start(jsonl_path: Option<&Path>, channel_cap: usize) -> Result<Self, String> {
|
||||
let (tx, rx) = mpsc::sync_channel::<TelemetryEvent>(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: Write>(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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user