perf(prefill): stream-scoped drains while the chunk expert stream is in flight

While a prompt chunk's expert copy stream is active, Api::synchronize (the one
cuCtxSynchronize choke point every compute producer uses) waits for the legacy
default stream and every registered compute stream except the copy stream,
instead of the whole context (which also waited for every queued expert copy
and made all earlier overlap attempts degenerate). Every stream the crate
creates is registered; outside a chunk stream a drain is unchanged.

The ring's layer drain no longer waits for the copy stream in stream mode, the
per-layer status words are pooled (a cuMemFree per MoE layer synchronized the
device), and each scoped drain first tops the copy queue up by
LELEKA_PREFILL_TOPUP (48) entries; the layer end queues the next layer's first
entries. Diagnostics: LELEKA_PREFILL_COPY_STATS (per-chunk PREFILL-COPY line:
calls, bytes, DMA GB/s), LELEKA_PREFILL_ALLOC_TRACE, LELEKA_PREFILL_STREAM_JITTER
(race hunt), LELEKA_PREFILL_STREAM_SEQ (paired A/B passes in one process).
Still opt-in (LELEKA_PREFILL_STREAM=1) until the paired A/B and the quality
gates pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-17 01:19:19 +02:00
co-authored by Claude Sonnet 5.5
parent 499faec1ae
commit e12914e0d5
14 changed files with 304 additions and 89 deletions
+2
View File
@@ -112,6 +112,7 @@ mod enabled {
if handle.is_null() {
return Err(Error::InvalidDriverValue("cuStreamCreate"));
}
crate::compute_drain::register(handle as usize);
Ok(Stream(handle as usize))
}
pub(crate) fn create_event(&self) -> Result<Event> {
@@ -193,6 +194,7 @@ mod enabled {
})
}
pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> {
crate::compute_drain::unregister(stream.0);
// SAFETY: only called before enqueue or after proven completion.
check("cuStreamDestroy_v2", unsafe {
(self.stream_destroy)(stream.0 as *mut c_void)
+78
View File
@@ -0,0 +1,78 @@
//! Stream-scoped drains for the prompt chunk's expert stream (prefill.cpp `stream_all`).
//!
//! Every compute producer of the prefill path drains with `cuCtxSynchronize`, which also waits for the expert
//! copies queued on the chunk's copy stream: no copy could ever overlap a mixer. While a chunk's copy stream is
//! the registered *background* stream, `Api::synchronize` instead waits for the legacy default stream and every
//! registered compute stream except the background one. Every stream the crate creates is registered here
//! (blas, Original schedule, owned-copy, swap), so the only work a drain no longer waits for is the chunk's copy
//! stream, whose consumers order themselves with the per-slot `copied`/`used` events. Outside a chunk stream
//! (background == 0) a drain is the unchanged context-wide `cuCtxSynchronize`.
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
static STREAMS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
static BACKGROUND: AtomicUsize = AtomicUsize::new(0);
static DRAINS: AtomicUsize = AtomicUsize::new(0);
/// Scoped drains since the last call (reported once per chunk stream).
pub(crate) fn take_drains() -> usize {
DRAINS.swap(0, Ordering::Relaxed)
}
pub(crate) fn register(stream: usize) {
if stream == 0 {
return;
}
let mut all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
if !all.contains(&stream) {
all.push(stream);
}
}
pub(crate) fn unregister(stream: usize) {
let mut all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
all.retain(|s| *s != stream);
let _ = BACKGROUND.compare_exchange(stream, 0, Ordering::SeqCst, Ordering::SeqCst);
}
/// The chunk's copy stream (0 clears): drains stop waiting for it.
pub(crate) fn set_background(stream: usize) {
BACKGROUND.store(stream, Ordering::SeqCst);
}
pub(crate) fn background() -> usize {
BACKGROUND.load(Ordering::SeqCst)
}
/// Drain the legacy default stream and every registered stream but the background one.
pub(crate) fn drain(mut sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> {
DRAINS.fetch_add(1, Ordering::Relaxed);
let background = background();
let mut result = sync(0);
let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
for &stream in all.iter() {
if stream != background {
let r = sync(stream);
if result.is_ok() {
result = r;
}
}
}
result
}
/// LELEKA_PREFILL_ALLOC_TRACE=1: while a chunk stream is in flight, every device allocation / free (cuMemFree and
/// cuMemAlloc synchronize the whole device, copy stream included) prints once per call site (first 64 events).
pub(crate) fn note_alloc(what: &str, bytes: usize) {
if background() == 0 {
return;
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static SEEN: AtomicUsize = AtomicUsize::new(0);
if !*ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_ALLOC_TRACE").is_some_and(|v| v == "1")) {
return;
}
if SEEN.fetch_add(1, Ordering::Relaxed) < 64 {
let trace = std::backtrace::Backtrace::force_capture().to_string();
let frames: Vec<&str> = trace
.lines()
.filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::"))
.take(5)
.collect();
eprintln!("PREFILL-ALLOC {what} bytes={bytes} at {}", frames.join(" <- "));
}
}
+14
View File
@@ -602,6 +602,7 @@ mod enabled {
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
type StreamSynchronizeRaw = unsafe extern "C" fn(*mut c_void) -> CuResult;
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
type MemGetInfoV2 = unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult;
@@ -655,6 +656,7 @@ mod enabled {
push: ContextPushCurrentV2,
pop: ContextPopCurrentV2,
synchronize: ContextSynchronize,
stream_synchronize: StreamSynchronizeRaw,
allocate: MemAllocV2,
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
@@ -1473,6 +1475,7 @@ mod enabled {
push: symbol!(library, c"cuCtxPushCurrent_v2", ContextPushCurrentV2),
pop: symbol!(library, c"cuCtxPopCurrent_v2", ContextPopCurrentV2),
synchronize: symbol!(library, c"cuCtxSynchronize", ContextSynchronize),
stream_synchronize: symbol!(library, c"cuStreamSynchronize", StreamSynchronizeRaw),
allocate: symbol!(library, c"cuMemAlloc_v2", MemAllocV2),
free: symbol!(library, c"cuMemFree_v2", MemFreeV2),
copy_from: symbol!(library, c"cuMemcpyHtoD_v2", MemcpyHtoDV2),
@@ -1954,10 +1957,20 @@ mod enabled {
Ok(ContextHandle(context as usize))
}
pub(crate) fn synchronize(&self) -> Result<()> {
if crate::compute_drain::background() != 0 {
// a chunk expert stream is in flight: queue a few more of its copies behind the work being
// drained, then wait for the compute streams only (never for the copy stream)
crate::prefetch_point();
// SAFETY: caller guard makes its live owned context current; registered live streams.
return crate::compute_drain::drain(|s| {
check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) })
});
}
// SAFETY: caller guard makes its live owned context current.
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
}
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
crate::compute_drain::note_alloc("cuMemAlloc", bytes);
let mut ptr = 0;
// SAFETY: current-context guard; nonzero, bounded size validated
// before mutation; valid u64 CUdeviceptr output on Linux64.
@@ -1968,6 +1981,7 @@ mod enabled {
Ok(BufferHandle(ptr))
}
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
crate::compute_drain::note_alloc("cuMemFree", 0);
// SAFETY: uniquely owned allocation, owner context is current.
// Poisoned/uncertain contexts never enter this operation.
check("cuMemFree_v2", unsafe { (self.free)(buffer.0) })
@@ -514,10 +514,6 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
.api
.copy_from(hin, &history_bytes)
.and_then(|()| context.driver.api.synchronize());
// the batch below runs without a drain until its end: next-MoE expert copies can run under it
if operation.is_ok() {
crate::prefetch_point();
}
if timed {
crate::command_profile::add("gdn", 0, "history upload", started.elapsed());
}
@@ -567,7 +563,6 @@ 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());
}
+2 -1
View File
@@ -29,6 +29,7 @@ use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc};
#[allow(unsafe_code)]
mod ffi;
mod compute_drain;
#[allow(unsafe_code)]
mod original_gpu_schedule;
pub use original_gpu_schedule::{
@@ -64,7 +65,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(crate) use mmq::resident::original_group::prefetch_point;
pub use mmq::resident::{
FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace,
};
@@ -2,18 +2,15 @@
//! 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.
//! The copies are enqueued on the calling thread (the copy stream waits device-side for a slot's `used` event, so
//! queueing never blocks the host). While the stream is active the compute path's drains are stream-scoped
//! (`compute_drain`: they wait for the legacy default stream and the compute streams, never for the copy stream),
//! and every such drain first tops the copy queue up by `LELEKA_PREFILL_TOPUP` (48) entries (`prefetch_point`,
//! called by `Api::synchronize`), so the next layers' experts arrive under the mixers' kernels. 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.
//! `LELEKA_PREFILL_COPY_STATS=1` (with LELEKA_BRINGUP_TRACE): per-copy event timing, one PREFILL-COPY line per chunk.
use crate::ffi::BufferHandle;
use crate::ffi::original_stager::Api;
use crate::{Error, Result};
@@ -28,6 +25,14 @@ pub(super) struct Entry {
/// gate/up/down host ranges (page-locked bank), copied back to back into the slot
pub(super) pieces: [(usize, usize); 3],
}
/// LELEKA_PREFILL_COPY_STATS: a timing event before every entry's copies (after its slot wait) and the entry's
/// `copied` event (created with timestamps): their gap is the entry's pure DMA time.
struct Stats {
starts: Vec<usize>,
sampled_ms: Cell<f64>,
sampled_bytes: Cell<u64>,
sampled: Cell<u64>,
}
struct Core {
api: Api,
entries: Vec<Entry>,
@@ -41,10 +46,15 @@ struct Core {
consumed: Cell<usize>,
next_layer: Cell<u8>,
failed: Cell<bool>,
/// measured length of the last prefetch window (point to closing drain) and the bytes/s estimate
window: Cell<Duration>,
window_start: Cell<Option<Instant>>,
bytes_per_second: f64,
topup: usize,
/// LELEKA_PREFILL_AHEAD: most entries queued beyond the consumed ones (default: the whole ring)
ahead: usize,
calls: Cell<u64>,
bytes: Cell<u64>,
issue_time: Cell<Duration>,
stats: Option<Stats>,
/// LELEKA_PREFILL_STREAM_JITTER=seed (race hunt): pseudo-random host delays between the copies' enqueues
jitter: Cell<u64>,
}
impl Core {
fn ring(&self) -> usize {
@@ -58,7 +68,7 @@ impl Core {
if self.failed.get() {
return Err(Error::ContextPoisoned);
}
let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring());
let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring().min(self.ahead));
while self.issued.get() < limit {
let k = self.issued.get();
let result = self.issue(k);
@@ -70,13 +80,47 @@ impl Core {
}
Ok(())
}
fn entry_bytes(&self, k: usize) -> u64 {
self.entries[k].pieces.iter().map(|p| p.1 as u64).sum()
}
/// Fold entry `k`'s DMA time into the sample when its events completed.
fn harvest(&self, k: usize, wait: bool) {
let Some(stats) = &self.stats else { return };
let slot = k % self.ring();
let done = if wait {
self.api.event_sync(self.copied[slot]).is_ok()
} else {
self.api.event_query(self.copied[slot]).unwrap_or(false)
};
if done && let Ok(ms) = self.api.event_elapsed_ms(stats.starts[slot], self.copied[slot]) {
stats.sampled_ms.set(stats.sampled_ms.get() + f64::from(ms));
stats.sampled_bytes.set(stats.sampled_bytes.get() + self.entry_bytes(k));
stats.sampled.set(stats.sampled.get() + 1);
}
}
fn issue(&self, k: usize) -> Result<()> {
let jitter = self.jitter.get();
if jitter != 0 {
let mut x = jitter;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.jitter.set(x);
if x % 5 == 0 {
std::thread::sleep(Duration::from_micros(x >> 8 & 0x3ff));
}
}
let started = Instant::now();
let entry = self.entries[k];
let slot = k % self.ring();
if k >= self.ring() {
self.harvest(k - self.ring(), false);
// the slot's previous entry was gathered (or released) on the compute stream
self.api.wait(self.copy, self.used[slot])?;
}
if let Some(stats) = &self.stats {
self.api.record(stats.starts[slot], self.copy)?;
}
let (target, capacity) = self.targets[slot];
let mut offset = 0usize;
for (address, length) in entry.pieces {
@@ -85,9 +129,13 @@ impl Core {
return Err(Error::InvalidSize);
}
self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?;
self.calls.set(self.calls.get() + 1);
offset = end;
}
self.api.record(self.copied[slot], self.copy)
self.bytes.set(self.bytes.get() + offset as u64);
let recorded = self.api.record(self.copied[slot], self.copy);
self.issue_time.set(self.issue_time.get() + started.elapsed());
recorded
}
}
@@ -96,42 +144,13 @@ thread_local! {
static ACTIVE: RefCell<Option<Rc<Core>>> = 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.
/// Called by `Api::synchronize` while a chunk stream is active, right before a compute drain waits: queue the
/// next `topup` entries (never past the ring: entry k - ring must be consumed first). The caller's Context is
/// current. No-op without an active stream.
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());
}
let _ = core.issue_until(core.issued.get() + core.topup);
});
}
@@ -141,7 +160,8 @@ pub(super) struct ChunkStream {
}
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).
/// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context);
/// `starts` the per-slot timing events of LELEKA_PREFILL_COPY_STATS (empty without it).
#[allow(clippy::too_many_arguments)]
pub(super) fn start(
api: Api,
@@ -151,9 +171,12 @@ impl ChunkStream {
targets: Vec<(BufferHandle, usize)>,
copied: Vec<usize>,
used: Vec<usize>,
bytes_per_second: f64,
starts: Vec<usize>,
topup: usize,
) -> Result<Self> {
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 {
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48
|| !(starts.is_empty() || starts.len() == targets.len())
{
return Err(Error::InvalidProjectionShape);
}
if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert))
@@ -181,9 +204,18 @@ impl ChunkStream {
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),
topup: topup.max(1),
ahead: std::env::var("LELEKA_PREFILL_AHEAD").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(usize::MAX).max(1),
calls: Cell::new(0),
bytes: Cell::new(0),
issue_time: Cell::new(Duration::ZERO),
jitter: Cell::new(std::env::var("LELEKA_PREFILL_STREAM_JITTER").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0)),
stats: (!starts.is_empty()).then(|| Stats {
starts,
sampled_ms: Cell::new(0.0),
sampled_bytes: Cell::new(0),
sampled: Cell::new(0),
}),
});
ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core)));
Ok(Self { core })
@@ -251,6 +283,8 @@ impl ChunkStream {
let end = self.core.layer_end(layer);
self.release_until(end, compute)?;
self.core.next_layer.set(layer + 1);
// the next layer's first entries go into the freed slots now (device-side waits on `used`)
self.core.issue_until(self.core.issued.get() + self.core.topup)?;
Ok(())
}
/// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream.
@@ -263,6 +297,27 @@ impl ChunkStream {
});
if self.core.failed.get() { Err(Error::ContextPoisoned) } else { Ok(()) }
}
/// After the copy stream drained: one PREFILL-COPY line (entries, calls, bytes, DMA GB/s of the sampled entries).
pub(super) fn report(&self, stream_ms: f64) {
let core = &self.core;
let issued = core.issued.get();
for k in issued.saturating_sub(core.ring())..issued {
core.harvest(k, true);
}
let (gbps, n) = core.stats.as_ref().map_or((0.0, 0), |s| {
let rate = if s.sampled_ms.get() > 0.0 { s.sampled_bytes.get() as f64 / (s.sampled_ms.get() * 1e6) } else { 0.0 };
(rate, s.sampled.get())
});
let calls = core.calls.get();
let bytes = core.bytes.get();
crate::bringup_trace!(
"PREFILL-COPY entries={issued} calls={calls} bytes={bytes} avg_call={} dma_gbps={gbps:.1} sampled={n} issue_ms={:.1} stream_ms={stream_ms:.1} avg_gbps_over_stream={:.1} scoped_drains={}",
bytes.checked_div(calls).unwrap_or(0),
core.issue_time.get().as_secs_f64() * 1e3,
if stream_ms > 0.0 { bytes as f64 / (stream_ms * 1e6) } else { 0.0 },
crate::compute_drain::take_drains()
);
}
pub(super) fn api(&self) -> &Api {
&self.core.api
}
+1 -1
View File
@@ -1435,7 +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};
pub(crate) use copy_ring::prefetch_point;
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
+53 -15
View File
@@ -22,12 +22,10 @@ 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};
pub(crate) use chunk_stream::prefetch_point;
#[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 {
@@ -106,6 +104,10 @@ pub struct OriginalMmqCopySchedule<'ctx> {
stream: Option<ChunkStream>,
stream_bank: Option<Rc<crate::MappedExpertBank<'ctx>>>,
stream_events: Vec<usize>,
stream_started: Option<std::time::Instant>,
/// The per-layer status words, kept between layers: a cuMemFree per layer would synchronize the whole device
/// (the copy stream included) and wait for every queued expert copy. `(bytes, buffer)`.
status_pool: Option<(usize, DeviceBuffer<'ctx>)>,
}
impl Context<'_> {
pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result<OriginalMmqCopySchedule<'_>> {
@@ -129,6 +131,8 @@ impl Context<'_> {
stream: None,
stream_bank: None,
stream_events: Vec::new(),
stream_started: None,
status_pool: None,
};
let result = (|| {
owner
@@ -258,10 +262,13 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
let api = StagerApi::load()?;
let guard = self.context.enter()?;
let mut events = Vec::new();
let stats = std::env::var_os("LELEKA_PREFILL_COPY_STATS").is_some_and(|v| v == "1");
let per_slot = if stats { 3 } else { 2 };
let created = (|| -> Result<()> {
events.try_reserve_exact(2 * ring).map_err(|_| Error::HostAllocation)?;
for _ in 0..2 * ring {
events.push(api.event_create()?);
events.try_reserve_exact(per_slot * ring).map_err(|_| Error::HostAllocation)?;
for i in 0..per_slot * ring {
// with the statistics on, `copied` (first block) and `start` (third block) carry timestamps
events.push(if stats && (i < ring || i >= 2 * ring) { api.event_create_timing()? } else { api.event_create()? });
}
Ok(())
})();
@@ -274,12 +281,18 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
let _ = guard.finish();
return Err(primary);
}
let (copied, used) = (events[..ring].to_vec(), events[ring..].to_vec());
let (copied, used) = (events[..ring].to_vec(), events[ring..2 * ring].to_vec());
let starts = events[2 * ring..].to_vec();
let topup = std::env::var("LELEKA_PREFILL_TOPUP").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(48);
let _ = bytes_per_second;
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) {
match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup) {
Ok(stream) => {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
self.stream_started = Some(std::time::Instant::now());
self.stream = Some(stream);
self.stream_bank = Some(Rc::clone(bank));
self.stream_events = events;
@@ -305,6 +318,11 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
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);
// drains are context-wide again (the copy stream is idle or the schedule is failed)
crate::compute_drain::set_background(0);
if copy.is_ok() && compute.is_ok() {
stream.report(self.stream_started.take().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3));
}
drop(stream);
let drained = combine(copy, compute);
let mut result = combine(stopped, drained);
@@ -403,6 +421,9 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
if let Some(s) = self.compute.take() {
result = combine(result, s.close());
}
if let Some((_, status)) = self.status_pool.take() {
result = combine(result, status.release());
}
if result.is_err() {
self.failed = true;
if let Some(api) = self.api.take() {
@@ -643,7 +664,14 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
{
return Err(Error::BudgetExceeded);
}
owner.status = Some(context.allocate(charge)?);
owner.status = match owner.schedule.status_pool.take() {
Some((bytes, buffer)) if bytes == charge => Some(buffer),
Some((_, other)) => {
other.release()?;
Some(context.allocate(charge)?)
}
None => Some(context.allocate(charge)?),
};
// The old input quantization/metadata upload used default stream.
// Admit that dependency once before starting nonblocking producers.
context.synchronize()?;
@@ -950,11 +978,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
return Ok(());
}
// Do not short-circuit the second producer on a first drain failure.
let copy = self
.schedule
.copy
.as_ref()
.map_or(Ok(()), OriginalGpuStream::synchronize);
// With the chunk's expert stream active the copy stream carries the NEXT layers' copies: this layer's own
// were waited for on the compute stream (the `copied` events) and its gathers are drained below.
let copy = if self.schedule.stream.is_some() {
Ok(())
} else {
self.schedule.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize)
};
let compute = self
.schedule
.compute
@@ -1011,7 +1041,15 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
self.bank.take();
}
if let Some(status) = self.status.take() {
result = combine(result, status.release());
if result.is_ok() && self.drained && !self.context.is_poisoned() && !self.schedule.closed {
// kept for the next layer (the words are zeroed on the device before each group's use)
let charge = status.bytes;
if let Some((_, old)) = self.schedule.status_pool.replace((charge, status)) {
result = combine(result, old.release());
}
} else {
result = combine(result, status.release());
}
}
result
}
@@ -12,6 +12,7 @@ type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32;
type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32;
type Copy = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32;
type Pop = unsafe extern "C" fn(*mut Handle) -> i32;
type Elapsed = unsafe extern "C" fn(*mut f32, Handle, Handle) -> i32;
fn check(name: &'static str, code: i32) -> Result<()> {
if code == 0 {
Ok(())
@@ -37,6 +38,7 @@ pub(crate) struct Api {
copy: Copy,
push: HandleCall,
pop: Pop,
event_elapsed: Elapsed,
}
impl Drop for Api {
fn drop(&mut self) {
@@ -118,6 +120,7 @@ impl Api {
copy: sym!(c"cuMemcpyHtoDAsync_v2", Copy),
push: sym!(c"cuCtxPushCurrent_v2", HandleCall),
pop: sym!(c"cuCtxPopCurrent_v2", Pop),
event_elapsed: sym!(c"cuEventElapsedTime", Elapsed),
};
std::mem::forget(opening);
Ok(result)
@@ -175,6 +178,18 @@ impl Api {
Ok(p as usize)
}
}
/// A timing event (LELEKA_PREFILL_COPY_STATS): the same as `event_create` with timestamps enabled.
pub(crate) fn event_create_timing(&self) -> Result<usize> {
let mut p = std::ptr::null_mut();
check("cuEventCreate", unsafe { (self.event_create)(&mut p, 0) })?;
if p.is_null() { Err(Error::InvalidDriverValue("cuEventCreate")) } else { Ok(p as usize) }
}
/// Milliseconds between two completed timing events.
pub(crate) fn event_elapsed_ms(&self, start: usize, end: usize) -> Result<f32> {
let mut ms = 0f32;
check("cuEventElapsedTime", unsafe { (self.event_elapsed)(&mut ms, start as Handle, end as Handle) })?;
Ok(ms)
}
pub(crate) fn event_destroy(&self, event: usize) -> Result<()> {
check("cuEventDestroy_v2", unsafe {
(self.event_destroy)(event as Handle)
@@ -152,9 +152,11 @@ mod platform {
if s.is_null() {
return Err(Error::InvalidDriverValue("cuStreamCreate"));
}
crate::compute_drain::register(s as usize);
Ok(s as usize)
}
pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> {
crate::compute_drain::unregister(s);
check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) })
}
pub(crate) fn stream_sync(&self, s: usize) -> Result<()> {
+2
View File
@@ -168,6 +168,7 @@ mod enabled {
return Err(Error::InvalidDriverValue("cuStreamCreate"));
}
owner.stream = Some(stream as usize);
crate::compute_drain::register(stream as usize);
let mut h = std::ptr::null_mut();
// SAFETY: current owner Context, valid writable output.
check("cublasCreate_v2", unsafe { create(&mut h) })?;
@@ -395,6 +396,7 @@ mod enabled {
});
}
if let Some(s) = self.stream.take() {
crate::compute_drain::unregister(s);
// SAFETY: actual created stream, no undisclosed outstanding commands.
result = combine(
result,
@@ -372,7 +372,15 @@ fn original_serve_long_context_streamed_kv_smoke() {
std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display()));
eprintln!("long-smoke prompt ids -> {}", path.display());
}
// LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process)
let stream_seq: Vec<i8> = env::var("LELEKA_PREFILL_STREAM_SEQ")
.map(|v| v.split(',').filter_map(|t| t.trim().parse().ok()).collect()).unwrap_or_default();
for pass in 0..repeat {
if !stream_seq.is_empty() {
let v = stream_seq[pass % stream_seq.len()];
crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE.store(v, std::sync::atomic::Ordering::Relaxed);
eprintln!("long-smoke pass={pass} stream_override={v}");
}
let started = std::time::Instant::now();
let mut tokens = Vec::new();
let outcome = stack
@@ -16,17 +16,20 @@ use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage};
/// 1,410 ms), so the per-layer copy ring stays the default.
/// `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<Option<(usize, f64)>> = std::sync::OnceLock::new();
*SETTINGS.get_or_init(|| {
if !std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "1") {
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::<f64>().ok())
.filter(|g| g.is_finite() && *g > 1.0).unwrap_or(45.0);
Some((number("STRATA_PREFILL_STREAM_MIN", 1024), gbps * 1e9))
})
use std::sync::atomic::Ordering;
let on = match PREFILL_STREAM_OVERRIDE.load(Ordering::Relaxed) {
0 => false,
1 => true,
_ => std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "1"),
};
if !on {
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), 45e9))
}
/// Test harness switch for in-process paired A/B (`LELEKA_PREFILL_STREAM_SEQ`): -1 = the environment, 0 off, 1 on.
pub static PREFILL_STREAM_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
fn native_format(key: MoeWeightDescriptor) -> Result<GdnNativeFormat> {
match key.raw_kind {
@@ -35,6 +35,8 @@ mod cache_strata_adaptive;
#[path = "cache_original_prompt.rs"]
mod cache_original_prompt;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub(crate) use cache_original_prompt::PREFILL_STREAM_OVERRIDE;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[path = "cache_original_verify.rs"]
mod cache_original_verify;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]