diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index 7e6242b0..5abef783 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -29,7 +29,7 @@ use super::planner::{Planner, WindowWeights}; use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs}; use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope}; use super::sm120; -use super::window_plan::gdn_index; +use super::window_plan::{gdn_index, qsa_layer}; use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group}; use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window}; use super::*; @@ -106,6 +106,10 @@ pub use all_window_assets::unsealed_window_assets; mod original_verifier; #[path = "original_verify_window_ops/original_verify_window_ops_methods.rs"] mod original_verify_window_ops_methods; +#[path = "original_verify_window_ops/side_qsa_branches.rs"] +mod side_qsa_branches; +#[path = "original_verify_window_ops/side_shared_expert.rs"] +mod side_shared_expert; #[path = "original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs"] mod window_ops_kernels_and_pcie_plan; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs b/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs index 57a03b72..3875dce3 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs @@ -26,7 +26,7 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { let mut resources = resources; resources.prepare(&policy)?; // SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused) - crate::original_gpu_schedule::set_side_streams_wanted(policy.side_mixer); + crate::original_gpu_schedule::set_side_streams_wanted(policy.side.any()); let recorded = self.record_window(t, resources, |capture, resources, groups| { // The recorder re-validates the shape; the groups come from `set_split`. let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy }; @@ -80,13 +80,13 @@ fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_, '_>, pol let want = sm120::Sm120Switches::from_env(major, minor); policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok(); policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok(); - policy.side_mixer = policy.side_mixer || want.side_mixer; + policy.side = policy.side.union(want.side_branches()); static SAID: std::sync::Once = std::sync::Once::new(); SAID.call_once(|| { eprintln!( - "leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} \ + "leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side={:?} \ (compute capability {major}.{minor}, requested {want:?})", - policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer + policy.qsa.attn_daily, policy.gu_swiglu, policy.side ) }); Ok(()) diff --git a/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs b/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs index 57985e99..44cac3c4 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs @@ -7,7 +7,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { /// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side /// streams of the window's graph. Not in a split window (two row groups), as upstream. pub(super) fn side_gdn(&self) -> bool { - self.policy.side_mixer && self.groups == 1 && self.capture.has_side() + self.policy.side.gdn && self.groups == 1 && self.capture.has_side() } /// The branch of one GDN layer. The gates (`gdn_alpha_beta`) read only the mixed activations, the gate projection /// only their q8_1 blocks; both are complete before the qkv projection starts, and the qkv projection, the conv diff --git a/crates/cuda-driver/src/original_verify_window_ops/side_qsa_branches.rs b/crates/cuda-driver/src/original_verify_window_ops/side_qsa_branches.rs new file mode 100644 index 00000000..c9671c44 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_ops/side_qsa_branches.rs @@ -0,0 +1,54 @@ +//! SIDE_MIXER, QSA part (upstream `STRATA_SIDE_MIXER=2`): the branches of a sparse-attention layer of the graph. +//! +//! In the literal order the layer is one chain on the capture stream. Its indexer chain (indexer key, tail snapshot, +//! indexer append, indexer query path, block scores and top-k) reads only the layer's mixed activations and the +//! indexer's own resident state, and its query chain (query projection, q/gate split, norm and RoPE) reads only the +//! q8_1 blocks of the mixed activations. Neither touches what the K/V projections, the K norm/RoPE and the K/V append +//! write (`kcur`, `vcur`, the KV pools), so both fork from the capture stream right after the layer's quantization and +//! join where they are first read: the indexer chain before the KV resolve (it selects the blocks), the query chain +//! before the decode attention. The launches are the literal ones and run in the same order inside each chain, so the +//! outputs are bitwise those of the in-line order; only the graph's dependency edges change. + +#[allow(unused_imports)] +use super::*; + +/// One sparse-attention layer of a window: its index among the QSA layers, the window rows and whether the rows run as +/// one batched launch. +#[derive(Clone, Copy)] +pub(super) struct QsaSideLayer { + pub(super) q: usize, + pub(super) rows: Rows, + pub(super) batched: bool, +} + +impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { + /// The QSA layers run their indexer and query chains on side streams (not in a split window, as upstream). + pub(super) fn side_qsa(&self) -> bool { + self.policy.side.qsa && self.groups == 1 && self.capture.has_side() + } + /// Fork the indexer chain on side stream 0 and the query chain on side stream 1. + pub(super) fn issue_qsa_side(&mut self, layer: QsaSideLayer) -> Result<()> { + self.capture.side_fork(0)?; + self.issue_indexer_chain(layer)?; + self.capture.side_end(0)?; + self.capture.side_fork(1)?; + self.issue_query_chain(layer)?; + self.capture.side_end(1) + } + /// The indexer's key, tail snapshot (before the first append), append, query path, block scores and top-k. + fn issue_indexer_chain(&mut self, layer: QsaSideLayer) -> Result<()> { + let QsaSideLayer { q, rows, batched } = layer; + self.plan_launch(|p| p.qsa_index_k(q, rows, batched))?; + let base = &self.resources.base; + base.qsa.capture_tail_snapshot(&base.journal, self.capture, q)?; + base.qsa.capture_append_rows(&base.journal, self.capture, q, rows.begin..rows.end)?; + self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched))?; + self.plan_launch(|p| p.qsa_block_scores_topk(q, rows)) + } + /// The query projection and its q/gate split, norm and RoPE. + fn issue_query_chain(&mut self, layer: QsaSideLayer) -> Result<()> { + let QsaSideLayer { q, rows, batched } = layer; + self.plan_launch(|p| p.mmvq(qsa_layer(q), Projection::QsaQ, rows))?; + self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) + } +} diff --git a/crates/cuda-driver/src/original_verify_window_ops/side_shared_expert.rs b/crates/cuda-driver/src/original_verify_window_ops/side_shared_expert.rs new file mode 100644 index 00000000..018aba57 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_ops/side_shared_expert.rs @@ -0,0 +1,25 @@ +//! The shared expert on a side stream (upstream's shared-expert stream, forked once the doorbell is published). +//! +//! In the literal order the shared expert (convert, quantize, gate/up, SwiGLU, down, gate scalar, row scale) sits on +//! the capture stream between the doorbell and the routed experts, so their plan wait and VRAM experts start only +//! after it: the first routed expert starts 27.6 us after the doorbell, against 15.0 us in the vanilla graph. The +//! shared expert reads the layer's mixed activations and writes only its own scratch (`xq`, `sh_*`, `shared`); the +//! routed experts use `nat_xq` and their own buffers, and only the combine reads `shared`. So it forks from the +//! capture stream right after the doorbell and joins before the combine. The launches and their order are the +//! literal ones: the outputs are bitwise those of the in-line order, only the graph's dependency edges change. + +#[allow(unused_imports)] +use super::*; + +impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { + /// The shared expert runs on side stream 0 (not in a split window, as the other side branches). + pub(super) fn side_shared(&self) -> bool { + self.policy.side.shared_expert && self.groups == 1 && self.capture.has_side() + } + /// Fork the shared expert of `layer` off the capture stream. + pub(super) fn issue_shared_expert_side(&mut self, layer: usize, rows: Rows, dec_batch: bool) -> Result<()> { + self.capture.side_fork(0)?; + self.plan_launch(|p| p.shared_expert(layer, rows, dec_batch))?; + self.capture.side_end(0) + } +} diff --git a/crates/cuda-driver/src/original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs b/crates/cuda-driver/src/original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs index 41d96132..98cb5dcc 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs @@ -1,5 +1,7 @@ //! Moved out of the parent module by STRA-338: impl WindowOps_for_OriginalVerifyWindowOps. +#[allow(unused_imports)] +use super::side_qsa_branches::QsaSideLayer; #[allow(unused_imports)] use super::*; @@ -33,6 +35,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.plan_launch(|p| p.quantize_q8_1(source, rows)) } fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()> { + if self.side_qsa() && matches!(projection, Projection::QsaQ) { + return Ok(()); // issued on side stream 1 by `issue_qsa_side` + } if self.side_gdn() { match projection { // SIDE_MIXER: the gates and the gate projection of this GDN layer are issued here, beside the qkv @@ -78,12 +83,20 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { ) } fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + if self.side_qsa() { + // SIDE_MIXER, QSA part: the indexer chain and the query chain of this layer are issued here, beside the + // K/V projections + return self.issue_qsa_side(QsaSideLayer { q, rows, batched }); + } self.plan_launch(|p| p.qsa_index_k(q, rows, batched)) } fn qsa_k_norm_rope(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { self.plan_launch(|p| p.qsa_k_norm_rope(q, rows, batched)) } fn qsa_tail_snapshot(&mut self, layer: usize) -> Result<()> { + if self.side_qsa() { + return Ok(()); // issued on side stream 0 by `issue_qsa_side` + } let base = &self.resources.base; base.qsa.capture_tail_snapshot(&base.journal, self.capture, layer) } @@ -91,22 +104,40 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.plan_launch(|p| p.qsa_kv_append(q, rows)) } fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> { + if self.side_qsa() { + return Ok(()); // issued on side stream 0 by `issue_qsa_side` + } let base = &self.resources.base; base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin..rows.end) } fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + if self.side_qsa() { + return Ok(()); // issued on side stream 1 by `issue_qsa_side` + } self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) } fn qsa_index_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + if self.side_qsa() { + return Ok(()); // issued on side stream 0 by `issue_qsa_side` + } self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched)) } fn qsa_block_scores_topk(&mut self, q: usize, rows: Rows) -> Result<()> { + if self.side_qsa() { + return Ok(()); // issued on side stream 0 by `issue_qsa_side` + } self.plan_launch(|p| p.qsa_block_scores_topk(q, rows)) } fn qsa_kv_resolve(&mut self, q: usize, rows: Rows) -> Result<()> { + if self.side_qsa() { + self.capture.side_join(0)?; // the resolve reads the blocks the indexer chain selected + } self.plan_launch(|p| p.qsa_kv_resolve(q, rows)) } fn qsa_decode_attention(&mut self, q: usize, rows: Rows) -> Result<()> { + if self.side_qsa() { + self.capture.side_join(1)?; // the attention reads the query the query chain produced + } self.plan_launch(|p| p.qsa_decode_attention(q, rows)) } fn qsa_gate(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { @@ -119,6 +150,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.resources.base.journal.capture_doorbell(self.capture, rows.begin, rows.end) } fn shared_expert(&mut self, layer: usize, rows: Rows, dec_batch: bool) -> Result<()> { + if self.side_shared() { + return self.issue_shared_expert_side(layer, rows, dec_batch); + } self.plan_launch(|p| p.shared_expert(layer, rows, dec_batch)) } fn quantize_expert_input(&mut self, _layer: usize, rows: Rows) -> Result<()> { @@ -194,6 +228,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.plan_launch(|p| p.hit_add(rows)) } fn combine(&mut self, _layer: usize, rows: Rows, batched: bool) -> Result<()> { + if self.side_shared() { + self.capture.side_join(0)?; // the combine adds the shared expert's rows + } self.plan_launch(|p| p.combine(rows, batched)) } fn final_write(&mut self, rows: Rows) -> Result<()> { diff --git a/crates/cuda-driver/src/original_verify_window_plan.rs b/crates/cuda-driver/src/original_verify_window_plan.rs index 5f9ef9a6..d01af694 100644 --- a/crates/cuda-driver/src/original_verify_window_plan.rs +++ b/crates/cuda-driver/src/original_verify_window_plan.rs @@ -28,6 +28,11 @@ pub const fn qsa_index(layer: usize) -> Option { if is_qsa_layer(layer) { Some(layer / 4) } else { None } } +/// Layer index of QSA layer `q` among all layers (the inverse of `qsa_index`). +pub const fn qsa_layer(q: usize) -> usize { + q * 4 + 3 +} + /// Groups of a T-token window: split windows of at least two rows use two. pub const fn window_groups(t: usize, split: bool) -> usize { if split && t >= 2 { 2 } else { 1 } @@ -135,6 +140,7 @@ mod tests { assert_eq!(gdn, (0..36).collect::>(), "GDN indices are dense and ordered"); let q: Vec = (0..WINDOW_LAYERS).filter_map(qsa_index).collect(); assert_eq!(q, (0..12).collect::>()); + assert!((0..12).all(|i| qsa_index(qsa_layer(i)) == Some(i))); assert_eq!((gdn_index(4), gdn_index(3), qsa_index(3), qsa_index(4)), (Some(3), None, Some(0), None)); } diff --git a/crates/cuda-driver/src/original_verify_window_record.rs b/crates/cuda-driver/src/original_verify_window_record.rs index 38e9e013..a9f6e9f9 100644 --- a/crates/cuda-driver/src/original_verify_window_record.rs +++ b/crates/cuda-driver/src/original_verify_window_record.rs @@ -98,9 +98,8 @@ pub struct WindowPolicy { /// the layer's gate/up format has the fused kernel. Off in `mode17()`; `record_literal_window` resolves it from the /// card and `LELEKA_SM120_GU_SWIGLU`. pub gu_swiglu: bool, - /// sm_120 `SIDE_MIXER` (GDN part of upstream's `STRATA_SIDE_MIXER=2`): the GDN gates and gate projection on side - /// streams of the window's graph. - pub side_mixer: bool, + /// The parts of the graph that run on the side streams (`SIDE_MIXER` and the shared-expert fork). + pub side: super::sm120::SideBranches, } impl WindowPolicy { pub const fn mode17() -> Self { @@ -122,7 +121,7 @@ impl WindowPolicy { gr_variant: super::gr::GrVariant::Staged, qsa: super::qsa::OriginalVerifyQsaPolicy::mode17(), gu_swiglu: false, - side_mixer: false, + side: super::sm120::SideBranches::NONE, } } pub fn validate_selected(&self) -> Result<()> { diff --git a/crates/cuda-driver/src/original_verify_window_sm120.rs b/crates/cuda-driver/src/original_verify_window_sm120.rs index 481efe61..67a40806 100644 --- a/crates/cuda-driver/src/original_verify_window_sm120.rs +++ b/crates/cuda-driver/src/original_verify_window_sm120.rs @@ -76,12 +76,43 @@ pub(crate) fn gu_swiglu_entry(ty: u32) -> Option<&'static str> { pub(crate) const DEFAULT_ON_ATTN_DAILY: bool = false; pub(crate) const DEFAULT_ON_GU_SWIGLU: bool = false; pub(crate) const DEFAULT_ON_SIDE_MIXER: bool = false; +pub(crate) const DEFAULT_ON_SIDE_QSA: bool = false; +pub(crate) const DEFAULT_ON_SIDE_SHARED: bool = false; + +/// Which parts of the verify graph run on the two side streams: the GDN gates and gate projection, the QSA indexer and +/// query chains (upstream `STRATA_SIDE_MIXER=2`), and the shared expert beside the routed experts (upstream's shared +/// expert stream). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SideBranches { + pub gdn: bool, + pub qsa: bool, + pub shared_expert: bool, +} +impl SideBranches { + pub const NONE: Self = Self { gdn: false, qsa: false, shared_expert: false }; + /// Some part needs the side streams. + pub const fn any(self) -> bool { + self.gdn || self.qsa || self.shared_expert + } + /// The parts either side takes. + pub const fn union(self, other: Self) -> Self { + Self { + gdn: self.gdn || other.gdn, + qsa: self.qsa || other.qsa, + shared_expert: self.shared_expert || other.shared_expert, + } + } +} #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Sm120Switches { pub attn_daily: bool, pub gu_swiglu: bool, pub side_mixer: bool, + /// The QSA part of upstream's `STRATA_SIDE_MIXER=2`: the indexer chain and the query chain on side streams. + pub side_qsa: bool, + /// The shared expert on a side stream, beside the routed experts. + pub side_shared: bool, } fn one(get: &impl Fn(&str) -> Option, var: &str, default: bool) -> bool { @@ -117,18 +148,27 @@ impl Sm120Switches { // the kernels are sm_120 PTX (no sm_86 companion): a card below 12.x never takes a switch, whatever the // variable says let capable = major >= 12; + let switch = |variable: &str, default_on: bool| capable && one(&get, variable, sm120 && default_on); Self { - attn_daily: capable && one(&get, "LELEKA_SM120_ATTN_DAILY", sm120 && DEFAULT_ON_ATTN_DAILY), - gu_swiglu: capable && one(&get, "LELEKA_SM120_GU_SWIGLU", sm120 && DEFAULT_ON_GU_SWIGLU), - side_mixer: capable && one(&get, "LELEKA_SM120_SIDE_MIXER", sm120 && DEFAULT_ON_SIDE_MIXER), + attn_daily: switch("LELEKA_SM120_ATTN_DAILY", DEFAULT_ON_ATTN_DAILY), + gu_swiglu: switch("LELEKA_SM120_GU_SWIGLU", DEFAULT_ON_GU_SWIGLU), + side_mixer: switch("LELEKA_SM120_SIDE_MIXER", DEFAULT_ON_SIDE_MIXER), + side_qsa: switch("LELEKA_SM120_SIDE_QSA", DEFAULT_ON_SIDE_QSA), + side_shared: switch("LELEKA_SM120_SIDE_SHARED", DEFAULT_ON_SIDE_SHARED), } } + /// The side-stream parts these switches ask for. + pub const fn side_branches(self) -> SideBranches { + SideBranches { gdn: self.side_mixer, qsa: self.side_qsa, shared_expert: self.side_shared } + } pub fn from_env(major: i32, minor: i32) -> Self { let s = Self::resolve(major, minor, |k| std::env::var(k).ok()); Self { attn_daily: overridden(&OVERRIDE_ATTN_DAILY, s.attn_daily), gu_swiglu: overridden(&OVERRIDE_GU_SWIGLU, s.gu_swiglu), side_mixer: overridden(&OVERRIDE_SIDE_MIXER, s.side_mixer), + side_qsa: s.side_qsa, + side_shared: s.side_shared, } } } @@ -189,6 +229,26 @@ mod tests { assert!(!Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_PERF", "0")])).side_mixer); } + #[test] + fn side_qsa_follows_its_own_variable_and_the_master_switch() { + assert_eq!(Sm120Switches::resolve(12, 0, env(&[])).side_qsa, DEFAULT_ON_SIDE_QSA); + assert!(Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_SIDE_QSA", "1")])).side_qsa); + assert!(!Sm120Switches::resolve(8, 6, env(&[("LELEKA_SM120_SIDE_QSA", "1")])).side_qsa); + assert!(!Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_SIDE_QSA", "0")])).side_qsa); + } + + #[test] + fn side_shared_follows_its_own_variable_and_the_branches_union() { + assert!(Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_SIDE_SHARED", "1")])).side_shared); + assert!(!Sm120Switches::resolve(8, 6, env(&[("LELEKA_SM120_SIDE_SHARED", "1")])).side_shared); + const PAIR: [(&str, &str); 2] = [("LELEKA_SM120_SIDE_SHARED", "1"), ("LELEKA_SM120_SIDE_QSA", "1")]; + let both = Sm120Switches::resolve(12, 0, env(&PAIR)).side_branches(); + assert_eq!(both, SideBranches { gdn: false, qsa: true, shared_expert: true }); + assert!(both.any() && !SideBranches::NONE.any()); + let gdn = SideBranches { gdn: true, ..SideBranches::NONE }; + assert_eq!(both.union(gdn), SideBranches { gdn: true, qsa: true, shared_expert: true }); + } + #[test] fn the_gu_swiglu_asset_is_sealed_and_exports_every_entry() { GU_SWIGLU.assert_sealed_and_fail_closed(); diff --git a/crates/deploy/src/profile/tests/builtin_profiles.rs b/crates/deploy/src/profile/tests/builtin_profiles.rs index c8ceef44..91ca51e3 100644 --- a/crates/deploy/src/profile/tests/builtin_profiles.rs +++ b/crates/deploy/src/profile/tests/builtin_profiles.rs @@ -163,17 +163,6 @@ fn only_the_server_profile_enables_the_mtp_draft_attention_switch() { .engine_env .contains_key("LELEKA_SM120_ATTN_DAILY_MTP") ); - // lever 1 of the speed program: the main attention and the gate/up SwiGLU kernels of the same card, bitwise - // identical on the teacher-forced gate (docs/experiments/codex-compare-speed-gap.md), decode +1.85 % paired - for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx5090-32g-gguf-ple"] { - let profile = Profile::builtin(name).unwrap(); - for key in ["LELEKA_SM120_ATTN_DAILY", "LELEKA_SM120_GU_SWIGLU"] { - assert_eq!(profile.engine_env.get(key).map(String::as_str), Some("1"), "{name} {key}"); - } - } - for key in ["LELEKA_SM120_ATTN_DAILY", "LELEKA_SM120_GU_SWIGLU"] { - assert!(!laptop.engine_env.contains_key(key), "{key}"); - } // the key space of engine_env still refuses everything else let mut bad = server.clone(); bad.engine_env.insert("LELEKA_SM86_X".into(), "1".into()); @@ -184,6 +173,25 @@ fn only_the_server_profile_enables_the_mtp_draft_attention_switch() { ok.validate().unwrap(); } +#[test] +fn only_the_5090_profiles_enable_the_sm120_main_attention_and_swiglu_kernels() { + // lever 1 of the speed program: the main attention and the gate/up SwiGLU kernels of the same card, bitwise + // identical on the teacher-forced gate (docs/experiments/codex-compare-speed-gap.md), decode +1.85 % paired + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx5090-32g-gguf-ple"] { + let profile = Profile::builtin(name).unwrap(); + for key in SM120_MAIN_KERNEL_KEYS { + assert_eq!(profile.engine_env.get(key).map(String::as_str), Some("1"), "{name} {key}"); + } + } + for key in SM120_MAIN_KERNEL_KEYS { + assert!(!laptop.engine_env.contains_key(key), "{key}"); + } +} + +/// Engine switches of the compute capability 12 kernels that replace the main attention and the gate/up SwiGLU. +const SM120_MAIN_KERNEL_KEYS: [&str; 2] = ["LELEKA_SM120_ATTN_DAILY", "LELEKA_SM120_GU_SWIGLU"]; + #[test] fn validation_rejects_unsafe_values() { let mut profile = Profile::builtin("rtx5090-32g").unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs index ac68e11e..4062837f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs @@ -283,7 +283,7 @@ use split_group_pcie::adapt_decay; #[allow(unused_imports)] use split_group_pcie::adapt_tuning; #[allow(unused_imports)] -pub(in crate::qwen_forward) use split_group_pcie::choose_swaps; +pub(in crate::qwen_forward) use split_group_pcie::{choose_swaps, choose_swaps_by}; #[cfg(test)] #[allow(unused_imports)] use split_group_pcie::choose_swaps_reference; @@ -293,6 +293,8 @@ pub(in crate::qwen_forward) use split_group_pcie::pcie_locked_only; pub(in crate::qwen_forward) use split_group_pcie::split_group_pcie; #[allow(unused_imports)] pub(in crate::qwen_forward) use split_group_pcie::{PcieSplitPolicy, RoutedGroup}; +mod swap_tie_order; +pub(in crate::qwen_forward) use swap_tie_order::TieOrder; mod span_cache_and_pcie_lag; #[allow(unused_imports)] use span_cache_and_pcie_lag::span_cache_enabled; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs index 526d567b..2fef2a4b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs @@ -256,11 +256,21 @@ impl<'ctx> GpuExpertPool<'_, '_, 'ctx> { } } } + /// How equal-gain swaps compete for the cap: the port's low-layer-first order unless `LELEKA_ADAPT_TIE_SPREAD`. + fn tie_order(&self) -> TieOrder { + if crate::settings::process().memory.adapt_tie_spread { + TieOrder::SpreadLayers { round: self.state.stats.adaptations } + } else { + TieOrder::LowLayerFirst + } + } /// The adaptive swaps chosen from the usage counts and queued onto the cache. fn queue_swaps(&mut self) -> Result> { let cache = &*self.cache; let p = super::super::original_serve_profile::span("adapt.choose"); - let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps); + let ties = self.tie_order(); + let swaps = + choose_swaps_by(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), (self.adapt_swaps, ties)); drop(p); let p = super::super::original_serve_profile::span("adapt.queue"); for swap in &swaps { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs index ea3a3387..0d48bfb6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs @@ -241,6 +241,15 @@ pub(in crate::qwen_forward) fn choose_swaps( resident: impl Fn(usize, usize) -> bool, max_swaps: usize, ) -> Vec { + choose_swaps_by(usage, resident, (max_swaps, TieOrder::LowLayerFirst)) +} +/// `choose_swaps` with the order in which equal-gain swaps compete for the `max_swaps` cap (`cap`.1). +pub(in crate::qwen_forward) fn choose_swaps_by( + usage: &[f32], + resident: impl Fn(usize, usize) -> bool, + cap: (usize, TieOrder), +) -> Vec { + let (max_swaps, ties) = cap; let (min_count, margin, _) = adapt_tuning(); let mut swaps = Vec::new(); if usage.len() != LAYERS * EXPERTS { @@ -260,7 +269,7 @@ pub(in crate::qwen_forward) fn choose_swaps( trim_victims(&mut vict, cand.len()); push_pairs(&cand, &vict, margin, layer, &mut swaps); } - swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)); + ties.order(&mut swaps); swaps.truncate(max_swaps); swaps } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/swap_tie_order.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/swap_tie_order.rs new file mode 100644 index 00000000..e2ec8824 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/swap_tie_order.rs @@ -0,0 +1,77 @@ +//! The order in which equal-gain adaptive swaps compete for the per-round cap (`adapt_swaps`, 96). +//! +//! The Original sorts all layers' swaps by gain with an unstable `std::sort`, so a tie at the cap falls where the +//! sort leaves it. The port's stable sort over swaps pushed layer by layer gives every tie to the lowest layer: when +//! more than 96 swaps are worth making (a short request that moved the tier to another topic) the late layers never +//! get theirs. `SpreadLayers` is the experimental alternative (`LELEKA_ADAPT_TIE_SPREAD=on`). + +use super::{LAYERS, Swap}; + +/// How swaps of equal gain are ordered before the cap cuts the list. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) enum TieOrder { + /// Ascending layer, then ascending expert (the port's order since the first version). + LowLayerFirst, + /// Every layer's best swap before any layer's second one; inside one rank the layers start at `round % 48`, so + /// the layer that loses the cap changes from one adaptation round to the next. + SpreadLayers { round: u64 }, +} + +impl TieOrder { + /// Sort `swaps` (pushed in ascending layer order, best pair first inside a layer) by descending gain. + pub(super) fn order(self, swaps: &mut [Swap]) { + match self { + Self::LowLayerFirst => swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)), + Self::SpreadLayers { round } => spread_layers(swaps, round), + } + } +} + +fn spread_layers(swaps: &mut [Swap], round: u64) { + let mut seen = [0usize; LAYERS]; + let mut keyed: Vec<(usize, usize, Swap)> = swaps + .iter() + .map(|swap| { + let rank = seen[swap.layer]; + seen[swap.layer] += 1; + (rank, (swap.layer + (round % LAYERS as u64) as usize) % LAYERS, *swap) + }) + .collect(); + keyed.sort_by(|a, b| b.2.gain.total_cmp(&a.2.gain).then(a.0.cmp(&b.0)).then(a.1.cmp(&b.1))); + for (slot, (_, _, swap)) in swaps.iter_mut().zip(keyed) { + *slot = swap; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn swap(layer: usize, incoming: usize, gain: f32) -> Swap { + Swap { gain, layer, incoming, outgoing: 0 } + } + + #[test] + fn equal_gains_go_to_the_low_layers_unless_the_layers_are_spread() { + // layers 0 and 1 have three equal-gain swaps each, layer 40 one: a cap of three + let swaps = [swap(0, 1, 2.0), swap(0, 2, 2.0), swap(0, 3, 2.0), swap(1, 1, 2.0), swap(40, 1, 2.0)]; + let mut low = swaps; + TieOrder::LowLayerFirst.order(&mut low); + assert_eq!(low.iter().take(3).map(|s| s.layer).collect::>(), [0, 0, 0]); + let mut spread = swaps; + TieOrder::SpreadLayers { round: 0 }.order(&mut spread); + assert_eq!(spread.iter().take(3).map(|s| s.layer).collect::>(), [0, 1, 40]); + } + + #[test] + fn gain_still_decides_before_the_spread_and_the_start_layer_rotates() { + let swaps = [swap(0, 1, 2.0), swap(0, 2, 9.0), swap(5, 1, 2.0), swap(9, 1, 2.0)]; + let mut first = swaps; + TieOrder::SpreadLayers { round: 0 }.order(&mut first); + assert_eq!((first[0].layer, first[0].incoming), (0, 2), "gain 9 first"); + assert_eq!(first[1].layer, 0, "rank 0 of layer 0 before the rank 1 of anything"); + let mut later = swaps; + TieOrder::SpreadLayers { round: 44 }.order(&mut later); + assert_eq!(later[2].layer, 9, "round 44 starts the rotation at layer 4, so layer 5 then 9"); + } +} diff --git a/crates/engine-qwen35-cuda/src/settings/memory.rs b/crates/engine-qwen35-cuda/src/settings/memory.rs index dcfa7c1d..2c6c3853 100644 --- a/crates/engine-qwen35-cuda/src/settings/memory.rs +++ b/crates/engine-qwen35-cuda/src/settings/memory.rs @@ -27,6 +27,9 @@ pub(crate) struct MemorySettings { pub(crate) adapt_min_count: f32, /// `LELEKA_ADAPT_MARGIN`: finite `f32`, 1.5 otherwise. pub(crate) adapt_margin: f32, + /// `LELEKA_ADAPT_TIE_SPREAD` is `on` or `1` (EXPERIMENTAL, off by default): equal-gain adaptive swaps share the + /// per-round cap across the layers instead of going to the lowest layer first. + pub(crate) adapt_tie_spread: bool, /// `LELEKA_ADAPT_DECAY`, as set: the range check and its log line stay with the tier that logs them. pub(crate) adapt_decay: Option, /// `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING`: the file the routing is dumped to. @@ -72,6 +75,7 @@ impl MemorySettings { pcie_auto_on: equals(env, "LELEKA_PCIE_AUTO", "on"), adapt_min_count: tuning("LELEKA_ADAPT_MIN_COUNT", 2.0), adapt_margin: tuning("LELEKA_ADAPT_MARGIN", 1.5), + adapt_tie_spread: one_of(env, "LELEKA_ADAPT_TIE_SPREAD", &["on", "1"]), adapt_decay: env.get("LELEKA_ADAPT_DECAY"), dump_routing: env.get_os("LELEKA_ORIGINAL_SERVE_DUMP_ROUTING"), per_layer_sized: on_unless_zero(env, "LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED"), diff --git a/crates/engine-qwen35-cuda/src/settings/memory_tests.rs b/crates/engine-qwen35-cuda/src/settings/memory_tests.rs index 5796a001..cfe74d0c 100644 --- a/crates/engine-qwen35-cuda/src/settings/memory_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/memory_tests.rs @@ -25,6 +25,7 @@ fn refill_defer_and_locked_only_are_on_or_one() { let spellings = [("on", true), ("1", true), ("off", false), ("0", false), ("yes", false), ("", false)]; rows("LELEKA_REFILL_DEFER", |m| m.refill_defer, false, &spellings); rows("LELEKA_PCIE_LOCKED_ONLY", |m| m.pcie_locked_only, false, &spellings); + rows("LELEKA_ADAPT_TIE_SPREAD", |m| m.adapt_tie_spread, false, &spellings); } #[test] diff --git a/docs/experiments/codex-compare-speed-gap.md b/docs/experiments/codex-compare-speed-gap.md index d890fd37..f777b21b 100644 --- a/docs/experiments/codex-compare-speed-gap.md +++ b/docs/experiments/codex-compare-speed-gap.md @@ -1,209 +1,209 @@ -# Codex compare: why Leleka decodes slower than vanilla Strata, and the ranked levers (RTX 5090, 2026-11-07) - -Branch `claude/speed-vs-strata-08143a`. Phase 1 = analysis of existing logs, **no new GPU run, no performance claim**. Phase 2 (measurements) is in section 6 once it has data. -Sources (server `/data/leleka-e2e/`): `codex-compare/runs/main/{LEL,VAN,VANL}/stack-r{1,2,3}/engine.log` (LEL: JSON `request` events of the engine; VAN/VANL: `strata serve: prompt ... generated ... drafts accepted a of b` lines), -`spd-gap/runs/main/{A,B,E,K*,KA*,KS*,P,T*,VANLP,VANL-noprof}` (replay of the recorded VANL `nestng-crm-r2` prompts), `docs/ledger.md`, `docs/roofline.md`, `docs/experiments/codex-compare-5090-results.md` (branch `claude/codex-compare`). -Arms: LEL = release package `leleka-0.1.0-17e372944279`, VANL = vanilla 0.2.6 with route tail skip and CPU prefill share off (reference), VAN = vanilla shipped defaults (both on). -Analysis scripts are not kept in Git (run over ssh from stdin; formulas below). - -## 1. Where the time goes (all requests with prompt > 200 tokens of the 9 `stack` logs per arm, ttt + nestng-crm together) - -Rounds of vanilla are estimated as `generated - drafts accepted` (one bonus token per window); LEL logs `rounds` itself. - -| metric | LEL | VANL (reference) | VAN | LEL vs VANL | -| --- | ---: | ---: | ---: | ---: | -| requests (3 stacks) | 531 | 246 | 271 | | -| decode tok/s (sum output / sum decode ms) | 177.5 | 217 | 238 | **-18 %** | -| tokens per round | 3.22-3.34 | 2.92-3.00 | 2.91-3.02 | **+12 %** (adaptive window) | -| ms per round | 18.1-18.8 | 13.5-13.9 | 12.3-12.5 | **+36 %** | -| prefill tok/s over uncached tokens | 930-1050 | 1460-1560 | 1320-1660 | -35 % | -| prefill share of request time | 9.5 % | 7.1 % | 7.3 % | +2.4 points | -| request time per output token, prefill + decode (ms) | 0.59 + 5.63 = 6.22 | 0.36 + 4.61 = 4.97 | 0.33 + 4.20 = 4.53 | gap 1.25 ms: **decode 82 %, prefill 18 %** | - -Reading: Leleka gets more tokens per round than vanilla (+12 %), but a round costs +5 ms. With vanilla's round time Leleka would be ~10 % *faster* than VANL. The whole gap is the time per round, plus a smaller prefill share. - -Prefill latency by size of the uncached part (median ms): the fixed cost per request is about +200-300 ms, and large reads are 2x slower. - -| uncached tokens | LEL | VANL | VAN | share of LEL requests | -| --- | ---: | ---: | ---: | ---: | -| < 64 | 430 | 268 | 210 | 19 % | -| 64-256 | 530 | 292 | 251 | 31 % | -| 256-1024 | 722 | 435 | 397 | 35 % | -| 1024-4096 | 1002 | 715 | 695 | 11 % | -| >= 4096 | 4405 | 2184 | 2044 | 4 % (19 % of LEL prefill time) | - -## 2. Same prompts replayed (spd-gap; `nestng-crm-r2` of VANL, first 30 requests, requests are identical across variants; dec_tps = output tokens / decode ms) - -| variant | what | dec tok/s | tok/round | ms/round | VRAM / PCIe / CPU % of routed | -| --- | --- | ---: | ---: | ---: | --- | -| VANL (vanilla, lossless) | `--spec 4 --spec-min-p 0.5` | **208.3** (2 runs equal) | 2.95 | 14.2 | hit 92.8 / 2.0 / 5.2 | -| A | ours shipped (adaptive window, floor 0) | 183.8 | 3.55 | 19.3 | 90.2 / 3.0 / 6.7 | -| B | ours with vanilla's window (fixed 4, floor 0.5) | 178.8 | 2.90 | 16.2 | 90.8 / 2.7 / 6.6 | -| E | A + our lossy tail skip | 206.7 | 3.58 | 17.3 | 93.7 / 1.7 / 4.6 | -| T45 | E, repeat | 205.8 | 3.59 | 17.4 | 94.0 / 1.6 / 4.4 | -| KAa | E + sm_120 `ATTN_DAILY` + `GU_SWIGLU` | 209.7 | 3.51 | 16.7 | 93.6 / 1.7 / 4.7 | - -Over requests 4-30 only (whole runs of 27 requests, n = 1-4 per variant, not a paired design): T45 family 207.8 / 210.1 / 213.3 / 209.0 (mean 210.1), K (all three sm_120 sets) 214.0 / 215.8 / 218.3 (216.0), KA 212.0 / 217.6 (214.8), KS (side mixer only) 208.3 / 210.5 (209.4), T30/T35/T40 (PCIe fraction) 204.0 / 206.8 / 207.2. -So: `ATTN_DAILY + GU_SWIGLU` ~ +2.3 %; the side mixer adds nothing; the PCIe fraction 0.45 is not worse than 0.30-0.40. Run-to-run spread inside one variant is +-1.5 %: these are indications, not A/B results. - -Step profile (`P` = ours with `LELEKA_SERVE_PROFILE=1`, vanilla `STRATA_DECODE_TIMING=1`; ms per window, GDN layers + QSA layers, 30 profile lines each): - -| step (ms/window) | ours, miss-heavy (lines 1, 2, 7, 8, 26) | vanilla, miss-heavy (lines 8, 9, 12, 22, 27) | ours, quiet (16, 17) | vanilla, quiet (17, 18) | -| --- | ---: | ---: | ---: | ---: | -| total per window | 21-26 | 16-17 | 12.0 | 10.7 | -| waitB (GDN + QSA) | 4.3-5.9 | 3.9-4.6 | 0.45 | 0.5 | -| **waitCPU (GDN + QSA)** | **3.1-4.0** | **0.4-1.3** | **0.8** | **0.2** | -| **PCIe group** | **0.6-0.9** | **0.3** | **0.4** | **0.1** | -| VRAM hits | 1.7-2.8 | 1.4-1.9 | 1.5 | 1.4 | - -The windows differ by 5-9 ms only in states with misses, and almost all of it is `waitCPU` + `PCIe group` (+2.5 ms of 21 in a miss-heavy window, +0.6 ms in a quiet one) and a hit rate that is lower in ours (90.2 % against 92.8 % of the routed experts). -Cache size: ours 12,192 expert slots (23.24 GiB), vanilla 12,575 (23.87 GiB, +3.1 %), vanilla leaves 389 MiB VRAM free (and warns); vanilla draft head over 106,299 tokens (212.9 MiB), ours the full 248,320-row head (ledger section 5). -Draft + commit outside the window: ours about 2.5 ms/round (`draft.finish` 1.7, `apply_pending` 0.6, commit 0.4), vanilla 1.2 (`draft` 1.17 in its timing line); ledger section 5 measured +1.5 ms/round. -The vanilla server drifts with uptime: 13.5-16 ms/round at 11-13 h, 10.1-11.7 after a fresh boot (`codex-lossy-delta.md`); every A/B must alternate inside one boot. - -## 3. Ranked levers - -Gain = estimated change of end-to-end tok/s on the Codex workload (contexts 30-120k), **E** = estimate from the numbers above, not measured as an A/B. Lossy = changes output; "placement-class" = changes which experts run on the GPU (GPU and CPU round differently), so output differs slightly without being a bug. - -| # | lever | expected gain | risk | class | evidence | -| --- | --- | ---: | --- | --- | --- | -| 1 | sm_120 sets `ATTN_DAILY` + `GU_SWIGLU` default on (the vanilla 0.1.50 defaults) | +2-3 % (E from KA vs T45: 214.8 vs 210.1) | low | non-lossy: byte-identical in the probe and 243-row replay | section 2 | -| 2 | Remove the CPU/PCIe wait of the miss leg (`waitCPU` + `PCIe group`: why is the CPU-expert result late: pool wake/hand-off, per-layer dispatch, split rule with `pcie_frac`, CPU kernel speed per expert) | +4-10 % (E: 1.0-3.1 ms of 19 ms/round; the quiet-state excess is already 0.6 ms) | medium (host threading) | non-lossy if the numerics of each expert stay (same device decides the rounding) | step profile | -| 3 | Fewer misses: slots 12,192 -> 12,575 (headroom policy), adaptive tier timing, draft-head VRAM | +2-6 % (E: miss rate 9.8 % -> 7.2 % removes up to a quarter of the miss leg) | medium: VRAM headroom (vanilla warns at 389 MiB), OOM/paging risk | placement-class (quality gate against control placement) | slots, hit rates | -| 4 | Per-round draft + commit overhead (merge small graphs, fewer launches, cheaper chain step: 0.68 vs 0.42 ms, `mtp_original_finite` guards) | +3-6 % (E: -1.3 ms of 19) | medium | non-lossy, bitwise (same kernels; draft vocabulary subset is a separate sub-lever, ledger: prompt-dependent -4 %..+19 %) | ledger 5, profile | -| 5 | Prefill fixed latency per request (+200-300 ms per small tail; vanilla reads <= 64 tokens through verify windows) and 2x slower large reads | +2-3 % (E: prefill share 9.5 % -> 7.1 %) | medium | tail through windows is a different kernel path: placement-class numerics; faster large chunks are bitwise | section 1 | -| 6 | Adaptive window policy: A vs B is +2.8 % net (+0.65 tokens per round for +3.1 ms); tune floor / ceiling (variants C, D of `spd_replay_job` never ran) | +1-3 % (E) | low | non-lossy (exact speculative decoding) | section 2 | -| 7 | Route tail skip (lossy): E vs A +12.5 % (206.7 vs 183.8), vanilla VAN vs VANL +9.7 % real | +10-12 %, shrinks lever 2 and 3 | quality: rounds growth unknown (codex-compare rounds CV 20-30 %) | **lossy, experimental, stays off** until the owner gate | section 2 | -| 8 | CPU prefill share (vanilla default, KL ~0.004) | ~0 (VAN prefill share 7.3 % vs VANL 7.1 %) | | lossy | section 1 - do not pursue | - -Total of the non-lossy levers 1, 2, 4, 5, 6 if additive: about +12-25 %; the gap to VANL is +22 % (217 / 177.5), to VAN +34 %. Lever 3 and 7 are the way past parity with vanilla's shipped defaults. -The levers interact: tail skip removes most of the miss leg, so lever 2 and 3 are measured with tail skip off (the default). - -## 4. Gates, per lever (AGENTS.md; nothing changes a default before its gate) - -| lever | A/B | quality / identity gate | -| --- | --- | --- | -| 1 | switch on/off, same boot | byte-identical outputs and R hashes on a **full** replay of a Codex session (all 56 requests of `nestng-crm-r2`, plus the earlier 243-row replay); then default on | -| 2 | switch on/off | per-step output identical on a frozen tier (`--adapt-every 0` and a frozen placement, because the adaptive tier is not reproducible run to run); a distribution comparison of the adaptive runs | -| 3 | slots / headroom / profile variants | placement-class gate: deviation against the control placement not worse than between two control placements (>= 1000 rows), zero OOM/paging in the 256k run, VRAM free >= the policy floor | -| 4 | switch on/off | greedy output and tensor identity (the kernels are the same); chain graph timing in the model-free probe first | -| 5 | switch on/off, tails of 1-64 / 64-256 tokens | R hash identity for the unchanged path; the window-tail path under the placement-class gate | -| 6 | variants of floor/ceiling on the same replay | identical greedy output (speculation is exact); tokens/round and ms/round reported | -| 7 | E against A on the replay + real Codex sessions | the **owner criterion**: rounds growth <= speed gain in %, game playable, CRM 56/56; stays experimental until it passes | - -## 5. Measurement protocol for phase 2 - -* Workload: the recorded VANL `nestng-crm-r2` requests (`proxy/rounds/NNNN.fwd.json.gz`) through `scripts/e2e/codex/compare/spd_replay_job.sh` (server copy `spd-gap/tools/spd_replay_job7.sh`), whole cell (56 requests); requests 1-3 are warm-up and dropped. -* Design: blocks of `leleka up` per variant, order A B B A A B ..., **n >= 10 blocks per variant** in one boot (uptime drift above), GPU lock and holder queue as for all jobs; the metric per block: dec tok/s, tok/round, ms/round, end-to-end tok/s (`otok / (pf + dec)`), tier %; paired difference per adjacent block pair with a 95 % CI. -* Record per run: GPU, driver, CUDA, host, model digest (`8f59b4aa...` profile, model files), binary sha256 and commit, the switches, cache state (prefix cache and expert tier start state: engine restarted per block, prefix cache empty at start), token counts and the distributions (per-request dec tok/s). -* Binary: lever 1 is a pure switch (`LELEKA_SM120_ATTN_DAILY`, `LELEKA_SM120_GU_SWIGLU`), so its paired A/B runs the same codex-compare release package on and off (sha256 in the job log); the default flip itself is a commit on the hexagonal head `e4993d151` and needs one confirmation block pair on that head. Levers that change code (2, 4, 5) are measured as head build against head build with the same switch off. -* Tools (this branch, `scripts/e2e/codex/speed/`): `spd_ab_job.sh` (holder job; variant names `NAME.BLOCK`, new variant `L`), `replay_hash.py` (adds `out_sha` per request), `ab_report.py RUN_DIR BASE VAR` (paired differences with 95 % t intervals and the identity count). Copies live in `/data/leleka-e2e/spd-gap/tools/`. - -## 6. Phase 2 results - -Not run yet: the GPU queue holds the hexagonal identity/A-B jobs (`hx-abg1` running, `hx-abc3..5`, `hx-id6`, `hx-abd1..5` behind it, ~30 min each) ahead of this program. -Queued at the end of `PRIORITY` (2026-11-07 18:30 UTC): `spd-l1a` (blocks 1-5) and `spd-l1b` (blocks 6-10) = lever 1, A (shipped lossless) against L (A + `ATTN_DAILY` + `GU_SWIGLU`), 10 blocks per arm, 30 requests of the recorded cell per block, ~12 min per block. -Read the result with `python3 -I - RUN_DIR A L < scripts/e2e/codex/speed/ab_report.py` on `/data/leleka-e2e/spd-gap/runs/ab-l1`. Smoke test of the report on three old block pairs (tail skip on, no hashes): L +1.9 % decode tok/s, CI -2.1..+6.0 % (n = 3, which is why n >= 10). -Entries are added below, one per lever, as each paired A/B finishes. - -### Lever 1, interim (blocks 1-5 of 10, `spd-l1a`; `spd-l1b` was running, so no final numbers yet) - -| metric | A | L | L - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 187.10 | 190.05 | +1.6 % (-0.3..+3.4 %) | -| end-to-end tok/s | 170.18 | 169.67 | -0.3 % (-3.2..+2.6 %) | -| ms/round | 19.60 | 19.21 | -2.0 % (-6.6..+2.6 %) | - -n = 5 pairs: not significant, gain below the +2-3 % of the estimate. **Identity gate cannot use two boots**: `out_sha` is equal for only 2 of 30 requests even between two runs of the *same* arm (A.1 vs A.2, A.2 vs A.3; L.1 vs L.2: 3 of 30), because the adaptive tier / placement is not reproducible run to run (as `codex-lossy-delta.md` noted). So the byte-identity of lever 1 must be shown on a frozen placement (`--adapt-every 0`, static tier, one boot, switch toggled per request or two boots with the same frozen tier), not by this A/B; the A/B above is the speed record only. -Queue order (orchestrator request 2026-11-07): `hx-abg2..5` (cumulative refactor A/B) are on top of `PRIORITY`; the running `spd-l1b` was left to finish. - - -### Lever 1, final speed result (10 pairs, `spd-l1a` + `spd-l1b`, 2026-11-08) - -Release package `leleka-0.1.0-17e372944279-5090`, RTX 5090, VANL `nestng-crm-r2`, 30 requests per block (27 after the 3-request warm-up skip), engine restarted per block, order alternated, only the switch differs. - -| metric | A (shipped lossless) | L (+ ATTN_DAILY + GU_SWIGLU) | L - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 186.58 | 190.03 | **+1.85 % (+0.97..+2.73 %)** | -| end-to-end tok/s | 168.87 | 170.07 | +0.71 % (-1.01..+2.44 %) | -| tokens/round | 3.66 | 3.63 | -0.66 % (-3.13..+1.82 %) | -| ms/round | 19.61 | 19.13 | -2.46 % (-4.47..-0.46 %) | -| VRAM % of routed | 90.37 | 90.34 | -0.03 % (-0.27..+0.21 %) | - -Decode gain is real and small (+1.85 %, CI excludes zero), inside the +2-3 % estimate's lower end; it does not reach the end-to-end number (prefill is untouched; CI crosses zero). The cross-boot `out_sha` identity is 22 of 300 and is **not** the gate (A against A is as low, adaptive tier and window). Default stays off until the frozen-placement gate passes: `spd-l1id` (variants `FA`/`FL` = tier swaps off + fixed window 4, with and without the two sets; `FA.1` vs `FA.2` is the A/A floor, then `FA.n` vs `FL.n` must be byte-identical), output `/data/leleka-e2e/spd-gap/runs/id-l1`, queued on top of `PRIORITY`. - -### Lever 1, identity gate: HTTP replay cannot decide, teacher-forced harness used (2026-11-08) - -`spd-l1id` (release package, `leleka up`, tier swaps off, fixed window 4, 30 requests, 4 boots FA.1 FL.1 FA.2 FL.2): `out_sha` equal for 10/30 (FA.1 vs FA.2), 10/30 (FL.1 vs FL.2), 11/30 (FA.1 vs FL.1), 9/30 (FA.2 vs FL.2). The A/A floor is as low as the A-vs-L pairs, so the live HTTP replay is not a deterministic probe even on a frozen tier and window (the remaining sources are not isolated: host-thread timing of the CPU/PCIe split, the persisted prefix-cache state between boots; the frozen tier also runs at 63 % VRAM hits, ~104 tok/s, so these four boots say nothing about speed). The gate is therefore the repository's teacher-forced harness (`scripts/e2e/decode/draftround-id.sh`, the 256k-class capture `night5-long-256k`, top-16 logprob rows, A/A floor inside each process): `spd-l1id2`, P1 = release kernels, P2 = P1 + `ATTN_DAILY` + `GU_SWIGLU`, test binary `rt-dr2`, output `/data/leleka-e2e/spd-gap/runs/id-l1-tf`. - -### Lever 1, verdict: default ON for the 5090 profiles (2026-11-08) - -`spd-l1id2` (teacher-forced, `rt-dr2`, five requests of `night5-long-256k` up to 243k prompt, 240 forced tokens each, `ADAPT=4`): reference process A/A floor 2057 of 2057 top-16 rows identical; P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference, both arms: 2057 of 2057 identical, 0 argmax flips; draft trace 1036 of 1036 lines identical (**IDENTICAL**); `q_tail_gate` PASS in both processes. So the two sets are bitwise identical to the shipped kernels on this gate and the paired decode gain is +1.85 % (CI +0.97..+2.73 %), end-to-end +0.71 % (not significant). Caveats: the gate binary `rt-dr2` (draft-round `28d74a2ef`) is older than the release package `17e372944279`, and the live HTTP replay cannot serve as an identity probe (floor 10/30). The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) now set `LELEKA_SM120_ATTN_DAILY=1` and `LELEKA_SM120_GU_SWIGLU=1`; the laptop profile (sm_86) does not; an operator's `engine_env` still wins. Rollback: set both to `0` in `engine_env`. - -Confirmation on the product tree (2026-11-08, jobs `spd-l1id4-c9`, `spd-l1id4-main`): the same teacher-forced gate on the hexagonal test binaries `rt-c9` (refactored product tree) and `rt-main` (its base). Both: A/A floor 2057 of 2057 top-16 rows identical, P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference 2057 of 2057 in both arms, 0 argmax flips, draft trace 1036 of 1036 identical, `q_tail_gate` PASS. The release package itself cannot run the replay smoke (it is a lib test), and a test binary of exactly `17e372944279` does not exist on the server (not built: 41 GiB free on `/data`); the kernels are the same PTX. The server copy of `draftround-id.sh` hardcodes the binary directory, so these two jobs use the repository version (`D` override) installed as `spd-gap/tools/draftround-id.sh`. The decision to keep the sets on stands; the paired A/B of the release package (10 pairs above) is the switch these profiles now set, so no further A/B was run. - -### Levers 2 and 4: what the existing evidence says before any code (2026-11-08, no GPU run) - -* Vanilla and ours run the same CPU leg shape: 15 workers on logical processors 1-15, host on 0 (vanilla engine.log, ours `cpu_workers=15`), `LELEKA_POOL_TASKS_PER_THREAD` 2/4/6 within +-2 us per expert (`docs/experiments/cpu-service2-5090.md`), PCIe fraction 0.30-0.40 not better than 0.45 (section 2 above). -* The step-profile columns are not comparable one to one: vanilla books the CPU wait inside `waitB` (GDN layers waitB 4.87, waitCPU 0.22, PCIe group 0.36 = 5.45 ms/window) where ours splits it (waitB 3.74, waitCPU 2.36, PCIe group 0.57 = 6.67 ms/window). The wait group of the GDN layers is ~1.2 ms/window longer in ours, the QSA layers ~0.2 ms/window shorter in ours: a net ~1.0 ms of ~19 ms/window (~5 %), and it moves with the miss count (hit rate 90.2 % against 92.8 %, 12,192 against 12,575 slots), so lever 2 and lever 3 are one effect until a per-miss cost is measured. -* The fused verifier commit graph (`LELEKA_DRAFT_FUSED_COMMIT=on`, bitwise, `docs/experiments/draft-round-5090.md`) measured -0.024 +- 0.046 ms per round: neutral, not worth an A/B here. -* Consequence: a code change for lever 2 needs a per-miss timing (CPU compute against late start) from an instrumented build before it is worth an A/B; the cheap config knobs are already flat. Not started; the next measured lever is 7 (tail skip, experimental, lossy): `spd-l7a`/`spd-l7b` queued, 10 paired blocks A against E, speed and rounds growth only (the owner gate also needs real Codex sessions and CRM 56/56), output `/data/leleka-e2e/spd-gap/runs/ab-l7`. - -### Lever 7 (route tail skip, EXPERIMENTAL, lossy), interim: blocks 1-5 of 10 (`spd-l7a`; `spd-l7b` running), 2026-11-08 - -Release package `17e372944279`, same replay as lever 1, A (shipped) against E (`LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100`), 27 requests per block after warm-up, order alternated. - -| metric | A | E | E - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 185.84 | 210.30 | **+13.16 % (+11.80..+14.53 %)** | -| end-to-end tok/s | 168.49 | 186.95 | +10.95 % (+8.47..+13.44 %) | -| tokens/round | 3.59 | 3.79 | +5.45 % (+0.07..+10.83 %) | -| ms/round | 19.31 | 18.00 | -6.81 % (-10.67..-2.96 %) | -| VRAM % of routed | 90.42 | 93.89 | +3.48 % (+3.09..+4.59 %) | - -The gain is large and the CI is far from zero; rounds per token did not grow in this replay (tokens/round +5.5 %), but the replay sends recorded prompts, so the replies differ from E's own (the task trajectory is not followed) and this says nothing about the owner criterion on real sessions. The output is not identical (lossy by definition). **Stays off by default.** The owner gate (rounds growth <= speed gain in %, game playable, CRM 56/56) runs on real Codex sessions: `spd-g1..3` (the codex-compare ours arm with the two tail-skip variables exported, tasks `ttt` + `nestng-crm`, repetitions 1-3, output `/data/leleka-e2e/spd-gap/runs/codex-tail`), queued behind `spd-l7b`; compare with the shipped `LEL` and `VANL` runs of `codex-compare/runs/main`. - -### Lever 7, final speed result (10 pairs, `spd-l7a` + `spd-l7b`, 2026-11-08) - -Same replay and arms as the interim table (27 requests per block after warm-up, 10 block pairs, order alternated): decode tok/s A 186.40, E 209.81, **+12.56 % (95 % CI +11.50..+13.62 %)**; end-to-end +11.00 % (+9.75..+12.25 %); tokens/round 3.65 against 3.77 (+3.30 %, CI -0.21..+6.80 %, includes zero); ms/round 19.57 against 17.96 (-8.24 %, -10.71..-5.77 %); VRAM share of routed 90.32 -> 93.76 %. `out_sha` identical in 4 of 300 requests: it is a lossy mode, and the HTTP replay floor is about 10 of 30 anyway, so this number decides nothing. - -### Lever 7, owner gate on real Codex sessions (jobs `spd-g1..3`, 2026-11-08) - the table below used the OLD accept.py, see the correction after it - -Release package `17e372944279`, `LELEKA_ROUTE_TAIL_SKIP=7`, `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100`, real Codex CLI 0.163.0, temperature 0, three repetitions of `ttt` and `nestng-crm`, run by `cmp_codex_job.sh` on the 5090 (`/data/leleka-e2e/spd-gap/runs/codex-tail`, report `_compare/compare.md`). Baseline is the shipped LEL of `codex-compare/runs/main` (same tools, same Codex, same tasks). - -| task | arm | accepted | rounds (mean +- sd) | wall s | decode tok/s | -| --- | --- | --- | --- | ---: | ---: | -| nestng-crm | LEL shipped | 3/3 (56/56 each) | 54.0 +- 7.5 | 488.4 | 163.1 | -| nestng-crm | LEL + tail skip | **0/3 (55/56, 55/56, 54/56)** | 55.0 +- 17.4 | 468.3 | 183.2 | -| ttt | LEL shipped | 3/3 (14/14) | 17.7 (15, 22, 16) | 177.9 | 164.3 | -| ttt | LEL + tail skip | 3/3 (14/14) | 18.0 +- 7.0 | 155.5 | 184.6 | - -* Speed: decode tok/s +12.3 % (crm) and +12.4 % (ttt); the engine's own per-round view over the CRM requests is 17.4 ms/round against 19.4 (-10 %) at an equal 3.47 tokens/round. -* Rounds: CRM +1.9 % and ttt +1.7 % (both far inside the sd): the growth of rounds is below the speed gain (+12 %) in both tasks (greedy sessions are not reproducible run to run, n = 3). -* Game: `ttt` accepted 3/3. -* **CRM 56/56 is not met in any of the three runs.** The failing check is `frontend src: a board with one column per stage (all five stages and a loop)` in r1, r2 and r3 (`no file with all five stages and a loop`), plus one backend e2e test in r3 (`deals.e2e-spec.ts`, passed=41 failed=1). All nine baseline sessions (LEL, VAN, VANL, three each) passed 56/56. Three of three against zero of nine is not noise at this size; the lossy skip changes what the model writes on this task, and the gate in AGENTS.md ("do not enable lossy optimizations by default until their separate quality gate passes") is not passed. - -Verdict: the route tail skip stays **experimental and off by default**; no default or profile was changed for it. The logit gate (`q_tail_gate`, teacher-forced `night5-long-256k`, `rt-c10`) is queued as `spd-l7id` for the record; it cannot overturn the CRM failure above. - -### Lever 2 (waitCPU / PCIe), decision after re-reading `cpu-service2-5090.md` (2026-11-08, no new GPU run) - -The CPU leg already costs what vanilla's costs per expert: the server bench of the dispatch gives 41-51 us per CPU expert (15 workers, 54-57 GB/s of expert bytes, near this host's DRAM bandwidth) and vanilla's PcieAuto line reports 44 us; the host-callback stages are 0.06-1.08 ms/round each and already trimmed (eager admission +4.24 %, AVX2 `q8_k`); pool tasks per thread, PCIe share 0.45-0.65 and the fused commit graph are flat or neutral. What remains of the `waitCPU` + `PCIe group` excess (about 1 ms of ~19 ms per window) scales with the number of misses per window, i.e. it is lever 3 (hit rate 90.2 % against 92.8 %), not a separate host-side defect. A per-miss instrumented build would only re-split a quantity that the miss count already explains, so none is built. Lever 2 is closed with **no change**; the remaining miss-leg work moves to lever 3 (placement-class gate) and, lossy, lever 7. - -Queued next: lever 6 (`spd-l6a`, `spd-l6b`: D = adaptive window at floor 0.5 against shipped A, 10 block pairs, exact speculative decoding) and the lever 7 logit gate `spd-l7id`. - -#### Correction: the `spd-g1..3` cells were accepted by the pre-fix `accept.py` (2026-11-08) - -`cmp_codex_job.sh` ran the frozen `codex-compare/tasks/nestng-crm/accept.py` (sha256 `db1b7095...`), whose check "a board with one column per stage" needs the five stages and the loop in ONE file and failed in all nine baseline cells too (`codex-compare-5090-results.md`, Deviations 4); the baseline 56/56 come from the fixed `reaccept-1/tasks/nestng-crm/accept.py` (sha256 `b2e6c690...`). The 0/3 above therefore compared unlike checkers. Re-accepted offline with the fixed script (copy at `/data/leleka-e2e/spd-gap/runs/codex-tail-reaccept/accept-task`, logs `r1.log r2.log r3.log`, original cell logs untouched): - -| cell | fixed accept.py | detail | -| --- | --- | --- | -| nestng-crm r1 | **56/56** | board: `@for (stage of stages ...)` in `deals.component.html` | -| nestng-crm r2 | **56/56** | board: `@for (stage of stages ...)` in `deals-page.html` | -| nestng-crm r3 | 55/56 (reproduced 3 of 3 runs) | `backend tests: npm run test:e2e passes`: 41 of 42 pass | - -* The board is present in all three (a column per stage over the five stages, read in the sources), so the static failure was the checker artifact, not a model defect. -* r3: the failing test is the agent's OWN `deals.e2e-spec.ts:176` ("searches deals by title ... combines with stage"): it expects one deal for `?stage=won&q=software`, but its own fixture creates two won deals with "software" in the title ("Alpha software" and "Beta software"), so the API correctly returns two. Deterministic (3 of 3 reruns), a wrong assertion written by the model, not environment noise, and not a defect of the service. It still fails the acceptance rule "the agent's tests pass". The baselines have 0 such cases in 9 sessions; 1 in 3 with tail skip is a small-n signal, not proof (an own-test slip of this kind can occur without tail skip, and greedy sessions are not reproducible). -* Gate re-assessed: rounds growth below the speed gain (yes, +1.9 % / +1.7 % against +12 %); game playable (ttt 3/3, 14/14); CRM 56/56: **2 of 3** (r3 55/56 through its own wrong test). Not passed in full; with n = 3 per arm I do not call it a quality regression either. Tail skip stays experimental and off. To settle it, run 3 more repetitions of `nestng-crm` with the fixed `accept.py` (and the first three re-run under it); needs the owner's go on the cost (about 8 GPU-min each). +# Codex compare: why Leleka decodes slower than vanilla Strata, and the ranked levers (RTX 5090, 2026-11-07) + +Branch `claude/speed-vs-strata-08143a`. Phase 1 = analysis of existing logs, **no new GPU run, no performance claim**. Phase 2 (measurements) is in section 6 once it has data. +Sources (server `/data/leleka-e2e/`): `codex-compare/runs/main/{LEL,VAN,VANL}/stack-r{1,2,3}/engine.log` (LEL: JSON `request` events of the engine; VAN/VANL: `strata serve: prompt ... generated ... drafts accepted a of b` lines), +`spd-gap/runs/main/{A,B,E,K*,KA*,KS*,P,T*,VANLP,VANL-noprof}` (replay of the recorded VANL `nestng-crm-r2` prompts), `docs/ledger.md`, `docs/roofline.md`, `docs/experiments/codex-compare-5090-results.md` (branch `claude/codex-compare`). +Arms: LEL = release package `leleka-0.1.0-17e372944279`, VANL = vanilla 0.2.6 with route tail skip and CPU prefill share off (reference), VAN = vanilla shipped defaults (both on). +Analysis scripts are not kept in Git (run over ssh from stdin; formulas below). + +## 1. Where the time goes (all requests with prompt > 200 tokens of the 9 `stack` logs per arm, ttt + nestng-crm together) + +Rounds of vanilla are estimated as `generated - drafts accepted` (one bonus token per window); LEL logs `rounds` itself. + +| metric | LEL | VANL (reference) | VAN | LEL vs VANL | +| --- | ---: | ---: | ---: | ---: | +| requests (3 stacks) | 531 | 246 | 271 | | +| decode tok/s (sum output / sum decode ms) | 177.5 | 217 | 238 | **-18 %** | +| tokens per round | 3.22-3.34 | 2.92-3.00 | 2.91-3.02 | **+12 %** (adaptive window) | +| ms per round | 18.1-18.8 | 13.5-13.9 | 12.3-12.5 | **+36 %** | +| prefill tok/s over uncached tokens | 930-1050 | 1460-1560 | 1320-1660 | -35 % | +| prefill share of request time | 9.5 % | 7.1 % | 7.3 % | +2.4 points | +| request time per output token, prefill + decode (ms) | 0.59 + 5.63 = 6.22 | 0.36 + 4.61 = 4.97 | 0.33 + 4.20 = 4.53 | gap 1.25 ms: **decode 82 %, prefill 18 %** | + +Reading: Leleka gets more tokens per round than vanilla (+12 %), but a round costs +5 ms. With vanilla's round time Leleka would be ~10 % *faster* than VANL. The whole gap is the time per round, plus a smaller prefill share. + +Prefill latency by size of the uncached part (median ms): the fixed cost per request is about +200-300 ms, and large reads are 2x slower. + +| uncached tokens | LEL | VANL | VAN | share of LEL requests | +| --- | ---: | ---: | ---: | ---: | +| < 64 | 430 | 268 | 210 | 19 % | +| 64-256 | 530 | 292 | 251 | 31 % | +| 256-1024 | 722 | 435 | 397 | 35 % | +| 1024-4096 | 1002 | 715 | 695 | 11 % | +| >= 4096 | 4405 | 2184 | 2044 | 4 % (19 % of LEL prefill time) | + +## 2. Same prompts replayed (spd-gap; `nestng-crm-r2` of VANL, first 30 requests, requests are identical across variants; dec_tps = output tokens / decode ms) + +| variant | what | dec tok/s | tok/round | ms/round | VRAM / PCIe / CPU % of routed | +| --- | --- | ---: | ---: | ---: | --- | +| VANL (vanilla, lossless) | `--spec 4 --spec-min-p 0.5` | **208.3** (2 runs equal) | 2.95 | 14.2 | hit 92.8 / 2.0 / 5.2 | +| A | ours shipped (adaptive window, floor 0) | 183.8 | 3.55 | 19.3 | 90.2 / 3.0 / 6.7 | +| B | ours with vanilla's window (fixed 4, floor 0.5) | 178.8 | 2.90 | 16.2 | 90.8 / 2.7 / 6.6 | +| E | A + our lossy tail skip | 206.7 | 3.58 | 17.3 | 93.7 / 1.7 / 4.6 | +| T45 | E, repeat | 205.8 | 3.59 | 17.4 | 94.0 / 1.6 / 4.4 | +| KAa | E + sm_120 `ATTN_DAILY` + `GU_SWIGLU` | 209.7 | 3.51 | 16.7 | 93.6 / 1.7 / 4.7 | + +Over requests 4-30 only (whole runs of 27 requests, n = 1-4 per variant, not a paired design): T45 family 207.8 / 210.1 / 213.3 / 209.0 (mean 210.1), K (all three sm_120 sets) 214.0 / 215.8 / 218.3 (216.0), KA 212.0 / 217.6 (214.8), KS (side mixer only) 208.3 / 210.5 (209.4), T30/T35/T40 (PCIe fraction) 204.0 / 206.8 / 207.2. +So: `ATTN_DAILY + GU_SWIGLU` ~ +2.3 %; the side mixer adds nothing; the PCIe fraction 0.45 is not worse than 0.30-0.40. Run-to-run spread inside one variant is +-1.5 %: these are indications, not A/B results. + +Step profile (`P` = ours with `LELEKA_SERVE_PROFILE=1`, vanilla `STRATA_DECODE_TIMING=1`; ms per window, GDN layers + QSA layers, 30 profile lines each): + +| step (ms/window) | ours, miss-heavy (lines 1, 2, 7, 8, 26) | vanilla, miss-heavy (lines 8, 9, 12, 22, 27) | ours, quiet (16, 17) | vanilla, quiet (17, 18) | +| --- | ---: | ---: | ---: | ---: | +| total per window | 21-26 | 16-17 | 12.0 | 10.7 | +| waitB (GDN + QSA) | 4.3-5.9 | 3.9-4.6 | 0.45 | 0.5 | +| **waitCPU (GDN + QSA)** | **3.1-4.0** | **0.4-1.3** | **0.8** | **0.2** | +| **PCIe group** | **0.6-0.9** | **0.3** | **0.4** | **0.1** | +| VRAM hits | 1.7-2.8 | 1.4-1.9 | 1.5 | 1.4 | + +The windows differ by 5-9 ms only in states with misses, and almost all of it is `waitCPU` + `PCIe group` (+2.5 ms of 21 in a miss-heavy window, +0.6 ms in a quiet one) and a hit rate that is lower in ours (90.2 % against 92.8 % of the routed experts). +Cache size: ours 12,192 expert slots (23.24 GiB), vanilla 12,575 (23.87 GiB, +3.1 %), vanilla leaves 389 MiB VRAM free (and warns); vanilla draft head over 106,299 tokens (212.9 MiB), ours the full 248,320-row head (ledger section 5). +Draft + commit outside the window: ours about 2.5 ms/round (`draft.finish` 1.7, `apply_pending` 0.6, commit 0.4), vanilla 1.2 (`draft` 1.17 in its timing line); ledger section 5 measured +1.5 ms/round. +The vanilla server drifts with uptime: 13.5-16 ms/round at 11-13 h, 10.1-11.7 after a fresh boot (`codex-lossy-delta.md`); every A/B must alternate inside one boot. + +## 3. Ranked levers + +Gain = estimated change of end-to-end tok/s on the Codex workload (contexts 30-120k), **E** = estimate from the numbers above, not measured as an A/B. Lossy = changes output; "placement-class" = changes which experts run on the GPU (GPU and CPU round differently), so output differs slightly without being a bug. + +| # | lever | expected gain | risk | class | evidence | +| --- | --- | ---: | --- | --- | --- | +| 1 | sm_120 sets `ATTN_DAILY` + `GU_SWIGLU` default on (the vanilla 0.1.50 defaults) | +2-3 % (E from KA vs T45: 214.8 vs 210.1) | low | non-lossy: byte-identical in the probe and 243-row replay | section 2 | +| 2 | Remove the CPU/PCIe wait of the miss leg (`waitCPU` + `PCIe group`: why is the CPU-expert result late: pool wake/hand-off, per-layer dispatch, split rule with `pcie_frac`, CPU kernel speed per expert) | +4-10 % (E: 1.0-3.1 ms of 19 ms/round; the quiet-state excess is already 0.6 ms) | medium (host threading) | non-lossy if the numerics of each expert stay (same device decides the rounding) | step profile | +| 3 | Fewer misses: slots 12,192 -> 12,575 (headroom policy), adaptive tier timing, draft-head VRAM | +2-6 % (E: miss rate 9.8 % -> 7.2 % removes up to a quarter of the miss leg) | medium: VRAM headroom (vanilla warns at 389 MiB), OOM/paging risk | placement-class (quality gate against control placement) | slots, hit rates | +| 4 | Per-round draft + commit overhead (merge small graphs, fewer launches, cheaper chain step: 0.68 vs 0.42 ms, `mtp_original_finite` guards) | +3-6 % (E: -1.3 ms of 19) | medium | non-lossy, bitwise (same kernels; draft vocabulary subset is a separate sub-lever, ledger: prompt-dependent -4 %..+19 %) | ledger 5, profile | +| 5 | Prefill fixed latency per request (+200-300 ms per small tail; vanilla reads <= 64 tokens through verify windows) and 2x slower large reads | +2-3 % (E: prefill share 9.5 % -> 7.1 %) | medium | tail through windows is a different kernel path: placement-class numerics; faster large chunks are bitwise | section 1 | +| 6 | Adaptive window policy: A vs B is +2.8 % net (+0.65 tokens per round for +3.1 ms); tune floor / ceiling (variants C, D of `spd_replay_job` never ran) | +1-3 % (E) | low | non-lossy (exact speculative decoding) | section 2 | +| 7 | Route tail skip (lossy): E vs A +12.5 % (206.7 vs 183.8), vanilla VAN vs VANL +9.7 % real | +10-12 %, shrinks lever 2 and 3 | quality: rounds growth unknown (codex-compare rounds CV 20-30 %) | **lossy, experimental, stays off** until the owner gate | section 2 | +| 8 | CPU prefill share (vanilla default, KL ~0.004) | ~0 (VAN prefill share 7.3 % vs VANL 7.1 %) | | lossy | section 1 - do not pursue | + +Total of the non-lossy levers 1, 2, 4, 5, 6 if additive: about +12-25 %; the gap to VANL is +22 % (217 / 177.5), to VAN +34 %. Lever 3 and 7 are the way past parity with vanilla's shipped defaults. +The levers interact: tail skip removes most of the miss leg, so lever 2 and 3 are measured with tail skip off (the default). + +## 4. Gates, per lever (AGENTS.md; nothing changes a default before its gate) + +| lever | A/B | quality / identity gate | +| --- | --- | --- | +| 1 | switch on/off, same boot | byte-identical outputs and R hashes on a **full** replay of a Codex session (all 56 requests of `nestng-crm-r2`, plus the earlier 243-row replay); then default on | +| 2 | switch on/off | per-step output identical on a frozen tier (`--adapt-every 0` and a frozen placement, because the adaptive tier is not reproducible run to run); a distribution comparison of the adaptive runs | +| 3 | slots / headroom / profile variants | placement-class gate: deviation against the control placement not worse than between two control placements (>= 1000 rows), zero OOM/paging in the 256k run, VRAM free >= the policy floor | +| 4 | switch on/off | greedy output and tensor identity (the kernels are the same); chain graph timing in the model-free probe first | +| 5 | switch on/off, tails of 1-64 / 64-256 tokens | R hash identity for the unchanged path; the window-tail path under the placement-class gate | +| 6 | variants of floor/ceiling on the same replay | identical greedy output (speculation is exact); tokens/round and ms/round reported | +| 7 | E against A on the replay + real Codex sessions | the **owner criterion**: rounds growth <= speed gain in %, game playable, CRM 56/56; stays experimental until it passes | + +## 5. Measurement protocol for phase 2 + +* Workload: the recorded VANL `nestng-crm-r2` requests (`proxy/rounds/NNNN.fwd.json.gz`) through `scripts/e2e/codex/compare/spd_replay_job.sh` (server copy `spd-gap/tools/spd_replay_job7.sh`), whole cell (56 requests); requests 1-3 are warm-up and dropped. +* Design: blocks of `leleka up` per variant, order A B B A A B ..., **n >= 10 blocks per variant** in one boot (uptime drift above), GPU lock and holder queue as for all jobs; the metric per block: dec tok/s, tok/round, ms/round, end-to-end tok/s (`otok / (pf + dec)`), tier %; paired difference per adjacent block pair with a 95 % CI. +* Record per run: GPU, driver, CUDA, host, model digest (`8f59b4aa...` profile, model files), binary sha256 and commit, the switches, cache state (prefix cache and expert tier start state: engine restarted per block, prefix cache empty at start), token counts and the distributions (per-request dec tok/s). +* Binary: lever 1 is a pure switch (`LELEKA_SM120_ATTN_DAILY`, `LELEKA_SM120_GU_SWIGLU`), so its paired A/B runs the same codex-compare release package on and off (sha256 in the job log); the default flip itself is a commit on the hexagonal head `e4993d151` and needs one confirmation block pair on that head. Levers that change code (2, 4, 5) are measured as head build against head build with the same switch off. +* Tools (this branch, `scripts/e2e/codex/speed/`): `spd_ab_job.sh` (holder job; variant names `NAME.BLOCK`, new variant `L`), `replay_hash.py` (adds `out_sha` per request), `ab_report.py RUN_DIR BASE VAR` (paired differences with 95 % t intervals and the identity count). Copies live in `/data/leleka-e2e/spd-gap/tools/`. + +## 6. Phase 2 results + +Not run yet: the GPU queue holds the hexagonal identity/A-B jobs (`hx-abg1` running, `hx-abc3..5`, `hx-id6`, `hx-abd1..5` behind it, ~30 min each) ahead of this program. +Queued at the end of `PRIORITY` (2026-11-07 18:30 UTC): `spd-l1a` (blocks 1-5) and `spd-l1b` (blocks 6-10) = lever 1, A (shipped lossless) against L (A + `ATTN_DAILY` + `GU_SWIGLU`), 10 blocks per arm, 30 requests of the recorded cell per block, ~12 min per block. +Read the result with `python3 -I - RUN_DIR A L < scripts/e2e/codex/speed/ab_report.py` on `/data/leleka-e2e/spd-gap/runs/ab-l1`. Smoke test of the report on three old block pairs (tail skip on, no hashes): L +1.9 % decode tok/s, CI -2.1..+6.0 % (n = 3, which is why n >= 10). +Entries are added below, one per lever, as each paired A/B finishes. + +### Lever 1, interim (blocks 1-5 of 10, `spd-l1a`; `spd-l1b` was running, so no final numbers yet) + +| metric | A | L | L - A (95 % CI) | +| --- | ---: | ---: | --- | +| decode tok/s | 187.10 | 190.05 | +1.6 % (-0.3..+3.4 %) | +| end-to-end tok/s | 170.18 | 169.67 | -0.3 % (-3.2..+2.6 %) | +| ms/round | 19.60 | 19.21 | -2.0 % (-6.6..+2.6 %) | + +n = 5 pairs: not significant, gain below the +2-3 % of the estimate. **Identity gate cannot use two boots**: `out_sha` is equal for only 2 of 30 requests even between two runs of the *same* arm (A.1 vs A.2, A.2 vs A.3; L.1 vs L.2: 3 of 30), because the adaptive tier / placement is not reproducible run to run (as `codex-lossy-delta.md` noted). So the byte-identity of lever 1 must be shown on a frozen placement (`--adapt-every 0`, static tier, one boot, switch toggled per request or two boots with the same frozen tier), not by this A/B; the A/B above is the speed record only. +Queue order (orchestrator request 2026-11-07): `hx-abg2..5` (cumulative refactor A/B) are on top of `PRIORITY`; the running `spd-l1b` was left to finish. + + +### Lever 1, final speed result (10 pairs, `spd-l1a` + `spd-l1b`, 2026-11-08) + +Release package `leleka-0.1.0-17e372944279-5090`, RTX 5090, VANL `nestng-crm-r2`, 30 requests per block (27 after the 3-request warm-up skip), engine restarted per block, order alternated, only the switch differs. + +| metric | A (shipped lossless) | L (+ ATTN_DAILY + GU_SWIGLU) | L - A (95 % CI) | +| --- | ---: | ---: | --- | +| decode tok/s | 186.58 | 190.03 | **+1.85 % (+0.97..+2.73 %)** | +| end-to-end tok/s | 168.87 | 170.07 | +0.71 % (-1.01..+2.44 %) | +| tokens/round | 3.66 | 3.63 | -0.66 % (-3.13..+1.82 %) | +| ms/round | 19.61 | 19.13 | -2.46 % (-4.47..-0.46 %) | +| VRAM % of routed | 90.37 | 90.34 | -0.03 % (-0.27..+0.21 %) | + +Decode gain is real and small (+1.85 %, CI excludes zero), inside the +2-3 % estimate's lower end; it does not reach the end-to-end number (prefill is untouched; CI crosses zero). The cross-boot `out_sha` identity is 22 of 300 and is **not** the gate (A against A is as low, adaptive tier and window). Default stays off until the frozen-placement gate passes: `spd-l1id` (variants `FA`/`FL` = tier swaps off + fixed window 4, with and without the two sets; `FA.1` vs `FA.2` is the A/A floor, then `FA.n` vs `FL.n` must be byte-identical), output `/data/leleka-e2e/spd-gap/runs/id-l1`, queued on top of `PRIORITY`. + +### Lever 1, identity gate: HTTP replay cannot decide, teacher-forced harness used (2026-11-08) + +`spd-l1id` (release package, `leleka up`, tier swaps off, fixed window 4, 30 requests, 4 boots FA.1 FL.1 FA.2 FL.2): `out_sha` equal for 10/30 (FA.1 vs FA.2), 10/30 (FL.1 vs FL.2), 11/30 (FA.1 vs FL.1), 9/30 (FA.2 vs FL.2). The A/A floor is as low as the A-vs-L pairs, so the live HTTP replay is not a deterministic probe even on a frozen tier and window (the remaining sources are not isolated: host-thread timing of the CPU/PCIe split, the persisted prefix-cache state between boots; the frozen tier also runs at 63 % VRAM hits, ~104 tok/s, so these four boots say nothing about speed). The gate is therefore the repository's teacher-forced harness (`scripts/e2e/decode/draftround-id.sh`, the 256k-class capture `night5-long-256k`, top-16 logprob rows, A/A floor inside each process): `spd-l1id2`, P1 = release kernels, P2 = P1 + `ATTN_DAILY` + `GU_SWIGLU`, test binary `rt-dr2`, output `/data/leleka-e2e/spd-gap/runs/id-l1-tf`. + +### Lever 1, verdict: default ON for the 5090 profiles (2026-11-08) + +`spd-l1id2` (teacher-forced, `rt-dr2`, five requests of `night5-long-256k` up to 243k prompt, 240 forced tokens each, `ADAPT=4`): reference process A/A floor 2057 of 2057 top-16 rows identical; P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference, both arms: 2057 of 2057 identical, 0 argmax flips; draft trace 1036 of 1036 lines identical (**IDENTICAL**); `q_tail_gate` PASS in both processes. So the two sets are bitwise identical to the shipped kernels on this gate and the paired decode gain is +1.85 % (CI +0.97..+2.73 %), end-to-end +0.71 % (not significant). Caveats: the gate binary `rt-dr2` (draft-round `28d74a2ef`) is older than the release package `17e372944279`, and the live HTTP replay cannot serve as an identity probe (floor 10/30). The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) now set `LELEKA_SM120_ATTN_DAILY=1` and `LELEKA_SM120_GU_SWIGLU=1`; the laptop profile (sm_86) does not; an operator's `engine_env` still wins. Rollback: set both to `0` in `engine_env`. + +Confirmation on the product tree (2026-11-08, jobs `spd-l1id4-c9`, `spd-l1id4-main`): the same teacher-forced gate on the hexagonal test binaries `rt-c9` (refactored product tree) and `rt-main` (its base). Both: A/A floor 2057 of 2057 top-16 rows identical, P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference 2057 of 2057 in both arms, 0 argmax flips, draft trace 1036 of 1036 identical, `q_tail_gate` PASS. The release package itself cannot run the replay smoke (it is a lib test), and a test binary of exactly `17e372944279` does not exist on the server (not built: 41 GiB free on `/data`); the kernels are the same PTX. The server copy of `draftround-id.sh` hardcodes the binary directory, so these two jobs use the repository version (`D` override) installed as `spd-gap/tools/draftround-id.sh`. The decision to keep the sets on stands; the paired A/B of the release package (10 pairs above) is the switch these profiles now set, so no further A/B was run. + +### Levers 2 and 4: what the existing evidence says before any code (2026-11-08, no GPU run) + +* Vanilla and ours run the same CPU leg shape: 15 workers on logical processors 1-15, host on 0 (vanilla engine.log, ours `cpu_workers=15`), `LELEKA_POOL_TASKS_PER_THREAD` 2/4/6 within +-2 us per expert (`docs/experiments/cpu-service2-5090.md`), PCIe fraction 0.30-0.40 not better than 0.45 (section 2 above). +* The step-profile columns are not comparable one to one: vanilla books the CPU wait inside `waitB` (GDN layers waitB 4.87, waitCPU 0.22, PCIe group 0.36 = 5.45 ms/window) where ours splits it (waitB 3.74, waitCPU 2.36, PCIe group 0.57 = 6.67 ms/window). The wait group of the GDN layers is ~1.2 ms/window longer in ours, the QSA layers ~0.2 ms/window shorter in ours: a net ~1.0 ms of ~19 ms/window (~5 %), and it moves with the miss count (hit rate 90.2 % against 92.8 %, 12,192 against 12,575 slots), so lever 2 and lever 3 are one effect until a per-miss cost is measured. +* The fused verifier commit graph (`LELEKA_DRAFT_FUSED_COMMIT=on`, bitwise, `docs/experiments/draft-round-5090.md`) measured -0.024 +- 0.046 ms per round: neutral, not worth an A/B here. +* Consequence: a code change for lever 2 needs a per-miss timing (CPU compute against late start) from an instrumented build before it is worth an A/B; the cheap config knobs are already flat. Not started; the next measured lever is 7 (tail skip, experimental, lossy): `spd-l7a`/`spd-l7b` queued, 10 paired blocks A against E, speed and rounds growth only (the owner gate also needs real Codex sessions and CRM 56/56), output `/data/leleka-e2e/spd-gap/runs/ab-l7`. + +### Lever 7 (route tail skip, EXPERIMENTAL, lossy), interim: blocks 1-5 of 10 (`spd-l7a`; `spd-l7b` running), 2026-11-08 + +Release package `17e372944279`, same replay as lever 1, A (shipped) against E (`LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100`), 27 requests per block after warm-up, order alternated. + +| metric | A | E | E - A (95 % CI) | +| --- | ---: | ---: | --- | +| decode tok/s | 185.84 | 210.30 | **+13.16 % (+11.80..+14.53 %)** | +| end-to-end tok/s | 168.49 | 186.95 | +10.95 % (+8.47..+13.44 %) | +| tokens/round | 3.59 | 3.79 | +5.45 % (+0.07..+10.83 %) | +| ms/round | 19.31 | 18.00 | -6.81 % (-10.67..-2.96 %) | +| VRAM % of routed | 90.42 | 93.89 | +3.48 % (+3.09..+4.59 %) | + +The gain is large and the CI is far from zero; rounds per token did not grow in this replay (tokens/round +5.5 %), but the replay sends recorded prompts, so the replies differ from E's own (the task trajectory is not followed) and this says nothing about the owner criterion on real sessions. The output is not identical (lossy by definition). **Stays off by default.** The owner gate (rounds growth <= speed gain in %, game playable, CRM 56/56) runs on real Codex sessions: `spd-g1..3` (the codex-compare ours arm with the two tail-skip variables exported, tasks `ttt` + `nestng-crm`, repetitions 1-3, output `/data/leleka-e2e/spd-gap/runs/codex-tail`), queued behind `spd-l7b`; compare with the shipped `LEL` and `VANL` runs of `codex-compare/runs/main`. + +### Lever 7, final speed result (10 pairs, `spd-l7a` + `spd-l7b`, 2026-11-08) + +Same replay and arms as the interim table (27 requests per block after warm-up, 10 block pairs, order alternated): decode tok/s A 186.40, E 209.81, **+12.56 % (95 % CI +11.50..+13.62 %)**; end-to-end +11.00 % (+9.75..+12.25 %); tokens/round 3.65 against 3.77 (+3.30 %, CI -0.21..+6.80 %, includes zero); ms/round 19.57 against 17.96 (-8.24 %, -10.71..-5.77 %); VRAM share of routed 90.32 -> 93.76 %. `out_sha` identical in 4 of 300 requests: it is a lossy mode, and the HTTP replay floor is about 10 of 30 anyway, so this number decides nothing. + +### Lever 7, owner gate on real Codex sessions (jobs `spd-g1..3`, 2026-11-08) - the table below used the OLD accept.py, see the correction after it + +Release package `17e372944279`, `LELEKA_ROUTE_TAIL_SKIP=7`, `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100`, real Codex CLI 0.163.0, temperature 0, three repetitions of `ttt` and `nestng-crm`, run by `cmp_codex_job.sh` on the 5090 (`/data/leleka-e2e/spd-gap/runs/codex-tail`, report `_compare/compare.md`). Baseline is the shipped LEL of `codex-compare/runs/main` (same tools, same Codex, same tasks). + +| task | arm | accepted | rounds (mean +- sd) | wall s | decode tok/s | +| --- | --- | --- | --- | ---: | ---: | +| nestng-crm | LEL shipped | 3/3 (56/56 each) | 54.0 +- 7.5 | 488.4 | 163.1 | +| nestng-crm | LEL + tail skip | **0/3 (55/56, 55/56, 54/56)** | 55.0 +- 17.4 | 468.3 | 183.2 | +| ttt | LEL shipped | 3/3 (14/14) | 17.7 (15, 22, 16) | 177.9 | 164.3 | +| ttt | LEL + tail skip | 3/3 (14/14) | 18.0 +- 7.0 | 155.5 | 184.6 | + +* Speed: decode tok/s +12.3 % (crm) and +12.4 % (ttt); the engine's own per-round view over the CRM requests is 17.4 ms/round against 19.4 (-10 %) at an equal 3.47 tokens/round. +* Rounds: CRM +1.9 % and ttt +1.7 % (both far inside the sd): the growth of rounds is below the speed gain (+12 %) in both tasks (greedy sessions are not reproducible run to run, n = 3). +* Game: `ttt` accepted 3/3. +* **CRM 56/56 is not met in any of the three runs.** The failing check is `frontend src: a board with one column per stage (all five stages and a loop)` in r1, r2 and r3 (`no file with all five stages and a loop`), plus one backend e2e test in r3 (`deals.e2e-spec.ts`, passed=41 failed=1). All nine baseline sessions (LEL, VAN, VANL, three each) passed 56/56. Three of three against zero of nine is not noise at this size; the lossy skip changes what the model writes on this task, and the gate in AGENTS.md ("do not enable lossy optimizations by default until their separate quality gate passes") is not passed. + +Verdict: the route tail skip stays **experimental and off by default**; no default or profile was changed for it. The logit gate (`q_tail_gate`, teacher-forced `night5-long-256k`, `rt-c10`) is queued as `spd-l7id` for the record; it cannot overturn the CRM failure above. + +### Lever 2 (waitCPU / PCIe), decision after re-reading `cpu-service2-5090.md` (2026-11-08, no new GPU run) + +The CPU leg already costs what vanilla's costs per expert: the server bench of the dispatch gives 41-51 us per CPU expert (15 workers, 54-57 GB/s of expert bytes, near this host's DRAM bandwidth) and vanilla's PcieAuto line reports 44 us; the host-callback stages are 0.06-1.08 ms/round each and already trimmed (eager admission +4.24 %, AVX2 `q8_k`); pool tasks per thread, PCIe share 0.45-0.65 and the fused commit graph are flat or neutral. What remains of the `waitCPU` + `PCIe group` excess (about 1 ms of ~19 ms per window) scales with the number of misses per window, i.e. it is lever 3 (hit rate 90.2 % against 92.8 %), not a separate host-side defect. A per-miss instrumented build would only re-split a quantity that the miss count already explains, so none is built. Lever 2 is closed with **no change**; the remaining miss-leg work moves to lever 3 (placement-class gate) and, lossy, lever 7. + +Queued next: lever 6 (`spd-l6a`, `spd-l6b`: D = adaptive window at floor 0.5 against shipped A, 10 block pairs, exact speculative decoding) and the lever 7 logit gate `spd-l7id`. + +#### Correction: the `spd-g1..3` cells were accepted by the pre-fix `accept.py` (2026-11-08) + +`cmp_codex_job.sh` ran the frozen `codex-compare/tasks/nestng-crm/accept.py` (sha256 `db1b7095...`), whose check "a board with one column per stage" needs the five stages and the loop in ONE file and failed in all nine baseline cells too (`codex-compare-5090-results.md`, Deviations 4); the baseline 56/56 come from the fixed `reaccept-1/tasks/nestng-crm/accept.py` (sha256 `b2e6c690...`). The 0/3 above therefore compared unlike checkers. Re-accepted offline with the fixed script (copy at `/data/leleka-e2e/spd-gap/runs/codex-tail-reaccept/accept-task`, logs `r1.log r2.log r3.log`, original cell logs untouched): + +| cell | fixed accept.py | detail | +| --- | --- | --- | +| nestng-crm r1 | **56/56** | board: `@for (stage of stages ...)` in `deals.component.html` | +| nestng-crm r2 | **56/56** | board: `@for (stage of stages ...)` in `deals-page.html` | +| nestng-crm r3 | 55/56 (reproduced 3 of 3 runs) | `backend tests: npm run test:e2e passes`: 41 of 42 pass | + +* The board is present in all three (a column per stage over the five stages, read in the sources), so the static failure was the checker artifact, not a model defect. +* r3: the failing test is the agent's OWN `deals.e2e-spec.ts:176` ("searches deals by title ... combines with stage"): it expects one deal for `?stage=won&q=software`, but its own fixture creates two won deals with "software" in the title ("Alpha software" and "Beta software"), so the API correctly returns two. Deterministic (3 of 3 reruns), a wrong assertion written by the model, not environment noise, and not a defect of the service. It still fails the acceptance rule "the agent's tests pass". The baselines have 0 such cases in 9 sessions; 1 in 3 with tail skip is a small-n signal, not proof (an own-test slip of this kind can occur without tail skip, and greedy sessions are not reproducible). +* Gate re-assessed: rounds growth below the speed gain (yes, +1.9 % / +1.7 % against +12 %); game playable (ttt 3/3, 14/14); CRM 56/56: **2 of 3** (r3 55/56 through its own wrong test). Not passed in full; with n = 3 per arm I do not call it a quality regression either. Tail skip stays experimental and off. To settle it, run 3 more repetitions of `nestng-crm` with the fixed `accept.py` (and the first three re-run under it); needs the owner's go on the cost (about 8 GPU-min each). ### Lever 7, owner gate on n = 7 CRM and 5 ttt (`spd-g1..3` re-accepted + `spd-g4..g9`, fixed `accept.py` b2e6c690, 2026-11-08): NOT passed on rounds @@ -232,3 +232,161 @@ D (adaptive window with `spec_min_p` floor 0.5, `leleka reconfigure`) against sh ### Lever 3 (fewer misses), plan (2026-11-08) `docs/experiments/vram-footprint-5090.md` already holds the footprint work (dense slab default on; decode reserve 130 MiB and the prompt-embedding alias are opt-in, about +250 slots together, against vanilla's 12,575; our 12,192 now). Free VRAM at idle after load is about 1,040 MiB. The paired test queued here (`spd-l3a`, `spd-l3b`, variant `G` = `leleka up --gpu-budget-gib 31`, +0.43 GiB, about +190 slots, free VRAM after load about 600 MiB against vanilla's 389) measures the upper bound of what ~+200 slots are worth without any code change. If the gain is under 1 % the slot route is closed except for the larger prompt-buffer carve-out (+250..450 slots, needs code). + +### Where the real-session gap goes, per request (existing cells only, no new run; `scripts/e2e/codex/speed/session_split.py`, 2026-11-08) + +Source: `codex-compare/runs/main/{LEL,VANL,VAN}/{nestng-crm,ttt}-r1..3`. Proxy time per request (`proxy/rounds.jsonl`, `t_end - t_start`) joined by order with the engine's own prefill and decode milliseconds (the cell's `engine_log_start_offset` slice of the stack `engine.log`; join checked: request counts equal in all 6 cells per arm, 3 per task). Proxy "tok/s" = output tokens / proxy time = the `decode tok/s` of `compare.md`. + +| nestng-crm (3 cells per arm) | LEL | VANL | VAN | LEL - VANL | +| --- | ---: | ---: | ---: | ---: | +| requests | 162 | 186 | 214 | | +| output tokens per request | 1,351 | 1,217 | 1,114 | | +| uncached prompt tokens per request | 583 | 609 | 441 | | +| proxy time per request, ms | 8,297 | 6,055 | 5,064 | | +| of it engine prefill, ms | 726 | 431 | 354 | **+295** | +| of it engine decode, ms | 7,549 | 5,592 | 4,674 | | +| of it rest (gateway, tokenizer, HTTP, SSE, prefix-cache work), ms | 22 | 32 | 36 | **-10** | +| pause between requests (tool run + Codex), ms | 713 | 1,405 | 1,013 | trajectory, not engine | +| ms per output token, proxy | 6.14 | 4.97 | 4.54 | **+1.17** | +| ... prefill / decode / rest | 0.54 / 5.59 / 0.02 | 0.35 / 4.59 / 0.03 | 0.32 / 4.19 / 0.03 | **+0.19 / +1.00 / -0.01** | +| proxy tok/s (the 163 vs 201 of `compare.md`) | 162.8 | 201.0 | 220.1 | -19.0 % | +| engine decode tok/s | 178.9 | 217.7 | 238.4 | -17.8 % | + +At LEL's own 1,351 output tokens per request the 1.17 ms/token gap is **about 1,580 ms per request: decode 1,350 ms (85 %), prefill 257 ms (16 %), gateway and the rest -13 ms (0 %)**. `ttt` is the same: 6.10 against 4.96 ms/token (+1.14 = prefill +0.13, decode +1.01, rest 0). The wall-clock of a cell also contains the pauses (LEL 38 s, VANL 86 s per CRM cell: the vanilla sessions ran heavier tool commands), which differ with the trajectory and are not the engine. + +So the 19 % (proxy) against the replay's 11-12 % (`dec tok/s` 183.8 against 208.3) is not a gateway, proxy, prefix-cache, tokenizer or serialization cost: the "rest" is 22 ms per request against 32 for vanilla. Two things make the gap look smaller in the replay: it counts decode only (the real-session proxy number adds the prefill gap, 0.19 of 1.17 ms/token, about 3 points), and the replay's two arms differ from the sessions by +-4 % each (LEL 186 in the replay against 178.9 in the sessions; VANL 208 against 217.7), i.e. a different text and a vanilla that ran at a different uptime. The decode gap itself is flat over the context: engine decode tok/s by prompt size (LEL / VANL): 0-20k 178.4 / 218.3 (-18.3 %), 20-40k 183.3 / 221.1 (-17.1 %), 40-70k 177.8 / 214.1 (-17.0 %), 70-100k 173.5 / 215.0 (-19.3 %), > 100k 155.8 / 206.7 (-24.6 %, 9 requests). + +Where the decode time goes (ms per round, phase 1): LEL 18.1-18.8, VANL 13.5-13.9: **+4.7 ms**. Our adaptive window pays +3.1 ms for +0.65 tokens per round (net +2.8 %, kept); the step-profile excess is `waitCPU` + `PCIe group` (+2.5 ms in miss-heavy windows, +0.6 in quiet ones, tied to the hit rate 90.2 % against 92.8 %), draft + commit outside the window +1.3 ms (full 248,320-row draft head against vanilla's 106,299-token subset), and +1.3 ms in quiet windows (12.0 against 10.7: kernels; the sm_120 sets of lever 1 took a part of it, +1.85 %). + +Prefill: +295 ms per request at equal uncached tokens (726 against 431); by size: < 64 tokens 430 against 268 ms, 64-256 530 against 292, >= 4096 4,405 against 2,184 (4 % of requests, 19 % of the prefill time). The known cause is old code work, not a switch: `docs/prefill-throughput.md` "Remaining gap" (8192-token chunks 2,830-2,930 tok/s against the Original's 5,400-5,900; tails of <= 64 tokens read through verify windows in the Original). + +What is available without lossy (E, none measured as an A/B yet beyond lever 1): lever 1 done (+1.85 % decode); lever 3 upper bound queued (`spd-l3a/b`: +190 slots); lever 4 (draft + commit, up to -1.3 ms of 18 = up to +7 % decode if all of it went, but the fused-commit graph measured neutral and the draft-vocabulary route is prompt-dependent and not bitwise); lever 5 (prefill: up to 16 % of the gap, code-level, placement-class numerics for the window tails). Nothing identified so far closes the 18 % without the lossy tail skip (+12.6 % decode, gate not passed). + +## Levers 4 and 5 after the base moved to hexagonal-finish (b686f6ab7), 2026-11-08 + +### Lever 4, draft head 248k against 106k: the premise was wrong for the shipped product + +* What the Original does: a **static** subset file, not a prompt-dependent or frequency-ranked choice at run time. `rt/draft_vocab.bin` (106,299 int32 ids, 425,196 bytes, sha256 `b1e1d3a7…cb91`) is copied by setup from `data/draft_vocab*.bin`, built offline by `tools/draft_vocab.py` (base list + whole scripts `--add han,kana,hangul,cjk_punct,cyrillic` or a language corpus by token frequency `--corpus --coverage 0.99`). The engine computes draft logits over those rows only (`MtpDrafter::bind`, `src/core/mtp.cpp`). +* What the product does: `leleka-deploy` always passes `--mtp-rt-dir ` (`crates/deploy/src/config/engine_launch.rs`), so the engine drafts over the same file. Checked on the running 5090 engine: argv has `--mtp-rt-dir /data/leleka-e2e/codex-compare/ours-assets/data/mtp-rt`, and that directory's `draft_vocab.bin` has sha256 `b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91`, the Original's default. The "248,320-row head" in section 2 and in the ledger (section 5) described the model-free smokes and the daemon without `--mtp-rt-dir`, **not** the release package that the A/B and the Codex cells ran. There is no subset sub-lever to take: ours already equals vanilla there. (The opt-in `LELEKA_DRAFT_VOCAB=en|cyrillic|fr` exists, is not bitwise and is prompt-dependent: unchanged, see `2026-10-30-draft-vocab-en.md`.) +* What is left of "draft + commit +1.3 ms/round": `draft.finish` 1.7 against vanilla's `draft` 1.17, `apply_pending` 0.6 and commit 0.4. The ledger's own split of the chain step with the subset bound is 0.466 ms against 0.421 (about 0.2 ms per round over 3.9 chain steps) plus launch calls of 100-200 us against 55-125 us. That is at most about 0.5 ms of 18.5 (2.7 %), spread over many small items; no single switch, nothing started. + +### Lever 5, prefill: the fixed cost per request, from the product's own profile lines (`runs/main/P/engine.log`, 30 replayed requests, `LELEKA_SERVE_PROFILE=1`) + +Per request, ms: `prefill.read` (the batched read of the uncached tokens), `prefill.refill` (the lent expert slots refilled after the read: 2,226 copy spans, constant), `decode.assemble` (host assembly and re-recording the window graphs: capture 54-62, instantiate 27-30, charged to the decode time). + +| uncached tokens | prefill.read | prefill.refill | decode.assemble | +| ---: | ---: | ---: | ---: | +| 239 | 485 | 139 | 109 | +| 266 | 486 | 136 | 106 | +| 536 | 582 | 140 | 104 | +| 1223 | 668 | 140 | 105 | +| 2453 | 1013 | 140 | 101 | +| 5440 | 1229 | 136 | 108 | + +A least-squares line through the 29 post-warm-up requests gives 581 ms plus 0.134 ms per token for the read; the smallest tails (239-266 tokens) read in 485 ms, where vanilla's whole prefill for the same size class is 292 ms. Fixed per request: about 490 (read of a small tail) + 139 (refill) + 105 (assemble, inside decode) = about 730 ms, 9 % of a 8.3 s request. Two of the three have a known non-lossy handle: + +* `prefill.refill` (139 ms): `LELEKA_REFILL_DEFER=on` (opt-in, never measured: "no GPU result yet (job 904)") queues the same copies inside the decode assembly, after its uploads and before the graph capture. Same bytes, other time; `spd-l5a/b` run it as variant R against A, 10 pairs. +* the read's ~490 ms fixed part: no per-stage split of a small tail exists for the 5090 (`docs/prefill-throughput.md` only has 8192-token chunks and an 80-token laptop run: GDN 1.3 s). `spd-l5q` is a single profiled replay (variant Q: `LELEKA_BRINGUP_TRACE=1`, `LELEKA_PREFILL_PROFILE_SYNC=1`) to get `PREFILL-PROFILE` lines per chunk; its sync drains make it a diagnosis run, never an A/B arm. + +### Lever 3, first attempt (variant G, `--gpu-budget-gib 31`): invalid, the arm opened the same cache + +`ab-l3`, 10 pairs, G against A: decode +0.58 % (CI -0.15..+1.31 %), end-to-end +0.07 %, tokens/round +1.71 %, ms/round +1.10 %, VRAM share 90.33 -> 90.28 %. **Both arms logged `expert cache 12192 slots`**: the cache is sized against `min(card free, context budget - allocated)` (`usable_room`, `original_cache_startup.rs`); on the 32 GiB card the card binds, so a larger declared budget adds no slot (the engine saw +177 MiB available for the prefix cache only). The result is a null experiment, not evidence about slots. + +Second attempt (`ab-l3h`, jobs `spd-l3c/d`): variant H = `LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130` (opt-in of `vram-footprint-5090.md`, bitwise: it moves only the cache size) and `LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB=500` (from 700): 370 MiB less reserve = about +190 slots, placement class, an upper bound of what ~+200 slots are worth. The slot count has to be read from the H log before the pairs are used. + +### Lever 5 first A/B (R = `LELEKA_REFILL_DEFER=on`) and lever 3 H: both invalid, the job script leaked their variables + +`ab-l5` (10 pairs): decode -0.65 % (CI -1.60..+0.30 %), end-to-end -0.26 % (-1.52..+0.99 %), `pf_ms` per request 866 -> 870 (mean paired difference +6.9 ms, sd 17.6): **no change in the prefill time at all**. Cause found afterwards: `spd_ab_job.sh` unset a fixed list of variables between blocks and the list did not contain `LELEKA_REFILL_DEFER`, so every A block after the first R block ran with the deferral on (the pair order `A R R A A R R A` makes half of the A blocks contaminated). The same hole applied to the lever 3 variable pair of H (`DECODE_RESERVE_MIB`, `VRAM_RESERVE_MIB`) and to Q. Levers 1, 3-G, 6 and 7 were not affected (their variables, `FLOOR` and `UPX` were reset per block). The script now unsets all of them (commit of this section); the contaminated outputs are kept as `runs/ab-l5-contaminated` and `runs/ab-l3h-contaminated` and are not evidence. `spd-l3e/f` (H against A) and `spd-l5c/d` (R against A) rerun the pairs into `runs/ab-l3v2` and `runs/ab-l5v2`. + +### Lever 5, where a small tail's prefill goes (`prof-l5/Q.1`, `PREFILL-PROFILE` per chunk, `PREFILL_PROFILE_SYNC=1`, 31 chunks; ms) + +| tokens in chunk | total | moe | moe.ring | gdn | qsa | input | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 238 | 492 | 374 | 355 | 52 | 46 | 3 | +| 278 | 558 | 424 | 404 | 66 | 42 | 8 | +| 541 | 696 | 546 | 522 | 74 | 46 | 7 | +| 1,242 | 738 | 516 | 475 | 108 | 56 | 18 | +| 1,416 | 861 | 601 | 565 | 120 | 83 | 14 | + +For a tail under about 1,500 tokens **72-80 % of the chunk is `moe.ring`**: the per-layer expert copy ring (48 layers, about 7.4 ms per layer even for 238 tokens, 355 ms in all). It barely grows with the tokens (238 -> 1,416 tokens: +210 ms), which is the fixed cost found in the product's profile lines (about 490 ms of read). GDN, QSA and the input stage together are under 120 ms. The prompt stream (`STRATA_PREFILL_STREAM_MIN`, 4096 rows) is off for these chunks. Whether the ring is bandwidth-bound (bytes of the non-resident routed experts at 36-47 GB/s) or latency-bound (48 synchronous per-layer round trips) is not known from the existing counters: `PREFILL-COPY` is only printed for streamed chunks. Code proposal (needs the orchestrator's word): see the report of 2026-11-08. + +### Graph re-recording per request (`decode.assemble`, 2026-11-08): what it would take + +Per request (product profile lines, 30 replayed requests): `decode.assemble` 98-109 ms, of which `assemble.record_all` 83 ms (capture 54-62, instantiate 27-30; nine graphs: windows T = 1..8 and the commit graph, about 6 ms capture + 3 ms instantiate each); `assemble.prepare` 12, `assemble.verifier_new` 2, `assemble.aggregates` 0.75. The decode phase uses every width up to 8 in a long request (`T_hist` of a 2,444-round request: 187/681/635/523/235/85/56/42 for T = 1..8), so recording only the widths used saves little. + +Why the graphs are not kept: a recorded graph holds device pointers, and four things behind them are made per request in `AssembleInputs::assemble` (`original_serve_verifier.rs`): the canonical GDN image (`original_verify_canonical_gdn(states, histories)` allocates and seeds from the session's priors), the verifier bank and its GDN journal (`OriginalVerifier::new`, `bank().gdn_journal`), the per-width head/embedding row views and window resources, and the QSA journal that takes the twelve resident index and mapped K/V owners **by value** from the prompt executor (`take_qsa_owners`) and gives them back in `disassemble`. Keeping the verifier between requests therefore needs (1) a persistent, re-seedable canonical GDN image and bank (seed = upload, no allocation), (2) the QSA owners staying with the journal while the prompt path appends to the same buffers, (3) the `'a` borrows of `DecodeResources` (dense and MoE weight caches) to outlive a request, which is a self-referential shape in the present `OriginalServeStack`, and (4) invalidation when any pointer changes (prefix-cache switch, window-cap fallback, tier reconfigure). Expected gain at best -60..-80 ms per request of about 8,300 (under 1 % end to end); it is a cross-crate ownership change (`cuda-driver` verifier/bank and `engine-qwen35-cuda` stack), not a switch. + +### Decode miss leg, draft + commit, quiet windows: what the P profile lines say (2026-11-08, no new GPU run) + +Per round and per group (48 groups per round), from `runs/main/P/engine.log` (30 profile lines): + +| window kind | rounds' T | window.verifier | doorbell wait (GPU mixers) | pool.cpu (CPU leg on the critical path) | cpu.compute per group | draft.finish | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| miss-heavy (lines 2, 7, 26) | 4.5-7.0 | 23.3-26.0 ms | 8.8-10.4 ms | 12.0-14.1 ms | 233-272 us | 1.5-2.6 ms | +| quiet (lines 16, 17) | 3.0-3.2 | 12.1-12.2 ms | 8.7-8.9 ms | 2.5-2.6 ms | 45-47 us | 0.93-0.97 ms | + +* The CPU leg is serial with the GPU mixers of the next layer (the layer output needs every expert): window time = doorbell wait + pool time + 0.5-0.7 ms sync. It is DRAM-bound (about 39 us per 2 MB expert = 52 GB/s, equal to vanilla's 44 us), so the miss leg is proportional to the number of CPU-computed experts; nothing in the host path adds to it: the fixed host work around a group (split 3, spans 2, publish plan 6, open + zero 5 us) is about 16 us x 48 = 0.8 ms per round and is already small. +* `draft.finish` follows the window width (0.93 ms at T 3.0, 2.5 ms at T 6.2): the chain has more steps in a wider window. It is not a per-round defect; the "+1.3 ms" is the width of the adaptive window, the same cost as the "+3.1 ms for +0.65 tokens" of the window price. +* Same speculation, ours against vanilla (B 178.8 against VANL 208.3 tok/s at 2.90 against 2.95 tokens/round): +2.0 ms per round (+14 %). The largest identified part is the miss count: hit rate 90.8 % against 92.8 % (28 % more misses, about +1.4 ms of CPU leg). Per request, vanilla's hit rate is higher in nearly every request, by up to 7 points in short ones (request 12: 93.2 against 86.4 at 276 tokens; request 26: 87.6 against 78.4), i.e. mostly at the start of a request. +* The tier policy is the same as the Original's (decay 0.7, margin 1.5, min count 2.0, `adapt_every` 4, 96 swaps, candidates and victims paired per layer; counts survive across requests; the lent slots are refilled with their own previous experts, so the prefill borrow does not lose learned placement). The differences left are +3 % slots (12,575 against 12,192), the window width and whatever the first rounds of a request see. `spd-w1..5` (tier knobs) and `spd-l3e/f` (slots) measure how much each of them moves the hit rate. + +### Real-session weighting of the hit-rate gap and the gap by context (owner rule 2026-11-08: weigh by time in the real session, ignore short-request-only gains) + +Tools: `scripts/e2e/codex/speed/session_hit.py` and `session_ctx_gap.py` (run on the server with `python3 -I`; read the `engine-slice.log` of the `runs/main/{LEL,VANL}` cells, three repetitions each). + +* **VRAM hit share weighted by decode time**: nestng-crm LEL 91.38 % against VANL 92.41 % (-1.03 points), ttt 92.68 % against 93.38 % (-0.70). By output length of the request (share of decode time in brackets), nestng-crm LEL/VANL: < 600 tokens (10 %/12 %) 86.9/89.9, 600-2000 (33 %/34 %) 90.5/91.6, >= 2000 (58 %/54 %) 92.7/93.5 (-0.9). The 3-8 point gaps of the replay are in the short requests, which carry 10 % of the decode time; in the long ones the gap is about 0.9 point. +* **Price of a point**: lever 7 raised the VRAM share by 3.5 points and took 2.0 ms off a round (19.3 -> 17.3) at equal tokens per round, so at most 0.57 ms per round per point (that figure also contains the skipped entries). One point of hit share is therefore at most 0.57 / 3.55 = 0.16 ms per output token: 2.6 % of nestng-crm's 6.14 ms request time per token (1.0 point), 1.8 % of ttt's (0.7 point). That is the ceiling for everything done about the hit rate together (tie order, tier knobs, slots). +* **Gap by context** (decode tok/s LEL against VANL, same cells): nestng-crm 0-30k -18.2 %, 30-60k -16.6 %, 60-100k -18.7 %, 100-160k -24.6 % (3 % of the time); ttt 0-30k -16.8 %, 30-60k -20.0 %. The sessions never pass 160k; the gap is flat in context, so there is no long-context hot spot in these two tasks (a 245k session is not in the cells). + +### Kernel level: what vanilla has on by default and the release does not (2026-11-08; the measured per-kernel table is queued) + +Vanilla `sm120_series.hpp` turns five bitwise switches on for a 12.0 card (`SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GR_DOWN_TG=1`, `GU_SWIGLU`) and its tables add the interleaved MMVQ (`MMVQ_IL`, 2-4 columns, 5-8 on sm_120). Upstream's own number for the set is 13.70 -> 12.23 ms per 4-token round on an RTX PRO 5000 (other hardware). Status in the release: `ATTN_DAILY` and `GU_SWIGLU` on since lever 1 (+1.85 % decode paired, bitwise); `SIDE_MIXER` exists (`LELEKA_SM120_SIDE_MIXER`), off, measured no gain (KS variants 209.4 against 209.1 tok/s); `GR_DOWN_TG` we have and better (`chain_gr_down_t2w8_nb4` 9.7 us against 18.4 us); `GR_UP75` partial; the rest below is missing. The remaining estimates are those of `docs/upstream-port-plan.md` rows 2.1/2.2 (estimates from our microseconds, not measurements), ms per round of about 18: + +| item | estimate ms/round | effort | numerics | +| --- | ---: | --- | --- | +| `COMMIT_BATCH` + state-only GDN commit (commit graph 158 kernels, 0.463 ms) | 0.25-0.35 | M, seal | bitwise (`gdn_parity`) | +| `GU_SWIGLU` sub16 expert kernels beyond the fused launch (`window_moe_gu_*` are warp-per-row) | 0.20-0.35 | L, seal | bitwise (claimed) | +| `MMVQ_IL` interleaved MMVQ 2-4 and 5-8 columns (we run the old `head_n*_t*`; dense 2.25 ms against a floor of ~2.0) | 0.10-0.40 | L, seal | bitwise (claimed) | +| `HEAD_MIX_MULTI` (one multi-token head mix) | 0.06-0.10 | S | bitwise | +| `GR_UP75` delta, batched K/V and indexer append, float4 combine, fused norm+rope | 0.05-0.10 each | S-M, seal | bitwise | + +Their sum is 1.0-1.4 ms per round, i.e. the "+1.3 ms in quiet windows" of the step profile; none is a single big defect. `spd-cuo` (ours, shipped package with the lever 1 switches) and `spd-cuv` (vanilla VANL) take one 15 s CUPTI window each over request 29 of the replay (67k context, 4,741 output tokens), `decode_rounds.py --tsv` per arm gives the measured per-kernel table. + +## Lever 5, variant R (`LELEKA_REFILL_DEFER=on`), clean paired result, 10 blocks (2026-11-08) + +Run `ab-l5v2` (server `/data/leleka-e2e/spd-gap/runs/`), A = release package, R = A + refill deferred into the decode assembly, 27 requests per block after the 3-request warm-up, 10 block pairs, `ab_report.py`: + +| metric | A | R | diff | 95 % CI | +|---|---:|---:|---:|---| +| decode tok/s | 180.19 | 178.53 | -0.92 % | -1.63..-0.21 % | +| end-to-end tok/s | 162.93 | 163.84 | +0.56 % | -0.15..+1.27 % | +| ms/round | 19.95 | 20.31 | +1.80 % | -1.26..+4.87 % | +| tokens/round | 3.59 | 3.63 | +0.87 % | -2.69..+4.43 % | + +Reading: the deferred refill moves prefill time into decode (decode slower by about 0.9 %, significant), the end-to-end gain is +0.56 % and not significant. Not a lever by itself; stays an opt-in, off by default. `out_sha` identity is not usable in live replay (A/A floor about 10/30), so no identity claim from this run. + +## Lever 3, variant H (larger VRAM reserves → slot count), clean paired result, 10 blocks (2026-11-09) + +Run `ab-l3v2`, A = release package, H = A with the reserve settings of variant H, 27 requests per block after warm-up, 10 block pairs, `ab_report.py`: + +| metric | A | H | diff | 95 % CI | +|---|---:|---:|---:|---| +| decode tok/s | 181.00 | 181.91 | +0.51 % | -0.19..+1.20 % | +| end-to-end tok/s | 163.07 | 164.79 | +1.06 % | -0.38..+2.50 % | +| ms/round | 20.23 | 19.79 | -2.19 % | -3.55..-0.83 % | +| tokens/round | 3.66 | 3.60 | -1.69 % | -3.33..-0.05 % | +| VRAM % of routed | 90.31 | 90.75 | +0.44 pp | +0.19..+0.79 pp | + +Reading: the extra resident share (+0.44 pp) makes the round shorter (significant), but tokens per round fall by a similar amount (the tier placement differs, accept changes), so decode and end-to-end gains are not significant. Placement-class change: would need a quality gate against the control placement before any default. Not a lever on this evidence. + +## Kernel level: one CUPTI window of request 29 (67k context), LEL against VANL (2026-11-09) + +Runs `cupti/CL.1` (release package + lever 1 switches) and `cupti/VANL` (vanilla 0.2.6, tail skip and CPU prefill share off, no engine-side profile), 15 s over the same replay request (`/data/leleka-e2e/spd-gap/runs/cupti/*/win-r29.lct`); analysis `decode_rounds.py --tsv`, `scripts/e2e/codex/speed/{cupti_verify_graph,cupti_stream_overlap,kernel_roles}.py`. One window per arm, greedy trajectories differ a little: shapes, not CIs. + +Round (graph start to start): LEL 17.86 ms, VANL 15.89 ms (-1.98). Verify graph GPU span 13.56 against 11.75 (-1.81); after the verify graph to the next start (draft, commit, host, CPU-leg join) 4.30 against 4.14 (-0.16). Kernels per verify graph 2061 against 2098; idle inside the graph 0.21 against 0.12 ms (launch gaps are negligible). Outside the verify graph: 630 against 147 kernels per round, 5.38 against 4.47 graph executions, 207 against 20 API calls, 121 against 12 copies (71.5 against 23.6 MB), 27.8 against 89 syncs (2.47 against 0.93 ms) per round; the tail they feed is only 0.16 ms longer. + +Structure: in LEL the verify graph is on ONE stream (714; kernel sum 13.35 ms = span 13.56 ms, zero overlap). In VANL it forks over 11 streams (kernel sum 13.73 ms, span 11.75 ms): wall time with two or more streams active is 2.03 ms per graph (1.52 expert/shared-expert branches against the main stream, 0.51 the QSA mixer branch: `native_mmvq_il` + `norm_rope` on side streams). That 2.03 ms is the verify gap (1.81 ms). + +Matched kernels are not slower in LEL: attention `leleka_qsa_decode_chunk_daily` 18.3 us against `attn_chunk_kernel_pre75` 17.1, topk 17.3 against 18.0, scores 14.2 against 17.1; draft chain `chain_gr_down` 11.1 against `gr_down_staged` 11.5, `chain_gr_split` 3.1 against 2.9; GDN equal; dense (`head_n*`, mmvf) 3.9 against 4.6 ms (LEL faster); routed experts at equal entry count: `window_moe_down_20` with 40 entries 13.6 us against `native_down_multi<20>` 17.4 us, `sm120_moe_gu_swiglu_22` with 50 entries 12.3 us against vanilla 26 us (with 40). Mean-per-kernel comparisons are distorted by the entry mix (vanilla has many empty 0.7 us launches). CPU/PCIe leg handling in total (flag waits + doorbell + mapped copies + `fetch_blobs`) 3.25 ms in LEL against 3.08 ms in VANL. + +Conclusion: no single kernel explains the gap; the verify graph has no parallel branches. Candidate steps in order: (1) measure the existing GDN `SIDE_MIXER` at this context (CUPTI window overlap + paired A/B), then port the QSA part (indexer/queries chain, about 0.5 ms of overlap in VANL), then the routed/shared-expert branch (about 1.5 ms of overlap); bitwise (only graph edges change). (2) the draft/commit tail: 0.16 ms. diff --git a/docs/experiments/step-ledger.md b/docs/experiments/step-ledger.md new file mode 100644 index 00000000..c268fcf4 --- /dev/null +++ b/docs/experiments/step-ledger.md @@ -0,0 +1,181 @@ +# Step ledger: every place where Leleka (LEL) loses to vanilla Strata (VANL), in pipeline order, request to decode + +Owner rule (2026-11-09): every step where we lose is recorded, even 0.02 ms. A row is never dropped as "below noise", "under 1 %", "neutral" or "NO-GO because small". This file is the single register; the narrative and the measurements behind it stay in `docs/experiments/codex-compare-speed-gap.md` (cited as *gap doc*). + +**Arms.** LEL = release package `leleka-0.1.0-17e372944279` (CUPTI `CL.1`: plus the lever 1 switches `ATTN_DAILY`, `GU_SWIGLU`). VANL = vanilla 0.2.6, tail skip and CPU prefill share off. Differences are LEL minus VANL: positive = we are slower. "ms/round" means per speculation round of the verify window; one round is 17.9 ms in LEL and 15.9 ms in VANL in the CUPTI window. + +**Closing rule.** A row is `fixed` only with (1) a measured *section* delta of that very step (CUPTI window or PROFILE lines of the step, not the end-to-end A/B, which cannot see 0.05 ms), (2) identity (bitwise for non-lossy changes: `draftround-id.sh` top-16 logprob rows and draft trace; placement-class changes need the gate against the control placement), and (3) the end-to-end paired A/B of the whole set of fixes. Statuses: `open` (nothing done), `fixing` (code or run exists, closing evidence incomplete), `fixed`, `proved-equal` (measured equal, or measured in our favour: the sign is in the difference column). + +**Owners.** `device` = verify graph and everything on the GPU (this register, session `hexagonal-44f3f4`); `hex-finish` = host, draft and prefill. + +**Sources.** `CUPTI` = one 15 s window over replay request 29 (67k context), runs `/data/leleka-e2e/spd-gap/runs/cupti/{CL.1,CM.1,VANL}/win-r29.lct`, scripts `scripts/e2e/codex/speed/{cupti_layer_phases,cupti_doorbell_latency,cupti_verify_graph,cupti_stream_overlap,kernel_roles}.py` and `decode_rounds.py`. One window per arm: the greedy trajectories differ a little (hit mix, window width), so a per-kernel mean can carry the entry mix. `PROFILE` = the product's own `LELEKA_SERVE_PROFILE` lines (`runs/main/P`). `LOG` = engine logs of the replay cells. `ORCH` = figure given by the orchestrator session, not re-derived here. + +**Order (owner rule 2026-11-09).** The ledger follows the request linearly, from the request into the engine, through prefill, to the decode round (draft, verify graph, accept, commit, publication of the tokens, next round). Work goes in this order: step N is closed (`fixed`, or `proved-equal` with a section measurement) before step N+1. Prefill and host are led by `hex-finish`, the decode part (verify graph, accept on the device, branch overlap, their streams) by `device`; both run in parallel, each in its own order. After each group of steps comes the end-to-end paired A/B of the group. + +Row ids are stable (they are cited in `codex-compare-speed-gap.md` and in reports); the section decides the order, not the number. + + +## A. Request into the engine (HTTP and gateway, tokenizer, prefix cache) + +No per-step figure exists for A1-A3; each is a `not measured` row that needs a section measurement before it can be closed. + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| A1 | HTTP, gateway and proxy time per request | not measured per step | not measured per step | the sum 'rest' per request is Q10: 22 ms against 32 ms | LOG | hex-finish | open | +| A2 | tokenizer and prompt assembly | not measured | not measured | n/a | none | hex-finish | open | +| A3 | prefix-cache lookup and import (cached tokens per request, import time) | not measured | not measured | n/a (replay logs `cached_tokens`; import time only in `last_import_split`) | none | hex-finish | open | +| Q10 | gateway, proxy, serialization ("rest" per request) | 22 ms | 32 ms | -10 ms | LOG | hex-finish | proved-equal (LEL ahead) | + +## B. Prefill (chunks, expert ring and copies, refill, QSA, GDN, first token), then the hand-over to decode + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| Q8 | request time per output token, prefill + decode | 0.59 + 5.63 = 6.22 ms | 0.36 + 4.61 = 4.97 ms | +1.25 ms (decode +1.02, prefill +0.23) | LOG | both | open | +| Q1 | prefill per request at equal uncached tokens | 726 ms | 431 ms | +295 ms | LOG | hex-finish | open | +| Q2 | prefill latency by uncached tokens (< 64, 64-256, 256-1024, 1024-4096, >= 4096), median ms | 430, 530, 722, 1002, 4405 | 268, 292, 435, 715, 2184 | +162, +238, +287, +287, +2221 | LOG | hex-finish | open | +| Q3 | prefill throughput over uncached tokens | 930-1050 tok/s | 1460-1560 tok/s | -35 % | LOG | hex-finish | open | +| Q4 | `prefill.read` fixed part (581 ms + 0.134 ms per token; 485 ms for 239 tokens) | 485-581 ms | whole prefill of that size class 292 ms | +193 and more | PROFILE | hex-finish | open | +| Q5 | `moe.ring` in a small tail (72-80 % of the chunk, 48 layers x 7.4 ms, 355 ms for 238 tokens) | 355 ms | vanilla reads tails of up to 64 tokens through verify windows | +355 ms for the smallest tails | PROFILE `prof-l5` | hex-finish | open | +| B1 | prefill GDN and QSA stages of a small tail (per stage split) | `prof-l5/Q.1` has moe, moe.ring, gdn, qsa, input per chunk | none for vanilla | n/a | PROFILE | hex-finish | open | +| B2 | first token sampling and publication after prefill | not measured | not measured | n/a | none | hex-finish | open | +| Q6 | `prefill.refill` of the lent expert slots (2,226 copy spans) | 137-140 ms per request | none | +138 ms; deferring it into the decode assembly (`LELEKA_REFILL_DEFER`): decode -0.92 % (CI -1.63..-0.21), end-to-end +0.56 % (CI -0.15..+1.27) | PROFILE, A/B `ab-l5v2` | hex-finish | fixing | +| Q7 | `decode.assemble` (graph re-recording per request: `record_all` 83 ms of 98-109 ms, nine graphs, 54-62 capture + 27-30 instantiate) | 98-109 ms per request | none (vanilla keeps its graphs) | +98-109 ms | PROFILE | device | open | + +## C. Decode round: summary, then draft, verify graph, accept, commit, publication, next round + +Round-level totals first (they are the sum of the steps below). + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| R1 | round wall (graph start to start) | 17.864 | 15.886 | +1.978 | CUPTI | device | open | +| R4 | GPU idle over the round | 2.574 | 3.103 | -0.529 (busy 85.6 % against 80.5 %) | CUPTI | device | proved-equal (LEL ahead) | +| Q9 | round count: tokens per round | 3.59-3.66 | 2.95 | +0.64..+0.71 tokens per round (+22 %): our adaptive window pays +3.1 ms for +0.65 tokens | LOG | device | proved-equal (net +2.8 % decode, kept) | + +## C1. Draft (chain from the previous commit to the verify window's tokens) + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| O9 | draft chain steps and idle between them | 0.27 | not given | +0.27 | ORCH | hex-finish | open | +| O8 | draft finite and q8 guard checks (`mtp_original_finite` 158.8 x 0.87 us, `mtp_original_q8_guard` 28 x 0.87 us per round, 186.8 launches) | 0.162 | none | +0.162 | CUPTI | hex-finish | open | +| K13 | draft chain role total (chain GR kernels, `mtp_*`) | 3.544 | 2.471 | +1.073 (includes the draft head and checks of R3 and O8; VANL books its draft in the shared GR kernels) | CUPTI role table | hex-finish | open | +| O12 | draft finish follows the window width (0.93 ms at T 3.0, 2.5 ms at T 6.2) | window price | | part of the +3.1 ms for +0.65 tokens per round | PROFILE | hex-finish | open | +| O2 | kernels outside big graphs | 630 | 147 | +483 | CUPTI | hex-finish | open | +| O3 | graph executions per round | 5.38 | 4.47 | +0.91 | CUPTI | hex-finish | open | + +## C2. Verify graph: embed, 48 layers (mixer half, FFN half), final write and head + +Structure first, then the layer steps in graph order: embed (R7), mixer half (V3 and the kernels in it), FFN half (V2/V4 and the kernels in it), tail (R8). + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| V1 | streams in the verify graph | 1 | 11 | wall time with two or more streams active: 0 against 2.03 ms | CUPTI | device | fixing | +| R2 | verify graph GPU span | 13.561 | 11.743 | +1.818 | CUPTI | device | open | +| V9 | verify graph kernel time sum | 13.349 | 13.728 | -0.379 (VANL runs kernels concurrently: its span is shorter than its sum) | CUPTI | device | proved-equal (LEL ahead) | +| V8 | launches per verify graph | 2061 | 2098 | -37 | CUPTI | device | proved-equal (LEL ahead) | +| R5 | verify graph launch call (host) | 1.485 | 1.509 | -0.024 | CUPTI | device | proved-equal (LEL ahead) | +| R6 | idle inside the verify graph (2052 gaps against 1193 per round, mean 0.1 us) | 0.213 | 0.119 | +0.094 | CUPTI | device | open | +| R7 | first doorbell after graph start (embed, first layer mixer) | 0.132 | 0.117 | +0.015 | CUPTI | device | open | +| V3 | mixer phase (`add_hits` end to next doorbell) | 6.366 | 5.963 | +0.403 | CUPTI | device | fixing | +| V3a | GDN gates and gate projection on side streams (`LELEKA_SM120_SIDE_MIXER=1`, existing, off) | mixer 5.913, round 17.508 (`CM.1`) | mixer 5.963 | section delta mixer -0.453, round -0.356; mixer phase now equal to VANL | CUPTI | device | fixing (identity `spd-sqid1`, A/B `spd-sm1` queued/running) | +| V3b | QSA indexer chain and query chain on side streams (`LELEKA_SM120_SIDE_QSA`, code `0c30105d4`, off) | in line | 0.509 ms of overlap with the main stream (main+qsa) | not yet measured; VANL mixer phase is already matched by V3a | CUPTI (VANL) | device | fixing (window `spd-sqw`, identity `spd-sqid1`) | +| K6 | attention role in total (norm/RoPE, appends, scores, top-k, resolve, chunk, merge, gate) | 1.357 | 1.125 | +0.232 | CUPTI role table | device | open | +| K1 | attention decode chunk (`leleka_qsa_decode_chunk_daily` 18.3 us, 12 per graph) against `attn_chunk_kernel_pre75` (17.1 us) | 0.220 | 0.206 | +0.014 | CUPTI | device | open | +| K2 | indexer block scores (`leleka_qsa_decode_scores` 14.2 us against `block_scores_multi` 17.1 us) | 0.170 | 0.205 | -0.035 | CUPTI | device | proved-equal (LEL ahead) | +| K3 | block top-k cluster (17.3 us against 18.0 us) | 0.208 | 0.216 | -0.008 | CUPTI | device | proved-equal (LEL ahead) | +| K4 | KV miss copy / copy kernel (11.1 us against 11.6 us) | 0.133 | 0.139 | -0.006 | CUPTI | device | proved-equal (LEL ahead) | +| K5 | KV resolve (7.8 us against 8.4 us) | 0.094 | 0.100 | -0.006 | CUPTI | device | proved-equal (LEL ahead) | +| K7 | GDN role in total (step, conv, ab, commit) | 0.914 | 0.759 | +0.155 | CUPTI role table | device | open | +| K7a | GDN step/norm in the verify graph (`verify_gdn_step_norm_multi` 6.1 us against `gdn_step_norm_multi` 6.2 us, but 36 against 30.9 launches) | 0.220 | 0.191 | +0.029 | CUPTI | device | open | +| K7b | GDN alpha/beta (`chain_gdn_ab_multi` 36 x 8.5 us against `gdn_ab_multi` 22.9 x 10.5 us plus the rest) | 0.307 | 0.344 | -0.037 | CUPTI | device | proved-equal (LEL ahead) | +| K12 | dense projections, lm head, MMVQ/MMVF role (`head_n*`, `bf16_f32_mmvf_multi`) | 3.892 | 4.589 | -0.697 | CUPTI | device | proved-equal (LEL ahead) | +| S1 | `ATTN_DAILY` (decode attention) | on since lever 1 | on | paired decode +1.85 % with S2 (CI excludes zero), identity PASS (teacher-forced, 2057 of 2057 rows); no section delta of its own | gap doc lever 1 | device | fixing (needs a CUPTI section delta) | +| S3 | `SIDE_MIXER=2` | GDN part off by default, QSA part not ported before `0c30105d4` | on | V3a, V3b | CUPTI | device | fixing | +| S8 | `MMVQ_IL` (2-4 and 5-8 columns) | not ported | on | estimate 0.10-0.40; CUPTI role K12 shows our dense projections faster by 0.70 in total | upstream plan | device | open | +| S10 | batched K/V append and indexer append | per row (`verify_qsa_append_analytic` 138 x 1.04 us, `mtp_original_append` 49 x 1.6 us) | batched (`append` 12 x 3.0 us, `kv_append_q8` 14.6 x 2.2 us) | estimate 0.05-0.10 | upstream plan, CUPTI | device | open | +| V2 | FFN phase (doorbell to `add_hits` end) | 6.600 | 5.293 | +1.307 | CUPTI | device | open | +| V4 | doorbell to first routed expert (gate/up) start, us | 27.6 | 15.0 | +12.6 us x 48 = +0.60 ms | CUPTI | device | fixing | +| V4a | shared expert on a side stream, forked after the doorbell, joined before the combine (`LELEKA_SM120_SIDE_SHARED`, code `255159a89`, off) | 27.6 us before the first expert | 15.0 us | section delta pending (`spd-sqw` window `CE.1`) | CUPTI | device | fixing | +| V4b | routed experts on their own branch (VANL: plan wait, VRAM experts, `fetch_blobs`, CPU wait, `add_hits` on a side stream; main stream does the shared expert and the next norm) | all on the capture stream | branch | rest of V2 after V4a, not yet known | CUPTI | device | open | +| V4c | norms and hyper-connection reads (`gr_norm_split`, `gr_down`, `gr_up`) as separate branches | main stream | main stream (VANL does not branch them; a layer's `gr_*` chain stays on the main stream) | no structural difference; kernels in K8..K10 | CUPTI | device | proved-equal | +| V5 | flag waits on the CPU leg (`verify_wait_flag_ge` 96 x 26.9 us + `chain_wait_copy_i32` 48 x 5.4 us against `wait_flag_ge` 144 x 8.1 us) | 2.836 | 1.160 | +1.676 | CUPTI | device | open | +| V6 | PCIe fetch and CPU-row hand-over (doorbell, mapped copies, `fetch_blobs`, `add_hits`, `rebase_ptrs`) | 0.488 | 2.109 | -1.621 | CUPTI | device | proved-equal (LEL ahead) | +| V7 | V5 + V6, the whole miss-leg handling | 3.324 | 3.269 | +0.055 (+0.17 by an earlier count of the same sets) | CUPTI | device | open | +| K11 | routed experts in the verify graph, role total (gate/up/SwiGLU, down) | 2.507 | 2.484 | +0.023 (entry mix differs; at equal entry counts LEL is faster: `window_moe_down_20` 13.6 us with 40 entries against 17.4 us, `sm120_moe_gu_swiglu_22` 12.3 us with 50 entries against 26 us with 40) | CUPTI | device | open | +| K15 | hit tally `add_hits` (48 x 1.2 us against 48 x 1.3 us) | 0.059 | 0.063 | -0.004 | CUPTI | device | proved-equal (LEL ahead) | +| S2 | `GU_SWIGLU` (routed expert gate/up + SwiGLU + q8_1) | on since lever 1 | on | as S1 | gap doc lever 1 | device | fixing (needs a CUPTI section delta) | +| S7 | sub16 routed-expert kernels beyond `GU_SWIGLU` | warp-per-row | sub16 | estimate 0.20-0.35; the CUPTI pair K11 does not show LEL slower, so this must be re-measured by kernel before any work | upstream plan | device | open | +| S11 | float4 combine | not ported | `combine_k10_vec4` 50.6 x 1.2 us | estimate 0.05-0.10 | upstream plan | device | open | +| K8 | hyper-connection down (`chain_gr_down_t2w8_nb4` 11.1 us against `gr_down_staged` 11.5 us) | 1.063 | 1.112 | -0.049 | CUPTI | device | proved-equal (LEL ahead) | +| K9 | hyper-connection up (`chain_gr_up8` 8.5 us against `gr_up75` + `gr_up_multi` variants) | 0.817 | 0.877 | -0.060 | CUPTI | device | proved-equal (LEL ahead) | +| K10 | hyper-connection split (`chain_gr_split` 96 x 3.1 us against `gr_norm_split` 97 x 2.9 us) | 0.299 | 0.280 | +0.019 | CUPTI | device | open | +| S4 | `GR_DOWN_TG` | 9.7 us (`chain_gr_down_t2w8_nb4`) | 18.4 us | -8.7 us | gap doc | device | proved-equal (LEL ahead) | +| S5 | `GR_UP75` (hoisted row loads) | partial | on | estimate 0.05-0.10 | upstream plan | device | open | +| K14 | small kernels (norms, PLE, copies, sampler) | 0.049 | 0.253 | -0.204 | CUPTI role table | device | proved-equal (LEL ahead) | +| R8 | tail after the last layer's `add_hits` (final write, head, argmax) | 0.463 | 0.373 | +0.090 | CUPTI | device | open | +| S9 | `HEAD_MIX_MULTI` | not ported | on | estimate 0.06-0.10 | upstream plan | device | open | + +## C3. Accept (verdict of the window on the device) and the hand-over to the next draft + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| O7 | verify end to first draft kernel, ms | 0.32 | 0.08 (accept decided on the device) | +0.24 | ORCH | hex-finish | open | + +## C4. Commit (accepted-prefix graph, GDN replay, QSA tail restore, re-append, PLE history) + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| S6 | `COMMIT_BATCH` + state-only GDN commit (commit graph 158 kernels, 0.463 ms) | not ported | on (`gdn_step_commit_layers` 0.9 per round, 0.095 ms) | estimate 0.25-0.35 | upstream plan, CUPTI | device | open | +| O11 | commit graph (158 kernels, `verify_gdn_conv_commit` 36 x 1.7 us) | 0.463 | 0.095 (`gdn_step_commit_layers`) | +0.37 (S6) | CUPTI | device | open | +| O10 | fused commit (`LELEKA_DRAFT_FUSED_COMMIT`) | measured | | -0.024 | ORCH | hex-finish | fixing | + +## C5. Publication of the tokens, host work and syncs around the round + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| R3 | verify end to next verify start (draft, commit, host, CPU-leg join) | 4.304 | 4.144 | +0.160 | CUPTI | hex-finish | open | +| O4 | API calls per round | 207 | 20 | +187 | CUPTI | hex-finish | open | +| O5 | copies per round (count, MB) | 121 (71.5 MB) | 12 (23.6 MB) | +109 copies, +47.9 MB | CUPTI | hex-finish | open | +| O6 | syncs per round (count, host time) | 27.8 (2.468 ms) | 89 (0.926 ms) | -61 syncs, +1.542 ms of host sync time (overlapped with GPU work: R3 is only +0.16) | CUPTI | hex-finish | open | +| O13 | host work around a group (split 3, spans 2, publish plan 6, open and zero 5 us; 48 groups) | 0.8 | not measured | n/a | PROFILE | hex-finish | open | +| O1 | kernels per round | 2691 | 2245 | +446 | CUPTI | hex-finish | open | + +## C6. Between rounds and requests: expert tier (hit rate, placement) + +The tier adapts every 4 rounds and survives across requests. + +| id | step | LEL | VANL | difference | source | owner | status | +| --- | --- | ---: | ---: | ---: | --- | --- | --- | +| H1 | VRAM hit share in the replay | 90.8 % | 92.8 % | -2.0 points; 28 % more misses | LOG | device | open | +| H2 | VRAM hit share weighted by decode time in real sessions | nestng-crm 91.38 %, ttt 92.68 % | 92.41 %, 93.38 % | -1.03 and -0.70 points; at most 0.57 ms per round per point, so up to 0.59 and 0.40 ms per round | LOG | device | open | +| H3 | short requests (< 600 tokens) hit share | 86.9 % | 89.9 % | -3.0 points (up to 7 in single requests) | LOG | device | open | +| H4 | expert slots | 12,192 | 12,575 (+3 %) | -383 slots; variant H (reserves 130 / 500 MiB, about +190 slots): VRAM share +0.44 points, ms/round -0.44 (-2.19 %, CI -3.55..-0.83), tokens per round -1.69 %, decode +0.51 % (CI -0.19..+1.20), end-to-end +1.06 % (CI -0.38..+2.50) | A/B `ab-l3v2` | device | fixing (placement-class: needs the gate against the control placement) | +| H5 | adaptive tie order (equal-gain swaps share the cap across layers, `LELEKA_ADAPT_TIE_SPREAD`, `9d130fd38`) | low layer first | | run `spd-xa/xb` queued | gap doc | device | fixing | +| H6 | tier knobs: adapt every 2, 192 swaps, decay 0.85, margin 1.0 (`spd-w1..w5`) | 4, 96, 0.7, 1.5 | same policy | runs queued | gap doc | device | fixing | +| H7 | first rounds of a request see an unadapted tier | | | not isolated | gap doc | device | open | +| H8 | CPU expert compute per expert (2 MB) | 39 us (52 GB/s) | 44 us | -5 us | PROFILE | hex-finish | proved-equal (LEL ahead) | + +## Counts + +Computed by `scripts/e2e/codex/speed/ledger_counts.py` (2026-11-09): 86 rows. + +| status | rows | device | hex-finish | both | +| --- | ---: | ---: | ---: | ---: | +| open | 52 | 28 | 23 | 1 | +| fixing | 14 | 12 | 2 | 0 | +| fixed | 0 | 0 | 0 | 0 | +| proved-equal | 20 | 18 | 2 | 0 | + +Nothing is `fixed` yet: the closing rule needs a section delta, identity and the set A/B for the same row, and no row has all three. + + +## Order of work in the device part (linear in the graph; step N closed before step N+1) + +The device part starts at the verify graph; the draft (C1) and the host (C5) belong to `hex-finish`. + +1. C2, structure: V1 closes when V3a, V3b, V4a and V4b are closed. +2. C2, mixer half in graph order: V3a (GDN branch; A/B `spd-sm1`, identity `spd-sqid1`), V3b (QSA branch; window `CN.1`, A/B `spd-sqn`), then the kernels of the half: K1, K6, K7, K7a, S1, S8, S10. +3. C2, FFN half: V4a (shared expert; window `CE.1`, A/B `spd-sqe`), V4b (routed-expert branch), V5, V7, K11, S2, S7, S11, then K10, S5 and the tail R8, S9. +4. C3 accept (O7), C4 commit (S6, O11). +5. C6 hit rate and tier placement (device side: H1..H7). + +Each step is closed with: section delta (CUPTI of that step), identity, and the end-to-end paired A/B after the group. diff --git a/limits-baseline.json b/limits-baseline.json index 0cb97155..8465c9ff 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -13,10 +13,6 @@ "params": 1 } }, - "test": { - "leleka-deploy": { - "fn_lines": 1 - } - } + "test": {} } } diff --git a/scripts/e2e/codex/speed/cupti_doorbell_latency.py b/scripts/e2e/codex/speed/cupti_doorbell_latency.py new file mode 100644 index 00000000..054f1ebc --- /dev/null +++ b/scripts/e2e/codex/speed/cupti_doorbell_latency.py @@ -0,0 +1,19 @@ +import sys,collections,statistics +sys.path.insert(0,"/data/leleka-e2e/decode/tools") +import lct as L +t=L.Trace(sys.argv[1]) +byc=collections.defaultdict(list) +for k in t.kernels: byc[k.corr].append(k) +big=[c for c,v in byc.items() if len(v)>=900]; big.sort(key=lambda c:min(k.start for k in byc[c])); big=big[2:-2] +lat=[];sh=[] +for c in big: + ks=sorted(byc[c],key=lambda k:k.start) + db=[k for k in ks if "doorbell_publish" in t.names.get(k.name,"")] + gu=[k for k in ks if "gu_swiglu" in t.names.get(k.name,"")] + if len(db)!=48: continue + for i,d in enumerate(db): + nxt=db[i+1].start if i+1<48 else 1<<62 + g=[k for k in gu if d.start first VRAM expert gate/up start (us): n=%d mean %.1f p10 %.1f p50 %.1f p90 %.1f"%(n,statistics.mean(lat),lat[n//10],lat[n//2],lat[9*n//10])) diff --git a/scripts/e2e/codex/speed/cupti_layer_phases.py b/scripts/e2e/codex/speed/cupti_layer_phases.py new file mode 100644 index 00000000..0754237f --- /dev/null +++ b/scripts/e2e/codex/speed/cupti_layer_phases.py @@ -0,0 +1,22 @@ +import sys,collections,statistics +sys.path.insert(0,"/data/leleka-e2e/decode/tools") +import lct as L +t=L.Trace(sys.argv[1]) +byc=collections.defaultdict(list) +for k in t.kernels: byc[k.corr].append(k) +big=[c for c,v in byc.items() if len(v)>=900]; big.sort(key=lambda c:min(k.start for k in byc[c])); big=big[2:-2] +ffn=[];mix=[];first=[];tail=[];nbell=collections.Counter() +for c in big: + ks=byc[c]; g0=min(k.start for k in ks); g1=max(k.end for k in ks) + db=sorted(k.start for k in ks if "doorbell_publish" in t.names.get(k.name,"")) + ah=sorted(k.end for k in ks if "add_hits" in t.names.get(k.name,"")) + nbell[(len(db),len(ah))]+=1 + if len(db)!=len(ah) or len(db)<40: continue + first.append((db[0]-g0)/1e3); tail.append((g1-ah[-1])/1e3) + for d,a in zip(db,ah): ffn.append((a-d)/1e3) + for a,d in zip(ah,db[1:]): mix.append((d-a)/1e3) +n=len(big) +print("graphs",n,"(doorbells,addhits) counts",nbell.most_common(3)) +print("first doorbell after graph start %.0f us, tail after last add_hits %.0f us"%(statistics.mean(first),statistics.mean(tail))) +print("FFN phase (doorbell->add_hits end): mean %.1f us (p50 %.1f p90 %.1f) x47-48 = %.3f ms"%(statistics.mean(ffn),statistics.median(ffn),sorted(ffn)[int(.9*len(ffn))],statistics.mean(ffn)*48/1e3)) +print("mixer phase (add_hits end->next doorbell): mean %.1f us (p50 %.1f p90 %.1f) x47 = %.3f ms"%(statistics.mean(mix),statistics.median(mix),sorted(mix)[int(.9*len(mix))],statistics.mean(mix)*47/1e3)) diff --git a/scripts/e2e/codex/speed/cupti_stream_overlap.py b/scripts/e2e/codex/speed/cupti_stream_overlap.py new file mode 100644 index 00000000..6bdefc69 --- /dev/null +++ b/scripts/e2e/codex/speed/cupti_stream_overlap.py @@ -0,0 +1,29 @@ +import sys,collections +sys.path.insert(0,"/data/leleka-e2e/decode/tools") +import lct as L +t=L.Trace(sys.argv[1]) +byc=collections.defaultdict(list) +for k in t.kernels: byc[k.corr].append(k) +big=[c for c,v in byc.items() if len(v)>=900] +big.sort(key=lambda c:min(k.start for k in byc[c])); big=big[2:-2] +# classify stream by dominant family +cls={} +for c in big[:50]: + for k in byc[c]: + n=t.names.get(k.name,"") + cls.setdefault(k.stream,collections.Counter())[("wait_flag" in n or "gu_swiglu" in n or "native_down_multi" in n) and "expert" or ("mmvq_il" in n and "qsa" or "main")]+=1 +role={s:c.most_common(1)[0][0] for s,c in cls.items()} +print(role) +two=0.0; comb=collections.defaultdict(float); N=len(big) +for c in big: + ks=byc[c]; ev=[] + for k in ks: ev.append((k.start,1,k.stream)); ev.append((k.end,-1,k.stream)) + ev.sort(); act=collections.Counter(); last=None + for tm,d,s in ev: + if last is not None and tm>last: + roles=frozenset(role.get(x,"main") for x,v in act.items() if v>0) + nstr=sum(1 for v in act.values() if v>0) + if nstr>=2: two+=tm-last; comb["+".join(sorted(roles))]+=tm-last + act[s]+=d; last=tm +print("wall time with >=2 streams active: %.3f ms/graph"%(two/N/1e6)) +for k,v in sorted(comb.items(),key=lambda x:-x[1]): print(" %-24s %.3f ms/graph"%(k,v/N/1e6)) diff --git a/scripts/e2e/codex/speed/cupti_verify_graph.py b/scripts/e2e/codex/speed/cupti_verify_graph.py new file mode 100644 index 00000000..407273b1 --- /dev/null +++ b/scripts/e2e/codex/speed/cupti_verify_graph.py @@ -0,0 +1,21 @@ +import sys,collections,statistics +sys.path.insert(0,"/data/leleka-e2e/decode/tools") +import lct as L +t=L.Trace(sys.argv[1]) +byc=collections.defaultdict(list) +for k in t.kernels: byc[k.corr].append(k) +big=[c for c,v in byc.items() if len(v)>=900] +big.sort(key=lambda c:min(k.start for k in byc[c])) +big=big[2:-2] +fam=collections.defaultdict(lambda:[0,0.0]) +spans=[] +for c in big: + ks=byc[c]; spans.append((max(k.end for k in ks)-min(k.start for k in ks))/1e6) + for k in ks: + n=t.names.get(k.name,str(k.name)) if hasattr(t,"names") else k.name + fam[n][0]+=1; fam[n][1]+=(k.end-k.start)/1e3 +N=len(big) +print("verify graphs",N,"mean span ms %.3f"%statistics.mean(spans)) +for n,(c,us) in sorted(fam.items(),key=lambda x:-x[1][1])[:45]: + print("%-44s %6.1f/graph %8.3f ms/graph %7.2f us"%(n,c/N,us/N/1e3,us/c)) +print("TOTAL kernel ms/graph %.3f count %.0f"%(sum(v[1] for v in fam.values())/N/1e3,sum(v[0] for v in fam.values())/N)) diff --git a/scripts/e2e/codex/speed/kernel_roles.py b/scripts/e2e/codex/speed/kernel_roles.py new file mode 100644 index 00000000..ba4dcde7 --- /dev/null +++ b/scripts/e2e/codex/speed/kernel_roles.py @@ -0,0 +1,40 @@ +import re,sys,collections +RULES=[ + ("wait on CPU leg / flag waits", r"wait_flag_ge|chain_wait_copy"), + ("doorbell, mapped copies, fetch_blobs, hit tally", r"doorbell|copy_rows_from_mapped|copy_i32_from_mapped|copy_from_mapped|add_hits|rebase_ptrs|fetch_blobs|verify_copy|copy_indexed|^copy$|chain_copy"), + ("draft chain GR up/down/split/norm (MTP routed experts)", r"chain_gr|gr_down|gr_up|gr_norm_split|chain_scale_rows|chain_row_top|chain_sampler|mtp_scalar_gr|mtp_full|mtp_original|mtp_scalar|mtp_prefill|sampler|row_top_prob|mtp_select"), + ("verify routed experts (gate/up/swiglu, down, combine)", r"window_moe|moe_gu|native_gu_swiglu|native_down_multi|native_swiglu|native_q8_1_interleave|sigmoid_scale|combine|gu_grouped|down_grouped|verify_gu|swiglu"), + ("GDN (step/conv/ab/commit)", r"gdn|conv_residual|conv_l2"), + ("attention (decode/QSA/chunk/topk/merge/append)", r"qsa|attn|block_|^resolve$|^append|kv_append|norm_rope|rope|^copy$"), + ("dense MMVQ / MMVF / lm head (head_n*, mmvq, mmvf)", r"head_n|head_quant|head_embed|mmvq|mmvf|bf16_f32|native_small|quantize_q8_1|native_quantize|embed_rows|head_"), + ("norms, small, ple, misc", r".*"), +] +def load(p): + d=collections.OrderedDict() + for l in open(p).read().splitlines()[1:]: + f=l.split("\t") + if len(f)<4 or f[0]=="ALL kernels": continue + d[f[0]]=(float(f[1]),float(f[2])) + return d +def role(n): + for r,rx in RULES: + if re.search(rx,n): return r +def agg(d): + a=collections.defaultdict(lambda:[0,0.0]); + for n,(c,m) in d.items(): + r=role(n); a[r][0]+=c; a[r][1]+=m + return a +L=load(sys.argv[1]); V=load(sys.argv[2]) +aL,aV=agg(L),agg(V) +rows=[] +for r,_ in RULES: + rows.append((aL[r][1]-aV[r][1],r,aL[r],aV[r])) +rows.sort(reverse=True) +print("%-58s %8s %8s %8s %7s %7s"%("role","LEL ms","VANL ms","diff ms","LELcnt","VANcnt")) +for d,r,l,v in rows: print("%-58s %8.3f %8.3f %+8.3f %7.0f %7.0f"%(r,l[1],v[1],d,l[0],v[0])) +print("TOTAL", sum(x[1] for x in aL.values()), sum(x[1] for x in aV.values()), sum(x[0] for x in aL.values()), sum(x[0] for x in aV.values())) +if len(sys.argv)>3: + for n,(c,m) in L.items(): + if role(n)==sys.argv[3]: print("L",n,c,m) + for n,(c,m) in V.items(): + if role(n)==sys.argv[3]: print("V",n,c,m) diff --git a/scripts/e2e/codex/speed/ledger_counts.py b/scripts/e2e/codex/speed/ledger_counts.py new file mode 100644 index 00000000..6f77ad0c --- /dev/null +++ b/scripts/e2e/codex/speed/ledger_counts.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Counts of the status column of docs/experiments/step-ledger.md (offline tool, stdlib only): per status and per owner. + + ledger_counts.py [LEDGER.md] +""" +import collections +import re +import sys + +path = sys.argv[1] if len(sys.argv) > 1 else "docs/experiments/step-ledger.md" +by_status, by_owner = collections.Counter(), collections.Counter() +for line in open(path, encoding="utf-8"): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) < 6 or not re.fullmatch(r"[A-Z]\d+[a-z]?", cells[0]): + continue + status = cells[-1].split(" ")[0].split("(")[0] + by_status[status] += 1 + by_owner[(cells[-2], status)] += 1 +total = sum(by_status.values()) +print("rows: %d" % total) +for s in ("open", "fixing", "fixed", "proved-equal"): + print(" %-13s %d" % (s, by_status[s])) +for o in sorted({k[0] for k in by_owner}): + print("owner %-10s " % o + ", ".join("%s %d" % (s, by_owner[(o, s)]) for s in ("open", "fixing", "fixed", "proved-equal"))) diff --git a/scripts/e2e/codex/speed/session_ctx_gap.py b/scripts/e2e/codex/speed/session_ctx_gap.py new file mode 100644 index 00000000..a7d51476 --- /dev/null +++ b/scripts/e2e/codex/speed/session_ctx_gap.py @@ -0,0 +1,28 @@ +import re,json,glob +root="/data/leleka-e2e/codex-compare/runs/main" +B=[(0,30000),(30000,60000),(60000,100000),(100000,160000),(160000,10**9)] +def cells(arm,task): return [c for c in sorted(glob.glob(f"{root}/{arm}/{task}-r*")) if not c.endswith(".out")] +def lel(c): + for l in open(c+"/engine-slice.log",errors="replace"): + if l.startswith("{") and '"ev":"request"' in l and '"comp":"engine"' in l: + j=json.loads(l); yield j["ptok"],j["otok"],j["dec_ms"],j["pf_ms"] +def van(c): + for l in open(c+"/engine-slice.log",errors="replace"): + m=re.search(r"prompt (\d+) tokens = (\d+) reused \+ (\d+) read in ([\d.]+) ms.*?(\d+) generated in ([\d.]+) ms",l) + if m: yield int(m.group(1)),int(m.group(5)),float(m.group(6)),float(m.group(4)) +for task in ("nestng-crm","ttt"): + res={} + for arm,f in (("LEL",lel),("VANL",van)): + acc={b:[0,0,0,0] for b in B} + for c in cells(arm,task): + for p,o,d,pf in f(c): + for b in B: + if b[0]<=p/-r (tasks ttt and nestng-crm) the proxy log `proxy/rounds.jsonl` gives per request the wall time in the proxy (t_end - t_start), +the output tokens and the pause before the next request (tool execution + Codex); the engine log of the stack, sliced from `engine_log_start_offset` of the cell, gives the +engine's own prefill and decode milliseconds (LEL: JSON `request` events; vanilla: `strata serve: prompt N tokens = R reused + P read in X ms ..., G generated in Y ms` lines). +The two are joined by order. Printed per variant and task: mean ms per request of proxy time, prefill, decode, remainder (= proxy - prefill - decode: tokenizer, HTTP, prefix-cache +work, SSE, response end), pause between requests, and the same per output token. +""" +import glob +import json +import os +import re +import sys + +VAN = re.compile(r"strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms.*?, (\d+) generated in (\d+) ms") + + +def engine_events(path, offset, variant, n): + out = [] + with open(path, "rb") as f: + f.seek(offset) + for raw in f: + line = raw.decode("utf-8", "replace") + if variant == "LEL": + if '"ev":"request"' in line and '"comp":"engine"' in line: + j = json.loads(line) + out.append({"ptok": j["ptok"], "cached": j["ctok"], "otok": j["otok"], "pf": j["pf_ms"], "dec": j["dec_ms"]}) + else: + m = VAN.search(line) + if m: + out.append({"ptok": int(m[1]) , "cached": int(m[2]), "otok": int(m[5]), "pf": float(m[4]), "dec": float(m[6])}) + if len(out) >= n: + break + return out + + +def cell(d, variant): + rounds = [json.loads(l) for l in open(os.path.join(d, "proxy", "rounds.jsonl"))] + rounds = [r for r in rounds if r.get("path", "").endswith("/responses") and r.get("status") == 200] + info = json.load(open(os.path.join(d, "cell.json"))) + rep = info["rep"] + stack = os.path.join(os.path.dirname(d), "stack-r%s" % rep) + ev = engine_events(os.path.join(stack, "engine.log"), info["engine_log_start_offset"], variant, len(rounds)) + return rounds, ev, info + + +def buckets(root, variants): + """Engine decode tok/s and prefill ms per request by prompt size (ptok, both tasks together), pause excluded.""" + edges = [0, 20000, 40000, 70000, 100000, 10**9] + print("prompt tokens bucket | " + " | ".join("%s: n, dec tok/s, pf ms/req, uncached/req" % v for v in variants)) + acc = {v: [dict(n=0, o=0, d=0.0, p=0.0, u=0) for _ in edges[:-1]] for v in variants} + for v in variants: + for d in sorted(glob.glob(os.path.join(root, v, "*-r[0-9]"))): + if not os.path.basename(d).startswith(("ttt", "nestng-crm")): + continue + rounds, ev, _ = cell(d, v) + if len(ev) != len(rounds): + continue + for e in ev: + if e["ptok"] < 200: + continue + for i in range(len(edges) - 1): + if edges[i] <= e["ptok"] < edges[i + 1]: + a = acc[v][i] + a["n"] += 1; a["o"] += e["otok"]; a["d"] += e["dec"]; a["p"] += e["pf"]; a["u"] += e["ptok"] - e["cached"] + for i in range(len(edges) - 1): + cols = [] + for v in variants: + a = acc[v][i] + cols.append("%4d %6.1f %6.0f %6.0f" % (a["n"], a["o"] / a["d"] * 1e3 if a["d"] else 0, a["p"] / a["n"] if a["n"] else 0, a["u"] / a["n"] if a["n"] else 0)) + print("%6d-%-9d | %s" % (edges[i], edges[i + 1], " | ".join(cols))) + + +def main(): + if sys.argv[1] == "--buckets": + return buckets(sys.argv[2], sys.argv[3:]) + root, variants = sys.argv[1], sys.argv[2:] + for v in variants: + for task in ("nestng-crm", "ttt"): + agg = dict(n=0, proxy=0.0, pf=0.0, dec=0.0, pause=0.0, otok=0, ptok=0, uncached=0, cells=0, mismatch=0, pausen=0, wall=0.0, first=0.0) + for d in sorted(glob.glob(os.path.join(root, v, task + "-r[0-9]"))): + rounds, ev, info = cell(d, v) + if len(ev) != len(rounds): + agg["mismatch"] += 1 + continue + agg["cells"] += 1 + agg["wall"] += info["wall_s"] * 1e3 + agg["first"] += rounds[0]["t_start_ms"] + for i, (r, e) in enumerate(zip(rounds, ev)): + agg["n"] += 1 + agg["proxy"] += r["t_end_ms"] - r["t_start_ms"] + agg["pf"] += e["pf"] + agg["dec"] += e["dec"] + agg["otok"] += r["resp"]["output_tokens"] if r.get("resp") else e["otok"] + agg["ptok"] += e["ptok"] + agg["uncached"] += e["ptok"] - e["cached"] + if i + 1 < len(rounds): + agg["pause"] += rounds[i + 1]["t_start_ms"] - r["t_end_ms"] + agg["pausen"] += 1 + n = agg["n"] + if not n: + print(v, task, "no joined cells (order mismatch in %d)" % agg["mismatch"]) + continue + rest = agg["proxy"] - agg["pf"] - agg["dec"] + print("%-5s %-10s cells %d requests %3d | per request ms: proxy %7.0f = prefill %6.0f + decode %6.0f + rest %5.0f | pause %6.0f | per cell: wall %5.0f s, model %5.0f s, pauses %5.0f s | out tok/req %5.1f, uncached/req %6.0f | ms/out tok: proxy %.2f pf %.2f dec %.2f rest %.2f | proxy tok/s %.1f, engine decode tok/s %.1f" % ( + v, task, agg["cells"], n, agg["proxy"] / n, agg["pf"] / n, agg["dec"] / n, rest / n, agg["pause"] / max(agg["pausen"], 1), + agg["wall"] / agg["cells"] / 1e3, agg["proxy"] / agg["cells"] / 1e3, agg["pause"] / agg["cells"] / 1e3, agg["otok"] / n, agg["uncached"] / n, + agg["proxy"] / agg["otok"], agg["pf"] / agg["otok"], agg["dec"] / agg["otok"], rest / agg["otok"], agg["otok"] / agg["proxy"] * 1e3, agg["otok"] / agg["dec"] * 1e3)) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/speed/spd_ab_job.sh b/scripts/e2e/codex/speed/spd_ab_job.sh index 0b2bdb5c..359de42a 100644 --- a/scripts/e2e/codex/speed/spd_ab_job.sh +++ b/scripts/e2e/codex/speed/spd_ab_job.sh @@ -35,11 +35,15 @@ CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib FD=${LELEKA_STRA169_KAR_FD:-} mkdir -p "$RUN" exec > >(tee -a "$RUN/job-$(date -u +%H%M%S).log") 2>&1 +DRT=/data/leleka-e2e/draft-round; WIN_S=${SPD_WIN_S:-15}; TRIG_AT=${SPD_TRIG_AT:-28} +# fire one CUPTI window as soon as the replay output file has $4 lines (the next request starts at once) +spd_watch() { for _ in $(seq 1 30000); do n=$(wc -l <"$1" 2>/dev/null || echo 0); if [ "${n:-0}" -ge "$4" ]; then printf '{"seconds": %s, "out": "%s/win-r%s", "label": "r%s"} +' "$WIN_S" "$3" "$((n+1))" "$((n+1))" >"$2.tmp" && mv "$2.tmp" "$2"; return; fi; sleep 0.2; done; } log() { echo "[spd $(date -u +%T)] $*"; } note() { echo "[$(date -u +%FT%TZ)] [DEV spd-gap] $*" >>/data/leleka-e2e/decode/notes.md; } readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || { echo "needs the holder's sealed memfd"; exit 3; } [ -d "$G/MODEL.lock" ] || { echo "MODEL.lock is not held"; exit 3; } -P=$CMP/ours-pkg; AS=$CMP/ours-assets; ST=$CMP/ours-state; PFX=$CMP/ours-prefix; BIN=$P/bin +P=$CMP/ours-pkg; AS=$CMP/ours-assets; ST=$CMP/ours-state; PFX=$CMP/ours-prefix; BIN=${SPD_BIN:-$P/bin} [ -x "$BIN/leleka" ] && [ -f "$ST/leleka.json" ] || { echo "the codex-compare release state is not prepared"; exit 3; } got=0; for _ in $(seq 1 4320); do if mkdir "$LOCK" 2>/dev/null; then echo "spd-gap $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi; sleep 5; done [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; } @@ -54,7 +58,7 @@ COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $ for v in $VARS; do D=$RUN/$v; mkdir -p "$D"; vb=${v%%.*} [ -f "$D/replay.jsonl" ] && { log "variant $v already done: skipped"; continue; } - unset LELEKA_ORIGINAL_SERVE_ADAPT_EVERY LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_ORIGINAL_SERVE_PCIE_FRAC LELEKA_SERVE_PROFILE STRATA_VERIFY_PROFILE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_FLOOR_CEILING LELEKA_SPEC_STATS + unset CUDA_INJECTION64_PATH LELEKA_CUPTI_TRIGGER LCT_MAX_SECONDS LELEKA_ADAPT_TIE_SPREAD LELEKA_ADAPT_DECAY LELEKA_ADAPT_MARGIN LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS LELEKA_REFILL_DEFER LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB LELEKA_BRINGUP_TRACE LELEKA_PREFILL_PROFILE_SYNC LELEKA_ORIGINAL_SERVE_ADAPT_EVERY LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_SIDE_QSA LELEKA_SM120_SIDE_SHARED LELEKA_ORIGINAL_SERVE_PCIE_FRAC LELEKA_SERVE_PROFILE STRATA_VERIFY_PROFILE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_FLOOR_CEILING LELEKA_SPEC_STATS FLOOR=""; UPX="" case $vb in A) ;; @@ -65,7 +69,20 @@ for v in $VARS; do C) export LELEKA_SPEC_ADAPTIVE=off LELEKA_SPEC=4;; D) FLOOR=0.5;; G) UPX="--gpu-budget-gib 31";; + H) export LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130 LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB=500;; # lever 3 upper bound: -370 MiB of reserve = about +190 expert slots (G, a larger --gpu-budget-gib, gained none: the card binds, not the budget) + W1) export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2;; # tier screening: swap round every 2 verify rounds (default 4) + W2) export LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS=192;; # up to 192 swaps per round (default 96) + W3) export LELEKA_ADAPT_DECAY=0.85;; # longer memory of the routing counts (default 0.7) + W4) export LELEKA_ADAPT_MARGIN=1.0;; # swap on a smaller count lead (default 1.5) + X) export LELEKA_ADAPT_TIE_SPREAD=on;; # equal-gain swaps share the 96-swap cap across layers (needs a binary with the switch: SPD_BIN) + C|CL|CM|CN|CE|CT) [ "$vb" != C ] && export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1; [ "$vb" = CM ] && export LELEKA_SM120_SIDE_MIXER=1; { [ "$vb" = CN ] || [ "$vb" = CT ]; } && export LELEKA_SM120_SIDE_QSA=1; { [ "$vb" = CE ] || [ "$vb" = CT ]; } && export LELEKA_SM120_SIDE_SHARED=1; export CUDA_INJECTION64_PATH=$DRT/tools/libleleka_cupti_trace.so LELEKA_CUPTI_TRIGGER=$D/cupti.trigger LCT_MAX_SECONDS=60 LD_LIBRARY_PATH=$DRT/cupti/lib:$LD_LIBRARY_PATH;; # one CUPTI kernel window (WIN_S seconds) over request SPD_TRIG_AT of the replay; a profiling run, never an A/B arm P) export LELEKA_SERVE_PROFILE=1 STRATA_VERIFY_PROFILE=1;; + Q) export LELEKA_SERVE_PROFILE=1 LELEKA_BRINGUP_TRACE=1 LELEKA_PREFILL_PROFILE_SYNC=1;; # per-stage prefill timing (not for A/B pairs: the sync drains change timings) + M) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1;; + N) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_QSA=1;; # L + the QSA indexer/query chains on side streams (needs SPD_BIN with the switch) + E) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_SHARED=1;; # L + the shared expert on a side stream + T) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1;; # both # L + the verify graph's side streams (SIDE_MIXER); base of the pair is L + R) export LELEKA_REFILL_DEFER=on;; # lever 5: the lent-slot refill queued inside the decode phase's assembly (same copies, other time) S) export LELEKA_ROUTE_TAIL_SKIP=7 LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100;; T*) export LELEKA_ROUTE_TAIL_SKIP=7 LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100; p=${vb#T}; p=${p%[a-z]}; [ "$p" != 45 ] && export LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.$p;; KA*) export LELEKA_ROUTE_TAIL_SKIP=7 LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100 LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1;; @@ -97,8 +114,12 @@ for v in $VARS; do done touch "$D/replay.jsonl" else + case $vb in C|CL|CM|CN|CE|CT) cupti_arm=1;; *) cupti_arm=0;; esac + if [ $cupti_arm = 1 ]; then spd_watch "$D/replay.jsonl" "$D/cupti.trigger" "$D" "$TRIG_AT" & WATCH_PID=$!; fi python3 -I "$SPD/tools/replay_hash.py" "${args[@]}" --url http://127.0.0.1:8081 --model qwen-iq3 --key-file "$ST/api-key" --out "$D/replay.jsonl" --max-requests "$MAXR" >"$D/replay.out" 2>&1 log "replay rc=$? $(wc -l <"$D/replay.jsonl") requests" + case $vb in C|CL|CM|CN|CE|CT) cupti_arm=1;; *) cupti_arm=0;; esac + if [ $cupti_arm = 1 ]; then for _ in $(seq 1 60); do [ -e "$D/cupti.trigger.done" ] && break; sleep 1; done; kill "$WATCH_PID" 2>/dev/null; fi fi cp "$ST/logs/engine.log" "$D/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$D/requests.log" 2>/dev/null stop_stack; kill "$MON_PID" 2>/dev/null; MON_PID= diff --git a/scripts/e2e/codex/speed/spd_van_job2.sh b/scripts/e2e/codex/speed/spd_van_job2.sh new file mode 100644 index 00000000..81cb23eb --- /dev/null +++ b/scripts/e2e/codex/speed/spd_van_job2.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Vanilla Strata 0.2.6 on the same recorded prompts as spd_replay_job.sh, with the verifier step profile on (STRATA_VERIFY_PROFILE=1), for the step-by-step comparison with the release +# (docs/experiments/codex-compare-speed-gap.md). Holder-free window payload (started by spd_window.sh). Test tooling, never in serving. +# SPD_LOSSY=0 (default) lossy defaults off (VANL); 1 = shipped defaults (VAN) SPD_MAX (requests per cell, default 30) SPD_CELLS SPD_RUN (result dir) +set -uo pipefail +SPD=/data/leleka-e2e/spd-gap +CMP=/data/leleka-e2e/codex-compare +A=/home/para/work/leleka/models/leleka-gates/assets +G=$HOME/work/gpu-runs +LOCK=/data/leleka-e2e/gpu.lock +LOSSY=${SPD_LOSSY:-0} +RUN=${SPD_RUN:-$SPD/runs/main/V$([ "$LOSSY" = 1 ] && echo AN || echo ANL)} +CELLS=${SPD_CELLS:-"$CMP/runs/main/VANL/nestng-crm-r2"} +MAXR=${SPD_MAX:-30} +mkdir -p "$RUN" +exec > >(tee -a "$RUN/job.log") 2>&1 +log() { echo "[spd-van $(date -u +%T)] $*"; } +mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held (holder still up?)"; exit 3; } +got=0; for _ in $(seq 1 4320); do if mkdir "$LOCK" 2>/dev/null; then echo "spd-gap vanilla $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi; sleep 5; done +[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; rmdir "$G/MODEL.lock"; exit 3; } +S=$HOME/work/vanilla-strata/control/bin/strata +cleanup() { ( cd "$HOME/work/vanilla-strata/control" && "$S" launch --stop >/dev/null 2>&1 ); sleep 5; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; rmdir "$G/MODEL.lock" 2>/dev/null; } +trap cleanup EXIT +[ -z "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ] || { echo "something uses the GPU"; exit 3; } +export XDG_CONFIG_HOME=$RUN/xdg-config XDG_STATE_HOME=$RUN/xdg-state +mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"; cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/" +if [ "$LOSSY" = 1 ]; then unset STRATA_ROUTE_TAIL_SKIP STRATA_PREFILL_CPU_SHARE; else export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; fi +if [ "${SPD_CUPTI:-0}" = 1 ]; then # a kernel window over one request of the replay: no engine-side profile (it costs vanilla about 20 % decode) + DRT=/data/leleka-e2e/draft-round; WIN_S=${SPD_WIN_S:-15}; TRIG_AT=${SPD_TRIG_AT:-28} + export CUDA_INJECTION64_PATH=$DRT/tools/libleleka_cupti_trace.so LELEKA_CUPTI_TRIGGER=$RUN/cupti.trigger LCT_MAX_SECONDS=60 LD_LIBRARY_PATH=$DRT/cupti/lib:${LD_LIBRARY_PATH:-} +else + export STRATA_VERIFY_PROFILE=1 + export STRATA_DECODE_TIMING=1 # the serve path prints "strata decode GPU stages" only with it +fi +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +cd "$HOME/work/vanilla-strata/control" +t0=$(date +%s) +timeout 2400 "$S" launch --model iq3_s --family qwen --model-path "$A/model" --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes >"$RUN/launch.out" 2>&1 +log "launch rc=$? ready after $(( $(date +%s) - t0 )) s" +curl -fs http://127.0.0.1:8090/v1/models >"$RUN/models.json" || { log "vanilla did not become ready"; exit 4; } +MODEL=$(python3 -c "import json;print(json.load(open('$RUN/models.json'))['data'][0]['id'])") +args=(); for c in $CELLS; do args+=(--cell "$c"); done +if [ "${SPD_CUPTI:-0}" = 1 ]; then + ( for _ in $(seq 1 30000); do n=$(wc -l <"$RUN/replay.jsonl" 2>/dev/null || echo 0); if [ "${n:-0}" -ge "$TRIG_AT" ]; then printf '{"seconds": %s, "out": "%s/win-r%s", "label": "r%s"} +' "$WIN_S" "$RUN" "$((n+1))" "$((n+1))" >"$RUN/cupti.trigger.tmp" && mv "$RUN/cupti.trigger.tmp" "$RUN/cupti.trigger"; break; fi; sleep 0.2; done ) & + WATCH_PID=$! +fi +python3 -I "$SPD/tools/replay_fwd.py" "${args[@]}" --url http://127.0.0.1:8090 --model "$MODEL" --out "$RUN/replay.jsonl" --max-requests "$MAXR" >"$RUN/replay.out" 2>&1 +log "replay rc=$? $(wc -l <"$RUN/replay.jsonl") requests" +if [ "${SPD_CUPTI:-0}" = 1 ]; then for _ in $(seq 1 60); do [ -e "$RUN/cupti.trigger.done" ] && break; sleep 1; done; kill "$WATCH_PID" 2>/dev/null; fi +cp "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "$RUN/engine.log" 2>/dev/null +log "done"