perf(prefill): defer cuMemFree while the chunk stream is in flight, pool ring status, blocking-call timing

Job 950 showed the expert stream moving the wait into moe.finish and GR inject
(cuMemFree of per-layer scratch synchronizes the device and waits for every queued
copy). Frees are queued on the Context during the stream and run at its end
(or past LELEKA_PREFILL_DEFER_FREE_MIB); the ring status buffer is fixed-size and
pooled; PREFILL-COPY reports the host-blocking calls (alloc/free/h2d/d2h/memset/drain).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-17 07:09:21 +02:00
co-authored by Claude Sonnet 5.5
parent 4a03e73a96
commit 73e2fdc038
5 changed files with 88 additions and 22 deletions
+29 -6
View File
@@ -12,11 +12,7 @@ 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 {
@@ -41,7 +37,6 @@ pub(crate) fn background() -> usize {
}
/// 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());
@@ -76,3 +71,31 @@ pub(crate) fn note_alloc(what: &str, bytes: usize) {
eprintln!("PREFILL-ALLOC {what} bytes={bytes} at {}", frames.join(" <- "));
}
}
const KINDS: usize = 6;
static BLOCK_NS: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS];
static BLOCK_N: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS];
/// Run a host-blocking driver call (0 alloc, 1 free, 2 H2D, 3 D2H, 4 memset, 5 scoped drain), timing it while a chunk
/// stream is in flight.
pub(crate) fn timed<T>(kind: usize, f: impl FnOnce() -> T) -> T {
if background() == 0 {
return f();
}
let started = std::time::Instant::now();
let out = f();
BLOCK_NS[kind].fetch_add(started.elapsed().as_nanos() as usize, Ordering::Relaxed);
BLOCK_N[kind].fetch_add(1, Ordering::Relaxed);
out
}
/// `alloc n/ms free n/ms h2d n/ms d2h n/ms memset n/ms drain n/ms` since the last call.
pub(crate) fn take_blocking_report() -> String {
let names = ["alloc", "free", "h2d", "d2h", "memset", "drain"];
(0..KINDS)
.map(|k| {
let n = BLOCK_N[k].swap(0, Ordering::Relaxed);
let ms = BLOCK_NS[k].swap(0, Ordering::Relaxed) as f64 / 1e6;
format!("{}={}/{:.1}ms", names[k], n, ms)
})
.collect::<Vec<_>>()
.join(" ")
}
+10 -10
View File
@@ -1962,9 +1962,9 @@ mod enabled {
// 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| {
return crate::compute_drain::timed(5, || 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)() })
@@ -1974,7 +1974,7 @@ mod enabled {
let mut ptr = 0;
// SAFETY: current-context guard; nonzero, bounded size validated
// before mutation; valid u64 CUdeviceptr output on Linux64.
check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) })?;
crate::compute_drain::timed(0, || check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) }))?;
if ptr == 0 {
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
}
@@ -1984,24 +1984,24 @@ mod enabled {
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) })
crate::compute_drain::timed(1, || check("cuMemFree_v2", unsafe { (self.free)(buffer.0) }))
}
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
// SAFETY: buffer owner is current, exact allocation size checked,
// and the caller owns this staging allocation. It synchronizes on
// both success/error and leaks staging on ambiguous completion, so
// the pointer stays valid even if the call retains it after return.
check("cuMemcpyHtoD_v2", unsafe {
crate::compute_drain::timed(2, || check("cuMemcpyHtoD_v2", unsafe {
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
})
}))
}
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
// SAFETY: valid owned writable staging of exactly the allocation
// size; current owner context; caller synchronizes or leaks as
// above. No borrowed output is passed directly to the driver.
check("cuMemcpyDtoH_v2", unsafe {
crate::compute_drain::timed(3, || check("cuMemcpyDtoH_v2", unsafe {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
})
}))
}
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
if destination == 0 || bytes == 0 {
@@ -2009,9 +2009,9 @@ mod enabled {
}
// SAFETY: caller owns the current-context allocation and has
// validated this exact nonzero extent before dispatch.
check("cuMemsetD8_v2", unsafe {
crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
(self.zero)(destination, 0, bytes)
})
}))
}
pub(crate) fn copy_mmq_weight(
&self,
+40
View File
@@ -420,6 +420,7 @@ impl<'driver> Device<'driver> {
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
window_modules: RefCell::new(Vec::new()),
deferred_frees: RefCell::new(Vec::new()),
})
}
}
@@ -471,6 +472,9 @@ pub struct Context<'driver> {
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
/// (the serve path assembles one per request) and unloaded with the context.
window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
}
#[derive(Clone, Copy)]
struct FixedKernel {
@@ -1030,6 +1034,37 @@ impl Context<'_> {
_thread: PhantomData,
})
}
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
/// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once.
fn defer_free(&self, handle: ffi::BufferHandle, bytes: usize) -> Result<()> {
let pending = {
let mut list = self.deferred_frees.borrow_mut();
list.push((handle, bytes));
list.iter().map(|b| b.1).sum::<usize>()
};
static LIMIT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
let limit = *LIMIT.get_or_init(|| {
std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(512) << 20
});
if pending > limit { self.flush_deferred_frees() } else { Ok(()) }
}
/// Free every deferred buffer (one device synchronization).
pub(crate) fn flush_deferred_frees(&self) -> Result<()> {
let list = std::mem::take(&mut *self.deferred_frees.borrow_mut());
if list.is_empty() {
return Ok(());
}
let guard = self.enter()?;
let mut result = Ok(());
for (handle, bytes) in list {
let free = self.driver.api.free(handle);
if free.is_ok() {
self.allocated.set(self.allocated.get() - bytes);
}
result = combine(result, free);
}
combine(result, guard.finish())
}
/// Read-only sticky completion fence; never resets or changes the context.
pub fn is_poisoned(&self) -> bool {
self.poisoned.get()
@@ -2366,6 +2401,10 @@ impl DeviceBuffer<'_> {
let Some(handle) = self.handle.take() else {
return Ok(());
};
if compute_drain::background() != 0 && !self.context.poisoned.get() {
// a chunk expert stream is in flight: do not synchronize the device now
return self.context.defer_free(handle, self.bytes);
}
let guard = self.context.enter()?;
let free = self.context.driver.api.free(handle);
if free.is_ok() {
@@ -2615,6 +2654,7 @@ mod tests {
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
window_modules: RefCell::new(Vec::new()),
deferred_frees: RefCell::new(Vec::new()),
};
let make = |handle| DeviceBuffer {
context: &context,
@@ -311,11 +311,11 @@ impl ChunkStream {
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={}",
"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} blocking: {}",
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()
crate::compute_drain::take_blocking_report()
);
}
pub(super) fn api(&self) -> &Api {
+7 -4
View File
@@ -318,10 +318,13 @@ 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);
let stream_ms = self.stream_started.take().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3);
// drains are context-wide again (the copy stream is idle or the schedule is failed)
crate::compute_drain::set_background(0);
let flushed = self.context.flush_deferred_frees();
let compute = combine(compute, flushed);
if copy.is_ok() && compute.is_ok() {
stream.report(self.stream_started.take().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3));
stream.report(stream_ms);
}
drop(stream);
let drained = combine(copy, compute);
@@ -665,12 +668,12 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
return Err(Error::BudgetExceeded);
}
owner.status = match owner.schedule.status_pool.take() {
Some((bytes, buffer)) if bytes == charge => Some(buffer),
Some((bytes, buffer)) if bytes >= charge => Some(buffer),
Some((_, other)) => {
other.release()?;
Some(context.allocate(charge)?)
Some(context.allocate(charge.max(512))?)
}
None => Some(context.allocate(charge)?),
None => Some(context.allocate(charge.max(512))?),
};
// The old input quantization/metadata upload used default stream.
// Admit that dependency once before starting nonblocking producers.