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 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 17:31:29 +02:00
co-authored by Claude Opus 5.5
parent 84983abdb2
commit 80627bc86d
6 changed files with 632 additions and 5 deletions
@@ -208,6 +208,26 @@ impl<'ctx> MappedExpertBank<'ctx> {
+ 2 * size_of::<usize>()
+ self.banks.capacity() * size_of::<RegisteredBank>()
}
/// 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
@@ -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<Entry>,
targets: Vec<(BufferHandle, usize)>,
copied: Vec<usize>,
used: Vec<usize>,
issued: AtomicUsize,
consumed: AtomicUsize,
stop: AtomicBool,
failed: AtomicBool,
error: Mutex<Option<Error>>,
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<Api>, shared: Arc<Shared>, 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<Api>,
shared: Arc<Shared>,
thread: Option<JoinHandle<()>>,
/// 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<Api>,
context: usize,
copy: usize,
first: u8,
entries: Vec<Entry>,
targets: Vec<(BufferHandle, usize)>,
copied: Vec<usize>,
used: Vec<usize>,
inflight: usize,
) -> Result<Self> {
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<usize> {
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<usize>, Vec<usize>) {
(self.shared.copied.clone(), self.shared.used.clone())
}
}
impl Drop for ChunkStream {
fn drop(&mut self) {
let _ = self.stop();
}
}
+265 -4
View File
@@ -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<usize> {
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<usize>;
@@ -64,6 +95,11 @@ pub struct OriginalMmqCopySchedule<'ctx> {
/// first use, with one completion event per page-locked buffer.
host: Option<HostStage>,
host_events: Vec<OriginalGpuEvent<'ctx>>,
/// prefill.cpp's `stream_all` issuer for the current prompt chunk (`begin_prompt_stream`), its bank and
/// raw per-slot events.
stream: Option<ChunkStream>,
stream_bank: Option<Rc<crate::MappedExpertBank<'ctx>>>,
stream_events: Vec<usize>,
}
impl Context<'_> {
pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result<OriginalMmqCopySchedule<'_>> {
@@ -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<crate::MappedExpertBank<'ctx>>,
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<crate::MappedExpertBank<'ctx>>,
_: 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<crate::MappedExpertBank<'ctx>>,
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<usize> {
@@ -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<usize>,
/// the host staging job of an expert copied through `HostStage`
job: Option<usize>,
/// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`)
entry: Option<usize>,
}
/// 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() {
@@ -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<bool> {
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
}
@@ -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<Option<(usize, usize)>> = 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<GdnNativeFormat> {
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<Rc<leleka_cuda_driver::MappedExpertBank<'ctx>>> {
@@ -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
}
@@ -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)