From 3e68def28efd4f565e24bb7e07f10d6a67c4af70 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 9 Nov 2026 23:16:19 +0100 Subject: [PATCH 1/2] decode graph reuse (Q7), part 1: LELEKA_DECODE_GRAPH_REUSE (off), key and policy tested on the lifecycle fake, shared-expert pin and weights epoch; assembly borrow and re-arm API documented as blocked DecodeGraphKey (shape, tier, pcie mode, cluster top-k, weights and owners epochs) and GraphReuse hand a kept assembly out only for an equal key after Reusable::rearm accepted the new request's seed; anything else retires it and records. The lifecycle fake bakes key and seed into its graph set and fails a stale replay: kept and re-recorded sets give the same text, each key input forces a re-record, a refused re-arm and a failed request do not replay. MoeWeightCache gets pin_for_window / unpin_window / weights_epoch (not wired). With the switch on, open states that the stack cannot keep the graphs yet; every request records as before. Not done: the assembly still borrows the stack (needs handles instead of &'a DeviceBuffer in original_verify_window_{moe,gr,proj,qsa}), the QSA owner loan and the MTP binding follow it, and the verify bank's re-arm API is the speed session's. Exact changes in docs/experiments/decode-graph-reuse.md. No speedup claim. Co-Authored-By: Claude Sonnet 5.5 --- .../src/backend/lifecycle_tests.rs | 1 + .../src/backend/lifecycle_tests/graphs.rs | 113 +++++++ .../src/qwen_forward/moe_weight_cache.rs | 6 + .../moe_cache_mmq_constructors.rs | 2 + .../moe_cache_shared_tail_constructors.rs | 3 + .../moe_cache_triplet_plan_upload.rs | 1 + .../moe_cache_validate_prepare_step.rs | 1 + .../moe_weight_cache/window_pins.rs | 39 +++ .../src/qwen_forward/original_serve_stack.rs | 3 + .../decode_graph_reuse.rs | 144 +++++++++ .../original_serve_stack/lifecycle_fake.rs | 2 + .../lifecycle_fake/graphs.rs | 87 ++++++ .../lifecycle_fake/stack.rs | 59 +++- .../original_serve_stack_open.rs | 3 + .../engine-qwen35-cuda/src/settings/serve.rs | 5 + .../src/settings/serve_tests.rs | 8 + docs/experiments/decode-graph-reuse.md | 288 ++++++++++++------ 17 files changed, 662 insertions(+), 103 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/backend/lifecycle_tests/graphs.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/window_pins.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/decode_graph_reuse.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/graphs.rs diff --git a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs index 81afe230..35ef7acd 100644 --- a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs @@ -12,6 +12,7 @@ use crate::qwen_forward::original_serve_stack::lifecycle_fake::{FakeDevice, Fake use leleka_obs::time::ManualClock; mod ends; +mod graphs; mod prefix; /// An id the model never produces: no request stops on it. diff --git a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/graphs.rs b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/graphs.rs new file mode 100644 index 00000000..4344250a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/graphs.rs @@ -0,0 +1,113 @@ +//! The decode graphs under the lifecycle (ledger row Q7, `LELEKA_DECODE_GRAPH_REUSE`): a kept graph set gives the same +//! text as re-recording, costs no recording, and is replaced - never replayed - when anything it was recorded over +//! changed. +use super::*; +use crate::qwen_forward::original_serve_stack::decode_graph_reuse::{Armed, DecodeGraphKey, Why}; + +/// What recording the graph set costs on the manual clock. +const RECORD_MS: u64 = 90; + +impl Rig { + fn with_graphs(self, enabled: bool) -> Self { + Self { stack: self.stack.with_graph_reuse(enabled, RECORD_MS), ..self } + } + + /// Runs `count` requests with different prompts: the text of each, and the decode milliseconds of each. + fn requests(&mut self, count: usize) -> (Vec, Vec) { + let (mut texts, mut decode_ms) = (Vec::new(), Vec::new()); + for i in 0..count { + let p = prompt_of(300 + 10 * i, i); + let run = self.run(&p, 12, NO_EOS); + assert_eq!(run.text, expect(&p, 12), "request {i}"); + texts.push(run.text); + decode_ms.push(self.stack.last_timing().1); + } + (texts, decode_ms) + } +} + +fn rig(enabled: bool) -> Rig { + Rig::new(Script::default(), false).with_graphs(enabled) +} + +#[test] +fn with_the_switch_off_every_request_records_its_graphs() { + let mut rig = rig(false); + let (_, decode_ms) = rig.requests(3); + assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (3, 0)); + assert_eq!(decode_ms, [90.0; 3]); + assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::Disabled))); + assert!(!rig.stack.graphs().is_held()); +} + +#[test] +fn a_kept_graph_set_gives_the_text_of_re_recording_and_costs_no_recording() { + let (mut kept, mut fresh) = (rig(true), rig(false)); + let (kept_text, kept_ms) = kept.requests(4); + let (fresh_text, _) = fresh.requests(4); + assert_eq!(kept_text, fresh_text, "the same text per request"); + assert_eq!((kept.stack.graphs().recordings, kept.stack.graphs().reuses), (1, 3)); + assert_eq!(kept_ms, [90.0, 0.0, 0.0, 0.0], "only the first request records"); + assert_eq!(kept.dev.digest(), fresh.dev.digest(), "the device ends in the same state"); + assert_eq!(kept.log("graphs"), ["graphs recorded: NothingHeld", "graphs reused", "graphs reused", "graphs reused"]); +} + +/// The inputs of the key, by the name `first_difference` gives them. +const INPUTS: [&str; 7] = + ["max_t", "max_cells", "pcie_mode", "expert tier", "cluster top-k", "weights epoch", "owners epoch"]; + +/// Changes the named input of the key. +fn change(name: &str, k: &mut DecodeGraphKey) { + match name { + "max_t" => k.max_t -= 1, + "max_cells" => k.max_cells *= 2, + "pcie_mode" => k.pcie_mode = 2, + "expert tier" => k.tier = true, + "cluster top-k" => k.cluster_topk = false, + "weights epoch" => k.weights_epoch += 1, + _ => k.owners_epoch += 1, + } +} + +#[test] +fn a_changed_input_of_the_key_forces_a_re_record_and_the_new_set_is_kept_again() { + for name in INPUTS { + let mut rig = rig(true); + rig.requests(1); + change(name, rig.stack.graph_key()); + let p = prompt_of(333, 7); + assert_eq!(rig.run(&p, 12, NO_EOS).text, expect(&p, 12), "{name}"); + assert_eq!(rig.stack.graphs().recordings, 2, "{name}"); + assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::KeyChanged(name))), "{name}"); + rig.run(&prompt_of(344, 8), 12, NO_EOS); + assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (2, 1), "{name}: kept for the new key"); + } +} + +#[test] +fn a_set_that_refuses_to_be_re_armed_is_recorded_again_not_replayed() { + let mut rig = rig(true); + rig.stack.graphs().refuse_rearm = true; + rig.requests(1); + rig.stack.graphs().refuse_rearm = false; + let (texts, _) = rig.requests(2); + assert_eq!(texts.len(), 2); + assert_eq!(rig.stack.graphs().recordings, 2, "the second request records; the third replays that recording"); + assert_eq!(rig.stack.graphs().reuses, 1); + assert_eq!(rig.log("graphs")[1], "graphs recorded: RearmRefused"); +} + +#[test] +fn a_request_that_fails_or_is_cancelled_does_not_keep_its_graphs() { + let mut rig = Rig::new(Script { fail_round: Some(0), ..Script::default() }, false).with_graphs(true); + let p = prompt(300); + assert!(matches!(rig.run(&p, 12, NO_EOS).ended, Ended::Failed(..))); + assert!(!rig.stack.graphs().is_held()); + let run = rig.run(&p, 12, NO_EOS); + assert_eq!(run.text, expect(&p, 12)); + assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::NothingHeld))); + assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (2, 0)); + assert!(rig.stack.graphs().is_held(), "the clean request keeps its set"); + rig.stack.graphs().invalidate(); + assert!(!rig.stack.graphs().is_held()); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index bd642621..97a23c55 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -170,6 +170,9 @@ pub(crate) struct MoeWeightCache<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] adaptive_shared: Option, age: u64, + /// The entries a held decode graph set reads in place (`window_pins`), and how many raw entries were evicted. + window_pins: std::collections::HashSet, + raw_evictions: u64, failed: Cell, bank: Option>>, dense: Vec>, @@ -351,6 +354,9 @@ pub(in crate::qwen_forward) use original_mtp_weights::{MtpHeadSources, RetainedO mod validate_ranked_profile; #[allow(unused_imports)] +// pinning and the epoch are read by the decode graph reuse, which the stack does not wire yet +#[allow(dead_code)] +mod window_pins; use validate_ranked_profile::dual_layout; #[allow(unused_imports)] use validate_ranked_profile::integer_iq3_triplet; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_mmq_constructors.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_mmq_constructors.rs index acb458ec..91def268 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_mmq_constructors.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_mmq_constructors.rs @@ -30,6 +30,8 @@ macro_rules! blank_cache { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] adaptive_shared: None, age: 0, + window_pins: Default::default(), + raw_evictions: 0, failed: Cell::new(false), bank: None, dense: Vec::new(), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_shared_tail_constructors.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_shared_tail_constructors.rs index a4c0f240..92ea856c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_shared_tail_constructors.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_shared_tail_constructors.rs @@ -139,6 +139,9 @@ impl<'ctx> MoeWeightCache<'ctx> { self.routed_workspace.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(in super::super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool { + if self.window_pins.contains(&key) { + return true; + } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if self.adaptive_shared.as_ref().is_some_and(|pool| pool.contains(key)) { return true; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_triplet_plan_upload.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_triplet_plan_upload.rs index bd058881..2e150ad7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_triplet_plan_upload.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_triplet_plan_upload.rs @@ -279,6 +279,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let key = self.eviction_key(protected)?; self.remove_lru_entry(key)?; let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; + self.note_eviction(&entry.weight); if entry.weight.close().is_err() { self.failed.set(true); return Err(Error::CudaExecution); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_validate_prepare_step.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_validate_prepare_step.rs index 17810b85..a4ffe70c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_validate_prepare_step.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/moe_weight_cache_methods/moe_cache_validate_prepare_step.rs @@ -72,6 +72,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let key = self.eviction_key(&[])?; self.remove_lru_entry(key)?; let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; + self.note_eviction(&entry.weight); if entry.weight.close().is_err() { self.failed.set(true); return Err(Error::CudaExecution); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/window_pins.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/window_pins.rs new file mode 100644 index 00000000..4449f7fd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/window_pins.rs @@ -0,0 +1,39 @@ +//! The shared experts a kept decode graph set reads in place (`LELEKA_DECODE_GRAPH_REUSE`, ledger row Q7). +//! +//! The window graphs hold the device addresses of the shared-expert tensors of all 48 layers. While a graph set is held +//! across requests the prompt path must not free them: `pin_for_window` makes the cache skip them when it needs room +//! (the same rule as the profile's permanent pool), and `raw_evictions` counts every raw entry the cache did free, so a +//! graph set recorded before such an eviction is never replayed (the count is part of the graph key's weights epoch). +use super::*; + +impl<'ctx> MoeWeightCache<'ctx> { + /// Keep the shared experts `keys` (from `ensure_original_verify_shared`) resident until `unpin_window`. + pub(in crate::qwen_forward) fn pin_for_window(&mut self, keys: &[[MoeWeightDescriptor; 4]]) -> Result<()> { + if keys.iter().flatten().any(|key| !self.main.contains_key(key)) { + return Err(Error::IdentityMismatch); + } + self.window_pins.extend(keys.iter().flatten().copied()); + Ok(()) + } + + /// Release the pins: the entries can be evicted again, so a graph set that read them is no longer replayable. + pub(in crate::qwen_forward) fn unpin_window(&mut self) { + if !self.window_pins.is_empty() { + self.window_pins.clear(); + self.raw_evictions = self.raw_evictions.wrapping_add(1); + } + } + + /// Raw entries freed so far, plus the pins released: unchanged between two requests means every address a window + /// graph read is still the same live buffer. + pub(in crate::qwen_forward) fn weights_epoch(&self) -> u64 { + self.raw_evictions + } + + /// Account an entry the cache is about to free (the window reads raw entries only). + pub(super) fn note_eviction(&mut self, weight: &EncodedWeight<'ctx>) { + if matches!(weight, EncodedWeight::Raw(_)) { + self.raw_evictions = self.raw_evictions.wrapping_add(1); + } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index 7a27e767..a1c47d84 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -233,6 +233,9 @@ mod tests; #[cfg(test)] pub(crate) mod lifecycle_fake; +// The reuse policy ahead of its stack wiring (see its module doc): driven by the lifecycle fake until then. +#[allow(dead_code)] +pub(crate) mod decode_graph_reuse; mod stack_groups; use stack_groups::{RequestState, ServePolicy, TierState}; mod stack_config_and_ttft_marks; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/decode_graph_reuse.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/decode_graph_reuse.rs new file mode 100644 index 00000000..a598e8cc --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/decode_graph_reuse.rs @@ -0,0 +1,144 @@ +//! When the assembled decode graphs may be kept for the next request (`LELEKA_DECODE_GRAPH_REUSE`, off by default; +//! docs/experiments/decode-graph-reuse.md). +//! +//! A captured graph holds the device and mapped-host ADDRESSES of every buffer its kernels touch, never the data, so a +//! graph set recorded for one request replays correctly in the next only when every address and every shape it was +//! recorded over is the same. `DecodeGraphKey` names those inputs; `GraphReuse` keeps one assembly together with the +//! key it was recorded for and hands it out again only for an equal key, after the assembly agreed to be re-armed with +//! the new request's seed. Anything else - a changed key, a refused re-arm, a request that did not end cleanly - +//! retires the held assembly and records a new one. There is no path that replays a graph set for a key it was not +//! recorded for. +//! +//! `Reusable::rearm` is the contract of the verify bank's re-arm API (`reset_for_new_request`, the part of the feature +//! that lives in the speed session's files); the lifecycle fake implements it, the real assembly does not yet, so the +//! stack states at `open` that the switch is refused and records every request as before. + +use std::mem; + +/// Everything the recorded decode graphs are specific to. Two requests may share a recording only when their keys are +/// equal. The two epochs are counters of the owners of the physical buffers: each owner bumps its counter whenever it +/// frees, moves or reallocates a buffer a window graph reads or writes in place (`MoeWeightCache::pin_epoch`, +/// the QSA journal's `OwnersFingerprint`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DecodeGraphKey { + /// The widest recorded window (a graph per T = 1..=`max_t`, plus the commit graph). + pub(crate) max_t: usize, + /// The cell budget the verifier arena and the QSA journals are sized for. + pub(crate) max_cells: usize, + /// How the window stages the PCIe share of the experts: 0 DMA, 2 copy kernel (baked into the graph). + pub(crate) pcie_mode: u8, + /// Whether a VRAM expert tier stands behind the windows. + pub(crate) tier: bool, + /// The decode top-k as a thread-block cluster, as resolved for the card (the graph holds the kernel choice). + pub(crate) cluster_topk: bool, + /// The shared experts and routers the windows read in place (MoE and dense caches). + pub(crate) weights_epoch: u64, + /// The twelve resident QSA index images and mapped K/V journals, the PLE history and the canonical GDN image. + pub(crate) owners_epoch: u64, +} + +impl DecodeGraphKey { + /// The name of the first input that differs from `other`, or `None` for equal keys. + pub(crate) fn first_difference(&self, other: &Self) -> Option<&'static str> { + let checks = [ + ("max_t", self.max_t != other.max_t), + ("max_cells", self.max_cells != other.max_cells), + ("pcie_mode", self.pcie_mode != other.pcie_mode), + ("expert tier", self.tier != other.tier), + ("cluster top-k", self.cluster_topk != other.cluster_topk), + ("weights epoch", self.weights_epoch != other.weights_epoch), + ("owners epoch", self.owners_epoch != other.owners_epoch), + ]; + checks.into_iter().find_map(|(name, differs)| differs.then_some(name)) + } +} + +/// A recorded decode assembly the policy can keep between requests. `S` is what the next request seeds it with (the +/// session's recurrent priors and PLE prior). +pub(crate) trait Reusable { + /// Make the assembly ready for the next request: drain both streams, reseed the canonical GDN image and the PLE + /// history in place, reset the bank's window state and every flag the graphs wait on. `false` refuses: the assembly + /// is then retired, never replayed. + fn rearm(&mut self, seed: &S) -> bool; +} + +/// Why a request got a freshly recorded assembly. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Why { + /// The switch is off. + Disabled, + /// Nothing was held (first request, or the previous one ended without releasing its assembly). + NothingHeld, + /// The held assembly was recorded for another key; the name of the first input that differs. + KeyChanged(&'static str), + /// The held assembly refused to be re-armed. + RearmRefused, +} + +/// How a request got its assembly. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Armed { + /// The assembly kept from the previous request, re-armed. + Reused, + /// A new recording. + Recorded(Why), +} + +/// One assembly kept between requests, with the key it was recorded for. +pub(crate) struct GraphReuse { + enabled: bool, + held: Option<(DecodeGraphKey, A)>, +} + +impl GraphReuse { + pub(crate) fn new(enabled: bool) -> Self { + Self { enabled, held: None } + } + + /// The assembly for a request over `key`: the held one when the key is equal and it re-arms with `seed`, else + /// `record()`'s. The held assembly is taken out in every case (a request owns its assembly while it runs). + pub(crate) fn acquire( + &mut self, + (key, seed): (&DecodeGraphKey, &S), + record: impl FnOnce() -> Result, + ) -> Result<(A, Armed), E> + where + A: Reusable, + { + let why = match self.held.take() { + _ if !self.enabled => Why::Disabled, + None => Why::NothingHeld, + Some((held_for, mut assembly)) => match held_for.first_difference(key) { + Some(name) => Why::KeyChanged(name), + None if assembly.rearm(seed) => return Ok((assembly, Armed::Reused)), + None => Why::RearmRefused, + }, + }; + record().map(|assembly| (assembly, Armed::Recorded(why))) + } + + /// The request ended cleanly: keep its assembly for the next one (a disabled policy drops it). + pub(crate) fn release(&mut self, key: &DecodeGraphKey, assembly: A) { + if self.enabled { + self.held = Some((*key, assembly)); + } + } + + /// Retire the held assembly (a lost owner, a reconfigure, a request that failed). + pub(crate) fn invalidate(&mut self) { + drop(mem::take(&mut self.held)); + } + + /// Whether an assembly is held. + pub(crate) fn is_held(&self) -> bool { + self.held.is_some() + } +} + +/// The one line `open` writes when the switch is on while the stack cannot keep an assembly yet. +pub(crate) fn refusal_line(requested: bool) -> Option<&'static str> { + requested.then_some( + "decode graph reuse (LELEKA_DECODE_GRAPH_REUSE) requested: refused, the verify bank has no re-arm API and the \ + assembly still borrows the stack (docs/experiments/decode-graph-reuse.md); every request records its graphs", + ) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs index 14f151ae..84943dc1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs @@ -21,10 +21,12 @@ use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +mod graphs; mod port; mod prefix; mod stack; +pub(crate) use graphs::GraphBook; pub(crate) use prefix::{FakeBlock, FakeState}; pub(crate) use stack::FakeStack; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/graphs.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/graphs.rs new file mode 100644 index 00000000..1b20140c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/graphs.rs @@ -0,0 +1,87 @@ +//! The decode graphs of the scripted device: what the reuse policy keeps between requests (test support only). +//! +//! `FakeGraphs` stands for the nine recorded window graphs and the commit graph. Recording costs `record_ms` on the +//! manual clock (the part of the request that `LELEKA_DECODE_GRAPH_REUSE` removes); a recording bakes the key it was +//! made for and the seed of its request, exactly as a captured graph bakes addresses, and a replay checks both, so a +//! graph set replayed for another key or without a re-arm fails the request instead of passing silently. +use super::super::decode_graph_reuse::{Armed, DecodeGraphKey, GraphReuse, Reusable}; +use crate::qwen_forward::contract::Error; + +/// What a request seeds the graphs with: the recurrent state the device stands at when its prompt is read. +pub(crate) type Seed = u64; + +/// A recorded graph set of the fake. +pub(crate) struct FakeGraphs { + baked: DecodeGraphKey, + seeded: Seed, + refuse_rearm: bool, +} + +impl FakeGraphs { + pub(crate) fn record(key: DecodeGraphKey, seed: Seed, refuse_rearm: bool) -> Self { + Self { baked: key, seeded: seed, refuse_rearm } + } + + /// The replay check of a captured graph: it runs only over the key it was recorded for, seeded for this request. + pub(crate) fn replay(&self, key: &DecodeGraphKey, seed: Seed) -> Result<(), Error> { + if self.baked != *key || self.seeded != seed { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} + +impl Reusable for FakeGraphs { + fn rearm(&mut self, seed: &Seed) -> bool { + if self.refuse_rearm { + return false; + } + self.seeded = *seed; + true + } +} + +/// The policy plus the counters a test reads. +pub(crate) struct GraphBook { + reuse: GraphReuse, + /// Graph sets recorded so far. + pub(crate) recordings: usize, + /// Requests that replayed a kept set. + pub(crate) reuses: usize, + /// The re-arm of the next kept set refuses. + pub(crate) refuse_rearm: bool, + /// How the last request got its graphs. + pub(crate) last: Option, +} + +impl GraphBook { + pub(crate) fn new(enabled: bool) -> Self { + Self { reuse: GraphReuse::new(enabled), recordings: 0, reuses: 0, refuse_rearm: false, last: None } + } + + /// The graphs for a request over `key` and `seed`: a kept set or a recording. + pub(crate) fn acquire(&mut self, key: &DecodeGraphKey, seed: Seed) -> Result<(FakeGraphs, Armed), Error> { + let (refuse, recordings) = (self.refuse_rearm, &mut self.recordings); + let record = || { + *recordings += 1; + Ok::<_, Error>(FakeGraphs::record(*key, seed, refuse)) + }; + let (graphs, armed) = self.reuse.acquire((key, &seed), record)?; + self.reuses += usize::from(armed == Armed::Reused); + self.last = Some(armed); + Ok((graphs, armed)) + } + + /// The request ended cleanly: its graphs are kept (when the switch is on). + pub(crate) fn release(&mut self, key: &DecodeGraphKey, graphs: FakeGraphs) { + self.reuse.release(key, graphs); + } + + pub(crate) fn invalidate(&mut self) { + self.reuse.invalidate(); + } + + pub(crate) fn is_held(&self) -> bool { + self.reuse.is_held() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs index 2fef8e9c..53151b20 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs @@ -1,9 +1,10 @@ //! `FakeStack`: the request-level seams of the stack over the scripted device. +use super::super::decode_graph_reuse::{Armed, DecodeGraphKey}; use super::super::{ PlanLimits, PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ResumePoint, ServeDevice, ServeError, ServeRequest, original_serve_residency, plan_error, run_request, }; -use super::{FakeBlock, FakeDevice, FakeState, GRID, VOCAB}; +use super::{CELLS, FakeBlock, FakeDevice, FakeState, GRID, GraphBook, VOCAB}; use crate::backend::original_prompt::PromptAction; use crate::qwen_forward::contract::Error; use crate::qwen_forward::original_serve_engine::{ @@ -24,6 +25,9 @@ pub(crate) struct FakeStack { max_context: i64, reused: usize, timing: (f64, f64), + graphs: GraphBook, + graph_key: DecodeGraphKey, + record_ms: u64, } impl FakeStack { @@ -45,9 +49,37 @@ impl FakeStack { max_context: 4096, reused: 0, timing: (0.0, 0.0), + graphs: GraphBook::new(false), + graph_key: DecodeGraphKey { + max_t: 4, + max_cells: CELLS, + pcie_mode: 0, + tier: false, + cluster_topk: true, + weights_epoch: 0, + owners_epoch: 0, + }, + record_ms: 0, } } + /// `LELEKA_DECODE_GRAPH_REUSE` on or off, and what recording the graph set costs on the manual clock. + pub(crate) fn with_graph_reuse(mut self, enabled: bool, record_ms: u64) -> Self { + self.graphs = GraphBook::new(enabled); + self.record_ms = record_ms; + self + } + + /// The policy's counters, and the switch for the next re-arm to refuse. + pub(crate) fn graphs(&mut self) -> &mut GraphBook { + &mut self.graphs + } + + /// The inputs the next request's graphs are keyed on (a test changes one between requests). + pub(crate) fn graph_key(&mut self) -> &mut DecodeGraphKey { + &mut self.graph_key + } + /// Checkpoint hits the prefix cache has counted. pub(crate) fn prefix_hits(&self) -> u64 { self.prefix.as_ref().map_or(0, |p| p.stats().hits) @@ -176,6 +208,29 @@ impl FakeStack { serve_request(&mut self.controller, &mut engine, speculative, callbacks) } + /// The graph set of the request (kept or recorded), the rounds over it, and the set kept again after a clean end. + fn decode_over_graphs( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>, + cancel: &mut dyn FnMut() -> bool, + ) -> Result { + let (key, seed) = (self.graph_key, self.dev.digest()); + let (graphs, armed) = self.graphs.acquire(&key, seed)?; + if let Armed::Recorded(why) = armed { + self.clock.advance_ms(self.record_ms); + self.dev.log(format!("graphs recorded: {why:?}")); + } else { + self.dev.log("graphs reused"); + } + graphs.replay(&key, seed)?; + let served = self.serve_rounds(request, emit, cancel); + if served.is_ok() { + self.graphs.release(&key, graphs); + } + served + } + fn prefix_resume(&mut self, request: &ServeRequest) -> Option { let prefix = self.prefix.as_mut()?; match prefix.begin(&mut self.dev, &request.prompt) { @@ -230,7 +285,7 @@ impl RequestOwners for FakeStack { cancel: &mut dyn FnMut() -> bool, ) -> Result { let started = self.clock.now(); - let result = self.serve_rounds(request, emit, cancel); + let result = self.decode_over_graphs(request, emit, cancel); self.timing.1 = self.clock.since(started).as_secs_f64() * 1e3; result } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_open.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_open.rs index 64a8e619..58ce3059 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_open.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_open.rs @@ -31,6 +31,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { this.register_memory_classes(); crate::memory_governor::post_open(); log_open_inventory(); + if let Some(line) = decode_graph_reuse::refusal_line(crate::settings::process().serve.decode_graph_reuse) { + operator_text(line); + } Ok(this) } } diff --git a/crates/engine-qwen35-cuda/src/settings/serve.rs b/crates/engine-qwen35-cuda/src/settings/serve.rs index 842bdbd6..4c8af0a4 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve.rs @@ -31,6 +31,10 @@ pub(crate) struct ServeSettings { /// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one /// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md). pub(crate) draft_chain_pipeline: bool, + /// `LELEKA_DECODE_GRAPH_REUSE` is `1` or `on`: keep the assembled decode graphs for the next request when nothing + /// they bake in changed (OFF by default; docs/experiments/decode-graph-reuse.md). The stack refuses the reuse + /// (and records every request, as without the switch) until the verify bank has its re-arm API. + pub(crate) decode_graph_reuse: bool, } impl ServeSettings { @@ -47,6 +51,7 @@ impl ServeSettings { cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"), prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]), draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]), + decode_graph_reuse: one_of(env, "LELEKA_DECODE_GRAPH_REUSE", &["1", "on"]), } } } diff --git a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs index bc9e8be9..0a3b959c 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs @@ -96,3 +96,11 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() { assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}"); } } + +#[test] +fn the_decode_graph_reuse_is_one_or_on_and_off_by_default() { + assert!(!serve(&[]).decode_graph_reuse); + for (value, want) in [("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("", false)] { + assert_eq!(serve(&[("LELEKA_DECODE_GRAPH_REUSE", value)]).decode_graph_reuse, want, "reuse {value:?}"); + } +} diff --git a/docs/experiments/decode-graph-reuse.md b/docs/experiments/decode-graph-reuse.md index d46120a8..5b14af52 100644 --- a/docs/experiments/decode-graph-reuse.md +++ b/docs/experiments/decode-graph-reuse.md @@ -1,101 +1,187 @@ -# Decode graph reuse across requests (ledger row Q7) - -Status: design only, no code committed. The reuse needs an ownership refactor (stack-independent assembly, QSA owner loan, a re-arm API in the verify bank / gpu plan, which is `original_verify_gpu_plan*`, owned by the speed-vs-strata session); see section 4 for why and the order of changes. No speedup claim. - -## 1. Why the graphs are recorded per request - -`decode_phase` (`OriginalServeStack`) calls `assemble_decode` -> `AssembleInputs::assemble` (`original_serve_verifier.rs`) for -every request, and `teardown_decode` -> `disassemble` at its end. `assemble` is: `prepare` (geometry, canonical GDN image -uploaded from the session's priors, QSA gamma), `OriginalVerifyQsaJournal::new` over the twelve QSA owners, then -`capture_verifier`: a new `OriginalVerifier` (new `Physical` arena, mapped allocations, two streams), one aggregate -(`OriginalVerifyWindowResources`) per T = 1..=max_t plus one for the commit graph, and `record_all` (nine graphs at T <= 8 -with the mode17 policy, 54-62 ms capture + 27-30 ms instantiate). `disassemble` closes the verifier (drains, drops every -graph and aggregate), which releases the aggregates' references to the QSA journal so `into_owners` can take the owners back, -and `release_mtp` drops the MTP drafter's programs bound to this verifier's bank. - -The recording is per request because of OWNERSHIP, not because the kernel arguments change: - -1. The QSA owners (twelve index images + mapped K/V journals) belong to the prompt executor. The next request's prefill - writes them (chunks, prefix-cache import, rollback). They can only get there by moving out of the journal - (`Rc::try_unwrap` in `into_owners`), which requires every graph that holds the journal to be gone. -2. The resources borrow the stack: `DecodeResources<'s, 'ctx>` holds `&'s DenseWeightCache`, `&'s MoeWeightCache`, - `&'s OriginalNativeOutput`, `&'s DeviceBuffer` (PLE history and scratch), `&SharedKeys` (a value of the request's own - stage). A value that borrows fields of `OriginalServeStack` cannot be stored in it (self-reference); this is why - `DecodeView` borrows the fields one by one. -3. The shared experts and routers are LRU entries of the MoE cache (`ensure_original_verify_shared`); the prompt path loads - layer by layer and may evict and reload them, so their device addresses are not guaranteed to survive a prefill. -4. The MTP drafter's round programs read the verifier's bank (final R span) and are released with it (`mtp_release_verifier`); - they are re-captured against the next bank (spans `draft.*`, a second cost of the same cause). - -`docs/decode-parity.md` already records this as "Verifier persistence: not done ... needs the executor to use the owners through -the journal". - -## 2. What the captured graphs point at - -Per-request buffers (created by `assemble`, addresses change every request today; data must be re-seeded if the buffer is kept): - -| Resource | Created in | Per request | Can be stable | -| --- | --- | --- | --- | -| Canonical GDN image (36 layers x 128*48*128 + 10240*3 f32, ~118 MB) | `prepare_assembly` (`original_verify_canonical_gdn(states, histories)`) | allocated and uploaded from the session priors | yes: keep the buffer, re-upload (118 MB H2D, stays in the per-request cost) | -| Verifier arena, `prof`, 15 mapped allocations, window modules | `OriginalVerifier::new` | new | yes: sized by `verify_geometry(max_t, max_cells, blobs)`; only the window state is data (`last_t`, `last_position`, `generation`, staged tokens) | -| Head rows per T, embedding rows per T, GDN journal, window aggregates | `aggregate()` | new | yes, part of the kept assembly | -| QSA journal `Rc` | `OriginalVerifyQsaJournal::new` | new Rc around the executor's buffers | the buffers are the executor's (fixed addresses); the Rc must outlive requests | -| Graphs, streams, event | `record_all` | new | the point of the feature | - -Stable resources the graphs also point at (owned across requests today, so reuse needs only a proof that they were not -reallocated): dense weights and gamma, router and shared experts (MoE cache entries, see 1.3), `OriginalNativeOutput`, PLE history -and PLE scratch (stack buffers), RoPE tables, the registered expert banks of the pcie path, the VRAM expert cache slots. - -Context length, window width, expert tier: - -* Context length and positions are DATA (staged into mapped host memory / device flags before each `run`); the arena and - the QSA journals are sized for `max_cells`, fixed by the configuration. A longer context does not change the graphs. -* The window width T is the graph identity (`OriginalGraphKey::VerifyWindow(t)`, t in 1..=8) and `max_t` is the arena - geometry. `verifier_max_t` can only fall during a process (`narrow_window_policy` after a graph OOM); a held assembly - recorded for another `max_t` must be retired. -* The expert tier: `pcie_mode` (0 DMA, 2 copy kernel) and the per-layer role bytes are baked into the graphs - (`set_pcie_mode`, `pcie_role_bytes`); the VRAM cache slot contents are data (published plan), the cache object and the - registered banks are addresses. `decode_pcie_mode` is a function of the configuration and of the cache being present. -* Process-level switches resolved at recording time: `qsa_cluster_requested` (cluster top-k), the sm120 switches - (`from_env`), `WindowPolicy::mode17()`. They are fixed for a process; they are in the key so a change is caught. - -## 3. Key and invalidation (the policy the reuse would implement) - -`DecodeGraphKey { max_t, max_cells, pcie_mode, tier, cluster_topk, weights_epoch, owners_epoch }`. `weights_epoch` and -`owners_epoch` are counters bumped by the owners of the physical buffers whenever one that a window reads or writes in place -is freed, moved or reallocated (MoE cache eviction or reload of a shared expert or router, dense cache reload, QSA owner -rebuilt, PLE or canonical buffer replaced, expert bank re-registered). `GraphReuse::acquire(key, record)` returns the held -assembly only for an equal key and only if `rearm()` accepts; otherwise it retires it and calls `record()`. `release` keeps an -assembly only after a clean request; `invalidate` retires it (broken stack, reconfigure, failed request, narrowed window). -A reuse that cannot show an equal key is a re-record. - -## 4. Why it is not implemented in this change - -The reuse needs, in order (none of it needs `original_verify_window_*`, `original_verify_gpu_plan*` or graph-stream code, -except where marked; without a GPU none of it can be validated here): - -1. Lifetimes: the held assembly must not borrow the stack. Either the caches the windows read (dense, MoE, output, formats, - PLE buffers) move behind `Rc` / a long-lived owner that the stack and the assembly both reference, or the assembly is kept - outside the stack in a holder that outlives it. Every `&'s` in `DecodeResources`, `VerifyWeights`, `AssembleInputs` and the - aggregates changes. (`unsafe` lifetime erasure is not an option in this crate.) -2. QSA owner loan: the journal must be able to lend the owners to the executor without the graphs being dropped - (`indices`/`mapped` as `RefCell>` in `qsa_verification_commit.rs`; a graph run while lent is refused), and the - executor must hand them back at the same addresses (`take_qsa_owners` / `adopt_qsa_owners` keep the physical buffers; they - rebuild the lineage objects, which is fine). Epoch `owners_epoch` bumps if any owner is replaced. -3. Re-arm API in the driver: reseed the canonical GDN image in place, reset the bank's window state (`last_*`, generation, the - gpu-plan state), drain both streams, instead of `OriginalVerifier::close`. The gpu-plan state lives in - `original_verify_gpu_plan*` (owned by another session): that part needs their change, exact need: a `reset_for_new_request` - on the bank/plan that leaves the registered buffers and clears per-request flags. -4. MTP drafter: do not release the verifier bindings when the bank is kept (`mtp_release_verifier`), release them on retire. -5. Epoch counters in the MoE and dense caches and the executor (the key above), and pinning of the shared experts / routers - for as long as an assembly is held, so that a prefill cannot evict a buffer a held graph reads. - -Validation (GPU, orchestrator): identity of greedy output reuse-on vs off over N requests with different prompts, lengths and -a forced eviction in between (must re-record, and match); paired A/B of `decode.assemble`, `decode.disassemble`, `record.capture`, -`record.instantiate`, `record.modules`, `draft.*` first-draft capture, and end-to-end request time; VRAM at the decode low-water -mark (a kept set holds the graph pool during prefill: the prefill arena and loan ladder budget shrink by the pool size). - -## 5. Expected size of the win and what stays - -Removes `record_all` (83-85 ms) and the aggregate construction; the canonical image upload and per-request state seeding stay -(about 15-25 ms of the 98-109 ms), `decode.disassemble` (B4, 11.7 ms) becomes a re-arm. The kept pool costs VRAM during prefill. +# Decode graph reuse across requests (ledger row Q7) + +Status: part 1 coded behind `LELEKA_DECODE_GRAPH_REUSE` (off by default, typed setting `serve.decode_graph_reuse`): the reuse +policy (`DecodeGraphKey`, `GraphReuse`, tested on the lifecycle fake), the shared-expert pin and the weights epoch in the MoE +cache. The stack does not hold an assembly: B1 below (the assembly borrows the stack) cannot be done without editing +`original_verify_window_{moe,gr,proj,qsa}.rs`, and part 2 (the verify bank's re-arm API) is the speed session's. With the +switch on, `open` says so on stderr and every request records its graphs, as without the switch. No speedup claim. + +## 1. Why the graphs are recorded per request + +`decode_phase` (`OriginalServeStack`) calls `assemble_decode` -> `AssembleInputs::assemble` (`original_serve_verifier.rs`) for +every request, and `teardown_decode` -> `disassemble` at its end. `assemble` is: `prepare` (geometry, canonical GDN image +uploaded from the session's priors, QSA gamma), `OriginalVerifyQsaJournal::new` over the twelve QSA owners, then +`capture_verifier`: a new `OriginalVerifier` (new `Physical` arena, mapped allocations, two streams), one aggregate +(`OriginalVerifyWindowResources`) per T = 1..=max_t plus one for the commit graph, and `record_all` (nine graphs at T <= 8 +with the mode17 policy, 54-62 ms capture + 27-30 ms instantiate). `disassemble` closes the verifier (drains, drops every +graph and aggregate), which releases the aggregates' references to the QSA journal so `into_owners` can take the owners back, +and `release_mtp` drops the MTP drafter's programs bound to this verifier's bank. + +The recording is per request because of OWNERSHIP, not because the kernel arguments change: + +1. The QSA owners (twelve index images + mapped K/V journals) belong to the prompt executor. The next request's prefill + writes them (chunks, prefix-cache import, rollback). They can only get there by moving out of the journal + (`Rc::try_unwrap` in `into_owners`), which requires every graph that holds the journal to be gone. +2. The resources borrow the stack: `DecodeResources<'s, 'ctx>` holds `&'s DenseWeightCache`, `&'s MoeWeightCache`, + `&'s OriginalNativeOutput`, `&'s DeviceBuffer` (PLE history and scratch), `&SharedKeys` (a value of the request's own + stage). A value that borrows fields of `OriginalServeStack` cannot be stored in it (self-reference); this is why + `DecodeView` borrows the fields one by one. +3. The shared experts and routers are LRU entries of the MoE cache (`ensure_original_verify_shared`); the prompt path loads + layer by layer and may evict and reload them, so their device addresses are not guaranteed to survive a prefill. +4. The MTP drafter's round programs read the verifier's bank (final R span) and are released with it (`mtp_release_verifier`); + they are re-captured against the next bank (spans `draft.*`, a second cost of the same cause). + +`docs/decode-parity.md` already records this as "Verifier persistence: not done ... needs the executor to use the owners through +the journal". + +## 2. What the captured graphs point at + +Per-request buffers (created by `assemble`, addresses change every request today; data must be re-seeded if the buffer is kept): + +| Resource | Created in | Per request | Can be stable | +| --- | --- | --- | --- | +| Canonical GDN image (36 layers x 128*48*128 + 10240*3 f32, ~118 MB) | `prepare_assembly` (`original_verify_canonical_gdn(states, histories)`) | allocated and uploaded from the session priors | yes: keep the buffer, re-upload (118 MB H2D, stays in the per-request cost) | +| Verifier arena, `prof`, 15 mapped allocations, window modules | `OriginalVerifier::new` | new | yes: sized by `verify_geometry(max_t, max_cells, blobs)`; only the window state is data (`last_t`, `last_position`, `generation`, staged tokens) | +| Head rows per T, embedding rows per T, GDN journal, window aggregates | `aggregate()` | new | yes, part of the kept assembly | +| QSA journal `Rc` | `OriginalVerifyQsaJournal::new` | new Rc around the executor's buffers | the buffers are the executor's (fixed addresses); the Rc must outlive requests | +| Graphs, streams, event | `record_all` | new | the point of the feature | + +Stable resources the graphs also point at (owned across requests today, so reuse needs only a proof that they were not +reallocated): dense weights and gamma, router and shared experts (MoE cache entries, see 1.3), `OriginalNativeOutput`, PLE history +and PLE scratch (stack buffers), RoPE tables, the registered expert banks of the pcie path, the VRAM expert cache slots. + +Context length, window width, expert tier: + +* Context length and positions are DATA (staged into mapped host memory / device flags before each `run`); the arena and + the QSA journals are sized for `max_cells`, fixed by the configuration. A longer context does not change the graphs. +* The window width T is the graph identity (`OriginalGraphKey::VerifyWindow(t)`, t in 1..=8) and `max_t` is the arena + geometry. `verifier_max_t` can only fall during a process (`narrow_window_policy` after a graph OOM); a held assembly + recorded for another `max_t` must be retired. +* The expert tier: `pcie_mode` (0 DMA, 2 copy kernel) and the per-layer role bytes are baked into the graphs + (`set_pcie_mode`, `pcie_role_bytes`); the VRAM cache slot contents are data (published plan), the cache object and the + registered banks are addresses. `decode_pcie_mode` is a function of the configuration and of the cache being present. +* Process-level switches resolved at recording time: `qsa_cluster_requested` (cluster top-k), the sm120 switches + (`from_env`), `WindowPolicy::mode17()`. They are fixed for a process; they are in the key so a change is caught. + +## 3. Key and invalidation (coded: `original_serve_stack/decode_graph_reuse.rs`) + +`DecodeGraphKey { max_t, max_cells, pcie_mode, tier, cluster_topk, weights_epoch, owners_epoch }`. `weights_epoch` and +`owners_epoch` are counters bumped by the owners of the physical buffers whenever one that a window reads or writes in place +is freed, moved or reallocated. `GraphReuse::acquire((key, seed), record)` returns the held assembly only for an equal key and +only if `Reusable::rearm(seed)` accepts; otherwise it retires it and calls `record()` (`Armed::Recorded(Why::KeyChanged(name) | +RearmRefused | NothingHeld | Disabled)`). `release` keeps an assembly only after a clean request (a failed or cancelled one drops +its set); `invalidate` retires it (broken stack, reconfigure, narrowed window). A reuse that cannot show an equal key is a +re-record. The lifecycle fake (`lifecycle_fake/graphs.rs`, tests `backend/lifecycle_tests/graphs.rs`) bakes the key and the seed +into its graph set and fails the request on a replay for another key or without a re-arm: kept and re-recorded sets give the +same text, a kept set costs no recording, each of the seven key inputs forces a re-record, a refused re-arm and a failed +request do not replay. + +Owners of the epochs: + +* `weights_epoch`: `MoeWeightCache::weights_epoch()` counts every raw entry the cache evicted (`room`, `room_protected`) and + every pin release; `pin_for_window(keys)` / `unpin_window()` make `is_pinned` true for the 192 shared tensors so the prompt + path cannot evict them while a set is held (the existing eviction rule, as for the profile's permanent pool). Not wired + yet: pinning shrinks what a prefill can evict, and a prefill that finds nothing evictable fails with `InputAllocation`, so + it is switched on only together with a held set. The routers and the other dense operands live in the dense cache, which + does not evict after open. +* `owners_epoch`: not coded (needs B2): the journal compares the window addresses (`window_addresses(layer)` for the twelve + layers: resident pools, table, host copy, resolver, pooled and dead key spans) taken when it lent the owners with those + of the owners that come back; any difference is a refusal and a re-record. + +## 4. What is not done and why + +### B1. The held assembly cannot borrow the stack (blocked: forbidden files) + +`DecodeResources<'s>` is `OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>`; the aggregates hold `&'a +DeviceBuffer<'ctx>` into the dense cache (projections, GR, QSA operands, gamma), the PLE history and scratch, the RoPE tables +and the MoE cache (shared experts, `original_verify_moe`). The prompt path of the next request needs `&mut MoeWeightCache` and +`&mut DeviceBuffer` (`seed_ple_history`), which a live `&'a` forbids, and a value that borrows fields of the stack cannot live in +the stack. No safe restructuring of the stack alone fixes this: an owner above the stack would have to hold the MoE cache +immutably (the prompt path mutates it) or split the shared experts out of it (the prompt path loads them through it). + +Exact change that removes the borrow (files of the speed session's area, or operand types they use): + +* `original_verify_window_moe.rs` (5 sites: `OriginalVerifyMoeLayerWeights`), `original_verify_window_gr.rs` (16: `PleBuffers`, + `HcLayerBuffers`, ...), `original_verify_window_proj*` and `original_verify_window_qsa.rs` (5), `qwen_dispatch/fixed_operands.rs` + (34): replace the `&'a DeviceBuffer<'ctx>` operands with a shared handle `DeviceRef<'ctx>` (an `Rc` to the allocation plus + offset and length, `Clone`, derefs to `&DeviceBuffer` for the existing `qwen_address()` calls). The aggregates then have no + `'a`, `OriginalVerifyWindowResources<'ctx>` and `DecodeResources<'ctx>` can sit in the stack, and the borrow of the caches + ends at `assemble`. +* The caches hand out handles: `DenseWeightCache::original_verify_*` and `MoeWeightCache::raw_shared` clone the `Rc` of the + entry (the entries become `Rc`); an unpinned entry that a held set still references is dropped from the + cache's book on eviction but not freed (the set keeps the allocation alive; `weights_epoch` bumps, so the set is retired + at the next request). +* `seed_ple_history` writes through the shared handle (a `&self` upload of `DeviceBuffer`, device idle). + +### B2. QSA owner loan (not coded: dead until B1, touches 25 hot-path sites of the journal) + +`OriginalVerifyQsaJournal` keeps `indices: [RefCell; 12]` and `mapped: [RefCell<...Journal>; 12]`. +Needed: both as `RefCell>` behind accessors (`index(layer)`, `index_mut`, `kv`, `kv_mut`, which return +`InvalidQwenShape` while lent), `lend(&self) -> Result` (requires not armed, every index idle and published; records +the twelve `window_addresses`; leaves the journal `lent`) and `take_back(&self, QsaOwners) -> Result<()>` (requires the same +addresses and `check_aligned` at the new position, else marks the journal failed so the set is retired). The executor side +needs no change: `take_qsa_owners` / `adopt_qsa_owners` already move the physical owners by value and keep their buffers; the +stack calls `journal.lend()` where it now calls `disassemble` and `journal.take_back(take_qsa_owners())` where it now builds a +journal. The driver's `into_owners` stays for the retire path. + +### B3. MTP drafter bound to the kept bank (not coded: follows B1) + +`teardown_decode` calls `release_mtp` (`mtp_release_verifier`) before the bank closes. With a kept bank it skips that call +(the drafter's cached round programs stay valid for the same bank and are not re-captured, which also removes the first-draft +capture of every request), and the retire path (`GraphReuse::invalidate`, a changed key, a refused re-arm) calls it before the +bank closes. The drafter keeps nothing keyed on the request (its tail is cleared by `OriginalMtpActor::set_prompt_len` as today). + +### Part 2: the verify bank's re-arm API (speed session's files; the policy codes against `Reusable::rearm`) + +Needed in `crates/cuda-driver` (`original_verify_schedule/*`, `original_verify.rs`, `original_verify_gpu_plan*`): + +```rust +/// Seed of the next request: the session's recurrent priors, in the canonical image's layout. +pub struct OriginalVerifyRearm<'s> { + pub gdn_states: [&'s [f32]; 36], // 128*48*128 f32 each + pub gdn_histories: [&'s [f32]; 36], // 10240*3 f32 each + pub ple_history: &'s [f32], // 9*10240 f32 +} +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + /// End of a request: drain both streams, wait a pending commit; keep graphs, bank, streams and event. + pub fn park(&mut self) -> Result<()>; + /// Start of the next request over the same recording. `Err` leaves the verifier unusable (the caller retires it). + pub fn rearm(&mut self, seed: OriginalVerifyRearm<'_>) -> Result<()>; +} +impl OriginalVerifyCanonicalGdn<'_> { + /// Overwrite the image in place (same device address): states and histories, 117.7 MB host to device. + pub fn reseed(&self, states: [&[f32]; 36], histories: [&[f32]; 36]) -> Result<()>; +} +``` + +Preconditions of `rearm`: `park` ran (both streams idle, `commit_pending`, `window_ready` and `active` false, `failed` false, +not released); every captured graph is quiescent; the QSA journal is not armed and not lent. State it resets (everything a +fresh `OriginalVerifier::new` + `record_all` leaves, so the first `run` of the new request sees what the first `run` after a +recording sees): + +* `OriginalVerifier`: `windows = 0`, `commits = 0`, `completed_generation = None`, `completed_ids = [0; 8]`, profile counters; + `split`, `groups`, `resource_keys` as recorded. +* `OriginalVerifyBank`: `last_t = 0`, `last_position = 0`, `last_tokens = [0; 8]`, `last_keep = 0`, `generation` advanced (old + `OriginalVerifyRow` / `OriginalVerifyWindow` values are refused), `released = false`, `pcie_sources` cleared (held until the + previous copy-stream fence); `pcie_mode` / `pcie_roles` unchanged (they are in the key). +* Every device and mapped flag the graphs wait on or raise (`verify_wait_flag_ge_kernel` / `_or_kernel` operands, the group flag + rings and doorbell of `raise_group_flag` / `wait_doorbell`, the `verify_clear_status` words, the ident-hit and tail-snapshot + flags): back to the value they have at the end of `record_all` (zero). The graphs compare against a "want" that counts up + inside a window; it must restart. +* The gpu-plan state in `Physical.mapped[..]` (the published plan, the fetch tables) and `prof`: cleared. +* The canonical GDN image (`reseed`) and the PLE history image (`seed.ple_history`, through the journal's `ple` handle). + +Postcondition for the stack: the first `stage_window` of the new request is accepted at any `position` the QSA owners stand at. +The policy retires and re-records on any `Err` or `false`, so a partial re-arm is safe. + +## 5. Validation (GPU, orchestrator) + +Identity of greedy output reuse-on vs off over N requests with different prompts and lengths and a forced eviction in between +(must re-record, and match); paired A/B of `decode.assemble`, `decode.disassemble`, `record.capture`, `record.instantiate`, +`record.modules`, the first-draft capture in `draft.*`, and end-to-end request time; VRAM at the decode low-water mark (a kept +set holds the graph pool during prefill: the prefill arena and loan ladder budget shrink by the pool size). + +## 6. Expected size of the win and what stays + +Removes `record_all` (83-85 ms) and the aggregate construction; the canonical image upload and per-request state seeding stay +(about 15-25 ms of the 98-109 ms), `decode.disassemble` (B4, 11.7 ms) becomes a park. The kept pool costs VRAM during prefill. From 2e7658567d97de0b91678bcdcd3386cdf4a566c6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 9 Nov 2026 23:16:24 +0100 Subject: [PATCH 2/2] ledger: Q7 status (code 3e68def28, switch, identity and section delta pending) Co-Authored-By: Claude Sonnet 5.5 --- docs/experiments/step-ledger.md | 418 ++++++++++++++++---------------- 1 file changed, 209 insertions(+), 209 deletions(-) diff --git a/docs/experiments/step-ledger.md b/docs/experiments/step-ledger.md index 9caab24a..7d78d4fa 100644 --- a/docs/experiments/step-ledger.md +++ b/docs/experiments/step-ledger.md @@ -1,209 +1,209 @@ -# 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 | request: HTTP, gateway and proxy time (code `pf_probe.py`) | probe pending (job `prefill-empty-request-probe-leleka`) | none: vanilla is not re-measured (owner 2026-11-09); the vanilla figure comes from its existing logs | the sum 'rest' per request is Q10: 22 ms against 32 ms | LOG | hex-finish | fixing (probe queued) | -| A2 | request: tokenizer and prompt assembly of a long prompt | probe pending (job `prefill-empty-request-probe-leleka`: long cached prompt minus tiny prompt) | not measured | n/a | none | hex-finish | fixing (probe queued) | -| A3 | request: prefix-cache lookup and import (code `request.resume`, `ctrl.begin_request`, `prefix.*`) | PROFILE `runs/dc1` (60 requests): `request.resume` 2.53 + `ctrl.begin_request` 0.60 + `prefix.import_session` 0.80 + `prefix.draft_resume_at` 1.05 + `prefix.mtp_kv_restore` 0.61 + `prefix.layer_index` 0.38 = 5.97 ms per request | not measured | n/a (replay logs `cached_tokens`; import time only in `last_import_split`) | none | hex-finish | fixing (VANL from its existing logs; only if the LEL sum is larger, one run of the instrumented copy of vanilla gives the split) | -| 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: time per request at equal uncached tokens (code ladder `LELEKA_PREFILL_LOAN_TIERS`) | 726 ms | 431 ms | +295 ms. Ladder (`LELEKA_PREFILL_LOAN_TIERS=1`) paired on the sparse holder, n=5 blocks: -3.1 s per 30-request session +-0.5; <= 2048 new tokens -151 ms per request (faster in 19 of 19); n=10 in job `prefill-ladder-ab-pairs-6-10` | LOG | hex-finish | fixing (profile switch ready, commit after job `prefill-ladder-ab-pairs-6-10`) | -| 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: fixed part of the chunk read (code `prefill.read`, 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: root cause found (see Q5) | -| 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. Root cause: `prompt_options` (`original_serve_stack_prefill_phase.rs`) sets `force_batched: true`; the planner already emits `PromptPath::Verify` actions for tails <= 64 tokens but the executor's `verify_window` hook (`original_prompt_executor_drop.rs:63`) is not implemented | PROFILE `prof-l5` | hex-finish | fixing (design pending) | -| 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 (code `prefill.refill`, 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 hand-over: graph assembly per request (code `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 | hex-finish | fixing: design in `docs/experiments/decode-graph-reuse.md`; cause is ownership (QSA owners, borrowed weights, evictable shared experts, drafter bound to the bank), needs a re-arm API in `original_verify_gpu_plan*` (speed session) | -| B3 | prefill: prefix-cache parking in the request path (code `prefix.export_kv` 19.0 + `export_index` 2.3 + `park_tail` 14.7 + `park_block` 6.5 + `after_prefill` 9.4 + `after_chunk` 0.7 + `after_decode` 12.5, mean per request) | 65.1 ms | vanilla parks the conversation (checkpoints) inside its own prompt time, not separable | n/a until the instrumented vanilla | PROFILE `runs/dc1` | hex-finish | open: move off the critical path (asynchronous parking after the first token) | -| B4 | decode hand-over: tear-down of the request (code `decode.disassemble`) | 11.7 ms per request | none | +11.7 ms | PROFILE `runs/dc1` | hex-finish | open | -| B5 | host: admission of CPU work (code `cpu.admit`, 819 calls per request) | 43.2 ms per request | not measured | n/a | PROFILE `runs/dc1` | hex-finish | 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 the host idle between them (code `LELEKA_DRAFT_CHAIN_PIPELINE`) | 0.272 ms per round (2.38 boundaries x 114 us) | idle inside the draft 0.52 ms on 4.5 streams (draft span at equal steps: 1.83 against 1.85) | +0.27 | ORCH | hex-finish | fixing: S1 `LELEKA_DRAFT_CHAIN_PIPELINE` (code `1ab37e408`, opt-in; all chain steps of a greedy draft with min_p 0 enqueued back to back, one drain, flags read once); package `pkg-s1`, identity and profile pair job `host-draft-chain-one-pass-identity`, paired A/B job `host-draft-chain-one-pass-ab` | -| O8 | draft: finite and q8 guard checks of the MTP ring (code `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 (S2': cheaper checks with the same detection) | -| 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. - -## U. Upstream fixes and small wins after the pin (checked 2026-11-09 against `strata-upstream/main`, reference only, `engine/strata` untouched) - -Owner rule: small upstream wins (+0.3..0.5 %) are taken too. "VANL" here is vanilla 0.2.6; upstream items dated after it are wins on top of vanilla, not gaps against it. Each row says whether we have the analogue, then the closing evidence needed. - -| id | step | LEL | VANL / upstream | difference | source | owner | status | -| --- | --- | --- | --- | --- | --- | --- | --- | -| U1 | prefill: GDN recurrence as a chunked scan on tensor cores (code `STRATA_GDN_TC`, upstream commits `8c2a84694` opt-in 2026-10-26, default `6858c919c` 2026-11-07 with `STRATA_GDN_CONVL2=2`) | not present: our GDN prompt kernels are the sealed Original ones (`gdn_closed_queue*`, `gdn_batch_gemm.rs`); the pinned `engine/strata` (0.1.50) has no `GDN_TC` either | upstream 0.2.9: prompt +4.4 % at 4K, +5.5 % at 16K, +5.7 % at 32K; **lossy**: first-token KL mean 0.0019, max 0.0125; engine gates it at run time (compute capability >= 8, one SM per value head, shared memory) | not a gap against VANL 0.2.6 (it has no `GDN_TC`); a possible win of about 5 % of prefill | upstream commit message | hex-finish | open: port needs a new CUDA kernel and a new sealed PTX (sm_120) plus the lossy quality gate (`docs/quality-gate.md`), marked experimental until it passes; section delta = `prefill.gdn` span at 4K/16K/32K | -| U2 | prefill: batched PLE post-ops (code `STRATA_PLE_BATCH`; upstream `78316c8df` 2026-11-02 turns it off for an engine built with CUDA 12.8 on cc 12.0: illegal memory access in `native_ple_postops_batch_snap`) | we run the PLE of a prompt chunk batched (`OriginalPromptDevice::apply_ple`, `ple_batch_ffi`, `ple_batch_queue`); our sealed PTX is ISA 9.2 = CUDA 13.2 and the deploy refuses a driver older than 595 (`docs/deploy.md`), the production RTX 5090 host runs driver 595.99 / CUDA 13.2 | upstream: with CUDA 13.0 the batch is ~23 % faster prompts, so only the 12.8 toolchain faults | same hazard does not apply (no 12.8 build exists in our chain); the batch is already on | source read | hex-finish | proved-equal (we have the fast path and not the faulting toolchain); no work | -| U3 | prefill: MMQ row table over-read by the stream-k fixup (code `ids_identity`; upstream `f225844d1` 2026-11-05, class E correctness) | same structure: `ids_identity` is `T*K` entries exactly (`original_prefill_layout.rs:330`, `a.rows("ids_identity", t, K, 4)`), read by the same ggml `mul_mat_q_stream_k_fixup` (`mmq_original_formats_fixup.cu`); upstream needs `T*K + roundup(T, J) + J` entries (J = 8..128). It stays inside the arena today because `bounds_dev`, `grp_gu`, `grp_d` follow it in the same allocation, so the over-read lands in a neighbouring span and the skipped writes never use it | upstream faulted (Xid 31) when the exact table ended a 2 MiB page | latent: not a fault with the current layout, would become one if the order of the `Common` spans changes or `mmq_any` spans end the allocation | source read | hex-finish | fixing: margin `roundup(T, 128) + 128` entries added (`original_prefill_layout/mmq_identity.rs`, unit test of every readable index; always on, class E, no switch); identity (prompt logit digests equal) pending in the batched identity job | -| U4 | verify: flag B stays behind queued copies (upstream `40849df0a` 2026-11-05, P1.1, class E) | `OriginalVerifyGpuPlan::raise_after_staging` (`plan_phases.rs`): a plan with a PCIe source queues the flag behind the staging copies on the copy stream even when the plan is empty (`stage_pcie`, then `raise_after_copies`), the copy-kernel mode and the no-source case raise at once. The upstream hazard (an empty plan raising the one counter early while an earlier layer's or the other token group's uploads are still queued) can only occur in the no-source branch if a window mixes groups with and without a source; not shown to happen | upstream: counter jumped past a layer whose bytes had not landed | unknown; needs the check in the file owned by the speed session | source read | device | open: handed to the speed-vs-strata session (`original_verify_gpu_plan*` is theirs): confirm the no-source branch cannot run while copies are queued, add a test | -| U5 | verify: adaptive-copy range covers the whole round (upstream `40849df0a`) | different implementation: adaptive swaps are planned and applied in `original_serve_residency` (`adapt_swaps` cap 96 per round, `swap_tie_order.rs`); no serial/pipelined split with `lo/hi/bi` ranges exists in the Rust port | upstream: a pipelined round that drained early marked only an earlier round's range resident, so other swaps were lost (slot held the new expert, table still named the old one) | analogue not found; the resident marking of a drained round needs a read-through | source read | device | open: review of "slot marked resident exactly when its copy landed" in `original_serve_residency` (hand to the memory/speed session) | - -## Job names (GPU queue stubs and result directories) - -Naming rule (owner 2026-11-09): `--`, in words; areas `prefill-`, `host-`, `draft-`, `memory-`. Result directories under `/data/leleka-e2e/prefill-latency/runs/` carry the same name. Jobs that already ran keep their old name; the map is old to new. - -| old name | new name (job stub, queue entry and result directory) | what it measures | row | -| --- | --- | --- | --- | -| `pf-ab4` | `prefill-ladder-ab-pairs-6-10` | paired A/B of the prompt loan ladder against shipped, pairs 6-10, sparse holder | Q1 | -| `pr-lel` | `prefill-empty-request-probe-leleka` | empty-request probe on LEL: tiny prompt, cold, cached long prompt | A1, A2, A3 | -| `pr-prof` | `prefill-prefix-park-subspans-profile` | profiled replay with the sub-spans of the prefix-cache export (sync, allocation, copy) | B3 | -| `s1-id1` | `host-draft-chain-one-pass-identity` | identity and host-span pair, draft chain in one pass against sequential | O9 | -| `s1-ab1` | `host-draft-chain-one-pass-ab` | paired A/B n=10, draft chain in one pass (ms per token, task time) | O9 | -| `pr-van` | removed | empty-request probe on VANL; vanilla is not re-measured (owner 2026-11-09) | A1-A3 | +# 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 | request: HTTP, gateway and proxy time (code `pf_probe.py`) | probe pending (job `prefill-empty-request-probe-leleka`) | none: vanilla is not re-measured (owner 2026-11-09); the vanilla figure comes from its existing logs | the sum 'rest' per request is Q10: 22 ms against 32 ms | LOG | hex-finish | fixing (probe queued) | +| A2 | request: tokenizer and prompt assembly of a long prompt | probe pending (job `prefill-empty-request-probe-leleka`: long cached prompt minus tiny prompt) | not measured | n/a | none | hex-finish | fixing (probe queued) | +| A3 | request: prefix-cache lookup and import (code `request.resume`, `ctrl.begin_request`, `prefix.*`) | PROFILE `runs/dc1` (60 requests): `request.resume` 2.53 + `ctrl.begin_request` 0.60 + `prefix.import_session` 0.80 + `prefix.draft_resume_at` 1.05 + `prefix.mtp_kv_restore` 0.61 + `prefix.layer_index` 0.38 = 5.97 ms per request | not measured | n/a (replay logs `cached_tokens`; import time only in `last_import_split`) | none | hex-finish | fixing (VANL from its existing logs; only if the LEL sum is larger, one run of the instrumented copy of vanilla gives the split) | +| 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: time per request at equal uncached tokens (code ladder `LELEKA_PREFILL_LOAN_TIERS`) | 726 ms | 431 ms | +295 ms. Ladder (`LELEKA_PREFILL_LOAN_TIERS=1`) paired on the sparse holder, n=5 blocks: -3.1 s per 30-request session +-0.5; <= 2048 new tokens -151 ms per request (faster in 19 of 19); n=10 in job `prefill-ladder-ab-pairs-6-10` | LOG | hex-finish | fixing (profile switch ready, commit after job `prefill-ladder-ab-pairs-6-10`) | +| 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: fixed part of the chunk read (code `prefill.read`, 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: root cause found (see Q5) | +| 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. Root cause: `prompt_options` (`original_serve_stack_prefill_phase.rs`) sets `force_batched: true`; the planner already emits `PromptPath::Verify` actions for tails <= 64 tokens but the executor's `verify_window` hook (`original_prompt_executor_drop.rs:63`) is not implemented | PROFILE `prof-l5` | hex-finish | fixing (design pending) | +| 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 (code `prefill.refill`, 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 hand-over: graph assembly per request (code `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 | hex-finish | fixing (code 3e68def28, switch `LELEKA_DECODE_GRAPH_REUSE` off by default, identity and section delta pending): key, policy and shared-expert pin are in, the stack does not keep the graphs yet; blocked on the assembly borrowing the stack (handles in `original_verify_window_*`) and on the verify bank's re-arm API (speed session); design `docs/experiments/decode-graph-reuse.md` | +| B3 | prefill: prefix-cache parking in the request path (code `prefix.export_kv` 19.0 + `export_index` 2.3 + `park_tail` 14.7 + `park_block` 6.5 + `after_prefill` 9.4 + `after_chunk` 0.7 + `after_decode` 12.5, mean per request) | 65.1 ms | vanilla parks the conversation (checkpoints) inside its own prompt time, not separable | n/a until the instrumented vanilla | PROFILE `runs/dc1` | hex-finish | open: move off the critical path (asynchronous parking after the first token) | +| B4 | decode hand-over: tear-down of the request (code `decode.disassemble`) | 11.7 ms per request | none | +11.7 ms | PROFILE `runs/dc1` | hex-finish | open | +| B5 | host: admission of CPU work (code `cpu.admit`, 819 calls per request) | 43.2 ms per request | not measured | n/a | PROFILE `runs/dc1` | hex-finish | 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 the host idle between them (code `LELEKA_DRAFT_CHAIN_PIPELINE`) | 0.272 ms per round (2.38 boundaries x 114 us) | idle inside the draft 0.52 ms on 4.5 streams (draft span at equal steps: 1.83 against 1.85) | +0.27 | ORCH | hex-finish | fixing: S1 `LELEKA_DRAFT_CHAIN_PIPELINE` (code `1ab37e408`, opt-in; all chain steps of a greedy draft with min_p 0 enqueued back to back, one drain, flags read once); package `pkg-s1`, identity and profile pair job `host-draft-chain-one-pass-identity`, paired A/B job `host-draft-chain-one-pass-ab` | +| O8 | draft: finite and q8 guard checks of the MTP ring (code `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 (S2': cheaper checks with the same detection) | +| 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. + +## U. Upstream fixes and small wins after the pin (checked 2026-11-09 against `strata-upstream/main`, reference only, `engine/strata` untouched) + +Owner rule: small upstream wins (+0.3..0.5 %) are taken too. "VANL" here is vanilla 0.2.6; upstream items dated after it are wins on top of vanilla, not gaps against it. Each row says whether we have the analogue, then the closing evidence needed. + +| id | step | LEL | VANL / upstream | difference | source | owner | status | +| --- | --- | --- | --- | --- | --- | --- | --- | +| U1 | prefill: GDN recurrence as a chunked scan on tensor cores (code `STRATA_GDN_TC`, upstream commits `8c2a84694` opt-in 2026-10-26, default `6858c919c` 2026-11-07 with `STRATA_GDN_CONVL2=2`) | not present: our GDN prompt kernels are the sealed Original ones (`gdn_closed_queue*`, `gdn_batch_gemm.rs`); the pinned `engine/strata` (0.1.50) has no `GDN_TC` either | upstream 0.2.9: prompt +4.4 % at 4K, +5.5 % at 16K, +5.7 % at 32K; **lossy**: first-token KL mean 0.0019, max 0.0125; engine gates it at run time (compute capability >= 8, one SM per value head, shared memory) | not a gap against VANL 0.2.6 (it has no `GDN_TC`); a possible win of about 5 % of prefill | upstream commit message | hex-finish | open: port needs a new CUDA kernel and a new sealed PTX (sm_120) plus the lossy quality gate (`docs/quality-gate.md`), marked experimental until it passes; section delta = `prefill.gdn` span at 4K/16K/32K | +| U2 | prefill: batched PLE post-ops (code `STRATA_PLE_BATCH`; upstream `78316c8df` 2026-11-02 turns it off for an engine built with CUDA 12.8 on cc 12.0: illegal memory access in `native_ple_postops_batch_snap`) | we run the PLE of a prompt chunk batched (`OriginalPromptDevice::apply_ple`, `ple_batch_ffi`, `ple_batch_queue`); our sealed PTX is ISA 9.2 = CUDA 13.2 and the deploy refuses a driver older than 595 (`docs/deploy.md`), the production RTX 5090 host runs driver 595.99 / CUDA 13.2 | upstream: with CUDA 13.0 the batch is ~23 % faster prompts, so only the 12.8 toolchain faults | same hazard does not apply (no 12.8 build exists in our chain); the batch is already on | source read | hex-finish | proved-equal (we have the fast path and not the faulting toolchain); no work | +| U3 | prefill: MMQ row table over-read by the stream-k fixup (code `ids_identity`; upstream `f225844d1` 2026-11-05, class E correctness) | same structure: `ids_identity` is `T*K` entries exactly (`original_prefill_layout.rs:330`, `a.rows("ids_identity", t, K, 4)`), read by the same ggml `mul_mat_q_stream_k_fixup` (`mmq_original_formats_fixup.cu`); upstream needs `T*K + roundup(T, J) + J` entries (J = 8..128). It stays inside the arena today because `bounds_dev`, `grp_gu`, `grp_d` follow it in the same allocation, so the over-read lands in a neighbouring span and the skipped writes never use it | upstream faulted (Xid 31) when the exact table ended a 2 MiB page | latent: not a fault with the current layout, would become one if the order of the `Common` spans changes or `mmq_any` spans end the allocation | source read | hex-finish | fixing: margin `roundup(T, 128) + 128` entries added (`original_prefill_layout/mmq_identity.rs`, unit test of every readable index; always on, class E, no switch); identity (prompt logit digests equal) pending in the batched identity job | +| U4 | verify: flag B stays behind queued copies (upstream `40849df0a` 2026-11-05, P1.1, class E) | `OriginalVerifyGpuPlan::raise_after_staging` (`plan_phases.rs`): a plan with a PCIe source queues the flag behind the staging copies on the copy stream even when the plan is empty (`stage_pcie`, then `raise_after_copies`), the copy-kernel mode and the no-source case raise at once. The upstream hazard (an empty plan raising the one counter early while an earlier layer's or the other token group's uploads are still queued) can only occur in the no-source branch if a window mixes groups with and without a source; not shown to happen | upstream: counter jumped past a layer whose bytes had not landed | unknown; needs the check in the file owned by the speed session | source read | device | open: handed to the speed-vs-strata session (`original_verify_gpu_plan*` is theirs): confirm the no-source branch cannot run while copies are queued, add a test | +| U5 | verify: adaptive-copy range covers the whole round (upstream `40849df0a`) | different implementation: adaptive swaps are planned and applied in `original_serve_residency` (`adapt_swaps` cap 96 per round, `swap_tie_order.rs`); no serial/pipelined split with `lo/hi/bi` ranges exists in the Rust port | upstream: a pipelined round that drained early marked only an earlier round's range resident, so other swaps were lost (slot held the new expert, table still named the old one) | analogue not found; the resident marking of a drained round needs a read-through | source read | device | open: review of "slot marked resident exactly when its copy landed" in `original_serve_residency` (hand to the memory/speed session) | + +## Job names (GPU queue stubs and result directories) + +Naming rule (owner 2026-11-09): `--`, in words; areas `prefill-`, `host-`, `draft-`, `memory-`. Result directories under `/data/leleka-e2e/prefill-latency/runs/` carry the same name. Jobs that already ran keep their old name; the map is old to new. + +| old name | new name (job stub, queue entry and result directory) | what it measures | row | +| --- | --- | --- | --- | +| `pf-ab4` | `prefill-ladder-ab-pairs-6-10` | paired A/B of the prompt loan ladder against shipped, pairs 6-10, sparse holder | Q1 | +| `pr-lel` | `prefill-empty-request-probe-leleka` | empty-request probe on LEL: tiny prompt, cold, cached long prompt | A1, A2, A3 | +| `pr-prof` | `prefill-prefix-park-subspans-profile` | profiled replay with the sub-spans of the prefix-cache export (sync, allocation, copy) | B3 | +| `s1-id1` | `host-draft-chain-one-pass-identity` | identity and host-span pair, draft chain in one pass against sequential | O9 | +| `s1-ab1` | `host-draft-chain-one-pass-ab` | paired A/B n=10, draft chain in one pass (ms per token, task time) | O9 | +| `pr-van` | removed | empty-request probe on VANL; vanilla is not re-measured (owner 2026-11-09) | A1-A3 |