Merge branch 'claude/adaptive-spec' into claude/port-gpu-bringup

# Conflicts:
#	crates/leleka-runtime/src/backend_original_serve_replay.rs
#	crates/leleka-runtime/src/backend_original_serve_smoke.rs
#	crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs
This commit is contained in:
Pavlo Ratushnyi
2026-10-25 02:51:11 +02:00
28 changed files with 2090 additions and 43 deletions
@@ -15,6 +15,13 @@
//! `LELEKA_REPLAY_MAX_CONTEXT` (262144), `LELEKA_REPLAY_PREFIX_MIB` (`auto` | MiB: the prefix cache instead of the
//! conversation cache), `LELEKA_ORIGINAL_SERVE_BUDGET_GIB` (24) and the VRAM expert tier environment of the smoke.
//!
//! * `LELEKA_REPLAY_REPS` (default 1) passes over the selected requests; with `LELEKA_SPEC_ARMS` (window policies, see
//! `OriginalServeSettings::arms_from_environment`) a warm-up pass runs first (arm 0, labelled `warm`, to be discarded)
//! and then `REPS x arms` passes, pass q of repetition r served by arm (q + r) mod arms, so every arm meets every
//! cache state; each pass prints `REPLAY PASS`;
//! * `LELEKA_REPLAY_FORCE=1` teacher forcing (`quality_force`): every arm decodes exactly the recorded text, so arms do
//! identical work and differ only in how they speculate (acceptance is measured against the recording).
//!
//! A recorded request with non-greedy sampling is replayed greedily (said in the output). Captures are private data
//! (the user's conversation) and stay out of Git.
//!
@@ -110,6 +117,25 @@ fn original_serve_replay_smoke() {
Ok(stack) => stack,
Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()),
};
let spec_arms = stack.spec_arms();
let reps = number("LELEKA_REPLAY_REPS", 1).max(1);
let force = env::var("LELEKA_REPLAY_FORCE").is_ok_and(|v| v == "1");
// (label, arm) of every pass: a warm-up with arm 0, then reps x arms rotated per repetition
let mut passes: Vec<(String, Option<String>)> = Vec::new();
if spec_arms.is_empty() {
passes.extend((0..reps).map(|r| (format!("p{r}"), None)));
} else {
passes.push(("warm".to_owned(), Some(spec_arms[0].clone())));
for r in 0..reps {
for q in 0..spec_arms.len() {
passes.push((format!("r{r}"), Some(spec_arms[(q + r) % spec_arms.len()].clone())));
}
}
}
for (pass_no, (pass_label, arm)) in passes.iter().enumerate() {
if let Some(arm) = arm {
assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}");
}
let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = (0usize, 0f64, 0usize, 0usize, 0f64);
for (n, file) in files.iter().enumerate() {
let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON");
@@ -121,17 +147,15 @@ fn original_serve_replay_smoke() {
if !greedy {
eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily");
}
crate::qwen_forward::quality_force::set(force.then(|| prompt.iter().copied().chain(recorded.iter().copied()).collect()));
if force {
let mut path = prompt.clone();
path.extend_from_slice(&recorded);
crate::qwen_forward::quality_force::set(Some(path));
eprintln!("DBG corpus {n} pass={arm_index} begin forced=true");
}
let started = std::time::Instant::now();
let mut first: Option<std::time::Duration> = None;
let mut out: Vec<i32> = Vec::new();
let served = stack.serve(
&ServeRequest::new(prompt.clone(), max_new, None, 7, min_p, vec![eos as i32]),
&ServeRequest::new(prompt.clone(), max_new, None, 7, stack.spec_arm_min_p().unwrap_or(min_p), vec![eos as i32]),
&mut |round| {
if first.is_none() {
first = Some(started.elapsed());
@@ -163,7 +187,8 @@ fn original_serve_replay_smoke() {
prompt.len(), prompt.len().saturating_sub(reused), ttft.as_secs_f64() * 1e3, m[0], m[1], m[2], m[3], m[0], m[1] - m[0], m[2] - m[1], m[3] - m[2]
);
eprintln!(
"REPLAY #{n} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}",
"REPLAY #{n} pass={pass_no} {pass_label} arm={} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}",
stack.spec_arm(),
file.file_name().and_then(|f| f.to_str()).unwrap_or("?"),
prompt.len(),
prompt.len().saturating_sub(reused),
@@ -186,13 +211,16 @@ fn original_serve_replay_smoke() {
Err(e) => eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()),
}
}
crate::qwen_forward::quality_force::set(None);
eprintln!(
"REPLAY SUMMARY requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}",
"REPLAY PASS {pass_no} {pass_label} arm={} requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}",
stack.spec_arm(),
files.len(),
if decode_ms > 0.0 { tokens as f64 * 1e3 / decode_ms } else { 0.0 },
decode_ms / 1e3,
prefill_ms / 1e3
);
}
stack.close().expect("stack cleanup failed");
}
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
@@ -238,7 +238,19 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
return;
}
// LELEKA_SPEC_ARMS (see OriginalServeSettings::arms_from_environment): pass p of prompt i is served by arm (p + i) % arms,
// so a prompt meets every arm (LELEKA_SMOKE_REPEAT = arms x repetitions) in a rotated order.
let spec_arms = stack.spec_arms();
for (index, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() {
// `@file:PATH` stands for the whole content of that file (a source file to rewrite: code with its newlines)
let file_text;
let line = match line.trim().strip_prefix("@file:") {
Some(path) => {
file_text = std::fs::read_to_string(path.trim()).expect("@file prompt unreadable");
file_text.as_str()
}
None => line,
};
// LELEKA_SMOKE_CHAT=1: each line is one user turn of a Qwen chat (thinking off), the shape an agent request has
// (a turn checkpoint at the last <|im_start|>, a resume on the repeated pass).
let chat = env::var("LELEKA_SMOKE_CHAT").is_ok_and(|v| v == "1");
@@ -266,12 +278,15 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
});
let forced_passes: usize = env::var("LELEKA_SMOKE_FORCE_PASSES").ok().and_then(|v| v.parse().ok()).unwrap_or(1);
for pass in 0..repeat {
if !spec_arms.is_empty() {
assert!(stack.select_spec_arm(&spec_arms[(pass + index) % spec_arms.len()]));
}
let forced = truth.as_ref().filter(|_| pass < forced_passes);
crate::qwen_forward::quality_force::set(forced.cloned());
eprintln!("DBG corpus {index} pass={pass} begin forced={}", forced.is_some());
let max_new = forced.map_or(max_new, |t| t.len() - ids.len());
let mut out = Vec::new();
let min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0);
let min_p: f32 = stack.spec_arm_min_p().unwrap_or_else(|| env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0));
// LELEKA_SMOKE_SAMPLED=1: the corpus is served with the sampling head and a penalty window (an agent-style
// request: temperature 0.7, top-k 20, top-p 0.95, repeat penalty 1.1 over 64, fixed seed) instead of greedy.
let sampled = env::var("LELEKA_SMOKE_SAMPLED").is_ok_and(|v| v == "1");
@@ -295,16 +310,16 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
}
match served {
Ok(outcome) => {
if pass == 0 {
if pass == 0 && spec_arms.is_empty() {
eprintln!("DBG corpus {index} output ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "));
} else {
eprintln!("DBG corpus {index} output pass={pass} ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "));
eprintln!("DBG corpus {index} output pass={pass} arm={} ({} tokens, rounds {}): {}", stack.spec_arm(), out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "));
}
let ttft = first.unwrap_or(total);
let decode_s = (total - ttft).as_secs_f64();
let decode_tps = if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 };
eprintln!("DBG corpus {index} timing pass={pass} prompt={} produced={} rounds={} ttft_ms={:.1} total_ms={:.1} decode_tok_s={:.2}",
ids.len(), out.len(), outcome.rounds, ttft.as_secs_f64() * 1e3, total.as_secs_f64() * 1e3, decode_tps);
eprintln!("DBG corpus {index} timing pass={pass} arm={} prompt={} produced={} rounds={} ttft_ms={:.1} total_ms={:.1} decode_tok_s={:.2}",
stack.spec_arm(), ids.len(), out.len(), outcome.rounds, ttft.as_secs_f64() * 1e3, total.as_secs_f64() * 1e3, decode_tps);
report_timing(&stack, &format!("corpus {index} pass {pass}"), out.len());
}
Err(e) => eprintln!("DBG corpus {index} pass={pass} FAILED {e:?} health={:?}", stack.health()),
@@ -483,6 +498,10 @@ fn original_serve_long_context_streamed_kv_smoke() {
}
continue;
}
// LELEKA_SPEC_ARMS: pass p of the prompt is served by arm p % arms (the window policy A/B inside one load);
// LELEKA_SMOKE_MIN_P: the request's draft floor (default 0).
let spec_arms = stack.spec_arms();
let spec_min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0);
// LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer<N>.ids` (comma-separated) holds the tokens
// another engine answered to the N-token prompt; the request then decodes along that text (teacher forcing, see
// `quality_force`) for exactly that many tokens, with the port's own logits and `LELEKA_TRACE_LOGPROBS` rows.
@@ -509,10 +528,14 @@ fn original_serve_long_context_streamed_kv_smoke() {
leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0);
eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}");
}
if !spec_arms.is_empty() {
assert!(stack.select_spec_arm(&spec_arms[pass % spec_arms.len()]));
}
let started = std::time::Instant::now();
let mut tokens = Vec::new();
let long_request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, spec_min_p, vec![eos as i32]);
let outcome = stack
.serve(&request(prompt, max_new, None, eos), &mut |round| {
.serve(&long_request, &mut |round| {
tokens.extend_from_slice(round);
Ok(())
}, &mut || false)
@@ -523,7 +546,8 @@ fn original_serve_long_context_streamed_kv_smoke() {
assert_eq!(stack.health(), None);
let (prompt_ms, decode_ms) = stack.last_timing();
eprintln!(
"long-smoke prefill pass={pass} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} decode_ms={decode_ms:.1}",
"long-smoke prefill pass={pass} arm={} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} decode_ms={decode_ms:.1}",
stack.spec_arm(),
prompt.len(),
(prompt.len() - 1) as f64 / (prompt_ms / 1e3).max(1e-9)
);
@@ -67,6 +67,7 @@ pub(crate) mod prompt_device_rows;
pub(crate) mod prefill_profile;
// Literal Original serve draft/verification scheduling; actual device adapters own execution.
pub(crate) mod original_spec_adaptive;
pub(crate) mod original_spec_controller;
pub(crate) mod original_serve_engine;
pub(crate) mod original_spec_draft;
@@ -10,6 +10,7 @@
use super::contract::{Error,Result};
use super::original_spec_controller::{OriginalSpecController,OriginalSpecEngine,SpecConfig,SpecError};
use super::original_spec_draft::{DraftPick,OriginalDraftEngine,OriginalFirstDraftEngine};
use super::original_spec_adaptive::AdaptiveConfig;
use super::original_spec_policy::MAX_T;
use std::rc::Rc;
@@ -93,13 +94,15 @@ enum FirstStage {Idle,Seeded{completion:DraftCompletion,next:usize,cell:i64},}
pub(crate) struct OriginalServeEngine<P:OriginalServePort> {
port:P,owner:Rc<()>,vocabulary:u32,max_t:usize,max_drafts:usize,min_p:f32,
/// The chain length of the NEXT draft stage (<= `max_drafts`, the cap); equal to the cap unless an adaptive plan lowers it.
plan_drafts:usize,
serial:u64,live_windows:usize,commit_pending:bool,adaptive_pending:bool,
history_staged:Option<u64>,draft:DraftStage,first:FirstStage,poisoned:bool,
}
impl<P:OriginalServePort> OriginalServeEngine<P> {
pub(crate) fn new(port:P,vocabulary:u32,max_t:usize,max_drafts:usize)->Result<Self> {
if vocabulary==0||vocabulary>262144||!(1..=MAX_T).contains(&max_t)||max_drafts>max_t-1 {return Err(Error::InvalidDimension);}
Ok(Self{port,owner:Rc::new(()),vocabulary,max_t,max_drafts,min_p:0.0,serial:0,live_windows:0,commit_pending:false,
Ok(Self{port,owner:Rc::new(()),vocabulary,max_t,max_drafts,min_p:0.0,plan_drafts:max_drafts,serial:0,live_windows:0,commit_pending:false,
adaptive_pending:false,history_staged:None,draft:DraftStage::Idle,first:FirstStage::Idle,poisoned:false})
}
/// The request's draft confidence floor; the controller uses the same value
@@ -149,9 +152,9 @@ impl<P:OriginalServePort> OriginalDraftEngine<ServedWindow<P::Window>> for Origi
||token!=verified.outputs[row] {return Err(Error::IdentityMismatch);}
// A coupled draft is sampled with the staged history of THIS window.
if coupled&&self.history_staged!=Some(verified.serial) {return Err(Error::IdentityMismatch);}
let max_picks=self.max_drafts.max(1);
let max_picks=self.plan_drafts.max(1);
let completion=self.port.draft_committed(&verified.window,verified.position,row,&verified.outputs[..verified.t],
self.max_drafts,self.min_p,coupled)?;
self.plan_drafts,self.min_p,coupled)?;
completion.validate(self.vocabulary,max_picks,cell,row)?;
let pick=self.cached_pick(&completion,0);
self.draft=DraftStage::Seeded{completion,next:1};Ok(pick)
@@ -172,6 +175,12 @@ impl<P:OriginalServePort> OriginalDraftEngine<ServedWindow<P::Window>> for Origi
// valid until the next verify bumps it).
self.history_staged=Some(self.serial);Ok(())
}
fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> {
self.usable()?;
if max_drafts==0||max_drafts>self.max_drafts||!min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);}
if !matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);}
self.plan_drafts=max_drafts;self.min_p=min_p;Ok(())
}
fn drain_draft(&mut self)->Result<()> {
// Always drain the real owner; then cross-check the controller's chain
// length against the one-shot completion.
@@ -184,7 +193,7 @@ impl<P:OriginalServePort> OriginalDraftEngine<ServedWindow<P::Window>> for Origi
if next<n {
// The controller stopped early: only legal when the literal stop
// rule fires (confidence below the floor or the draft cap).
let stopped=completion.probabilities[next-1]<self.min_p||next>=self.max_drafts.min(self.max_t-1);
let stopped=completion.probabilities[next-1]<self.min_p||next>=self.plan_drafts.min(self.max_t-1);
if !stopped {return Err(Error::IdentityMismatch);}
}
}
@@ -331,6 +340,9 @@ impl<P:OriginalServePort> OriginalFirstDraftEngine<P::Seed> for OriginalServeEng
}
/// Whether the adaptive speculative window is the default of the serve stack (docs/adaptive-spec.md).
pub(crate) const ADAPTIVE_DEFAULT:bool=true;
/// Original `generate` serve settings for mode17: `--spec 4` verify width, prompt lookup on
/// (`--suffix-draft 3`), which makes the MTP keep 4-wide windows (`mtp_max_t = spec`) and the
/// verifier take windows up to `spec + 2` (`kVerifyMaxT` 8), coupled draft sampling per env.
@@ -338,16 +350,74 @@ impl<P:OriginalServePort> OriginalFirstDraftEngine<P::Seed> for OriginalServeEng
pub(crate) struct OriginalServeSettings {
pub(crate) max_t:usize,pub(crate) mtp_max_t:usize,pub(crate) max_context:i64,pub(crate) vocabulary:u32,
pub(crate) suffix_min_match:usize,pub(crate) coupled:bool,
/// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy (`original_spec_adaptive.rs`).
pub(crate) adaptive:Option<AdaptiveConfig>,
/// An arm's own `spec_min_p` for the requests it serves (`fixed4@0`), overriding the harness default; `None` = the harness's.
pub(crate) request_min_p:Option<f32>,
}
impl OriginalServeSettings {
pub(crate) fn mode17(max_context:i64,vocabulary:u32,coupled:bool)->Self {
const SPEC:usize=4;const SUFFIX:usize=3;
Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled}
Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled,adaptive:None,request_min_p:None}
}
/// Mode17 with the operator's overrides from the environment (read once per stack):
/// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8),
/// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and
/// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up
/// to `max_t - 1` drafts). Unset = mode17 exactly.
pub(crate) fn from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Self {
let num=|name:&str|std::env::var(name).ok().and_then(|v|v.trim().parse::<usize>().ok());
let mut s=Self::mode17(max_context,vocabulary,coupled);
if let Some(spec)=num("LELEKA_SPEC") {
let spec=spec.clamp(2,MAX_T);s.max_t=(spec+2).min(MAX_T);s.mtp_max_t=spec;
}
if let Some(m)=num("LELEKA_SPEC_MTP_MAX_T") {s.mtp_max_t=if m==0 {s.max_t.min(s.mtp_max_t)} else {m.min(s.max_t)};}
if let Some(n)=num("LELEKA_SPEC_SUFFIX") {s.suffix_min_match=n;}
let explicit=std::env::var("LELEKA_SPEC_ADAPTIVE").ok();
if Self::adaptive_wanted(explicit.as_deref(),std::env::var_os("LELEKA_SPEC").is_some()) {
let max_t=num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2,MAX_T);
s.max_t=max_t;s.mtp_max_t=max_t;
s.adaptive=Some(AdaptiveConfig::new(max_t,max_t-1).from_environment());
}
s
}
/// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise
/// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`].
pub(crate) fn adaptive_wanted(explicit:Option<&str>,fixed_spec_set:bool)->bool {
match explicit {
Some("on"|"1"|"yes")=>true,
Some("off"|"0"|"no")=>false,
_=>!fixed_spec_set&&ADAPTIVE_DEFAULT,
}
}
/// `STRATA_SPEC_COUPLED`: set, non-empty and not "0" (read once by the operator, not per request).
pub(crate) fn coupled_from_environment()->bool {
std::env::var("STRATA_SPEC_COUPLED").is_ok_and(|v|!v.is_empty()&&v!="0")
}
/// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an
/// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the
/// adaptive window; the verifier is built for the widest arm. Empty when unset.
pub(crate) fn arms_from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Vec<(String,Self)> {
let Ok(list)=std::env::var("LELEKA_SPEC_ARMS") else {return Vec::new()};
let base=Self::from_environment(max_context,vocabulary,coupled);
let mut arms=Vec::new();
for entry in list.split(',').map(str::trim).filter(|l|!l.is_empty()) {
// `name@MIN_P` pins the arm's request floor
let (label,min_p)=match entry.split_once('@') {
Some((l,p))=>(l,p.parse::<f32>().ok()),
None=>(entry,None),
};
let mut s=base;s.adaptive=None;s.request_min_p=min_p;
if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::<usize>().ok()) {
let n=n.clamp(2,MAX_T);s.max_t=(n+2).min(MAX_T);s.mtp_max_t=n;s.suffix_min_match=3;
} else if label=="adaptive" {
s.max_t=MAX_T;s.mtp_max_t=MAX_T;s.suffix_min_match=3;
s.adaptive=Some(AdaptiveConfig::new(MAX_T,MAX_T-1).from_environment());
} else {continue;}
arms.push((entry.to_owned(),s));
}
arms
}
/// Draft cap the engine shares with the controller's `DraftPreparation`.
pub(crate) fn max_drafts(&self)->usize {self.mtp_max_t.min(self.max_t).saturating_sub(1)}
/// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537)
@@ -358,7 +428,7 @@ impl OriginalServeSettings {
/// The one production call of `OriginalSpecController::new`.
pub(crate) fn controller(&self)->Result<OriginalSpecController> {
OriginalSpecController::new(SpecConfig::new(self.max_t,self.mtp_max_t,self.max_context,self.vocabulary,
self.suffix_min_match,self.coupled)?)
self.suffix_min_match,self.coupled)?.with_adaptive(self.adaptive))
}
}
@@ -958,6 +1028,15 @@ mod tests {
e.drain_verified(v).unwrap();
}
#[test]
fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() {
let w=OriginalServeSettings::adaptive_wanted;
assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true));
assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false));
assert_eq!(w(None,false),ADAPTIVE_DEFAULT);
assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window");
}
#[test]
fn mode17_settings_follow_generate_defaults() {
let s=OriginalServeSettings::mode17(4096,VOCAB,false);
@@ -975,7 +1054,7 @@ mod tests {
fn serve(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option<usize>)
->(std::result::Result<ServeOutcome,SpecError>,Vec<i32>,OriginalSpecController,OriginalServeEngine<Fake>) {
let (f,w)=Fake::new(p);
let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context:4096,vocabulary:VOCAB,suffix_min_match:0,coupled:false};
let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context:4096,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,request_min_p:None};
let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap();
let mut c=s.controller().unwrap();
let mut out=Vec::new();
@@ -243,6 +243,19 @@ impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> {
}
}
impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> {
/// The MTP actor drafts as many chain steps as it is configured for (`set_max_drafts`); an adaptive round's plan is
/// applied here (the engine has already bounded it by the request's cap). Equal values cost one comparison.
fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> {
let want = i32::try_from(max_drafts).map_err(|_| Error::Overflow)?;
let actor = self.executor.mtp_actor(self.binding)?;
if actor.settings().max_drafts() != want {
actor.set_max_drafts(want);
}
Ok(())
}
}
impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
type TargetCheckpoint = LedgerCheckpoint;
type DraftCheckpoint = OriginalDraftCheckpoint;
@@ -455,10 +468,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
if before.next_position() != first {
return Err(Error::IdentityMismatch);
}
// The actor was configured for this request's draft cap; a different cap would draft another chain.
if usize::try_from(self.executor.mtp_actor(self.binding)?.settings().max_drafts()).ok() != Some(max_drafts) {
return Err(Error::IdentityMismatch);
}
// The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round.
self.apply_draft_cap(max_drafts)?;
let p = profile::span("draft.receipt");
let receipt = OriginalCommittedMtpReceipt::for_published_window(
self.binding,
@@ -499,10 +510,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
if before.next_position() != first {
return Err(Error::IdentityMismatch);
}
// The actor was configured for this request's draft cap; a different cap would draft another chain.
if usize::try_from(self.executor.mtp_actor(self.binding)?.settings().max_drafts()).ok() != Some(max_drafts) {
return Err(Error::IdentityMismatch);
}
// The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round.
self.apply_draft_cap(max_drafts)?;
let launched = self.executor.launch_committing_mtp(
self.binding,
self.session,
@@ -241,6 +241,12 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> {
full_policy: OriginalMtpFullPolicy,
scalar_policy: OriginalMtpScalarPolicy,
controller: OriginalSpecController,
/// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned
/// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm.
parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>,
arm_label: String,
arm_order: Vec<String>,
verifier_max_t: usize,
/// Why the stack can serve no more (a lost physical owner); `None` while healthy.
broken: Option<Error>,
// The empty-prompt lineage taken at load: the reset target of every request.
@@ -345,7 +351,19 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
});
}
let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?;
let settings = OriginalServeSettings::mode17(config.max_context, VOCABULARY, config.coupled);
let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled);
let mut arm_label = String::from("env");
let arm_order: Vec<String> = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect();
let mut parked = Vec::new();
let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled);
let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t);
if let Some(((label, first), rest)) = arms.split_first() {
settings = *first;
arm_label = label.clone();
for (label, s) in rest {
parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?));
}
}
let controller = settings.controller().map_err(at("settings.controller"))?;
let rope = RopeConstants::from_serving_context();
let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?;
@@ -363,7 +381,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_arena"))?);
vram_note(context, "after embedding, output, kar, dense, moe arena");
let mut session = QwenSession::for_binding_on_shared_device(binding, shared);
let request = OriginalMtpRequest::ring_int8(settings.mtp_load_t(), config.capacity, settings.coupled, MTP_RESIDENT_CELLS);
let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS);
let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context));
let (executor, draft) = match &config.rt_directory {
Some(directory) => OriginalPromptExecutor::select_rt_mtp(
@@ -372,7 +390,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?,
None => {
let mut executor = OriginalPromptExecutor::new(
binding, &dense, &mut session, context, &moe, &embedding, config.capacity, settings.mtp_load_t(), true,
binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true,
).map_err(at("OriginalPromptExecutor::new"))?;
let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request)
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?;
@@ -481,6 +499,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
blobs,
formats,
controller,
parked,
arm_label,
arm_order,
verifier_max_t,
broken: None,
empty_session,
empty_draft,
@@ -633,6 +655,35 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
}
/// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included.
#[allow(dead_code)]
pub(crate) fn spec_arms(&self) -> Vec<String> {
self.arm_order.clone()
}
/// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label.
#[allow(dead_code)]
pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool {
if self.arm_label == label {
return true;
}
let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false };
let (new_label, new_settings, new_controller) = self.parked.swap_remove(at);
let old_label = std::mem::replace(&mut self.arm_label, new_label);
let old_settings = std::mem::replace(&mut self.settings, new_settings);
let old_controller = std::mem::replace(&mut self.controller, new_controller);
self.parked.push((old_label, old_settings, old_controller));
true
}
/// The live arm's own request floor, if its label pinned one (`fixed4@0`).
#[allow(dead_code)]
pub(crate) fn spec_arm_min_p(&self) -> Option<f32> {
self.settings.request_min_p
}
#[allow(dead_code)]
pub(crate) fn spec_arm(&self) -> &str {
&self.arm_label
}
/// Wall-clock milliseconds of the last request's prompt phase and decode phase.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn last_timing(&self) -> (f64, f64) {
@@ -812,6 +863,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
formats,
full_policy,
controller,
arm_label,
verifier_max_t,
history,
ple_history,
ple_scratch,
@@ -882,7 +935,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
Ok(())
};
let assembled = assemble(
binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, settings.max_t, *max_cells,
binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells,
pcie_mode, &mut queue_refill,
);
drop(p);
@@ -993,6 +1046,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
)
});
drop(serve_span);
{
// the controller's round counters belong to this request in every window policy
let stats = controller.take_stats();
if super::original_spec_controller::stats_enabled() {
eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line());
}
}
if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); }
let (mut verifier, mut host) = engine.into_port().0.into_parts();
// STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise)
@@ -0,0 +1,814 @@
//! Adaptive speculative window (flag-gated, `LELEKA_SPEC_ADAPTIVE=on`; design in `docs/adaptive-spec.md`).
//!
//! The Original verifies a fixed window: the MTP chain stops at `--spec-min-p`, the suffix drafter is a yes/no
//! alternative chosen by `DraftPolicy`. This policy instead picks, per round, the number of rows to verify and the
//! draft source by maximising E[tokens committed by the round] / T(t) where
//! * E(t) = 1 + sum_{j<t} prod_{i<=j} a_i with a_i the CALIBRATED probability that draft i is accepted given that
//! drafts 1..i-1 were (online estimates, below),
//! * T(t) the measured round time of a t-row window (windows are separate graphs; unmeasured widths come from a
//! two-parameter fit through the measured ones).
//! Verification is untouched: whatever the policy picks, the target still checks every row, so the committed tokens are
//! exactly those of any other window (up to the batch-rounding envelope of the verifier itself).
//!
//! Estimators (all decayed counts, no randomness, so a trace is reproducible):
//! * MTP draft i with own probability p: `a = cell[depth][bucket(p)]`, shrunk toward the depth-independent
//! `cell[bucket(p)]`, shrunk toward a prior calibrated from the bucket centre; plus a fast scalar logit bias that
//! tracks the current content (code edit vs prose vs tool-call JSON) with a rate of a few rounds.
//! * suffix rows: first row and continuation rows by match-length bucket, separately for suffix tokens that AGREE with
//! the MTP's first draft and for those that do not (the Original only ever used the agreeing ones).
//! * T(t): decayed mean of (round ms - draft ms) per width, winsorised, blended with a fit `a + c (t-1)` whose slope
//! is ridge-regularised toward a typical value; the slope is what the expert tier / CPU pool / PCIe state shows up as.
use super::original_spec_policy::MAX_T;
const P_BUCKETS: usize = 8;
const P_EDGES: [f32; P_BUCKETS + 1] = [0.0, 0.25, 0.4, 0.55, 0.7, 0.8, 0.9, 0.95, f32::INFINITY];
/// Acceptance prior of a bucket (slightly under its centre: drafts are a little over-confident).
const P_PRIOR: [f64; P_BUCKETS] = [0.12, 0.28, 0.42, 0.57, 0.70, 0.80, 0.88, 0.95];
const M_BUCKETS: usize = 5;
/// First-row / continuation-row acceptance prior of a suffix match, by match-length bucket (<6, <12, <24, <48, 48+).
const S_FIRST_AGREE: [f64; M_BUCKETS] = [0.75, 0.88, 0.93, 0.96, 0.97];
const S_FIRST_OTHER: [f64; M_BUCKETS] = [0.25, 0.35, 0.45, 0.55, 0.65];
const S_CONT_AGREE: [f64; M_BUCKETS] = [0.88, 0.93, 0.96, 0.97, 0.98];
const S_CONT_OTHER: [f64; M_BUCKETS] = [0.75, 0.85, 0.90, 0.93, 0.95];
const N0_BUCKET: f64 = 6.0;
const N0_DEPTH: f64 = 10.0;
const N0_SUFFIX: f64 = 4.0;
/// Typical extra cost per verified row as a fraction of the one-row window (docs/roofline.md: chain 8 + 1.6 T ms plus the expert
/// misses; about 0.12-0.2 with a converged tier, more with a cold one). Only the prior of the slope fit.
const PRIOR_SLOPE: f64 = 0.15;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Origin {
Mtp,
Suffix,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AdaptiveConfig {
/// Widest window (rows) the verifier can run.
pub(crate) max_t: usize,
/// Cap of the MTP chain (drafts).
pub(crate) max_drafts: usize,
/// Relative advantage a new width needs over the previous round's width.
pub(crate) margin: f64,
/// Rounds between exploration probes of an adjacent width (0 = never).
pub(crate) explore_period: u64,
/// Chain stop floor bounds. `min_p_hi` is the operator's static value (the policy only lowers it).
pub(crate) min_p_lo: f32,
pub(crate) min_p_hi: f32,
/// Cost of one MTP chain step in ms (the round time contains the chain; it is not a property of the window width).
pub(crate) draft_step_ms: f64,
/// Weight of a new round time in the width cost.
pub(crate) cost_alpha: f64,
/// Decay applied to a cell on each update.
pub(crate) decay: f64,
/// Rate of the fast content bias.
pub(crate) bias_rate: f64,
}
impl AdaptiveConfig {
pub(crate) fn new(max_t: usize, max_drafts: usize) -> Self {
let max_t = max_t.clamp(1, MAX_T);
Self {
max_t,
max_drafts: max_drafts.min(max_t - 1),
margin: 0.02,
explore_period: 32,
min_p_lo: 0.10,
min_p_hi: 0.90,
draft_step_ms: 0.45,
cost_alpha: 0.12,
decay: 0.995,
bias_rate: 0.06,
}
}
/// `LELEKA_SPEC_EXPLORE` (period), `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE`.
pub(crate) fn from_environment(mut self) -> Self {
fn num<T: std::str::FromStr>(name: &str) -> Option<T> {
std::env::var(name).ok().and_then(|v| v.trim().parse().ok())
}
if let Some(v) = num("LELEKA_SPEC_EXPLORE") { self.explore_period = v; }
if let Some(v) = num("LELEKA_SPEC_MARGIN") { self.margin = v; }
if let Some(v) = num("LELEKA_SPEC_MIN_P_LO") { self.min_p_lo = v; }
if let Some(v) = num("LELEKA_SPEC_DRAFT_STEP_MS") { self.draft_step_ms = v; }
if let Some(v) = num("LELEKA_SPEC_COST_ALPHA") { self.cost_alpha = v; }
if let Some(v) = num("LELEKA_SPEC_DECAY") { self.decay = v; }
if let Some(v) = num("LELEKA_SPEC_BIAS_RATE") { self.bias_rate = v; }
self
}
}
#[derive(Clone, Copy, Default, Debug)]
struct Cell {
ok: f64,
n: f64,
}
impl Cell {
fn rate(&self, prior: f64, n0: f64) -> f64 {
(self.ok + n0 * prior) / (self.n + n0)
}
fn add(&mut self, hit: bool, decay: f64) {
self.ok = self.ok * decay + if hit { 1.0 } else { 0.0 };
self.n = self.n * decay + 1.0;
}
}
fn p_bucket(p: f32) -> usize {
(1..P_BUCKETS).find(|&b| p < P_EDGES[b]).map_or(P_BUCKETS - 1, |b| b - 1)
}
fn m_bucket(n: usize) -> usize {
if n < 6 { 0 } else if n < 12 { 1 } else if n < 24 { 2 } else if n < 48 { 3 } else { 4 }
}
fn logit(p: f64) -> f64 {
let p = p.clamp(1e-4, 1.0 - 1e-4);
(p / (1.0 - p)).ln()
}
fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
/// What the drafters offer this round.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Offer<'a> {
/// Probabilities of the drafted MTP tokens, in chain order (so `len() + 1` rows are available).
pub(crate) mtp_probs: &'a [f32],
/// Suffix continuation tokens available (0 = none), the length of the match behind them, and whether the first of
/// them equals the MTP's first draft.
pub(crate) suffix_k: usize,
pub(crate) suffix_match: usize,
pub(crate) suffix_agrees: bool,
}
/// The decision of one round and what `observe` needs to learn from it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Choice {
pub(crate) origin: Origin,
/// Rows verified (1 = the input token alone).
pub(crate) t: usize,
pub(crate) expected: f64,
pub(crate) rate: f64,
pub(crate) explored: bool,
probs: [f32; MAX_T],
matched: usize,
agrees: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct DraftPlan {
pub(crate) max_drafts: usize,
pub(crate) min_p: f32,
}
#[derive(Clone, Copy, Debug)]
struct Cand {
origin: Origin,
t: usize,
expected: f64,
rate: f64,
}
#[derive(Clone)]
pub(crate) struct AdaptivePolicy {
cfg: AdaptiveConfig,
hi_default: f32,
mtp_bucket: [Cell; P_BUCKETS],
mtp_depth: [[Cell; P_BUCKETS]; MAX_T],
suf_first: [[Cell; M_BUCKETS]; 2],
suf_cont: [[Cell; M_BUCKETS]; 2],
bias_mtp: f64,
bias_suf: [f64; 2],
cost: [f64; MAX_T + 1],
cost_n: [f64; MAX_T + 1],
seen: [u64; MAX_T + 1],
/// Forgetting sufficient statistics [sum w, sum w x, sum w x^2, sum w y, sum w x y, sum w y/(1+0.3x)] of (t-1, ms).
fitstat: [f64; 6],
rounds: u64,
since_explore: u64,
last: Option<(Origin, usize)>,
/// A probe in progress: the width being measured and how many more rounds it runs (a single sample moves a decayed mean too little).
probe: Option<(usize, u32)>,
hold_t: f64,
drafts_ewma: f64,
survive_ewma: f64,
rate_ewma: f64,
}
impl AdaptivePolicy {
pub(crate) fn new(cfg: AdaptiveConfig) -> Self {
Self {
cfg,
hi_default: cfg.min_p_hi,
mtp_bucket: [Cell::default(); P_BUCKETS],
mtp_depth: [[Cell::default(); P_BUCKETS]; MAX_T],
suf_first: [[Cell::default(); M_BUCKETS]; 2],
suf_cont: [[Cell::default(); M_BUCKETS]; 2],
bias_mtp: 0.0,
bias_suf: [0.0; 2],
cost: [0.0; MAX_T + 1],
cost_n: [0.0; MAX_T + 1],
seen: [0; MAX_T + 1],
fitstat: [0.0; 6],
rounds: 0,
since_explore: 0,
last: None,
probe: None,
hold_t: 4.0,
drafts_ewma: 3.0,
survive_ewma: 0.5,
rate_ewma: 0.0,
}
}
pub(crate) fn config(&self) -> &AdaptiveConfig {
&self.cfg
}
pub(crate) fn rounds(&self) -> u64 {
self.rounds
}
/// A new request: the content changes, so the fast biases restart (the cell statistics and the costs persist).
/// `min_p`: the request's chain floor, the policy's upper bound (0 = none given: the default bound).
pub(crate) fn begin_request(&mut self, min_p: f32) {
self.cfg.min_p_hi = if min_p > 0.0 && min_p.is_finite() { min_p.max(self.cfg.min_p_lo) } else { self.hi_default };
self.bias_mtp = 0.0;
self.bias_suf = [0.0; 2];
self.last = None;
self.probe = None;
self.hold_t = self.hold_t.max(4.0);
}
// ---- acceptance -------------------------------------------------------------------------------------------
/// Calibrated acceptance of MTP draft number `depth` (1-based) with own probability `p`, given the earlier ones.
pub(crate) fn mtp_rate(&self, depth: usize, p: f32) -> f64 {
let b = p_bucket(p);
let base = self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET);
let r = self.mtp_depth[depth.min(MAX_T - 1)][b].rate(base, N0_DEPTH);
sigmoid(logit(r) + self.bias_mtp)
}
fn suffix_row_rate(&self, row: usize, matched: usize, agrees: bool) -> f64 {
let (c, m) = (agrees as usize ^ 1, m_bucket(matched));
let r = if row == 1 {
let prior = if agrees { S_FIRST_AGREE[m] } else { S_FIRST_OTHER[m] };
self.suf_first[c][m].rate(prior, N0_SUFFIX)
} else {
let prior = if agrees { S_CONT_AGREE[m] } else { S_CONT_OTHER[m] };
self.suf_cont[c][m].rate(prior, N0_SUFFIX)
};
sigmoid(logit(r) + self.bias_suf[c])
}
// ---- cost -------------------------------------------------------------------------------------------------
/// Trust in the per-width mean: it fades as it ages (the machine's state drifts), so a stale width falls back to what
/// the recent rounds imply.
fn weight(&self, t: usize) -> f64 {
let age = self.rounds.saturating_sub(self.seen[t]) as f64;
self.cost_n[t].min(10.0) * (-age / 24.0).exp()
}
/// `y = a + c x` (x = t-1) through the recent rounds (forgetting 0.97 per round) with the slope pulled toward a
/// typical 15 % of the level per row, so a run at one width still extrapolates sensibly.
fn fit(&self) -> Option<(f64, f64)> {
let [sw, sx, sxx, sy, sxy, sr] = self.fitstat;
if sw <= 1e-6 {
return None;
}
let c0 = PRIOR_SLOPE * sr / sw;
let lambda = 6.0;
// minimise sum w (y - a - c x)^2 + lambda (c - c0)^2
let (m11, m12, m22) = (sw, sx, sxx + lambda);
let (b1, b2) = (sy, sxy + lambda * c0);
let det = m11 * m22 - m12 * m12;
if det.abs() < 1e-9 {
return Some((sy / sw, c0));
}
let a = (b1 * m22 - b2 * m12) / det;
let c = (m11 * b2 - m12 * b1) / det;
Some((a, c.max(0.0)))
}
/// Expected ms of a t-row window (excluding the chain).
pub(crate) fn window_ms(&self, t: usize) -> f64 {
let t = t.clamp(1, MAX_T);
let fit = self.fit().map_or(40.0 * (1.0 + PRIOR_SLOPE * (t - 1) as f64), |(a, c)| a + c * (t - 1) as f64);
let wt = self.weight(t);
let w = wt / (wt + 4.0);
(w * self.cost[t] + (1.0 - w) * fit).max(1.0)
}
/// ms per extra row.
pub(crate) fn row_slope_ms(&self) -> f64 {
self.fit().map_or(8.0, |(_, c)| c.max(0.2))
}
// ---- decision ---------------------------------------------------------------------------------------------
fn candidates(&self, offer: &Offer<'_>, out: &mut Vec<Cand>) {
let overhead = self.cfg.draft_step_ms * self.drafts_ewma;
let w1 = self.window_ms(1) + overhead;
out.push(Cand { origin: Origin::Mtp, t: 1, expected: 1.0, rate: 1.0 / w1 });
let (mut e, mut cum) = (1.0, 1.0);
for (j, &p) in offer.mtp_probs.iter().enumerate().take(self.cfg.max_t - 1) {
cum *= self.mtp_rate(j + 1, p);
e += cum;
let t = j + 2;
out.push(Cand { origin: Origin::Mtp, t, expected: e, rate: e / (self.window_ms(t) + overhead) });
}
if offer.suffix_k > 0 {
let (mut e, mut cum) = (1.0, 1.0);
for row in 1..=offer.suffix_k.min(self.cfg.max_t - 1) {
cum *= self.suffix_row_rate(row, offer.suffix_match, offer.suffix_agrees);
e += cum;
let t = row + 1;
out.push(Cand { origin: Origin::Suffix, t, expected: e, rate: e / (self.window_ms(t) + overhead) });
}
}
}
pub(crate) fn choose(&mut self, offer: &Offer<'_>) -> Choice {
let mut cands = Vec::with_capacity(2 * MAX_T);
self.candidates(offer, &mut cands);
let mut best = cands[0];
for c in &cands {
if c.rate > best.rate {
best = *c;
}
}
// hysteresis: keep the previous round's (origin, width) unless the best is clearly better
if let Some((o, t)) = self.last {
if let Some(prev) = cands.iter().find(|c| c.origin == o && c.t == t) {
if prev.rate * (1.0 + self.cfg.margin) >= best.rate {
best = *prev;
}
}
}
// exploration: a neighbouring width whose model says it is nearly as good, when it has not been measured lately
let mut explored = false;
if let Some((t, left)) = self.probe {
// continue the probe while its width is still on offer
match cands.iter().filter(|c| c.t == t).max_by(|a, b| a.rate.total_cmp(&b.rate)) {
Some(c) if left > 0 => {
best = *c;
explored = true;
self.probe = Some((t, left - 1));
}
_ => self.probe = None,
}
}
self.since_explore += 1;
let period = if self.rounds < 24 { (self.cfg.explore_period / 4).max(2) } else { self.cfg.explore_period };
if self.cfg.explore_period > 0 && !explored && self.since_explore >= period {
let mut pick: Option<Cand> = None;
for c in &cands {
if c.t == best.t || (c.t as i64 - best.t as i64).abs() != 1 || c.rate < 0.88 * best.rate {
continue;
}
let stale = self.rounds.saturating_sub(self.seen[c.t]);
if self.cost_n[c.t] >= 3.0 && stale < 48 {
continue;
}
if pick.is_none_or(|p| self.cost_n[c.t] < self.cost_n[p.t] || (self.cost_n[c.t] == self.cost_n[p.t] && c.rate > p.rate)) {
pick = Some(*c);
}
}
if let Some(p) = pick {
best = p;
explored = true;
self.since_explore = 0;
self.probe = Some((p.t, 3));
}
}
let mut probs = [0.0f32; MAX_T];
for (d, &p) in offer.mtp_probs.iter().take(MAX_T).enumerate() {
probs[d] = p;
}
Choice { origin: best.origin, t: best.t, expected: best.expected, rate: best.rate, explored, probs, matched: offer.suffix_match, agrees: offer.suffix_agrees }
}
// ---- learning ---------------------------------------------------------------------------------------------
/// `accepted` of the `t-1` offered rows were accepted; `round_ms` is the whole round (verify, commit, emit, draft,
/// adaptation) and `drafts_after` the MTP drafts that round's chain produced.
pub(crate) fn observe(&mut self, c: &Choice, accepted: usize, round_ms: f64, drafts_after: usize) {
self.rounds += 1;
let tested = (accepted + 1).min(c.t - 1);
let (decay, eta) = (self.cfg.decay, self.cfg.bias_rate);
for j in 1..=tested {
let hit = j <= accepted;
match c.origin {
Origin::Mtp => {
let p = c.probs[j - 1];
let b = p_bucket(p);
let predicted = self.mtp_rate(j, p);
self.mtp_bucket[b].add(hit, decay);
self.mtp_depth[j.min(MAX_T - 1)][b].add(hit, decay);
self.bias_mtp = (self.bias_mtp + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5);
}
Origin::Suffix => {
let (cl, m) = (c.agrees as usize ^ 1, m_bucket(c.matched));
let predicted = self.suffix_row_rate(j, c.matched, c.agrees);
if j == 1 { self.suf_first[cl][m].add(hit, decay) } else { self.suf_cont[cl][m].add(hit, decay) }
self.bias_suf[cl] = (self.bias_suf[cl] + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5);
}
}
}
// the bias fades back to the cell statistics
self.bias_mtp *= 0.995;
for b in &mut self.bias_suf {
*b *= 0.995;
}
if round_ms.is_finite() && round_ms > 0.0 {
let y = (round_ms - self.cfg.draft_step_ms * drafts_after as f64).max(1.0);
let t = c.t.clamp(1, MAX_T);
// a probe that came out clearly cheaper than the model said: the machine is in another state, look further now
if c.explored && y < 0.9 * self.window_ms(t) {
self.since_explore = u64::MAX / 2;
}
if self.cost_n[t] <= 0.0 {
self.cost[t] = y;
} else {
let m = self.cost[t];
let w = if self.cost_n[t] < 3.0 { 0.35 } else { self.cfg.cost_alpha };
let yc = y.clamp(0.6 * m, 1.8 * m);
self.cost[t] = m + w * (yc - m);
// a change of the machine's state (tier hit rate, CPU leg, context) moves every width: the other
// widths follow part of the way so they are not judged by stale numbers
let ratio = yc / m;
for u in 1..=MAX_T {
if u != t && self.cost_n[u] > 0.0 {
self.cost[u] *= 1.0 + 0.5 * w * (ratio - 1.0);
}
}
}
self.cost_n[t] += 1.0;
self.seen[t] = self.rounds;
let x = (t - 1) as f64;
let f = &mut self.fitstat;
for v in f.iter_mut() {
*v *= 0.97;
}
f[0] += 1.0; f[1] += x; f[2] += x * x; f[3] += y; f[4] += x * y; f[5] += y / (1.0 + PRIOR_SLOPE * x);
}
self.drafts_ewma += 0.1 * (drafts_after as f64 - self.drafts_ewma);
self.hold_t = (c.t as f64).max(self.hold_t * 0.92);
let surv = if c.t > 1 { (c.expected - self.expected_without_last(c)).clamp(0.0, 1.0) } else { 0.0 };
if c.t > 1 {
self.survive_ewma += 0.1 * (surv - self.survive_ewma);
}
self.rate_ewma = if self.rate_ewma > 0.0 { self.rate_ewma + 0.1 * (c.rate - self.rate_ewma) } else { c.rate };
self.last = Some((c.origin, c.t));
}
/// E of the chosen window without its last row (`expected` is a prefix sum of the cumulative acceptances).
fn expected_without_last(&self, c: &Choice) -> f64 {
let (mut e, mut cum) = (1.0, 1.0);
for j in 1..c.t - 1 {
cum *= match c.origin {
Origin::Mtp => self.mtp_rate(j, c.probs[j - 1]),
Origin::Suffix => self.suffix_row_rate(j, c.matched, c.agrees),
};
e += cum;
}
e
}
// ---- next draft chain -------------------------------------------------------------------------------------
/// How deep the next MTP chain should go and the draft probability below which it stops. A chain step costs
/// `draft_step_ms`; a verified row costs `row_slope_ms` and is worth it when `survival * a / slope` beats the current
/// tokens-per-ms, so the floor is the smallest draft probability whose calibrated acceptance clears that bar.
pub(crate) fn draft_plan(&self) -> DraftPlan {
let max_drafts = ((self.hold_t.ceil() as usize).max(2)).min(self.cfg.max_drafts.max(1));
let rate = if self.rate_ewma > 0.0 { self.rate_ewma } else { 0.04 };
let a_req = (rate * (self.row_slope_ms() + self.cfg.draft_step_ms) / self.survive_ewma.max(0.2)).clamp(0.0, 0.99);
let mut min_p = self.cfg.min_p_hi;
for b in 0..P_BUCKETS {
let r = sigmoid(logit(self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + self.bias_mtp);
if r >= a_req {
min_p = P_EDGES[b];
break;
}
}
DraftPlan { max_drafts, min_p: min_p.clamp(self.cfg.min_p_lo, self.cfg.min_p_hi) }
}
}
/// Counters of what rounds did, kept by the controller for every policy (fixed windows included) and printed per
/// request by `LELEKA_SPEC_STATS=1`.
#[derive(Clone, Debug, Default)]
pub(crate) struct SpecStats {
pub(crate) rounds: u64,
pub(crate) tokens: u64,
pub(crate) lookup_rounds: u64,
pub(crate) explored: u64,
pub(crate) by_t: [u64; MAX_T + 1],
pub(crate) ms_by_t: [f64; MAX_T + 1],
pub(crate) acc_hist: [u64; MAX_T + 1],
pub(crate) offered: u64,
pub(crate) accepted: u64,
pub(crate) total_ms: f64,
}
impl SpecStats {
pub(crate) fn record(&mut self, t: usize, accepted: usize, lookup: bool, explored: bool, ms: f64) {
self.rounds += 1;
self.tokens += accepted as u64 + 1;
self.offered += (t - 1) as u64;
self.accepted += accepted as u64;
self.lookup_rounds += lookup as u64;
self.explored += explored as u64;
self.by_t[t.min(MAX_T)] += 1;
self.ms_by_t[t.min(MAX_T)] += ms;
self.acc_hist[accepted.min(MAX_T)] += 1;
self.total_ms += ms;
}
pub(crate) fn line(&self) -> String {
let hist = |h: &[u64]| h.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",");
let mean_ms: Vec<String> = (0..=MAX_T)
.map(|t| if self.by_t[t] > 0 { format!("{:.1}", self.ms_by_t[t] / self.by_t[t] as f64) } else { "-".into() })
.collect();
format!(
"rounds={} tokens={} tok_per_round={:.3} lookup_rounds={} explored={} accepted={}/{} round_ms={:.2} T_hist[0..={}]={} acc_hist={} ms_by_T={}",
self.rounds, self.tokens,
self.tokens as f64 / self.rounds.max(1) as f64, self.lookup_rounds, self.explored, self.accepted, self.offered,
self.total_ms / self.rounds.max(1) as f64, MAX_T, hist(&self.by_t), hist(&self.acc_hist), mean_ms.join(",")
)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Deterministic generator for the synthetic traces.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 11) as f64) / ((1u64 << 53) as f64)
}
}
/// A synthetic content regime: draft probabilities are drawn from `[p_lo, p_hi]` and a draft with probability p is
/// accepted with probability `clamp(p * calib)`; a window of t rows costs `base + slope (t-1)` ms (+ noise).
#[derive(Clone, Copy)]
struct World {
p_lo: f64,
p_hi: f64,
calib: f64,
base: f64,
slope: f64,
suffix_q: f64,
suffix_len: usize,
suffix_match: usize,
}
const CODE_CHEAP: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 };
const CODE_COSTLY: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 };
const PROSE_CHEAP: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 };
const PROSE_COSTLY: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 };
const REPEAT: World = World { p_lo: 0.5, p_hi: 1.0, calib: 0.9, base: 30.0, slope: 3.0, suffix_q: 0.995, suffix_len: 7, suffix_match: 40 };
/// One policy-driven (`fixed == None`) or fixed-width round; returns (tokens, ms, t).
fn play(world: &World, rng: &mut Rng, policy: Option<&mut AdaptivePolicy>, fixed: Option<usize>) -> (usize, f64, usize) {
let max_t = 8;
let probs: Vec<f32> = (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect();
let hits = |rng: &mut Rng, q: f64, n: usize| -> usize {
let mut a = 0;
while a < n && rng.next() < q { a += 1; }
a
};
let accept_mtp = |rng: &mut Rng, rows: usize| -> usize {
let mut a = 0;
while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { a += 1; }
a
};
let noise = 1.0 + 0.04 * (rng.next() - 0.5);
let cost = |t: usize| (world.base + world.slope * (t - 1) as f64) * noise;
match (policy, fixed) {
(Some(pol), _) => {
let offer = Offer { mtp_probs: &probs, suffix_k: world.suffix_len, suffix_match: world.suffix_match, suffix_agrees: true };
let c = pol.choose(&offer);
let a = match c.origin {
Origin::Mtp => accept_mtp(rng, c.t - 1),
Origin::Suffix => hits(rng, world.suffix_q, c.t - 1),
};
let ms = cost(c.t) + 0.45 * probs.len().min(4) as f64;
pol.observe(&c, a, ms, probs.len().min(4));
(a + 1, ms, c.t)
}
(None, Some(t)) => {
let a = if world.suffix_len > 0 && world.suffix_q > 0.9 && t - 1 <= world.suffix_len {
hits(rng, world.suffix_q, t - 1)
} else {
accept_mtp(rng, t - 1)
};
(a + 1, cost(t) + 0.45 * 3.0, t)
}
_ => unreachable!(),
}
}
fn fixed_rate(world: &World, t: usize) -> f64 {
let mut rng = Rng(7);
let (mut tok, mut ms) = (0usize, 0.0);
for _ in 0..4000 {
let (a, m, _) = play(world, &mut rng, None, Some(t));
tok += a; ms += m;
}
tok as f64 / ms
}
fn best_fixed(world: &World) -> (usize, f64) {
(1..=8).map(|t| (t, fixed_rate(world, t))).fold((1, 0.0), |b, x| if x.1 > b.1 { x } else { b })
}
fn adaptive_run(world_seq: &[(World, usize)], cfg: AdaptiveConfig) -> (f64, Vec<f64>) {
let mut pol = AdaptivePolicy::new(cfg);
let mut rng = Rng(11);
let (mut tok, mut ms) = (0usize, 0.0);
let mut mean_t = Vec::new();
for (w, n) in world_seq {
let mut sum_t = 0usize;
let mut tail = 0usize;
for i in 0..*n {
let (a, m, t) = play(w, &mut rng, Some(&mut pol), None);
tok += a; ms += m; sum_t += t;
if i >= *n / 2 { tail += t; }
}
let _ = sum_t;
mean_t.push(tail as f64 / (*n - *n / 2) as f64);
}
(tok as f64 / ms, mean_t)
}
fn cfg() -> AdaptiveConfig {
AdaptiveConfig::new(8, 7)
}
#[test]
fn stationary_regimes_reach_the_best_fixed_width() {
for w in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] {
let (bt, best) = best_fixed(&w);
let (rate, _) = adaptive_run(&[(w, 4000)], cfg());
assert!(rate >= 0.97 * best, "adaptive {rate:.5} vs best fixed t={bt} {best:.5}");
for t in [3usize, 4, 6] {
assert!(rate >= 0.99 * fixed_rate(&w, t), "adaptive {rate:.5} vs fixed {t}");
}
}
}
#[test]
fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() {
let (_, cheap) = adaptive_run(&[(CODE_CHEAP, 1500)], cfg());
let (_, costly) = adaptive_run(&[(CODE_COSTLY, 1500)], cfg());
assert!(cheap[0] > costly[0] + 1.5, "cheap {:.2} costly {:.2}", cheap[0], costly[0]);
assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]);
}
#[test]
fn it_follows_a_change_of_content_and_of_cost() {
let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)];
let (rate, tail) = adaptive_run(&seq, cfg());
assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}");
// against the oracle that knows each segment's best fixed width
let (mut tok, mut ms) = (0.0, 0.0);
for (w, n) in seq {
let (_, r) = best_fixed(&w);
tok += r * n as f64 * 1.0;
ms += n as f64;
}
let _ = (tok, ms);
let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::<f64>() / seq.iter().map(|(_, n)| *n as f64).sum::<f64>();
assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}");
// and it beats every single fixed width over the whole sequence
let whole = |t: usize| -> f64 {
let mut rng = Rng(3);
let (mut tk, mut m) = (0usize, 0.0);
for (w, n) in seq {
for _ in 0..n {
let (a, c, _) = play(&w, &mut rng, None, Some(t));
tk += a; m += c;
}
}
tk as f64 / m
};
for t in 1..=8 {
assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t));
}
}
#[test]
fn reaction_to_a_switch_takes_tens_of_rounds_not_hundreds() {
let mut pol = AdaptivePolicy::new(cfg());
let mut rng = Rng(5);
for _ in 0..600 { play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); }
let mut ts = Vec::new();
for _ in 0..120 { ts.push(play(&CODE_CHEAP, &mut rng, Some(&mut pol), None).2); }
let late: f64 = ts[60..].iter().sum::<usize>() as f64 / 60.0;
assert!(late >= 5.5, "width 60..120 rounds after the cost dropped: {late:.2}");
}
#[test]
fn exploration_costs_little_and_is_the_only_way_to_learn_unseen_widths() {
let mut off = cfg();
off.explore_period = 0;
let (on_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], cfg());
let (off_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], off);
assert!(on_rate >= 0.97 * off_rate, "on {on_rate:.5} off {off_rate:.5}");
let mut pol = AdaptivePolicy::new(cfg());
let mut rng = Rng(9);
let mut explored = 0;
for _ in 0..400 {
let before = pol.since_explore;
let _ = before;
let probs = [0.9f32; 7];
let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 0, suffix_match: 0, suffix_agrees: false });
explored += c.explored as usize;
pol.observe(&c, 3.min(c.t - 1), 40.0 + 2.0 * c.t as f64 + rng.next(), 3);
}
assert!(explored >= 4 && explored <= 60, "explored {explored} of 400");
}
#[test]
fn a_long_repeated_suffix_opens_the_widest_window() {
let (rate, tail) = adaptive_run(&[(REPEAT, 600)], cfg());
assert!(tail[0] >= 7.5, "mean width {:.2}", tail[0]);
assert!(rate > fixed_rate(&REPEAT, 4) * 1.3, "rate {rate:.5} vs fixed-4 {:.5}", fixed_rate(&REPEAT, 4));
}
#[test]
fn a_suffix_that_keeps_missing_is_dropped() {
let mut pol = AdaptivePolicy::new(cfg());
let mut rng = Rng(21);
let probs = [0.9f32, 0.9, 0.9, 0.9, 0.8, 0.8, 0.7];
let mut suffix_late = 0;
for i in 0..600 {
// a stale short match that never continues, MTP is right 85 % of the time
let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 5, suffix_match: 4, suffix_agrees: false });
let a = match c.origin {
Origin::Suffix => 0,
Origin::Mtp => { let mut a = 0; while a < c.t - 1 && rng.next() < 0.85 { a += 1; } a }
};
if i >= 300 && c.origin == Origin::Suffix && c.t > 1 { suffix_late += 1; }
pol.observe(&c, a, 40.0 + 3.0 * c.t as f64, 3);
}
assert!(suffix_late <= 20, "{suffix_late} late suffix rounds");
}
#[test]
fn unmeasured_widths_are_interpolated_from_the_measured_ones() {
let mut pol = AdaptivePolicy::new(cfg());
for i in 0..200 {
let t = [2usize, 4, 6][i % 3];
let c = Choice { origin: Origin::Mtp, t, expected: 2.0, rate: 0.04, explored: false, probs: [0.8; MAX_T], matched: 0, agrees: false };
pol.observe(&c, 1, 30.0 + 5.0 * (t - 1) as f64 + 0.45 * 3.0, 3);
}
for t in [1usize, 3, 5, 7, 8] {
let want = 30.0 + 5.0 * (t - 1) as f64;
let got = pol.window_ms(t);
assert!((got - want).abs() <= 0.1 * want, "t={t}: {got:.1} vs {want:.1}");
}
assert!((pol.row_slope_ms() - 5.0).abs() < 1.0);
}
#[test]
fn the_calibration_follows_the_drafter() {
// a drafter that is right half as often as it claims: its 0.9 drafts must be believed less than 0.9
let mut pol = AdaptivePolicy::new(cfg());
let mut rng = Rng(2);
for _ in 0..800 {
let c = Choice { origin: Origin::Mtp, t: 4, expected: 2.0, rate: 0.04, explored: false, probs: [0.92; MAX_T], matched: 0, agrees: false };
let mut a = 0;
while a < 3 && rng.next() < 0.45 { a += 1; }
pol.observe(&c, a, 40.0, 3);
}
let r = pol.mtp_rate(1, 0.92);
assert!((r - 0.45).abs() < 0.1, "calibrated rate {r:.3}");
assert!(pol.mtp_rate(1, 0.6) < 0.8);
}
#[test]
fn the_draft_plan_stays_inside_its_bounds_and_follows_the_cost() {
let mut cheap = AdaptivePolicy::new(cfg());
let mut costly = AdaptivePolicy::new(cfg());
let mut rng = Rng(4);
for _ in 0..500 {
play(&CODE_CHEAP, &mut rng, Some(&mut cheap), None);
play(&CODE_COSTLY, &mut rng, Some(&mut costly), None);
}
let (a, b) = (cheap.draft_plan(), costly.draft_plan());
for p in [a, b] {
assert!((1..=7).contains(&p.max_drafts) && (0.10..=0.90).contains(&p.min_p), "{p:?}");
}
assert!(a.max_drafts > b.max_drafts, "{a:?} {b:?}");
assert!(a.min_p <= b.min_p, "{a:?} {b:?}");
}
#[test]
fn a_trace_is_reproducible() {
let run = || {
let mut pol = AdaptivePolicy::new(cfg());
let mut rng = Rng(1);
(0..300).map(|_| play(&PROSE_CHEAP, &mut rng, Some(&mut pol), None).2).collect::<Vec<_>>()
};
assert_eq!(run(), run());
}
#[test]
fn stats_line_reports_the_histograms() {
let mut s = SpecStats::default();
s.record(4, 3, false, false, 50.0);
s.record(6, 0, true, true, 60.0);
let l = s.line();
assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}");
assert!(l.contains("accepted=3/8"), "{l}");
}
}
@@ -3,9 +3,21 @@
use super::contract::{Error,Result};
use std::rc::Rc;
use super::original_spec_draft::{DraftBatch,DraftPreparation,OriginalDraftEngine};
use super::original_spec_adaptive::{AdaptiveConfig,AdaptivePolicy,Choice,DraftPlan,Offer,Origin,SpecStats};
use super::original_spec_policy::{DraftPolicy,MAX_T};
use super::original_spec_suffix::SuffixDrafter;
/// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's expectation).
pub(crate) fn trace_enabled()->bool {
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
*ON.get_or_init(||std::env::var("LELEKA_SPEC_TRACE").is_ok_and(|v|!v.is_empty()&&v!="0"))
}
/// `LELEKA_SPEC_STATS`: one `DBG spec-stats` line per request (rounds, tokens per round, T and accepted histograms, ms per T).
pub(crate) fn stats_enabled()->bool {
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
*ON.get_or_init(||std::env::var("LELEKA_SPEC_STATS").is_ok_and(|v|!v.is_empty()&&v!="0"))
}
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub(crate) enum SpecError {Cancelled,Forward(Error)}
impl From<Error> for SpecError {fn from(e:Error)->Self {Self::Forward(e)}}
@@ -47,13 +59,20 @@ pub(crate) trait OriginalSpecEngine:OriginalDraftEngine<Self::Verified> {
pub(crate) struct SpecConfig {
max_t:usize,mtp_t:usize,max_context:i64,vocabulary:u32,
suffix_min_match:usize,coupled:bool,
/// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy replaces the fixed `mtp_t` / min_p / DraftPolicy choice.
adaptive:Option<AdaptiveConfig>,
}
impl SpecConfig {
pub(crate) fn new(max_t:usize,mtp_max_t:usize,max_context:i64,vocabulary:u32,suffix_min_match:usize,coupled:bool)->Result<Self> {
if !(1..=MAX_T).contains(&max_t)||max_context<1||max_context>crate::qwen_forward::contract::serving_cells() as i64||vocabulary==0||vocabulary>262144 {return Err(Error::InvalidDimension);}
// Original --mtp-max-t<=0 means S; public usize zero carries that case.
let mtp_t=if mtp_max_t==0 {max_t} else {mtp_max_t.min(max_t)};
Ok(Self{max_t,mtp_t,max_context,vocabulary,suffix_min_match,coupled})
Ok(Self{max_t,mtp_t,max_context,vocabulary,suffix_min_match,coupled,adaptive:None})
}
/// Select the adaptive window policy (`max_t` is the widest verify window, `mtp_t - 1` the longest MTP chain).
pub(crate) fn with_adaptive(mut self,adaptive:Option<AdaptiveConfig>)->Self {
self.adaptive=adaptive.map(|mut a|{a.max_t=a.max_t.min(self.max_t);a.max_drafts=a.max_drafts.min(self.mtp_t.saturating_sub(1)).min(a.max_t.saturating_sub(1));a});
self
}
}
struct Request {
@@ -66,13 +85,14 @@ pub(crate) struct OriginalSpecController {
/// Draft the window after the LAST round too (generate.cpp skips it on EOS/length), so the draft ring stands at the session's
/// position when the request ends and a checkpoint of both can be taken there. Off unless the caller asks, per request.
final_draft:bool,
adaptive:Option<AdaptivePolicy>,plan:Option<DraftPlan>,stats:SpecStats,
}
/// Holds the authentic complete verification receipt until MTP catch-up has
/// consumed all T residuals. It cannot be cloned or used as a state checkpoint.
/// The caller emits only tokens() AFTER verify_commit returned successfully.
pub(crate) struct CommittedRound<V,A> {
verified:V,outputs:[i32;MAX_T],emitted:usize,t:usize,accepted:usize,
position:i64,from_lookup:bool,matched:usize,timed:bool,eos:bool,
position:i64,from_lookup:bool,matched:usize,timed:bool,eos:bool,choice:Option<Choice>,
next_position:i64,round_number:u64,work:Option<A>,owner:Rc<()>,bookkeeping_error:Option<Error>,
}
impl<V,A> CommittedRound<V,A> {
@@ -102,7 +122,8 @@ impl OriginalSpecController {
let cap=(config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?;
let suffix=SuffixDrafter::new(config.suffix_min_match.max(1),64,cap)?;
let policy=DraftPolicy::new(config.max_t,0.03)?;
Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),final_draft:false})
let adaptive=config.adaptive.map(AdaptivePolicy::new);
Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),final_draft:false,adaptive,plan:None,stats:SpecStats::default()})
}
/// See `final_draft`; set before `begin_request`.
pub(crate) fn set_final_draft(&mut self,on:bool) {self.final_draft=on;}
@@ -125,6 +146,11 @@ impl OriginalSpecController {
// Reserve/admit before resetting the previous suffix state.
self.suffix.reserve_reset(prompt.len())?;
self.suffix.reset();if self.config.suffix_min_match>0 {self.suffix.append(prompt)?;}
self.plan=None;
if let Some(pol)=self.adaptive.as_mut() {
pol.begin_request(min_p);
self.plan=Some(pol.draft_plan());
}
self.request=Some(Request{consumed,input:prompt[prompt.len()-1],position:prompt.len() as i64-1,
first_window:true,produced:0,max_new,min_p,eos,drafts:DraftBatch::empty(),pending_draft:false,finished:max_new==0});
Ok(())
@@ -139,6 +165,9 @@ impl OriginalSpecController {
pub(crate) fn consumed(&self)->Result<&[i32]> {Ok(&self.request.as_ref().ok_or(Error::IdentityMismatch)?.consumed)}
pub(crate) fn finished(&self)->bool {self.request.as_ref().is_none_or(|r|r.finished)}
pub(crate) fn policy(&self)->&DraftPolicy {&self.policy}
pub(crate) fn adaptive(&self)->Option<&AdaptivePolicy> {self.adaptive.as_ref()}
/// The round counters since the last call (per request in the serve loop), for every window policy.
pub(crate) fn take_stats(&mut self)->SpecStats {std::mem::take(&mut self.stats)}
pub(crate) fn is_failed(&self)->bool {self.failed}
fn abort<E:OriginalSpecEngine>(&mut self,engine:&mut E,target:&E::TargetCheckpoint,draft:&E::DraftCheckpoint,primary:SpecError)->SpecError {
@@ -158,7 +187,22 @@ impl OriginalSpecController {
if r.min_p>0.0 {t=1;while t<self.config.mtp_t&&r.drafts.probabilities()[t-1]>=r.min_p {t+=1;}}
if r.first_window {t=1;}
let mut suffix_tokens=[0;MAX_T];let(mut lookup,mut matched)=(false,0);
if self.config.suffix_min_match>0&&!r.first_window {
let mut choice=None;
if let Some(pol)=self.adaptive.as_mut() {
// Adaptive window: every offered row (MTP chain up to its plan, suffix continuation of any agreement) is a
// candidate; the policy verifies the prefix with the best expected tokens per ms.
t=1;
if !r.first_window {
let (mut k,mut agrees)=(0,false);
if self.config.suffix_min_match>0 {
k=self.suffix.propose(&mut suffix_tokens[..self.config.max_t-1]);matched=self.suffix.last_match();
agrees=k>0&&r.drafts.produced()>0&&suffix_tokens[0]==r.drafts.ids()[0];
}
let n=r.drafts.produced().min(self.config.max_t-1);
let c=pol.choose(&Offer{mtp_probs:&r.drafts.probabilities()[..n],suffix_k:k,suffix_match:matched,suffix_agrees:agrees});
t=c.t;lookup=c.origin==Origin::Suffix&&t>1;choice=Some(c);
}
} else if self.config.suffix_min_match>0&&!r.first_window {
let k=self.suffix.propose(&mut suffix_tokens[..self.config.max_t-1]);matched=self.suffix.last_match();
if k>0&&suffix_tokens[0]==r.drafts.ids()[0] {
let pick=self.policy.choose(t,k,matched);if pick.lookup {t=pick.t;lookup=true;}
@@ -214,7 +258,7 @@ impl OriginalSpecController {
r.input=outputs[accepted];r.position=next;r.pending_draft=true;r.finished=eos||r.produced>=r.max_new;
self.rounds=next_round;
// Store the actual pending adaptive owner with the committed receipt.
Ok(Some(CommittedRound{verified,outputs,emitted,t,accepted,position:p,from_lookup:lookup,matched,timed,eos,
Ok(Some(CommittedRound{verified,outputs,emitted,t,accepted,position:p,from_lookup:lookup,matched,timed,eos,choice,
next_position:next,round_number:next_round,work:Some(work),owner:Rc::clone(&self.owner),bookkeeping_error}))
}
}
@@ -243,11 +287,14 @@ impl OriginalSpecController {
if let Some(e)=round.bookkeeping_error {Err(e.into())}
else if r.finished&&!self.final_draft {Ok(None)}
else {
let preparation=DraftPreparation::new(self.config.max_t,self.config.mtp_t-1,self.config.vocabulary);
match preparation {
Err(e)=>Err(e.into()),
Ok(preparation)=>preparation.after_verified(engine,&round.verified,round.position,round.accepted,
&round.outputs[..round.t],&r.consumed,r.min_p,self.config.coupled).map(Some).map_err(Into::into),
// the chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan
let (chain,floor)=match self.plan {Some(p)=>(p.max_drafts,p.min_p),None=>(self.config.mtp_t-1,r.min_p)};
let planned=if self.plan.is_some() {engine.set_draft_plan(chain,floor)} else {Ok(())};
let preparation=DraftPreparation::new(self.config.max_t,chain,self.config.vocabulary);
match (planned,preparation) {
(Err(e),_)|(_,Err(e))=>Err(e.into()),
(Ok(()),Ok(preparation))=>preparation.after_verified(engine,&round.verified,round.position,round.accepted,
&round.outputs[..round.t],&r.consumed,floor,self.config.coupled).map(Some).map_err(Into::into),
}
}
}
@@ -268,11 +315,31 @@ impl OriginalSpecController {
}
Ok(next)=> {
let r=self.request.as_mut().ok_or(Error::IdentityMismatch)?;
let drafts_after=next.as_ref().map_or(0,|b|b.produced());
if let Some(batch)=next {r.drafts=batch;}
r.pending_draft=false;
let ms=round_ms();
if round.timed&&!round.eos {
if let Err(e)=self.policy.observe(round.from_lookup,round.t,round.accepted,round.matched,ms) {r.finished=true;return Err(e.into());}
match (self.adaptive.as_mut(),round.choice.as_ref()) {
(Some(pol),Some(c))=>{
pol.observe(c,round.accepted,ms,drafts_after);
self.plan=Some(pol.draft_plan());
if trace_enabled() {
let plan=self.plan.unwrap_or(DraftPlan{max_drafts:0,min_p:0.0});
eprintln!("DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2}",
round.round_number,round.t,c.origin,round.accepted,ms,c.expected,c.rate,c.explored as u8,drafts_after,plan.max_drafts,plan.min_p);
}
}
_=>{
if self.adaptive.is_none() {
if let Err(e)=self.policy.observe(round.from_lookup,round.t,round.accepted,round.matched,ms) {r.finished=true;return Err(e.into());}
}
if trace_enabled() {
eprintln!("DBG spec-trace r={} t={} src={} acc={} ms={:.2} drafts={}",round.round_number,round.t,if round.from_lookup {"Lookup"} else {"Mtp"},round.accepted,ms,drafts_after);
}
}
}
self.stats.record(round.t,round.accepted,round.from_lookup,round.choice.is_some_and(|c|c.explored),ms);
}
if cancel() {r.finished=true;return Err(SpecError::Cancelled);}
Ok(())
@@ -414,6 +481,45 @@ mod tests {
assert_eq!(c.begin_request(&[1],4,0.0,&[]),Err(Error::IdentityMismatch));
}
#[test]
fn the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter() {
use super::super::original_spec_adaptive::AdaptiveConfig;
for bad in [None,Some(0),Some(1),Some(3)] {
for probs in [vec![0.95;8],vec![0.3;8],vec![0.9,0.8,0.6,0.5,0.4,0.9,0.9,0.9]] {
for suffix in [0usize,3] {
let p=prompt(6);let mut e=Fake::new(&p[..5]);
e.bad_draft=bad;e.probs=probs.clone();
let mut c=OriginalSpecController::new(config(6,6,suffix).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap();
begin(&mut c,&p,70,&[]);
let out=drive(&mut c,&mut e,&mut||false).unwrap();
c.finish_request(&mut e).unwrap();
assert_eq!(out,expected(&p,70),"bad {bad:?} probs {probs:?} suffix {suffix}");
let stats=c.take_stats();
assert!(stats.rounds>=2&&stats.tokens as usize>=stats.rounds as usize,"{}",stats.line());
assert!(c.adaptive().is_some_and(|a|a.rounds()>=stats.rounds-1));
}
}
}
}
#[test]
fn the_adaptive_window_learns_to_verify_wide_when_the_drafter_is_perfect() {
use super::super::original_spec_adaptive::AdaptiveConfig;
let p=prompt(6);let mut e=Fake::new(&p[..5]);
let mut c=OriginalSpecController::new(config(6,6,0).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap();
begin(&mut c,&p,200,&[]);
let mut widths=Vec::new();
while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() {
widths.push(round.offered()+1);
// a wider window costs a little more in this fake clock
let ms=30.0+1.0*(round.offered() as f64);
c.finish_round(&mut e,round,move||ms,&mut||false).unwrap();
}
c.finish_request(&mut e).unwrap();
let tail=&widths[widths.len()-8..];
assert!(tail.iter().all(|&t|t>=5),"{widths:?}");
}
#[test]
fn perfect_drafter_accepts_whole_windows_and_emits_greedy_text() {
let p=prompt(6);let mut e=Fake::new(&p[..5]);
@@ -40,6 +40,9 @@ pub(crate) trait OriginalDraftEngine<Verified> {
/// All actual commands/events/ABI/registered resources must be drained even
/// after callback failure. Transport uncertainty fences real owner/Context.
fn drain_draft(&mut self)->Result<()>;
/// Adaptive speculative window: the chain length cap and the confidence floor of the NEXT draft stage (before
/// `full_target_seed`). Engines with a fixed chain keep the default (nothing to apply).
fn set_draft_plan(&mut self,_max_drafts:usize,_min_p:f32)->Result<()> {Ok(())}
}
pub(crate) struct DraftPreparation {max_t:usize,max_drafts:usize,vocabulary:u32}
+115
View File
@@ -0,0 +1,115 @@
# Adaptive speculative window (`claude/adaptive-spec`)
Status: implemented, measured on the 5090, **default on** (`LELEKA_SPEC_ADAPTIVE=off` or `LELEKA_SPEC=N` selects the fixed Original window).
## Why
The Original verifies a fixed window: MTP chain of `spec - 1` = 3 drafts cut at `--spec-min-p 0.5`, plus an optional suffix
(prompt lookup) window up to `spec + 2` = 6 rows chosen by `DraftPolicy` (a yes/no on the suffix, with the MTP window as the
alternative). Whether a wider window pays depends on two things that differ between workloads and between moments of one run:
* how often the next draft is right (code edit, a file re-emitted from the context, tool-call JSON: high; prose: low), and
* what one more verified row costs (expert tier hit rate, CPU pool and PCIe load: with a converged tier the extra rows are nearly
free; with a cold tier each row touches more distinct experts and the window gets slower).
At about 50 ms a round, one more accepted token per round is worth 30-40 %, so the choice of the width is worth more than most
kernel work, and a fixed value is wrong for part of every session.
## Policy (crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs)
Per round the policy sees everything the drafters offer: the MTP chain (tokens and their own probabilities) and the suffix
continuation (up to `max_t - 1` tokens, the match length, whether its first token equals the MTP's first draft). It evaluates every
prefix of each as a candidate window and takes the one with the best
rate(t) = E[tokens committed by the round](t) / (T(t) + chain ms)
E(t) = 1 + sum_{j<t} prod_{i<=j} a_i
* `a_i` is the **calibrated** probability that draft i is accepted given drafts 1..i-1 were: for the MTP a table indexed by
(depth, bucket of the draft's own probability), shrunk toward a depth-free table per probability bucket, shrunk toward a prior
from the bucket centre; for the suffix the first row and the continuation rows by match-length bucket, separately when the suffix
agrees with the MTP and when it does not. Counts are decayed (0.995 per sample). A scalar logit bias per source moves fast
(rate 0.06 per tested row, fading) so a change of content (code to prose, JSON, a pasted file) is followed in tens of rounds
without waiting for the tables.
* The learning signal is exact: of `t-1` offered rows, rows 1..min(accepted+1, t-1) were tested (row j counts as a hit when
j <= accepted), the rest were censored by the first rejection.
* `T(t)` is the measured round time of a t-row window minus the draft chain (0.45 ms per chain step), kept as a decayed mean per
width (winsorised) blended with a fit `a + c (t-1)` over the recent rounds (forgetting 0.97 per round, slope pulled toward 15 %
of the level per row). The fit is what predicts widths not run lately: it carries the current tier / CPU / PCIe state. A width's own mean is trusted less as
it ages. Every observation also moves the other widths a part of the way (a state change is mostly common to all widths).
* Hysteresis: the previous round's (source, width) is kept unless another candidate is better by `LELEKA_SPEC_MARGIN` (2 %).
* Exploration is deterministic (no RNG, traces are reproducible): every `LELEKA_SPEC_EXPLORE` rounds (32; 8 for the first 24
rounds) a neighbouring width (+-1) whose model rate is within 12 % of the best and which has not been measured for 48 rounds is
run instead. Verification keeps the result exact; only one round's speed is at stake.
* **Next chain plan** (`draft_plan`): chain length = peak-held recent width (decays 8 % per round) capped by `max_t - 1`; confidence
floor = the smallest draft probability whose calibrated acceptance clears `rate * (row slope + chain step ms) / survival`, i.e.
a lower floor when rows are cheap, clamped to `[LELEKA_SPEC_MIN_P_LO, request spec_min_p]` (the operator's value stays the upper
bound; 0 means 0.9). The plan is applied to the MTP actor per round (`set_draft_plan`; the actor's `max_drafts` is set from it).
Verification is untouched. The controller still checks every offered row against the target's own output, commits the accepted
prefix and the bonus token. Sampled requests use the existing sampled verification path unchanged (acceptance is equality with the
sampled target token; the policy only chooses how many rows to offer).
## Knobs
| variable | default | meaning |
| --- | --- | --- |
| `LELEKA_SPEC_ADAPTIVE` | on | `off`: the fixed mode17 window; adaptive = 8-row verifier, MTP chain up to 7 drafts, suffix 3 |
| `LELEKA_SPEC_ADAPTIVE_MAX_T` | 8 | widest window (rows); the Original's constant `kVerifyMaxT` is 8 |
| `LELEKA_SPEC` / `_MTP_MAX_T` / `_SUFFIX` | unset / spec / 3 | the Original's `--spec`, `--mtp-max-t`, `--suffix-draft`; setting `LELEKA_SPEC` selects the fixed window |
| `LELEKA_SPEC_ARMS` | - | `fixed3@0.5,fixed4@0,adaptive@0`: policies one process switches between per request (A/B in one load); `@P` pins the arm's request floor (`spec_min_p`) |
| `LELEKA_SPEC_EXPLORE`, `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE` | 32, 0.02, 0.10, 0.45, 0.12, 0.995, 0.06 | policy constants |
| `LELEKA_SPEC_STATS=1` | off | one `DBG spec-stats` line per request: rounds, tokens per round, width and accepted histograms, mean ms per width |
| `LELEKA_SPEC_TRACE=1` | off | one `DBG spec-trace` line per timed round (width, source, accepted, round ms, expected tokens, next chain plan) |
| smoke: `@file:PATH` lines in `LELEKA_SMOKE_PROMPTS` | - | a whole file as one prompt (code with its newlines); with `LELEKA_SPEC_ARMS` pass p of prompt i uses arm (p+i) mod arms |
## Wider windows than 6
`kVerifyMaxT = 8` is compiled into the window kernels (`acc[kVerifyMaxT]` register arrays, the grouped-expert `GMAX >= kVerifyMaxT`
static_assert, head and MoE group tables), so 8 rows is the ceiling without kernel changes and a re-seal of the PTX
(sm_120 + sm_86); 12 or 16 rows are not available from this branch. With `--spec 6` equivalent (`LELEKA_SPEC=6`, adaptive) the
verifier records windows 1..8 (one more capture + instantiate than 1..6, about +20 ms per request), the MTP is loaded at 8.
## Results (RTX 5090, driver 595.99, CUDA 13.2, KAR PLE, int8 KV, conversation/prefix caches as noted; 1 model load per job)
Method. All arms of a job run in ONE process (`LELEKA_SPEC_ARMS`): same tier, caches and clocks, the verifier built for the widest arm
(8 rows) for all of them, so the arms differ only in the window policy. Arm order rotates per repetition; 3 repetitions each.
`fixedN@P` is the Original's `--spec N` with `spec_min_p = P` (0.5 = the Original's serve setting, 0 = what the live Codex runs shipped).
Decode tok/s is tokens / verify-loop time (`decode.serve`) for the corpus jobs and `weighted_decode_tok_s` (total tokens / total decode
time) for the replays. Jobs: 9a1, 9a2 (chat + code corpus, 192 new tokens, 10 prompts x 3 repetitions per arm), 9b1-9b3 (real Codex session
replays, `scripts/spec/`, teacher forced to the recorded text, so every arm does identical work).
| workload / tier | fixed3@0.5 | fixed4@0.5 | fixed6@0.5 | fixed4@0 (shipped) | adaptive | adaptive vs fixed4@0.5 (per repetition) |
| --- | --- | --- | --- | --- | --- | --- |
| corpus, static tier 2048 slots (hit ~11 %), job 9a1 | 60.25 | 63.05 | 63.15 | - | **65.06** | +2.5 / +3.1 / +3.9 % |
| corpus, auto tier + adaptation (hit 91-97 %), job 9a2 | 148.34 | 153.18 | 151.12 | - | **155.99** | +5.0 / +0.3 / +0.1 % |
| tic-tac-toe session, requests 0-15 (9-30k ctx), auto tier, job 9b1 | 135.72 | 138.40 | 134.79 | 134.52 | **141.04** | +1.8 / +1.8 / +2.1 % |
| CRM session, requests 0-15 (10-30k ctx), auto tier, prefix cache, job 9b2 | 139.71 | 144.48 | 145.25 | 141.57 | **150.71** | +4.4 / +4.2 / +4.4 % |
| CRM session, requests 56-67 (80-90k ctx), auto tier, job 9b3 | 121.62 | 125.59 | 124.89 | 122.64 | **130.10** | +3.8 / +3.3 / +3.6 % |
Against the shipped live configuration (fixed4@0): +4.9 % (tic-tac-toe), +6.5 % (CRM), +6.1 % (CRM long context). Adaptive is above every fixed arm in every repetition of every
replay; ranges over the three repetitions are under 1 % of the mean.
The gain is small because the cost of a verified row is not small: measured round ms by width (replay 9b1, auto tier): T1 13.0, T2 15.1, T3 18.3,
T4 22.3, T5 26.2, T6 31.2, T7 34.8, T8 38.9 (about 3.6 ms per row, 28 % of the one-row window; with the static 2048-slot tier 10.5 ms per row, 45 %).
A row pays only when the cumulative acceptance of the rows before it times its own exceeds roughly 0.6, so the policy mostly moves the width
between 2 and 4 in uncertain text and to 7-8 in re-emitted code. Width histograms (share of rounds) in 9b2: adaptive T2 26 %, T3 17 %, T4 11 %,
T5 8 %, T6 11 %, T7 8 %, T8 15 % against fixed4@0.5 T4 79 %. Tokens per round: 3.69 (adaptive) / 3.17 (fixed4@0.5) / 3.91 (fixed6) with mean round 24.4 / 21.9 / 26.9 ms.
Policy trace (tic-tac-toe request 4, adaptive, `width:accepted/source`, `LELEKA_SPEC_TRACE=1`): `3:1 2:1 2:0 3:1 2:1 4:0 5:4 5:4 2:1 3:2 2:1 3:1
3:2 3:1 2:1 2:0 4:3 4:2 3:2 5:4 3:2 6:5 5:4 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:1(suffix) 8:5 8:7 8:7 8:2 8:5(suffix) 5:4 5:4 8:7 8:7 8:7
7:6(suffix) 7:1(suffix) 7:5 3:2 7:6 7:6 5:4`: narrow in uncertain code, 8 rows inside a re-emitted block, back to 3 when the match ends.
Draft floor: the policy's computed floor is at its ceiling (0.9 when the request carries 0, otherwise the request's value) in every trace inspected: with 3-4 ms
per row a draft below 0.9 never clears the marginal bar, so "a lower floor when rows are cheap" never triggered on this hardware; the verify-time prefix
choice (calibrated acceptance, not the raw draft probability) does the work that a floor would do. Job 9b5 (adaptive@0.5 / @0.7 / @0) measures the
ceiling; it was not run when this was written.
Exactness. Verification is unchanged and the controller tests (fake target, perfect/poor/failing drafters, suffix on and off) check that the adaptive
window emits exactly the greedy text. On the device (static tier, seed off, adaptation off, 10 prompts, 192 tokens, 3 passes each, compared with the
first fixed4 pass of the same prompt): adaptive identical in 16/30 requests, fixed3 13/30, fixed6 13/30, and fixed4 against its own repeats 15/20; the
differences are the known batch-rounding envelope (a different window width rounds a near tie differently; the first difference is at token 5-170),
not a policy effect: the adaptive arm is no further from fixed4 than fixed3 or fixed6 are. With the auto tier (placement changes with timing):
21/30, 17/30, 19/30 and 11/20. Sampled requests are untouched (acceptance is equality with the sampled target token).
Not feasible / not done: windows beyond 8 rows (`kVerifyMaxT = 8` is compiled into the window kernels); the 100k/180k jobs 9a3/9a4 are void (the
raw-text prompt makes the model stop after two tokens; the replay 9b3 at 80-90k context replaces them); 9b4 (static-tier replay) was skipped by the
queue; the chain-step graphs are captured lazily per request, the policy's deeper chains pay a capture the first time a depth is used in a request.
+4
View File
@@ -0,0 +1,4 @@
set -uo pipefail
# claude/adaptive-spec: first run of the adaptive window on the device: fixed4 vs adaptive, static tier (2048 slots/layer, seed off, no adaptation), 2 passes of the 10-prompt code+prose corpus (trace on).
source ~/work/gpu-runs/holder2/spec-common.sh
run_arms smoke fixed4,adaptive 2 96 $G/spec/prompts-spec.txt LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off
+4
View File
@@ -0,0 +1,4 @@
set -uo pipefail
# claude/adaptive-spec: fixed 3 / 4 / 6 and adaptive in ONE model load, static tier (2048 slots, seed off, ADAPT_EVERY=0): prompt p of pass q by arm (q+p) mod 4; 3 repetitions of the rotation = 12 passes of the 10-prompt corpus, 192 new tokens
source ~/work/gpu-runs/holder2/spec-common.sh
run_arms ab-static fixed3,fixed4,fixed6,adaptive 12 192 $G/spec/prompts-spec.txt LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off
+4
View File
@@ -0,0 +1,4 @@
set -uo pipefail
# claude/adaptive-spec: same arms with the auto-sized tier and adaptive placement (high hit rate: cheap windows)
source ~/work/gpu-runs/holder2/spec-common.sh
run_arms ab-auto fixed3,fixed4,fixed6,adaptive 12 192 $G/spec/prompts-spec.txt LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+5
View File
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: 100k-token code context, fixed3/4/6 and adaptive, 3 repetitions of the 4-arm rotation, 256 new tokens, auto tier + adaptation every 2 rounds
export BIN=$HOME/work/leleka-spec-bin/sp2
source ~/work/gpu-runs/holder2/spec-common.sh
run_long 100k fixed3,fixed4,fixed6,adaptive 100000 12 256 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+5
View File
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: 180k-token code context (the agent session scale), same arms, 2 repetitions (8 passes), 256 new tokens
export BIN=$HOME/work/leleka-spec-bin/sp2
source ~/work/gpu-runs/holder2/spec-common.sh
run_long 180k fixed3,fixed4,fixed6,adaptive 180000 8 256 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+5
View File
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: replay of the real Codex tic-tac-toe session (943b, first 16 requests, context 9k-30k), teacher forced, auto tier + adaptation every 2 rounds, conversation cache; arms fixed3/4/6 @0.5, fixed4 @0 (the shipped floor), adaptive; 3 repetitions
export BIN=$HOME/work/leleka-spec-bin/sp4
source ~/work/gpu-runs/holder2/spec-common.sh
TRACE=1 run_replay ttt-auto $HOME/work/codex-e2e/capture/943b-codex-ttt fixed3@0.5,fixed4@0.5,fixed6@0.5,fixed4@0,adaptive@0 3 0 16 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+5
View File
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: replay of the real Codex CRM session (945, first 16 requests, context 10k-30k), prefix cache auto, otherwise as 9b1
export BIN=$HOME/work/leleka-spec-bin/sp4
source ~/work/gpu-runs/holder2/spec-common.sh
run_replay crm-auto $HOME/work/codex-e2e/capture/945-codex-crm fixed3@0.5,fixed4@0.5,fixed6@0.5,fixed4@0,adaptive@0 3 0 16 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2 LELEKA_REPLAY_PREFIX_MIB=auto
+5
View File
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: the same CRM session, requests 56-67 (context 80k-90k, the long-context regime), prefix cache auto
export BIN=$HOME/work/leleka-spec-bin/sp4
source ~/work/gpu-runs/holder2/spec-common.sh
run_replay crm-long $HOME/work/codex-e2e/capture/945-codex-crm fixed3@0.5,fixed4@0.5,fixed6@0.5,fixed4@0,adaptive@0 3 56 12 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2 LELEKA_REPLAY_PREFIX_MIB=auto
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: tic-tac-toe replay (first 16 requests) with the cold-ish static tier of the live Codex run (2048 slots/layer, placeholder profile, no adaptation): the expensive-window regime
export BIN=$HOME/work/leleka-spec-bin/sp4
source ~/work/gpu-runs/holder2/spec-common.sh
run_replay ttt-static $HOME/work/codex-e2e/capture/943b-codex-ttt fixed3@0.5,fixed4@0.5,fixed6@0.5,fixed4@0,adaptive@0 3 0 16 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off
@@ -0,0 +1,5 @@
set -uo pipefail
# claude/adaptive-spec: the adaptive window's draft-floor ceiling (the request's spec_min_p is the upper bound of the policy's floor, 0 = 0.9): adaptive@0.5, @0.7, @0 against fixed4@0.5, tic-tac-toe replay first 16 requests, auto tier
export BIN=$HOME/work/leleka-spec-bin/sp4
source ~/work/gpu-runs/holder2/spec-common.sh
run_replay ttt-floor $HOME/work/codex-e2e/capture/943b-codex-ttt fixed4@0.5,adaptive@0.5,adaptive@0.7,adaptive@0 3 0 16 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+6
View File
@@ -0,0 +1,6 @@
set -uo pipefail
# claude/adaptive-spec: the shipped default (no LELEKA_SPEC* variable: adaptive window on) against the explicit fixed window (LELEKA_SPEC=4) on the first 6 requests of the tic-tac-toe replay, teacher forced, auto tier: one process each
export BIN=$HOME/work/leleka-spec-bin/sp5
source ~/work/gpu-runs/holder2/spec-common.sh
run_replay default-adaptive $HOME/work/codex-e2e/capture/943b-codex-ttt "" 2 0 6 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
run_replay explicit-fixed4 $HOME/work/codex-e2e/capture/943b-codex-ttt "" 2 0 6 LELEKA_SPEC=4 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2
+133
View File
@@ -0,0 +1,133 @@
You are a careful Rust engineer. Here is a module.
```
//! Literal translations of Original spec/draft_policy.cpp and spec/controller.cpp.
//! The serve loop uses DraftPolicy; CostController remains the separate P6 policy.
use super::contract::{Error, Result};
pub(crate) const MAX_T: usize = 8;
const SHAPE: [f64; 9] = [0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6];
const PRIOR_Q: [f64; 4] = [0.75, 0.88, 0.93, 0.96];
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Pick { pub(crate) lookup: bool, pub(crate) t: usize }
#[derive(Clone)]
pub(crate) struct DraftPolicy {
max_t: usize, margin: f64,
cost: [f64; 9], cost_n: [f64; 9],
mtp_tok: [f64; 9], mtp_n: [f64; 9],
ok: [f64; 4], bad: [f64; 4],
}
impl DraftPolicy {
pub(crate) fn new(max_t: usize, margin: f64) -> Result<Self> {
if !(1..=MAX_T).contains(&max_t) || !margin.is_finite() { return Err(Error::InvalidDimension); }
Ok(Self { max_t, margin, cost: [0.0;9], cost_n: [0.0;9], mtp_tok: [0.0;9], mtp_n: [0.0;9], ok: [0.0;4], bad: [0.0;4] })
}
fn bucket(n: usize) -> usize { if n<6 {0} else if n<12 {1} else if n<24 {2} else {3} }
pub(crate) fn lookup_rate(&self, n: usize) -> f64 {
let b=Self::bucket(n); (self.ok[b]+4.0*PRIOR_Q[b])/(self.ok[b]+self.bad[b]+4.0)
}
pub(crate) fn cost_ms(&self, t: usize) -> f64 {
let t=t.clamp(1,MAX_T);
if self.cost_n[t]>0.0 { return self.cost[t]; }
let (mut num,mut den)=(0.0,0.0);
for u in 1..=MAX_T { if self.cost_n[u]>0.0 {
let w=self.cost_n[u].min(20.0); num+=w*self.cost[u]*SHAPE[t]/SHAPE[u]; den+=w;
}}
if den>0.0 {num/den} else {SHAPE[t]}
}
fn mtp_tokens(&self,t:usize)->f64 {
if self.mtp_n[t]>0.0 {self.mtp_tok[t]} else {1.0+0.7*(t as f64-1.0)}
}
pub(crate) fn choose(&self,t_mtp:usize,lookup_k:usize,matched:usize)->Pick {
let mut p=Pick { lookup:false,t:t_mtp.clamp(1,self.max_t) };
if lookup_k==0 { return p; }
let base=self.mtp_tokens(p.t)/self.cost_ms(p.t);
let q=self.lookup_rate(matched);
let (mut e,mut qi,mut best,mut best_t)=(1.0,1.0,0.0,0);
for k in 1..=lookup_k.min(self.max_t-1) {
qi*=q; e+=qi; let r=e/self.cost_ms(k+1);
if r>best {best=r;best_t=k+1;}
}
if best_t>0 && best>base*(1.0+self.margin) { return Pick {lookup:true,t:best_t}; }
let t_full=lookup_k.min(self.max_t-1)+1;
if t_full>p.t && self.cost_n[t_full]<3.0 && q>=0.85 {p.lookup=true;p.t=t_full;}
p
}
pub(crate) fn observe(&mut self,lookup:bool,t:usize,accepted:usize,matched:usize,round_ms:f64)->Result<()> {
if !(1..=MAX_T).contains(&t) || accepted>=t || !round_ms.is_finite() {return Err(Error::InvalidDimension);}
if round_ms>0.0 {
self.cost[t]=if self.cost_n[t]>0.0 {(1.0-0.1)*self.cost[t]+0.1*round_ms} else {round_ms};
self.cost_n[t]+=1.0;
}
if lookup {
let b=Self::bucket(matched); self.ok[b]=0.97*self.ok[b]+accepted as f64;
self.bad[b]=0.97*self.bad[b]+if accepted<t-1 {1.0} else {0.0};
} else {
let got=accepted as f64+1.0;
self.mtp_tok[t]=if self.mtp_n[t]>0.0 {(1.0-0.05)*self.mtp_tok[t]+0.05*got} else {got};
self.mtp_n[t]+=1.0;
}
Ok(())
}
}
#[derive(Clone)]
pub(crate) struct CostModel {
pub(crate) dense_ms:f64, pub(crate) dense_ratio:[f64;9],
pub(crate) cpu_all_miss_ms:f64, pub(crate) hit_rate:f64, pub(crate) distinct_ratio:[f64;9],
pub(crate) extra_use_cost:f64, pub(crate) sync_ms:f64, pub(crate) mtp_draft_ms:f64, pub(crate) lookup_draft_ms:f64,
}
impl Default for CostModel {
fn default()->Self {Self {dense_ms:11.0,dense_ratio:[1.0,1.05,1.3,1.45,1.85,2.2,2.6,3.0,3.3],
cpu_all_miss_ms:15.8,hit_rate:0.55,distinct_ratio:[1.0,1.70,2.31,2.88,3.40,3.89,4.35,4.80,5.2],
extra_use_cost:0.25,sync_ms:2.4,mtp_draft_ms:1.2,lookup_draft_ms:0.01}}
}
impl CostModel {
pub(crate) fn step_ms(&self,k:usize,mtp:bool)->f64 {
let n=k.saturating_add(1).clamp(1,9);
let dense=self.dense_ms*self.dense_ratio[n-1]; let u=self.distinct_ratio[n-1];
let uses=n as f64/u;
let cpu=(1.0-self.hit_rate)*self.cpu_all_miss_ms*u*(1.0+self.extra_use_cost*(uses-1.0));
let draft=k as f64*if mtp {self.mtp_draft_ms} else {self.lookup_draft_ms};
dense+cpu+self.sync_ms+draft
}
}
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub(crate) enum Source { None, Lookup, Mtp }
#[derive(Clone,Copy,Debug,PartialEq)]
pub(crate) struct Choice {pub(crate) source:Source,pub(crate) k:usize,pub(crate) expected_tokens:f64,pub(crate) tokens_per_ms:f64}
pub(crate) struct CostController { cost:CostModel,min_gain:f64,ema:f64,mtp_p:[f64;8],lookup_q:[f64;4] }
impl CostController {
pub(crate) fn new(cost:CostModel,min_gain:f64,ema:f64)->Self {Self{cost,min_gain,ema,mtp_p:[0.86;8],lookup_q:[0.35,0.6,0.8,0.92]}}
fn bucket(n:usize)->usize {if n>=16 {3} else if n>=8 {2} else if n>=5 {1} else {0}}
fn expected(p:&[f64],k:usize,same:bool)->f64 {
let(mut e,mut run)=(1.0,1.0); for i in 0..k {run*=p[if same {0} else {i}];e+=run;}e
}
pub(crate) fn choose(&self,lookup_available:usize,lookup_match:usize,mtp_ready:bool)->Choice {
let baseline=1.0/self.cost.step_ms(0,false);
let mut best=Choice{source:Source::None,k:0,expected_tokens:1.0,tokens_per_ms:baseline};
let mut consider=|source,k,e| {let rate=e/self.cost.step_ms(k,source==Source::Mtp);
if rate>best.tokens_per_ms {best=Choice{source,k,expected_tokens:e,tokens_per_ms:rate};}};
let q=self.lookup_q[Self::bucket(lookup_match)];
for k in 1..=lookup_available.min(8) {consider(Source::Lookup,k,Self::expected(&[q],k,true));}
if mtp_ready {for k in 1..=8 {consider(Source::Mtp,k,Self::expected(&self.mtp_p,k,false));}}
if best.source!=Source::None && best.tokens_per_ms<baseline*(1.0+self.min_gain) {
Choice{source:Source::None,k:0,expected_tokens:1.0,tokens_per_ms:baseline}
} else {best}
}
pub(crate) fn observe(&mut self,c:Choice,accepted:usize,matched:usize)->Result<()> {
if c.source==Source::None || c.k==0 {return Ok(());}
if c.k>8 {return Err(Error::InvalidDimension);}
let a=accepted.min(c.k);
for i in 0..c.k.min(a+1) {
let hit=if i<a {1.0} else {0.0};
if c.source==Source::Mtp {self.mtp_p[i]+=self.ema*(hit-self.mtp_p[i]);}
else {let b=Self::bucket(matched);self.lookup_q[b]+=self.ema*(hit-self.lookup_q[b]);}
}
if c.source==Source::Mtp && a==c.k && c.k<8 {for i in c.k..8 {self.mtp_p[i]+=self.ema*(self.mtp_p[c.k-1]-self.mtp_p[i]);}}
Ok(())
}
}
```
Rewrite the whole module with identical behavior, adding a doc comment to every item and replacing single-letter variable names with descriptive ones. Output the complete file.
+116
View File
@@ -0,0 +1,116 @@
Here is a Rust module.
```
//! Original four-way trigram suffix index. It is a drafter, never target authority.
use super::contract::{Error, Result};
#[derive(Clone,Copy,Default)]
struct Slot { key:u64,pos:[u32;4],n:u8 }
pub(crate) struct SuffixDrafter {
min_match:usize,max_match:usize,history:Vec<i32>,table:Box<[Slot]>,mask:usize,last_match:usize,
/// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is
/// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots).
touched:Vec<u32>,
}
/// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control).
fn sparse_reset()->bool {
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
*ON.get_or_init(||!std::env::var("LELEKA_SUFFIX_RESET").is_ok_and(|v|v=="full"))
}
fn mix(mut x:u64)->u64 {
x^=x>>33;x=x.wrapping_mul(0xff51afd7ed558ccd);x^=x>>33;
x=x.wrapping_mul(0xc4ceb9fe1a85ec53);x^(x>>33)
}
impl SuffixDrafter {
pub(crate) fn new(min_match:usize,max_match:usize,capacity_tokens:usize)->Result<Self> {
if capacity_tokens==0 || capacity_tokens>i32::MAX as usize {return Err(Error::InvalidDimension);}
let cap=capacity_tokens.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?;
let mut table=Vec::new();table.try_reserve_exact(cap).map_err(|_|Error::InputAllocation)?;
table.resize(cap,Slot::default());
let mut history=Vec::new();history.try_reserve_exact(capacity_tokens).map_err(|_|Error::InputAllocation)?;
Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0,touched:Vec::new()})
}
pub(crate) fn metadata_bytes(&self)->Result<usize> {
self.history.capacity().checked_mul(std::mem::size_of::<i32>())
.and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::<Slot>())?))
.and_then(|n|n.checked_add(std::mem::size_of::<Self>())).ok_or(Error::Overflow)
}
pub(crate) fn reset(&mut self) {
self.history.clear();self.last_match=0;
// Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill.
if sparse_reset()&&self.touched.len()<=self.table.len()/4 {
for &i in &self.touched {self.table[i as usize]=Slot::default();}
} else {
self.table.fill(Slot::default());
}
self.touched.clear();
}
pub(crate) fn reserve_reset(&self,n:usize)->Result<()> {
if n>self.history.capacity() {return Err(Error::InputAllocation);}Ok(())
}
pub(crate) fn reserve_append(&self,n:usize)->Result<()> {
if self.history.len().checked_add(n).ok_or(Error::Overflow)?>self.history.capacity() {return Err(Error::InputAllocation);}Ok(())
}
fn key_at(&self,end:usize)->u64 {
let a=self.history[end-2] as u32 as u64;let b=self.history[end-1] as u32 as u64;let c=self.history[end] as u32 as u64;
mix(a.wrapping_mul(0x9E3779B97F4A7C15)^mix(b.wrapping_add(0x632BE59BD9B4E019))^(c<<1))|1
}
fn find_slot(&mut self,key:u64,insert:bool)->Option<usize> {
let mut i=key as usize & self.mask;
for _ in 0..=self.mask {
if self.table[i].key==key {return Some(i);}
if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;self.touched.push(i as u32);return Some(i);}
i=(i+1)&self.mask;
}None
}
pub(crate) fn append(&mut self,tokens:&[i32])->Result<()> {
self.reserve_append(tokens.len())?;
for &token in tokens {
self.history.push(token);let end=self.history.len()-1;if end<2 {continue;}
let key=self.key_at(end);
if let Some(i)=self.find_slot(key,true) {
let s=&mut self.table[i];for w in (1..4).rev() {s.pos[w]=s.pos[w-1];}
s.pos[0]=end as u32;if s.n<4 {s.n+=1;}
}
}Ok(())
}
pub(crate) fn propose(&mut self,out:&mut[i32])->usize {
self.last_match=0;let n=self.history.len();if n<4||out.is_empty() {return 0;}
let cur=n-1;let key=self.key_at(cur);let Some(i)=self.find_slot(key,false) else {return 0;};
let slot=self.table[i];let(mut best_end,mut best_len)=(0,0);
for w in 0..slot.n as usize {
let p=slot.pos[w] as usize;if p>=cur {continue;}
let mut len=0;while len<self.max_match && len<=p && self.history[p-len]==self.history[cur-len] {len+=1;}
if len>best_len {best_len=len;best_end=p;}
}
if best_len<self.min_match {return 0;}self.last_match=best_len;
let mut k=0;for q in best_end+1..=cur {if k==out.len() {break;}out[k]=self.history[q];k+=1;}k
}
pub(crate) fn last_match(&self)->usize {self.last_match}
pub(crate) fn len(&self)->usize {self.history.len()}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_sparse_reset_leaves_the_same_empty_table_as_a_full_clear() {
let mut drafter=SuffixDrafter::new(3,64,4096).unwrap();
let tokens:Vec<i32>=(0..300).map(|i|(i*7+i/3)%97).collect();
drafter.append(&tokens).unwrap();
assert!(!drafter.touched.is_empty());
drafter.reset();
assert!(drafter.table.iter().all(|s|s.key==0&&s.n==0&&s.pos==[0;4]),"every claimed slot is cleared");
assert!(drafter.touched.is_empty()&&drafter.len()==0);
// the same tokens give the same proposals after the reset as on a fresh drafter
let mut fresh=SuffixDrafter::new(3,64,4096).unwrap();
drafter.append(&tokens).unwrap();fresh.append(&tokens).unwrap();
let (mut a,mut b)=([0;7],[0;7]);
assert_eq!(drafter.propose(&mut a),fresh.propose(&mut b));
assert_eq!(a,b);
assert_eq!(drafter.last_match(),fresh.last_match());
}
}
```
Write the same module again, restructured so that each long function is split into small helper functions. Output the complete file.
+81
View File
@@ -0,0 +1,81 @@
Here is a Rust module.
```
//! Operator profile of the Original serve path's host phases (`LELEKA_SERVE_PROFILE=1`, off by default).
//!
//! Named wall-clock spans (inclusive of any wait inside them) are summed per thread and printed as one
//! `DBG profile` line per request by the stack, then reset. Nested spans are not additive. Nothing here
//! changes what runs: when the switch is off a span is one cached boolean test.
use std::cell::RefCell;
use std::time::Instant;
/// `LELEKA_SERVE_PROFILE` set to anything but `0`, read once.
pub(crate) fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_SERVE_PROFILE").is_ok_and(|v| !v.is_empty() && v != "0"))
}
thread_local! {
static SUMS: RefCell<Vec<(&'static str, f64, u64)>> = const { RefCell::new(Vec::new()) };
}
/// A running span; its time is added to `name` when it is dropped.
pub(crate) struct Span {
name: &'static str,
started: Option<Instant>,
}
impl Span {
/// Add the time so far to this span's name and disarm it.
pub(crate) fn stop(&mut self) {
if let Some(started) = self.started.take() {
add(self.name, started.elapsed().as_secs_f64() * 1e3);
}
}
}
impl Drop for Span {
fn drop(&mut self) {
if let Some(started) = self.started {
add(self.name, started.elapsed().as_secs_f64() * 1e3);
}
}
}
/// Start a span (a no-op unless the profile is on).
pub(crate) fn span(name: &'static str) -> Span {
Span { name, started: enabled().then(Instant::now) }
}
/// Add `ms` to `name` (one call).
pub(crate) fn add(name: &'static str, ms: f64) {
if !enabled() {
return;
}
SUMS.with(|sums| {
let mut sums = sums.borrow_mut();
match sums.iter_mut().find(|(n, _, _)| *n == name) {
Some(entry) => {
entry.1 += ms;
entry.2 += 1;
}
None => sums.push((name, ms, 1)),
}
});
}
/// Print the sums since the last report as `DBG profile <label>: name=total_ms/count ...` and reset them.
pub(crate) fn report(label: &str) {
if !enabled() {
return;
}
let mut sums = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut()));
// the driver's own host spans (window launch, doorbell waits, syncs, head, MTP draft graphs)
sums.extend(leleka_cuda_driver::host_profile::take());
let mut line = format!("DBG profile {label}:");
for (name, ms, count) in sums {
line.push_str(&format!(" {name}={ms:.2}/{count}"));
}
eprintln!("{line}");
}
```
Translate this module to idiomatic Python 3 with type hints, keeping every comment. Output the complete file.
+170
View File
@@ -0,0 +1,170 @@
Here is a Rust module.
```
//! expert_source.cpp `RouterLookahead` for the file-mapped expert source (the Original's `--mmap-experts`):
//! when the CPU tier starts layer `l`, a background thread applies layer `l + 1`'s router (BF16 host copy) to
//! layer `l`'s MoE input (the residual stream changes little from one layer to the next), takes each row's
//! top-10, drops the experts the VRAM tier holds and advises the kernel to read the rest's pages
//! (`MADV_WILLNEED`), so they are on the way while layer `l` computes. A prediction only warms pages: it
//! never changes which experts are computed or how. `submit` never waits: a prediction still running for an
//! earlier layer makes this one skip.
use std::sync::{Arc, Condvar, Mutex, atomic::{AtomicU64, Ordering}};
use std::thread::JoinHandle;
const HIDDEN: usize = 2560;
const EXPERTS: usize = 512;
const TOP_K: usize = 10;
const MAX_ROWS: usize = 8;
/// Where layer `l`'s routed experts live in the mapped bank: per role (gate, up, down) the address of
/// expert 0 and the bytes of one expert (experts are contiguous and uniform, `checked_descriptor`).
pub(in crate::qwen_forward) type LayerLayout = [(usize, usize); 3];
#[derive(Default)]
struct Mail {
pending: bool,
busy: bool,
quit: bool,
layer: usize,
rows: usize,
x: Vec<f32>,
resident: Vec<bool>,
}
#[derive(Default)]
pub(in crate::qwen_forward) struct LookaheadStats {
pub(in crate::qwen_forward) submitted: AtomicU64,
pub(in crate::qwen_forward) skipped: AtomicU64,
pub(in crate::qwen_forward) predicted: AtomicU64,
pub(in crate::qwen_forward) busy_us: AtomicU64,
}
pub(in crate::qwen_forward) struct RouterLookahead {
shared: Arc<(Mutex<Mail>, Condvar)>,
stats: Arc<LookaheadStats>,
thread: Option<JoinHandle<()>>,
}
impl RouterLookahead {
/// `routers[l]`: layer l's `ffn_gate_inp` as BF16 bits, 512 rows of 2560; `layouts[l]`: its bank layout.
pub(in crate::qwen_forward) fn start(routers: Vec<Box<[u16]>>, layouts: Vec<LayerLayout>) -> Option<Self> {
if routers.len() != layouts.len() || routers.iter().any(|r| r.len() != EXPERTS * HIDDEN) {
return None;
}
let mut mail = Mail::default();
mail.x.try_reserve_exact(MAX_ROWS * HIDDEN).ok()?;
mail.resident.try_reserve_exact(EXPERTS).ok()?;
let shared = Arc::new((Mutex::new(mail), Condvar::new()));
let stats = Arc::new(LookaheadStats::default());
let (worker_shared, worker_stats) = (Arc::clone(&shared), Arc::clone(&stats));
let thread = std::thread::Builder::new()
.name("leleka-lookahead".into())
.spawn(move || run(&worker_shared, &worker_stats, &routers, &layouts))
.ok()?;
Some(Self { shared, stats, thread: Some(thread) })
}
/// Layer `layer`'s MoE input (`rows` x 2560): predict and warm layer `layer + 1`, leaving out the experts
/// `resident` (of layer `layer + 1`) says the VRAM tier holds.
pub(in crate::qwen_forward) fn submit(&self, layer: usize, x: &[f32], resident: impl Fn(usize) -> bool) {
let rows = (x.len() / HIDDEN).min(MAX_ROWS);
if rows == 0 {
return;
}
let (lock, wake) = &*self.shared;
let Ok(mut mail) = lock.try_lock() else {
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
return;
};
if mail.busy || mail.pending || mail.quit {
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
return;
}
mail.x.clear();
mail.x.extend_from_slice(&x[..rows * HIDDEN]);
mail.resident.clear();
mail.resident.extend((0..EXPERTS).map(&resident));
mail.layer = layer + 1;
mail.rows = rows;
mail.pending = true;
drop(mail);
self.stats.submitted.fetch_add(1, Ordering::Relaxed);
wake.notify_one();
}
pub(in crate::qwen_forward) fn stats(&self) -> &LookaheadStats {
&self.stats
}
}
impl Drop for RouterLookahead {
fn drop(&mut self) {
let (lock, wake) = &*self.shared;
if let Ok(mut mail) = lock.lock() {
mail.quit = true;
}
wake.notify_all();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
fn run(shared: &(Mutex<Mail>, Condvar), stats: &LookaheadStats, routers: &[Box<[u16]>], layouts: &[LayerLayout]) {
let (lock, wake) = shared;
let mut x = vec![0.0f32; MAX_ROWS * HIDDEN];
let mut resident = vec![false; EXPERTS];
let mut logits = vec![0.0f32; MAX_ROWS * EXPERTS];
let mut order: Vec<usize> = (0..EXPERTS).collect();
let mut want: Vec<usize> = Vec::with_capacity(MAX_ROWS * TOP_K);
loop {
let (layer, rows) = {
let Ok(mut mail) = lock.lock() else { return };
while !mail.quit && !mail.pending {
mail = match wake.wait(mail) {
Ok(mail) => mail,
Err(_) => return,
};
}
if mail.quit {
return;
}
mail.pending = false;
mail.busy = true;
let rows = mail.rows;
x[..rows * HIDDEN].copy_from_slice(&mail.x[..rows * HIDDEN]);
resident.copy_from_slice(&mail.resident);
(mail.layer, rows)
};
let started = std::time::Instant::now();
if let (Some(router), Some(layout)) = (routers.get(layer), layouts.get(layer)) {
let out = &mut logits[..rows * EXPERTS];
if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &x[..rows * HIDDEN], rows, out).is_ok() {
want.clear();
for t in 0..rows {
let lt = &out[t * EXPERTS..(t + 1) * EXPERTS];
order.iter_mut().enumerate().for_each(|(i, o)| *o = i);
order.select_nth_unstable_by(TOP_K - 1, |&a, &b| lt[b].total_cmp(&lt[a]));
for &e in &order[..TOP_K] {
if !resident[e] && !want.contains(&e) {
want.push(e);
}
}
}
for &e in &want {
for &(base, bytes) in layout {
leleka_native_cpu_expert::advise_will_need(base + e * bytes, bytes);
}
}
stats.predicted.fetch_add(want.len() as u64, Ordering::Relaxed);
}
}
stats.busy_us.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
if let Ok(mut mail) = lock.lock() {
mail.busy = false;
}
}
}
```
Add a thorough set of unit tests for the public functions of this module and show the final test module. Then reprint the module's public API.
+60
View File
@@ -0,0 +1,60 @@
# sourced by the 9a*-spec-*.sh holder jobs (claude/adaptive-spec); defines run_arms
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
A=$HOME/leleka-gates/assets
G=$HOME/work/gpu-runs
mkdir -p $G/mtp-staging-own; chmod 700 $G/mtp-staging-own
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
PH=$G/baseline/profile.bin
BIN=${BIN:-$HOME/work/leleka-spec-bin/sp1}
cd $HOME/work/leleka-spec-bin
FILTER='^MEMINFO|^DBG vram|^DBG mtp|^DBG (corpus|timing|profile request|tier request|verify-profile|spec-stats|spec-trace)|smoke: greedy|smoke: sampled|smoke: short|expert cache|cpu expert pool|test result|panicked|FAILED|leleka-serve'
mem_check() { avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"; [ "$avail" -ge 15 ]; }
# run_arms LABEL ARMS REPEAT MAX_NEW PROMPTS [ENV=V ...]: one model load, the prompts of PROMPTS (chat turns, @file: lines allowed) each served REPEAT
# times, pass p of prompt i by arm (p+i) mod |ARMS|; static tier unless the caller sets ADAPT_EVERY
run_arms() {
local label=$1 arms=$2 repeat=$3 max_new=$4 prompts=$5; shift 5
mem_check || { echo "abort $label: memory"; return; }
echo "=== spec $label: arms=$arms repeat=$repeat max_new=$max_new prompts=$prompts $*"; date -u +%FT%TZ
env LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$prompts LELEKA_SMOKE_MAX_NEW=$max_new LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=$repeat LELEKA_SMOKE_CHAT=1 \
LELEKA_SMOKE_MAX_CONTEXT=${MAXCTX:-4096} LELEKA_SPEC_ARMS=$arms LELEKA_SPEC_STATS=1 LELEKA_SPEC_TRACE=${TRACE:-1} \
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=${PROFILE:-$PH} "$@" \
$BIN --ignored --test-threads=1 --nocapture original_serve_smoke_prompt_decode 2>&1 | grep -E "$FILTER"
echo "rc=${PIPESTATUS[0]} spec=$label"; date -u +%FT%TZ
}
date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader; sha256sum $BIN
LONGFILTER='^MEMINFO|^DBG vram|^DBG (profile request|spec-stats|spec-trace)|long-smoke (prompt tokens|prefill|result|output)|expert cache|cpu expert pool|test result|panicked|FAILED|leleka-serve'
# run_long LABEL ARMS TOKENS REPEAT MAX_NEW [ENV=V ...]: the long-context smoke (code filler from long-code.txt, a question that makes the model re-emit it),
# pass p served by arm p mod |ARMS|; every pass reads the whole prompt (no cache)
run_long() {
local label=$1 arms=$2 tokens=$3 repeat=$4 max_new=$5; shift 5
mem_check || { echo "abort $label: memory"; return; }
echo "=== spec-long $label: arms=$arms tokens=$tokens repeat=$repeat max_new=$max_new $*"; date -u +%FT%TZ
env LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192 LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 \
LELEKA_ORIGINAL_SERVE_LONG_TOKENS=$tokens LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=$max_new LELEKA_ORIGINAL_SERVE_LONG_REPEAT=$repeat \
LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE=$G/long-code.txt \
"LELEKA_ORIGINAL_SERVE_LONG_QUESTION=
End of the source files. Task: reprint the file leleka-runtime/src/qwen_forward/original_serve_config.rs from the beginning, exactly as it appears above, without comments from you." \
LELEKA_SMOKE_MIN_P=0.5 LELEKA_SPEC_ARMS=$arms LELEKA_SPEC_STATS=1 LELEKA_SPEC_TRACE=${TRACE:-0} \
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=${PROFILE:-$PH} "$@" \
$BIN --ignored --test-threads=1 --nocapture original_serve_long_context_streamed_kv_smoke 2>&1 | grep -E "$LONGFILTER"
echo "rc=${PIPESTATUS[0]} spec-long=$label"; date -u +%FT%TZ
}
REPLAYFILTER='^REPLAY|^DBG spec-(stats|trace)|^DBG tier request|test result|panicked|FAILED|leleka-serve expert cache'
# run_replay LABEL DIR ARMS REPS FIRST COUNT [ENV=V ...]: replay of a captured agent session (teacher forced: every arm decodes the recorded text),
# one warm-up pass then REPS x |ARMS| passes (arm labels may pin the request floor: fixed4@0). Tier from the caller's environment.
run_replay() {
local label=$1 dir=$2 arms=$3 reps=$4 first=$5 count=$6; shift 6
mem_check || { echo "abort $label: memory"; return; }
echo "=== spec-replay $label: dir=$dir arms=$arms reps=$reps first=$first count=$count $*"; date -u +%FT%TZ
env LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_REPLAY_DIR=$dir LELEKA_REPLAY_FIRST=$first LELEKA_REPLAY_COUNT=$count LELEKA_REPLAY_REPS=$reps LELEKA_REPLAY_FORCE=1 \
LELEKA_REPLAY_SPEC_MIN_P=0 LELEKA_SPEC_ARMS=$arms LELEKA_SPEC_STATS=1 LELEKA_SPEC_TRACE=${TRACE:-0} LELEKA_SERVE_PROFILE=0 \
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=${PROFILE:-$PH} "$@" \
$BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke 2>&1 | grep -E "$REPLAYFILTER"
echo "rc=${PIPESTATUS[0]} spec-replay=$label"; date -u +%FT%TZ
}
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Parse a claude/adaptive-spec holder log (run_arms) into per-arm tables.
usage: spec_analyze.py LOG [--trace ARM:PROMPT:PASS]
Per arm: weighted decode tok/s = sum(tokens) / sum(serve ms) (decode.serve span of the profile line, i.e. the verify loop
alone) and with the phase wall (DBG timing, includes the per-request verifier assembly), tokens per round, accepted-per-round
histogram, mean round ms and round count per window width. Also: greedy token equality of every arm against fixed4, per prompt.
"""
import re, sys, collections, statistics
def main():
path = sys.argv[1]
lines = open(path, errors="replace").read().splitlines()
stats = None; prof = None
reqs = [] # dict per corpus request
outputs = {} # (prompt, pass) -> (arm, ids)
trace = collections.defaultdict(list) # request index -> trace lines
cur_trace = []
for ln in lines:
if ln.startswith("DBG spec-trace"):
cur_trace.append(ln)
elif ln.startswith("DBG spec-stats"):
stats = ln; stats_trace = cur_trace; cur_trace = []
elif ln.startswith("DBG profile request"):
prof = ln
else:
m = re.match(r"DBG corpus (\d+) output pass=(\d+) arm=(\S+) \((\d+) tokens, rounds (\d+)\): (.*)", ln)
if m:
outputs[(int(m.group(1)), int(m.group(2)))] = (m.group(3), m.group(6).split())
continue
m = re.match(r"DBG corpus (\d+) timing pass=(\d+) arm=(\S+) prompt=(\d+) produced=(\d+) rounds=(\d+) ttft_ms=([\d.]+) total_ms=([\d.]+)", ln)
if m:
r = dict(prompt=int(m.group(1)), pass_=int(m.group(2)), arm=m.group(3), plen=int(m.group(4)),
produced=int(m.group(5)), rounds=int(m.group(6)), ttft=float(m.group(7)))
r["stats"] = stats; r["trace"] = stats_trace if stats else []
r["serve_ms"] = None
if prof:
mm = re.search(r"decode\.serve=([\d.]+)/", prof)
if mm: r["serve_ms"] = float(mm.group(1))
reqs.append(r); stats = None; prof = None
continue
m = re.match(r"DBG timing corpus (\d+) pass (\d+): prompt ([\d.]+) ms, decode ([\d.]+) ms, produced (\d+)", ln)
if m and reqs and reqs[-1]["prompt"] == int(m.group(1)) and reqs[-1]["pass_"] == int(m.group(2)):
reqs[-1]["phase_ms"] = float(m.group(4))
arms = collections.OrderedDict()
for r in reqs:
st = r["stats"] or ""
kv = dict(re.findall(r"(\w+)=(\S+)", st))
a = arms.setdefault(r["arm"], dict(tok=0, serve=0.0, phase=0.0, rounds=0, n=0, tpr=[], hist_t=[0]*9, hist_acc=[0]*9,
ms_by_t=[0.0]*9, expl=0, lookup=0, per_prompt=collections.defaultdict(list)))
a["n"] += 1; a["tok"] += r["produced"]; a["rounds"] += r["rounds"]
if r.get("serve_ms"): a["serve"] += r["serve_ms"]
if r.get("phase_ms"): a["phase"] += r["phase_ms"]
a["expl"] += int(kv.get("explored", 0)); a["lookup"] += int(kv.get("lookup_rounds", 0))
if "T_hist[0..=8]" in kv:
for i, v in enumerate(kv["T_hist[0..=8]"].split(",")): a["hist_t"][i] += int(v)
for i, v in enumerate(kv["acc_hist"].split(",")): a["hist_acc"][i] += int(v)
ms = kv["ms_by_T"].split(",")
th = kv["T_hist[0..=8]"].split(",")
for i, v in enumerate(ms):
if v != "-": a["ms_by_t"][i] += float(v) * int(th[i])
if r.get("serve_ms"): a["per_prompt"][r["prompt"]].append(r["produced"] * 1e3 / r["serve_ms"])
print(f"{'arm':10} {'reqs':>4} {'tok':>6} {'serve tok/s':>11} {'phase tok/s':>11} {'tok/round':>9} {'round ms':>8} {'lookup%':>7} {'expl':>5}")
for name, a in arms.items():
timed = sum(a["hist_t"])
tot_ms = sum(a["ms_by_t"])
print(f"{name:10} {a['n']:4d} {a['tok']:6d} {a['tok']*1e3/max(a['serve'],1e-9):11.2f} {a['tok']*1e3/max(a['phase'],1e-9):11.2f} "
f"{a['tok']/max(a['rounds'],1):9.3f} {tot_ms/max(timed,1):8.2f} {100*a['lookup']/max(timed,1):7.1f} {a['expl']:5d}")
print()
for name, a in arms.items():
timed = sum(a["hist_t"])
print(f"[{name}] window width histogram (rows: share%, mean round ms):")
print(" " + " ".join(f"T{t}:{100*a['hist_t'][t]/max(timed,1):4.1f}%/{(a['ms_by_t'][t]/a['hist_t'][t] if a['hist_t'][t] else 0):5.1f}ms" for t in range(1, 9) if a["hist_t"][t]))
acc = a["hist_acc"]
print(" accepted per round: " + " ".join(f"{i}:{100*acc[i]/max(timed,1):.1f}%" for i in range(9) if acc[i]))
# greedy equality against fixed4 (or the first arm)
ref = "fixed4" if "fixed4" in arms else next(iter(arms))
by = collections.defaultdict(dict)
for (p, q), (arm, ids) in outputs.items():
by[p].setdefault(arm, []).append(ids)
print(f"\ngreedy token ids against {ref} (same prompt, any pass): identical / first-diff index")
for arm in arms:
if arm == ref: continue
same = tot = 0; diffs = []
for p, d in sorted(by.items()):
if arm in d and ref in d:
for ids in d[arm]:
tot += 1
r0 = d[ref][0]
n = min(len(ids), len(r0))
k = next((i for i in range(n) if ids[i] != r0[i]), None)
if k is None and len(ids) == len(r0): same += 1
else: diffs.append((p, k if k is not None else n))
print(f" {arm}: {same}/{tot} identical; differing (prompt, first diff token): {diffs}")
# fixed4 self-consistency (repeats of the reference arm)
selfsame = selftot = 0
for p, d in by.items():
if ref in d and len(d[ref]) > 1:
for ids in d[ref][1:]:
selftot += 1; selfsame += ids == d[ref][0]
print(f" {ref} against itself (repeat passes): {selfsame}/{selftot} identical")
# per prompt serve tok/s per arm
print("\nper-prompt serve tok/s (mean over passes):")
ps = sorted({p for a in arms.values() for p in a["per_prompt"]})
print("prompt " + " ".join(f"{n:>9}" for n in arms))
for p in ps:
print(f"{p:6d} " + " ".join(f"{statistics.mean(a['per_prompt'][p]) if a['per_prompt'].get(p) else 0:9.2f}" for a in arms.values()))
if "--trace" in sys.argv:
spec = sys.argv[sys.argv.index("--trace") + 1].split(":")
arm, prompt, pas = spec[0], int(spec[1]), int(spec[2])
for r in reqs:
if r["arm"] == arm and r["prompt"] == prompt and r["pass_"] == pas:
print("\n".join(l.replace("DBG spec-trace ", "") for l in r["trace"]))
main()
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Parse a claude/adaptive-spec replay log (run_replay) into a per-arm table.
usage: spec_replay.py LOG [--trace ARM:PASS:REQUEST]
Per arm (the warm-up pass is dropped): weighted decode tok/s per pass (total tokens / total decode time, REPLAY PASS lines),
mean and range over the repetitions, pooled tokens per round, accepted-per-round histogram, mean round ms per window width
(from the `DBG spec-stats` lines), and the policy trace of one request (`DBG spec-trace`, when the job traced).
"""
import re, sys, collections, statistics
def main():
lines = open(sys.argv[1], errors="replace").read().splitlines()
passes = collections.OrderedDict() # (pass_no) -> dict(arm, tok_s, tokens)
arms = collections.OrderedDict()
cur_stats = None; trace = []
req_trace = {} # (arm, pass, request) -> trace lines
for ln in lines:
if ln.startswith("DBG spec-trace"):
trace.append(ln); continue
m = re.match(r"DBG spec-stats arm=(\S+) (.*)", ln)
if m:
cur_stats = (m.group(1), m.group(2)); stats_trace = trace; trace = []; continue
m = re.match(r"REPLAY #(\d+) pass=(\d+) (\S+) arm=(\S+) .*produced=(\d+) rounds=(\d+) .*decode_ms=([\d.]+)", ln)
if m:
n, p, lab, arm = int(m.group(1)), int(m.group(2)), m.group(3), m.group(4)
if cur_stats:
req_trace[(arm, p, n)] = stats_trace
if lab != "warm":
a = arms.setdefault(arm, dict(hist_t=[0]*9, hist_acc=[0]*9, ms=[0.0]*9, rounds=0, tokens=0, expl=0, lookup=0, passes={}))
kv = dict(re.findall(r"(\w+)(?:\[[^\]]*\])?=(\S+)", cur_stats[1]))
a["rounds"] += int(kv["rounds"]); a["tokens"] += int(kv["tokens"])
a["expl"] += int(kv["explored"]); a["lookup"] += int(kv["lookup_rounds"])
th = kv["T_hist"].split(",")
for i, v in enumerate(th): a["hist_t"][i] += int(v)
for i, v in enumerate(kv["acc_hist"].split(",")): a["hist_acc"][i] += int(v)
for i, v in enumerate(kv["ms_by_T"].split(",")):
if v != "-": a["ms"][i] += float(v) * int(th[i])
cur_stats = None
continue
m = re.match(r"REPLAY PASS (\d+) (\S+) arm=(\S+) requests=(\d+) weighted_decode_tok_s=([\d.]+) \(tokens (\d+) / decode ([\d.]+) s\) rounds=(\d+)", ln)
if m:
p, lab, arm = int(m.group(1)), m.group(2), m.group(3)
if lab == "warm": continue
a = arms.setdefault(arm, dict(hist_t=[0]*9, hist_acc=[0]*9, ms=[0.0]*9, rounds=0, tokens=0, expl=0, lookup=0, passes={}))
a["passes"][p] = (float(m.group(5)), int(m.group(6)), float(m.group(7)), int(m.group(8)))
print(f"{'arm':14} {'reps':>4} {'tok/s mean':>10} {'min':>7} {'max':>7} {'tok/round':>9} {'round ms':>8} {'lookup%':>7} {'explored':>8}")
base = None
for name, a in arms.items():
v = [x[0] for x in a["passes"].values()]
if not v: continue
timed = sum(a["hist_t"]); tot = sum(a["ms"])
tot_tok = sum(x[1] for x in a["passes"].values()); tot_s = sum(x[2] for x in a["passes"].values()); tot_r = sum(x[3] for x in a["passes"].values())
w = tot_tok / tot_s
print(f"{name:14} {len(v):4d} {w:10.2f} {min(v):7.2f} {max(v):7.2f} {tot_tok/max(tot_r,1):9.3f} {tot/max(timed,1):8.2f} {100*a['lookup']/max(timed,1):7.1f} {a['expl']:8d}")
print()
for name, a in arms.items():
timed = sum(a["hist_t"])
if not timed: continue
print(f"[{name}] widths (share / mean round ms): " + " ".join(
f"T{t}:{100*a['hist_t'][t]/timed:4.1f}%/{a['ms'][t]/a['hist_t'][t]:5.1f}" for t in range(1, 9) if a["hist_t"][t]))
print(f" accepted per round: " + " ".join(f"{i}:{100*a['hist_acc'][i]/timed:.1f}%" for i in range(9) if a["hist_acc"][i]))
# paired by repetition: each arm's per-pass tok/s relative to the same repetition's fixed4@0.5
ref = next((n for n in arms if n.startswith("fixed4@0.5")), None)
if ref:
print(f"\nper-repetition tok/s relative to {ref} (same repetition = adjacent passes):")
order = sorted({p for a in arms.values() for p in a["passes"]})
nar = len(arms)
for name, a in arms.items():
rel = []
for p, (t, *_r) in sorted(a["passes"].items()):
rep = (p - 1) // nar
lo = 1 + rep * nar
rr = [arms[ref]["passes"][q][0] for q in range(lo, lo + nar) if q in arms[ref]["passes"]]
if rr: rel.append(100 * (t / rr[0] - 1))
print(f" {name:14} " + " ".join(f"{x:+6.1f}%" for x in rel))
if "--trace" in sys.argv:
arm, p, n = sys.argv[sys.argv.index("--trace") + 1].split(":")
print("\n".join(l.replace("DBG spec-trace ", "") for l in req_trace.get((arm, int(p), int(n)), [])))
main()