From 3a81783a3c851bc3619e937d1b4990a1bbe964fe Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 01:26:34 +0200 Subject: [PATCH 1/8] feat(spec): adaptive speculative window policy (LELEKA_SPEC_ADAPTIVE), per-round chain plan, spec stats/trace, LELEKA_SPEC* fixed-window knobs AdaptivePolicy picks per round the verify width and draft source by expected tokens per ms from online calibrated acceptance (MTP prob buckets x depth, suffix match buckets by agreement) and a forgetting linear cost fit per window width, with hysteresis and staleness-driven exploration; plans the next MTP chain (length, floor). Verification is unchanged. Off by default. Co-Authored-By: Claude Sonnet 5.5 --- crates/leleka-runtime/src/qwen_forward/mod.rs | 1 + .../src/qwen_forward/original_serve_engine.rs | 47 +- .../src/qwen_forward/original_serve_host.rs | 25 +- .../src/qwen_forward/original_serve_stack.rs | 2 +- .../qwen_forward/original_spec_adaptive.rs | 791 ++++++++++++++++++ .../qwen_forward/original_spec_controller.rs | 128 ++- .../src/qwen_forward/original_spec_draft.rs | 3 + 7 files changed, 970 insertions(+), 27 deletions(-) create mode 100644 crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs diff --git a/crates/leleka-runtime/src/qwen_forward/mod.rs b/crates/leleka-runtime/src/qwen_forward/mod.rs index 38c0a922..33c61e80 100644 --- a/crates/leleka-runtime/src/qwen_forward/mod.rs +++ b/crates/leleka-runtime/src/qwen_forward/mod.rs @@ -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; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index 122424bf..42075704 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -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 { 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,draft:DraftStage,first:FirstStage,poisoned:bool, } impl OriginalServeEngine

{ pub(crate) fn new(port:P,vocabulary:u32,max_t:usize,max_drafts:usize)->Result { 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 OriginalDraftEngine> 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 OriginalDraftEngine> 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 OriginalDraftEngine> for Origi if next=self.max_drafts.min(self.max_t-1); + let stopped=completion.probabilities[next-1]=self.plan_drafts.min(self.max_t-1); if !stopped {return Err(Error::IdentityMismatch);} } } @@ -338,11 +347,33 @@ impl OriginalFirstDraftEngine 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, } 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} + } + /// 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::().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;} + if std::env::var("LELEKA_SPEC_ADAPTIVE").is_ok_and(|v|matches!(v.as_str(),"on"|"1"|"yes")) { + 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 } /// `STRATA_SPEC_COUPLED`: set, non-empty and not "0" (read once by the operator, not per request). pub(crate) fn coupled_from_environment()->bool { @@ -358,7 +389,7 @@ impl OriginalServeSettings { /// The one production call of `OriginalSpecController::new`. pub(crate) fn controller(&self)->Result { 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)) } } @@ -402,6 +433,8 @@ pub(crate) fn serve_request(controller:&mut OriginalSpecCo let _=controller.finish_request(engine);return Err(e); } controller.finish_request(engine)?; + if super::original_spec_controller::stats_enabled() {eprintln!("DBG spec-stats: {}",controller.take_stats().line());} + else {let _=controller.take_stats();} let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context}); Ok(ServeOutcome{stop,produced,rounds}) } @@ -975,7 +1008,7 @@ mod tests { fn serve(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option) ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { 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}; 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(); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs index 8a67fc62..7bb4eb0c 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs @@ -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, diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 7b59312d..7166de13 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -305,7 +305,7 @@ 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 settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); 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"))?; diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs new file mode 100644 index 00000000..22e3c2f0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs @@ -0,0 +1,791 @@ +//! 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 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(name: &str) -> Option { + 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)>, + 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, + 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.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 30 % 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 = 0.3 * 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 + 0.3 * (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) { + 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; + 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 && self.since_explore >= period { + let mut pick: Option = 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; + } + } + 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); + 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 + 0.3 * 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::>().join(","); + let mean_ms: Vec = (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, f64, usize) { + let max_t = 8; + let probs: Vec = (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) { + 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::() / seq.iter().map(|(_, n)| *n as f64).sum::(); + 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::() 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::>() + }; + 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}"); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs index acb2d6d9..238d71da 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs @@ -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=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=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 for SpecError {fn from(e:Error)->Self {Self::Forward(e)}} @@ -47,13 +59,20 @@ pub(crate) trait OriginalSpecEngine:OriginalDraftEngine { 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, } 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 { 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)->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 { @@ -63,13 +82,14 @@ struct Request { } pub(crate) struct OriginalSpecController { config:SpecConfig,policy:DraftPolicy,suffix:SuffixDrafter,request:Option,rounds:u64,failed:bool,owner:Rc<()>, + adaptive:Option,plan:Option,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 { 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, next_position:i64,round_number:u64,work:Option,owner:Rc<()>,bookkeeping_error:Option, } impl CommittedRound { @@ -99,7 +119,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(())}) + let adaptive=config.adaptive.map(AdaptivePolicy::new); + Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),adaptive,plan:None,stats:SpecStats::default()}) } /// Policy and adaptive round cadence survive requests, exactly like serve. /// Prompt suffix/history is reset for each request, including resumed ones. @@ -120,6 +141,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(()) @@ -134,6 +160,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(&mut self,engine:&mut E,target:&E::TargetCheckpoint,draft:&E::DraftCheckpoint,primary:SpecError)->SpecError { @@ -153,7 +182,22 @@ impl OriginalSpecController { if r.min_p>0.0 {t=1;while t=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;} @@ -209,7 +253,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})) } } @@ -238,11 +282,14 @@ impl OriginalSpecController { if let Some(e)=round.bookkeeping_error {Err(e.into())} else if r.finished {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), } } } @@ -263,11 +310,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(()) @@ -409,6 +476,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]); diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_draft.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_draft.rs index c4eaad57..df8ff0f2 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_draft.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_draft.rs @@ -40,6 +40,9 @@ pub(crate) trait OriginalDraftEngine { /// 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} From 53e2ad24801df909de886daff0839870a51fbe28 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 01:33:24 +0200 Subject: [PATCH 2/8] feat(spec): LELEKA_SPEC_ARMS in-process window-policy A/B, spec stats per request, @file prompts in the corpus smoke Co-Authored-By: Claude Sonnet 5.5 --- .../src/backend_original_serve_smoke.rs | 23 +++++-- .../src/qwen_forward/original_serve_engine.rs | 21 ++++++- .../src/qwen_forward/original_serve_stack.rs | 63 +++++++++++++++++-- 3 files changed, 97 insertions(+), 10 deletions(-) diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index 0735f019..8dc9a63a 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -235,7 +235,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"); @@ -247,6 +259,9 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { let ids = tokenizer.encode(&turn, true).expect("corpus tokenization failed"); eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::>().join(",")); for pass in 0..repeat { + if !spec_arms.is_empty() { + assert!(stack.select_spec_arm(&spec_arms[(pass + index) % spec_arms.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); // LELEKA_SMOKE_SAMPLED=1: the corpus is served with the sampling head and a penalty window (an agent-style @@ -267,16 +282,16 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { let total = started.elapsed(); 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::>().join(" ")); } else { - eprintln!("DBG corpus {index} output pass={pass} ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::>().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::>().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()), diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index 42075704..aee1f572 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -379,6 +379,25 @@ impl OriginalServeSettings { 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 label in list.split(',').map(str::trim).filter(|l|!l.is_empty()) { + let mut s=base;s.adaptive=None; + if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::().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((label.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) @@ -433,8 +452,6 @@ pub(crate) fn serve_request(controller:&mut OriginalSpecCo let _=controller.finish_request(engine);return Err(e); } controller.finish_request(engine)?; - if super::original_spec_controller::stats_enabled() {eprintln!("DBG spec-stats: {}",controller.take_stats().line());} - else {let _=controller.take_stats();} let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context}); Ok(ServeOutcome{stop,produced,rounds}) } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 7166de13..68d4e394 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -205,6 +205,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, + verifier_max_t: usize, /// Why the stack can serve no more (a lost physical owner); `None` while healthy. broken: Option, // The empty-prompt lineage taken at load: the reset target of every request. @@ -305,7 +311,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::from_environment(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 = 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"))?; @@ -321,7 +339,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let dense = DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?; let moe = MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_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, draft) = match &config.rt_directory { Some(directory) => OriginalPromptExecutor::select_rt_mtp( binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, @@ -329,7 +347,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 })?; @@ -424,6 +442,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { blobs, formats, controller, + parked, + arm_label, + arm_order, + verifier_max_t, broken: None, empty_session, empty_draft, @@ -469,6 +491,30 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { run_request(self, request, max_context, emit, cancel) } + /// 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 { + 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 + } + #[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) { @@ -622,6 +668,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { formats, full_policy, controller, + arm_label, + verifier_max_t, history, ple_history, ple_scratch, @@ -689,7 +737,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); @@ -790,6 +838,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) From a784d2348c7cde3f8c06b5a3096db71f8da98ee8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 02:05:07 +0200 Subject: [PATCH 3/8] feat(spec): long-context smoke serves pass p with spec arm p mod arms; long-context spec jobs Co-Authored-By: Claude Sonnet 5.5 --- .../src/backend_original_serve_smoke.rs | 13 +- docs/adaptive-spec.md | 70 ++++++++ scripts/spec/9a0-spec-smoke.sh | 4 + scripts/spec/9a1-spec-ab-static.sh | 4 + scripts/spec/9a2-spec-ab-auto.sh | 4 + scripts/spec/9a3-spec-long-100k.sh | 4 + scripts/spec/9a4-spec-long-180k.sh | 4 + scripts/spec/corpus/code1.txt | 133 ++++++++++++++ scripts/spec/corpus/code2.txt | 116 ++++++++++++ scripts/spec/corpus/code3.txt | 81 +++++++++ scripts/spec/corpus/code4.txt | 170 ++++++++++++++++++ scripts/spec/spec-common.sh | 47 +++++ scripts/spec/spec_analyze.py | 115 ++++++++++++ 13 files changed, 763 insertions(+), 2 deletions(-) create mode 100644 docs/adaptive-spec.md create mode 100644 scripts/spec/9a0-spec-smoke.sh create mode 100644 scripts/spec/9a1-spec-ab-static.sh create mode 100644 scripts/spec/9a2-spec-ab-auto.sh create mode 100644 scripts/spec/9a3-spec-long-100k.sh create mode 100644 scripts/spec/9a4-spec-long-180k.sh create mode 100644 scripts/spec/corpus/code1.txt create mode 100644 scripts/spec/corpus/code2.txt create mode 100644 scripts/spec/corpus/code3.txt create mode 100644 scripts/spec/corpus/code4.txt create mode 100644 scripts/spec/spec-common.sh create mode 100644 scripts/spec/spec_analyze.py diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index 8dc9a63a..39527712 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -470,11 +470,19 @@ 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); for pass in 0..repeat { + 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) @@ -484,7 +492,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) ); diff --git a/docs/adaptive-spec.md b/docs/adaptive-spec.md new file mode 100644 index 00000000..cbd5824c --- /dev/null +++ b/docs/adaptive-spec.md @@ -0,0 +1,70 @@ +# Adaptive speculative window (`claude/adaptive-spec`) + +Status: implemented, flag-gated (`LELEKA_SPEC_ADAPTIVE=on`), model-free tests pass; device results below. + +## 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= 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. diff --git a/scripts/spec/9a0-spec-smoke.sh b/scripts/spec/9a0-spec-smoke.sh new file mode 100644 index 00000000..aa06813a --- /dev/null +++ b/scripts/spec/9a0-spec-smoke.sh @@ -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 diff --git a/scripts/spec/9a1-spec-ab-static.sh b/scripts/spec/9a1-spec-ab-static.sh new file mode 100644 index 00000000..d614c3cf --- /dev/null +++ b/scripts/spec/9a1-spec-ab-static.sh @@ -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 diff --git a/scripts/spec/9a2-spec-ab-auto.sh b/scripts/spec/9a2-spec-ab-auto.sh new file mode 100644 index 00000000..ec8d11db --- /dev/null +++ b/scripts/spec/9a2-spec-ab-auto.sh @@ -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 diff --git a/scripts/spec/9a3-spec-long-100k.sh b/scripts/spec/9a3-spec-long-100k.sh new file mode 100644 index 00000000..f06bf9a6 --- /dev/null +++ b/scripts/spec/9a3-spec-long-100k.sh @@ -0,0 +1,4 @@ +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 +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 diff --git a/scripts/spec/9a4-spec-long-180k.sh b/scripts/spec/9a4-spec-long-180k.sh new file mode 100644 index 00000000..debb7d1a --- /dev/null +++ b/scripts/spec/9a4-spec-long-180k.sh @@ -0,0 +1,4 @@ +set -uo pipefail +# claude/adaptive-spec: 180k-token code context (the agent session scale), same arms, 2 repetitions (8 passes), 256 new tokens +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 diff --git a/scripts/spec/corpus/code1.txt b/scripts/spec/corpus/code1.txt new file mode 100644 index 00000000..12c45b43 --- /dev/null +++ b/scripts/spec/corpus/code1.txt @@ -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 { + 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 accepted0.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_msResult<()> { + 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,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, +} +/// `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=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 { + 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 { + self.history.capacity().checked_mul(std::mem::size_of::()) + .and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::())?)) + .and_then(|n|n.checked_add(std::mem::size_of::())).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 { + 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 lenbest_len {best_len=len;best_end=p;} + } + if best_lenusize {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=(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. diff --git a/scripts/spec/corpus/code3.txt b/scripts/spec/corpus/code3.txt new file mode 100644 index 00000000..91bd7edf --- /dev/null +++ b/scripts/spec/corpus/code3.txt @@ -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 = 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> = 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, +} +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