From 57fdd21b13df30e4f73162de413c40d6409e29bd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 23:59:59 +0200 Subject: [PATCH] perf(serve): host profile spans, verify GPU profile report, span cache, sparse suffix reset Driver host_profile spans (LELEKA_SERVE_PROFILE) for the window launch, doorbell waits, syncs, head, commit and MTP draft graphs; STRATA_VERIFY_PROFILE report printed per request; PCIe/swap/refill source span cache (LELEKA_SPAN_CACHE=off controls); suffix drafter clears only the slots it claimed (LELEKA_SUFFIX_RESET=full controls). Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/src/host_profile.rs | 62 ++++++++ crates/cuda-driver/src/lib.rs | 1 + .../src/mtp_original_full_drafter.rs | 7 + crates/cuda-driver/src/native_head.rs | 3 + crates/cuda-driver/src/original_verify.rs | 6 +- .../src/original_verify_schedule.rs | 26 +++- .../src/backend_original_serve_smoke.rs | 2 +- .../src/qwen_forward/original_serve_engine.rs | 8 + .../qwen_forward/original_serve_profile.rs | 4 +- .../qwen_forward/original_serve_residency.rs | 146 ++++++++++++++---- .../src/qwen_forward/original_serve_stack.rs | 12 +- .../src/qwen_forward/original_spec_suffix.rs | 46 +++++- .../src/qwen4exp_expert_source_bank.rs | 2 + 13 files changed, 281 insertions(+), 44 deletions(-) create mode 100644 crates/cuda-driver/src/host_profile.rs diff --git a/crates/cuda-driver/src/host_profile.rs b/crates/cuda-driver/src/host_profile.rs new file mode 100644 index 00000000..a0115ded --- /dev/null +++ b/crates/cuda-driver/src/host_profile.rs @@ -0,0 +1,62 @@ +//! Operator profile of the driver's host-side spans (`LELEKA_SERVE_PROFILE=1`, off by default), summed per thread +//! and printed by the runtime's serve profile next to its own spans. Inclusive wall-clock; nested spans are not +//! additive. When the switch is off a span is one cached boolean test. +use std::cell::RefCell; +use std::time::Instant; + +/// `LELEKA_SERVE_PROFILE` set to anything but `0`, read once. +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_SERVE_PROFILE").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +thread_local! { + static SUMS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// A running span; its time is added to `name` when it is dropped. +pub struct Span { + name: &'static str, + started: Option, +} +impl Span { + pub fn stop(&mut self) { + if let Some(started) = self.started.take() { + add(self.name, started.elapsed().as_secs_f64() * 1e3); + } + } +} +impl Drop for Span { + fn drop(&mut self) { + if let Some(started) = self.started { + add(self.name, started.elapsed().as_secs_f64() * 1e3); + } + } +} + +/// Start a span (a no-op unless the profile is on). +pub fn span(name: &'static str) -> Span { + Span { name, started: enabled().then(Instant::now) } +} + +/// Add `ms` to `name` (one call). +pub fn add(name: &'static str, ms: f64) { + if !enabled() { + return; + } + SUMS.with(|sums| { + let mut sums = sums.borrow_mut(); + match sums.iter_mut().find(|(n, _, _)| *n == name) { + Some(entry) => { + entry.1 += ms; + entry.2 += 1; + } + None => sums.push((name, ms, 1)), + } + }); +} + +/// The sums since the last call, `(name, total ms, count)`, and reset them. +pub fn take() -> Vec<(&'static str, f64, u64)> { + SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut())) +} diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b10a9d26..321e2eb3 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -132,6 +132,7 @@ pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace}; #[allow(unsafe_code)] mod qwen_ffi; +pub mod host_profile; pub mod experimental; /// Per-command timing of the batched prompt producers (bring-up profiling only). pub mod command_profile; diff --git a/crates/cuda-driver/src/mtp_original_full_drafter.rs b/crates/cuda-driver/src/mtp_original_full_drafter.rs index d2e5777c..507061c3 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter.rs @@ -294,6 +294,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let span_record = crate::host_profile::span("mtp.launch_record"); let first_capture = graphs.find_mut(key)?.is_none(); let graph = graphs.record( key, @@ -314,12 +315,14 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { }, |c, r| r.capture(c), )?; + drop(span_record); if first_capture { self.graph_metadata = self .graph_metadata .checked_add(graph.mtp_resource_metadata()?) .ok_or(Error::BudgetExceeded)?; } + let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue"); // generate.cpp enqueues the draft on the commit's stream: here the draft stream waits the verifier's // commit event before its first command, so the GPU orders them without a host wait. if let Some(event) = after { @@ -388,7 +391,9 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let mut ids = [0i32; 8]; let mut probabilities = [0f32; 8]; let mut count; + let span_first = crate::host_profile::span("mtp.finish_first_step"); let first_result = graph.mtp_finish_step(stream); + drop(span_first); let output = match first_result { Ok(o) => o, Err(error) => { @@ -404,6 +409,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let limit = (self.max_t as i32 - 1).min(max_drafts); let mut j = 1usize; while (j as i32) < limit && probabilities[j - 1] >= min_p { + let _span_chain = crate::host_profile::span("mtp.chain_step"); let key = OriginalGraphKey::MtpStep { step: j as u8, coupled: cp, @@ -444,6 +450,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let end = first .checked_add(rows.max(a + count)) .ok_or(Error::InvalidSize)?; + let _span_ring = crate::host_profile::span("mtp.finish_ring"); let snapshot = ring.finish_original_graph_mutation(prior, first, end, generation)?; Ok(CompletedOriginalMtpDraft { snapshot, diff --git a/crates/cuda-driver/src/native_head.rs b/crates/cuda-driver/src/native_head.rs index 6aab0512..47af3bd5 100644 --- a/crates/cuda-driver/src/native_head.rs +++ b/crates/cuda-driver/src/native_head.rs @@ -769,11 +769,14 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { stream.native_head_stream_key()?, )?; self.prepare_commands(&commands)?; + let span_sample = crate::host_profile::span("head.sample_sync"); let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands))); let sync = stream.synchronize(); + drop(span_sample); combine(operation, sync)?; self.commands.borrow_mut().clear(); } + let _span_ids = crate::host_profile::span("head.read_ids"); let ids = self .mapped .as_ref() diff --git a/crates/cuda-driver/src/original_verify.rs b/crates/cuda-driver/src/original_verify.rs index 187b99ac..7e49a345 100644 --- a/crates/cuda-driver/src/original_verify.rs +++ b/crates/cuda-driver/src/original_verify.rs @@ -339,11 +339,11 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{ /// is an integration finite gate, never an id-as-finite certificate. The four /// byte status reuses retired hit_count scratch; no active kernel can alias it. pub(crate) fn validate_completed_logits(&self,stream:&mut crate::OriginalGpuStream<'ctx>,logits:&DeviceBuffer<'ctx>,rows:usize)->Result<()>{ - self.validate_context(self.physical.context)?;stream.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if !(1..=g.max_t).contains(&rows){return Err(Error::InvalidQwenShape)}let words=rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?;let src=admit(self.physical.context,logits,words.checked_mul(4).ok_or(Error::InvalidSize)?)?; + let _span_validate=crate::host_profile::span("head.validate_logits");self.validate_context(self.physical.context)?;stream.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if !(1..=g.max_t).contains(&rows){return Err(Error::InvalidQwenShape)}let words=rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?;let src=admit(self.physical.context,logits,words.checked_mul(4).ok_or(Error::InvalidSize)?)?; let arena=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;if handle(logits)?.overlaps(logits.len(),handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)}let status=self.span("hit_count",0,4)?; let mut commands=vec![command("verify_clear_status",[1,1,1],[32,1,1],vec![Arg::Address(status.qwen_address())])?,command("verify_scan_logits",[words.div_ceil(256).min(65535)as u32,1,1],[256,1,1],vec![Arg::Address(src),Arg::U64(words as u64),Arg::Address(status.qwen_address())])?]; - let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?;}let launched=stream.with_enqueue(|h|{for c in &mut commands{module.launch(h,c)?;}Ok(())});let sync=stream.synchronize();if sync.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(commands);return combine(launched,sync)}combine(launched,sync)?; - let mut bytes=zero(4)?;let guard=self.physical.context.enter()?;let copy=self.physical.context.driver.api.copy_to(status,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish();if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop)}combine(combine(copy,sync),pop)?;if u32::from_le_bytes(bytes[..4].try_into().map_err(|_|Error::InvalidSize)?)!=0{return Err(Error::NonFiniteMmqOutput("Original Verifier full logits"))}Ok(()) + let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?;}let span_vs=crate::host_profile::span("head.validate_stream");let launched=stream.with_enqueue(|h|{for c in &mut commands{module.launch(h,c)?;}Ok(())});let sync=stream.synchronize();drop(span_vs);if sync.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(commands);return combine(launched,sync)}combine(launched,sync)?; + let span_vc=crate::host_profile::span("head.validate_ctx_copy");let mut bytes=zero(4)?;let guard=self.physical.context.enter()?;let copy=self.physical.context.driver.api.copy_to(status,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish();drop(span_vc);if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop)}combine(combine(copy,sync),pop)?;if u32::from_le_bytes(bytes[..4].try_into().map_err(|_|Error::InvalidSize)?)!=0{return Err(Error::NonFiniteMmqOutput("Original Verifier full logits"))}Ok(()) } /// Actual original PLE history image; selected accepted row, never final-image /// metadata relabel. Borrowed destination must survive the graph aggregate. diff --git a/crates/cuda-driver/src/original_verify_schedule.rs b/crates/cuda-driver/src/original_verify_schedule.rs index 7debd7aa..ffa6f300 100644 --- a/crates/cuda-driver/src/original_verify_schedule.rs +++ b/crates/cuda-driver/src/original_verify_schedule.rs @@ -43,6 +43,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources< if resources.native_head_rows()?.rows()!=t||resources.native_head_rows()?.completed_logits()?.len()!=t*self.bank()?.geometry().vocabulary*4{return Err(Error::InvalidQwenShape)} let groups=window_plan::window_groups(t,self.split);let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?; let graph=stream.capture_owned(OriginalCapturePolicy::VerifierWindow,resources,|capture,r|{r.verifier_journal().capture_inputs(capture,t)?;record(capture,r,groups)})?; + if crate::host_profile::enabled(){eprintln!("DBG graph window t={t} groups={groups} nodes={:?}",graph.nodes());} self.window[t-1]=Some(graph);self.groups[t-1]=groups;Ok(()) } pub fn record_commit(&mut self,resources:R,mut record_extra:impl FnMut(&mut OriginalCapture<'_, 'ctx>,&mut R,usize)->Result<()>)->Result<()>{ @@ -52,7 +53,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources< r.verifier_journal().capture_commit_begin(capture)?;let mut gi=0;let mut qi=0; for layer in 0..48{if layer%4==3{r.verifier_qsa().capture_commit_layer(r.verifier_journal(),capture,qi)?;record_extra(capture,r,layer)?;qi+=1}else{r.verifier_journal().capture_commit_layer(capture,gi)?;gi+=1}} if r.verifier_journal().ple.is_some(){r.verifier_journal().capture_ple_commit(capture)?;}Ok(()) - })?);Ok(()) + })?);if crate::host_profile::enabled(){eprintln!("DBG graph commit nodes={:?}",self.commit.as_ref().and_then(|g|g.nodes()));}Ok(()) } /// Cached real all-T graph; CPU/GPU split and mapped flag rings match Original. /// Callback must finish actual expert/source work before returning. An error @@ -65,18 +66,28 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources< if wants_ple!=ple.is_some(){return Err(Error::InvalidQwenShape)} // The preceding asynchronous commit has the same compute stream. Its actual // mapped records are overwritten only after that completed receipt/window. + let span_wait=crate::host_profile::span("drv.run_wait_commit"); self.wait_commit()?; + drop(span_wait); + let span_stage=crate::host_profile::span("drv.stage"); let generation=self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens,position)?; if let Some(ple)=ple{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)?} + drop(span_stage); + let span_begin=crate::host_profile::span("drv.begin_window"); self.window[t-1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?; + drop(span_begin); self.active=true;if let Some(r)=&self.registration{r.begin_window(t,position as u64)} let operation=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||->Result{ + let span_launch=crate::host_profile::span("drv.launch"); self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; let _=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; + drop(span_launch); let groups=self.groups[t-1];for k in 0..window_plan::window_rings(groups){ let layer=k/groups;let group=k%groups;let want=window_plan::ring(layer,groups,group);let start=Instant::now();let mut last_flush=start;let mut spins=0u32; if let Some(r)=&self.registration{r.layer_step(want)} + let span_bell=crate::host_profile::span("drv.doorbell_wait"); loop{if self.bank()?.doorbell_sequence()?>=want{break}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue}let now=Instant::now();if self.registration.as_ref().is_some_and(diag::Registration::is_released){return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)"))}if now.duration_since(last_flush)>Duration::from_micros(2000){last_flush=now;let q=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;if q&&self.bank()?.doorbell_sequence()?Duration::from_secs(20){return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"))}} + drop(span_bell); let (begin,end)=window_plan::group_rows(t,groups,group);let rows=end-begin;let g=self.bank()?.geometry();let physical=self.bank()?.physical.clone(); let x=physical.mapped[6].try_borrow().map_err(|_|Error::InvalidQwenShape)?; let ids=physical.mapped[7].try_borrow().map_err(|_|Error::InvalidQwenShape)?; @@ -85,19 +96,26 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources< drop((x,ids,w)); // A pool with no GPU plan publishes the literal empty plan; actual DMA // producers publish A and raise B only from completed host callbacks. + let span_flag=crate::host_profile::span("drv.group_publish"); let flag=self.bank()?.physical.mapped[11].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?; if flag!=want{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group,want)?} let stalled=self.test_stall>0&&self.windows+1==self.test_stall&&k+1==window_plan::window_rings(groups); if !stalled{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,want)?;} + drop(span_flag); } // Original order: compute fence, then copy-stream fence (no late flag B), // then request sampling with Philox counter tied to actual position. + let span_sync=crate::host_profile::span("drv.sync_compute"); let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; + drop(span_sync); + let span_copy=crate::host_profile::span("drv.sync_copy"); self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; + drop(span_copy); // Every PCIe copy of the window has landed: the registered sources it read may go. self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources(); // The window's GPU stage stamps (single-group windows only, as in Original). if groups==1&&self.bank()?.profile_enabled(){let stamps=self.bank()?.read_profile()?;self.profile.add_window(&stamps,48,|l|l%4==3);} + let _span_head=crate::host_profile::span("drv.head"); self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(self.compute.as_mut().ok_or(Error::ContextPoisoned)?,&receipt,sampling) })); if let Some(r)=&self.registration{r.end_window()} @@ -107,17 +125,17 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources< /// Root prepares all genuine accepted-prefix publication permits AFTER this /// commit completion; this controller does not forge session capabilities. pub fn commit(&mut self,n_keep:usize,async_commit:bool)->Result<()>{ - if self.failed||self.active||!self.window_ready{return Err(Error::InvalidQwenShape)}self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?; + if self.failed||self.active||!self.window_ready{return Err(Error::InvalidQwenShape)}let span_commit=crate::host_profile::span("drv.commit_enqueue");self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?; let operation=(||{self.commit.as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.window_ready=false; let forced=std::env::var_os("STRATA_COMMIT_SYNC").is_some(); if async_commit&&!forced{self.event.as_mut().ok_or(Error::ContextPoisoned)?.record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit_pending=true;Ok(())} else{let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())} - })();if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(()) + })();drop(span_commit);if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(()) } /// The pending asynchronous commit's completion event (generate.cpp: what the next work on the commit's stream /// follows), for another stream to wait on the device. `None` when no commit is outstanding. pub fn pending_commit_event(&mut self)->Option<&mut OriginalGpuEvent<'ctx>>{if !self.commit_pending||self.failed{return None}self.event.as_mut()} - pub fn wait_commit(&mut self)->Result<()>{if !self.commit_pending{return Ok(())}let operation=(||{self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())})();self.commit_pending=false;if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())} + pub fn wait_commit(&mut self)->Result<()>{if !self.commit_pending{return Ok(())}let _span_wait=crate::host_profile::span("drv.commit_event_wait");let operation=(||{self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())})();self.commit_pending=false;if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())} /// Original final_R row, minted only after a genuine completed window. pub fn final_row(&self,row:usize)->Result>{self.require_completed_window()?;self.bank()?.completed_row(row)} fn require_completed_window(&self)->Result<()>{if self.failed||self.active||self.completed_generation!=Some(self.bank()?.generation){return Err(Error::InvalidQwenShape)}self.bank()?.staged_window()?;Ok(())} diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index c4402014..01f3998d 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -89,7 +89,7 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - let mut config = StackConfig::new(4096); + let mut config = StackConfig::new(env::var("LELEKA_SMOKE_MAX_CONTEXT").ok().and_then(|v| v.parse().ok()).unwrap_or(4096)); config.capacity = env::var("LELEKA_ORIGINAL_SERVE_CAPACITY").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index 967d14ec..122424bf 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -373,17 +373,25 @@ pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:us pub(crate) fn serve_request(controller:&mut OriginalSpecController,engine:&mut E, prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>, mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result { + let begin_span=super::original_serve_profile::span("ctrl.begin_request"); controller.begin_request(prompt,max_new,min_p,eos)?; + drop(begin_span); let (mut produced,mut rounds,mut stop)=(0usize,0usize,None); let looped=(||->std::result::Result<(),SpecError> { while !controller.finished() { let started=clock_ms(); + let vc_span=super::original_serve_profile::span("round.verify_commit"); let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break}; + drop(vc_span); + let emit_span=super::original_serve_profile::span("round.emit"); let emitted=emit(round.tokens()); + drop(emit_span); produced+=round.tokens().len();rounds+=1; if round.stopped_on_eos() {stop=Some(ServeStop::Eos);} // A failed emit still finishes the round (drain + join) before reporting. + let fr_span=super::original_serve_profile::span("round.finish"); let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel); + drop(fr_span); emitted?;finished?; } Ok(()) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_profile.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_profile.rs index 5985c7e3..ad028994 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_profile.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_profile.rs @@ -64,7 +64,9 @@ pub(crate) fn report(label: &str) { if !enabled() { return; } - let sums = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut())); + let mut sums = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut())); + // the driver's own host spans (window launch, doorbell waits, syncs, head, MTP draft graphs) + sums.extend(leleka_cuda_driver::host_profile::take()); let mut line = format!("DBG profile {label}:"); for (name, ms, count) in sums { line.push_str(&format!(" {name}={ms:.2}/{count}")); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 654151ca..eb5839b1 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -29,6 +29,7 @@ use super::{ original_serve_verifier::driver_error, }; use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use leleka_cuda_driver::{ Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, @@ -338,15 +339,52 @@ impl ResidencyStats { } } +/// The registered source spans (gate, up, down) of routed experts by (layer, expert), kept for the life of the stack: +/// the mapped bank never moves, so a span set found once (the per-call scan through the binding costs 30-70 us) is +/// the span set of every later PCIe stage, adaptive swap and lent-slot refill of that expert. +/// `LELEKA_SPAN_CACHE=off` looks every set up again (A/B control). +#[derive(Default)] +pub(crate) struct SpanCache { + sets: std::collections::HashMap, +} +impl std::fmt::Debug for SpanCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "SpanCache({} sets)", self.sets.len()) + } +} +fn span_cache_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_SPAN_CACHE").is_ok_and(|v| v == "off" || v == "0")) +} +impl SpanCache { + fn key(layer: usize, expert: u32) -> u32 { + (layer * EXPERTS) as u32 + expert + } + fn get(&self, layer: usize, expert: u32) -> Option<[ResidentExpertBankSpan; 3]> { + self.sets.get(&Self::key(layer, expert)).cloned() + } + fn contains(&self, layer: usize, expert: u32) -> bool { + self.sets.contains_key(&Self::key(layer, expert)) + } + fn insert(&mut self, layer: usize, expert: u32, spans: [ResidentExpertBankSpan; 3]) { + self.sets.insert(Self::key(layer, expert), spans); + } +} + /// What survives requests: the routed counts of the adaptive tier (`drive.d.usage`) and the counters. #[derive(Debug, Default)] pub(crate) struct ResidencyState { usage: Vec, pub(crate) stats: ResidencyStats, + pub(crate) spans: SpanCache, } impl ResidencyState { pub(crate) fn new(config: &ExpertTierConfig) -> Self { - Self { usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() }, stats: ResidencyStats::default() } + Self { + usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() }, + stats: ResidencyStats::default(), + spans: SpanCache::default(), + } } } @@ -363,6 +401,64 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> { pub(in crate::qwen_forward) adapt_every: u32, pub(in crate::qwen_forward) adapt_swaps: usize, } +impl GpuExpertPool<'_, '_, '_> { + fn source_spans(&mut self, layer: usize, experts: &[u32]) -> Result> { + source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, experts) + } +} +/// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU +/// tier's admission (or the binding's own scan on the legacy path) and remembered. +fn source_spans( + cpu: &mut CpuExpertPool<'_>, + bank: &MappedExpertBank<'_>, + moe: &MoeWeightCache<'_>, + binding: &ModelBinding, + known: &mut SpanCache, + layer: usize, + experts: &[u32], +) -> Result> { + { + let cached = span_cache_enabled(); + let fetch: Vec = if cached { + experts.iter().copied().filter(|&e| !known.contains(layer, e)).collect() + } else { + experts.to_vec() + }; + let mut fetched: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); + fetched.try_reserve_exact(fetch.len()).map_err(|_| Error::InputAllocation)?; + if !fetch.is_empty() { + // The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the + // PCIe sources too; the legacy path keeps the per-expert full scan. + match cpu.admitted_spans(layer as u32, &fetch) { + Some(admitted) => { + for spans_of in admitted? { + if !bank.eligible(&spans_of) { + return Err(Error::IdentityMismatch); + } + fetched.push(spans_of); + } + } + None => { + for &e in &fetch { + fetched.push(moe.original_expert_spans(binding, layer as u32, e)?); + } + } + } + } + if !cached { + return Ok(fetched); + } + for (&e, spans_of) in fetch.iter().zip(fetched) { + known.insert(layer, e, spans_of); + } + let mut spans = Vec::new(); + spans.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?; + for &e in experts { + spans.push(known.get(layer, e).ok_or(Error::IdentityMismatch)?); + } + Ok(spans) + } +} impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { fn run_group( &mut self, @@ -395,25 +491,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); drop(profile_split); let profile_spans = super::original_serve_profile::span("pool.spans"); - let mut spans = Vec::new(); - spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?; - // The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the - // PCIe sources too; the legacy path keeps the per-expert full scan. - match self.cpu.admitted_spans(layer as u32, &split.pcie_experts) { - Some(admitted) => { - for spans_of in admitted? { - if !self.bank.eligible(&spans_of) { - return Err(Error::IdentityMismatch); - } - spans.push(spans_of); - } - } - None => { - for &e in &split.pcie_experts { - spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?); - } - } - } + let spans = source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, &split.pcie_experts)?; super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock); super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64); drop(profile_spans); @@ -461,16 +539,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps); for swap in &swaps { let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; - let spans = match self.cpu.admitted_spans(swap.layer as u32, &[swap.incoming as u32]) { - Some(admitted) => { - let admitted = admitted?.pop().ok_or(Error::IdentityMismatch)?; - if !self.bank.eligible(&admitted) { - return Err(Error::IdentityMismatch); - } - admitted - } - None => self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?, - }; + let spans = self.source_spans(swap.layer, &[swap.incoming as u32])?.pop().ok_or(Error::IdentityMismatch)?; self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?; } self.cache.arm_swaps().map_err(|e| driver_error(&e))?; @@ -605,15 +674,30 @@ pub(in crate::qwen_forward) fn refill_lent<'ctx>( binding: &ModelBinding, moe: &MoeWeightCache<'ctx>, cache: &mut OriginalExpertCache<'ctx>, + known: &mut SpanCache, ) -> Result { + let cached = span_cache_enabled(); let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; let mut refilled = 0usize; for slot in 0..cache.slots() { let Some((layer, expert)) = cache.needs_refill(slot).map_err(|e| driver_error(&e))? else { continue }; - let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?; + let span_spans = super::original_serve_profile::span("refill.spans"); + let spans = match if cached { known.get(layer, expert as u32) } else { None } { + Some(spans) => spans, + None => { + let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?; + if cached { + known.insert(layer, expert as u32, spans.clone()); + } + spans + } + }; + drop(span_spans); + let _span_queue = super::original_serve_profile::span("refill.queue"); cache.fill_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; refilled += 1; } + let _span_sync = super::original_serve_profile::span("refill.sync"); cache.sync_queued().map_err(|e| driver_error(&e))?; Ok(refilled) } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 435c7607..1e3dc2e0 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -604,6 +604,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { drop(serve_span); if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } let (mut verifier, mut host) = engine.into_port().0.into_parts(); + // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) + let gpu_profile = verifier.profile_report(); + if !gpu_profile.is_empty() { + eprintln!("DBG verify-profile:{gpu_profile}"); + } // conversation cache: the session can be continued as is only when the draft ring // stands at its position (then its recurrent state is settled to match) let live = conversation.is_some() @@ -683,7 +688,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { drop(p); let _p = profile::span("prefill.refill"); let refilled = match (self.loan, self.expert_cache.as_mut()) { - (Some(_), Some(cache)) => original_serve_residency::refill_lent(self.binding, &self.moe, cache).map(|_| ()), + (Some(_), Some(cache)) => original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans).map(|_| ()), _ => Ok(()), }; match (read, refilled) { @@ -706,12 +711,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's // sampling parameters configure the actor for the whole request. + let mtp_setup_span = profile::span("prefill.mtp_setup"); self.executor.set_mtp_prompt_len(binding, n as i64)?; self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; self.executor.set_mtp_draft_sampling(binding, &request.params)?; + drop(mtp_setup_span); if n < 2 { return Ok(()); } + let setup_span = profile::span("prefill.setup"); let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; let options = PromptOptions { @@ -733,6 +741,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let capacity = self.config.capacity; let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); + drop(setup_span); for action in plan { crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); if action.path == PromptPath::FinalSeed { @@ -966,6 +975,7 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { self.reused = 0; self.resume_point = 0; let mut conversation = self.conversation.take()?; + let _resume_span = profile::span("request.resume"); let resume = if self.broken.is_some() { conversation.invalidate(); None diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_suffix.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_suffix.rs index f0eab5ae..cd3c71ab 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_suffix.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_suffix.rs @@ -4,6 +4,14 @@ use super::contract::{Error, Result}; struct Slot { key:u64,pos:[u32;4],n:u8 } pub(crate) struct SuffixDrafter { min_match:usize,max_match:usize,history:Vec,table:Box<[Slot]>,mask:usize,last_match:usize, + /// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is + /// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots). + touched:Vec, +} +/// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control). +fn sparse_reset()->bool { + static ON:std::sync::OnceLock=std::sync::OnceLock::new(); + *ON.get_or_init(||!std::env::var("LELEKA_SUFFIX_RESET").is_ok_and(|v|v=="full")) } fn mix(mut x:u64)->u64 { x^=x>>33;x=x.wrapping_mul(0xff51afd7ed558ccd);x^=x>>33; @@ -16,14 +24,23 @@ impl SuffixDrafter { let mut table=Vec::new();table.try_reserve_exact(cap).map_err(|_|Error::InputAllocation)?; table.resize(cap,Slot::default()); let mut history=Vec::new();history.try_reserve_exact(capacity_tokens).map_err(|_|Error::InputAllocation)?; - Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0}) + Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0,touched:Vec::new()}) } pub(crate) fn metadata_bytes(&self)->Result { self.history.capacity().checked_mul(std::mem::size_of::()) .and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::())?)) .and_then(|n|n.checked_add(std::mem::size_of::())).ok_or(Error::Overflow) } - pub(crate) fn reset(&mut self) {self.history.clear();self.table.fill(Slot::default());self.last_match=0;} + pub(crate) fn reset(&mut self) { + self.history.clear();self.last_match=0; + // Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill. + if sparse_reset()&&self.touched.len()<=self.table.len()/4 { + for &i in &self.touched {self.table[i as usize]=Slot::default();} + } else { + self.table.fill(Slot::default()); + } + self.touched.clear(); + } pub(crate) fn reserve_reset(&self,n:usize)->Result<()> { if n>self.history.capacity() {return Err(Error::InputAllocation);}Ok(()) } @@ -38,7 +55,7 @@ impl SuffixDrafter { let mut i=key as usize & self.mask; for _ in 0..=self.mask { if self.table[i].key==key {return Some(i);} - if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;return Some(i);} + if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;self.touched.push(i as u32);return Some(i);} i=(i+1)&self.mask; }None } @@ -68,3 +85,26 @@ impl SuffixDrafter { pub(crate) fn last_match(&self)->usize {self.last_match} pub(crate) fn len(&self)->usize {self.history.len()} } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_sparse_reset_leaves_the_same_empty_table_as_a_full_clear() { + let mut drafter=SuffixDrafter::new(3,64,4096).unwrap(); + let tokens:Vec=(0..300).map(|i|(i*7+i/3)%97).collect(); + drafter.append(&tokens).unwrap(); + assert!(!drafter.touched.is_empty()); + drafter.reset(); + assert!(drafter.table.iter().all(|s|s.key==0&&s.n==0&&s.pos==[0;4]),"every claimed slot is cleared"); + assert!(drafter.touched.is_empty()&&drafter.len()==0); + // the same tokens give the same proposals after the reset as on a fresh drafter + let mut fresh=SuffixDrafter::new(3,64,4096).unwrap(); + drafter.append(&tokens).unwrap();fresh.append(&tokens).unwrap(); + let (mut a,mut b)=([0;7],[0;7]); + assert_eq!(drafter.propose(&mut a),fresh.propose(&mut b)); + assert_eq!(a,b); + assert_eq!(drafter.last_match(),fresh.last_match()); + } +} diff --git a/crates/model-format/src/qwen4exp_expert_source_bank.rs b/crates/model-format/src/qwen4exp_expert_source_bank.rs index d2a6b9ae..75d41e58 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank.rs @@ -460,6 +460,7 @@ impl ResidentExpertBankLease { } /// Exact named bank retained from an admitted catalog, not caller bytes/ranges. /// `bytes` is initialized immutable addressability, never a finite/pinned proof. +#[derive(Clone)] pub struct ResidentExpertBankMember { descriptor: BankDescriptor, tensor: Rc, @@ -557,6 +558,7 @@ impl Qwen4ExpArtifact { /// Immutable initialized fixed-expert addressability, not source health, /// registration, finite data or a runtime row/Context certificate. +#[derive(Clone)] pub struct ResidentExpertBankSpan { member: ResidentExpertBankMember, expert: u32,