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..22c7667c 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -507,15 +507,26 @@ 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 { + // 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()); + } + 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 +551,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 +567,10 @@ 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()); + } let pop = guard.finish(); let result = combine(combine(combine(operation, sync), all), pop); if result.is_err() { 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/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b10edb07..b10a9d26 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, }; @@ -132,6 +133,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/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index ca48d96b..a8a96ca5 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..f5609335 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_chunk_stream.rs @@ -0,0 +1,274 @@ +//! 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 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}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +#[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 Core { + api: Api, + entries: Vec, + targets: Vec<(BufferHandle, usize)>, + copied: Vec, + used: Vec, + /// 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 Core { + fn ring(&self) -> usize { + self.targets.len() + } + 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 + self.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); + } + self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?; + offset = end; + } + self.api.record(self.copied[slot], self.copy) + } +} + +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 { + 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: Api, + copy: usize, + first: u8, + entries: Vec, + targets: Vec<(BufferHandle, usize)>, + copied: Vec, + used: Vec, + 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() { + while k < entries.len() && usize::from(entries[k].layer) < layer { + k += 1; + } + *start = k; + } + let core = Rc::new(Core { + api, + entries, + targets, + copied, + used, + 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), + }); + ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core))); + Ok(Self { core }) + } + pub(super) fn next_layer_is(&self, layer: u8) -> bool { + 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.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()) + }) + } + /// 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.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`. + 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(()) + } + /// 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.core.consumed.get() != k { + return Err(Error::InvalidProjectionShape); + } + 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.core.consumed.get() != k || self.core.issued.get() <= k { + return Err(Error::InvalidProjectionShape); + } + 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 !self.next_layer_is(layer) { + return Err(Error::InvalidProjectionShape); + } + let end = self.core.layer_end(layer); + self.release_until(end, compute)?; + self.core.next_layer.set(layer + 1); + Ok(()) + } + /// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream. + pub(super) fn stop(&mut self) -> 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(()) } + } + pub(super) fn api(&self) -> &Api { + &self.core.api + } +} +impl Drop for ChunkStream { + fn drop(&mut self) { + let _ = self.stop(); + } +} 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 4a3d2cb4..eb60c366 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -9,7 +9,50 @@ 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}; +#[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(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")))] +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; @@ -58,6 +101,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> { @@ -78,6 +126,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 @@ -117,7 +168,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<()> { @@ -137,6 +188,150 @@ 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, + bytes_per_second: f64, + ) -> Result<()> { + 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( + &mut self, + _: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + _: &Rc>, + _: u8, + _: f64, + ) -> 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, + bytes_per_second: f64, + ) -> 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 = StagerApi::load()?; + 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, copy, first, entries, targets, copied, used, bytes_per_second) { + 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 { @@ -172,6 +367,7 @@ impl OriginalMmqCopySchedule<'_> { if self.closed { return Ok(()); } + let ended = self.end_prompt_stream(); self.closed = true; let copy = self .copy @@ -181,7 +377,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()); @@ -227,6 +423,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. @@ -243,6 +441,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, @@ -295,6 +496,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, @@ -386,13 +589,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)?; @@ -500,7 +729,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() { @@ -527,7 +756,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)?; @@ -602,8 +834,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]; @@ -645,6 +892,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]; @@ -661,6 +917,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()?; @@ -707,6 +975,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/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/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/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 2e1a645f..c4402014 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -348,6 +348,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); @@ -359,6 +364,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(); 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..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,6 +9,22 @@ 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` 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_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); + 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)) + }) +} + fn native_format(key: MoeWeightDescriptor) -> Result { match key.raw_kind { 8 => Ok(GdnNativeFormat::Q8_0), 12 => Ok(GdnNativeFormat::Q4K), @@ -66,6 +82,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 +185,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, 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, 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); let mut layer_program = program.prepare(read, shared, weights, formats, false) @@ -228,8 +261,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/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/executor_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs index 22c40cb3..d63b5df7 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); @@ -345,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})?; @@ -390,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) 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/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 69fcde9b..407614f0 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. @@ -23,6 +31,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 +64,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; 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, ]; @@ -59,11 +74,18 @@ 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", 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", @@ -170,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)] 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..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())?;} @@ -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) }