Dissolve the M0 crates (core/io/proto/telemetry/hip/cli) into the approved service layout abi/kn/ld/cc/rt/lab/sp/nt/tm/gw (docs/ARCHITECTURE.md). - kn: Lean-verified control bus + service registry (bus_lifecycle.lean, 14 thms) and SlabRing/UMA broker; rt: PrefixState + hybrid checkpoint pool. - sp: faithful throughput-aware Adaptive-K port of clover_policy.h (cooldowns, probes, throughput guards) with scenario parity tests. - gw: strata-ctl-compatible wire emitters + serve session FSM (serve_session.lean, 10 thms); abi::serve accepts image= (Vision delta closed). - abi: pure contracts, checked JSON/VTC1/GEN parsers, zero-alloc sampler. - ld/cc: checked safetensors reader + write-once VTC1 writer / O_RDONLY reader. - tm: lock-free telemetry; nt: LyraRpc; lab shares the rt executor core. - Docs: ARCHITECTURE.md decision-complete spec (MoE-only scope, .vbundle, .vplan->CompiledPlan, wire contract, migration map); AGENTS.md Lean rule + tandem/review workflow. Verified live: cargo test --workspace -D warnings = 46/46 PASS; lean proofs = 34 theorems (slab_ring_dma 10, bus_lifecycle 14, serve_session 10), 0 sorryAx, standard axioms only; vetta-infer info on Inkling = 1244 tensors, 18.18 GiB, checked bounds.
474 lines
14 KiB
Rust
474 lines
14 KiB
Rust
//! Deterministic zero-allocation top-K sampler, exact penalties, and Leviathan speculative verifier.
|
|
//!
|
|
//! Eliminates F-07 (centralized `mask_token_id` suppression) and F-09 (no 1 MiB/token heap churn,
|
|
//! no silent 256-token truncation for `top_k == 0`, explicit non-finite logit count).
|
|
//! Pure algorithms shared by `rt`, `sp` and `gw` (docs/ARCHITECTURE.md §9).
|
|
|
|
use std::cmp::Ordering;
|
|
use std::collections::{BinaryHeap, HashMap};
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
pub struct SamplingOpts {
|
|
pub temperature: f32,
|
|
pub top_k: usize,
|
|
pub top_p: f32,
|
|
pub min_p: f32,
|
|
pub penalty_repeat: f32,
|
|
pub penalty_freq: f32,
|
|
pub penalty_present: f32,
|
|
pub penalty_last_n: usize,
|
|
pub seed: u64,
|
|
}
|
|
|
|
impl Default for SamplingOpts {
|
|
fn default() -> Self {
|
|
Self {
|
|
temperature: 0.0,
|
|
top_k: 0,
|
|
top_p: 1.0,
|
|
min_p: 0.0,
|
|
penalty_repeat: 1.0,
|
|
penalty_freq: 0.0,
|
|
penalty_present: 0.0,
|
|
penalty_last_n: 64,
|
|
seed: 42,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl SamplingOpts {
|
|
pub fn is_greedy(&self) -> bool {
|
|
self.temperature <= 0.0
|
|
}
|
|
|
|
pub fn has_penalties(&self) -> bool {
|
|
self.penalty_last_n > 0
|
|
&& (self.penalty_repeat != 1.0
|
|
|| self.penalty_freq != 0.0
|
|
|| self.penalty_present != 0.0)
|
|
}
|
|
}
|
|
|
|
/// SplitMix64 deterministic RNG (zero external crate deps, fast & reproducible).
|
|
#[derive(Debug, Clone)]
|
|
pub struct SplitMix64 {
|
|
state: u64,
|
|
}
|
|
|
|
impl SplitMix64 {
|
|
pub fn new(seed: u64) -> Self {
|
|
Self { state: if seed == 0 { 0x9E37_79B9_7F4A_7C15 } else { seed } }
|
|
}
|
|
|
|
pub fn next_u64(&mut self) -> u64 {
|
|
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let mut z = self.state;
|
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
z ^ (z >> 31)
|
|
}
|
|
|
|
/// Uniform float in `[0, 1)`.
|
|
pub fn next_f64(&mut self) -> f64 {
|
|
(self.next_u64() >> 11) as f64 * (1.0 / ((1u64 << 53) as f64))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
struct Cand {
|
|
val: f32,
|
|
id: i32,
|
|
}
|
|
|
|
impl PartialEq for Cand {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.id == other.id && self.val.to_bits() == other.val.to_bits()
|
|
}
|
|
}
|
|
impl Eq for Cand {}
|
|
|
|
/// Reverse order so `BinaryHeap<MinCand>` keeps the WORST candidate on top (min-heap of top-K).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
struct MinCand(Cand);
|
|
|
|
impl Ord for MinCand {
|
|
fn cmp(&self, other: &Self) -> Ordering {
|
|
// Better = higher val, or equal val with smaller id.
|
|
// For min-heap, `other` better than `self` => self > other (so worst is popped first).
|
|
match other.0.val.total_cmp(&self.0.val) {
|
|
Ordering::Equal => self.0.id.cmp(&other.0.id),
|
|
ord => ord,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl PartialOrd for MinCand {
|
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
|
Some(self.cmp(other))
|
|
}
|
|
}
|
|
|
|
fn cand_desc(a: &Cand, b: &Cand) -> Ordering {
|
|
match b.val.total_cmp(&a.val) {
|
|
Ordering::Equal => a.id.cmp(&b.id),
|
|
ord => ord,
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Default, Clone)]
|
|
pub struct SamplerScratch {
|
|
pub idx: Vec<i32>,
|
|
pub prob: Vec<f64>,
|
|
cands: Vec<Cand>,
|
|
counts: HashMap<i32, u32>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, Default)]
|
|
pub struct SampleReport {
|
|
pub token: i32,
|
|
pub confidence: f32,
|
|
pub nonfinite_logits: usize,
|
|
pub entropy_nats: f32,
|
|
}
|
|
|
|
pub fn suppress_token(logits: &mut [f32], banned: Option<i32>) {
|
|
if let Some(id) = banned {
|
|
if id >= 0 && (id as usize) < logits.len() {
|
|
logits[id as usize] = f32::NEG_INFINITY;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn apply_penalties(logits: &mut [f32], opts: &SamplingOpts, history: &[i32], scratch: &mut SamplerScratch) {
|
|
if !opts.has_penalties() || history.is_empty() || logits.is_empty() {
|
|
return;
|
|
}
|
|
scratch.counts.clear();
|
|
let win = history.len().min(opts.penalty_last_n);
|
|
for &id in &history[history.len() - win..] {
|
|
if id >= 0 && (id as usize) < logits.len() {
|
|
*scratch.counts.entry(id).or_insert(0) += 1;
|
|
}
|
|
}
|
|
for (&id, &cnt) in &scratch.counts {
|
|
let v = &mut logits[id as usize];
|
|
if !v.is_finite() {
|
|
continue;
|
|
}
|
|
if opts.penalty_repeat != 1.0 {
|
|
*v = if *v > 0.0 { *v / opts.penalty_repeat } else { *v * opts.penalty_repeat };
|
|
}
|
|
if opts.penalty_freq != 0.0 {
|
|
*v -= opts.penalty_freq * (cnt as f32);
|
|
}
|
|
if opts.penalty_present != 0.0 {
|
|
*v -= opts.penalty_present;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Builds a normalized/unnormalized truncated distribution into `scratch.{idx, prob}`.
|
|
/// Returns the number of non-finite logits encountered.
|
|
pub fn build_truncated_dist(
|
|
logits: &mut [f32],
|
|
opts: &SamplingOpts,
|
|
history: &[i32],
|
|
banned: Option<i32>,
|
|
scratch: &mut SamplerScratch,
|
|
) -> usize {
|
|
scratch.idx.clear();
|
|
scratch.prob.clear();
|
|
if logits.is_empty() {
|
|
return 0;
|
|
}
|
|
suppress_token(logits, banned);
|
|
apply_penalties(logits, opts, history, scratch);
|
|
|
|
let v = logits.len();
|
|
let mut nonfinite = 0usize;
|
|
let mut mx = f32::NEG_INFINITY;
|
|
for &val in logits.iter() {
|
|
if !val.is_finite() {
|
|
if val.is_nan() || val.is_infinite() && val.is_sign_positive() {
|
|
nonfinite += 1;
|
|
}
|
|
} else if val > mx {
|
|
mx = val;
|
|
}
|
|
}
|
|
if !mx.is_finite() {
|
|
scratch.idx.push(0);
|
|
scratch.prob.push(1.0);
|
|
return nonfinite;
|
|
}
|
|
|
|
let inv_t = 1.0f64 / (opts.temperature as f64).max(1e-6);
|
|
|
|
scratch.cands.clear();
|
|
if opts.top_k > 0 && opts.top_k < v && opts.top_k <= 512 {
|
|
let mut heap: BinaryHeap<MinCand> = BinaryHeap::with_capacity(opts.top_k + 1);
|
|
for (i, &val) in logits.iter().enumerate() {
|
|
if !val.is_finite() {
|
|
continue;
|
|
}
|
|
let c = MinCand(Cand { val, id: i as i32 });
|
|
if heap.len() < opts.top_k {
|
|
heap.push(c);
|
|
} else if let Some(&top) = heap.peek() {
|
|
if cand_desc(&c.0, &top.0) == Ordering::Less {
|
|
heap.pop();
|
|
heap.push(c);
|
|
}
|
|
}
|
|
}
|
|
scratch.cands.extend(heap.into_iter().map(|m| m.0));
|
|
scratch.cands.sort_unstable_by(cand_desc);
|
|
} else {
|
|
let logit_floor = if opts.min_p > 0.0 && opts.min_p < 1.0 && opts.top_k == 0 {
|
|
(mx as f64 + (opts.min_p as f64).ln() / inv_t) as f32
|
|
} else {
|
|
f32::NEG_INFINITY
|
|
};
|
|
for (i, &val) in logits.iter().enumerate() {
|
|
if !val.is_finite() {
|
|
continue;
|
|
}
|
|
if val < logit_floor && val < mx {
|
|
continue;
|
|
}
|
|
scratch.cands.push(Cand { val, id: i as i32 });
|
|
}
|
|
if scratch.cands.is_empty() {
|
|
scratch.idx.push(0);
|
|
scratch.prob.push(1.0);
|
|
return nonfinite;
|
|
}
|
|
let need_sort = (opts.top_k > 0 && opts.top_k < scratch.cands.len())
|
|
|| (opts.top_p > 0.0 && opts.top_p < 1.0);
|
|
if opts.top_k > 0 && opts.top_k < scratch.cands.len() {
|
|
scratch.cands.select_nth_unstable_by(opts.top_k, cand_desc);
|
|
scratch.cands.truncate(opts.top_k);
|
|
scratch.cands.sort_unstable_by(cand_desc);
|
|
} else if need_sort {
|
|
scratch.cands.sort_unstable_by(cand_desc);
|
|
}
|
|
}
|
|
|
|
let mut p_max = 0.0f64;
|
|
let mut z = 0.0f64;
|
|
for c in &scratch.cands {
|
|
let w = (((c.val as f64) - (mx as f64)) * inv_t).exp();
|
|
if w > p_max {
|
|
p_max = w;
|
|
}
|
|
scratch.idx.push(c.id);
|
|
scratch.prob.push(w);
|
|
z += w;
|
|
}
|
|
if z <= 0.0 {
|
|
let first = scratch.idx.first().copied().unwrap_or(0);
|
|
scratch.idx.clear();
|
|
scratch.prob.clear();
|
|
scratch.idx.push(first);
|
|
scratch.prob.push(1.0);
|
|
return nonfinite;
|
|
}
|
|
|
|
if opts.min_p > 0.0 && opts.min_p < 1.0 {
|
|
let thresh = (opts.min_p as f64) * p_max;
|
|
let mut keep = 0usize;
|
|
for i in 0..scratch.idx.len() {
|
|
if i == 0 || scratch.prob[i] >= thresh {
|
|
scratch.idx[keep] = scratch.idx[i];
|
|
scratch.prob[keep] = scratch.prob[i];
|
|
keep += 1;
|
|
}
|
|
}
|
|
scratch.idx.truncate(keep);
|
|
scratch.prob.truncate(keep);
|
|
}
|
|
|
|
if opts.top_p > 0.0 && opts.top_p < 1.0 && scratch.idx.len() > 1 {
|
|
let z2: f64 = scratch.prob.iter().sum();
|
|
let inv_z2 = 1.0 / z2.max(1e-30);
|
|
let mut cum = 0.0f64;
|
|
let mut keep = scratch.idx.len();
|
|
for i in 0..scratch.idx.len() {
|
|
cum += scratch.prob[i] * inv_z2;
|
|
if cum >= opts.top_p as f64 {
|
|
keep = i + 1;
|
|
break;
|
|
}
|
|
}
|
|
scratch.idx.truncate(keep);
|
|
scratch.prob.truncate(keep);
|
|
}
|
|
nonfinite
|
|
}
|
|
|
|
pub fn sample_logits_exact(
|
|
logits: &mut [f32],
|
|
opts: &SamplingOpts,
|
|
history: &[i32],
|
|
banned: Option<i32>,
|
|
rng: &mut SplitMix64,
|
|
scratch: &mut SamplerScratch,
|
|
) -> SampleReport {
|
|
if logits.is_empty() {
|
|
return SampleReport { token: 0, confidence: 1.0, nonfinite_logits: 0, entropy_nats: 0.0 };
|
|
}
|
|
if opts.is_greedy() {
|
|
suppress_token(logits, banned);
|
|
apply_penalties(logits, opts, history, scratch);
|
|
let mut best_id = 0i32;
|
|
let mut mx = f32::NEG_INFINITY;
|
|
let mut nonfinite = 0usize;
|
|
for (i, &val) in logits.iter().enumerate() {
|
|
if !val.is_finite() {
|
|
if val.is_nan() || (val.is_infinite() && val.is_sign_positive()) {
|
|
nonfinite += 1;
|
|
}
|
|
} else if val > mx {
|
|
mx = val;
|
|
best_id = i as i32;
|
|
}
|
|
}
|
|
let mut z = 0.0f64;
|
|
let mut h = 0.0f64;
|
|
if mx.is_finite() {
|
|
for &val in logits.iter() {
|
|
if val.is_finite() {
|
|
let w = ((val - mx) as f64).exp();
|
|
z += w;
|
|
}
|
|
}
|
|
if z > 0.0 {
|
|
for &val in logits.iter() {
|
|
if val.is_finite() {
|
|
let p = ((val - mx) as f64).exp() / z;
|
|
if p > 1e-12 {
|
|
h -= p * p.ln();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return SampleReport {
|
|
token: best_id,
|
|
confidence: if z > 0.0 { (1.0 / z) as f32 } else { 1.0 },
|
|
nonfinite_logits: nonfinite,
|
|
entropy_nats: h as f32,
|
|
};
|
|
}
|
|
|
|
let nonfinite = build_truncated_dist(logits, opts, history, banned, scratch);
|
|
let z: f64 = scratch.prob.iter().sum();
|
|
let inv_z = 1.0 / z.max(1e-30);
|
|
let mut h = 0.0f64;
|
|
for &w in &scratch.prob {
|
|
let p = w * inv_z;
|
|
if p > 1e-12 {
|
|
h -= p * p.ln();
|
|
}
|
|
}
|
|
let r = rng.next_f64() * z;
|
|
let mut c = 0.0f64;
|
|
let mut chosen = scratch.idx[0];
|
|
let mut chosen_p = scratch.prob[0] * inv_z;
|
|
for i in 0..scratch.idx.len() {
|
|
c += scratch.prob[i];
|
|
if r <= c {
|
|
chosen = scratch.idx[i];
|
|
chosen_p = scratch.prob[i] * inv_z;
|
|
break;
|
|
}
|
|
}
|
|
SampleReport {
|
|
token: chosen,
|
|
confidence: chosen_p as f32,
|
|
nonfinite_logits: nonfinite,
|
|
entropy_nats: h as f32,
|
|
}
|
|
}
|
|
|
|
/// Lossless Leviathan speculative verification (exact target distribution `p(x)`).
|
|
/// Returns `(emitted_token, accepted)`.
|
|
pub fn verify_draft_exact(
|
|
logits: &mut [f32],
|
|
opts: &SamplingOpts,
|
|
history: &[i32],
|
|
banned: Option<i32>,
|
|
rng: &mut SplitMix64,
|
|
draft_tok: i32,
|
|
scratch: &mut SamplerScratch,
|
|
) -> (i32, bool) {
|
|
if opts.is_greedy() {
|
|
let rep = sample_logits_exact(logits, opts, history, banned, rng, scratch);
|
|
return (rep.token, rep.token == draft_tok);
|
|
}
|
|
let _ = build_truncated_dist(logits, opts, history, banned, scratch);
|
|
let z: f64 = scratch.prob.iter().sum();
|
|
if z <= 0.0 || scratch.idx.is_empty() {
|
|
return (draft_tok, true);
|
|
}
|
|
let dpos = scratch.idx.iter().position(|&id| id == draft_tok);
|
|
let p_draft = dpos.map(|i| scratch.prob[i] / z).unwrap_or(0.0);
|
|
if dpos.is_some() && (scratch.idx.len() == 1 || rng.next_f64() < p_draft) {
|
|
return (draft_tok, true);
|
|
}
|
|
let z_rem = z - dpos.map(|i| scratch.prob[i]).unwrap_or(0.0);
|
|
if z_rem <= 0.0 {
|
|
return match dpos {
|
|
Some(_) => (draft_tok, true),
|
|
None => (scratch.idx[0], false),
|
|
};
|
|
}
|
|
let r = rng.next_f64() * z_rem;
|
|
let mut c = 0.0f64;
|
|
let mut last_valid = scratch.idx[0];
|
|
for i in 0..scratch.idx.len() {
|
|
if Some(i) == dpos {
|
|
continue;
|
|
}
|
|
last_valid = scratch.idx[i];
|
|
c += scratch.prob[i];
|
|
if r <= c {
|
|
return (scratch.idx[i], false);
|
|
}
|
|
}
|
|
(last_valid, false)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn top_k_tie_break_and_no_256_cap_for_top_p() {
|
|
let mut sc = SamplerScratch::default();
|
|
let mut lg = vec![0.0f32; 600];
|
|
lg[500] = 5.0;
|
|
lg[10] = 5.0;
|
|
lg[300] = 4.0;
|
|
let opts = SamplingOpts { temperature: 1.0, top_k: 3, ..Default::default() };
|
|
let nf = build_truncated_dist(&mut lg, &opts, &[], None, &mut sc);
|
|
assert_eq!(nf, 0);
|
|
assert_eq!(sc.idx, vec![10, 500, 300]);
|
|
|
|
// 400 uniform tokens with top_k=0, top_p=0.9 -> keeps ~360 tokens (not truncated at 256!)
|
|
let mut unif = vec![1.0f32; 400];
|
|
let opts_u = SamplingOpts { temperature: 1.0, top_k: 0, top_p: 0.9, ..Default::default() };
|
|
build_truncated_dist(&mut unif, &opts_u, &[], None, &mut sc);
|
|
assert!((359..=361).contains(&sc.idx.len()));
|
|
}
|
|
|
|
#[test]
|
|
fn nonfinite_reported_and_mask_suppressed() {
|
|
let mut sc = SamplerScratch::default();
|
|
let mut rng = SplitMix64::new(7);
|
|
let mut lg = vec![1.0, f32::NAN, 9.0, 5.0];
|
|
let rep = sample_logits_exact(&mut lg, &SamplingOpts::default(), &[], Some(2), &mut rng, &mut sc);
|
|
assert_eq!(rep.nonfinite_logits, 1);
|
|
assert_eq!(rep.token, 3); // token 2 was suppressed
|
|
}
|
|
} |