From ae283e6423a9e35e7a0ea3a2c2f2a769fdbc0a85 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 13:21:32 +0200 Subject: [PATCH] perf(prefill): stage pageable experts through page-locked buffers (prefill.cpp Stager) With a pageable, file-mapped expert bank (the laptop profile) the copy ring copied every expert with a pageable cuMemcpyHtoDAsync on the launching thread: the driver stages it, the mapped file is faulted in on one thread and the GPU waits for each copy; the runtime had also rescanned every first-seen expert's bytes for the finite admission, a second read. The ring now keeps prefill.cpp's Stager in its copy schedule: helper threads (4, or 32 when the experts are read in place from the model files; STRATA_STAGER_THREADS) copy each staged expert's gate/up/down bytes, in launch order, into a ring of page-locked buffers (16, or 4 x threads; STRATA_STAGER_RING) and check every block scale finite on the copy; the launching thread DMAs a buffer once it is ready and releases it when its DMA completed (no CUDA call on a helper). Experts inside page-locked pin_resident ranges, registered banks and arena-resident experts keep their direct DMA. A staged expert skips the runtime's host rescan (the helpers check the same scales). Same bytes reach the same device slots. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/api.rs | 9 + crates/cuda-driver/src/mapped_expert_bank.rs | 12 + .../src/mmq_original_host_stage.rs | 361 ++++++++++++++++++ crates/cuda-driver/src/mmq_original_ring.rs | 98 +++++ .../src/qwen_forward/cache_original_prompt.rs | 22 +- 5 files changed, 494 insertions(+), 8 deletions(-) create mode 100644 crates/cuda-driver/src/mmq_original_host_stage.rs diff --git a/crates/cuda-driver/src/api.rs b/crates/cuda-driver/src/api.rs index 57731106..3067ce85 100644 --- a/crates/cuda-driver/src/api.rs +++ b/crates/cuda-driver/src/api.rs @@ -308,6 +308,12 @@ mod enabled { // SAFETY: identical live registered base from `register_read_only`; all consumers drained. check("cuMemHostUnregister", unsafe { (self.inner.unregister)(start as *mut c_void) }) } + /// Page-lock `len` bytes at page-aligned `start` of a writable host allocation the caller owns (flags 0): + /// the prompt path's host staging buffers, so their H2D copies are DMA. Released by `unregister_at`. + pub(crate) fn register_staging(&self, start: usize, len: usize) -> Result<()> { + // SAFETY: the caller passes a live page-aligned allocation it retains until `unregister_at`. + check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 0) }) + } pub(crate) fn copy_kernel( &self, actual: &mut MappedCopyArguments, @@ -480,6 +486,9 @@ impl MappedApi { pub(crate) fn unregister_at(&self, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } + pub(crate) fn register_staging(&self, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn copy_kernel(&self, _: &mut MappedCopyArguments, _: Stream) -> Result<()> { Err(Error::UnsupportedPlatform) } diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index 53b7f48b..b21773c4 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -334,6 +334,18 @@ impl<'ctx> MappedExpertBank<'ctx> { cuts.dedup(); cuts.windows(2).map(|w| (w[0] - start, w[1] - w[0])).collect() } + /// Whether the prompt path copies this expert through its pinned host staging (`HostStage` of the copy + /// ring, prefill.cpp's `Stager`): a pageable bank whose gate/up/down bytes are not all inside page-locked + /// `pin_resident` ranges. Those bytes are copied by helper threads into page-locked buffers, which also check + /// every block scale finite there, then DMA'd; the rest are DMA'd from the bank in place. + pub fn host_staged(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { + self.pageable && !spans.iter().all(|span| self.page_locked(span.bytes())) + } + fn page_locked(&self, bytes: &[u8]) -> bool { + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + self.resident.borrow().iter().any(|&(a, n)| start >= a && end <= a + n) + } /// Bytes page-locked by `pin_resident`. pub fn resident_bytes(&self) -> u64 { self.resident.borrow().iter().map(|&(_, n)| n as u64).sum() diff --git a/crates/cuda-driver/src/mmq_original_host_stage.rs b/crates/cuda-driver/src/mmq_original_host_stage.rs new file mode 100644 index 00000000..fdbf04c3 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_host_stage.rs @@ -0,0 +1,361 @@ +//! prefill.cpp `Stager` (166..294): the prompt path's host staging of experts that are not page-locked. Helper +//! threads copy each such expert's gate/up/down bytes, in launch order, into a ring of page-locked host buffers +//! ahead of the launches; the launching thread DMAs a buffer once its copy is ready, and the buffer is free again +//! once that DMA has completed. Copied in line by the launching thread (a pageable `cuMemcpyHtoDAsync`, which the +//! driver stages and which faults a mapped file in on one thread), the GPU waited for every copy. +//! +//! The helpers also check every block scale of the bytes they copied finite (the routed formats' one FP16 field, +//! see `encoded_finite` of the runtime): a staged expert is admitted there instead of by a separate host pass +//! over the source, so the source is read once. +//! +//! The helpers never call CUDA: the launching thread records the DMA events and releases the buffers. Every job +//! pointer is into a bank the copy ring retains, and `finish` (run before the ring releases the bank, on every +//! path) returns only once no helper is copying. +// Raw page-locked buffers shared with the helper threads (see the SAFETY notes). +#![allow(unsafe_code)] +use crate::{Error, Result, api}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::{self, JoinHandle}; + +/// Jobs of one layer at most (every routed expert). +const MAX_JOBS: usize = 512; + +/// One expert's three role slices (address, length, raw GGUF kind), copied back to back into one buffer. +#[derive(Clone, Copy)] +pub(super) struct Job { + pub(super) pieces: [(usize, usize, u32); 3], +} + +struct Wake { + generation: u32, + jobs: Arc<[Job]>, + quit: bool, +} +struct Shared { + wake: Mutex, + cv: Condvar, + /// generation << 32 | job count << 16 | next job to claim + head: AtomicU64, + /// the generation in which job j's buffer was filled (finite) / found non-finite (high bit) + ready: Box<[AtomicU32]>, + /// jobs below this have their buffers free again (their DMA completed) + released: AtomicUsize, + active: AtomicUsize, + buffers: Box<[usize]>, + buffer_bytes: usize, +} +const NON_FINITE: u32 = 1 << 31; + +/// Block bytes of the routed formats with one leading FP16 scale per block (IQ3_XXS, IQ3_S, IQ2_S, IQ4_XS, +/// IQ4_NL, Q2_0); `None` for any other kind, which is refused. +fn block_bytes(kind: u32) -> Option { + match kind { + 18 => Some(98), + 21 => Some(110), + 22 => Some(82), + 23 => Some(136), + 20 | 42 => Some(18), + _ => None, + } +} +/// Every block's FP16 scale finite (exponent field not all ones), whole blocks only. +pub(super) fn scales_finite(kind: u32, bytes: &[u8]) -> bool { + let Some(block) = block_bytes(kind) else { return false }; + bytes.len().is_multiple_of(block) + && bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) +} + +impl Shared { + fn claim(&self, generation: u32) -> Option { + let mut current = self.head.load(Ordering::Acquire); + loop { + if (current >> 32) as u32 != generation { + return None; + } + let n = ((current >> 16) & 0xffff) as usize; + let j = (current & 0xffff) as usize; + if j >= n { + return None; + } + match self.head.compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return Some(j), + Err(actual) => current = actual, + } + } + } + fn work(&self) { + let mut seen = 0u32; + loop { + let jobs = { + let mut wake = self.wake.lock().unwrap_or_else(|p| p.into_inner()); + while !wake.quit && wake.generation == seen { + wake = self.cv.wait(wake).unwrap_or_else(|p| p.into_inner()); + } + if wake.quit { + return; + } + seen = wake.generation; + Arc::clone(&wake.jobs) + }; + loop { + self.active.fetch_add(1, Ordering::AcqRel); + let Some(j) = self.claim(seen) else { + self.active.fetch_sub(1, Ordering::AcqRel); + break; + }; + let ring = self.buffers.len(); + // buffer j % ring holds job j - ring until that job's DMA completed + let mut cancelled = false; + while j >= ring && self.released.load(Ordering::Acquire) <= j - ring { + if (self.head.load(Ordering::Acquire) >> 32) as u32 != seen + || ((self.head.load(Ordering::Acquire) >> 16) & 0xffff) == 0 + { + cancelled = true; + break; + } + thread::yield_now(); + } + if !cancelled { + let job = jobs[j]; + let base = self.buffers[j % ring]; + let mut offset = 0usize; + let mut finite = true; + for (address, length, kind) in job.pieces { + if offset + length > self.buffer_bytes { + finite = false; + break; + } + // SAFETY: `address..+length` lies in a bank the copy ring retains until `finish` has seen + // this helper leave (active == 0); the destination is this job's exclusive buffer (its + // previous job's DMA completed: `released`), inside the owned allocation. + let (source, destination) = unsafe { + ( + std::slice::from_raw_parts(address as *const u8, length), + std::slice::from_raw_parts_mut((base + offset) as *mut u8, length), + ) + }; + destination.copy_from_slice(source); + finite &= scales_finite(kind, destination); + offset += length; + } + self.ready[j].store(if finite { seen } else { seen | NON_FINITE }, Ordering::Release); + } + self.active.fetch_sub(1, Ordering::AcqRel); + } + } + } +} + +/// The page-locked ring and its helper threads, persistent across layers and chunks (one per copy schedule). +pub(super) struct HostStage { + shared: Arc, + threads: Vec>, + /// page-aligned allocations backing `shared.buffers`, page-locked while `registered` + allocations: Vec<(*mut u8, std::alloc::Layout)>, + registered: Vec, + api: Option, + generation: u32, + jobs: usize, + issued: usize, + poisoned: bool, +} +impl HostStage { + /// `ring` page-locked buffers of `buffer_bytes`, `threads` helpers (prefill.cpp: 4 threads and 16 buffers, + /// 32 and 128 when the experts are read in place from the model files; `STRATA_STAGER_THREADS` / + /// `STRATA_STAGER_RING` override). The caller's Context must be current (page-locking). + pub(super) fn new(buffer_bytes: usize, files: bool) -> Result { + let atoi = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let hw = thread::available_parallelism().map_or(1, usize::from); + let threads = match atoi("STRATA_STAGER_THREADS") { + Some(t) => t.clamp(1, 32) as usize, + None if files => 32, + None => (hw / 4).clamp(2, 4), + }; + let ring = match atoi("STRATA_STAGER_RING") { + Some(r) => r.clamp(2, 256) as usize, + None if files => 4 * threads, + None => 16, + }; + if buffer_bytes == 0 { + return Err(Error::InvalidSize); + } + let page = api::page_size()?; + let bytes = buffer_bytes.next_multiple_of(page); + let layout = std::alloc::Layout::from_size_align(bytes, page).map_err(|_| Error::InvalidSize)?; + let mut owner = Self { + shared: Arc::new(Shared { + wake: Mutex::new(Wake { generation: 0, jobs: Arc::from(Vec::new()), quit: false }), + cv: Condvar::new(), + head: AtomicU64::new(0), + ready: (0..MAX_JOBS).map(|_| AtomicU32::new(0)).collect(), + released: AtomicUsize::new(0), + active: AtomicUsize::new(0), + buffers: Box::new([]), + buffer_bytes, + }), + threads: Vec::new(), + allocations: Vec::new(), + registered: Vec::new(), + api: None, + generation: 0, + jobs: 0, + issued: 0, + poisoned: false, + }; + owner.api = Some(api::MappedApi::load()?); + let mut buffers = Vec::with_capacity(ring); + for _ in 0..ring { + // SAFETY: non-zero size, valid power-of-two alignment. + let pointer = unsafe { std::alloc::alloc(layout) }; + if pointer.is_null() { + return Err(Error::HostAllocation); + } + owner.allocations.push((pointer, layout)); + buffers.push(pointer as usize); + } + for &(pointer, layout) in &owner.allocations { + owner.api.as_ref().ok_or(Error::ContextPoisoned)?.register_staging(pointer as usize, layout.size())?; + owner.registered.push(pointer as usize); + } + Arc::get_mut(&mut owner.shared).ok_or(Error::ContextPoisoned)?.buffers = buffers.into_boxed_slice(); + for _ in 0..threads { + let shared = Arc::clone(&owner.shared); + let handle = thread::Builder::new() + .name("leleka-stager".into()) + .stack_size(256 * 1024) + .spawn(move || shared.work()) + .map_err(|_| Error::HostAllocation)?; + owner.threads.push(handle); + } + Ok(owner) + } + pub(super) fn ring(&self) -> usize { + self.shared.buffers.len() + } + pub(super) fn buffer_bytes(&self) -> usize { + self.shared.buffer_bytes + } + /// A layer's jobs, in launch order; the previous layer's were finished. + pub(super) fn start(&mut self, jobs: Vec) -> Result<()> { + if self.poisoned || self.jobs != 0 || jobs.len() > MAX_JOBS { + return Err(Error::InvalidProjectionShape); + } + if jobs.is_empty() { + return Ok(()); + } + self.generation = self.generation.wrapping_add(1) & !NON_FINITE; + if self.generation == 0 { + self.generation = 1; + } + self.jobs = jobs.len(); + self.issued = 0; + self.shared.released.store(0, Ordering::Release); + let mut wake = self.shared.wake.lock().map_err(|_| Error::ContextPoisoned)?; + wake.jobs = Arc::from(jobs); + wake.generation = self.generation; + self.shared.head.store( + (u64::from(self.generation) << 32) | ((self.jobs as u64) << 16), + Ordering::Release, + ); + drop(wake); + self.shared.cv.notify_all(); + Ok(()) + } + /// Job `j`'s staged bytes (`length` of them), once its copy is ready. `release` is polled while waiting: it + /// returns how many issued jobs' DMAs have completed, in order (the helpers wait for those buffers). + pub(super) fn wait(&mut self, j: usize, length: usize, mut release: impl FnMut() -> Result) -> Result<&[u8]> { + if j >= self.jobs || j != self.issued || length > self.shared.buffer_bytes { + return Err(Error::InvalidProjectionShape); + } + loop { + let state = self.shared.ready[j].load(Ordering::Acquire); + if state & !NON_FINITE == self.generation { + if state & NON_FINITE != 0 { + return Err(Error::NonFiniteMmqOutput("routed expert weights")); + } + break; + } + let done = release()?; + if done > self.shared.released.load(Ordering::Acquire) { + self.shared.released.store(done, Ordering::Release); + } + thread::yield_now(); + } + let base = self.shared.buffers[j % self.ring()]; + // SAFETY: the helper finished writing this buffer (Acquire above) and no helper writes it again before the + // DMA the caller queues from it completed (`released`); the allocation outlives this borrow. + Ok(unsafe { std::slice::from_raw_parts(base as *const u8, length) }) + } + /// The caller queued job `j`'s DMA (and recorded its completion event). + pub(super) fn issued(&mut self, j: usize) { + self.issued = j + 1; + } + /// Jobs whose DMA has been queued. + pub(super) fn issued_count(&self) -> usize { + self.issued + } + /// No helper copies after this (the end of a layer, or an early return in the middle of one). + pub(super) fn finish(&mut self) { + self.shared.head.store(u64::from(self.generation) << 32, Ordering::Release); + self.shared.released.store(usize::MAX / 2, Ordering::Release); + while self.shared.active.load(Ordering::Acquire) != 0 { + thread::yield_now(); + } + self.jobs = 0; + self.issued = 0; + } + /// Stop the helpers and unlock and free the buffers. The caller drained every DMA from them. + pub(super) fn close(&mut self) -> Result<()> { + self.finish(); + if let Ok(mut wake) = self.shared.wake.lock() { + wake.quit = true; + } + self.shared.cv.notify_all(); + for handle in self.threads.drain(..) { + let _ = handle.join(); + } + let mut result = Ok(()); + if let Some(api) = &self.api { + for start in self.registered.drain(..) { + result = crate::combine(result, api.unregister_at(start)); + } + } + if result.is_err() { + // a buffer that may still be page-locked is never returned to the allocator + self.poisoned = true; + self.allocations.clear(); + return result; + } + for (pointer, layout) in self.allocations.drain(..) { + // SAFETY: allocated above with this layout, unregistered, no helper or DMA uses it. + unsafe { std::alloc::dealloc(pointer, layout) }; + } + result + } +} +impl Drop for HostStage { + fn drop(&mut self) { + let _ = self.close(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn scales_finite_matches_the_one_fp16_field_rule() { + for (kind, block) in [(18u32, 98usize), (21, 110), (22, 82), (23, 136), (20, 18), (42, 18)] { + let mut bytes = vec![0x11u8; block * 3]; + assert!(scales_finite(kind, &bytes)); + for bits in [0x7c00u16, 0x7e00, 0xfc00, 0x7c01, 0xffff] { + bytes[block..block + 2].copy_from_slice(&bits.to_le_bytes()); + assert!(!scales_finite(kind, &bytes), "kind {kind} bits {bits:#x}"); + } + bytes[block..block + 2].copy_from_slice(&0x7bffu16.to_le_bytes()); + assert!(scales_finite(kind, &bytes)); + assert!(!scales_finite(kind, &bytes[..block + 1]), "partial block"); + } + assert!(!scales_finite(8, &[0u8; 34])); + } +} diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index a7871b94..4a3d2cb4 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -7,6 +7,9 @@ use crate::original_gpu_schedule::{ }; use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole}; use std::rc::Rc; +#[path = "mmq_original_host_stage.rs"] +mod host_stage; +use host_stage::{HostStage, Job}; const COMMAND_CAP: usize = 2048; trait RingArena: GroupArena { fn stage_slots(&self) -> Result; @@ -51,6 +54,10 @@ pub struct OriginalMmqCopySchedule<'ctx> { failed: bool, closed: bool, host_metadata_outside: usize, + /// prefill.cpp's `Stager` for experts that are not page-locked (a pageable, file-mapped bank): created on + /// first use, with one completion event per page-locked buffer. + host: Option, + host_events: Vec>, } impl Context<'_> { pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result> { @@ -69,6 +76,8 @@ impl Context<'_> { failed: false, closed: false, host_metadata_outside: 0, + host: None, + host_events: Vec::new(), }; let result = (|| { owner @@ -173,6 +182,17 @@ impl OriginalMmqCopySchedule<'_> { .as_ref() .map_or(Ok(()), OriginalGpuStream::synchronize); let mut result = combine(copy, compute); + if let Some(mut host) = self.host.take() { + if result.is_ok() { + result = combine(result, host.close()); + } else { + // a DMA may still read a buffer: keep the allocation and the helpers' state + std::mem::forget(host); + } + } + for event in self.host_events.drain(..) { + result = combine(result, event.close()); + } for events in &mut self.events { if let Some(e) = events.copied.take() { result = combine(result, e.close()); @@ -205,6 +225,8 @@ struct Source<'read> { spans: &'read [ResidentExpertBankSpan; 3], resident: Option<[ffi::BufferHandle; 3]>, slot: Option, + /// the host staging job of an expert copied through `HostStage` + job: Option, } /// Private owner: no external pointer/ready event can manufacture a stage. /// The actual source Rc prevents unregister/free during H2D or gathered use. @@ -219,6 +241,9 @@ pub(super) struct Ring<'read, 'ctx> { status: Option>, flags: Vec, stage_next: usize, + /// host staging started for this layer; DMAs of staged jobs known complete (in order) + staging: bool, + stage_done: usize, submitted: bool, drained: bool, closed: bool, @@ -269,6 +294,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { status: None, flags: Vec::new(), stage_next: 0, + staging: false, + stage_done: 0, submitted: false, drained: false, closed: false, @@ -358,8 +385,23 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { spans, resident, slot: None, + job: None, }); } + // 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) { + let mut pieces = [(0usize, 0usize, 0u32); 3]; + for (role, span) in source.spans.iter().enumerate() { + let bytes = bank.cache_source(span)?; + pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind()); + } + source.job = Some(jobs.len()); + jobs.push(Job { pieces }); + } + } let charge = groups * 16; let required = charge .checked_add(128 * 1024 * 1024) @@ -376,6 +418,33 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { // The old input quantization/metadata upload used default stream. // Admit that dependency once before starting nonblocking producers. context.synchronize()?; + if !jobs.is_empty() { + let pageable = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable(); + let schedule = &mut *owner.schedule; + if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) { + // a larger blob than the buffers: every earlier DMA from them was drained with its layer + let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?; + old.close()?; + for event in schedule.host_events.drain(..) { + event.close()?; + } + } + if schedule.host.is_none() { + let guard = context.enter()?; + let created = HostStage::new(blob, pageable); + let pop = guard.finish(); + let host = match (created, pop) { + (Ok(host), Ok(())) => host, + (Err(e), _) | (Ok(_), Err(e)) => return Err(e), + }; + for _ in 0..host.ring() { + schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?); + } + schedule.host = Some(host); + } + schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?; + owner.staging = true; + } Ok(()) })(); if let Err(primary) = result { @@ -458,6 +527,27 @@ 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 { + // 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)?; + let host_events = &mut self.schedule.host_events; + let ring = host.ring(); + let issued = host.issued_count(); + let done = &mut self.stage_done; + let staged = host.wait(j, blob, || { + while *done < issued && host_events[*done % ring].query()? { + *done += 1; + } + Ok(*done) + })?; + let destination = slot.span.checked_subspan(slot.bytes, 0, blob)?; + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| api.copy_registered(destination, staged, stream))?; + host_events[j % ring].record(copy)?; + host.issued(j); + } else { let sources = [ bank.cache_source(&source.spans[0])?, bank.cache_source(&source.spans[1])?, @@ -485,6 +575,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } Ok(()) })?; + } events .copied .as_mut() @@ -616,6 +707,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { return Ok(()); } self.closed = true; + // no stager helper reads the bank after this + if self.staging { + if let Some(host) = self.schedule.host.as_mut() { + host.finish(); + } + self.staging = false; + } let mut result = if self.submitted { self.drain() } else { Ok(()) }; if self.context.is_poisoned() || result.is_err() { self.context.poison(); 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 d095845d..05b1adf9 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs @@ -179,7 +179,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let members = [(&bound, 0)]; let bit = layer.get() as usize * 512 + expert as usize; let admitted = bit < 48 * 512 && finite[bit / 64] >> (bit % 64) & 1 == 1; - let (span, format) = binding.with_moe_routed_source(&members, binding_error, |source| { + let ((span, scanned), format) = binding.with_moe_routed_source(&members, binding_error, |source| { let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let operation = (|| { source.validate_binding(binding).map_err(binding_error)?; @@ -193,13 +193,19 @@ impl<'ctx> MoeWeightCache<'ctx> { original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?.0, original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?.0]; // The whole finite admission of an expert's immutable bank bytes runs once per bank; - // later chunks take the same descriptor/geometry-checked span without the rescan. - let span = |role| if admitted { source.bank_span(0, role) } else { source.mapped_span(0, role) }; - let spans = [span(roles[0]).map_err(binding_error)?, - span(roles[1]).map_err(binding_error)?, - span(roles[2]).map_err(binding_error)?]; + // later chunks take the same descriptor/geometry-checked span without the rescan. An expert + // the copy ring stages through page-locked host buffers (a pageable bank) is checked by the + // stager's helpers on the bytes they copy, so the source is not read twice. + let located = [source.bank_span(0, roles[0]).map_err(binding_error)?, + source.bank_span(0, roles[1]).map_err(binding_error)?, + source.bank_span(0, roles[2]).map_err(binding_error)?]; + let (spans, scanned) = if admitted || bank.host_staged(&located) { (located, false) } else { + ([source.mapped_span(0, roles[0]).map_err(binding_error)?, + source.mapped_span(0, roles[1]).map_err(binding_error)?, + source.mapped_span(0, roles[2]).map_err(binding_error)?], true) + }; if !bank.eligible(&spans) { return Err(Error::IdentityMismatch); } - Ok((spans, formats)) + Ok(((spans, scanned), formats)) })(); // Actual retained immutable spans survive this source fence; // every later DMA holds the real bank owner, not this scope. @@ -207,7 +213,7 @@ impl<'ctx> MoeWeightCache<'ctx> { match operation { Err(e) => Err(e), Ok(v) => { finish?; Ok(v) } } })?; if bit >= 48 * 512 { return Err(Error::InvalidExpert); } - finite[bit / 64] |= 1 << (bit % 64); + if scanned { finite[bit / 64] |= 1 << (bit % 64); } if routed_formats.is_some_and(|previous| previous != format) { return Err(Error::IdentityMismatch); } routed_formats = Some(format); sources.push(span);