From f6b48226e327b9f242cec2bce519ef5e1dd8cee8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 15:51:00 +0200 Subject: [PATCH 1/7] perf(prefill): reuse the GDN next-state finite guard across layers and chunks Every GDN layer of every prompt chunk created a GdnStateFiniteGuard, which loads its CUDA module (cuModuleLoadData) and allocates its status word, and closed it again at the layer's end. The dense cache now keeps up to four idle guards: a layer borrows one and gives it back after a clean finish; a failed guard is closed, never reused. The guard resets its status word on every check, so reuse changes no result. PREFILL-PROFILE also splits the GDN mixer into state_in / compute / state_out. Co-Authored-By: Claude Opus 5.5 --- .../cuda-driver/src/gdn_state_finite_guard.rs | 5 +++ .../src/qwen_forward/dense_weight_cache.rs | 42 +++++++++++++++++++ .../src/qwen_forward/gdn_chunk_device.rs | 7 +--- .../src/qwen_forward/prefill_profile.rs | 14 ++++++- .../src/qwen_forward/prompt_device_rows.rs | 7 ++++ 5 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/cuda-driver/src/gdn_state_finite_guard.rs b/crates/cuda-driver/src/gdn_state_finite_guard.rs index 4d890323..1b1d15f2 100644 --- a/crates/cuda-driver/src/gdn_state_finite_guard.rs +++ b/crates/cuda-driver/src/gdn_state_finite_guard.rs @@ -68,6 +68,11 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { Ok(owner) } + /// Whether this guard refused or lost its owners (a failed guard is never reused). + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + /// Actual private status allocation; no state buffer is allocated here. pub fn allocated_bytes(&self) -> usize { self.status.as_ref().map_or(0, |status| status.bytes) diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs index 8928c223..09b826e1 100644 --- a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs @@ -77,6 +77,9 @@ pub(crate) struct DenseWeightCache<'ctx> { gdn_qk_workspace: Option>>, qsa_attention_workspace: Option>>, gdn_verification: Option>>>, + /// Idle GDN next-state finite guards (each owns a loaded module and a status word): a prompt chunk's GDN + /// layer borrows one and gives it back, instead of loading the module once per layer and chunk. + gdn_guards: RefCell>>, gr_scratch: Option>>, qsa_input: Option>>, qsa_keys: Option>>, @@ -377,6 +380,39 @@ impl<'ctx> DenseWeightCache<'ctx> { let qsa=leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?; gr.checked_add(qsa).ok_or(Error::Overflow) } + /// An idle GDN next-state finite guard of this cache's Context, or a new one. + pub(in crate::qwen_forward) fn take_gdn_guard( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result> { + let context = self.retained_context(binding, context)?; + let idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); + match idle { + Some(guard) if !guard.is_failed() => Ok(guard), + Some(guard) => { + let _ = guard.close(); + context.gdn_state_finite_guard().map_err(driver_error) + } + None => context.gdn_state_finite_guard().map_err(driver_error), + } + } + /// Give a guard back after a clean use; a failed one is closed instead. + pub(in crate::qwen_forward) fn return_gdn_guard( + &self, + guard: leleka_cuda_driver::GdnStateFiniteGuard<'ctx>, + ) -> Result<()> { + if guard.is_failed() { + return guard.close().map_err(driver_error); + } + let mut idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + if idle.len() >= 4 { + drop(idle); + return guard.close().map_err(driver_error); + } + idle.push(guard); + Ok(()) + } pub(in crate::qwen_forward) fn has_gdn_verification_workspace(&self) -> bool { self.gdn_verification.is_some() } @@ -414,6 +450,7 @@ impl<'ctx> DenseWeightCache<'ctx> { gdn_qk_workspace: None, qsa_attention_workspace: None, gdn_verification: None, + gdn_guards: RefCell::new(Vec::new()), gr_scratch: None, qsa_input: None, qsa_keys: None, @@ -1385,6 +1422,11 @@ impl<'ctx> DenseWeightCache<'ctx> { } pub(crate) fn close(self) -> Result<()> { let mut error = self.mirror_failed.get().then_some(Error::CudaExecution); + for guard in self.gdn_guards.take() { + if let Err(e) = guard.close() { + error.get_or_insert(driver_error(e)); + } + } if let Some(modules) = self.modules && let Err(e) = modules.close() { diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device.rs index c02b383c..910966d9 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device.rs @@ -147,7 +147,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { // No position-only key or intermediate host state is manufactured. owner.state = Some(upload(context, owner.start.prior().values())?); owner.next = Some(allocate(context, STATE_ELEMENTS)?); - owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?); + owner.guard = Some(cache.take_gdn_guard(binding, context)?); Ok(()) })(); if let Err(primary) = operation { @@ -563,10 +563,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { })?; } if let Some(guard) = self.guard.take() { - guard.close().map_err(|e| { - self.failed.set(true); - driver_error(e) - })?; + cache.return_gdn_guard(guard).inspect_err(|_| self.failed.set(true))?; } let mut mirror = cache.gdn_mirror(binding, prior.layer().get(), self.context)?; let buffer = self.state.take().ok_or(Error::IdentityMismatch)?; diff --git a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs index 69fcde9b..720bca0a 100644 --- a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs +++ b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs @@ -23,6 +23,12 @@ pub(crate) enum Stage { AttnRead, /// GDN mixer (projections, conv, recurrence, out) incl. the following GR injection. Gdn, + /// GDN layer state staging: the chunk owner's prior upload, scratch and finite guard. + GdnStateIn, + /// GDN projections, conv, recurrence and output of the chunk. + GdnCompute, + /// GDN end state download, mirror adoption and journal staging. + GdnStateOut, /// QSA mixer (index, selection, attention, KV) incl. the following GR injection. Qsa, /// GR read before the FFN. @@ -50,8 +56,9 @@ pub(crate) enum Stage { /// Expert-cache slot loan for the chunk's arena (expert tier only). Lend, } -const STAGES: [Stage; 19] = [ - Stage::Input, Stage::Initialize, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::Qsa, +const STAGES: [Stage; 22] = [ + Stage::Input, Stage::Initialize, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::GdnStateIn, + Stage::GdnCompute, Stage::GdnStateOut, Stage::Qsa, Stage::FfnRead, Stage::Moe, Stage::MoePrepare, Stage::MoeSpans, Stage::MoeRing, Stage::MoeFinish, Stage::Inject, Stage::Final, Stage::DraftKv, Stage::FinishPreview, Stage::Publish, Stage::Lend, ]; @@ -64,6 +71,9 @@ impl Stage { Self::Validate => "validate", Self::AttnRead => "attn_read", Self::Gdn => "gdn", + Self::GdnStateIn => "gdn.state_in", + Self::GdnCompute => "gdn.compute", + Self::GdnStateOut => "gdn.state_out", Self::Qsa => "qsa", Self::FfnRead => "ffn_read", Self::Moe => "moe", diff --git a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs index cac0a09b..b0751bfc 100644 --- a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs +++ b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs @@ -367,13 +367,20 @@ fn produce_original_gdn<'arena,'loan,'ctx>(binding:&ModelBinding,dense:&DenseWei txn:&OriginalPromptTxn<'_, '_>,context:&'ctx Context<'ctx>,layer:LayerId, read:OriginalDeviceGrRead<'arena,'loan,'ctx>,gdn:&mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, )->Result>{ + use super::prefill_profile::{span,Stage as P,Drain}; + let drain=Some(context as &dyn Drain); + let state_in=span(P::GdnStateIn,drain); let prior=txn.gdn_prior(layer)?; let(start,rows)=super::session::chunk::GdnChunkStart::from_original_prompt(txn,layer,&prior)?; let mut owner=super::gdn::chunk_device::GdnChunkDevice::new(binding,context,dense,start.clone())?; + drop(state_in); + let compute=span(P::GdnCompute,drain); let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; let(block,edges)=super::gdn::GdnStage::produce_prompt_device(binding,layer,dense,context, &mut owner,rows,read,gdn,&mut workspace)?; drop(workspace); + drop(compute); + let _state_out=span(P::GdnStateOut,drain); let seal=super::session::chunk::GdnChunkSeal::from_original_prompt(txn,&start,edges)?; let next=owner.finish(seal,binding,dense)?;txn.stage_gdn(&prior,next)?;Ok(block) } From fdb1071783b17dfbf220143edbe2dcb666f8eb7e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 15:52:23 +0200 Subject: [PATCH 2/7] perf(prefill): profile spans for input embedding/PLE and row init sources/upload Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/executor_original_prompt.rs | 5 ++++- crates/leleka-runtime/src/qwen_forward/input.rs | 3 +++ .../src/qwen_forward/prefill_profile.rs | 16 ++++++++++++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs index 22c40cb3..02527f3f 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs @@ -274,10 +274,13 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ drop(input_span); let init_span=prof::span(PStage::Initialize,drain); let mut sources=Vec::new();sources.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; + let sources_span=prof::span(PStage::InitSources,None); for local in 0..tokens.len(){sources.push(PromptDeviceSource::from_original(binding,self.context,&txn,local)?);} + drop(sources_span); + let upload_span=prof::span(PStage::InitUpload,drain); let prompt=self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; let rows=PromptDeviceRows::initialize(binding,dense,self.context,prompt,arena.begin_rows(tokens.len()).map_err(driver_error)?,sources)?; - drop(init_span); + drop(upload_span);drop(init_span); let mut carrier=Carrier::Plain(rows); for layer in binding.ordered_layers(){ let index=layer.index();let role=super::super::gr::GrRole::Attention(index); diff --git a/crates/leleka-runtime/src/qwen_forward/input.rs b/crates/leleka-runtime/src/qwen_forward/input.rs index f172a1ec..03df518b 100644 --- a/crates/leleka-runtime/src/qwen_forward/input.rs +++ b/crates/leleka-runtime/src/qwen_forward/input.rs @@ -115,8 +115,11 @@ impl InputStage { txn.input_predecessors()?, binding.input_constants(), )?; + let embedding_span = super::prefill_profile::span(super::prefill_profile::Stage::InputEmbedding, None); let embedding = binding.embedding_row(token.get()).map_err(binding_error)?; let streams = ResidualStreams::broadcast(&embedding)?; + drop(embedding_span); + let _ple_span = super::prefill_profile::span(super::prefill_profile::Stage::InputPle, None); let ple = cache.gather(kar, &rows)?; Ok(InputReady { binding: binding.identity(), diff --git a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs index 720bca0a..a908ac17 100644 --- a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs +++ b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs @@ -13,8 +13,16 @@ use std::time::{Duration, Instant}; pub(crate) enum Stage { /// Host input staging of every row (token embedding, KAR/PLE inputs). Input, + /// Token embedding rows of the input staging (KAR path). + InputEmbedding, + /// PLE rows of the input staging (KAR gather, KAR path). + InputPle, /// Row source keys and the initial R/PLE upload. Initialize, + /// Row source keys and their finite checks. + InitSources, + /// Initial R/PLE staging and upload. + InitUpload, /// Layer-one PLE application and its history. Ple, /// Chronological per-row session validation of every phase. @@ -56,8 +64,8 @@ pub(crate) enum Stage { /// Expert-cache slot loan for the chunk's arena (expert tier only). Lend, } -const STAGES: [Stage; 22] = [ - Stage::Input, Stage::Initialize, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::GdnStateIn, +const STAGES: [Stage; 26] = [ + Stage::Input, Stage::InputEmbedding, Stage::InputPle, Stage::Initialize, Stage::InitSources, Stage::InitUpload, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::GdnStateIn, Stage::GdnCompute, Stage::GdnStateOut, Stage::Qsa, Stage::FfnRead, Stage::Moe, Stage::MoePrepare, Stage::MoeSpans, Stage::MoeRing, Stage::MoeFinish, Stage::Inject, Stage::Final, Stage::DraftKv, Stage::FinishPreview, Stage::Publish, Stage::Lend, @@ -66,7 +74,11 @@ impl Stage { fn name(self) -> &'static str { match self { Self::Input => "input", + Self::InputEmbedding => "input.embedding", + Self::InputPle => "input.ple", Self::Initialize => "init", + Self::InitSources => "init.sources", + Self::InitUpload => "init.upload", Self::Ple => "ple", Self::Validate => "validate", Self::AttnRead => "attn_read", From 4780170fe3d8163eadb5f03eb9747193672cb25b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 16:09:34 +0200 Subject: [PATCH 3/7] perf(prefill): per-command timing of the GDN prompt producer; prefill benches can read from the empty prompt - LELEKA_BRINGUP_TRACE + LELEKA_PREFILL_PROFILE_SYNC: the GDN prompt producer drains after every kernel/GEMM and a PREFILL-COMMANDS line per chunk sums them (driver command_profile). - LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA=1 (EXPERIMENTAL diagnostic, wrong outputs): the copy ring moves no expert bytes, to time its compute alone. - The long-context smoke reads every request from the empty prompt unless LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION=yes (the stack now defaults to --prompt-cache 6); the laptop bench takes LELEKA_LAPTOP_PROMPT_CACHE=0. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/command_profile.rs | 37 +++++++++++++++++++ crates/cuda-driver/src/gdn_prompt_device.rs | 17 ++++++++- crates/cuda-driver/src/lib.rs | 2 + crates/cuda-driver/src/mmq_original_ring.rs | 11 +++++- .../src/backend_original_serve_laptop.rs | 4 ++ .../src/backend_original_serve_smoke.rs | 5 +++ .../src/qwen_forward/prefill_profile.rs | 4 ++ 7 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 crates/cuda-driver/src/command_profile.rs diff --git a/crates/cuda-driver/src/command_profile.rs b/crates/cuda-driver/src/command_profile.rs new file mode 100644 index 00000000..4f516b25 --- /dev/null +++ b/crates/cuda-driver/src/command_profile.rs @@ -0,0 +1,37 @@ +//! `LELEKA_BRINGUP_TRACE` + `LELEKA_PREFILL_PROFILE_SYNC`: per-command wall time of the batched prompt +//! producers (each command drained on its own; attribution only, the drains slow the run). The runtime's +//! `PREFILL-PROFILE` takes and prints the totals once per chunk. +use std::sync::Mutex; +use std::time::Duration; + +static TOTALS: Mutex> = Mutex::new(Vec::new()); + +/// Whether per-command timing is on (both switches set). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some() + }) +} +pub(crate) fn add(producer: &'static str, index: usize, label: &'static str, elapsed: Duration) { + if let Ok(mut totals) = TOTALS.lock() { + match totals.iter_mut().find(|e| e.0 == producer && e.1 == index) { + Some(entry) => { + entry.3 += elapsed; + entry.4 += 1; + } + None => totals.push((producer, index, label, elapsed, 1)), + } + } +} +/// The accumulated totals as `producer#index:label=ms(xcount)` and reset. +pub fn take_report() -> String { + let Ok(mut totals) = TOTALS.lock() else { return String::new() }; + let mut entries = std::mem::take(&mut *totals); + entries.sort_by_key(|e| (e.0, e.1)); + entries + .iter() + .map(|(p, i, l, d, n)| format!("{p}#{i}:{l}={:.1}(x{n})", d.as_secs_f64() * 1e3)) + .collect::>() + .join(" ") +} diff --git a/crates/cuda-driver/src/gdn_prompt_device.rs b/crates/cuda-driver/src/gdn_prompt_device.rs index d62e79dc..edef0dd8 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -507,15 +507,22 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { return Err(e); } }; + let timed = crate::command_profile::enabled(); + let started = std::time::Instant::now(); let mut operation = context .driver .api .copy_from(hin, &history_bytes) .and_then(|()| context.driver.api.synchronize()); - for cmd in &mut commands { + if timed { + crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); + } + for (index, cmd) in commands.iter_mut().enumerate() { if operation.is_err() { break; } + let started = std::time::Instant::now(); + let label = match cmd { DeviceCommand::Kernel { .. } => "kernel", DeviceCommand::Gemm { .. } => "gemm" }; operation = match cmd { DeviceCommand::Kernel { function, @@ -540,8 +547,13 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { offset, beta, } => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta), + }; + if timed && operation.is_ok() { + operation = blas.synchronize(); + crate::command_profile::add("gdn", index + 1, label, started.elapsed()); } } + let started = std::time::Instant::now(); let sync = blas.synchronize(); if operation.is_ok() && sync.is_ok() { operation = context @@ -551,6 +563,9 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { .and_then(|()| context.driver.api.copy_to(hout, &mut final_history)) } let all = context.driver.api.synchronize(); + if timed { + crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); + } let pop = guard.finish(); let result = combine(combine(combine(operation, sync), all), pop); if result.is_err() { diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index bde54b31..53f0d960 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -132,6 +132,8 @@ pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace}; mod qwen_ffi; pub mod experimental; +/// Per-command timing of the batched prompt producers (bring-up profiling only). +pub mod command_profile; #[cfg(all( feature = "cuda-driver", target_os = "linux", diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 4a3d2cb4..302f9529 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -9,6 +9,12 @@ use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole}; use std::rc::Rc; #[path = "mmq_original_host_stage.rs"] mod host_stage; +/// `LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA=1` (EXPERIMENTAL, diagnostic, wrong outputs): the copy ring issues no +/// expert copies, so a profile shows the ring's compute alone. Never set in serving. +fn skip_expert_dma() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA").is_some_and(|v| v == "1")) +} use host_stage::{HostStage, Job}; const COMMAND_CAP: usize = 2048; trait RingArena: GroupArena { @@ -527,7 +533,10 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; - if let Some(j) = source.job { + if skip_expert_dma() { + // EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it + // held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream. + } else if let Some(j) = source.job { // prefill.cpp stage_one, unpinned: the stager's page-locked copy (waits only if it is behind), then DMA let blob = gu * 2 + down; let host = self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?; diff --git a/crates/leleka-runtime/src/backend_original_serve_laptop.rs b/crates/leleka-runtime/src/backend_original_serve_laptop.rs index 61fed1b5..143dbe42 100644 --- a/crates/leleka-runtime/src/backend_original_serve_laptop.rs +++ b/crates/leleka-runtime/src/backend_original_serve_laptop.rs @@ -104,6 +104,10 @@ fn original_serve_laptop_bench() { config.kv_resident = v.parse().expect("LELEKA_ORIGINAL_SERVE_KV_RESIDENT must be a count"); } config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + // LELEKA_LAPTOP_PROMPT_CACHE=0 reads every request from the empty prompt (the stack default is --prompt-cache 6) + if env::var("LELEKA_LAPTOP_PROMPT_CACHE").is_ok_and(|v| v == "0") { + config.conversation = None; + } config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}", diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index dd7192fd..2d832c5c 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -346,6 +346,11 @@ fn original_serve_long_context_streamed_kv_smoke() { config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); config.kv_resident = resident; + // A prefill measurement: every request is read from the empty prompt unless + // LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION=yes keeps the stack's conversation cache. + if !env::var("LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION").is_ok_and(|v| v == "yes") { + config.conversation = None; + } config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); eprintln!("long-smoke capacity={} expert tier {:?}", config.capacity, config.expert_tier); diff --git a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs index a908ac17..407614f0 100644 --- a/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs +++ b/crates/leleka-runtime/src/qwen_forward/prefill_profile.rs @@ -192,6 +192,10 @@ pub(crate) fn end_chunk(first: u64, tokens: usize) { let covered: Duration = top.iter().map(|s| acc[s.index()]).sum(); line.push_str(&format!(" other={:.1}", ms(total.saturating_sub(covered)))); eprintln!("{line}"); + let commands = leleka_cuda_driver::command_profile::take_report(); + if !commands.is_empty() { + eprintln!("PREFILL-COMMANDS first={first} {commands}"); + } } #[cfg(test)] From 84983abdb22dfb7eb68d9ed0fb6c6b6ff47ceff1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 17:31:29 +0200 Subject: [PATCH 4/7] perf(prefill): stage the initial rows in one pass per buffer PromptDeviceRows::initialize concatenated every row's 10240 stream values and 2560 PLE values into two host vectors, then the driver scanned them for non-finite values and converted them to bytes: three passes over ~420 MB at an 8192-token chunk. The driver's initialize_rows takes the row slices and builds the two byte buffers in one pass each, with the same finite refusal and the same device bytes. Co-Authored-By: Claude Opus 5.5 --- .../cuda-driver/src/native_prompt_device.rs | 45 ++++++++++++++++++- .../src/qwen_forward/prompt_device_rows.rs | 8 ++-- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/cuda-driver/src/native_prompt_device.rs b/crates/cuda-driver/src/native_prompt_device.rs index 3bde02fa..fe22131f 100644 --- a/crates/cuda-driver/src/native_prompt_device.rs +++ b/crates/cuda-driver/src/native_prompt_device.rs @@ -658,7 +658,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { /// Initial authentic prompt staging only. Later phases never download R. pub fn initialize<'arena, 'loan>( &mut self, - mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, streams: &[f32], embedding: &[f32], @@ -673,6 +673,49 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } let s = encode(streams)?; let e = encode(embedding)?; + self.upload_initial(lease, workspace, s, e) + } + /// `initialize` over the rows in place: each row's 10240 residual-stream values and 2560 PLE embedding + /// values, in row order. The same finite refusal and the same device bytes, staged in one pass per buffer + /// instead of a caller concatenation, a finite scan and a byte conversion. + pub fn initialize_rows<'arena, 'loan>( + &mut self, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + rows: &[(&[f32], &[f32])], + ) -> Result> { + self.validate(&lease, workspace)?; + let t = lease.rows(); + if rows.len() != t || rows.iter().any(|(s, e)| s.len() != 10240 || e.len() != 2560) { + return Err(Error::InvalidQwenShape); + } + let mut s = Vec::new(); + s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?; + let mut e = Vec::new(); + e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?; + let mut finite = true; + for (streams, embedding) in rows { + for x in streams.iter() { + finite &= x.is_finite(); + s.extend_from_slice(&x.to_le_bytes()); + } + for x in embedding.iter() { + finite &= x.is_finite(); + e.extend_from_slice(&x.to_le_bytes()); + } + } + if !finite { + return Err(Error::NonFiniteMmqOutput("Original prompt input")); + } + self.upload_initial(lease, workspace, s, e) + } + fn upload_initial<'arena, 'loan>( + &mut self, + mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + s: Vec, + e: Vec, + ) -> Result> { let rh = Self::span(&lease, S::R, 40960)?; let eh = Self::span(&lease, S::PleEmbedding, 10240)?; let guard = match self.context.enter() { diff --git a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs index b0751bfc..9119e4b2 100644 --- a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs +++ b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs @@ -193,11 +193,11 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{ let sources=Sources{binding:binding.identity(),context,rows,role:GrRole::Attention(0),validated:0};sources.validate(binding,cache)?; // Only initial real source staging: Original also uploads initial R // and PLE embeddings. Later layer phases retain this same device R. - let mut streams=Vec::new();streams.try_reserve_exact(sources.rows.len()*10240).map_err(|_|Error::InputAllocation)?; - let mut embedding=Vec::new();embedding.try_reserve_exact(sources.rows.len()*2560).map_err(|_|Error::InputAllocation)?; - for s in &sources.rows{streams.extend_from_slice(s.input.streams().values());embedding.extend_from_slice(s.input.ple_embedding());} + // The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals). + let mut slices=Vec::new();slices.try_reserve_exact(sources.rows.len()).map_err(|_|Error::InputAllocation)?; + for s in &sources.rows{slices.push((s.input.streams().values(),s.input.ple_embedding()));} let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.initialize(lease,&mut workspace,&streams,&embedding).map_err(micro_driver_error)})(); + producer.initialize_rows(lease,&mut workspace,&slices).map_err(micro_driver_error)})(); if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} let device=result?;sources.validate(binding,cache)?; if let Some(phase)=sources.original_phase()?{phase.initialize(sources.rows.len())?;} From 80627bc86d3a611177a4574c9ae5bfad1c72f0f1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 17:31:29 +0200 Subject: [PATCH 5/7] perf(prefill): prefill.cpp stream_all issuer for registered expert banks From the first MoE layer of a chunk of at least 1024 rows, an issuer thread copies every expert the arena cache does not hold, layer by layer in id order, from the page-locked bank into the copy ring (entry k in slot k % ring), the Original's stream_all with its D-5 issuer thread. The copies for the next layers therefore run while the mixers, GR reads and routers compute instead of only during each layer's MoE (the skip-DMA diagnostic of job 705 put the DMA at ~0.77 s of the 1.1 s ring of an 8192-token chunk). The issuer only enqueues (no compute), waits for entry k - ring's 'used' event before reusing a slot and keeps at most LELEKA_PREFILL_STREAM_INFLIGHT (4) copies queued, so the compute path's context-wide synchronizations wait for a few copies at most. The per-layer copy ring consumes the stream: gather waits for the entry's 'copied' event, records 'used', and entries a layer does not route are released in order. Every routed entry is checked to copy exactly the bytes its admitted span names. The stream ends with the last layer, on any layer failure and on every forward error before the transaction rolls back. Same bytes into ring slots, same gather and grouped MMQ: products unchanged. LELEKA_PREFILL_STREAM=0 keeps the per-layer ring; pageable banks keep the HostStage path. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/mapped_expert_bank.rs | 20 ++ .../src/mmq_original_chunk_stream.rs | 276 ++++++++++++++++++ crates/cuda-driver/src/mmq_original_ring.rs | 269 ++++++++++++++++- .../src/original_expert_stager_ffi.rs | 27 ++ .../src/qwen_forward/cache_original_prompt.rs | 41 ++- .../qwen_forward/executor_original_prompt.rs | 4 + 6 files changed, 632 insertions(+), 5 deletions(-) create mode 100644 crates/cuda-driver/src/mmq_original_chunk_stream.rs diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index b21773c4..94cc37b1 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -208,6 +208,26 @@ impl<'ctx> MappedExpertBank<'ctx> { + 2 * size_of::() + self.banks.capacity() * size_of::() } + /// The gate/up/down host ranges (address, length) of `expert` of `layer`: the members hold 512 equal + /// per-expert extents in id order (the same extents `cache_source` returns for that expert's spans). + pub(crate) fn expert_pieces(&self, layer: u8, expert: u32) -> Result<[(usize, usize); 3]> { + if self.closed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if layer >= 48 || expert >= 512 { + return Err(Error::InvalidSize); + } + let mut pieces = [(0usize, 0usize); 3]; + for (role, piece) in pieces.iter_mut().enumerate() { + let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); + if !bytes.len().is_multiple_of(512) { + return Err(Error::InvalidSize); + } + let each = bytes.len() / 512; + *piece = (bytes.as_ptr() as usize + expert as usize * each, each); + } + Ok(pieces) + } /// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field). pub fn pageable(&self) -> bool { self.pageable diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream.rs new file mode 100644 index 00000000..14b6ca05 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_chunk_stream.rs @@ -0,0 +1,276 @@ +//! prefill.cpp's `stream_all` with its own issuer thread (1159-1286, D-5), for a page-locked (registered) expert +//! bank: every expert of every layer of the chunk that the arena cache does not hold is copied, layer by layer in +//! id order, into the copy ring (entry k lands in slot k % ring), whether or not the routing uses it. The copies +//! therefore run while the mixers and the router of the next layers compute, not only during that layer's MoE. +//! +//! The issuer thread only enqueues: it waits for entry k - ring to be consumed (its `used` event is on the compute +//! stream) before reusing that slot, and keeps at most `inflight` copies queued, so a context-wide synchronization +//! of the compute path waits for a few copies at most. The consumer (the per-layer copy ring) waits for entry k's +//! `copied` event on the compute stream before gathering it and records `used` after; entries a layer does not +//! route are released in order. Same bytes into the same kind of slot, gathered by the same kernels: the +//! layer's products do not change. +#![allow(unsafe_code)] +use crate::ffi::BufferHandle; +use crate::ffi::original_stager::Api; +use crate::{Error, Result, combine}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; + +#[derive(Clone, Copy)] +pub(super) struct Entry { + pub(super) layer: u8, + pub(super) expert: u32, + /// gate/up/down host ranges (page-locked bank), copied back to back into the slot + pub(super) pieces: [(usize, usize); 3], +} +struct Shared { + entries: Vec, + targets: Vec<(BufferHandle, usize)>, + copied: Vec, + used: Vec, + issued: AtomicUsize, + consumed: AtomicUsize, + stop: AtomicBool, + failed: AtomicBool, + error: Mutex>, + inflight: usize, + copy: usize, +} +impl Shared { + fn fail(&self, error: Error) { + self.failed.store(true, Ordering::Release); + self.stop.store(true, Ordering::Release); + if let Ok(mut first) = self.error.lock() { + first.get_or_insert(error); + } + } + fn ring(&self) -> usize { + self.targets.len() + } + fn issue(&self, api: &Api, k: usize) -> Result<()> { + let entry = self.entries[k]; + let slot = k % self.ring(); + if k >= self.ring() { + // the slot's previous entry was gathered (or released) on the compute stream + api.wait(self.copy, self.used[slot])?; + } + let (target, capacity) = self.targets[slot]; + let mut offset = 0usize; + for (address, length) in entry.pieces { + let end = offset.checked_add(length).ok_or(Error::InvalidSize)?; + if end > capacity { + return Err(Error::InvalidSize); + } + api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?; + offset = end; + } + api.record(self.copied[slot], self.copy) + } +} +fn issuer(api: Arc, shared: Arc, context: usize) { + if let Err(e) = api.worker_enter(context) { + shared.fail(e); + return; + } + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> { + for k in 0..shared.entries.len() { + let ring = shared.ring(); + // the slot is free once entry k - ring was consumed + while k >= shared.consumed.load(Ordering::Acquire).saturating_add(ring) { + if shared.stop.load(Ordering::Acquire) { + return Ok(()); + } + thread::yield_now(); + } + // at most `inflight` copies queued: wait for entry k - inflight's copy + if k >= shared.inflight { + let event = shared.copied[(k - shared.inflight) % ring]; + while !api.event_query(event)? { + if shared.stop.load(Ordering::Acquire) { + return Ok(()); + } + thread::yield_now(); + } + } + if shared.stop.load(Ordering::Acquire) { + return Ok(()); + } + shared.issue(&api, k)?; + shared.issued.store(k + 1, Ordering::Release); + } + Ok(()) + })); + match result { + Ok(Ok(())) => {} + Ok(Err(e)) => shared.fail(e), + Err(_) => shared.fail(Error::InvalidDriverValue("prefill expert issuer panic")), + } + if let Err(e) = api.worker_leave(context) { + shared.fail(e); + } +} + +/// One chunk's stream: the issuer thread and the consumer's cursor. +pub(super) struct ChunkStream { + api: Arc, + shared: Arc, + thread: Option>, + /// first entry of every layer (49 bounds) + layer_start: [usize; 49], + pub(super) next_layer: u8, + cursor: usize, +} +impl ChunkStream { + /// `entries` in stream order (layers ascending, experts ascending within a layer, from `first` to 48); + /// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context). + pub(super) fn start( + api: Arc, + context: usize, + copy: usize, + first: u8, + entries: Vec, + targets: Vec<(BufferHandle, usize)>, + copied: Vec, + used: Vec, + inflight: usize, + ) -> Result { + if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 { + return Err(Error::InvalidProjectionShape); + } + let mut layer_start = [0usize; 49]; + let mut k = 0usize; + for (layer, start) in layer_start.iter_mut().enumerate() { + while k < entries.len() && usize::from(entries[k].layer) < layer { + k += 1; + } + *start = k; + } + if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert)) + || entries.iter().any(|e| e.layer < first || e.layer >= 48 || e.expert >= 512) + { + return Err(Error::InvalidProjectionShape); + } + let shared = Arc::new(Shared { + entries, + targets, + copied, + used, + issued: AtomicUsize::new(0), + consumed: AtomicUsize::new(0), + stop: AtomicBool::new(false), + failed: AtomicBool::new(false), + error: Mutex::new(None), + inflight: inflight.max(1), + copy, + }); + let thread = { + let (api, shared) = (Arc::clone(&api), Arc::clone(&shared)); + thread::Builder::new() + .name("leleka-prefill-issuer".into()) + .stack_size(256 * 1024) + .spawn(move || issuer(api, shared, context)) + .map_err(|_| Error::HostAllocation)? + }; + Ok(Self { api, shared, thread: Some(thread), layer_start, next_layer: first, cursor: layer_start[usize::from(first)] }) + } + pub(super) fn next_layer_is(&self, layer: u8) -> bool { + self.next_layer == layer + } + /// Whether entry `k` copies exactly these gate/up/down byte ranges. + pub(super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool { + self.shared.entries.get(k).is_some_and(|e| { + e.pieces.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len()) + }) + } + pub(super) fn healthy(&self) -> Result<()> { + if self.shared.failed.load(Ordering::Acquire) { + return Err(self.shared.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned)); + } + Ok(()) + } + /// Entry index of `expert` in `layer`, if the stream carries it (not arena-resident). + pub(super) fn entry(&self, layer: u8, expert: u32) -> Option { + let (a, b) = (self.layer_start[usize::from(layer)], self.layer_start[usize::from(layer) + 1]); + self.shared.entries[a..b].binary_search_by_key(&expert, |e| e.expert).ok().map(|i| a + i) + } + /// Release (record `used`, consume) every entry before `upto` in order on `compute`. + pub(super) fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> { + while self.cursor < upto { + self.healthy()?; + // an unconsumed entry may not even be issued yet: its copy must be queued before the release + // is ordered after it, or a later re-use of the slot could overtake the copy + while self.shared.issued.load(Ordering::Acquire) <= self.cursor { + self.healthy()?; + thread::yield_now(); + } + let slot = self.cursor % self.shared.ring(); + self.api.wait(compute, self.shared.copied[slot])?; + self.api.record(self.shared.used[slot], compute)?; + self.cursor += 1; + self.shared.consumed.store(self.cursor, Ordering::Release); + } + Ok(()) + } + /// Make entry `k` (the cursor) ready on `compute`: its slot and the slot's byte capacity. + pub(super) fn acquire(&mut self, k: usize, compute: usize) -> Result<(BufferHandle, usize)> { + self.release_until(k, compute)?; + if self.cursor != k { + return Err(Error::InvalidProjectionShape); + } + while self.shared.issued.load(Ordering::Acquire) <= k { + self.healthy()?; + thread::yield_now(); + } + let slot = k % self.shared.ring(); + self.api.wait(compute, self.shared.copied[slot])?; + Ok(self.shared.targets[slot]) + } + /// The gather of entry `k` (the cursor) is enqueued on `compute`: mark its slot used. + pub(super) fn consumed(&mut self, k: usize, compute: usize) -> Result<()> { + if self.cursor != k { + return Err(Error::InvalidProjectionShape); + } + let slot = k % self.shared.ring(); + self.api.record(self.shared.used[slot], compute)?; + self.cursor += 1; + self.shared.consumed.store(self.cursor, Ordering::Release); + Ok(()) + } + /// The layer's last routed expert was gathered: release its remaining entries and move to the next layer. + pub(super) fn finish_layer(&mut self, layer: u8, compute: usize) -> Result<()> { + if layer != self.next_layer { + return Err(Error::InvalidProjectionShape); + } + let end = self.layer_start[usize::from(layer) + 1]; + self.release_until(end, compute)?; + self.next_layer += 1; + Ok(()) + } + pub(super) fn complete(&self) -> bool { + self.cursor == self.shared.entries.len() + } + /// Stop and join the issuer. The caller drains the copy stream afterwards before the slots or the bank go. + pub(super) fn stop(&mut self) -> Result<()> { + self.shared.stop.store(true, Ordering::Release); + let mut result = Ok(()); + if let Some(t) = self.thread.take() + && t.join().is_err() + { + result = Err(Error::InvalidDriverValue("prefill expert issuer join")); + } + if self.shared.failed.load(Ordering::Acquire) { + result = combine(result, Err(self.shared.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned))); + } + result + } + /// The raw per-slot events, for the owner to destroy after the drain. + pub(super) fn events(&self) -> (Vec, Vec) { + (self.shared.copied.clone(), self.shared.used.clone()) + } +} +impl Drop for ChunkStream { + fn drop(&mut self) { + let _ = self.stop(); + } +} diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 302f9529..06aa0775 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -16,6 +16,37 @@ fn skip_expert_dma() -> bool { *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA").is_some_and(|v| v == "1")) } use host_stage::{HostStage, Job}; +#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +#[path = "mmq_original_chunk_stream.rs"] +mod chunk_stream; +#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +use chunk_stream::{ChunkStream, Entry as StreamEntry}; +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +struct ChunkStream; +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +impl ChunkStream { + fn entry(&self, _: u8, _: u32) -> Option { + None + } + fn next_layer_is(&self, _: u8) -> bool { + false + } + fn entry_matches(&self, _: usize, _: [&[u8]; 3]) -> bool { + false + } + fn acquire(&mut self, _: usize, _: usize) -> Result<(ffi::BufferHandle, usize)> { + Err(Error::UnsupportedPlatform) + } + fn consumed(&mut self, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + fn finish_layer(&mut self, _: u8, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + fn stop(&mut self) -> Result<()> { + Ok(()) + } +} const COMMAND_CAP: usize = 2048; trait RingArena: GroupArena { fn stage_slots(&self) -> Result; @@ -64,6 +95,11 @@ pub struct OriginalMmqCopySchedule<'ctx> { /// first use, with one completion event per page-locked buffer. host: Option, host_events: Vec>, + /// prefill.cpp's `stream_all` issuer for the current prompt chunk (`begin_prompt_stream`), its bank and + /// raw per-slot events. + stream: Option, + stream_bank: Option>>, + stream_events: Vec, } impl Context<'_> { pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result> { @@ -84,6 +120,9 @@ impl Context<'_> { host_metadata_outside: 0, host: None, host_events: Vec::new(), + stream: None, + stream_bank: None, + stream_events: Vec::new(), }; let result = (|| { owner @@ -123,7 +162,7 @@ impl Context<'_> { Ok(owner) } } -impl OriginalMmqCopySchedule<'_> { +impl<'ctx> OriginalMmqCopySchedule<'ctx> { /// Byte accounting only: the real caller computes retained bank, source /// vector and current router-layer capacities before this exclusive loan. pub fn retain_host_metadata_charge(&mut self, bytes: usize) -> Result<()> { @@ -143,6 +182,151 @@ impl OriginalMmqCopySchedule<'_> { pub fn ring_slots(&self) -> usize { self.events.len() } + /// Whether a prompt-chunk expert stream is active. + pub fn prompt_stream_active(&self) -> bool { + self.stream.is_some() + } + /// prefill.cpp `stream_all` for the rest of this prompt chunk, from `first` (a layer about to run its + /// MoE) to the last layer: an issuer thread copies every expert the arena cache does not hold, layer by + /// layer in id order, from the page-locked `bank` into this arena's copy ring, at most `inflight` copies + /// queued at a time. Only for a registered bank (a pageable one is staged by the ring's `HostStage`). + /// The caller ends the stream (`end_prompt_stream`) before the row lease or the bank go, on every path. + pub fn begin_prompt_stream( + &mut self, + read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + bank: &Rc>, + first: u8, + inflight: usize, + ) -> Result<()> { + self.begin_stream_inner(read, bank, first, inflight) + } + #[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] + fn begin_stream_inner( + &mut self, + _: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + _: &Rc>, + _: u8, + _: usize, + ) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + #[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] + fn begin_stream_inner( + &mut self, + read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + bank: &Rc>, + first: u8, + inflight: usize, + ) -> Result<()> { + use crate::ffi::original_stager::Api as StagerApi; + self.validate_context(self.context)?; + if self.stream.is_some() || bank.pageable() || !bank.cache_context_matches(self.context) || first >= 48 + || !read.context_matches(self.context) + { + return Err(Error::InvalidProjectionShape); + } + let lease = read.lease(); + let ring = lease.copy_ring_slots()?; + let mut targets = Vec::new(); + targets.try_reserve_exact(ring).map_err(|_| Error::HostAllocation)?; + for index in 0..ring { + targets.push(lease.copy_ring_span(index)?); + } + let mut entries = Vec::new(); + entries + .try_reserve_exact((48 - usize::from(first)) * 512) + .map_err(|_| Error::HostAllocation)?; + for layer in first..48 { + for expert in 0..512u32 { + if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() { + continue; + } + let pieces = bank.expert_pieces(layer, expert)?; + let bytes: usize = pieces.iter().map(|p| p.1).sum(); + if targets.iter().any(|t| t.1 < bytes) { + return Err(Error::InvalidSize); + } + entries.push(StreamEntry { layer, expert, pieces }); + } + } + let api = std::sync::Arc::new(StagerApi::load()?); + let token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?); + let guard = self.context.enter()?; + let mut events = Vec::new(); + let created = (|| -> Result<()> { + events.try_reserve_exact(2 * ring).map_err(|_| Error::HostAllocation)?; + for _ in 0..2 * ring { + events.push(api.event_create()?); + } + Ok(()) + })(); + let pop = guard.finish(); + if let Err(primary) = combine(created, pop) { + let guard = self.context.enter()?; + for e in &events { + let _ = api.event_destroy(*e); + } + let _ = guard.finish(); + return Err(primary); + } + let (copied, used) = (events[..ring].to_vec(), events[ring..].to_vec()); + let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?; + // the copies must follow everything the compute path queued so far on its own streams + self.context.synchronize()?; + match ChunkStream::start(api, token, copy, first, entries, targets, copied, used, inflight) { + Ok(stream) => { + self.stream = Some(stream); + self.stream_bank = Some(Rc::clone(bank)); + self.stream_events = events; + Ok(()) + } + Err(primary) => { + let guard = self.context.enter()?; + let loaded = StagerApi::load(); + if let Ok(api) = loaded { + for e in &events { + let _ = api.event_destroy(*e); + } + } + let _ = guard.finish(); + Err(primary) + } + } + } + /// End the chunk's expert stream: stop and join the issuer, drain the copy and compute streams, release the + /// raw events. Idempotent; a failure poisons the schedule. + pub fn end_prompt_stream(&mut self) -> Result<()> { + let Some(mut stream) = self.stream.take() else { return Ok(()) }; + let stopped = stream.stop(); + let copy = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize); + let compute = self.compute.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize); + drop(stream); + let drained = combine(copy, compute); + let mut result = combine(stopped, drained); + let events = std::mem::take(&mut self.stream_events); + if result.is_ok() { + result = self.destroy_stream_events(&events); + } else { + self.failed = true; + std::mem::forget(events); + } + self.stream_bank.take(); + result + } + #[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] + fn destroy_stream_events(&self, _: &[usize]) -> Result<()> { + Ok(()) + } + #[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] + fn destroy_stream_events(&self, events: &[usize]) -> Result<()> { + let api = crate::ffi::original_stager::Api::load()?; + let guard = self.context.enter()?; + let mut result = Ok(()); + for e in events { + result = combine(result, api.event_destroy(*e)); + } + combine(result, guard.finish()) + } /// Bounded Rust metadata includes conservative actual private event/API/Rc /// storage. CUDA's opaque residency remains actual physical room, not zero. pub fn metadata_bytes(&self) -> Result { @@ -178,6 +362,7 @@ impl OriginalMmqCopySchedule<'_> { if self.closed { return Ok(()); } + let ended = self.end_prompt_stream(); self.closed = true; let copy = self .copy @@ -187,7 +372,7 @@ impl OriginalMmqCopySchedule<'_> { .compute .as_ref() .map_or(Ok(()), OriginalGpuStream::synchronize); - let mut result = combine(copy, compute); + let mut result = combine(ended, combine(copy, compute)); if let Some(mut host) = self.host.take() { if result.is_ok() { result = combine(result, host.close()); @@ -233,6 +418,8 @@ struct Source<'read> { slot: Option, /// the host staging job of an expert copied through `HostStage` job: Option, + /// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`) + entry: Option, } /// Private owner: no external pointer/ready event can manufacture a stage. /// The actual source Rc prevents unregister/free during H2D or gathered use. @@ -249,6 +436,9 @@ pub(super) struct Ring<'read, 'ctx> { stage_next: usize, /// host staging started for this layer; DMAs of staged jobs known complete (in order) staging: bool, + /// this layer's experts come from the chunk stream + streamed: bool, + layer: u8, stage_done: usize, submitted: bool, drained: bool, @@ -301,6 +491,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { flags: Vec::new(), stage_next: 0, staging: false, + streamed: false, + layer: layer as u8, stage_done: 0, submitted: false, drained: false, @@ -392,13 +584,39 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { resident, slot: None, job: None, + entry: None, }); } + // With an active chunk stream for this layer, every non-resident expert is the stream's entry. + if let Some(stream) = owner.schedule.stream.as_ref() { + if stream.next_layer_is(layer as u8) { + for source in &mut owner.sources { + if source.resident.is_some() { + continue; + } + let entry = stream + .entry(layer as u8, source.spans[0].expert()) + .ok_or(Error::InvalidProjectionShape)?; + // the stream copies exactly the bytes this span names + if !stream.entry_matches(entry, [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ]) { + return Err(Error::InvalidProjectionShape); + } + source.entry = Some(entry); + } + owner.streamed = true; + } else { + return Err(Error::InvalidProjectionShape); + } + } // Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked // buffers, in launch order, ahead of their DMAs. let mut jobs = Vec::new(); for source in &mut owner.sources { - if source.resident.is_none() && bank.host_staged(source.spans) { + if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) { let mut pieces = [(0usize, 0usize, 0u32); 3]; for (role, span) in source.spans.iter().enumerate() { let bytes = bank.cache_source(span)?; @@ -506,7 +724,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { .sources .get(index) .ok_or(Error::InvalidProjectionShape)?; - if source.resident.is_some() { + if source.resident.is_some() || source.entry.is_some() { return Ok(()); } if source.slot.is_some() { @@ -611,8 +829,23 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; let sl = source.slot; + let entry = source.entry; let raw = if let Some(raw) = source.resident { raw + } else if let Some(k) = entry { + // the chunk stream's copy of entry k (the compute stream waits for it) + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let (span, bytes) = schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.acquire(k, s))?; + [ + span.checked_subspan(bytes, 0, gu)?, + span.checked_subspan(bytes, gu, gu)?, + span.checked_subspan(bytes, gu * 2, down)?, + ] } else { let sl = sl.ok_or(Error::InvalidProjectionShape)?; let slot = &mut self.slots[sl]; @@ -654,6 +887,15 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { ((gu * 2 + down) / 16) as u32, ffi::MmqOriginalGatherArguments::new(raw, gate_up, down_out, gu, down), ))?; + if let Some(k) = entry { + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.consumed(k, s))?; + } if let Some(sl) = sl { let slot = &mut self.slots[sl]; let events = &mut self.schedule.events[sl]; @@ -670,6 +912,18 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { /// Every status is copied only after BOTH real streams drain. Numeric /// refusal remains stage/group ordered; later transport failure is primary. pub(super) fn finish_statuses(&mut self) -> Result<&[u8]> { + if self.streamed { + // release the layer's unrouted stream entries (in order) and hand the stream to the next layer + let layer = self.layer; + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.finish_layer(layer, s))?; + self.streamed = false; + } self.drain()?; let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; let guard = self.context.enter()?; @@ -716,6 +970,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { return Ok(()); } self.closed = true; + if self.streamed { + // a layer that did not finish leaves the stream unusable: stop its issuer now (the owner ends it) + if let Some(stream) = self.schedule.stream.as_mut() { + let _ = stream.stop(); + } + self.streamed = false; + } // no stager helper reads the bank after this if self.staging { if let Some(host) = self.schedule.host.as_mut() { diff --git a/crates/cuda-driver/src/original_expert_stager_ffi.rs b/crates/cuda-driver/src/original_expert_stager_ffi.rs index f118dbb0..2912d45f 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi.rs @@ -31,6 +31,7 @@ pub(crate) struct Api { event_create: EventCreate, event_destroy: HandleCall, event_sync: HandleCall, + event_query: HandleCall, event_record: EventRecord, stream_wait: StreamWait, copy: Copy, @@ -111,6 +112,7 @@ impl Api { event_create: sym!(c"cuEventCreate", EventCreate), event_destroy: sym!(c"cuEventDestroy_v2", HandleCall), event_sync: sym!(c"cuEventSynchronize", HandleCall), + event_query: sym!(c"cuEventQuery", HandleCall), event_record: sym!(c"cuEventRecord", EventRecord), stream_wait: sym!(c"cuStreamWaitEvent", StreamWait), copy: sym!(c"cuMemcpyHtoDAsync_v2", Copy), @@ -183,6 +185,31 @@ impl Api { (self.event_sync)(event as Handle) }) } + /// `cuEventQuery`: `Ok(true)` once complete, `Ok(false)` while pending (CUDA_ERROR_NOT_READY = 600). + pub(crate) fn event_query(&self, event: usize) -> Result { + match unsafe { (self.event_query)(event as Handle) } { + 0 => Ok(true), + 600 => Ok(false), + code => Err(Error::Driver { operation: "cuEventQuery", code }), + } + } + /// One H2D copy of `bytes` from a host address the caller retains (a page-locked bank range) into + /// `destination` on `stream`. + pub(crate) fn copy_raw( + &self, + destination: BufferHandle, + source: usize, + bytes: usize, + stream: usize, + ) -> Result<()> { + destination.validate_extent(bytes)?; + if bytes == 0 || source == 0 { + return Err(Error::InvalidSize); + } + check("cuMemcpyHtoDAsync_v2", unsafe { + (self.copy)(destination.0, source as *const c_void, bytes, stream as Handle) + }) + } pub(crate) fn context_token(handle: ContextHandle) -> usize { handle.0 } diff --git a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs index 05b1adf9..1a8fd222 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs @@ -9,6 +9,20 @@ use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace, use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage}; +/// prefill.cpp `stream_all` (`begin_prompt_stream`): on for chunks of at least `STRATA_PREFILL_STREAM_MIN` +/// rows (1024) over a registered bank; `LELEKA_PREFILL_STREAM=0` keeps the per-layer copy ring. +/// `LELEKA_PREFILL_STREAM_INFLIGHT` bounds the queued copies (default 4). +fn prompt_stream_settings() -> Option<(usize, usize)> { + static SETTINGS: std::sync::OnceLock> = std::sync::OnceLock::new(); + *SETTINGS.get_or_init(|| { + if std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "0") { + return None; + } + let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default); + Some((number("STRATA_PREFILL_STREAM_MIN", 1024), number("LELEKA_PREFILL_STREAM_INFLIGHT", 4).clamp(1, 64))) + }) +} + fn native_format(key: MoeWeightDescriptor) -> Result { match key.raw_kind { 8 => Ok(GdnNativeFormat::Q8_0), 12 => Ok(GdnNativeFormat::Q4K), @@ -66,6 +80,14 @@ impl<'ctx> MoeWeightCache<'ctx> { Ok(cache) } + /// End the prompt chunk's expert stream, if any (idempotent; every forward exit calls it). + pub(in crate::qwen_forward) fn end_prompt_stream(&mut self) -> Result<()> { + match self.original_copy_schedule.as_mut() { + Some(schedule) => schedule.end_prompt_stream().map_err(driver_error), + None => Ok(()), + } + } + /// The registered retained model bank the prompt path streams from: also the source of the VRAM expert /// tier's fills, lent-slot refills, adaptive swaps and PCIe copies. pub(crate) fn original_expert_bank(&self) -> Option>> { @@ -161,7 +183,16 @@ impl<'ctx> MoeWeightCache<'ctx> { schedule.validate_context(self.context).map_err(driver_error)?; let context = self.context; let drain = Some(context as &dyn prof::Drain); + let last_layer = layer.get() + 1 == binding.layer_count(); let result = (|| { + if layer.get() == 0 && !schedule.prompt_stream_active() + && let Some((minimum, inflight)) = prompt_stream_settings() + && read.rows() >= minimum && !bank.pageable() + { + // the whole chunk's expert stream starts with the first MoE layer + schedule.begin_prompt_stream(&read, &bank, 0, inflight).map_err(driver_error)?; + crate::bringup_trace!("DBG prefill stream: begin rows={} inflight={inflight}", read.rows()); + } // High-only is the selected literal Original mixed BF16 policy. let prepare_span = prof::span(PStage::MoePrepare, drain); let mut layer_program = program.prepare(read, shared, weights, formats, false) @@ -228,8 +259,16 @@ impl<'ctx> MoeWeightCache<'ctx> { routed_formats.ok_or(Error::IdentityMismatch)?, &sources).map_err(driver_error)?; drop(ring_span); let _span = prof::span(PStage::MoeFinish, drain); - layer_program.finish(shared).map_err(driver_error) + let block = layer_program.finish(shared).map_err(driver_error)?; + if last_layer && schedule.prompt_stream_active() { + schedule.end_prompt_stream().map_err(driver_error)?; + } + Ok(block) })(); + if result.is_err() { + // the stream never outlives a failed layer + let _ = schedule.end_prompt_stream(); + } if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } result } diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs index 02527f3f..d63b5df7 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs @@ -348,6 +348,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok",crate::qwen_forward::original_serve_stack::dbg_el()); } let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; + // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers + moe.end_prompt_stream()?; let final_span=prof::span(PStage::Final,drain); crate::bringup_trace!("DBG[{:.0}s] forward: all layers ok, final row",crate::qwen_forward::original_serve_stack::dbg_el()); let final_row=rows.preview_conditioning(binding,dense,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] preview_conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; @@ -393,6 +395,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ match operation{ Err(primary)=>{ crate::bringup_trace!("DBG[{:.0}s] forward operation failed: {primary:?}",crate::qwen_forward::original_serve_stack::dbg_el()); + // stop the chunk's expert stream before the transaction rolls back + if moe.end_prompt_stream().is_err(){self.failed=true;} let cleanup=txn.abort_with_draft(binding,dense,&mut self.layers,&checkpoint,draft,&draft_checkpoint); if cleanup.is_err()||self.context.is_poisoned(){self.failed=true;} Err(primary) From 468f34e1f5a6240c72b84b04a1fdc2be4a5fb502 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 19:19:11 +0200 Subject: [PATCH 6/7] test(serve): long-context smoke writes its prompt ids for the Original (LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR) Co-Authored-By: Claude Opus 5.5 --- crates/leleka-runtime/src/backend_original_serve_smoke.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index 2d832c5c..23a76cbb 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -362,6 +362,14 @@ fn original_serve_long_context_streamed_kv_smoke() { for prompt in &prompts { let prompt = prompt.as_slice(); eprintln!("long-smoke prompt tokens={} kv-resident={resident} max-context={max_context}", prompt.len()); + // LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt.ids` (comma-separated) for the Original's + // `--tokens-file`, so both engines read the identical token sequence + if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") { + let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len())); + let text = prompt.iter().map(|t| t.to_string()).collect::>().join(","); + std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + eprintln!("long-smoke prompt ids -> {}", path.display()); + } for pass in 0..repeat { let started = std::time::Instant::now(); let mut tokens = Vec::new(); From e9b8a5e8b6a16d0968dbf3756cce95760cb432fa Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 19:24:11 +0200 Subject: [PATCH 7/7] perf(prefill): enqueue the stream's copies on the calling thread, under the GDN kernel batches The issuer thread of 80627bc made the prompt path slower (job 707: 1,083 vs 1,413 tok/s at chunk 2048, 2,419 vs 2,624 at 8192): every stage of the compute path drains with cuCtxSynchronize, which also waits for the copy stream, so each drain waited while the free-running issuer filled the ring. The stream (same stream_all order, slots and events) is now driven by the calling thread only: a layer's MoE queues its own entries up to the ring (as the per-layer ring did), and the GDN prompt producer calls prefetch_point right after its last drain before its sync-free kernel batch, which queues as many of the upcoming MoE layer's entries as 90% of its previous batch window covers at LELEKA_PREFILL_PCIE_GBPS (45), so those copies run under the GDN kernels and are complete by the batch's closing drain. Same bytes, slots, gathers and products. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/gdn_prompt_device.rs | 5 + crates/cuda-driver/src/lib.rs | 1 + .../src/mmq_original_chunk_stream.rs | 332 +++++++++--------- crates/cuda-driver/src/mmq_original_group.rs | 1 + crates/cuda-driver/src/mmq_original_ring.rs | 19 +- .../src/qwen_forward/cache_original_prompt.rs | 18 +- 6 files changed, 194 insertions(+), 182 deletions(-) diff --git a/crates/cuda-driver/src/gdn_prompt_device.rs b/crates/cuda-driver/src/gdn_prompt_device.rs index edef0dd8..22c7667c 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -514,6 +514,10 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { .api .copy_from(hin, &history_bytes) .and_then(|()| context.driver.api.synchronize()); + // the batch below runs without a drain until its end: next-MoE expert copies can run under it + if operation.is_ok() { + crate::prefetch_point(); + } if timed { crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); } @@ -563,6 +567,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { .and_then(|()| context.driver.api.copy_to(hout, &mut final_history)) } let all = context.driver.api.synchronize(); + crate::prefetch_window_end(); if timed { crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); } diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 53f0d960..d01e413d 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -64,6 +64,7 @@ mod mmq_native; pub use mmq::resident::original_group::{ OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes, }; +pub(crate) use mmq::resident::original_group::{prefetch_point, prefetch_window_end}; pub use mmq::resident::{ FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace, }; diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream.rs index 14b6ca05..f5609335 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream.rs @@ -1,21 +1,25 @@ -//! prefill.cpp's `stream_all` with its own issuer thread (1159-1286, D-5), for a page-locked (registered) expert -//! bank: every expert of every layer of the chunk that the arena cache does not hold is copied, layer by layer in -//! id order, into the copy ring (entry k lands in slot k % ring), whether or not the routing uses it. The copies -//! therefore run while the mixers and the router of the next layers compute, not only during that layer's MoE. +//! prefill.cpp's `stream_all` (1159-1286) order for a page-locked (registered) expert bank: every expert of every +//! layer of the chunk that the arena cache does not hold is copied, layer by layer in id order, into the copy ring +//! (entry k lands in slot k % ring), whether or not the routing uses it. //! -//! The issuer thread only enqueues: it waits for entry k - ring to be consumed (its `used` event is on the compute -//! stream) before reusing that slot, and keeps at most `inflight` copies queued, so a context-wide synchronization -//! of the compute path waits for a few copies at most. The consumer (the per-layer copy ring) waits for entry k's -//! `copied` event on the compute stream before gathering it and records `used` after; entries a layer does not -//! route are released in order. Same bytes into the same kind of slot, gathered by the same kernels: the -//! layer's products do not change. -#![allow(unsafe_code)] +//! The port's compute path drains with context-wide synchronizations (cuCtxSynchronize) after every stage, and +//! such a drain also waits for every copy queued on the copy stream: copies queued ahead of a mixer would be waited +//! for at its first drain. (A free-running issuer thread, the Original's D-5, made every mixer drain wait for the +//! issuer to fill the ring: measured slower, job 707.) So the copies are enqueued on the calling thread, at two +//! kinds of points: +//! * the layer's MoE: entries up to the ring's capacity, within the current layer only (as the per-layer ring); +//! * `prefetch_point` (called by a long mixer producer right after its last drain before a sync-free batch of +//! kernels, the GDN prompt producer): as many entries of the next MoE layer as its measured batch time covers, +//! so those copies run under the mixer's kernels and are complete by its closing drain. +//! The consumer (the per-layer copy ring) waits for entry k's `copied` event on the compute stream before +//! gathering it and records `used` after; entries a layer does not route are released in order. Same bytes into +//! the same kind of slot, gathered by the same kernels: the layer's products do not change. use crate::ffi::BufferHandle; use crate::ffi::original_stager::Api; -use crate::{Error, Result, combine}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread::{self, JoinHandle}; +use crate::{Error, Result}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::{Duration, Instant}; #[derive(Clone, Copy)] pub(super) struct Entry { @@ -24,36 +28,54 @@ pub(super) struct Entry { /// gate/up/down host ranges (page-locked bank), copied back to back into the slot pub(super) pieces: [(usize, usize); 3], } -struct Shared { +struct Core { + api: Api, entries: Vec, targets: Vec<(BufferHandle, usize)>, copied: Vec, used: Vec, - issued: AtomicUsize, - consumed: AtomicUsize, - stop: AtomicBool, - failed: AtomicBool, - error: Mutex>, - inflight: usize, + /// first entry of every layer (49 bounds) + layer_start: [usize; 49], copy: usize, + issued: Cell, + consumed: Cell, + next_layer: Cell, + failed: Cell, + /// measured length of the last prefetch window (point to closing drain) and the bytes/s estimate + window: Cell, + window_start: Cell>, + bytes_per_second: f64, } -impl Shared { - fn fail(&self, error: Error) { - self.failed.store(true, Ordering::Release); - self.stop.store(true, Ordering::Release); - if let Ok(mut first) = self.error.lock() { - first.get_or_insert(error); - } - } +impl Core { fn ring(&self) -> usize { self.targets.len() } - fn issue(&self, api: &Api, k: usize) -> Result<()> { + fn layer_end(&self, layer: u8) -> usize { + self.layer_start[usize::from(layer) + 1] + } + /// Enqueue entries until `limit` (never past the ring: entry k - ring must be consumed first). + fn issue_until(&self, limit: usize) -> Result<()> { + if self.failed.get() { + return Err(Error::ContextPoisoned); + } + let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring()); + while self.issued.get() < limit { + let k = self.issued.get(); + let result = self.issue(k); + if result.is_err() { + self.failed.set(true); + return result; + } + self.issued.set(k + 1); + } + Ok(()) + } + fn issue(&self, k: usize) -> Result<()> { let entry = self.entries[k]; let slot = k % self.ring(); if k >= self.ring() { // the slot's previous entry was gathered (or released) on the compute stream - api.wait(self.copy, self.used[slot])?; + self.api.wait(self.copy, self.used[slot])?; } let (target, capacity) = self.targets[slot]; let mut offset = 0usize; @@ -62,82 +84,83 @@ impl Shared { if end > capacity { return Err(Error::InvalidSize); } - api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?; + self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?; offset = end; } - api.record(self.copied[slot], self.copy) - } -} -fn issuer(api: Arc, shared: Arc, context: usize) { - if let Err(e) = api.worker_enter(context) { - shared.fail(e); - return; - } - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> { - for k in 0..shared.entries.len() { - let ring = shared.ring(); - // the slot is free once entry k - ring was consumed - while k >= shared.consumed.load(Ordering::Acquire).saturating_add(ring) { - if shared.stop.load(Ordering::Acquire) { - return Ok(()); - } - thread::yield_now(); - } - // at most `inflight` copies queued: wait for entry k - inflight's copy - if k >= shared.inflight { - let event = shared.copied[(k - shared.inflight) % ring]; - while !api.event_query(event)? { - if shared.stop.load(Ordering::Acquire) { - return Ok(()); - } - thread::yield_now(); - } - } - if shared.stop.load(Ordering::Acquire) { - return Ok(()); - } - shared.issue(&api, k)?; - shared.issued.store(k + 1, Ordering::Release); - } - Ok(()) - })); - match result { - Ok(Ok(())) => {} - Ok(Err(e)) => shared.fail(e), - Err(_) => shared.fail(Error::InvalidDriverValue("prefill expert issuer panic")), - } - if let Err(e) = api.worker_leave(context) { - shared.fail(e); + self.api.record(self.copied[slot], self.copy) } } -/// One chunk's stream: the issuer thread and the consumer's cursor. +thread_local! { + /// The active chunk stream of this thread, for `prefetch_point` (the producers have no schedule handle). + static ACTIVE: RefCell>> = const { RefCell::new(None) }; +} + +/// Called by a long mixer producer right after its last drain and before its sync-free kernel batch: enqueue as +/// many next-MoE entries as the previous window covered. The caller must call `prefetch_window_end` after its +/// closing drain. No-op without an active stream. The caller's Context must be current. +pub(crate) fn prefetch_point() { + ACTIVE.with(|active| { + let Some(core) = active.borrow().clone() else { return }; + core.window_start.set(Some(Instant::now())); + let window = core.window.get(); + if window.is_zero() { + return; + } + let layer = core.next_layer.get(); + if layer >= 48 { + return; + } + let blob: usize = core + .entries + .get(core.issued.get()) + .map_or(0, |e| e.pieces.iter().map(|p| p.1).sum()); + if blob == 0 { + return; + } + // 90% of the window: the copies must be done by the window's closing drain + let budget = (window.as_secs_f64() * 0.9 * core.bytes_per_second / blob as f64) as usize; + let limit = (core.issued.get() + budget).min(core.layer_end(layer)); + let _ = core.issue_until(limit); + }); +} +/// The producer's closing drain returned: record the window length for the next `prefetch_point`. +pub(crate) fn prefetch_window_end() { + ACTIVE.with(|active| { + if let Some(core) = active.borrow().as_ref() + && let Some(start) = core.window_start.take() + { + core.window.set(start.elapsed()); + } + }); +} + +/// One chunk's stream and the consumer's cursor (the caller's thread only). pub(super) struct ChunkStream { - api: Arc, - shared: Arc, - thread: Option>, - /// first entry of every layer (49 bounds) - layer_start: [usize; 49], - pub(super) next_layer: u8, - cursor: usize, + core: Rc, } impl ChunkStream { /// `entries` in stream order (layers ascending, experts ascending within a layer, from `first` to 48); /// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context). + #[allow(clippy::too_many_arguments)] pub(super) fn start( - api: Arc, - context: usize, + api: Api, copy: usize, first: u8, entries: Vec, targets: Vec<(BufferHandle, usize)>, copied: Vec, used: Vec, - inflight: usize, + bytes_per_second: f64, ) -> Result { if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 { return Err(Error::InvalidProjectionShape); } + if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert)) + || entries.iter().any(|e| e.layer < first || e.layer >= 48 || e.expert >= 512) + { + return Err(Error::InvalidProjectionShape); + } let mut layer_start = [0usize; 49]; let mut k = 0usize; for (layer, start) in layer_start.iter_mut().enumerate() { @@ -146,127 +169,102 @@ impl ChunkStream { } *start = k; } - if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert)) - || entries.iter().any(|e| e.layer < first || e.layer >= 48 || e.expert >= 512) - { - return Err(Error::InvalidProjectionShape); - } - let shared = Arc::new(Shared { + let core = Rc::new(Core { + api, entries, targets, copied, used, - issued: AtomicUsize::new(0), - consumed: AtomicUsize::new(0), - stop: AtomicBool::new(false), - failed: AtomicBool::new(false), - error: Mutex::new(None), - inflight: inflight.max(1), + layer_start, copy, + issued: Cell::new(layer_start[usize::from(first)]), + consumed: Cell::new(layer_start[usize::from(first)]), + next_layer: Cell::new(first), + failed: Cell::new(false), + window: Cell::new(Duration::ZERO), + window_start: Cell::new(None), + bytes_per_second: bytes_per_second.max(1e9), }); - let thread = { - let (api, shared) = (Arc::clone(&api), Arc::clone(&shared)); - thread::Builder::new() - .name("leleka-prefill-issuer".into()) - .stack_size(256 * 1024) - .spawn(move || issuer(api, shared, context)) - .map_err(|_| Error::HostAllocation)? - }; - Ok(Self { api, shared, thread: Some(thread), layer_start, next_layer: first, cursor: layer_start[usize::from(first)] }) + ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core))); + Ok(Self { core }) } pub(super) fn next_layer_is(&self, layer: u8) -> bool { - self.next_layer == layer + self.core.next_layer.get() == layer } /// Whether entry `k` copies exactly these gate/up/down byte ranges. pub(super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool { - self.shared.entries.get(k).is_some_and(|e| { + self.core.entries.get(k).is_some_and(|e| { e.pieces.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len()) }) } - pub(super) fn healthy(&self) -> Result<()> { - if self.shared.failed.load(Ordering::Acquire) { - return Err(self.shared.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned)); - } - Ok(()) - } /// Entry index of `expert` in `layer`, if the stream carries it (not arena-resident). pub(super) fn entry(&self, layer: u8, expert: u32) -> Option { - let (a, b) = (self.layer_start[usize::from(layer)], self.layer_start[usize::from(layer) + 1]); - self.shared.entries[a..b].binary_search_by_key(&expert, |e| e.expert).ok().map(|i| a + i) + let (a, b) = (self.core.layer_start[usize::from(layer)], self.core.layer_start[usize::from(layer) + 1]); + self.core.entries[a..b].binary_search_by_key(&expert, |e| e.expert).ok().map(|i| a + i) } /// Release (record `used`, consume) every entry before `upto` in order on `compute`. - pub(super) fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> { - while self.cursor < upto { - self.healthy()?; - // an unconsumed entry may not even be issued yet: its copy must be queued before the release - // is ordered after it, or a later re-use of the slot could overtake the copy - while self.shared.issued.load(Ordering::Acquire) <= self.cursor { - self.healthy()?; - thread::yield_now(); - } - let slot = self.cursor % self.shared.ring(); - self.api.wait(compute, self.shared.copied[slot])?; - self.api.record(self.shared.used[slot], compute)?; - self.cursor += 1; - self.shared.consumed.store(self.cursor, Ordering::Release); + fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> { + let core = &self.core; + while core.consumed.get() < upto { + let k = core.consumed.get(); + // its copy is queued before its release is ordered after it + core.issue_until(k + 1)?; + let slot = k % core.ring(); + core.api.wait(compute, core.copied[slot])?; + core.api.record(core.used[slot], compute)?; + core.consumed.set(k + 1); } Ok(()) } - /// Make entry `k` (the cursor) ready on `compute`: its slot and the slot's byte capacity. + /// The ring's look-ahead for the cursor's layer: queue entries up to the ring's capacity, within the layer. + pub(super) fn stage_ahead(&mut self, k: usize) -> Result<()> { + let layer = self.core.entries.get(k).ok_or(Error::InvalidProjectionShape)?.layer; + let end = self.core.layer_end(layer); + self.core.issue_until(end) + } + /// Make entry `k` ready on `compute`: its slot and the slot's byte capacity. pub(super) fn acquire(&mut self, k: usize, compute: usize) -> Result<(BufferHandle, usize)> { self.release_until(k, compute)?; - if self.cursor != k { + if self.core.consumed.get() != k { return Err(Error::InvalidProjectionShape); } - while self.shared.issued.load(Ordering::Acquire) <= k { - self.healthy()?; - thread::yield_now(); - } - let slot = k % self.shared.ring(); - self.api.wait(compute, self.shared.copied[slot])?; - Ok(self.shared.targets[slot]) + self.stage_ahead(k)?; + let slot = k % self.core.ring(); + self.core.api.wait(compute, self.core.copied[slot])?; + Ok(self.core.targets[slot]) } /// The gather of entry `k` (the cursor) is enqueued on `compute`: mark its slot used. pub(super) fn consumed(&mut self, k: usize, compute: usize) -> Result<()> { - if self.cursor != k { + if self.core.consumed.get() != k || self.core.issued.get() <= k { return Err(Error::InvalidProjectionShape); } - let slot = k % self.shared.ring(); - self.api.record(self.shared.used[slot], compute)?; - self.cursor += 1; - self.shared.consumed.store(self.cursor, Ordering::Release); + let slot = k % self.core.ring(); + self.core.api.record(self.core.used[slot], compute)?; + self.core.consumed.set(k + 1); Ok(()) } /// The layer's last routed expert was gathered: release its remaining entries and move to the next layer. pub(super) fn finish_layer(&mut self, layer: u8, compute: usize) -> Result<()> { - if layer != self.next_layer { + if !self.next_layer_is(layer) { return Err(Error::InvalidProjectionShape); } - let end = self.layer_start[usize::from(layer) + 1]; + let end = self.core.layer_end(layer); self.release_until(end, compute)?; - self.next_layer += 1; + self.core.next_layer.set(layer + 1); Ok(()) } - pub(super) fn complete(&self) -> bool { - self.cursor == self.shared.entries.len() - } - /// Stop and join the issuer. The caller drains the copy stream afterwards before the slots or the bank go. + /// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream. pub(super) fn stop(&mut self) -> Result<()> { - self.shared.stop.store(true, Ordering::Release); - let mut result = Ok(()); - if let Some(t) = self.thread.take() - && t.join().is_err() - { - result = Err(Error::InvalidDriverValue("prefill expert issuer join")); - } - if self.shared.failed.load(Ordering::Acquire) { - result = combine(result, Err(self.shared.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned))); - } - result + ACTIVE.with(|active| { + let mut active = active.borrow_mut(); + if active.as_ref().is_some_and(|a| Rc::ptr_eq(a, &self.core)) { + *active = None; + } + }); + if self.core.failed.get() { Err(Error::ContextPoisoned) } else { Ok(()) } } - /// The raw per-slot events, for the owner to destroy after the drain. - pub(super) fn events(&self) -> (Vec, Vec) { - (self.shared.copied.clone(), self.shared.used.clone()) + pub(super) fn api(&self) -> &Api { + &self.core.api } } impl Drop for ChunkStream { diff --git a/crates/cuda-driver/src/mmq_original_group.rs b/crates/cuda-driver/src/mmq_original_group.rs index 41e376f1..0a18702b 100644 --- a/crates/cuda-driver/src/mmq_original_group.rs +++ b/crates/cuda-driver/src/mmq_original_group.rs @@ -1435,6 +1435,7 @@ impl OriginalMmqOutput<'_, '_, '_> { #[path = "mmq_original_ring.rs"] mod copy_ring; pub use copy_ring::OriginalMmqCopySchedule; +pub(crate) use copy_ring::{prefetch_point, prefetch_window_end}; impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { /// Execute the actual ascending expert layer through Original's copy ring. /// The actual read/arena and registered bank remain retained until BOTH stream diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 06aa0775..eb60c366 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -21,6 +21,12 @@ use host_stage::{HostStage, Job}; mod chunk_stream; #[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] use chunk_stream::{ChunkStream, Entry as StreamEntry}; +#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +pub(crate) use chunk_stream::{prefetch_point, prefetch_window_end}; +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +pub(crate) fn prefetch_point() {} +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +pub(crate) fn prefetch_window_end() {} #[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] struct ChunkStream; #[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] @@ -196,9 +202,9 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, bank: &Rc>, first: u8, - inflight: usize, + bytes_per_second: f64, ) -> Result<()> { - self.begin_stream_inner(read, bank, first, inflight) + self.begin_stream_inner(read, bank, first, bytes_per_second) } #[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] fn begin_stream_inner( @@ -206,7 +212,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { _: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, _: &Rc>, _: u8, - _: usize, + _: f64, ) -> Result<()> { Err(Error::UnsupportedPlatform) } @@ -216,7 +222,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, bank: &Rc>, first: u8, - inflight: usize, + bytes_per_second: f64, ) -> Result<()> { use crate::ffi::original_stager::Api as StagerApi; self.validate_context(self.context)?; @@ -249,8 +255,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { entries.push(StreamEntry { layer, expert, pieces }); } } - let api = std::sync::Arc::new(StagerApi::load()?); - let token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?); + let api = StagerApi::load()?; let guard = self.context.enter()?; let mut events = Vec::new(); let created = (|| -> Result<()> { @@ -273,7 +278,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?; // the copies must follow everything the compute path queued so far on its own streams self.context.synchronize()?; - match ChunkStream::start(api, token, copy, first, entries, targets, copied, used, inflight) { + match ChunkStream::start(api, copy, first, entries, targets, copied, used, bytes_per_second) { Ok(stream) => { self.stream = Some(stream); self.stream_bank = Some(Rc::clone(bank)); diff --git a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs index 1a8fd222..e1d89725 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs @@ -9,17 +9,19 @@ use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace, use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage}; -/// prefill.cpp `stream_all` (`begin_prompt_stream`): on for chunks of at least `STRATA_PREFILL_STREAM_MIN` +/// prefill.cpp `stream_all` order (`begin_prompt_stream`): on for chunks of at least `STRATA_PREFILL_STREAM_MIN` /// rows (1024) over a registered bank; `LELEKA_PREFILL_STREAM=0` keeps the per-layer copy ring. -/// `LELEKA_PREFILL_STREAM_INFLIGHT` bounds the queued copies (default 4). -fn prompt_stream_settings() -> Option<(usize, usize)> { - static SETTINGS: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// `LELEKA_PREFILL_PCIE_GBPS` (default 45) sizes the copies queued under a GDN layer's kernels. +fn prompt_stream_settings() -> Option<(usize, f64)> { + static SETTINGS: std::sync::OnceLock> = std::sync::OnceLock::new(); *SETTINGS.get_or_init(|| { if std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "0") { return None; } let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default); - Some((number("STRATA_PREFILL_STREAM_MIN", 1024), number("LELEKA_PREFILL_STREAM_INFLIGHT", 4).clamp(1, 64))) + let gbps = std::env::var("LELEKA_PREFILL_PCIE_GBPS").ok().and_then(|v| v.trim().parse::().ok()) + .filter(|g| g.is_finite() && *g > 1.0).unwrap_or(45.0); + Some((number("STRATA_PREFILL_STREAM_MIN", 1024), gbps * 1e9)) }) } @@ -186,12 +188,12 @@ impl<'ctx> MoeWeightCache<'ctx> { let last_layer = layer.get() + 1 == binding.layer_count(); let result = (|| { if layer.get() == 0 && !schedule.prompt_stream_active() - && let Some((minimum, inflight)) = prompt_stream_settings() + && let Some((minimum, bytes_per_second)) = prompt_stream_settings() && read.rows() >= minimum && !bank.pageable() { // the whole chunk's expert stream starts with the first MoE layer - schedule.begin_prompt_stream(&read, &bank, 0, inflight).map_err(driver_error)?; - crate::bringup_trace!("DBG prefill stream: begin rows={} inflight={inflight}", read.rows()); + schedule.begin_prompt_stream(&read, &bank, 0, bytes_per_second).map_err(driver_error)?; + crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows()); } // High-only is the selected literal Original mixed BF16 policy. let prepare_span = prof::span(PStage::MoePrepare, drain);