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:
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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(<[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.
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user