[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,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user