diff --git a/crates/cuda-driver/src/api.rs b/crates/cuda-driver/src/api.rs index 3067ce85..08a99fcb 100644 --- a/crates/cuda-driver/src/api.rs +++ b/crates/cuda-driver/src/api.rs @@ -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 { @@ -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) diff --git a/crates/cuda-driver/src/compute_drain.rs b/crates/cuda-driver/src/compute_drain.rs new file mode 100644 index 00000000..efba5040 --- /dev/null +++ b/crates/cuda-driver/src/compute_drain.rs @@ -0,0 +1,203 @@ +//! 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> = Mutex::new(Vec::new()); +static BACKGROUND: AtomicUsize = AtomicUsize::new(0); + + +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) +} +/// Every registered stream except `except` and the chunk's background copy stream, plus the legacy default stream (0): the +/// streams whose later work must be ordered after a stream's deferred-guard run (deferred_status.rs). +pub(crate) fn streams_except(except: usize) -> Vec { + let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner()); + let background = background(); + std::iter::once(0usize).chain(all.iter().copied().filter(|&s| s != except && s != background)).collect() +} +/// Drain the legacy default stream and every registered stream but the background one. +pub(crate) fn drain(sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> { + let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner()); + drain_set(&all, background(), sync) +} +/// The legacy default stream first, then each stream of `all` except `background`; the first error wins but every +/// stream is still waited for. +fn drain_set(all: &[usize], background: usize, mut sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> { + let mut result = sync(0); + for &stream in all { + 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 = 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(" <- ")); + } +} + +const KINDS: usize = 8; +static SHOWN: AtomicUsize = AtomicUsize::new(0); +static SITES: Mutex> = Mutex::new(std::collections::BTreeMap::new()); +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, 6 D2D, 7 other stream/event sync), timing it while a chunk +/// stream is in flight. +pub(crate) fn timed(kind: usize, f: impl FnOnce() -> T) -> T { + if background() == 0 { + return f(); + } + let started = std::time::Instant::now(); + let out = f(); + let took = started.elapsed(); + BLOCK_NS[kind].fetch_add(took.as_nanos() as usize, Ordering::Relaxed); + BLOCK_N[kind].fetch_add(1, Ordering::Relaxed); + // LELEKA_PREFILL_STALL_TRACE=1: every blocking call over 2 ms (first 40 per chunk) with its callers, and a + // per-call-site histogram of the host-to-device / device-to-host / memset / device-to-device calls + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if matches!(kind, 2 | 3 | 4 | 6) && *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) { + 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::")) + .skip(1) + .take(4) + .collect(); + let key = format!("kind={kind} {}", frames.join(" <- ")); + let mut sites = SITES.lock().unwrap_or_else(|e| e.into_inner()); + let entry = sites.entry(key).or_insert((0, 0)); + entry.0 += 1; + entry.1 += took.as_nanos() as usize; + } + if took.as_micros() > 2000 + && *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) + && SHOWN.fetch_add(1, Ordering::Relaxed) < 40 + { + 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::")) + .skip(1) + .take(6) + .collect(); + eprintln!("PREFILL-STALL kind={kind} ms={:.1} at {}", took.as_secs_f64() * 1e3, frames.join(" <- ")); + } + 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 { + SHOWN.store(0, Ordering::Relaxed); + let sites = std::mem::take(&mut *SITES.lock().unwrap_or_else(|e| e.into_inner())); + let mut ranked: Vec<_> = sites.into_iter().collect(); + ranked.sort_by_key(|(_, v)| std::cmp::Reverse(v.0)); + for (site, (n, ns)) in ranked.iter().take(16) { + eprintln!("PREFILL-SITE n={n} ms={:.1} {site}", *ns as f64 / 1e6); + } + let names = ["alloc", "free", "h2d", "d2h", "memset", "drain", "d2d", "streamsync"]; + (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::>() + .join(" ") +} + +static ZERO_MEMSET: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); +/// Harness switch (`LELEKA_PREFILL_STREAM_SEQ` bit 1): -1 = default (on; `LELEKA_PREFILL_ZERO_MEMSET=0` disables). +pub fn set_zero_memset(on: bool) { + ZERO_MEMSET.store(i8::from(on), Ordering::Relaxed); +} +/// Whether all-zero host-to-device uploads become device memsets while a chunk stream is in flight (the upload is a +/// copy-engine transfer that waits behind the expert copies; the memset is not). +pub(crate) fn zero_memset() -> bool { + static ENV: std::sync::OnceLock = std::sync::OnceLock::new(); + background() != 0 + && match ZERO_MEMSET.load(Ordering::Relaxed) { + 0 => false, + 1 => true, + _ => *ENV.get_or_init(|| std::env::var_os("LELEKA_PREFILL_ZERO_MEMSET").is_none_or(|v| v != "0")), + } +} + +static DEPTH_OVERRIDE: AtomicUsize = AtomicUsize::new(0); +/// Harness switch (`LELEKA_PREFILL_STREAM_SEQ` `value:depth`): issuer-thread depth for the next chunks (0 = env). +pub fn set_issue_depth(depth: usize) { + DEPTH_OVERRIDE.store(depth, Ordering::Relaxed); +} +pub(crate) fn issue_depth_override() -> usize { + DEPTH_OVERRIDE.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn drain_waits_for_default_and_compute_streams_but_not_the_background_one() { + let mut seen = Vec::new(); + drain_set(&[11, 12, 13], 12, |s| { + seen.push(s); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, [0, 11, 13]); + } + #[test] + fn drain_reports_the_first_error_after_waiting_for_every_stream() { + let mut seen = Vec::new(); + let result = drain_set(&[5, 6, 7], 0, |s| { + seen.push(s); + if s == 6 { Err(crate::Error::ContextPoisoned) } else { Ok(()) } + }); + assert!(matches!(result, Err(crate::Error::ContextPoisoned))); + assert_eq!(seen, [0, 5, 6, 7]); + } +} diff --git a/crates/cuda-driver/src/deferred_status.rs b/crates/cuda-driver/src/deferred_status.rs new file mode 100644 index 00000000..a63de325 --- /dev/null +++ b/crates/cuda-driver/src/deferred_status.rs @@ -0,0 +1,246 @@ +//! `LELEKA_PREFILL_DEFER_GUARDS=1` (EXPERIMENTAL, claude/schedule): deferred guard status for the prompt producer's `run`. +//! +//! Today every `OriginalPromptDevice::run` (the hyper-connection reads and injections: about 560 per 8192-token chunk) zeroes its status +//! words with a synchronous upload, runs its kernels, drains the whole context, reads the words back and refuses on the first set one: +//! three host synchronizations and two transfers per call, each one a hole in the GPU queue and a latecomer in the H2D copy FIFO. +//! Deferred mode keeps the same words, the same kernels and the same refusal, but moves the *host's look* at them: +//! 1. the words are zeroed by a stream-ordered memset (no upload, no wait); +//! 2. after the kernels the words are copied by a stream-ordered DtoH into a pinned slot and an event is recorded behind the copy; +//! 3. every other stream (and the legacy default stream) is ordered after that event on the device, which replaces the context +//! drain that used to order the next producer after this one (the host does not wait); +//! 4. the slot is evaluated by `resolve`, in order, with the unchanged evaluation (`evaluate`): when the ring of 64 slots is full, and +//! at the points where results leave the device (final-row reads, preview/finish of the phase, row-lease teardown). +//! A failing slot poisons the context exactly like the immediate check does (every later driver call refuses with `ContextPoisoned`) and +//! returns the same error class and label as the immediate path would have, only later: work enqueued after the failing run has executed +//! on its output, but nothing of it is observable (no row is read back, no phase is sealed, no session state is published) before `resolve`. +use crate::Error; +use crate::Result; + +/// The evaluation of one status readback, shared by the immediate and the deferred path: any word above 1 is an unknown status; then +/// the first set word in the producer's order (`stride == 10`: PLE, row first then stage order; otherwise GR, stage first over all rows). +pub(crate) fn evaluate(readback: &[u8], stride: usize, order: &[usize], labels: &[&'static str]) -> Result<()> { + for word in readback.as_chunks::<4>().0 { + if u32::from_le_bytes(*word) > 1 { + return Err(Error::InvalidDriverValue("Original prompt status")); + } + } + let word_at = |row: &[u8], stage: usize| -> Result { + Ok(u32::from_le_bytes(row[stage * 4..stage * 4 + 4].try_into().map_err(|_| Error::InvalidQwenShape)?)) + }; + if stride == 10 { + for row in readback.chunks_exact(stride * 4) { + for &stage in order { + if word_at(row, stage)? != 0 { + return Err(Error::NonFiniteMmqOutput(labels[stage])); + } + } + } + } else { + for &stage in order { + for row in readback.chunks_exact(stride * 4) { + if word_at(row, stage)? != 0 { + return Err(Error::NonFiniteMmqOutput(labels[stage])); + } + } + } + } + Ok(()) +} + +/// Read once: the switch. Off by default (experimental mode). +pub(crate) fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_PREFILL_DEFER_GUARDS").is_ok_and(|v| v == "1")) +} + +#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +mod device { + use super::evaluate; + use crate::ffi::{BufferHandle, deferred_status::{Api, HostBuffer}}; + use crate::{Context, Error, Result}; + use std::cell::RefCell; + use std::collections::VecDeque; + + const SLOTS: usize = 64; + + struct Check { + slot: usize, + bytes: usize, + stride: usize, + order: Vec, + labels: Vec<&'static str>, + } + struct Slot { + host: HostBuffer, + event: usize, + } + struct State { + api: Api, + context: usize, + slots: Vec, + live: VecDeque, + head: usize, + } + thread_local! { + // The contexts are single-thread owners (Rc), so one state per thread, bound to the context that created it. + static STATE: RefCell> = const { RefCell::new(None) }; + } + + fn open(context: &Context<'_>, slot_bytes: usize) -> Result { + let api = Api::load()?; + let mut slots = Vec::with_capacity(SLOTS); + for _ in 0..SLOTS { + slots.push(Slot { host: api.host_buffer(slot_bytes)?, event: api.event()? }); + } + Ok(State { api, context: std::ptr::from_ref(context) as usize, slots, live: VecDeque::new(), head: 0 }) + } + + /// Wait for the oldest live check and evaluate it. The first failure poisons the context; every other live copy is still waited for. + fn resolve_oldest(context: &Context<'_>, st: &mut State) -> Result<()> { + let Some(check) = st.live.pop_front() else { return Ok(()) }; + let slot = &st.slots[check.slot]; + st.api.wait_host(slot.event)?; + let verdict = slot.host.view(check.bytes).and_then(|b| evaluate(b, check.stride, &check.order, &check.labels)); + if verdict.is_err() { + context.poisoned.set(true); + while let Some(rest) = st.live.pop_front() { + let _ = st.api.wait_host(st.slots[rest.slot].event); + } + } + verdict + } + + /// Step 1 of a deferred run: zero the status words, stream ordered. + pub(crate) fn begin(context: &Context<'_>, status: BufferHandle, bytes: usize, stream: usize, slot_bytes: usize) -> Result<()> { + STATE.with(|cell| { + let mut guard = cell.borrow_mut(); + if guard.as_ref().is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) { + if guard.as_ref().is_some_and(|s| !s.live.is_empty()) { + return Err(Error::ContextMismatch); + } + *guard = None; + } + if guard.is_none() { + *guard = Some(open(context, slot_bytes.max(bytes))?); + } + let st = guard.as_mut().ok_or(Error::ContextPoisoned)?; + st.api.zero_async(status, bytes, stream) + }) + } + + /// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, remember the check. + pub(crate) fn finish( + context: &Context<'_>, + status: BufferHandle, + bytes: usize, + stream: usize, + stride: usize, + order: &[usize], + labels: &[&'static str], + ) -> Result<()> { + STATE.with(|cell| { + let mut guard = cell.borrow_mut(); + let st = guard.as_mut().ok_or(Error::ContextPoisoned)?; + if st.live.len() == SLOTS { + resolve_oldest(context, st)?; + } + let slot_index = st.head % SLOTS; + st.head += 1; + let slot = &st.slots[slot_index]; + st.api.read_async(&slot.host, status, bytes, stream)?; + st.api.record(slot.event, stream)?; + for other in crate::compute_drain::streams_except(stream) { + st.api.wait_stream(other, slot.event)?; + } + st.live.push_back(Check { slot: slot_index, bytes, stride, order: order.to_vec(), labels: labels.to_vec() }); + Ok(()) + }) + } + + /// Evaluate everything outstanding, in order. Enters the context itself. + pub(crate) fn resolve(context: &Context<'_>) -> Result<()> { + STATE.with(|cell| { + let mut guard = cell.borrow_mut(); + let Some(st) = guard.as_mut() else { return Ok(()) }; + if st.live.is_empty() { + return Ok(()); + } + if st.context != std::ptr::from_ref(context) as usize { + return Err(Error::ContextMismatch); + } + let entered = context.enter()?; + let mut result = Ok(()); + while !st.live.is_empty() { + let r = resolve_oldest(context, st); + if result.is_ok() { + result = r; + } + } + let popped = entered.finish(); + result.and(popped.map(|_| ())) + }) + } + + pub(crate) fn pending() -> usize { + STATE.with(|cell| cell.borrow().as_ref().map_or(0, |s| s.live.len())) + } +} +#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +#[allow(unused_imports)] +pub(crate) use device::{begin, finish, pending, resolve}; + +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +mod unsupported { + use crate::ffi::BufferHandle; + use crate::{Context, Error, Result}; + pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn finish(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize, _: &[usize], _: &[&'static str]) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn resolve(_: &Context<'_>) -> Result<()> { + Ok(()) + } + pub(crate) fn pending() -> usize { + 0 + } +} +#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))] +pub(crate) use unsupported::{begin, finish, pending, resolve}; + +#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +#[path = "deferred_status_gpu.rs"] +mod gpu_tests; + +#[cfg(test)] +mod tests { + use super::*; + fn words(rows: &[&[u32]]) -> Vec { + rows.iter().flat_map(|r| r.iter().flat_map(|w| w.to_le_bytes())).collect() + } + #[test] + fn evaluate_reports_the_first_set_stage_in_the_producers_order() { + let labels = ["a", "b", "c", "d"]; + // GR (stride 4): stage first over all rows; order [2, 0, 1, 3]; row 1 sets stage 0 and row 2 sets stage 2 + let b = words(&[&[0, 0, 0, 0], &[1, 0, 0, 0], &[0, 0, 1, 0]]); + assert!(matches!(evaluate(&b, 4, &[2, 0, 1, 3], &labels), Err(Error::NonFiniteMmqOutput("c")))); + assert!(matches!(evaluate(&b, 4, &[0, 1, 2, 3], &labels), Err(Error::NonFiniteMmqOutput("a")))); + assert!(evaluate(&words(&[&[0; 4], &[0; 4]]), 4, &[0, 1, 2, 3], &labels).is_ok()); + } + #[test] + fn evaluate_orders_ple_rows_before_stages_and_refuses_unknown_words() { + let labels = ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9"]; + let mut r0 = [0u32; 10]; + let mut r1 = [0u32; 10]; + r0[5] = 1; + r1[2] = 1; + let b = words(&[&r0, &r1]); + // PLE: row 0 is examined before row 1 whatever the stage order + assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::NonFiniteMmqOutput("s5")))); + // an unknown status (2) beats a set flag that comes earlier + r0[0] = 2; + let b = words(&[&r0, &r1]); + assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::InvalidDriverValue(_)))); + } +} diff --git a/crates/cuda-driver/src/deferred_status_ffi.rs b/crates/cuda-driver/src/deferred_status_ffi.rs new file mode 100644 index 00000000..7ba079a8 --- /dev/null +++ b/crates/cuda-driver/src/deferred_status_ffi.rs @@ -0,0 +1,160 @@ +//! Audited child of ffi (claude/schedule): the few asynchronous driver calls the deferred guard status block needs +//! (`LELEKA_PREFILL_DEFER_GUARDS`, see deferred_status.rs): a device memset and a device-to-host copy on a stream, pinned host +//! buffers, and events with cross-stream waits. Nothing here owns a device allocation or a stream; the host buffers are owned +//! by `HostBuffer` and freed by `Api::free_host`. Callers keep the context current (their `enter()` guard) and keep every +//! device allocation alive until the event of the copy that reads it has been waited for. +use super::BufferHandle; +use crate::{Error, Result}; +use std::ffi::{CStr, c_void}; +type Handle = *mut c_void; +type HostAlloc = unsafe extern "C" fn(*mut Handle, usize, u32) -> i32; +type HandleCall = unsafe extern "C" fn(Handle) -> i32; +type EventCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32; +type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32; +type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32; +type DtoHAsync = unsafe extern "C" fn(*mut c_void, u64, usize, Handle) -> i32; +type MemsetAsync = unsafe extern "C" fn(u64, u8, usize, Handle) -> i32; +fn check(name: &'static str, code: i32) -> Result<()> { + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code }) } +} +pub(crate) struct HostBuffer { + address: usize, + bytes: usize, +} +impl HostBuffer { + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + /// The first `len` bytes. SAFETY contract (checked by the caller's protocol, not here): the event of the last copy + /// into this buffer has completed, and no copy into it is in flight. + pub(crate) fn view(&self, len: usize) -> Result<&[u8]> { + if len > self.bytes { + return Err(Error::InvalidSize); + } + // SAFETY: `address` is a live pinned allocation of `bytes` bytes owned by `self`; `len <= bytes`; the protocol above + // guarantees no concurrent writer. + Ok(unsafe { std::slice::from_raw_parts(self.address as *const u8, len) }) + } +} +// usize is the real dlopen handle; the table holds only immutable C ABI function pointers. +pub(crate) struct Api { + library: usize, + host_alloc: HostAlloc, + host_free: HandleCall, + event_create: EventCreate, + event_destroy: HandleCall, + event_sync: HandleCall, + event_record: EventRecord, + stream_wait: StreamWait, + dtoh: DtoHAsync, + memset: MemsetAsync, +} +impl Drop for Api { + fn drop(&mut self) { + // SAFETY: the handle returned by dlopen in `load`, closed once. + unsafe { + libc::dlclose(self.library as Handle); + } + } +} +impl Api { + pub(crate) fn load() -> Result { + // SAFETY: NUL-terminated literal name. + let l = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if l.is_null() { + return Err(Error::LibraryUnavailable); + } + struct Opening(Handle); + impl Drop for Opening { + fn drop(&mut self) { + // SAFETY: dlopen handle not yet transferred to `Api`. + unsafe { + libc::dlclose(self.0); + } + } + } + let opening = Opening(l); + fn symbol(l: Handle, n: &'static CStr) -> Result { + // SAFETY: valid dlopen handle and NUL-terminated name. + let p = unsafe { libc::dlsym(l, n.as_ptr()) }; + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("deferred status symbol"))) } else { Ok(p) } + } + macro_rules! sym { + ($n:literal,$t:ty) => { + // SAFETY: the CUDA driver ABI of this symbol is exactly the declared function type. + unsafe { std::mem::transmute::(symbol(l, $n)?) } + }; + } + let result = Self { + library: l as usize, + host_alloc: sym!(c"cuMemHostAlloc", HostAlloc), + host_free: sym!(c"cuMemFreeHost", HandleCall), + event_create: sym!(c"cuEventCreate", EventCreate), + event_destroy: sym!(c"cuEventDestroy_v2", HandleCall), + event_sync: sym!(c"cuEventSynchronize", HandleCall), + event_record: sym!(c"cuEventRecord", EventRecord), + stream_wait: sym!(c"cuStreamWaitEvent", StreamWait), + dtoh: sym!(c"cuMemcpyDtoHAsync_v2", DtoHAsync), + memset: sym!(c"cuMemsetD8Async", MemsetAsync), + }; + std::mem::forget(opening); + Ok(result) + } + pub(crate) fn host_buffer(&self, bytes: usize) -> Result { + if bytes == 0 { + return Err(Error::InvalidSize); + } + let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer, nonzero size, flags 0 (plain page-locked memory). + check("cuMemHostAlloc", unsafe { (self.host_alloc)(&mut p, bytes, 0) })?; + if p.is_null() { + return Err(Error::InvalidDriverValue("cuMemHostAlloc")); + } + Ok(HostBuffer { address: p as usize, bytes }) + } + pub(crate) fn free_host(&self, buffer: HostBuffer) -> Result<()> { + // SAFETY: the address came from `host_buffer`; the caller has waited for every copy into it. + check("cuMemFreeHost", unsafe { (self.host_free)(buffer.address as Handle) }) + } + pub(crate) fn event(&self) -> Result { + let mut e = std::ptr::null_mut(); + // SAFETY: valid out pointer; flags 2 = CU_EVENT_DISABLE_TIMING. + check("cuEventCreate", unsafe { (self.event_create)(&mut e, 2) })?; + Ok(e as usize) + } + pub(crate) fn destroy_event(&self, event: usize) -> Result<()> { + // SAFETY: event created by `event`, no pending waits the caller still needs. + check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event as Handle) }) + } + pub(crate) fn record(&self, event: usize, stream: usize) -> Result<()> { + // SAFETY: live event and stream handles of the current context. + check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) }) + } + /// Block the host until the event has completed (a spin wait is the driver default). + pub(crate) fn wait_host(&self, event: usize) -> Result<()> { + // SAFETY: live event of the current context. + check("cuEventSynchronize", unsafe { (self.event_sync)(event as Handle) }) + } + /// Order `stream` (0 = the legacy default stream) after the work recorded in `event`, device side. + pub(crate) fn wait_stream(&self, stream: usize, event: usize) -> Result<()> { + // SAFETY: live event and stream (or the null stream) of the current context. + check("cuStreamWaitEvent", unsafe { (self.stream_wait)(stream as Handle, event as Handle, 0) }) + } + pub(crate) fn zero_async(&self, buffer: BufferHandle, bytes: usize, stream: usize) -> Result<()> { + if bytes == 0 { + return Err(Error::InvalidSize); + } + buffer.validate_extent(bytes)?; + // SAFETY: validated extent of a live allocation of the current context; stream handle of the same context. + check("cuMemsetD8Async", unsafe { (self.memset)(buffer.0, 0, bytes, stream as Handle) }) + } + pub(crate) fn read_async(&self, host: &HostBuffer, source: BufferHandle, bytes: usize, stream: usize) -> Result<()> { + if bytes == 0 || bytes > host.bytes { + return Err(Error::InvalidSize); + } + source.validate_extent(bytes)?; + // SAFETY: pinned destination of at least `bytes`, validated device extent, same-context stream; the caller keeps both + // alive and does not read or reuse the host buffer before the event recorded after this copy has completed. + check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) }) + } +} diff --git a/crates/cuda-driver/src/deferred_status_gpu.rs b/crates/cuda-driver/src/deferred_status_gpu.rs new file mode 100644 index 00000000..eeee1079 --- /dev/null +++ b/crates/cuda-driver/src/deferred_status_gpu.rs @@ -0,0 +1,61 @@ +//! Model-free GPU proof of the deferred guard status machinery (deferred_status.rs): the stream-ordered zero, the DtoH into the pinned +//! ring, the ordering events, the ring wrap and the poisoning, against the immediate evaluation. Enable with +//! `LELEKA_PREFILL_STAGE_GPU=yes` (`cargo test -p leleka-cuda-driver --features cuda-driver deferred -- --ignored`). +use super::*; +use crate::{Context, DeviceBuffer, Driver}; + +fn status_bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn deferred_status_equals_the_immediate_evaluation_and_poisons() { + assert_eq!(std::env::var("LELEKA_PREFILL_STAGE_GPU").ok().as_deref(), Some("yes")); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device"); + let context = device.create_context(1usize << 30).expect("context"); + let workspace = context.native_batch_workspace().expect("workspace"); + let blas = workspace.blas().expect("blas"); + let stride = 4usize; + let rows = 8usize; + let bytes = rows * stride * 4; + let order = [0usize, 1, 2, 3]; + let labels = ["n", "d", "s", "u"]; + let mut status: DeviceBuffer<'_> = context.allocate(4096).expect("alloc"); + let handle = status.handle.expect("handle"); + let put = |status: &mut DeviceBuffer<'_>, words: &[u32]| { + let mut b = status_bytes(words); + b.resize(4096, 0); + status.copy_from(&b).expect("upload"); + }; + let run = |status: &mut DeviceBuffer<'_>, words: &[u32]| { + let guard = context.enter().expect("enter"); + begin(&context, handle, bytes, blas.stream(), 4096).expect("begin"); + blas.synchronize().expect("sync"); + put(status, words); // stands in for the kernels' flag writes + finish(&context, handle, bytes, blas.stream(), stride, &order, &labels).expect("finish"); + guard.finish().expect("pop"); + }; + // clean run, the zeroing must have cleared the previous words + run(&mut status, &vec![0; rows * stride]); + run(&mut status, &vec![0; rows * stride]); + assert_eq!(pending(), 2); + resolve(&context).expect("clean runs"); + assert_eq!(pending(), 0); + // more runs than slots: the ring wraps and resolves its oldest entries by itself + for _ in 0..150 { + run(&mut status, &vec![0; rows * stride]); + } + assert!(pending() <= 64); + resolve(&context).expect("wrapped ring"); + // a set flag: same label as the immediate evaluation + let mut words = vec![0u32; rows * stride]; + words[3 * stride + 2] = 1; + run(&mut status, &words); + let expected = evaluate(&status_bytes(&words), stride, &order, &labels).unwrap_err(); + let got = resolve(&context).unwrap_err(); + assert_eq!(format!("{got:?}"), format!("{expected:?}")); + assert!(context.is_poisoned()); + assert!(matches!(context.enter(), Err(Error::ContextPoisoned))); +} diff --git a/crates/cuda-driver/src/ffi.rs b/crates/cuda-driver/src/ffi.rs index 1d6074cf..8c21d636 100644 --- a/crates/cuda-driver/src/ffi.rs +++ b/crates/cuda-driver/src/ffi.rs @@ -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,40 +1957,58 @@ 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::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)() }) } pub(crate) fn allocate(&self, bytes: usize) -> Result { + 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. - 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")); } 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) }) + 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 { + if crate::compute_drain::zero_memset() && owned.len() <= 1 << 20 && owned.iter().all(|b| *b == 0) { + // EXPERIMENT (chunk stream in flight): an all-zero upload is a device memset, which does not queue + // behind the expert copies on the host-to-device copy engine + return crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe { + (self.zero)(buffer.0, 0, owned.len()) + })); + } + 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 { @@ -1995,9 +2016,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, @@ -2011,9 +2032,9 @@ mod enabled { // SAFETY: the closed MMQ facade validates actual same-context, // disjoint whole raw source and padded destination allocations. // Owners stay borrowed until synchronize/pop, with poison on uncertainty. - check("cuMemcpyDtoD_v2", unsafe { + crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) - }) + })) } pub(crate) fn copy_moe_down( &self, @@ -2024,9 +2045,9 @@ mod enabled { // a checked ten-slot destination address and exactly10240 bytes. // Both allocations remain borrowed until sync and context restore; // ambiguous completion poisons their context before any later free. - check("cuMemcpyDtoD_v2", unsafe { + crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 10_240) - }) + })) } pub(crate) fn copy_original_down_group( &self, @@ -2039,9 +2060,9 @@ mod enabled { } // SAFETY: actual affine grouped Down producer and prompt arena // supply disjoint checked extents; both survive sync and pop. - check("cuMemcpyDtoD_v2", unsafe { + crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) - }) + })) } pub(crate) fn copy_moe_group_column( &self, @@ -2052,9 +2073,9 @@ mod enabled { // a checked 64-column destination address and exactly2560 bytes. // Both allocations remain borrowed until sync and context restore; // ambiguous completion poisons their context before any later free. - check("cuMemcpyDtoD_v2", unsafe { + crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 2560) - }) + })) } } } @@ -2747,3 +2768,11 @@ pub(crate) mod original_stager; ))] #[path = "original_file_expert_source_ffi.rs"] pub(crate) mod original_file_source; + +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +#[path = "deferred_status_ffi.rs"] +pub(crate) mod deferred_status; diff --git a/crates/cuda-driver/src/gdn_prompt_device.rs b/crates/cuda-driver/src/gdn_prompt_device.rs index 5d3ce6ca..d0fb934c 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -639,10 +639,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()); } @@ -701,7 +697,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()); } diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 0a64aeaa..b0077567 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -29,6 +29,8 @@ use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; #[allow(unsafe_code)] mod ffi; +pub mod compute_drain; +mod deferred_status; #[allow(unsafe_code)] mod original_gpu_schedule; pub use original_gpu_schedule::{ @@ -64,7 +66,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, }; @@ -420,6 +422,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 +474,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>)>>, + /// 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>, } #[derive(Clone, Copy)] struct FixedKernel { @@ -1030,6 +1036,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::() + }; + static LIMIT: std::sync::OnceLock = 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::().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 +2403,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 +2656,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, diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index a8a96ca5..f25e5eaa 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -158,6 +158,15 @@ impl Context<'_> { } } } +const PAGE: usize = 4096; +/// Extra bytes a ring slot needs to hold three page-aligned supersets next to each other: the pieces start up to one page +/// early and end up to one page late. +pub(crate) const ALIGNED_COPY_SLACK: usize = 3 * 2 * PAGE; +/// `LELEKA_PREFILL_ALIGNED_COPY=0` turns the page-aligned expert copies off (the A/B switch; default on). +pub(crate) fn aligned_copy_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_PREFILL_ALIGNED_COPY").map_or(true, |v| v != "0")) +} impl<'ctx> MappedExpertBank<'ctx> { pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool { !self.closed && std::ptr::eq(self.context, context) @@ -191,6 +200,37 @@ impl<'ctx> MappedExpertBank<'ctx> { .get(span.offset()..end) .ok_or(Error::InvalidSize) } + /// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it + /// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at + /// `expert * piece_bytes`, i.e. at arbitrary offsets; job 907/9051 and the CUPTI ledger: 36-40 GB/s unaligned, 47-50 aligned). + /// The superset is clamped to the tensor (a registered range), so it never reads outside the bank. + pub(crate) fn cache_source_aligned(&self, span: &ResidentExpertBankSpan) -> Result<(&[u8], usize)> { + let exact = self.cache_source(span)?; + let layer = match span.role() { + TensorRole::Layer { layer, .. } => layer, + _ => return Err(Error::InvalidSize), + }; + let role = match span.role() { + TensorRole::Layer { role, .. } => role, + _ => return Err(Error::InvalidSize), + }; + let n = usize::from(layer) * 3 + + match role { + LayerRole::FfnGateExperts => 0, + LayerRole::FfnUpExperts => 1, + LayerRole::FfnDownExperts => 2, + _ => return Err(Error::InvalidSize), + }; + let member = self.banks.get(n).ok_or(Error::InvalidSize)?.member.bytes(); + let base = member.as_ptr() as usize; + let (start, end) = (exact.as_ptr() as usize, exact.as_ptr() as usize + exact.len()); + let a = (start & !(PAGE - 1)).max(base); + let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); + if a > start || b < end { + return Err(Error::InvalidSize); + } + Ok((&member[a - base..b - base], start - a)) + } pub(crate) fn retained_span_handle( &self, span: &ResidentExpertBankSpan, @@ -228,6 +268,21 @@ impl<'ctx> MappedExpertBank<'ctx> { } Ok(pieces) } + /// `expert_pieces` as 4 KiB-aligned supersets clamped to the member: (address, length, lead) where `lead` is the offset of the + /// exact piece inside the superset (claude/ledger; the stream issuer copies the superset and reads the piece at `lead`). + pub(crate) fn expert_pieces_aligned(&self, layer: u8, expert: u32) -> Result<[(usize, usize, usize); 3]> { + let exact = self.expert_pieces(layer, expert)?; + let mut out = [(0usize, 0usize, 0usize); 3]; + for (role, piece) in out.iter_mut().enumerate() { + let member = self.banks[usize::from(layer) * 3 + role].member.bytes(); + let base = member.as_ptr() as usize; + let (start, end) = (exact[role].0, exact[role].0 + exact[role].1); + let a = (start & !(PAGE - 1)).max(base); + let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); + *piece = (a, b - a, start - a); + } + Ok(out) + } /// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field). pub fn pageable(&self) -> bool { self.pageable diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream.rs index f5609335..33ac482b 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream.rs @@ -2,31 +2,50 @@ //! 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 +//! Two issue modes (`LELEKA_PREFILL_ISSUER`, default `thread`): +//! * `thread` (the Original's D-5 issuer): a helper thread keeps at most `LELEKA_PREFILL_DEPTH` (2) entries +//! outstanding on the copy stream, i.e. the host-to-device copy engine stays busy while any other copy of the +//! compute path (uploads, status readbacks) waits behind at most that many entries (the engine is a FIFO: a +//! deep queue made every small transfer wait for it). The compute thread only waits for an entry's issue (it +//! spins until the helper has recorded the entry's `copied` event) before ordering its stream after it. +//! * `inline`: the calling thread queues entries at every scoped drain (`prefetch_point`, `LELEKA_PREFILL_TOPUP` +//! entries each) and at the layer ends. +//! 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). 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. The copy of entry k waits (device side) for the `used` +//! event of entry k - ring, which the compute thread has recorded before it publishes `consumed`. 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}; -use std::cell::{Cell, RefCell}; -use std::rc::Rc; +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; #[derive(Clone, Copy)] pub(super) struct Entry { pub(super) layer: u8, pub(super) expert: u32, - /// gate/up/down host ranges (page-locked bank), copied back to back into the slot + /// gate/up/down host ranges (page-locked bank) as copied: the exact pieces back to back, or their 4 KiB-aligned + /// supersets (claude/ledger, `LELEKA_PREFILL_ALIGNED_COPY`: ~15% faster DMA) pub(super) pieces: [(usize, usize); 3], + /// the exact gate/up/down host ranges (what the consumer gathers) + pub(super) exact: [(usize, usize); 3], + /// slot offset each copied piece lands at + pub(super) dest: [usize; 3], + /// slot offset each exact piece starts at (dest + the lead inside its superset) + pub(super) at: [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, + sampled_ns: AtomicU64, + sampled_bytes: AtomicU64, + sampled: AtomicU64, } struct Core { api: Api, @@ -37,14 +56,23 @@ struct Core { /// first entry of every layer (49 bounds) layer_start: [usize; 49], copy: usize, - issued: Cell, - consumed: Cell, - next_layer: Cell, - failed: Cell, - /// measured length of the last prefetch window (point to closing drain) and the bytes/s estimate - window: Cell, - window_start: Cell>, - bytes_per_second: f64, + issued: AtomicUsize, + consumed: AtomicUsize, + next_layer: AtomicUsize, + failed: AtomicBool, + stop: AtomicBool, + topup: usize, + /// LELEKA_PREFILL_AHEAD: most entries queued beyond the consumed ones (default: the whole ring) + ahead: usize, + /// issuer thread mode: entries outstanding on the copy stream (0 = inline mode) + depth: usize, + context: usize, + calls: AtomicU64, + bytes: AtomicU64, + issue_ns: AtomicU64, + stats: Option, + /// LELEKA_PREFILL_STREAM_JITTER=seed (race hunt): pseudo-random host delays between the copies' enqueues + jitter: AtomicU64, } impl Core { fn ring(&self) -> usize { @@ -53,95 +81,162 @@ impl Core { fn layer_end(&self, layer: u8) -> usize { self.layer_start[usize::from(layer) + 1] } - /// Enqueue entries until `limit` (never past the ring: entry k - ring must be consumed first). - fn issue_until(&self, limit: usize) -> Result<()> { - if self.failed.get() { + fn limit(&self, wanted: usize) -> usize { + wanted + .min(self.entries.len()) + .min(self.consumed.load(Ordering::Acquire) + self.ring().min(self.ahead)) + } + /// Inline mode: enqueue entries until `wanted` (never past the ring: entry k - ring must be consumed first). + fn issue_until(&self, wanted: usize) -> Result<()> { + if self.failed.load(Ordering::Acquire) { return Err(Error::ContextPoisoned); } - let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring()); - while self.issued.get() < limit { - let k = self.issued.get(); + let limit = self.limit(wanted); + while self.issued.load(Ordering::Relaxed) < limit { + let k = self.issued.load(Ordering::Relaxed); let result = self.issue(k); if result.is_err() { - self.failed.set(true); + self.failed.store(true, Ordering::Release); return result; } - self.issued.set(k + 1); + self.issued.store(k + 1, Ordering::Release); } Ok(()) } + /// Make sure entry `k` has been enqueued (its `copied` event recorded) before the compute stream waits for it. + fn need(&self, k: usize) -> Result<()> { + if self.depth == 0 { + return self.issue_until(k + 1); + } + let started = Instant::now(); + while self.issued.load(Ordering::Acquire) <= k { + if self.failed.load(Ordering::Acquire) || started.elapsed() > Duration::from_secs(60) { + self.failed.store(true, Ordering::Release); + return Err(Error::ContextPoisoned); + } + std::thread::yield_now(); + } + Ok(()) + } + /// Inline mode only: queue ahead up to `wanted`. + fn want(&self, wanted: usize) -> Result<()> { + if self.depth == 0 { self.issue_until(wanted) } else { 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_ns.fetch_add((f64::from(ms) * 1e6) as u64, Ordering::Relaxed); + stats.sampled_bytes.fetch_add(self.entry_bytes(k), Ordering::Relaxed); + stats.sampled.fetch_add(1, Ordering::Relaxed); + } + } fn issue(&self, k: usize) -> Result<()> { + let jitter = self.jitter.load(Ordering::Relaxed); + if jitter != 0 { + let mut x = jitter; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.jitter.store(x, Ordering::Relaxed); + 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 { - let end = offset.checked_add(length).ok_or(Error::InvalidSize)?; + let mut copied_bytes = 0usize; + for (piece, &(address, length)) in entry.pieces.iter().enumerate() { + let end = entry.dest[piece].checked_add(length).ok_or(Error::InvalidSize)?; if end > capacity { return Err(Error::InvalidSize); } - self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?; - offset = end; + self.api.copy_raw(target.checked_subspan(capacity, entry.dest[piece], length)?, address, length, self.copy)?; + self.calls.fetch_add(1, Ordering::Relaxed); + copied_bytes += length; } - self.api.record(self.copied[slot], self.copy) + self.bytes.fetch_add(copied_bytes as u64, Ordering::Relaxed); + let recorded = self.api.record(self.copied[slot], self.copy); + self.issue_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + recorded + } + /// The issuer thread: keep `depth` entries outstanding, never past the ring. + fn issuer(&self) { + if self.api.worker_enter(self.context).is_err() { + self.failed.store(true, Ordering::Release); + return; + } + let mut idle = 0u32; + while !self.stop.load(Ordering::Acquire) { + let k = self.issued.load(Ordering::Relaxed); + if k >= self.entries.len() { + break; + } + let ready = k < self.limit(k + 1) + && (k < self.depth || self.api.event_query(self.copied[(k - self.depth) % self.ring()]).unwrap_or(false)); + if !ready { + idle += 1; + if idle < 200 { + std::hint::spin_loop(); + } else { + std::thread::sleep(Duration::from_micros(20)); + } + continue; + } + idle = 0; + if self.issue(k).is_err() { + self.failed.store(true, Ordering::Release); + break; + } + self.issued.store(k + 1, Ordering::Release); + } + let _ = self.api.worker_leave(self.context); } } thread_local! { - /// The active chunk stream of this thread, for `prefetch_point` (the producers have no schedule handle). - static ACTIVE: RefCell>> = const { RefCell::new(None) }; + /// The active inline-mode chunk stream of this thread, for `prefetch_point` (the producers have no handle). + static ACTIVE: RefCell>> = const { RefCell::new(None) }; } -/// Called by a long mixer producer right after its last drain and before its sync-free kernel batch: enqueue as -/// many next-MoE entries as the previous window covered. The caller must call `prefetch_window_end` after its -/// closing drain. No-op without an active stream. The caller's Context must be current. +/// Called by `Api::synchronize` while a chunk stream is active, right before a compute drain waits: inline mode +/// queues the next `topup` entries (never past the ring). The caller's Context is current. No-op otherwise. 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.load(Ordering::Relaxed) + core.topup); }); } /// One chunk's stream and the consumer's cursor (the caller's thread only). pub(super) struct ChunkStream { - core: Rc, + core: Arc, + thread: Option>, } 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); `context` the raw + /// context token for the issuer thread. #[allow(clippy::too_many_arguments)] pub(super) fn start( api: Api, @@ -151,9 +246,13 @@ impl ChunkStream { targets: Vec<(BufferHandle, usize)>, copied: Vec, used: Vec, - bytes_per_second: f64, + starts: Vec, + topup: usize, + context: usize, ) -> Result { - 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)) @@ -169,7 +268,18 @@ impl ChunkStream { } *start = k; } - let core = Rc::new(Core { + let env_number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let threaded = std::env::var("LELEKA_PREFILL_ISSUER").map_or(true, |v| v != "inline"); + let depth = if threaded && targets.len() > 1 { + (match crate::compute_drain::issue_depth_override() { + 0 => env_number("LELEKA_PREFILL_DEPTH").unwrap_or(2), + n => n, + }) + .clamp(1, targets.len() - 1) + } else { + 0 + }; + let core = Arc::new(Core { api, entries, targets, @@ -177,26 +287,53 @@ impl ChunkStream { used, layer_start, copy, - issued: Cell::new(layer_start[usize::from(first)]), - consumed: Cell::new(layer_start[usize::from(first)]), - next_layer: Cell::new(first), - failed: Cell::new(false), - window: Cell::new(Duration::ZERO), - window_start: Cell::new(None), - bytes_per_second: bytes_per_second.max(1e9), + issued: AtomicUsize::new(layer_start[usize::from(first)]), + consumed: AtomicUsize::new(layer_start[usize::from(first)]), + next_layer: AtomicUsize::new(usize::from(first)), + failed: AtomicBool::new(false), + stop: AtomicBool::new(false), + topup: topup.max(1), + ahead: env_number("LELEKA_PREFILL_AHEAD").unwrap_or(usize::MAX).max(1), + depth, + context, + calls: AtomicU64::new(0), + bytes: AtomicU64::new(0), + issue_ns: AtomicU64::new(0), + stats: (!starts.is_empty()).then(|| Stats { + starts, + sampled_ns: AtomicU64::new(0), + sampled_bytes: AtomicU64::new(0), + sampled: AtomicU64::new(0), + }), + jitter: AtomicU64::new(env_number("LELEKA_PREFILL_STREAM_JITTER").unwrap_or(0) as u64), }); - ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core))); - Ok(Self { core }) + let thread = if depth > 0 { + let shared = Arc::clone(&core); + Some( + std::thread::Builder::new() + .name("leleka-expert-issuer".into()) + .spawn(move || shared.issuer()) + .map_err(|_| Error::HostAllocation)?, + ) + } else { + ACTIVE.with(|active| *active.borrow_mut() = Some(Arc::clone(&core))); + None + }; + Ok(Self { core, thread }) } pub(super) fn next_layer_is(&self, layer: u8) -> bool { - self.core.next_layer.get() == layer + self.core.next_layer.load(Ordering::Relaxed) == usize::from(layer) } /// Whether entry `k` copies exactly these gate/up/down byte ranges. pub(super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool { self.core.entries.get(k).is_some_and(|e| { - e.pieces.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len()) + e.exact.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len()) }) } + /// Slot offsets of entry `k`'s exact gate/up/down pieces. + pub(super) fn entry_at(&self, k: usize) -> Result<[usize; 3]> { + self.core.entries.get(k).map(|e| e.at).ok_or(Error::InvalidProjectionShape) + } /// Entry index of `expert` in `layer`, if the stream carries it (not arena-resident). pub(super) fn entry(&self, layer: u8, expert: u32) -> Option { let (a, b) = (self.core.layer_start[usize::from(layer)], self.core.layer_start[usize::from(layer) + 1]); @@ -205,14 +342,15 @@ impl ChunkStream { /// Release (record `used`, consume) every entry before `upto` in order on `compute`. fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> { let core = &self.core; - while core.consumed.get() < upto { - let k = core.consumed.get(); + while core.consumed.load(Ordering::Relaxed) < upto { + let k = core.consumed.load(Ordering::Relaxed); // its copy is queued before its release is ordered after it - core.issue_until(k + 1)?; + core.need(k)?; let slot = k % core.ring(); core.api.wait(compute, core.copied[slot])?; core.api.record(core.used[slot], compute)?; - core.consumed.set(k + 1); + // `used` is recorded before the entry counts as consumed: the copy of k + ring may then wait for it + core.consumed.store(k + 1, Ordering::Release); } Ok(()) } @@ -220,27 +358,28 @@ impl ChunkStream { pub(super) fn stage_ahead(&mut self, k: usize) -> Result<()> { let layer = self.core.entries.get(k).ok_or(Error::InvalidProjectionShape)?.layer; let end = self.core.layer_end(layer); - self.core.issue_until(end) + self.core.want(end) } /// Make entry `k` ready on `compute`: its slot and the slot's byte capacity. pub(super) fn acquire(&mut self, k: usize, compute: usize) -> Result<(BufferHandle, usize)> { self.release_until(k, compute)?; - if self.core.consumed.get() != k { + if self.core.consumed.load(Ordering::Relaxed) != k { return Err(Error::InvalidProjectionShape); } self.stage_ahead(k)?; + self.core.need(k)?; let slot = k % self.core.ring(); self.core.api.wait(compute, self.core.copied[slot])?; Ok(self.core.targets[slot]) } /// The gather of entry `k` (the cursor) is enqueued on `compute`: mark its slot used. pub(super) fn consumed(&mut self, k: usize, compute: usize) -> Result<()> { - if self.core.consumed.get() != k || self.core.issued.get() <= k { + if self.core.consumed.load(Ordering::Relaxed) != k || self.core.issued.load(Ordering::Acquire) <= k { return Err(Error::InvalidProjectionShape); } let slot = k % self.core.ring(); self.core.api.record(self.core.used[slot], compute)?; - self.core.consumed.set(k + 1); + self.core.consumed.store(k + 1, Ordering::Release); Ok(()) } /// The layer's last routed expert was gathered: release its remaining entries and move to the next layer. @@ -250,18 +389,48 @@ impl ChunkStream { } let end = self.core.layer_end(layer); self.release_until(end, compute)?; - self.core.next_layer.set(layer + 1); + self.core.next_layer.store(usize::from(layer) + 1, Ordering::Relaxed); + // inline mode: the next layer's first entries go into the freed slots now (device-side waits on `used`) + self.core.want(self.core.issued.load(Ordering::Relaxed) + self.core.topup)?; Ok(()) } - /// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream. + /// Deactivate: no producer prefetches into these slots after this; the issuer thread is stopped and joined. + /// The caller drains the copy stream. pub(super) fn stop(&mut self) -> Result<()> { + self.core.stop.store(true, Ordering::Release); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } ACTIVE.with(|active| { let mut active = active.borrow_mut(); - if active.as_ref().is_some_and(|a| Rc::ptr_eq(a, &self.core)) { + if active.as_ref().is_some_and(|a| Arc::ptr_eq(a, &self.core)) { *active = None; } }); - if self.core.failed.get() { Err(Error::ContextPoisoned) } else { Ok(()) } + if self.core.failed.load(Ordering::Acquire) { 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.load(Ordering::Acquire); + 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 ns = s.sampled_ns.load(Ordering::Relaxed); + let rate = if ns > 0 { s.sampled_bytes.load(Ordering::Relaxed) as f64 / ns as f64 } else { 0.0 }; + (rate, s.sampled.load(Ordering::Relaxed)) + }); + let calls = core.calls.load(Ordering::Relaxed); + let bytes = core.bytes.load(Ordering::Relaxed); + crate::bringup_trace!( + "PREFILL-COPY mode={} 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: {}", + if core.depth > 0 { "thread" } else { "inline" }, + bytes.checked_div(calls).unwrap_or(0), + core.issue_ns.load(Ordering::Relaxed) as f64 / 1e6, + if stream_ms > 0.0 { bytes as f64 / (stream_ms * 1e6) } else { 0.0 }, + crate::compute_drain::take_blocking_report() + ); } pub(super) fn api(&self) -> &Api { &self.core.api diff --git a/crates/cuda-driver/src/mmq_original_group.rs b/crates/cuda-driver/src/mmq_original_group.rs index 0a18702b..d977aeca 100644 --- a/crates/cuda-driver/src/mmq_original_group.rs +++ b/crates/cuda-driver/src/mmq_original_group.rs @@ -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 diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index eb60c366..a5c8bed2 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -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, stream_bank: Option>>, stream_events: Vec, + stream_started: Option, + /// 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> { @@ -129,6 +131,8 @@ impl Context<'_> { stream: None, stream_bank: None, stream_events: Vec::new(), + stream_started: None, + status_pool: None, }; let result = (|| { owner @@ -238,6 +242,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { for index in 0..ring { targets.push(lease.copy_ring_span(index)?); } + let aligned_copy = crate::mapped_expert_bank::aligned_copy_enabled(); let mut entries = Vec::new(); entries .try_reserve_exact((48 - usize::from(first)) * 512) @@ -247,21 +252,52 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { 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); + let exact = bank.expert_pieces(layer, expert)?; + let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0); + // page-aligned supersets side by side at page offsets when they fit the slot (claude/ledger), else the + // exact pieces back to back + let mut entry = None; + if aligned_copy { + let sup = bank.expert_pieces_aligned(layer, expert)?; + let mut dest = [0usize; 3]; + let mut at = [0usize; 3]; + let mut off = 0usize; + for i in 0..3 { + dest[i] = off; + at[i] = off + sup[i].2; + off += sup[i].1.div_ceil(4096) * 4096; + } + if off <= slot_bytes { + entry = Some(StreamEntry { + layer, expert, pieces: [(sup[0].0, sup[0].1), (sup[1].0, sup[1].1), (sup[2].0, sup[2].1)], + exact, dest, at, + }); + } } - entries.push(StreamEntry { layer, expert, pieces }); + let entry = match entry { + Some(e) => e, + None => { + let bytes: usize = exact.iter().map(|p| p.1).sum(); + if bytes > slot_bytes { + return Err(Error::InvalidSize); + } + let dest = [0, exact[0].1, exact[0].1 + exact[1].1]; + StreamEntry { layer, expert, pieces: exact, exact, dest, at: dest } + } + }; + entries.push(entry); } } 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 +310,19 @@ 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::().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) { + let context_token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?); + match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup, context_token) { 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 +348,14 @@ 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(stream_ms); + } drop(stream); let drained = combine(copy, compute); let mut result = combine(stopped, drained); @@ -403,6 +454,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() { @@ -425,6 +479,8 @@ struct Source<'read> { job: Option, /// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`) entry: Option, + /// slot offsets of gate, up and down after a page-aligned copy (claude/ledger); `None`: the literal blob layout 0, gu, 2*gu + dest: Option<[usize; 3]>, } /// Private owner: no external pointer/ready event can manufacture a stage. /// The actual source Rc prevents unregister/free during H2D or gathered use. @@ -590,6 +646,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { slot: None, job: None, entry: None, + dest: None, }); } // With an active chunk stream for this layer, every non-resident expert is the stream's entry. @@ -643,7 +700,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.max(512))?) + } + None => Some(context.allocate(charge.max(512))?), + }; // The old input quantization/metadata upload used default stream. // Admit that dependency once before starting nonblocking producers. context.synchronize()?; @@ -756,6 +820,7 @@ 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; + let mut new_dest: Option<[usize; 3]> = None; if skip_expert_dma() { // EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it // held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream. @@ -780,6 +845,30 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { host_events[j % ring].record(copy)?; host.issued(j); } else { + // page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit) + let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() { + let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3]; + let mut off = 0usize; + for (i, part) in parts.iter_mut().enumerate() { + let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?; + *part = (superset, lead, off); + off += superset.len().div_ceil(4096) * 4096; + } + (off <= slot.bytes).then_some(parts) + } else { + None + }; + if let Some(parts) = aligned { + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| { + for (superset, _, off) in parts { + api.copy_registered(slot.span.checked_subspan(slot.bytes, off, superset.len())?, superset, stream)?; + } + Ok(()) + })?; + new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]); + } else { let sources = [ bank.cache_source(&source.spans[0])?, bank.cache_source(&source.spans[1])?, @@ -808,6 +897,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { Ok(()) })?; } + } events .copied .as_mut() @@ -816,6 +906,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { slot.live = true; slot.gathered = false; self.sources[index].slot = Some(sl); + self.sources[index].dest = new_dest; self.stage_next = next; Ok(()) } @@ -835,21 +926,23 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let down = formats[2].layout(1)?.raw_weight; let sl = source.slot; let entry = source.entry; + let dest = source.dest; 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 at = stream.entry_at(k)?; 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)?, + span.checked_subspan(bytes, at[0], gu)?, + span.checked_subspan(bytes, at[1], gu)?, + span.checked_subspan(bytes, at[2], down)?, ] } else { let sl = sl.ok_or(Error::InvalidProjectionShape)?; @@ -868,10 +961,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { .as_ref() .ok_or(Error::ContextPoisoned)?, )?; + let at = dest.unwrap_or([0, gu, gu * 2]); [ - slot.span.checked_subspan(slot.bytes, 0, gu)?, - slot.span.checked_subspan(slot.bytes, gu, gu)?, - slot.span.checked_subspan(slot.bytes, gu * 2, down)?, + slot.span.checked_subspan(slot.bytes, at[0], gu)?, + slot.span.checked_subspan(slot.bytes, at[1], gu)?, + slot.span.checked_subspan(slot.bytes, at[2], down)?, ] }; // Destination checks are closed to actual group-bank ranges. All source @@ -950,11 +1044,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 +1107,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 } diff --git a/crates/cuda-driver/src/native_prompt_device.rs b/crates/cuda-driver/src/native_prompt_device.rs index 5d6b1b45..df699c94 100644 --- a/crates/cuda-driver/src/native_prompt_device.rs +++ b/crates/cuda-driver/src/native_prompt_device.rs @@ -158,6 +158,11 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { } /// Consume the actual retained lease only after Root validated the genuine /// preview identity and draft receipt. No second host row read occurs. + /// Look at every deferred guard status now (LELEKA_PREFILL_DEFER_GUARDS; a no-op when nothing is deferred). The runtime calls it + /// before it seals a phase whose rows stay on the device. + pub fn resolve_guards(&self) -> Result<()> { + crate::deferred_status::resolve(self.lease.context()) + } pub fn finish_after_preview(mut self) -> Result<()> { if self.lease.is_failed() { return Err(Error::ContextPoisoned); @@ -790,8 +795,16 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return Err(e); } }; - let mut op = self.context.driver.api.copy_from(status, &zero); - if op.is_ok() { + // LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and + // looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate. + let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled(); + let status_bytes = t * stride * 4; + let mut op = if defer { + crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40) + } else { + self.context.driver.api.copy_from(status, &zero) + }; + if op.is_ok() && !defer { op = self.context.driver.api.synchronize() } // LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position) @@ -843,6 +856,28 @@ impl<'ctx> OriginalPromptDevice<'ctx> { crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed()); } } + if defer { + // no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs) + let queued = if op.is_ok() { + crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels) + } else { + op + }; + let pop = guard.finish(); + if queued.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed(); + std::mem::forget((commands, zero, readback)); + self.context.retain_driver(); + return combine(queued, pop); + } + // cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the + // call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain + // as a conservative audit rule; the failure path above still leaks them) + drop(commands); + return Ok(()); + } let sync = blas.synchronize(); if op.is_ok() && sync.is_ok() { op = self.context.driver.api.copy_to(status, &mut readback) @@ -860,44 +895,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return combine(combine(combine(op, sync), all), pop); } combine(combine(combine(op, sync), all), pop)?; - // Unknown status is never a usable finite product, including a later - // word after an earlier numerical flag. All actual kernels write0/1. - for word in readback.as_chunks::<4>().0 { - if u32::from_le_bytes(*word) > 1 { + // Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual + // kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate). + if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) { + if matches!(e, Error::InvalidDriverValue(_)) { self.failed = true; lease.mark_failed(); self.context.retain_driver(); - return Err(Error::InvalidDriverValue("Original prompt status")); - } - } - if stride == 10 { - // PLE preserves chronological row THEN original ten-stage order. - for row in readback.chunks_exact(stride * 4) { - for &stage in order { - if u32::from_le_bytes( - row[stage * 4..stage * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ) != 0 - { - return Err(Error::NonFiniteMmqOutput(labels[stage])); - } - } - } - } else { - // GR preserves the original stage-first whole-output validation. - for &stage in order { - for row in readback.chunks_exact(stride * 4) { - if u32::from_le_bytes( - row[stage * 4..stage * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ) != 0 - { - return Err(Error::NonFiniteMmqOutput(labels[stage])); - } - } } + return Err(e); } Ok(()) } diff --git a/crates/cuda-driver/src/original_expert_stager_ffi.rs b/crates/cuda-driver/src/original_expert_stager_ffi.rs index d7754c4c..3419f9c4 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi.rs @@ -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) { @@ -127,6 +129,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) @@ -188,6 +191,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 { + 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 { + 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<()> { // SAFETY: event created by `event_create`, destroyed once by the owner after it was synchronized. check("cuEventDestroy_v2", unsafe { diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs index f58bdd1d..39e94ca1 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs @@ -179,15 +179,17 @@ 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); // SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included). check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) }) } pub(crate) fn stream_sync(&self, s: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) }) + crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) })) } pub(crate) fn stream_query(&self, s: usize) -> Result { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. @@ -246,9 +248,9 @@ mod platform { } pub(crate) fn event_sync(&self, e: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuEventSynchronize", unsafe { + crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { (self.event_sync)(e as Handle) - }) + })) } pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result { let mut ms = 0.; diff --git a/crates/cuda-driver/src/original_moe_prompt_device.rs b/crates/cuda-driver/src/original_moe_prompt_device.rs index 3066115e..061ecca3 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device.rs @@ -50,6 +50,7 @@ pub struct OriginalMoePromptLayer<'program, 'arena, 'loan, 'ctx> { counts: Vec, source_rows: Vec, slot_map: Vec, + slot_uploaded: bool, completed_experts: usize, } enum Command { @@ -571,6 +572,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { counts: actual_counts, source_rows, slot_map, + slot_uploaded: false, completed_experts: 0, }) } @@ -668,6 +670,7 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo return Err(Error::InvalidQwenShape); } } + self.upload_slot_table()?; let mut program = workspace.prepare_original_expert_layer_device( &self.read, &self.counts, @@ -724,12 +727,12 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo self.completed_experts = self.order.len(); Ok(()) } - pub fn finish( - self, - workspace: &mut NativeBatchWorkspace<'ctx>, - ) -> Result> { - if self.completed_experts != self.order.len() || self.order.is_empty() { - return Err(Error::InvalidQwenShape); + /// The routed slot table's upload (read only by the combine kernel). The copy ring does it BEFORE its expert + /// copies, because after the ring the chunk's expert stream has the host-to-device copy engine busy and a + /// 327 KB upload then waits for several milliseconds behind it. Same bytes, same completion fence. + fn upload_slot_table(&mut self) -> Result<()> { + if self.slot_uploaded { + return Ok(()); } let rows = self.read.lease(); let t = rows.rows(); @@ -750,6 +753,21 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo return combine(combine(copy, wait), pop).map(|()| unreachable!()); } combine(combine(copy, wait), pop)?; + self.slot_uploaded = true; + Ok(()) + } + pub fn finish( + mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + if self.completed_experts != self.order.len() || self.order.is_empty() { + return Err(Error::InvalidQwenShape); + } + self.upload_slot_table()?; + let rows = self.read.lease(); + let t = rows.rows(); + let (slot, extent) = rows.span(PrefillPhase::Moe, "slot_dev")?; + let slot = slot.checked_subspan(extent, 0, t * 10 * 4)?; let bo = common(rows, S::Block, 2560 * 4)?; let mut commands = Vec::new(); kernel( diff --git a/crates/cuda-driver/src/original_prefill_arena.rs b/crates/cuda-driver/src/original_prefill_arena.rs index fba68c34..2186f00e 100644 --- a/crates/cuda-driver/src/original_prefill_arena.rs +++ b/crates/cuda-driver/src/original_prefill_arena.rs @@ -252,6 +252,11 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { /// required for source-equivalent stream ordering at the caller seam. pub(crate) fn drain(&mut self) -> Result<()> { if self.drained { return Ok(()); } + // deferred guard words (LELEKA_PREFILL_DEFER_GUARDS) are looked at before anything leaves the device + if let Err(e) = crate::deferred_status::resolve(self.arena.context) { + self.arena.failed = true; + return Err(e); + } let result = self.arena.context.synchronize(); if result.is_err() { self.arena.failed = true; } self.drained = result.is_ok(); diff --git a/crates/cuda-driver/src/original_prefill_layout.rs b/crates/cuda-driver/src/original_prefill_layout.rs index 8a6b116a..6622423e 100644 --- a/crates/cuda-driver/src/original_prefill_layout.rs +++ b/crates/cuda-driver/src/original_prefill_layout.rs @@ -242,7 +242,9 @@ impl PrefillLayoutOptions { } let ring_slots = self.original_ring_slots()?; // Names intentionally share one role; the index is the span occurrence. - for _ in 0..ring_slots { a.take("stage_dev", self.max_expert_blob, 1)?; } + // room for three page-aligned supersets (claude/ledger: LELEKA_PREFILL_ALIGNED_COPY, default on) + let slot_bytes = if crate::mapped_expert_bank::aligned_copy_enabled() { add(self.max_expert_blob, crate::mapped_expert_bank::ALIGNED_COPY_SLACK)? } else { self.max_expert_blob }; + for _ in 0..ring_slots { a.take("stage_dev", slot_bytes, 1)?; } a.rows("ple_emb", t, N, 4)?; a.take("ple_norm", D, 4)?; let mut owned = Alloc::new(PrefillPhase::Common); diff --git a/crates/cuda-driver/src/ple_batch_ffi.rs b/crates/cuda-driver/src/ple_batch_ffi.rs index f84868d5..a6abc1ed 100644 --- a/crates/cuda-driver/src/ple_batch_ffi.rs +++ b/crates/cuda-driver/src/ple_batch_ffi.rs @@ -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) })?; @@ -379,9 +380,9 @@ mod enabled { } pub(crate) fn synchronize(&self) -> Result<()> { // SAFETY: actual private stream remains owned through this call. - check("cuStreamSynchronize", unsafe { + crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(self.stream() as *mut c_void) - }) + })) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() @@ -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, diff --git a/crates/cuda-driver/src/qsa_prompt_attention.rs b/crates/cuda-driver/src/qsa_prompt_attention.rs index 710c4416..aad5f34a 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention.rs @@ -340,7 +340,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { Arg::I32(end as i32), Arg::U64(status), ])?; - self.run_in(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?; + self.run_in(variants, w, guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?; let flags = self.flags()?; if flags & 2 != 0 { return Err(Error::InvalidQwenShape); @@ -369,7 +369,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { Arg::I32((t * 6144) as i32), Arg::U64(status), ])?; - self.run_in(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?; + self.run_in(variants, w, scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } @@ -479,3 +479,12 @@ mod device_attention; mod resident_attention; pub use resident_attention::OriginalQsaResidentAttention; + +/// Grid of the prompt attention's input and output guards (claude/ledger). Both are grid-stride loops over `t * 6144` floats (and +/// the id-order scan over `t` rows); the literal 64 blocks left 100+ SMs idle and cost 1.8 + 1.0 ms per QSA layer of an 8192-token +/// chunk. Any grid gives the same status words (an OR of the same per-element conditions); `LELEKA_PREFILL_GUARD_GRID=64` restores it. +pub(crate) fn guard_grid(t: usize) -> u32 { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let fixed = *FIXED.get_or_init(|| std::env::var("LELEKA_PREFILL_GUARD_GRID").ok().and_then(|v| v.parse().ok())); + fixed.unwrap_or_else(|| ((t * 6144).div_ceil(256 * 4)).clamp(64, 2048) as u32) +} diff --git a/crates/cuda-driver/src/qsa_prompt_device_attention.rs b/crates/cuda-driver/src/qsa_prompt_device_attention.rs index 407cf227..3d06face 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_attention.rs @@ -46,7 +46,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32(end as i32), Arg::U64(status), ])?; - self.run_in(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?; + self.run_in(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?; let flags = self.flags()?; if flags & 2 != 0 { return Err(Error::InvalidQwenShape); @@ -75,7 +75,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32((t * 6144) as i32), Arg::U64(status), ])?; - self.run_in(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?; + self.run_in(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } diff --git a/crates/cuda-driver/src/qsa_resident_attention.rs b/crates/cuda-driver/src/qsa_resident_attention.rs index e933024d..59d8eecd 100644 --- a/crates/cuda-driver/src/qsa_resident_attention.rs +++ b/crates/cuda-driver/src/qsa_resident_attention.rs @@ -45,7 +45,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32(end as i32), Arg::U64(status), ])?; - self.run_resident(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?; + self.run_resident(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?; let flags = self.flags()?; if flags & 2 != 0 { return Err(Error::InvalidQwenShape); @@ -74,7 +74,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32((t * 6144) as i32), Arg::U64(status), ])?; - self.run_resident(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?; + self.run_resident(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index 800441d5..273c37dc 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -488,10 +488,24 @@ fn original_serve_long_context_streamed_kv_smoke() { Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect()) }); let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len()); + // LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process) + let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ") + .map(|v| v.split(',').filter_map(|t| { + let mut parts = t.trim().splitn(2, ':'); + Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0))) + }).collect()).unwrap_or_default(); for pass in 0..repeat { crate::qwen_forward::quality_force::set(forced_answer.as_ref().map(|answer| { prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect() })); + if !stream_seq.is_empty() { + let (v, depth) = stream_seq[pass % stream_seq.len()]; + leleka_cuda_driver::compute_drain::set_issue_depth(depth); + // bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight + crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE.store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed); + leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0); + eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}"); + } let started = std::time::Instant::now(); let mut tokens = Vec::new(); let outcome = stack 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 0f93f088..a9ef87ea 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs @@ -9,24 +9,27 @@ use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace, use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage}; -/// EXPERIMENTAL, off by default: prefill.cpp `stream_all` order (`begin_prompt_stream`) with next-MoE copies -/// queued under the GDN kernel batches, for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows (1024) over a -/// registered bank, with `LELEKA_PREFILL_STREAM=1`. Measured (job 0708): the copies moved out of the ring into -/// the GDN windows instead of overlapping them (8192-token chunks 2,676 vs 2,730 ms, 2048-token chunks 1,755 vs -/// 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. +/// prefill.cpp `stream_all` order (`begin_prompt_stream`): for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows +/// (default 4096: it copies every expert of every layer, while the per-layer ring copies only the routed ones, about +/// 60% of them at 2048 rows, so a 2048-row chunk is DMA-bound and 20% slower with the stream; ~100% at 8192) over a registered bank every layer's experts are copied by an issuer thread with a bounded copy queue, +/// overlapped with the mixers; the compute path's drains are stream-scoped meanwhile. `LELEKA_PREFILL_STREAM=0` +/// keeps the per-layer copy ring. Measured (docs/prefill-throughput.md, jobs 956-965): 16,000 tokens at chunk 8192 +/// +13..27% prefill tok/s over the per-layer ring, identical greedy ids. fn prompt_stream_settings() -> Option<(usize, f64)> { - static SETTINGS: std::sync::OnceLock> = std::sync::OnceLock::new(); - *SETTINGS.get_or_init(|| { - if !std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "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::().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").map_or(true, |v| v != "0"), + }; + 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", 4096), 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 { match key.raw_kind { diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs index 22a2ed47..2184003f 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs @@ -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"))] diff --git a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs index 94d1c4c4..30f9672d 100644 --- a/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs +++ b/crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs @@ -126,6 +126,7 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{ if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)} let known_next=txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; let lease_identity=self.device.lease_identity(); + self.device.resolve_guards().map_err(micro_driver_error)?; phase.seal_final()?; Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(), product:FinalProduct::DeviceConditioning{known_next},lease_identity}) diff --git a/docs/prefill-throughput.md b/docs/prefill-throughput.md index 1b5b03d4..c5909c9f 100644 --- a/docs/prefill-throughput.md +++ b/docs/prefill-throughput.md @@ -248,3 +248,101 @@ equal job 0708's reference of the same chunking: EXPERIMENTAL and off. Defaults of the other four switches are on. What remains: the expert DMA (claude/prefill-overlap), the GDN recurrence (155 ms, a 128-step FMA chain per token that cannot be reordered without changing bits), cuBLAS GEMMs at the tensor-core limit, per-layer host drains. + +## Expert stream overlap (branch `claude/prefill-overlap`, jobs 950-968, RTX 5090) + +Goal: hide the expert DMA of an 8192-token chunk (24,576 experts = 50.3 GB, i.e. every expert of all 48 layers at +2.05 MB; a 16,000-token prompt moves it twice) under the mixers. The per-layer ring paid it layer by layer (moe.ring +~1,110 ms of a 2,140 ms chunk after the prefill-kernels merge, 3,780 tok/s on 16,000 tokens). + +### What blocked the overlap (and what was removed) + +1. Every compute producer drained with `cuCtxSynchronize`, which also waits for the copy stream. All of them go through + `ffi::Api::synchronize`; while a chunk's expert stream runs (`compute_drain`, background stream registered by + `begin_prompt_stream`) it now waits for the legacy default stream and every registered compute stream except the + copy stream (all four stream creators register: Blas, Original schedule, owned copy, swap). Outside a chunk stream + it is the unchanged context-wide drain. The ring's own layer drain no longer syncs the copy stream either. +2. `cuMemFree` synchronizes the whole device (per-layer GDN/QSA/PLE scratch, 6 MB per GDN layer): frees are queued + on the `Context` while the stream runs and executed when it ends (or past `LELEKA_PREFILL_DEFER_FREE_MIB`, 512); + the ring's per-layer status buffer is pooled. +3. **The host-to-device copy engine is a FIFO.** Any other transfer of the compute path (synchronous H2D uploads, + D2H status readbacks) waits for all expert copies queued before it: model-free probe, job 955 + (`scripts/h2d_copy_engine_probe.cu`): a 327 KB `cudaMemcpy` waits 0.13 ms behind 2 queued experts, 0.42 ms behind 8, + 1.6 ms behind 32, 5.7 ms behind 128+ (= outstanding bytes / 36 GB/s); memsets, kernels and D2D copies do not queue. + With a deep queue the waits only moved from the ring into `moe.finish` (372 ms) and `inject` (650 ms) (job 953: + `PREFILL-SITE`/`PREFILL-STALL` call-site histograms). Fixes: an issuer thread (the Original's D-5) keeps only + `LELEKA_PREFILL_DEPTH` (default 2) entries outstanding on the copy stream, event-query paced, the compute thread + only waits until an entry is enqueued before ordering its stream after it; all-zero uploads become device memsets + while the stream runs (`LELEKA_PREFILL_ZERO_MEMSET=0` disables); the routed slot table (327 KB, non-zero) is + uploaded before the ring instead of after it. +4. Not done (open, see below): ~1,100 small blocking H2D/D2H calls per chunk remain (status readbacks, shared-layer + weight uploads, GDN state staging, QSA tables); each costs up to the queue depth in latency and keeps the depth at 2. + +The stream copies *every* expert of every layer (prefill.cpp `stream_all`), while the per-layer ring copies only the +routed ones: at 2,048 rows only ~60% of the experts are routed, so the stream is 20% slower there (jobs 961/962: +1,330 vs 1,670 tok/s) and nearly free at 8,192 (~100% routed). It therefore starts at 4,096 rows +(`STRATA_PREFILL_STREAM_MIN`); `LELEKA_PREFILL_STREAM=0` restores the per-layer ring everywhere. + +### Results (paired passes alternating inside one process, same binary and prompts, greedy 16 tokens) + +| config | prompt | per-layer ring | expert stream | notes | +| --- | --- | --- | --- | --- | +| chunk 8192, tier off, depth 16 (job 960) | 8,000 | 3,764-3,784 | 4,367-4,406 | +16% | +| chunk 8192, tier off, depth 16 (job 960) | 16,000 | 3,780 | 4,275-4,358 | +13% | +| chunk 8192, tier off, depth sweep (job 958) | 16,000 | 3,795-3,799 | 2: 4,805-4,811; 4: 4,163-4,181; 8: 4,227-4,293; 16: 4,300-4,350; 32: 4,199 | depth 2 best | +| chunk 8192, tier off, depth 2, 12 passes (job 963) | 16,000 | - | 4,789-4,851 | +27% | +| chunk 8192, tier on (job 962, depth 16) | 8,000 / 16,000 | 3,573 / 3,625-3,686 | 4,499-4,528 / 4,631-4,654 | +26% | +| chunk 2048 (jobs 961/962, stream forced) | 8,000 / 16,000 | 1,670-1,718 / 1,659-1,711 | 1,325-1,380 / 1,324-1,384 | -20%: off below 4096 rows | + +Greedy ids: identical between the two modes on every paired pass (8000 and 16000, chunk 8192 and 2048, tier off and +on) and equal to job 0708's ids for the same chunking. With the tier on the 16000-token answer at chunk 8192 is a +near-tie that the unmodified head already flips between passes (one OFF pass of job 962 answered `271,248069` instead +of `198`); the stream's passes all gave `198`. Race hunt (job 963): 36 consecutive full 16,000-token prefills +(12 plain, 12 with pseudo-random host delays between the copy enqueues `LELEKA_PREFILL_STREAM_JITTER`, 12 with the +same jitter at depth 1): identical ids, no `CudaExecution`. `compute-sanitizer` racecheck/synccheck only see +shared-memory hazards inside a kernel, which this change does not touch; the cross-stream ordering is by events +(`copied`/`used` per ring slot), and the repeated runs under jitter are the evidence. + +### Copy rate, bytes per chunk, tier + +Every 8192-row chunk streams 24,576 entries x 3 copies of 682 KB = 50.3 GB (job 950+ `PREFILL-COPY`: per-entry event +timing 35.5-36.5 GB/s, independent of queue depth and of concurrent kernels; `cudaHostAlloc` memory in the model-free +probe 40.3-40.9 GB/s for 3x682 KB, 1x2 MB, depth 4-64, 1-2 streams; the registered bank is ~12% slower). With the stream +the DMA is busy ~77% of the chunk (stream window 1.6-1.8 s for a 1.42 s copy floor at 35.5 GB/s). The VRAM expert tier +(2048 slots per layer, 1891 lent) removes only ~0.6% of the entries at chunk 8192 (24,419 vs 24,576) and 4.7% at 2048 +(23,415): prefill with the tier streams essentially the same bytes. Chunk sizes above 8192 are not possible: the prompt +arena, GEMM and MMQ shape checks are capped at 8192 rows (30+ sites, 81920-row MMQ layouts); bytes per token fall 4x +from 2048 to 8192 as the per-chunk traffic is constant. + +### Late chunks (180,000-token prompt, job 915/957) + +Per-chunk time grows from 2,120 ms (position 0) to 2,480 ms (position 172k) on the unmodified head, of which QSA +250 -> 537 ms and moe.ring 1,117 -> 1,200 ms; GDN is flat. Per-command profile (job 957, 8 -> 90k -> 164k): +`qsa index+norm+rope run` 49 -> 167 -> 269 ms (the indexer scores every earlier block: ~1.4 ms per 1k positions per +chunk), `kv append` 15 -> 36 -> 54 ms, `attend` flat 124 ms, proj Q/out flat. The indexer is the stage that grows with +position; its kernels were not touched here. + +### Final defaults and the 180k prompt (jobs 965-968) + +- Queue depth (job 965, 16,000 tokens @8192, same process): depth 1 3,343; **2 4,805-4,821**; 3 4,238-4,310 tok/s + (per-layer ring 3,790); depth 2 is the default. The stream runs one expert (2 MB) ahead of its consumer, so the + copy engine is never idle for long but any other transfer waits at most ~2 MB / 36 GB/s. +- Shipped defaults vs `LELEKA_PREFILL_STREAM=0`, separate processes (job 966, second and third pass): chunk 8192 + 8,000 tokens 4,851 / 4,844 vs 3,760 / 3,766 tok/s, 16,000 tokens 4,820 / 4,816 vs 3,796 / 3,778; chunk 2048 + identical (1,670 vs 1,671 / 1,656 vs 1,655: the stream is off below 4096 rows). All greedy ids equal. +- Chunk 4096 (job 967): stream = ring (2,598-2,601 vs 2,583-2,584 for 8,000 tokens; 2,593-2,598 vs 2,598 for 16,000), + ids equal: copying every expert costs what the overlap saves. +- 180,000 tokens, tier on, chunk 8192 (job 968, passes alternating in one process): stream 40.9 s / 39.9 s + (4,397 / 4,508 tok/s) vs ring 51.0 s (3,532 tok/s) = +25..28%; identical ids. Per chunk (position 8k / 82k / 164k): + stream 1,680 / 1,773 / 1,905 ms (qsa 272 / 398 / 530, moe.ring 539 / 582 / 581, gdn 464, inject 85) vs ring + 2,080 / 2,320 / 2,473 ms (moe.ring 1,057 / 1,169 / 1,186). The unmodified Original needs 39.4 s for the same prompt. + What still grows with position is the QSA indexer (above) and, slightly, the ring. + +### Merged copy path + +`claude/ledger`'s page-aligned expert supersets (+12% on the ring: DMA 36 -> 47 GB/s) are merged into the stream: +stream entries carry the 4 KiB-aligned supersets, their slot offsets and the offsets of the exact pieces, and the +gather reads the exact pieces there (`LELEKA_PREFILL_ALIGNED_COPY=0` turns both paths off). The schedule agent's +deferred guard status (`LELEKA_PREFILL_DEFER_GUARDS=1`, experimental, default off; +1.6% in its A/B) is merged. +Open: runs of consecutive experts per role in one copy / `cuMemcpyBatchAsync` (50-51 GB/s in the roofline probes), the +~1,100 remaining blocking small copies per chunk, QSA indexer growth with position. diff --git a/scripts/h2d_copy_engine_probe.cu b/scripts/h2d_copy_engine_probe.cu new file mode 100644 index 00000000..d4031163 --- /dev/null +++ b/scripts/h2d_copy_engine_probe.cu @@ -0,0 +1,95 @@ +// Model-free probe: latency of small synchronous host/device copies and kernels while an "expert stream" keeps the +// host-to-device copy engine busy (claude/prefill-overlap). Build: nvcc -O2 -arch=sm_120 h2d_probe.cu -o h2d_probe +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0) +using Clock = std::chrono::steady_clock; +static double ms(Clock::time_point a) { return std::chrono::duration(Clock::now() - a).count(); } +__global__ void tiny(float* p, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p[i] += 1.0f; } + +int main(int argc, char** argv) { + setvbuf(stdout, NULL, _IOLBF, 0); + int only_depth = argc > 1 ? atoi(argv[1]) : -1; + const size_t ENTRY = 2046000; // one expert (gate+up+down), bytes + const int PIECES = 3, RING = 384, NENT = 4096; + const size_t SMALL = 327680; // the routed slot table + uint8_t* host; + uint8_t* ring; CK(cudaMalloc((void**)&ring, ENTRY * RING)); + uint8_t* dev_small; CK(cudaMalloc((void**)&dev_small, 64 << 20)); + float* dev_f; CK(cudaMalloc((void**)&dev_f, 1 << 20)); + std::vector pageable(SMALL, 7); + uint8_t* pinned_small; CK(cudaHostAlloc((void**)&pinned_small, SMALL, cudaHostAllocDefault)); + cudaStream_t copy, hi, other; + CK(cudaStreamCreateWithFlags(©, cudaStreamNonBlocking)); + int lo, hip; CK(cudaDeviceGetStreamPriorityRange(&lo, &hip)); + CK(cudaStreamCreateWithPriority(&hi, cudaStreamNonBlocking, hip)); + CK(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking)); + CK(cudaStreamSynchronize(0)); + size_t hostN = 1ull << 30; + CK(cudaHostAlloc((void**)&host, hostN * 4, cudaHostAllocDefault)); // 4 GiB + memset(host, 1, hostN * 4); + const size_t entries_in_host = (hostN * 4) / ENTRY; + + auto bg = [&](int depth, int pieces, std::atomic* stop, std::atomic* bytes) { + std::vector ev(depth + 1); + for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming)); + long k = 0; + while (!stop->load()) { + int slot = (int)(k % RING); + size_t src = (size_t)(k % entries_in_host) * ENTRY; + size_t piece = ENTRY / pieces; + for (int p = 0; p < pieces; ++p) + CK(cudaMemcpyAsync(ring + (size_t)slot * ENTRY + p * piece, host + src + p * piece, piece, cudaMemcpyHostToDevice, copy)); + CK(cudaEventRecord(ev[k % (depth + 1)], copy)); + ++k; bytes->fetch_add(ENTRY); + if (k > depth) CK(cudaEventSynchronize(ev[(k - depth - 1) % (depth + 1)])); // keep `depth` entries outstanding + } + CK(cudaStreamSynchronize(copy)); + for (auto& e : ev) cudaEventDestroy(e); + }; + + struct Probe { const char* name; }; + auto measure = [&](const char* name, int reps, auto&& f) { + std::vector t; + for (int i = 0; i < reps; ++i) { auto a = Clock::now(); f(); t.push_back(ms(a)); std::this_thread::sleep_for(std::chrono::microseconds(300)); } + std::sort(t.begin(), t.end()); + double mean = 0; for (double x : t) mean += x; mean /= t.size(); + printf(" %-34s mean %7.3f ms p50 %7.3f p90 %7.3f max %7.3f\n", name, mean, t[t.size() / 2], t[t.size() * 9 / 10], t.back()); + }; + + int depths[] = {0, 2, 8, 32, 128, 384}; + int pieces_list[] = {3, 1}; + for (int pieces : pieces_list) { + for (int depth : depths) { + if (only_depth >= 0 && depth != only_depth) continue; + printf("expert stream: depth=%d entries outstanding, %d copies per entry (%zu B each)\n", depth, pieces, ENTRY / pieces); + std::atomic stop{false}; std::atomic bytes{0}; + std::thread th; + auto t0 = Clock::now(); + if (depth > 0) th = std::thread([&] { bg(depth, pieces, &stop, &bytes); }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + long b0 = bytes.load(); auto tm = Clock::now(); + measure("cudaMemcpy H2D 327KB pageable", 60, [&] { CK(cudaMemcpy(dev_small, pageable.data(), SMALL, cudaMemcpyHostToDevice)); }); + measure("cudaMemcpy H2D 6MB pageable", 20, [&] { std::vector big(6 << 20, 1); CK(cudaMemcpy(dev_small, big.data(), big.size(), cudaMemcpyHostToDevice)); }); + measure("cudaMemcpyAsync pinned 327KB hi-prio", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, hi)); CK(cudaStreamSynchronize(hi)); }); + measure("cudaMemcpyAsync pinned 327KB other", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, other)); CK(cudaStreamSynchronize(other)); }); + measure("cudaMemcpy D2H 4KB", 60, [&] { uint8_t h[4096]; CK(cudaMemcpy(h, dev_small, 4096, cudaMemcpyDeviceToHost)); }); + measure("cudaMemset 4KB (legacy)", 60, [&] { CK(cudaMemset(dev_small, 0, 4096)); }); + measure("cudaMemcpy D2D 100MB (legacy)", 20, [&] { CK(cudaMemcpy(dev_small + (32 << 20), dev_small, 16 << 20, cudaMemcpyDeviceToDevice)); }); + measure("tiny kernel + sync (other)", 60, [&] { tiny<<<64, 256, 0, other>>>(dev_f, 16384); CK(cudaStreamSynchronize(other)); }); + measure("tiny kernel + sync (legacy)", 60, [&] { tiny<<<64, 256, 0, 0>>>(dev_f, 16384); CK(cudaStreamSynchronize(0)); }); + long b1 = bytes.load(); double dt = ms(tm); + stop = true; if (th.joinable()) th.join(); + if (depth > 0) printf(" expert DMA while probing: %.1f GB/s\n", (b1 - b0) / (dt * 1e6)); + (void)t0; + } + } + return 0; +} diff --git a/scripts/h2d_probe.cu b/scripts/h2d_probe.cu new file mode 100644 index 00000000..63b5f062 --- /dev/null +++ b/scripts/h2d_probe.cu @@ -0,0 +1,92 @@ +// Model-free probe: latency of small synchronous host/device copies and kernels while an "expert stream" keeps the +// host-to-device copy engine busy (claude/prefill-overlap). Build: nvcc -O2 -arch=sm_120 h2d_probe.cu -o h2d_probe +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0) +using Clock = std::chrono::steady_clock; +static double ms(Clock::time_point a) { return std::chrono::duration(Clock::now() - a).count(); } +__global__ void tiny(float* p, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p[i] += 1.0f; } + +int main(int argc, char** argv) { + const size_t ENTRY = 2046000; // one expert (gate+up+down), bytes + const int PIECES = 3, RING = 384, NENT = 4096; + const size_t SMALL = 327680; // the routed slot table + uint8_t* host; + uint8_t* ring; CK(cudaMalloc((void**)&ring, ENTRY * RING)); + uint8_t* dev_small; CK(cudaMalloc((void**)&dev_small, 64 << 20)); + float* dev_f; CK(cudaMalloc((void**)&dev_f, 1 << 20)); + std::vector pageable(SMALL, 7); + uint8_t* pinned_small; CK(cudaHostAlloc((void**)&pinned_small, SMALL, cudaHostAllocDefault)); + cudaStream_t copy, hi, other; + CK(cudaStreamCreateWithFlags(©, cudaStreamNonBlocking)); + int lo, hip; CK(cudaDeviceGetStreamPriorityRange(&lo, &hip)); + CK(cudaStreamCreateWithPriority(&hi, cudaStreamNonBlocking, hip)); + CK(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking)); + CK(cudaStreamSynchronize(0)); + size_t hostN = 1ull << 30; + CK(cudaHostAlloc((void**)&host, hostN * 4, cudaHostAllocDefault)); // 4 GiB + memset(host, 1, hostN * 4); + const size_t entries_in_host = (hostN * 4) / ENTRY; + + auto bg = [&](int depth, int pieces, std::atomic* stop, std::atomic* bytes) { + std::vector ev(depth + 1); + for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming)); + long k = 0; + while (!stop->load()) { + int slot = (int)(k % RING); + size_t src = (size_t)(k % entries_in_host) * ENTRY; + size_t piece = ENTRY / pieces; + for (int p = 0; p < pieces; ++p) + CK(cudaMemcpyAsync(ring + (size_t)slot * ENTRY + p * piece, host + src + p * piece, piece, cudaMemcpyHostToDevice, copy)); + CK(cudaEventRecord(ev[k % (depth + 1)], copy)); + ++k; bytes->fetch_add(ENTRY); + if (k > depth) CK(cudaEventSynchronize(ev[(k - depth - 1) % (depth + 1)])); // keep `depth` entries outstanding + } + CK(cudaStreamSynchronize(copy)); + for (auto& e : ev) cudaEventDestroy(e); + }; + + struct Probe { const char* name; }; + auto measure = [&](const char* name, int reps, auto&& f) { + std::vector t; + for (int i = 0; i < reps; ++i) { auto a = Clock::now(); f(); t.push_back(ms(a)); std::this_thread::sleep_for(std::chrono::microseconds(300)); } + std::sort(t.begin(), t.end()); + double mean = 0; for (double x : t) mean += x; mean /= t.size(); + printf(" %-34s mean %7.3f ms p50 %7.3f p90 %7.3f max %7.3f\n", name, mean, t[t.size() / 2], t[t.size() * 9 / 10], t.back()); + }; + + int depths[] = {0, 2, 8, 32, 128, 384}; + int pieces_list[] = {3, 1}; + for (int pieces : pieces_list) { + for (int depth : depths) { + printf("expert stream: depth=%d entries outstanding, %d copies per entry (%zu B each)\n", depth, pieces, ENTRY / pieces); + std::atomic stop{false}; std::atomic bytes{0}; + std::thread th; + auto t0 = Clock::now(); + if (depth > 0) th = std::thread([&] { bg(depth, pieces, &stop, &bytes); }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + long b0 = bytes.load(); auto tm = Clock::now(); + measure("cudaMemcpy H2D 327KB pageable", 60, [&] { CK(cudaMemcpy(dev_small, pageable.data(), SMALL, cudaMemcpyHostToDevice)); }); + measure("cudaMemcpy H2D 6MB pageable", 20, [&] { std::vector big(6 << 20, 1); CK(cudaMemcpy(dev_small, big.data(), big.size(), cudaMemcpyHostToDevice)); }); + measure("cudaMemcpyAsync pinned 327KB hi-prio", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, hi)); CK(cudaStreamSynchronize(hi)); }); + measure("cudaMemcpyAsync pinned 327KB other", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, other)); CK(cudaStreamSynchronize(other)); }); + measure("cudaMemcpy D2H 4KB", 60, [&] { uint8_t h[4096]; CK(cudaMemcpy(h, dev_small, 4096, cudaMemcpyDeviceToHost)); }); + measure("cudaMemset 4KB (legacy)", 60, [&] { CK(cudaMemset(dev_small, 0, 4096)); }); + measure("cudaMemcpy D2D 100MB (legacy)", 20, [&] { CK(cudaMemcpy(dev_small + (32 << 20), dev_small, 16 << 20, cudaMemcpyDeviceToDevice)); }); + measure("tiny kernel + sync (other)", 60, [&] { tiny<<<64, 256, 0, other>>>(dev_f, 16384); CK(cudaStreamSynchronize(other)); }); + measure("tiny kernel + sync (legacy)", 60, [&] { tiny<<<64, 256, 0, 0>>>(dev_f, 16384); CK(cudaStreamSynchronize(0)); }); + long b1 = bytes.load(); double dt = ms(tm); + stop = true; if (th.joinable()) th.join(); + if (depth > 0) printf(" expert DMA while probing: %.1f GB/s\n", (b1 - b0) / (dt * 1e6)); + (void)t0; + } + } + return 0; +} diff --git a/scripts/profile/build_rt.sh b/scripts/profile/build_rt.sh new file mode 100644 index 00000000..2d64d875 --- /dev/null +++ b/scripts/profile/build_rt.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Build the leleka-runtime test binary of THIS worktree in WSL (never on the server) and print its path. +# scripts/profile/build_rt.sh TAG (run from Windows Git Bash in the worktree; needs WSL distro "Ubuntu") +# Result: WSL ~/ledger-bin/rt-TAG. Copy to the server with: scp (see docs/ledger.md). +set -euo pipefail +tag=${1:?tag} +root=$(git rev-parse --show-toplevel) +tmp=$(mktemp -d) +git -C "$root" -c core.autocrlf=false ls-files -z | tar -C "$root" --null -T - -cf "$tmp/wt.tar" +win=$(cygpath -w "$tmp/wt.tar" | sed 's#\\#/#g; s#^\([A-Za-z]\):#/mnt/\L\1#') +wsl -d Ubuntu -e bash -lc " +set -e +source ~/.cargo/env +export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin +rm -rf ~/ledger-src && mkdir -p ~/ledger-src ~/ledger-bin && tar -xf '$win' -C ~/ledger-src +cd ~/ledger-src +export CARGO_TARGET_DIR=\$HOME/ledger-target +nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib 2>&1 | tee ~/ledger-build-$tag.log | grep -E 'Executable|^error|warning: unused' | tail -5 +exe=\$(grep -o 'target/release/deps/leleka_runtime-[0-9a-f]*' ~/ledger-build-$tag.log | tail -1) +cp \$CARGO_TARGET_DIR/\${exe#target/} ~/ledger-bin/rt-$tag +ls -la ~/ledger-bin/rt-$tag +" +rm -rf "$tmp" diff --git a/scripts/profile/h2d_src_probe.cu b/scripts/profile/h2d_src_probe.cu new file mode 100644 index 00000000..6648fe3f --- /dev/null +++ b/scripts/profile/h2d_src_probe.cu @@ -0,0 +1,113 @@ +// Model-free probe (claude/ledger): sustained host-to-device DMA rate of the expert stream by SOURCE MEMORY KIND and COPY SHAPE. +// The ledger found the port's ring at ~37 GB/s (3 copies of 0.5-0.9 MB from the registered bank) while the Original's ring runs at +// ~50 GB/s (1 copy of ~2.1 MB from its arena). This isolates which property matters. +// nvcc -O2 -arch=sm_120 h2d_src_probe.cu -o h2d_src_probe ; ./h2d_src_probe [shard.gguf] +// Source kinds: hostalloc | anon4k+register(0) | anon4k+register(PORTABLE) | anon4k+register(DEVICEMAP, the port's bank) | +// anon+MADV_HUGEPAGE+register(DEVICEMAP) | file mapping (MAP_SHARED, PROT_READ) + register(READ_ONLY). +// Shapes (per "expert" of ENTRY bytes): 3 x ENTRY/3 from three role-major regions (the port) | 1 x ENTRY contiguous (the Original) | +// 1 x 2 MiB 4K-aligned | 1 x 8 MiB. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0) +using Clock = std::chrono::steady_clock; + + +static uint8_t* anon(size_t bytes, bool thp) { + void* p = mmap(nullptr, bytes + (2 << 20), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) { perror("mmap"); exit(1); } + uint8_t* a = (uint8_t*)(((size_t)p + (2 << 20) - 1) & ~((size_t)(2 << 20) - 1)); + if (thp) madvise(a, bytes, MADV_HUGEPAGE); + memset(a, 0x5a, bytes); + return a; +} + +// run: copy `n` entries, each `pieces` copies of ENTRY/pieces bytes, cycling over `regions` role-major regions (pieces==3) or one region +static double run(uint8_t* base, size_t region_bytes, size_t entry, int pieces, bool role_major, size_t stride, uint8_t* ring, int slots, + cudaStream_t s, int n, int depth) { + std::vector ev(depth + 1); + for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming)); + cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b)); + size_t piece = entry / pieces; + size_t unit = role_major ? stride : stride * pieces; // distance between consecutive experts inside one region + size_t per_region = region_bytes / (role_major ? pieces : 1) / unit; + CK(cudaEventRecord(a, s)); + for (int k = 0; k < n; ++k) { + int slot = k % slots; + if (k >= depth) CK(cudaStreamWaitEvent(s, ev[(k - depth) % (depth + 1)], 0)); + for (int p = 0; p < pieces; ++p) { + const uint8_t* src; + if (role_major) src = base + (size_t)p * (region_bytes / pieces) + (size_t)(k % per_region) * stride; + else src = base + (size_t)(k % per_region) * unit + (size_t)p * stride; + CK(cudaMemcpyAsync(ring + (size_t)slot * entry + p * piece, src, piece, cudaMemcpyHostToDevice, s)); + } + CK(cudaEventRecord(ev[k % (depth + 1)], s)); + if (k >= depth + 2) CK(cudaEventSynchronize(ev[(k - depth - 2) % (depth + 1)])); + } + CK(cudaEventRecord(b, s)); CK(cudaEventSynchronize(b)); + float ms; CK(cudaEventElapsedTime(&ms, a, b)); + for (auto& e : ev) cudaEventDestroy(e); + cudaEventDestroy(a); cudaEventDestroy(b); + return (double)n * entry / (ms * 1e6); +} + +int main(int argc, char** argv) { + const size_t ENTRY = 2046000; + const size_t REGION = 16ull << 30; // 16 GiB per source kind: the footprint matters (IOMMU/IOTLB), the real bank is ~50 GB + CK(cudaSetDevice(0)); + cudaStream_t s; CK(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking)); + const int SLOTS = 64; + uint8_t* ring; CK(cudaMalloc((void**)&ring, (9ull << 20) * SLOTS)); + struct Shape { const char* name; size_t entry; int pieces; bool role_major; size_t stride; }; + std::vector shapes = {{"3 x 682000 role-major (port)", ENTRY, 3, true, ENTRY / 3}, + {"3 x 682000 role-major, 4K-aligned stride", ENTRY, 3, true, 684032}, + {"1 x 2046000 contiguous (Original)", ENTRY, 1, false, ENTRY}, + {"1 x 2046000, 4K-aligned stride", ENTRY, 1, false, 2048000 + 4096 - 2048000 % 4096}, + {"1 x 2 MiB aligned", 2u << 20, 1, false, 2u << 20}, {"1 x 8 MiB", 8u << 20, 1, false, 8u << 20}}; + struct Kind { const char* name; int id; }; + std::vector kinds = {{"cudaHostAlloc", 0}, {"anon 4K + register(0)", 1}, {"anon 4K + register(PORTABLE)", 2}, + {"anon 4K + register(DEVICEMAP) (port bank)", 3}, {"anon THP + register(DEVICEMAP)", 4}, {"file map RO + register(READ_ONLY)", 5}}; + for (auto& kd : kinds) { + uint8_t* base = nullptr; size_t bytes = REGION; void* map = nullptr; size_t map_bytes = 0; int fd = -1; + if (kd.id == 0) { CK(cudaHostAlloc((void**)&base, bytes, cudaHostAllocDefault)); memset(base, 0x5a, bytes); } + else if (kd.id >= 1 && kd.id <= 4) { + base = anon(bytes, kd.id == 4); + unsigned flags = kd.id == 1 ? 0 : kd.id == 2 ? cudaHostRegisterPortable : cudaHostRegisterMapped; + CK(cudaHostRegister(base, bytes, flags)); + } else { + if (argc < 2) { printf("%-44s skipped (no shard path)\n", kd.name); continue; } + fd = open(argv[1], O_RDONLY); + struct stat st; fstat(fd, &st); + map_bytes = (size_t)st.st_size < bytes ? st.st_size : bytes; + map = mmap(nullptr, map_bytes, PROT_READ, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) { printf("%-44s mmap failed\n", kd.name); continue; } + base = (uint8_t*)map; bytes = map_bytes; + volatile uint8_t sink = 0; + for (size_t i = 0; i < bytes; i += 4096) sink += base[i]; // fault the pages in + cudaError_t e = cudaHostRegister(base, bytes, cudaHostRegisterReadOnly); + if (e != cudaSuccess) { printf("%-44s register failed: %s\n", kd.name, cudaGetErrorString(e)); munmap(map, map_bytes); continue; } + } + for (auto& sh : shapes) { + double best = 0, sum = 0; + for (int rep = 0; rep < 3; ++rep) { + double r = run(base, bytes, sh.entry, sh.pieces, sh.role_major, sh.stride, ring, SLOTS, s, 6000, 16); + if (r > best) best = r; + sum += r; + } + printf("%-44s %-36s %6.1f GB/s (best %6.1f)\n", kd.name, sh.name, sum / 3, best); + fflush(stdout); + } + if (kd.id == 0) cudaFreeHost(base); + else if (kd.id <= 4) { cudaHostUnregister(base); } + else { cudaHostUnregister(base); munmap(map, map_bytes); close(fd); } + } + return 0; +} diff --git a/scripts/profile/jobs/9001-ledger-h2d-probe.sh b/scripts/profile/jobs/9001-ledger-h2d-probe.sh new file mode 100644 index 00000000..28d49660 --- /dev/null +++ b/scripts/profile/jobs/9001-ledger-h2d-probe.sh @@ -0,0 +1,10 @@ +# claude/ledger: model-free probe, H2D DMA rate by source memory kind and copy shape (the port's 3 x 0.68 MB role-major pieces from the registered bank +# vs the Original's single ~2 MB blob from its arena). GPU otherwise idle (holder job). +source ~/work/ledger/ledger-common.sh +header 2>/dev/null | head -3 +nvidia-smi --query-gpu=pcie.link.gen.current,pcie.link.width.current,clocks.sm,clocks.mem --format=csv,noheader +timeout 600 $LD/bin/h2d_src_probe $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf 2>&1 +echo "rc=$?"; date -u +%FT%TZ +# the same probe question inside the port: the bank's anonymous Vecs with transparent huge pages (LELEKA_BANK_THP=on), traced like port-16k-off +mem_ok 30 && port_long port-16k-thp 16000 2 PREFILL-PROFILE 2 9 LELEKA_BANK_THP=on +date -u +%FT%TZ diff --git a/scripts/profile/jobs/9002-ledger-aligned-ab.sh b/scripts/profile/jobs/9002-ledger-aligned-ab.sh new file mode 100644 index 00000000..13380364 --- /dev/null +++ b/scripts/profile/jobs/9002-ledger-aligned-ab.sh @@ -0,0 +1,20 @@ +# claude/ledger: two port-only changes against the previous head, same binary (rt-ledger1), switches: +# LELEKA_PREFILL_ALIGNED_COPY=0 + LELEKA_PREFILL_GUARD_GRID=64 = previous head behaviour (arm A) +# defaults = page-aligned ring copies + full-grid QSA guards (arm C) +# LELEKA_PREFILL_GUARD_GRID=64 only = aligned copies alone (arm B) +# 1) bit gate: FNV-1a hash of the final residual R of every chunk + greedy ids, arms A and C (must be identical); +# 2) CUPTI trace of arm C (H2D GB/s of the ring copies); 3) timing, untraced, second pass of each process, A C A C B. +source ~/work/ledger/ledger-common.sh +mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; } +export BIN=$LD/bin/rt-ledger1 +A_ARM="LELEKA_PREFILL_ALIGNED_COPY=0 LELEKA_PREFILL_GUARD_GRID=64" +header +port_long hash-A 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1 $A_ARM +port_long hash-C 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1 +port_long port-16k-C 16000 2 PREFILL-PROFILE 2 9 X=1 +port_long ab-A-1 16000 2 PREFILL-PROFILE 0 9 $A_ARM +port_long ab-C-1 16000 2 PREFILL-PROFILE 0 9 X=1 +port_long ab-A-2 16000 2 PREFILL-PROFILE 0 9 $A_ARM +port_long ab-C-2 16000 2 PREFILL-PROFILE 0 9 X=1 +port_long ab-B-1 16000 2 PREFILL-PROFILE 0 9 LELEKA_PREFILL_GUARD_GRID=64 +date -u +%FT%TZ diff --git a/scripts/profile/jobs/901-ledger-port-prefill16k.sh b/scripts/profile/jobs/901-ledger-port-prefill16k.sh new file mode 100644 index 00000000..e7d6b08b --- /dev/null +++ b/scripts/profile/jobs/901-ledger-port-prefill16k.sh @@ -0,0 +1,9 @@ +# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill (chunks 8192 + 7807) of the PORT (rt-base = head 7330ddb), second pass of +# each process (pass 0 pays the one-time finite admission). A: tier off, B: expert tier on, C: tier off WITHOUT the tracer (overhead A/B). +source ~/work/ledger/ledger-common.sh +mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; } +header +port_long port-16k-off 16000 2 PREFILL-PROFILE 2 9 +port_long port-16k-on 16000 2 PREFILL-PROFILE 2 9 $PORT_TIER +port_long port-16k-off-plain 16000 2 PREFILL-PROFILE 0 9 +date -u +%FT%TZ diff --git a/scripts/profile/jobs/902-ledger-orig-prefill16k.sh b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh new file mode 100644 index 00000000..e17f9f55 --- /dev/null +++ b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh @@ -0,0 +1,9 @@ +# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill of the unmodified ORIGINAL (--serve, prompt ids of job 0708), second request +# traced (the first is the warm-up of the same process). One profiling pass per scenario, not a throughput A/B. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +header +R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R +orig_serve orig-16k-off 2 9 "--prefill 8192 --max-context 65536 --kv-resident 20480" $R +orig_serve orig-16k-on 2 9 "--prefill auto --max-context 65536 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh new file mode 100644 index 00000000..2fcede75 --- /dev/null +++ b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh @@ -0,0 +1,6 @@ +# claude/ledger: the ORIGINAL without the expert tier (job 902's off arm was refused: a native pack needs --spec T >= 2), traced, 16000 tokens, second request. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R +orig_serve orig-16k-off 2 9 "--prefill 8192 --spec 4 --max-context 65536 --kv-resident 20480" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/903-ledger-port-180k.sh b/scripts/profile/jobs/903-ledger-port-180k.sh new file mode 100644 index 00000000..0810d90d --- /dev/null +++ b/scripts/profile/jobs/903-ledger-port-180k.sh @@ -0,0 +1,6 @@ +# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the PORT (22 chunks), tier on (the job 915 configuration), trace from the start of the request. +source ~/work/ledger/ledger-common.sh +mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; } +header +port_long port-180k 180000 1 "long-smoke prompt tokens" 1 150 $PORT_TIER +date -u +%FT%TZ diff --git a/scripts/profile/jobs/904-ledger-orig-180k.sh b/scripts/profile/jobs/904-ledger-orig-180k.sh new file mode 100644 index 00000000..d8ae891c --- /dev/null +++ b/scripts/profile/jobs/904-ledger-orig-180k.sh @@ -0,0 +1,7 @@ +# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the unmodified ORIGINAL (job 916 configuration, --serve), trace from the start of the request. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +header +R=$LD/req180k.txt; { echo "GEN 16 $(cat $G/long-180k/prompt180000.ids)"; echo QUIT; } > $R +orig_serve orig-180k 1 150 "--prefill auto --max-context 262144 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/905-ledger-port-decode.sh b/scripts/profile/jobs/905-ledger-port-decode.sh new file mode 100644 index 00000000..1f9ca4ad --- /dev/null +++ b/scripts/profile/jobs/905-ledger-port-decode.sh @@ -0,0 +1,7 @@ +# claude/ledger: CUPTI timeline of the decode rounds of the PORT: 6-prompt corpus x 2 passes x 128 tokens, spec 4 + suffix 3, min_p 0.5, 2048 slots/layer, static residency. +# Window of 10 s after the 2nd finished request (the first prompt, twice), i.e. over the 2nd prompt's two requests. +source ~/work/ledger/ledger-common.sh +mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; } +header +port_corpus port-corpus 2 10 +date -u +%FT%TZ diff --git a/scripts/profile/jobs/906-ledger-orig-decode.sh b/scripts/profile/jobs/906-ledger-orig-decode.sh new file mode 100644 index 00000000..5de0bc37 --- /dev/null +++ b/scripts/profile/jobs/906-ledger-orig-decode.sh @@ -0,0 +1,6 @@ +# claude/ledger: the same corpus on the unmodified ORIGINAL (--serve, round-profile/original-requests.txt), static residency, trace window before request 3. +source ~/work/ledger/ledger-common.sh +mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; } +header +orig_serve orig-corpus 3 10 "--prefill 2048 --max-context 4096 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55 --adapt-every 0" $G/round-profile/original-requests.txt +date -u +%FT%TZ diff --git a/scripts/profile/jobs/ledger-common.sh b/scripts/profile/jobs/ledger-common.sh new file mode 100644 index 00000000..332f33e4 --- /dev/null +++ b/scripts/profile/jobs/ledger-common.sh @@ -0,0 +1,112 @@ +# Sourced by the 90x-ledger-*.sh holder jobs (copied next to them on the server, ~/work/ledger/). +# Runs the PORT (test binary) or the unmodified ORIGINAL (strata) with the CUPTI tracer injected and a trigger-file window. +set -uo pipefail +export PATH=$HOME/cuda-toolkits/13.2.2/bin:$PATH RUST_BACKTRACE=1 +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +A=$HOME/leleka-gates/assets +G=$HOME/work/gpu-runs +LD=$HOME/work/ledger +OUT=$LD/traces; mkdir -p $OUT +CUPTI_LIB=$HOME/work/cupti-trace/libleleka_cupti_trace.so +TRIG=$LD/cupti.trigger +ORIG=${ORIG:-$HOME/work/numerics-orig/build/strata} +PROFILE=$G/baseline/profile.bin +T_LONG=backend::original_serve_smoke::original_serve_long_context_streamed_kv_smoke +T_CORPUS=original_serve_smoke_prompt_decode +mkdir -p $G/mtp-staging-own; chmod 700 $G/mtp-staging-own +export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json +export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf +export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own +export LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 LELEKA_BRINGUP_TRACE=1 LELEKA_SERVE_PROFILE=1 +PORT_TIER="LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$PROFILE LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55" +BIN=${BIN:-$LD/bin/rt-base} + +mem_ok() { local avail; avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"; [ "${avail:-0}" -ge "$1" ]; } + +# trig LABEL SECONDS OUTNAME: ask the injected tracer for one window (same protocol as the daemon's trigger file) +trig() { + rm -f $TRIG.active $TRIG.done $TRIG.stop + printf '{"seconds": %s, "out": "%s/%s", "label": "%s"}\n' "$2" "$OUT" "$3" "$1" > $TRIG.tmp && mv $TRIG.tmp $TRIG + for _ in $(seq 100); do [ -e $TRIG.active ] && return 0; sleep 0.05; done + echo "TRIGGER-NOT-TAKEN $1" +} +trig_stop() { touch $TRIG.stop; } +stamp() { perl -MTime::HiRes=time -ne 'BEGIN{$|=1} printf "%.3f %s", time, $_'; } +header() { date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,clocks.max.sm --format=csv,noheader; sha256sum $BIN $CUPTI_LIB; } + +# port_long LABEL TOKENS REPEAT TRIG_LINE_REGEX TRIG_AFTER_N WINDOW_S [ENV=V ...] +# one model process of the port's long-context smoke (chunk 8192, INT8 KV streamed, 16 new tokens); the tracer window starts +# when the TRIG_AFTER_N-th line matching TRIG_LINE_REGEX has been printed. TRIG_AFTER_N=0: no window (tracer not injected). +port_long() { + local label=$1 toks=$2 rep=$3 re=$4 after=$5 win=$6; shift 6 + local inj=() + [ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== port $label tokens=$toks repeat=$rep trigger=$re#$after win=${win}s: $*"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + mkdir -p $G/ledger-ids + local n=0 + env "${inj[@]}" LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes LELEKA_ORIGINAL_SERVE_LONG_TOKENS=$toks LELEKA_ORIGINAL_SERVE_LONG_REPEAT=$rep \ + LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=16 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192 \ + LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 "$@" \ + $BIN --ignored --exact --test-threads=1 --nocapture $T_LONG 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do + case "$line" in *"$re"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac + case "$line" in *PREFILL-PROFILE*|*PREFILL-R*|*long-smoke*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac + done + echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ +} + +# port_corpus LABEL TRIG_AFTER_N WINDOW_S [ENV=V ...]: the 6 prompts of prompts.txt, each served twice, 128 new tokens, static residency; +# the window starts after the N-th "DBG profile request" line (a finished request). +port_corpus() { + local label=$1 after=$2 win=$3; shift 3 + local inj=() + [ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== port $label corpus trigger=after request #$after win=${win}s: $*"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + local n=0 + env "${inj[@]}" LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$G/prompts.txt LELEKA_SMOKE_MAX_NEW=128 LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=2 \ + LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=4096 LELEKA_ORIGINAL_SERVE_CAPACITY=2048 LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_GRAPH_EXEC_REUSE=off \ + LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 $PORT_TIER "$@" \ + $BIN --ignored --test-threads=1 --nocapture $T_CORPUS 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do + case "$line" in *"DBG profile request"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac + case "$line" in *"DBG profile request"*|*"DBG timing"*|*"DBG tier request"*|*"smoke:"*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac + done + echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ +} + +# orig_serve LABEL STRATA_FLAGS... -- REQUEST_FILE_LINES... : the unmodified Original in --serve mode; requests are fed through a FIFO +# one at a time; before request number TRIG_BEFORE a tracer window of WINDOW_S seconds is requested (TRIG_BEFORE=0: none). +# usage: orig_serve LABEL TRIG_BEFORE WINDOW_S "flags" reqfile +orig_serve() { + local label=$1 before=$2 win=$3 flags=$4 req=$5 + local inj=() + [ "$before" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== original $label trigger before request #$before win=${win}s: $flags"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + local d=$OUT/$label.orig; mkdir -p $d; rm -f $d/fifo; mkfifo $d/fifo + local kar=${KAR_PATH:-/proc/self/fd/${LELEKA_STRA169_KAR_FD:-0}} + env "${inj[@]}" STRATA_DECODE_TIMING=1 $ORIG --pack $A/data/iq3_s --native $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf \ + --ple-gguf $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf --ple-kar $kar --ple-kar-level 2 \ + --serve --mtp $A/data/mtp-rt --kv int8 $flags \ + < $d/fifo > $d/out.txt 2> $d/err.txt & + local pid=$! + exec 7>$d/fifo + for _ in $(seq 1200); do grep -q "^READY" $d/out.txt 2>/dev/null && break; kill -0 $pid 2>/dev/null || break; sleep 0.5; done + grep -q "^READY" $d/out.txt || { echo "original did not become ready"; tail -3 $d/err.txt | cut -c1-300; exec 7>&-; kill $pid 2>/dev/null; return 1; } + local i=0 line + while IFS= read -r line; do + i=$((i+1)) + [ "$line" = QUIT ] && break + [ "$before" -gt 0 ] && [ $i -eq "$before" ] && trig "$label" "$win" "$label" + echo "$(date +%s.%N) request $i sent" + printf '%s\n' "$line" >&7 + for _ in $(seq 6000); do [ "$(grep -c '^DONE' $d/out.txt)" -ge $i ] && break; kill -0 $pid 2>/dev/null || break; sleep 0.2; done + echo "$(date +%s.%N) request $i done: $(grep '^DONE' $d/out.txt | sed -n ${i}p | cut -c1-120)" + done < $req + echo QUIT >&7; exec 7>&- + wait $pid; echo "rc=$? original=$label"; date -u +%FT%TZ + grep -E "prefill [0-9]+ tokens|PCIe probe" $d/err.txt | cut -c1-300 + grep -E "strata decode|strata serve: (prompt|decode)" $d/err.txt | cut -c1-600 | head -40 + grep "^DONE" $d/out.txt | awk '{printf "ORIG-DONE produced %s prompt_ms %s decode_ms %s -> %.2f tok/s\n", $2, $4, $5, $2*1000/$5}' +} diff --git a/scripts/profile/lct.py b/scripts/profile/lct.py new file mode 100644 index 00000000..502aabfc --- /dev/null +++ b/scripts/profile/lct.py @@ -0,0 +1,247 @@ +"""Loader and interval helpers for CUPTI trace directories written by tools/cupti-trace (libleleka_cupti_trace.so). + +Pure Python (no numpy): `struct.iter_unpack` over the fixed-size record files. All times are CUPTI ns. +""" +import os +import re +import struct +from collections import namedtuple + +K = namedtuple("K", "start end dev stream corr graph node name gx gy gz bx by bz sshm dshm regs launch pad") +C = namedtuple("C", "start end bytes dev stream corr graph node ckind skind dkind flags apicorr") +M = namedtuple("M", "start end bytes dev stream corr graph mkind pad") +Y = namedtuple("Y", "start end corr stream event type ctx ret") +A = namedtuple("A", "start end corr thread name ret domain pad") +G = namedtuple("G", "start end corr graph dev stream") + +# struct formats mirror the C++ side's #pragma pack(1) records: 80, 56, 44, 40, 36, 32 bytes +FMT = { + "kernel.bin": ("= len(ids): + break + except Exception: + out = None + if not out: + return + try: + with open(cache, "w", encoding="utf-8", newline="\n") as f: + for i, d in zip(ids, out): + f.write("%d\t%s\n" % (i, d.strip())) + except OSError: + for i, d in zip(ids, out): + self.names[i] = d.strip() + return + for line in open(cache, encoding="utf-8", errors="replace"): + i, _, n = line.rstrip("\n").partition("\t") + if i.isdigit() and n: + self.names[int(i)] = n + + def _load(self, fn): + p = os.path.join(self.path, fn) + if not os.path.exists(p) or os.path.getsize(p) == 0: + return [] + fmt, nt = FMT[fn] + sz = struct.calcsize(fmt) + with open(p, "rb") as f: + data = f.read() + data = data[: len(data) // sz * sz] + lo, hi = self._lo, self._hi + if lo is None: + return [nt(*t) for t in struct.iter_unpack(fmt, data)] + return [nt(*t) for t in struct.iter_unpack(fmt, data) if t[1] >= lo and t[0] <= hi] + + def kname(self, r): + return self.names.get(r.name, "?") + + def clip(self, lo, hi): + """Keep only records overlapping [lo, hi] (CUPTI ns) and make that the window.""" + for nm in ("kernels", "copies", "memsets", "syncs", "apis", "graphs"): + setattr(self, nm, [r for r in getattr(self, nm) if r.end >= lo and r.start <= hi]) + self.t0, self.t1 = lo, hi + + +def union(intervals): + """Merge [(a,b),...] into disjoint sorted [a,b] lists.""" + out = [] + for a, b in sorted(intervals): + if out and a <= out[-1][1]: + if b > out[-1][1]: + out[-1][1] = b + else: + out.append([a, b]) + return out + + +def total(ivs): + return sum(b - a for a, b in ivs) + + +def intersect_total(u1, u2): + """Total overlap of two disjoint sorted interval lists.""" + i = j = 0 + t = 0 + while i < len(u1) and j < len(u2): + a = max(u1[i][0], u2[j][0]) + b = min(u1[i][1], u2[j][1]) + if b > a: + t += b - a + if u1[i][1] < u2[j][1]: + i += 1 + else: + j += 1 + return t + + +_fam_cache = {} + + +def _strip_templates(n): + out, depth = [], 0 + args = [] + cur = [] + for ch in n: + if ch == "<": + depth += 1 + if depth == 1: + cur = [] + continue + elif ch == ">": + depth -= 1 + if depth == 0: + args.append("".join(cur)) + continue + if depth == 0: + out.append(ch) + elif depth >= 1: + cur.append(ch) + return "".join(out), args + + +def family(name): + """Short kernel family label: namespaces, parameter lists, template arguments and a trailing _kernel are dropped; the first + template argument is kept for the kernels that are one template instantiated per format (mul_mat_q, dequant_kernel, cutlass).""" + f = _fam_cache.get(name) + if f is not None: + return f + n = name.replace("(anonymous namespace)::", "") + n = re.sub(r"^(void|std::enable_if<.*?>::type)\s+", "", n) + # parameter list: the last top-level '(' ... end + depth = 0 + cut = len(n) + for k, ch in enumerate(n): + if ch == "<": + depth += 1 + elif ch == ">": + depth -= 1 + elif ch == "(" and depth == 0: + cut = k + break + n = n[:cut].strip() + base, args = _strip_templates(n) + base = base.strip() + if "::" in base: + base = base.split("::")[-1] + base = re.sub(r"_kernel$", "", base) + first = args[0].split(",")[0].strip() if args else "" + first = first.replace("(ggml_type)", "t") + if base in ("mul_mat_q", "dequant", "mul_mat_q_stream_k_fixup", "Kernel2") and first: + base = base + "<" + first[:60] + ">" + _fam_cache[name] = base or name + return _fam_cache[name] + + +def percentile(sorted_vals, p): + if not sorted_vals: + return 0.0 + return sorted_vals[min(len(sorted_vals) - 1, int(p / 100.0 * len(sorted_vals)))] + + +def chunk_windows(full_log, trace_dir): + """Chunk windows (ms from the trace window start) of the stamped PREFILL-PROFILE lines of a job log (