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/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 f4c2e65b..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() { @@ -646,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()?; @@ -872,15 +933,16 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { // 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)?; @@ -982,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 @@ -1043,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/mtp_original_full_ffi.rs b/crates/cuda-driver/src/mtp_original_full_ffi.rs index ca6eb50f..a5304b94 100644 --- a/crates/cuda-driver/src/mtp_original_full_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_full_ffi.rs @@ -57,6 +57,7 @@ mod enabled { type FunctionAttr = unsafe extern "C" fn(*mut c_void,i32,i32)->i32; type Unload = unsafe extern "C" fn(*mut c_void) -> i32; type CopySync = unsafe extern "C" fn(u64,u64,usize)->i32; + type StreamSync = unsafe extern "C" fn(*mut c_void)->i32; type Copy = unsafe extern "C" fn(u64,u64,usize,*mut c_void)->i32; type C2D = unsafe extern "C" fn(*const Copy2D,*mut c_void)->i32; type Memset = unsafe extern "C" fn(u64,u8,usize)->i32; @@ -117,6 +118,7 @@ mod enabled { unload: Unload, copy: Copy, copy_sync:CopySync, + stream_sync:StreamSync, h2d: H2D, memset:Memset, c2d:C2D, @@ -163,6 +165,7 @@ mod enabled { unload: sym!(l, c"cuModuleUnload", Unload), copy: sym!(l,c"cuMemcpyAsync",Copy), copy_sync:sym!(l,c"cuMemcpy",CopySync), + stream_sync:sym!(l,c"cuStreamSynchronize",StreamSync), h2d: sym!(l,c"cuMemcpyHtoDAsync_v2",H2D), memset:sym!(l,c"cuMemsetD8_v2",Memset), c2d:sym!(l,c"cuMemcpy2DAsync_v2",C2D), @@ -294,6 +297,10 @@ mod enabled { // SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host destinations; // a device->device copy is merely ordered on the legacy default stream (callers: mtp_original_full_round.rs). pub(crate) fn copy_sync(&self,dst:u64,src:u64,n:usize)->Result<()>{if dst==0||src==0||n==0{return Err(Error::InvalidSize);}check("cuMemcpy",unsafe{(self.copy_sync)(dst,src,n)})} + // SAFETY: stream handle 0 is the legacy default stream, which `copy_sync` (cuMemcpy) uses; synchronizing it returns once every earlier + // legacy-stream operation (the D2D copies) has completed, and it does NOT wait for work queued on non-blocking streams (a pending + // verifier commit), unlike cuCtxSynchronize. After it returns, a launch on a non-blocking stream is ordered after the copies by the host. + pub(crate) fn fence_legacy_stream(&self)->Result<()>{check("cuStreamSynchronize",unsafe{(self.stream_sync)(std::ptr::null_mut())})} // SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered on the legacy // default stream but asynchronous with respect to the host; its only caller (FullOwned::new_internal) fences it. pub(crate) fn zero(&self,dst:u64,n:usize)->Result<()>{if dst==0||n==0{return Err(Error::InvalidSize);}check("cuMemsetD8_v2",unsafe{(self.memset)(dst,0,n)})} @@ -368,6 +375,7 @@ impl Module { } pub(crate) fn copy(&self,_:u64,_:u64,_:usize,_:usize)->Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn copy_sync(&self,_:u64,_:u64,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} + pub(crate) fn fence_legacy_stream(&self)->Result<()>{Err(Error::UnsupportedPlatform)} pub(crate) fn zero(&self,_:u64,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} pub(crate) fn copy2d(&self,_:&Copy2D,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} pub(crate) fn copy_host(&self,_dst:u64,_source:&[u8],_stream:usize)->Result<()> {Err(Error::UnsupportedPlatform)} diff --git a/crates/cuda-driver/src/mtp_original_full_round.rs b/crates/cuda-driver/src/mtp_original_full_round.rs index 0cca42ec..4d97cdd1 100644 --- a/crates/cuda-driver/src/mtp_original_full_round.rs +++ b/crates/cuda-driver/src/mtp_original_full_round.rs @@ -197,6 +197,40 @@ impl<'ctx> OriginalMtpFullForward<'ctx>{ } } +/// Bytes of one verifier residual row (10240 f32). +const RESIDUAL_ROW_BYTES:usize=40960; + +/// The copies of `stage_first_residual_direct`, then the fence. `cuMemcpy` between device addresses is ordered only on the legacy default +/// stream and does not block the host; the draft graph that reads the rows runs on a NON-blocking stream, which the legacy stream does not +/// order against, so without the fence the graph could read a row before its copy finished (cross-stream race, docs/memory-safety-unsafe.md +/// section 6.2). The fence is `cuStreamSynchronize(0)`: it waits for these copies only, not for a verifier commit queued on another stream. +/// A failed copy skips the fence (the caller poisons the context); a failed fence is an error. +fn copy_rows_then_fence(rows:usize,dst:u64,src:u64,copy:&mut dyn FnMut(u64,u64,usize)->Result<()>,fence:&mut dyn FnMut()->Result<()>)->Result<()>{ + for row in 0..rows{copy(dst+(row*RESIDUAL_ROW_BYTES)as u64,src,RESIDUAL_ROW_BYTES)?;} + fence() +} + +#[cfg(test)] +mod stage_fence_tests{ + use super::*; + #[test] + fn the_fence_comes_after_the_last_copy_and_only_once(){ + let log=std::cell::RefCell::new(Vec::::new()); + copy_rows_then_fence(3,0x1000,0x2000,&mut |d,s,n|{log.borrow_mut().push(format!("copy {d:#x}<-{s:#x} {n}"));Ok(())},&mut ||{log.borrow_mut().push("fence".into());Ok(())}).unwrap(); + assert_eq!(*log.borrow(),vec!["copy 0x1000<-0x2000 40960","copy 0xb000<-0x2000 40960","copy 0x15000<-0x2000 40960","fence"]); + } + #[test] + fn a_failed_copy_skips_the_fence_and_a_failed_fence_is_an_error(){ + let fenced=std::cell::Cell::new(0); + let r=copy_rows_then_fence(4,1,2,&mut |d,_,_|if d>1+40960{Err(Error::InvalidSize)}else{Ok(())},&mut ||{fenced.set(fenced.get()+1);Ok(())}); + assert!(r.is_err()&&fenced.get()==0,"no fence after a failed copy"); + let r=copy_rows_then_fence(1,1,2,&mut |_,_,_|Ok(()),&mut ||Err(Error::InvalidProjectionShape)); + assert!(matches!(r,Err(Error::InvalidProjectionShape)),"a failed fence must not read as success"); + let r=copy_rows_then_fence(0,1,2,&mut |_,_,_|panic!("no rows, no copies"),&mut ||Ok(())); + assert!(r.is_ok()); + } +} + impl<'ctx> OriginalMtpFullForward<'ctx>{ /// Literal mtp.cpp834: actual synchronous D2D into Verifier's OWN R bank, /// before capture. Repeated scratch rows do not become verification results. @@ -209,7 +243,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx>{ let staged=StagedSource{window,selection,accepted_row:0,next_j:0,ready:false,rows,first_repeat:true};staged.validate(o.context)?; *o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?=Some(staged); let g=o.context.enter().inspect_err(|_|{o.failed.set(true);o.context.poison();o.context.retain_driver();})?; - let copies=(||{for row in 0..rows{o.modules[13].copy_sync(dst+(row*40960)as u64,src,40960)?;}Ok(())})();let pop=g.finish(); + let copies=copy_rows_then_fence(rows,dst,src,&mut |d,s,n|o.modules[13].copy_sync(d,s,n),&mut ||o.modules[13].fence_legacy_stream());let pop=g.finish(); if copies.is_err()||pop.is_err(){o.failed.set(true);o.context.poison();o.context.retain_driver();}combine(copies,pop)?; o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::InvalidQwenShape)?.ready=true;Ok(()) } 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/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/deploy/src/config.rs b/crates/deploy/src/config.rs index e9a0cc10..f7167fc4 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -180,6 +180,10 @@ impl RunConfig { "original".into(), "--expert-source".into(), profile.expert_source.as_str().into(), + // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine + // drafts over the full 248k-row head, about 0.2 ms more per draft step. + "--mtp-rt-dir".into(), + paths.mtp_pack().display().to_string(), ]); if let Some(value) = profile.prefill_capacity { args.extend(["--original-prefill-capacity".into(), value.to_string()]); @@ -341,7 +345,7 @@ mod tests { assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}"); assert!(text.contains("--gpu 0 --gpu-budget 25769803776 --context-tokens 262144")); assert!(text.contains("--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json")); - assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident")); + assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident --mtp-rt-dir /data/leleka/data/mtp-rt")); // The engine parser reads the first 14 arguments positionally. assert_eq!(args[..14].len(), 14); assert_eq!(args[12], "--context-tokens"); diff --git a/crates/leleka-memory/src/census.rs b/crates/leleka-memory/src/census.rs index f61a4980..bf0924a1 100644 --- a/crates/leleka-memory/src/census.rs +++ b/crates/leleka-memory/src/census.rs @@ -11,6 +11,10 @@ use serde::Serialize; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] pub struct Census { pub rss: u64, + /// `RssAnon` / `RssFile` / `RssShmem` of `/proc/self/status`: a leak is an anonymous or shmem slope; file pages are reclaimable. + pub rss_anon: u64, + pub rss_file: u64, + pub rss_shmem: u64, pub swap: u64, pub pinned: u64, pub locked: u64, @@ -29,6 +33,9 @@ impl Census { let f = HostFacts::probe(src); Self { rss: f.status.vm_rss.unwrap_or(0), + rss_anon: f.status.rss_anon.unwrap_or(0), + rss_file: f.status.rss_file.unwrap_or(0), + rss_shmem: f.status.rss_shmem.unwrap_or(0), swap: f.status.vm_swap.unwrap_or(0), pinned: f.status.vm_pin.unwrap_or(0), locked: f.status.vm_lck.unwrap_or(0), @@ -140,6 +147,60 @@ pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatRep FlatReport { samples: series.len(), warmup, drifts, ok } } +/// An ordinary-least-squares line through `(x, y)` with its 95% confidence interval, and the Theil-Sen slope (the median of the +/// pairwise slopes: robust against the steps a cache filling or a request in flight puts into a memory series). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct SlopeFit { + pub n: usize, + pub slope: f64, + pub ci95_low: f64, + pub ci95_high: f64, + pub theil_sen: f64, + /// R squared of the OLS line. + pub r2: f64, +} + +impl SlopeFit { + /// The interval contains zero: no growth is distinguishable from none. + pub fn includes_zero(&self) -> bool { + self.ci95_low <= 0.0 && self.ci95_high >= 0.0 + } +} + +/// Fit `y` against `x`; `None` with fewer than 8 points or no spread in `x`. The interval uses the normal quantile 1.96 (n is in the +/// hundreds) and treats samples as independent, which a slowly drifting series is not: read it as a lower bound of the uncertainty and +/// look at `theil_sen` next to it. +pub fn fit_slope(points: &[(f64, f64)]) -> Option { + let n = points.len(); + if n < 8 { + return None; + } + let nf = n as f64; + let (mx, my) = (points.iter().map(|p| p.0).sum::() / nf, points.iter().map(|p| p.1).sum::() / nf); + let sxx: f64 = points.iter().map(|p| (p.0 - mx).powi(2)).sum(); + if sxx <= 0.0 { + return None; + } + let sxy: f64 = points.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum(); + let slope = sxy / sxx; + let intercept = my - slope * mx; + let sse: f64 = points.iter().map(|p| (p.1 - intercept - slope * p.0).powi(2)).sum(); + let syy: f64 = points.iter().map(|p| (p.1 - my).powi(2)).sum(); + let se = (sse / (nf - 2.0) / sxx).sqrt(); + let mut slopes = Vec::with_capacity(n * (n - 1) / 2); + for i in 0..n { + for j in i + 1..n { + let dx = points[j].0 - points[i].0; + if dx != 0.0 { + slopes.push((points[j].1 - points[i].1) / dx); + } + } + } + slopes.sort_by(f64::total_cmp); + let theil_sen = slopes.get(slopes.len() / 2).copied().unwrap_or(0.0); + Some(SlopeFit { n, slope, ci95_low: slope - 1.96 * se, ci95_high: slope + 1.96 * se, theil_sen, r2: if syy > 0.0 { 1.0 - sse / syy } else { 0.0 } }) +} + #[cfg(test)] mod tests { use super::*; @@ -195,6 +256,22 @@ mod tests { assert!(!check_flat(&l, 10, &Tolerances::default()).ok); } + #[test] + fn the_slope_fit_finds_a_leak_and_a_plateau() { + // 4 KiB per request leaking, with deterministic noise + let leak: Vec<(f64, f64)> = (0..400).map(|i| (i as f64, 1e9 + 4096.0 * i as f64 + ((i * 7919) % 2000) as f64 * 1024.0)).collect(); + let fit = fit_slope(&leak).unwrap(); + assert!((fit.slope - 4096.0).abs() < 4096.0 * 0.2, "{fit:?}"); + assert!(!fit.includes_zero() || fit.ci95_low < 4096.0, "{fit:?}"); + assert!((fit.theil_sen - 4096.0).abs() < 4096.0 * 0.2, "{fit:?}"); + let flat: Vec<(f64, f64)> = (0..400).map(|i| (i as f64, 1e9 + ((i * 7919) % 2000) as f64 * 1024.0)).collect(); + let fit = fit_slope(&flat).unwrap(); + assert!(fit.includes_zero() || fit.slope.abs() < 300.0, "{fit:?}"); + assert!(fit.theil_sen.abs() < 300.0, "{fit:?}"); + assert!(fit_slope(&flat[..5]).is_none()); + assert!(fit_slope(&vec![(1.0, 2.0); 20]).is_none(), "no spread in x"); + } + #[test] fn too_few_samples_is_not_a_pass() { let r = check_flat(&series(12, |_| base()), 10, &Tolerances::default()); diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index 67332cb3..d5ac0ddb 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -213,6 +213,8 @@ struct Inner { counters: Counters, ledger: Ledger, vram: Mutex>, + /// (predicted available after the fixed footprint, available measured after the stack opened) + post_load: Mutex>, #[cfg(all(target_os = "linux", target_pointer_width = "64"))] guarded: Mutex>, stop: AtomicBool, @@ -261,6 +263,7 @@ impl Governor { counters: Counters::default(), ledger: Ledger::new(), vram: Mutex::new(None), + post_load: Mutex::new(None), #[cfg(all(target_os = "linux", target_pointer_width = "64"))] guarded: Mutex::new(None), stop: AtomicBool::new(false), @@ -385,6 +388,25 @@ impl Governor { } } + /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the + /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). + pub fn note_post_load(&self, actual_available: Option) -> Option { + let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; + let actual = actual_available?; + *lock(&self.inner.post_load) = Some((predicted, actual)); + let error = i128::from(actual) - i128::from(predicted); + let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); + if error.unsigned_abs() > 512 * MIB { + self.log(&format!( + "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", + gib(predicted), + gib(actual), + error >> 20 + )); + } + Some(error) + } + pub fn set_plan(&self, plan: Plan) { self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); *lock(&self.inner.plan) = Some(plan); @@ -783,6 +805,7 @@ impl Governor { "inventory": self.inventory().to_json(), "ledger": self.inner.ledger.to_json(), "vram": &*lock(&self.inner.vram), + "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p) as i128})), "transitions": &*lock(&self.inner.transitions), }) } diff --git a/crates/leleka-memory/src/heap.rs b/crates/leleka-memory/src/heap.rs index caf18730..5ab93684 100644 --- a/crates/leleka-memory/src/heap.rs +++ b/crates/leleka-memory/src/heap.rs @@ -5,10 +5,48 @@ //! host at all. `trim` hands the free pages of every arena back (`malloc_trim(0)`), and is called after an eviction. On other //! allocators or platforms it does nothing. +/// `LELEKA_MEMORY_NO_TRIM=1` turns `trim` into a no-op (for the A/B of what the trim buys). +fn trim_disabled() -> bool { + static OFF: std::sync::OnceLock = std::sync::OnceLock::new(); + *OFF.get_or_init(|| std::env::var("LELEKA_MEMORY_NO_TRIM").is_ok_and(|v| v == "1")) +} + +/// glibc allocator totals (`mallinfo2`, summed over all arenas), bytes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct HeapStats { + /// Non-mmapped space obtained from the system (heap arenas). + pub arena: u64, + /// Bytes in use by the program. + pub in_use: u64, + /// Free bytes the allocator holds inside its arenas (what a trim can give back, and what fragmentation hides). + pub free: u64, + /// Bytes in mmapped chunks (large allocations: returned to the OS at free). + pub mmapped: u64, + /// Top-most releasable space. + pub releasable: u64, +} + +/// Allocator statistics, `None` off glibc. +#[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))] +#[allow(unsafe_code)] +pub fn stats() -> Option { + // SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters under its locks. + let m = unsafe { libc::mallinfo2() }; + Some(HeapStats { arena: m.arena as u64, in_use: m.uordblks as u64, free: m.fordblks as u64, mmapped: m.hblkhd as u64, releasable: m.keepcost as u64 }) +} + +#[cfg(not(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64")))] +pub fn stats() -> Option { + None +} + /// Return free heap pages to the OS. Returns whether anything was attempted. #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))] #[allow(unsafe_code)] pub fn trim() -> bool { + if trim_disabled() { + return false; + } // SAFETY: `malloc_trim` takes no pointers; it walks the allocator's own free lists under the allocator's locks and releases whole // free pages with madvise. It is safe to call from any thread at any time. unsafe { @@ -32,5 +70,8 @@ mod tests { drop(block); let attempted = super::trim(); assert_eq!(attempted, cfg!(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))); + if let Some(s) = super::stats() { + assert!(s.in_use > 0 && s.arena + s.mmapped > 0, "{s:?}"); + } } } diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs index b7251d14..65b77fa3 100644 --- a/crates/leleka-memory/src/plan.rs +++ b/crates/leleka-memory/src/plan.rs @@ -29,7 +29,8 @@ pub struct Policy { /// Below this new requests are refused with 503 `memory_pressure`. pub hard_floor: u64, /// Slack kept on top of `soft_floor` after the fixed footprint for the transients of one request - /// (a conversation checkpoint is ~118 MB, a prefix node state ~127 MB, import staging). + /// (a conversation checkpoint is ~118 MB, a prefix node state ~127 MB, import staging) and for lazy growth the plan does not model. + /// It is also the margin above the soft floor at which the caches stop admitting (see `Policy::admit_floor`). pub reserve: u64, /// Leaving a level needs this much margin above its threshold. pub hysteresis: u64, @@ -55,12 +56,17 @@ pub struct Policy { } impl Policy { + /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`. + pub fn admit_floor(&self) -> u64 { + self.soft_floor.saturating_add(self.reserve) + } /// 4 GiB soft / 2 GiB hard floors (more on very large hosts), 75% of the elastic memory to an auto cache. pub fn for_host(mem_total: u64, laptop: bool) -> Self { Self { soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB), hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB), - reserve: GIB, + // 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in the real Codex CRM session (job 945) + reserve: 2 * GIB, hysteresis: GIB, cache_share_percent: 75, prefix_cap: if laptop { 24 * GIB } else { 96 * GIB }, @@ -559,8 +565,13 @@ mod tests { assert_eq!(auto_prefix_budget(Some(g(5)), &p, 0), 0); // job 922: 22 GiB available at open let b = auto_prefix_budget(Some(g(22)), &p, 0); - assert!(b > g(12) && b < g(13), "{b}"); + assert!(b >= g(12) && b < g(13), "{b}"); // (22 - 4 - 2) x 75% assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b); + // the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the host sat at 7.4 GiB + // available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and takes 75% of the rest + let crm = auto_prefix_budget(Some(14_064 * MIB), &p, 0); + assert!(crm > 5 * GIB + 800 * MIB && crm < 6 * GIB + 100 * MIB, "{crm}"); + assert!(14_064 * MIB - crm > 7 * GIB + 900 * MIB, "at least ~8 GiB stays available with the cache full"); assert_eq!(auto_prefix_budget(Some(g(1000)), &p, 0), g(96)); } diff --git a/crates/leleka-runtime/src/backend_original_serve_laptop.rs b/crates/leleka-runtime/src/backend_original_serve_laptop.rs index 975d19d0..0da77a83 100644 --- a/crates/leleka-runtime/src/backend_original_serve_laptop.rs +++ b/crates/leleka-runtime/src/backend_original_serve_laptop.rs @@ -15,6 +15,11 @@ //! `LELEKA_ORIGINAL_SERVE_BUDGET_GIB` (15), `LELEKA_ORIGINAL_SERVE_KV_RESIDENT` (default window), //! `LELEKA_ORIGINAL_SERVE_RT_DIR`, and the VRAM expert tier's `LELEKA_ORIGINAL_SERVE_EXPERT_*` switches. //! +//! * laptop-opt additions: `LELEKA_LAPTOP_PREFIX_MIB` (`auto` | MiB: the cross-session prefix cache replaces the conversation +//! cache), `LELEKA_LAPTOP_SEQUENCE` (comma-separated prompt indices served in this order, `repeat` times, instead of file +//! order) and `LELEKA_LAPTOP_SOAK_S` (keep serving the sequence until this many seconds have passed, then stop at a request +//! boundary), `LELEKA_LAPTOP_SKIP_FAILED=1` (log a failed request and stop instead of panicking, for soaks). +//! //! Prints one `LAPTOP request` line per request (prompt tokens, TTFT, prompt and decode phase wall time, prefill //! and decode tok/s) and the output IDs of the first pass. Greedy, no penalties, EOS stops. //! @@ -39,12 +44,19 @@ fn number(name: &str, default: usize) -> usize { fn memory_line() -> String { let text = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); let mut out = Vec::new(); - for key in ["VmRSS:", "VmHWM:", "RssAnon:", "RssFile:", "RssShmem:", "VmLck:", "VmPin:"] { + for key in ["VmRSS:", "VmHWM:", "RssAnon:", "RssFile:", "RssShmem:", "VmLck:", "VmPin:", "VmSwap:"] { if let Some(line) = text.lines().find(|l| l.starts_with(key)) { let kib: u64 = line.split_ascii_whitespace().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0); out.push(format!("{}={}MiB", key.trim_end_matches(':'), kib / 1024)); } } + let meminfo = std::fs::read_to_string("/proc/meminfo").unwrap_or_default(); + for key in ["MemAvailable:", "SwapFree:"] { + if let Some(line) = meminfo.lines().find(|l| l.starts_with(key)) { + let kib: u64 = line.split_ascii_whitespace().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0); + out.push(format!("{}={}MiB", key.trim_end_matches(':'), kib / 1024)); + } + } out.join(" ") } @@ -110,6 +122,14 @@ fn original_serve_laptop_bench() { } config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + if let Ok(v) = env::var("LELEKA_LAPTOP_PREFIX_MIB") { + use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig}; + let budget = match v.as_str() { + "auto" => PrefixBudget::Auto, + other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_LAPTOP_PREFIX_MIB: auto or MiB") << 20), + }; + config.prefix = Some(PrefixConfig { budget, block_tokens: number("LELEKA_LAPTOP_PREFIX_BLOCK", 0), laptop: true, ..PrefixConfig::auto() }); + } eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}", config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { @@ -147,8 +167,23 @@ fn original_serve_laptop_bench() { Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); return; } - for pass in 0..repeat { - for (index, ids) in prompts.iter().enumerate() { + let sequence: Vec = env::var("LELEKA_LAPTOP_SEQUENCE") + .map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_SEQUENCE: indices")).collect()) + .unwrap_or_else(|_| (0..prompts.len()).collect()); + assert!(sequence.iter().all(|&i| i < prompts.len()), "LELEKA_LAPTOP_SEQUENCE index out of range"); + let soak_s: f64 = env::var("LELEKA_LAPTOP_SOAK_S").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SOAK_S")).unwrap_or(0.0); + let skip_failed = env::var("LELEKA_LAPTOP_SKIP_FAILED").is_ok_and(|v| v == "1"); + let served_from = std::time::Instant::now(); + let mut done_requests = 0usize; + 'passes: for pass in 0.. { + if pass >= repeat && (soak_s <= 0.0 || served_from.elapsed().as_secs_f64() >= soak_s) { + break; + } + for &index in &sequence { + if pass >= repeat && served_from.elapsed().as_secs_f64() >= soak_s { + break 'passes; + } + let ids = &prompts[index]; let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)); let mut out = Vec::new(); let begun = std::time::Instant::now(); @@ -165,11 +200,11 @@ fn original_serve_laptop_bench() { let (prompt_ms, decode_ms) = stack.last_timing(); match served { Ok(outcome) => { + done_requests += 1; let prefill = if prompt_ms > 0.0 { ids.len() as f64 * 1e3 / prompt_ms } else { 0.0 }; let decode = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 }; - eprintln!("LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} \ - decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2}; {}", - index + 1, ids.len(), out.len(), outcome.rounds, memory_line()); + eprintln!("LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2} t={:.1}; {}", + index + 1, ids.len(), out.len(), outcome.rounds, served_from.elapsed().as_secs_f64(), memory_line()); if let Some(stats) = stack.expert_tier_stats() { eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe()); } @@ -177,10 +212,15 @@ fn original_serve_laptop_bench() { eprintln!("LAPTOP output p{}: {}", index + 1, out.iter().map(|t| t.to_string()).collect::>().join(",")); } } + Err(e) if skip_failed => { + eprintln!("LAPTOP failed p{} pass={pass} after {done_requests} requests: {e:?} health={:?}; {}", index + 1, stack.health(), memory_line()); + break 'passes; + } Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()), } } } + eprintln!("LAPTOP done: {done_requests} requests in {:.1} s; {}", served_from.elapsed().as_secs_f64(), memory_line()); stack.close().expect("stack cleanup failed"); Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); } diff --git a/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs index 76703811..f6953d6d 100644 --- a/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs @@ -13,6 +13,7 @@ //! * soak: `LELEKA_MEM_REQUESTS` (220), `LELEKA_MEM_BIG` (comma list of big prompt sizes, default 100000,180000), //! `LELEKA_MEM_BIG_EVERY` (55), `LELEKA_MEM_SESSIONS` (6), `LELEKA_MEM_WARMUP` (30); //! * reader: `LELEKA_MEM_READER_FILE` (a big file, e.g. the KAR archive), `_GIB` (40), `_REQS` (6), `_NEW` (96 tokens); +//! * leak: `LELEKA_MEM_LEAK_SECS` (10800), `_SAMPLE_S` (30), `_WARMUP_PCT` (25), `_TSV` (file), `LELEKA_MEM_SESSIONS` (8), `_SESSION_CAP` (40000), `_BIG`, `_BIG_EVERY` (120); //! * shed: `LELEKA_MEM_SOFT_BELOW_MIB` / `_HARD_BELOW_MIB` (floors this far below the MemAvailable at start, 1536 / 3072), //! `LELEKA_MEM_BALLAST_MIB` (3584). //! @@ -511,6 +512,215 @@ fn original_serve_memory_smoke() { } print_report("recovered"); } + "leak" => { + // Time-bounded mixed workload for the RSS-slope question: sample every `LELEKA_MEM_LEAK_SAMPLE_S` seconds RSS split into + // anon / file / shmem, swap, meminfo (Cached, Shmem, file LRU), VRAM, the prefix store and the glibc heap, then fit the slope + // of each series against the request count after the warm-up and print it with its confidence interval. + let seconds = number("LELEKA_MEM_LEAK_SECS", 10_800) as u64; + let sample_every = number("LELEKA_MEM_LEAK_SAMPLE_S", 30) as u64; + let warm_frac = number("LELEKA_MEM_LEAK_WARMUP_PCT", 25) as f64 / 100.0; + let sessions_n = number("LELEKA_MEM_SESSIONS", 8); + let session_cap = number("LELEKA_MEM_SESSION_CAP", 40_000).min(max_context.saturating_sub(6000)); + let big = list("LELEKA_MEM_BIG", "100000,180000"); + let big_every = number("LELEKA_MEM_BIG_EVERY", 120); + let tsv_path = env::var_os("LELEKA_MEM_LEAK_TSV").map(PathBuf::from); + let mut tsv = String::from("t_s\treq\trss\trss_anon\trss_file\trss_shmem\tswap\tavail\tcached\tshmem_sys\tactive_file\tinactive_file\tvram_used\tvram_acct\tprefix_store\tmalloc_arena\tmalloc_in_use\tmalloc_free\tmalloc_mmapped\tthreads\tfds\n"); + let mut sessions: Vec> = (0..sessions_n) + .map(|s| { + let mut p = system.clone(); + p.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests.\n"))); + p.extend(filler(&tokenizer, &mut rng, 1, 1500)); + p + }) + .collect(); + let started = std::time::Instant::now(); + let mut next_sample = 0u64; + let (mut req, mut served, mut cancelled, mut refused, mut bigs, mut fresh) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); + // req, rss, anon, file, shmem, swap, vram, vram_acct, prefix, malloc_in_use, malloc_free, avail + let mut series: Vec<[f64; 12]> = Vec::new(); + while started.elapsed().as_secs() < seconds { + let s = (rng.next() as usize) % sessions_n; + let roll = rng.next() % 100; + let kind = if req > 0 && req % big_every == 0 { + "big" + } else if roll < 4 { + "overlong" + } else if roll < 12 { + "cancel" + } else if roll < 18 { + "fresh" + } else { + "normal" + }; + match kind { + "overlong" => { + let prompt_len = max_context + 16; + let shape = RequestShape { prompt_tokens: prompt_len as u64, max_new_tokens: 16, max_context: max_context as u64 }; + match governor.admit(&shape) { + Admission::Refuse(r) if r.status == 400 => refused += 1, + other => failed.push(format!("overlong {req} not refused with 400: {other:?}")), + } + } + "big" => { + let target = big[bigs % big.len()].min(max_context.saturating_sub(64)); + bigs += 1; + let mut prompt = system.clone(); + prompt.extend(tok(&format!("<|im_start|>user\nBig {req}.\n"))); + prompt.extend(filler(&tokenizer, &mut rng, 1, target.saturating_sub(prompt.len() + 8))); + prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); + match serve_one(&mut stack, &prompt, 8, eos, None, None) { + Ok(_) => served += 1, + Err(e) => failed.push(format!("big {req}: {e:?}")), + } + } + "fresh" => { + // an unshared session: its own task text, 8k..30k tokens, never seen again + fresh += 1; + let size = 8000 + (rng.next() as usize % 22_000); + let mut prompt = tok(&format!("<|im_start|>system\nIndependent agent {req}.<|im_end|>\n<|im_start|>user\nUnshared task {req}.\n")); + prompt.extend(filler(&tokenizer, &mut rng, (req % 2) as u8, size.min(max_context.saturating_sub(2000)))); + prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); + match serve_one(&mut stack, &prompt, 12, eos, None, None) { + Ok(_) => served += 1, + Err(e) => failed.push(format!("fresh {req}: {e:?}")), + } + } + _ => { + let grow = 300 + (rng.unit().powi(3) * 9000.0) as usize; + let mut next = std::mem::take(&mut sessions[s]); + next.extend(tok("shell {\"cmd\": \"cargo test\"}<|im_end|>\n<|im_start|>user\n\n")); + next.extend(filler(&tokenizer, &mut rng, (req % 2) as u8, grow)); + next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n")); + if next.len() > session_cap { + next = system.clone(); + next.extend(tok(&format!("<|im_start|>user\nTask {req}.\n"))); + next.extend(filler(&tokenizer, &mut rng, 1, 1500)); + } + let result = if kind == "cancel" { + let r = if req % 2 == 0 { serve_one(&mut stack, &next, 32, eos, Some(3), None) } else { serve_one(&mut stack, &next, 64, eos, None, Some(1)) }; + match r { + Err(ServeError::Cancelled) => { + cancelled += 1; + Ok(()) + } + Ok(_) => Ok(()), + Err(e) => Err(e), + } + } else { + serve_one(&mut stack, &next, 12, eos, None, None).map(|_| served += 1) + }; + if let Err(e) = result { + failed.push(format!("{kind} {req}: {e:?}")); + } + sessions[s] = next; + } + } + req += 1; + if stack.health().is_some() { + failed.push(format!("stack lost an owner at request {req}")); + break; + } + guard(abort_gib, "leak soak"); + let t = started.elapsed().as_secs(); + if t >= next_sample { + next_sample = t + sample_every; + governor.sample_now(); + let c = census(context.as_ref()); + let facts = governor.probe(); + let heap = leleka_memory::heap::stats().unwrap_or_default(); + let mi = &facts.meminfo; + let prefix = stack.prefix_bytes() as u64; + tsv.push_str(&format!( + "{t}\t{req}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{prefix}\t{}\t{}\t{}\t{}\t{}\t{}\n", + c.rss, + c.rss_anon, + c.rss_file, + c.rss_shmem, + c.swap, + c.available, + mi.cached.unwrap_or(0), + mi.shmem.unwrap_or(0), + mi.active_file.unwrap_or(0), + mi.inactive_file.unwrap_or(0), + c.device_used.unwrap_or(0), + c.device_accounted.unwrap_or(0), + heap.arena, + heap.in_use, + heap.free, + heap.mmapped, + c.threads, + c.fds + )); + series.push([ + req as f64, + c.rss as f64, + c.rss_anon as f64, + c.rss_file as f64, + c.rss_shmem as f64, + c.swap as f64, + c.device_used.unwrap_or(0) as f64, + c.device_accounted.unwrap_or(0) as f64, + prefix as f64, + heap.in_use as f64, + heap.free as f64, + c.available as f64, + ]); + eprintln!( + "MEM-LEAK t={t} req={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs} rss={} anon={} file={} shmem={} swap={} avail={} vram={} prefix={} malloc_in_use={} malloc_free={} malloc_arena={} mmapped={} threads={} fds={}", + c.rss >> 20, + c.rss_anon >> 20, + c.rss_file >> 20, + c.rss_shmem >> 20, + c.swap >> 20, + c.available >> 20, + c.device_used.unwrap_or(0) >> 20, + prefix >> 20, + heap.in_use >> 20, + heap.free >> 20, + heap.arena >> 20, + heap.mmapped >> 20, + c.threads, + c.fds + ); + if let Some(path) = &tsv_path { + let _ = std::fs::write(path, &tsv); + } + } + } + if let Some(path) = &tsv_path { + let _ = std::fs::write(path, &tsv); + } + // slope after the warm-up, in MiB per 1000 requests, for every series + let skip = (series.len() as f64 * warm_frac) as usize; + let tail = &series[skip.min(series.len())..]; + let names = ["rss", "rss_anon", "rss_file", "rss_shmem", "swap", "vram_used", "vram_accounted", "prefix_store", "malloc_in_use", "malloc_free", "mem_available"]; + eprintln!( + "MEM-LEAK-FIT requests={req} samples={} used_for_fit={} (after {:.0}% warm-up); slope in MiB per 1000 requests with its 95% interval (OLS) and the Theil-Sen slope", + series.len(), + tail.len(), + warm_frac * 100.0 + ); + for (k, name) in names.iter().enumerate() { + let pts: Vec<(f64, f64)> = tail.iter().map(|r| (r[0], r[k + 1])).collect(); + match leleka_memory::census::fit_slope(&pts) { + Some(f) => eprintln!( + "MEM-LEAK-FIT {name:<15} slope {:+9.3} MiB/1000req [{:+9.3}, {:+9.3}] theil-sen {:+9.3} r2 {:.3} n={} first {:.0} MiB last {:.0} MiB{}", + f.slope * 1000.0 / 1_048_576.0, + f.ci95_low * 1000.0 / 1_048_576.0, + f.ci95_high * 1000.0 / 1_048_576.0, + f.theil_sen * 1000.0 / 1_048_576.0, + f.r2, + f.n, + pts.first().map_or(0.0, |p| p.1) / 1_048_576.0, + pts.last().map_or(0.0, |p| p.1) / 1_048_576.0, + if f.includes_zero() { " (zero inside)" } else { "" } + ), + None => eprintln!("MEM-LEAK-FIT {name}: too few samples"), + } + } + eprintln!("MEM-LEAK-RESULT requests={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs}"); + print_report("leak-end"); + } "reader" => { // decode speed and the memfd's residency while a competing reader streams a big file through the page cache (what the // Original did when it read the KAR file next to the memfd): phase A without the reader, B with it, C after @@ -592,7 +802,7 @@ fn original_serve_memory_smoke() { eprintln!("MEM-READER decode tok/s mean: A {:.2} B {:.2} C {:.2} (B/A {:.3})", mean(&a), mean(&b), mean(&c), mean(&b) / mean(&a).max(1e-9)); print_report("reader-end"); } - other => panic!("LELEKA_MEM_SCENARIO: inventory | soak | shed | reader, not {other}"), + other => panic!("LELEKA_MEM_SCENARIO: inventory | soak | shed | reader | leak, not {other}"), } guard(abort_gib, "end"); eprintln!("MEM-CENSUS end {}", serde_json::to_string(&census(context.as_ref())).unwrap()); diff --git a/crates/leleka-runtime/src/backend_original_serve_replay.rs b/crates/leleka-runtime/src/backend_original_serve_replay.rs index 2bd5897d..aaeec2fa 100644 --- a/crates/leleka-runtime/src/backend_original_serve_replay.rs +++ b/crates/leleka-runtime/src/backend_original_serve_replay.rs @@ -63,6 +63,8 @@ fn original_serve_replay_smoke() { let context = Rc::new(device.create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30).expect("bounded Context unavailable")); let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); config.capacity = number("LELEKA_REPLAY_CAPACITY", 2048); + // the Original's draft vocabulary (the MTP pack directory); unset = the full head, as the daemon did without --mtp-rt-dir + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); if let Ok(mib) = env::var("LELEKA_REPLAY_PREFIX_MIB") { 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/memory_governor.rs b/crates/leleka-runtime/src/memory_governor.rs index f11713c6..6e8a85de 100644 --- a/crates/leleka-runtime/src/memory_governor.rs +++ b/crates/leleka-runtime/src/memory_governor.rs @@ -19,6 +19,9 @@ pub(crate) const CHECKPOINT_BYTES: u64 = 118 << 20; /// Replaced by the loader's own report once it has run (`ResidentExpertSourceReport::charged_bytes`). pub(crate) const RESIDENT_BANK_BYTES: u64 = 50_300_000_000; /// Pinned staging rings, the MTP pack staging, the CPU pool scratch and the empty-prompt checkpoints taken at open. +/// The same steps with the bank as a RAM copy (`--expert-source resident`): the real service (e2e job 945) took 54,771 MiB of `MemAvailable` +/// from the idle holder (68,762 -> 13,991 MiB); minus the 46.85 GiB bank and the 3.09 GiB K/V image that is 3.55 GiB for everything else. +pub(crate) const OTHER_FIXED_ESTIMATE_RESIDENT: u64 = 3686 << 20; /// Measured on the 5090 (job 911, `docs/memory-safety.md` section 3): the opening steps other than the bank and the K/V image took 2,192 MiB of /// `MemAvailable` (dense weights 946, MTP/executor pins 3,061 minus the 3,168 K/V already counted, native head 487, MoE arena 426, pool 38, ...). 2.5 GiB keeps a margin. pub(crate) const OTHER_FIXED_ESTIMATE: u64 = 2560 << 20; @@ -94,7 +97,7 @@ pub(crate) fn startup(args: &StartArgs) -> Result<&'static Governor, BackendErro } fixed.push(FixedItem::new( "rings_staging_pool_checkpoints", - OTHER_FIXED_ESTIMATE, + if args.expert_source_mapped { OTHER_FIXED_ESTIMATE } else { OTHER_FIXED_ESTIMATE_RESIDENT }, Space::HostPinned, "dense weights host side, native head, MoE arena, MTP pins, CPU pool, empty-prompt checkpoints (measured, docs/memory-safety.md section 3)", )); @@ -198,6 +201,13 @@ pub(crate) fn set_bytes(id: &str, bytes: u64) { } } +/// After the stack opened: compare the plan with the real post-load availability (logged, and in the report as `plan_check`). +pub(crate) fn post_open() { + if let Some(g) = Governor::global() { + g.note_post_load(g.available_now()); + } +} + /// The report, freshly rendered (`None` before the governor exists). The status surface serves the sampler's published copy; the /// smokes want the state at this very moment. #[allow(dead_code)] 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/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 5237cd4e..b751b10d 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -369,7 +369,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { .unwrap_or_else(|| prefix_config.resolve_budget(available)); let mut prefix_config = prefix_config.clone(); if let Some(g) = leleka_memory::Governor::global() { - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().soft_floor); + // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); } let prefix_config = &prefix_config; if bytes == 0 { @@ -471,6 +472,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { embedding, }; this.register_memory_classes(); + crate::memory_governor::post_open(); if let Some(governor) = leleka_memory::Governor::global() { governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): {}", governor.inventory().table())); 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/crates/tokenizer/examples/long_prompts.rs b/crates/tokenizer/examples/long_prompts.rs new file mode 100644 index 00000000..89700001 --- /dev/null +++ b/crates/tokenizer/examples/long_prompts.rs @@ -0,0 +1,69 @@ +//! Build long chat prompts of exact token counts for the laptop benches (docs/laptop-profile.md): one +//! comma-separated token-ID line per requested size, written to `OUT_DIR/prompt-.ids`. +//! +//! `cargo run -p leleka-tokenizer --example long_prompts -- TOKENIZER_DIR CORPUS.txt OUT_DIR 8192 32768 ...` +//! +//! The prompt is one Qwen user turn (thinking off): a short preamble, a slice of the corpus (any text; the +//! benches use this repository's sources and documents, an agent-shaped context) cut so that the whole prompt has +//! exactly the requested number of tokens, and a closing question. Token boundaries between the three parts +//! are not merged (each part is encoded alone), which is irrelevant for throughput measurements. + +use std::{env, fs, path::Path, process::ExitCode}; + +use leleka_tokenizer::Tokenizer; + +const PREAMBLE: &str = "<|im_start|>user\nBelow is part of a code base with its documentation. Read it, then answer the question at the end.\n\n"; +const QUESTION: &str = "\n\nQuestion: In four or five sentences, which component of the text above looks the most performance critical, and why? Mention one concrete risk.<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"; + +fn main() -> ExitCode { + let args: Vec = env::args().collect(); + if args.len() < 5 { + eprintln!("usage: long_prompts TOKENIZER_DIR CORPUS.txt OUT_DIR TOKENS..."); + return ExitCode::from(2); + } + let tokenizer = match Tokenizer::from_assets(Path::new(&args[1])) { + Ok(t) => t, + Err(e) => { + eprintln!("long_prompts: tokenizer: {e}"); + return ExitCode::FAILURE; + } + }; + let corpus = match fs::read_to_string(&args[2]) { + Ok(t) => t, + Err(e) => { + eprintln!("long_prompts: {}: {e}", args[2]); + return ExitCode::FAILURE; + } + }; + let out_dir = Path::new(&args[3]); + if let Err(e) = fs::create_dir_all(out_dir) { + eprintln!("long_prompts: {}: {e}", args[3]); + return ExitCode::FAILURE; + } + let encode = |text: &str, special: bool| tokenizer.encode(text, special).map_err(|e| format!("encode: {e}")); + let run = || -> Result<(), String> { + let head = encode(PREAMBLE, true)?; + let tail = encode(QUESTION, true)?; + let body = encode(&corpus, false)?; + eprintln!("long_prompts: corpus {} bytes = {} tokens", corpus.len(), body.len()); + for size in &args[4..] { + let size: usize = size.parse().map_err(|_| format!("bad size {size}"))?; + let room = size.checked_sub(head.len() + tail.len()).ok_or("size below the fixed parts")?; + if room > body.len() { + return Err(format!("corpus has {} tokens, {size} needs {room}", body.len())); + } + let ids: Vec = head.iter().chain(&body[..room]).chain(&tail).map(u32::to_string).collect(); + let path = out_dir.join(format!("prompt-{size}.ids")); + fs::write(&path, ids.join(",") + "\n").map_err(|e| format!("{}: {e}", path.display()))?; + eprintln!("long_prompts: {} ({} tokens)", path.display(), ids.len()); + } + Ok(()) + }; + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("long_prompts: {e}"); + ExitCode::FAILURE + } + } +} diff --git a/docs/e2e-data/943b-analysis.txt b/docs/e2e-data/943b-analysis.txt new file mode 100644 index 00000000..5fcc17fb --- /dev/null +++ b/docs/e2e-data/943b-analysis.txt @@ -0,0 +1,68 @@ +== Session 943b-codex-ttt: 51 generations in strata-next.log, 51 prefill phases in inference.log, 0 join mismatches + +== Time shares (first request start to last request end = 918 s) + time to first text (prefill + first token) 111.3 s 12.1 % + decode after the first token 788.1 s 85.9 % + between requests (agent + tools) 18.4 s 2.0 % + of which command execution seen in Codex events 11.7 s 1.3 % + queue wait: 0 by construction (one client, one generation at a time; strata-next /metrics queue_used was 0) + +== HEADLINE: weighted decode tok/s over the whole session + 71.7 tok/s = 56502 tokens after the first / 788.1 s decode time (51 requests; per-request median 68.5) + reference lines (earlier vanilla Strata Codex tic-tac-toe runs, 256K, INT8 K+V, same host): native 115.7 tok/s (about 110 at 180k fill), KAR PLE 150.1-150.3 tok/s (about 160); 98-99 % of CLI input tokens cached + engine tokens per verify round (accepted drafts + 1), all requests: 2.92 + +== Context growth (prompt tokens per request) + requests 1- 4: prompt avg 10862 max 12484 reused avg 7737 re-prefilled avg 3124 ttft avg 3.87s + requests 5- 8: prompt avg 19602 max 22206 reused avg 17167 re-prefilled avg 2435 ttft avg 2.48s + requests 9- 12: prompt avg 25546 max 27159 reused avg 24303 re-prefilled avg 1243 ttft avg 1.96s + requests 13- 16: prompt avg 32404 max 34697 reused avg 30514 re-prefilled avg 1889 ttft avg 2.40s + requests 17- 20: prompt avg 37336 max 39870 reused avg 36038 re-prefilled avg 1298 ttft avg 1.96s + requests 21- 24: prompt avg 43605 max 45730 reused avg 42135 re-prefilled avg 1470 ttft avg 2.07s + requests 25- 28: prompt avg 50743 max 52772 reused avg 48977 re-prefilled avg 1765 ttft avg 2.23s + requests 29- 32: prompt avg 55878 max 60446 reused avg 53955 re-prefilled avg 1923 ttft avg 2.25s + requests 33- 36: prompt avg 62430 max 63592 reused avg 61638 re-prefilled avg 791 ttft avg 1.61s + requests 37- 40: prompt avg 67516 max 69723 reused avg 65978 re-prefilled avg 1537 ttft avg 1.85s + requests 41- 44: prompt avg 73245 max 75340 reused avg 71836 re-prefilled avg 1409 ttft avg 1.82s + requests 45- 48: prompt avg 78389 max 79745 reused avg 77283 re-prefilled avg 1106 ttft avg 2.01s + requests 49- 51: prompt avg 81563 max 82315 reused avg 80702 re-prefilled avg 861 ttft avg 1.75s + context reached: 82315 tokens (request 51) + +== Reuse effectiveness + prompt tokens 2474932, reused 2392367 (96.7 %), re-prefilled 82565 + requests with no reuse and a prompt above 4000 tokens: 1 (re-prefilled 9358 tokens) + codex-side usage: {"input_tokens": 2474932, "cached_input_tokens": 2392367, "output_tokens": 56553} + +== Prefill cost against re-prefilled tokens (engine PREFILL-PROFILE chunks, > 16 tokens per chunk) + re-prefilled 64-512: 10 requests, engine prefill 388 tok/s, ttft median 1.47s + re-prefilled 512-2048: 31 requests, engine prefill 873 tok/s, ttft median 1.75s + re-prefilled 2048-8192: 9 requests, engine prefill 1158 tok/s, ttft median 3.26s + re-prefilled 8192-32768: 1 requests, engine prefill 929 tok/s, ttft median 10.61s + +== Decode speed against context length (requests with > 4 generated tokens) + context 4000-16000: 5 requests, decode median 66.0 tok/s (p10 60.7, p90 92.8) + context 16000-48000: 19 requests, decode median 71.4 tok/s (p10 64.9, p90 82.7) + context 48000-96000: 27 requests, decode median 67.4 tok/s (p10 61.6, p90 76.8) + tokens per verify round (accepted drafts + 1): median 2.96, p10 2.59, p90 3.51 + expert entries served from VRAM per request: median 49.0 %, PCIe 23.0 % + +== Slowest 8 requests (time to first text + decode) + # 31 prompt 55120 reused 54689 ttft 1.35s decode 4971 tok in 73.79s 4971 generated tokens + # 13 prompt 27718 reused 27154 ttft 1.62s decode 4960 tok in 58.35s 4960 generated tokens + # 9 prompt 22557 reused 22201 ttft 1.46s decode 3267 tok in 50.36s 3267 generated tokens + # 4 prompt 12484 reused 11453 ttft 1.56s decode 3207 tok in 48.19s 3207 generated tokens + # 5 prompt 15806 reused 12479 ttft 3.17s decode 3665 tok in 39.47s re-prefilled 3327 tokens after reusing 12479; 3665 generated tokens + # 21 prompt 40774 reused 39865 ttft 1.67s decode 2891 tok in 39.27s 2891 generated tokens + # 45 prompt 75764 reused 75335 ttft 1.56s decode 2851 tok in 37.12s 2851 generated tokens + # 19 prompt 37273 reused 36346 ttft 1.70s decode 2014 tok in 26.89s 2014 generated tokens + +== Ideal against actual (every turn re-reads only its new suffix) + re-prefilled tokens actual 82565, ideal (new tokens only; a chain of linear turns) about 26414 + at the engine's measured 1107 tok/s for large chunks: actual prefill about 75 s, ideal about 24 s; time to first text actually spent 111 s + +== Memory (env.tsv, inference process) + samples 92: RSS MiB first 53617 / max 54980 / last 54920; VRAM MiB first 13192 / max 13640 / last 13640; MemAvailable MiB first 14364 / min 12844 / last 12909 + +== Codex events + {"item.completed.agent_message": 16, "item.completed.command_execution": 53, "item.completed.error": 1, "item.started.command_execution": 53, "thread.started": 1, "turn.completed": 1, "turn.started": 1} + command executions 53, exit != 0: 5, duration median 0.0 s, max 12.4 s, total 14 s diff --git a/docs/e2e-data/943b-env.tsv b/docs/e2e-data/943b-env.tsv new file mode 100644 index 00000000..12c28002 --- /dev/null +++ b/docs/e2e-data/943b-env.tsv @@ -0,0 +1,277 @@ +epoch name vmrss_mib vmhwm_mib rssanon_mib rssshmem_mib vmlck_mib gpu_used_mib mem_available_mib +1792294612 inference 53617 53617 49588 3836 0 13192 14364 +1792294612 strata 94 94 82 0 0 13192 14364 +1792294612 daemon 10 10 0 0 0 13192 14364 +1792294622 inference 54081 54081 50040 3836 0 13368 13778 +1792294622 strata 99 99 84 0 0 13368 13778 +1792294622 daemon 10 10 0 0 0 13368 13778 +1792294632 inference 54434 54434 50392 3836 0 13422 13373 +1792294632 strata 102 102 87 0 0 13422 13373 +1792294632 daemon 10 10 0 0 0 13422 13373 +1792294642 inference 54548 54548 50507 3836 0 13640 13294 +1792294642 strata 102 102 87 0 0 13640 13294 +1792294642 daemon 10 10 0 0 0 13640 13294 +1792294652 inference 54661 54661 50620 3836 0 13640 13191 +1792294652 strata 103 103 88 0 0 13640 13191 +1792294652 daemon 10 10 0 0 0 13640 13191 +1792294662 inference 54662 54662 50620 3836 0 13640 13197 +1792294662 strata 103 103 88 0 0 13640 13197 +1792294662 daemon 10 10 0 0 0 13640 13197 +1792294672 inference 54663 54663 50622 3836 0 13640 13173 +1792294672 strata 103 103 88 0 0 13640 13173 +1792294672 daemon 10 10 0 0 0 13640 13173 +1792294682 inference 54664 54664 50622 3836 0 13640 13169 +1792294682 strata 103 103 88 0 0 13640 13169 +1792294682 daemon 10 10 0 0 0 13640 13169 +1792294692 inference 54664 54664 50623 3836 0 13640 13193 +1792294692 strata 103 103 88 0 0 13640 13193 +1792294692 daemon 10 10 0 0 0 13640 13193 +1792294702 inference 54665 54665 50623 3836 0 13424 13171 +1792294702 strata 103 103 88 0 0 13424 13171 +1792294702 daemon 10 10 0 0 0 13424 13171 +1792294712 inference 54778 54778 50736 3836 0 13640 13084 +1792294712 strata 103 103 89 0 0 13640 13084 +1792294712 daemon 10 10 0 0 0 13640 13084 +1792294722 inference 54779 54779 50737 3836 0 13640 13077 +1792294722 strata 103 103 89 0 0 13640 13077 +1792294722 daemon 10 10 0 0 0 13640 13077 +1792294733 inference 54780 54780 50738 3836 0 13640 13098 +1792294733 strata 103 103 89 0 0 13640 13098 +1792294733 daemon 10 10 0 0 0 13640 13098 +1792294743 inference 54781 54781 50739 3836 0 13640 13077 +1792294743 strata 103 103 89 0 0 13640 13077 +1792294743 daemon 10 10 0 0 0 13640 13077 +1792294753 inference 54886 54886 50845 3836 0 13432 12974 +1792294753 strata 104 104 89 0 0 13432 12974 +1792294753 daemon 10 10 0 0 0 13432 12974 +1792294763 inference 54886 54886 50845 3836 0 13640 12981 +1792294763 strata 104 104 89 0 0 13640 12981 +1792294763 daemon 10 10 0 0 0 13640 12981 +1792294773 inference 54886 54886 50845 3836 0 13640 12977 +1792294773 strata 104 104 90 0 0 13640 12977 +1792294773 daemon 10 10 0 0 0 13640 12977 +1792294783 inference 54886 54886 50845 3836 0 13640 12977 +1792294783 strata 104 104 90 0 0 13640 12977 +1792294783 daemon 10 10 0 0 0 13640 12977 +1792294793 inference 54886 54886 50845 3836 0 13640 12976 +1792294793 strata 105 105 90 0 0 13640 12976 +1792294793 daemon 10 10 0 0 0 13640 12976 +1792294803 inference 54887 54887 50845 3836 0 13640 12974 +1792294803 strata 105 105 90 0 0 13640 12974 +1792294803 daemon 10 10 0 0 0 13640 12974 +1792294813 inference 54887 54887 50845 3836 0 13640 12975 +1792294813 strata 105 105 90 0 0 13640 12975 +1792294813 daemon 10 10 0 0 0 13640 12975 +1792294823 inference 54887 54887 50845 3836 0 13640 12988 +1792294823 strata 105 105 90 0 0 13640 12988 +1792294823 daemon 10 10 0 0 0 13640 12988 +1792294833 inference 54887 54887 50845 3836 0 13640 12983 +1792294833 strata 105 105 90 0 0 13640 12983 +1792294833 daemon 10 10 0 0 0 13640 12983 +1792294843 inference 54887 54887 50845 3836 0 13640 12978 +1792294843 strata 105 105 90 0 0 13640 12978 +1792294843 daemon 10 10 0 0 0 13640 12978 +1792294853 inference 54911 54911 50869 3836 0 13424 12943 +1792294853 strata 107 107 92 0 0 13424 12943 +1792294853 daemon 10 10 0 0 0 13424 12943 +1792294863 inference 54911 54911 50869 3836 0 13640 12946 +1792294863 strata 107 107 92 0 0 13640 12946 +1792294863 daemon 10 10 0 0 0 13640 12946 +1792294873 inference 54911 54911 50869 3836 0 13640 12945 +1792294873 strata 107 107 92 0 0 13640 12945 +1792294873 daemon 10 10 0 0 0 13640 12945 +1792294883 inference 54911 54911 50869 3836 0 13640 12951 +1792294883 strata 107 107 92 0 0 13640 12951 +1792294883 daemon 10 10 0 0 0 13640 12951 +1792294893 inference 54911 54911 50869 3836 0 13640 12956 +1792294893 strata 107 107 92 0 0 13640 12956 +1792294893 daemon 10 10 0 0 0 13640 12956 +1792294903 inference 54911 54911 50869 3836 0 13640 12951 +1792294903 strata 107 107 92 0 0 13640 12951 +1792294903 daemon 10 10 0 0 0 13640 12951 +1792294913 inference 54911 54911 50869 3836 0 13640 12872 +1792294913 strata 107 107 92 0 0 13640 12872 +1792294913 daemon 10 10 0 0 0 13640 12872 +1792294923 inference 54911 54911 50869 3836 0 13640 12890 +1792294923 strata 107 107 92 0 0 13640 12890 +1792294923 daemon 10 10 0 0 0 13640 12890 +1792294933 inference 54911 54911 50869 3836 0 13640 12909 +1792294933 strata 108 108 93 0 0 13640 12909 +1792294933 daemon 10 10 0 0 0 13640 12909 +1792294943 inference 54911 54911 50869 3836 0 13640 12929 +1792294943 strata 108 108 93 0 0 13640 12929 +1792294943 daemon 10 10 0 0 0 13640 12929 +1792294953 inference 54911 54911 50869 3836 0 13640 12926 +1792294953 strata 108 108 94 0 0 13640 12926 +1792294953 daemon 10 10 0 0 0 13640 12926 +1792294963 inference 54911 54911 50869 3836 0 13640 12936 +1792294963 strata 108 108 94 0 0 13640 12936 +1792294963 daemon 10 10 0 0 0 13640 12936 +1792294973 inference 54857 54907 50815 3836 0 13640 12951 +1792294973 strata 110 110 95 0 0 13640 12951 +1792294973 daemon 10 10 0 0 0 13640 12951 +1792294983 inference 54857 54907 50815 3836 0 13640 12992 +1792294983 strata 110 110 95 0 0 13640 12992 +1792294983 daemon 10 10 0 0 0 13640 12992 +1792294993 inference 54857 54907 50815 3836 0 13640 13000 +1792294993 strata 110 110 95 0 0 13640 13000 +1792294993 daemon 10 10 0 0 0 13640 13000 +1792295003 inference 54857 54907 50815 3836 0 13424 12986 +1792295003 strata 111 111 96 0 0 13424 12986 +1792295003 daemon 10 10 0 0 0 13424 12986 +1792295013 inference 54920 54920 50878 3836 0 13640 12934 +1792295013 strata 111 111 96 0 0 13640 12934 +1792295013 daemon 10 10 0 0 0 13640 12934 +1792295023 inference 54920 54920 50878 3836 0 13640 12918 +1792295023 strata 111 111 96 0 0 13640 12918 +1792295023 daemon 10 10 0 0 0 13640 12918 +1792295034 inference 54920 54920 50878 3836 0 13640 12881 +1792295034 strata 111 111 96 0 0 13640 12881 +1792295034 daemon 10 10 0 0 0 13640 12881 +1792295044 inference 54920 54920 50878 3836 0 13640 12906 +1792295044 strata 111 111 96 0 0 13640 12906 +1792295044 daemon 10 10 0 0 0 13640 12906 +1792295054 inference 54920 54920 50878 3836 0 13640 12921 +1792295054 strata 111 111 96 0 0 13640 12921 +1792295054 daemon 10 10 0 0 0 13640 12921 +1792295064 inference 54923 54923 50881 3836 0 13640 12904 +1792295064 strata 111 111 96 0 0 13640 12904 +1792295064 daemon 10 10 0 0 0 13640 12904 +1792295074 inference 54923 54923 50881 3836 0 13640 12915 +1792295074 strata 112 112 97 0 0 13640 12915 +1792295074 daemon 10 10 0 0 0 13640 12915 +1792295084 inference 54923 54923 50881 3836 0 13640 12921 +1792295084 strata 112 112 97 0 0 13640 12921 +1792295084 daemon 10 10 0 0 0 13640 12921 +1792295094 inference 54935 54935 50894 3836 0 13640 12897 +1792295094 strata 112 112 97 0 0 13640 12897 +1792295094 daemon 10 10 0 0 0 13640 12897 +1792295104 inference 54935 54935 50894 3836 0 13640 12906 +1792295104 strata 112 112 98 0 0 13640 12906 +1792295104 daemon 10 10 0 0 0 13640 12906 +1792295114 inference 54935 54935 50894 3836 0 13640 12906 +1792295114 strata 112 112 98 0 0 13640 12906 +1792295114 daemon 10 10 0 0 0 13640 12906 +1792295124 inference 54935 54935 50894 3836 0 13640 12916 +1792295124 strata 113 113 98 0 0 13640 12916 +1792295124 daemon 10 10 0 0 0 13640 12916 +1792295134 inference 54935 54935 50894 3836 0 13640 12913 +1792295134 strata 113 113 98 0 0 13640 12913 +1792295134 daemon 10 10 0 0 0 13640 12913 +1792295144 inference 54935 54935 50894 3836 0 13640 12909 +1792295144 strata 113 113 98 0 0 13640 12909 +1792295144 daemon 10 10 0 0 0 13640 12909 +1792295154 inference 54935 54935 50894 3836 0 13640 12881 +1792295154 strata 113 113 99 0 0 13640 12881 +1792295154 daemon 10 10 0 0 0 13640 12881 +1792295164 inference 54935 54935 50894 3836 0 13640 12901 +1792295164 strata 114 114 99 0 0 13640 12901 +1792295164 daemon 10 10 0 0 0 13640 12901 +1792295174 inference 54935 54935 50894 3836 0 13640 12912 +1792295174 strata 114 114 99 0 0 13640 12912 +1792295174 daemon 10 10 0 0 0 13640 12912 +1792295184 inference 54935 54935 50894 3836 0 13640 12916 +1792295184 strata 114 114 99 0 0 13640 12916 +1792295184 daemon 10 10 0 0 0 13640 12916 +1792295194 inference 54935 54935 50894 3836 0 13640 12923 +1792295194 strata 114 114 99 0 0 13640 12923 +1792295194 daemon 10 10 0 0 0 13640 12923 +1792295204 inference 54935 54935 50894 3836 0 13640 12902 +1792295204 strata 114 114 99 0 0 13640 12902 +1792295204 daemon 10 10 0 0 0 13640 12902 +1792295214 inference 54935 54935 50894 3836 0 13640 12911 +1792295214 strata 114 114 99 0 0 13640 12911 +1792295214 daemon 10 10 0 0 0 13640 12911 +1792295224 inference 54935 54935 50894 3836 0 13640 12913 +1792295224 strata 114 114 99 0 0 13640 12913 +1792295224 daemon 10 10 0 0 0 13640 12913 +1792295234 inference 54956 54956 50915 3836 0 13424 12880 +1792295234 strata 114 114 99 0 0 13424 12880 +1792295234 daemon 10 10 0 0 0 13424 12880 +1792295244 inference 54956 54956 50915 3836 0 13640 12885 +1792295244 strata 114 114 99 0 0 13640 12885 +1792295244 daemon 10 10 0 0 0 13640 12885 +1792295254 inference 54956 54956 50915 3836 0 13640 12896 +1792295254 strata 115 115 100 0 0 13640 12896 +1792295254 daemon 10 10 0 0 0 13640 12896 +1792295264 inference 54920 54952 50879 3836 0 13640 12908 +1792295264 strata 115 115 100 0 0 13640 12908 +1792295264 daemon 10 10 0 0 0 13640 12908 +1792295274 inference 54920 54952 50879 3836 0 13640 12921 +1792295274 strata 115 115 100 0 0 13640 12921 +1792295274 daemon 10 10 0 0 0 13640 12921 +1792295284 inference 54920 54952 50879 3836 0 13640 12881 +1792295284 strata 115 115 100 0 0 13640 12881 +1792295284 daemon 10 10 0 0 0 13640 12881 +1792295294 inference 54920 54952 50879 3836 0 13424 12892 +1792295294 strata 115 115 100 0 0 13424 12892 +1792295294 daemon 10 10 0 0 0 13424 12892 +1792295304 inference 54920 54952 50879 3836 0 13640 12921 +1792295304 strata 115 115 100 0 0 13640 12921 +1792295304 daemon 10 10 0 0 0 13640 12921 +1792295314 inference 54920 54952 50879 3836 0 13640 12905 +1792295314 strata 116 116 101 0 0 13640 12905 +1792295314 daemon 10 10 0 0 0 13640 12905 +1792295325 inference 54920 54952 50879 3836 0 13640 12923 +1792295325 strata 116 116 101 0 0 13640 12923 +1792295325 daemon 10 10 0 0 0 13640 12923 +1792295335 inference 54920 54952 50879 3836 0 13640 12914 +1792295335 strata 116 116 101 0 0 13640 12914 +1792295335 daemon 10 10 0 0 0 13640 12914 +1792295345 inference 54920 54952 50879 3836 0 13640 12904 +1792295345 strata 116 116 101 0 0 13640 12904 +1792295345 daemon 10 10 0 0 0 13640 12904 +1792295355 inference 54920 54952 50879 3836 0 13640 12896 +1792295355 strata 116 116 101 0 0 13640 12896 +1792295355 daemon 10 10 0 0 0 13640 12896 +1792295365 inference 54920 54952 50879 3836 0 13640 12925 +1792295365 strata 116 116 101 0 0 13640 12925 +1792295365 daemon 10 10 0 0 0 13640 12925 +1792295375 inference 54920 54952 50879 3836 0 13424 12912 +1792295375 strata 116 116 101 0 0 13424 12912 +1792295375 daemon 10 10 0 0 0 13424 12912 +1792295385 inference 54920 54952 50879 3836 0 13640 12912 +1792295385 strata 116 116 101 0 0 13640 12912 +1792295385 daemon 10 10 0 0 0 13640 12912 +1792295395 inference 54920 54952 50879 3836 0 13640 12923 +1792295395 strata 116 116 101 0 0 13640 12923 +1792295395 daemon 10 10 0 0 0 13640 12923 +1792295405 inference 54920 54952 50879 3836 0 13640 12906 +1792295405 strata 116 116 101 0 0 13640 12906 +1792295405 daemon 10 10 0 0 0 13640 12906 +1792295415 inference 54920 54952 50879 3836 0 13640 12931 +1792295415 strata 116 116 101 0 0 13640 12931 +1792295415 daemon 10 10 0 0 0 13640 12931 +1792295425 inference 54920 54952 50879 3836 0 13640 12925 +1792295425 strata 116 116 101 0 0 13640 12925 +1792295425 daemon 10 10 0 0 0 13640 12925 +1792295435 inference 54920 54952 50879 3836 0 13640 12918 +1792295435 strata 116 116 101 0 0 13640 12918 +1792295435 daemon 10 10 0 0 0 13640 12918 +1792295445 inference 54920 54952 50879 3836 0 13640 12916 +1792295445 strata 116 116 101 0 0 13640 12916 +1792295445 daemon 10 10 0 0 0 13640 12916 +1792295455 inference 54920 54952 50879 3836 0 13640 12916 +1792295455 strata 116 116 101 0 0 13640 12916 +1792295455 daemon 10 10 0 0 0 13640 12916 +1792295465 inference 54920 54952 50879 3836 0 13640 12918 +1792295465 strata 116 116 101 0 0 13640 12918 +1792295465 daemon 10 10 0 0 0 13640 12918 +1792295475 inference 54920 54952 50879 3836 0 13424 12902 +1792295475 strata 117 117 102 0 0 13424 12902 +1792295475 daemon 10 10 0 0 0 13424 12902 +1792295485 inference 54980 54980 50939 3836 0 13424 12851 +1792295485 strata 117 117 102 0 0 13424 12851 +1792295485 daemon 10 10 0 0 0 13424 12851 +1792295495 inference 54980 54980 50939 3836 0 13640 12861 +1792295495 strata 117 117 102 0 0 13640 12861 +1792295495 daemon 10 10 0 0 0 13640 12861 +1792295505 inference 54980 54980 50939 3836 0 13640 12844 +1792295505 strata 118 118 103 0 0 13640 12844 +1792295505 daemon 10 10 0 0 0 13640 12844 +1792295515 inference 54980 54980 50939 3836 0 13640 12850 +1792295515 strata 118 118 103 0 0 13640 12850 +1792295515 daemon 10 10 0 0 0 13640 12850 +1792295525 inference 54920 54976 50879 3836 0 13640 12909 +1792295525 strata 118 118 103 0 0 13640 12909 +1792295525 daemon 10 10 0 0 0 13640 12909 diff --git a/docs/e2e-data/943b-trace.csv b/docs/e2e-data/943b-trace.csv new file mode 100644 index 00000000..a57b0f65 --- /dev/null +++ b/docs/e2e-data/943b-trace.csv @@ -0,0 +1,52 @@ +idx,t_start_ms,t_done_ms,finish,prompt_tokens,reused_tokens,reprefilled_tokens,ttft_ms,decode_tokens,decode_ms,decode_tok_s,engine_prefill_tokens,engine_prefill_ms,engine_prefill_tok_s,rounds,tokens_per_round,vram_expert_share,pcie_expert_share,swaps,prefix_hit,prefix_resume,prefix_import_ms,gap_before_ms,tool_exec_in_gap_ms,queue_wait_ms,inference_rss_mib,gpu_mib,mem_available_mib,join_ok +0,1792294613112,1792294626114,Stop,9358,0,9358,10613.4,146,2388.3,60.7,9353,10069.4,928.9,47,3.11,0.378,0.286,2958,,,,,,0,54081,13368,13778,True +1,1792294626193,1792294631625,Stop,10149,9353,796,1590.4,254,3841.9,65.9,791,1157.3,683.5,95,2.67,0.514,0.226,3607,,,,79,1,0,54434,13422,13373,True +2,1792294631791,1792294646041,Stop,11458,10144,1314,1707.7,829,12542.2,66.0,1309,1313.5,996.6,330,2.51,0.547,0.208,9284,,,,166,1,0,54548,13640,13294,True +3,1792294647297,1792294697043,Stop,12484,11453,1031,1558.8,3207,48186.6,66.5,1026,1190.6,861.8,1222,2.62,0.513,0.223,30173,,,,1256,1072,0,54665,13424,13171,True +4,1792294707261,1792294749899,Stop,15806,12479,3327,3168.9,3665,39469.9,92.8,3322,2777.3,1196.1,1001,3.66,0.527,0.22,25273,,,,10218,10040,0,54886,13432,12974,True +5,1792294749985,1792294771487,Stop,19550,15801,3749,3382.7,1220,18119.1,67.3,3744,3014.1,1242.2,484,2.52,0.554,0.207,12394,,,,86,1,0,54886,13640,12977,True +6,1792294771543,1792294789397,Stop,20848,19545,1303,1617.5,1135,16236.2,69.8,1298,1219.5,1064.4,399,2.84,0.493,0.233,10343,,,,56,0,0,54886,13640,12976,True +7,1792294789492,1792294794543,Stop,22206,20843,1363,1762.7,257,3289.0,77.8,1358,1373.5,988.7,72,3.57,0.426,0.27,2960,,,,95,2,0,54886,13640,12976,True +8,1792294794627,1792294846443,Stop,22557,22201,356,1459.4,3267,50356.5,64.9,351,1108.0,316.8,1260,2.59,0.506,0.228,30730,,,,84,1,0,54887,13640,12978,True +9,1792294846541,1792294853083,Stop,26038,22552,3486,3299.6,230,3242.8,70.6,3481,2911.6,1195.6,75,3.07,0.442,0.257,3023,,,,98,0,0,54911,13424,12943,True +10,1792294853178,1792294857200,Stop,26433,26033,400,1416.8,186,2605.5,71.0,395,1054.3,374.7,53,3.51,0.321,0.311,1826,,,,95,1,0,54911,13424,12943,True +11,1792294857288,1792294864864,Stop,27159,26428,731,1665.9,467,5910.3,78.8,726,1273.9,569.9,122,3.83,0.386,0.289,4163,,,,88,1,0,54911,13640,12946,True +12,1792294864953,1792294924923,Stop,27718,27154,564,1624.0,4960,58345.7,85.0,559,1257.3,444.6,1548,3.2,0.562,0.202,37802,,,,89,1,0,54911,13640,12890,True +13,1792294925081,1792294945521,Stop,32944,27713,5231,4634.5,1189,15806.4,75.2,5226,4247.5,1230.4,348,3.42,0.441,0.261,9228,,,,158,0,0,54911,13640,12929,True +14,1792294945626,1792294949428,Stop,34257,32939,1318,1799.9,144,2002.0,71.4,1313,1416.6,926.9,43,3.35,0.383,0.282,1806,,,,105,1,0,54911,13640,12926,True +15,1792294949524,1792294963886,Stop,34697,34252,445,1557.2,1060,12804.7,82.7,440,1181.4,372.4,229,4.63,0.398,0.27,6400,,,,96,0,0,54911,13640,12936,True +16,1792294963988,1792294971241,Stop,35851,34692,1159,1815.4,405,5437.7,74.3,1154,1431.7,806.0,111,3.65,0.397,0.277,3367,,,,102,0,0,54857,13640,12951,True +17,1792294971344,1792294974403,Stop,36351,35846,505,1544.6,106,1514.2,69.3,500,1170.5,427.2,31,3.42,0.359,0.289,1387,,,,103,1,0,54857,13640,12951,True +18,1792294974529,1792295003114,Stop,37273,36346,927,1696.9,2014,26888.1,74.9,922,1297.6,710.5,699,2.88,0.555,0.207,17984,,,,126,0,0,54857,13424,12986,True +19,1792295003224,1792295017299,Stop,39870,37268,2602,2780.8,811,11293.9,71.7,2597,2375.5,1093.2,263,3.08,0.468,0.246,7451,,,,110,1,0,54920,13640,12934,True +20,1792295017405,1792295058348,Stop,40774,39865,909,1669.3,2891,39274.3,73.6,904,1278.1,707.3,934,3.1,0.5,0.235,23245,,,,106,0,0,54920,13640,12921,True +21,1792295058457,1792295064694,Stop,43760,40769,2991,3202.7,200,3034.2,65.6,2986,2809.5,1062.8,67,2.99,0.442,0.254,2473,,,,109,0,0,54923,13640,12904,True +22,1792295064799,1792295070636,Stop,44159,43755,404,1472.9,291,4364.5,66.4,399,1086.9,367.1,103,2.83,0.468,0.246,3255,,,,105,1,0,54923,13640,12915,True +23,1792295070785,1792295090938,Stop,45730,44154,1576,1916.0,1165,18237.3,63.8,1571,1492.3,1052.7,445,2.62,0.498,0.234,12119,,,,149,1,0,54935,13640,12897,True +24,1792295091046,1792295096610,Stop,48350,45725,2625,3188.0,161,2376.2,67.3,2620,2769.4,946.1,52,3.1,0.397,0.279,2651,,,,108,0,0,54935,13640,12897,True +25,1792295096719,1792295120222,Stop,50138,48345,1793,2019.4,1482,21484.1,68.9,1788,1588.6,1125.5,497,2.98,0.458,0.252,13499,,,,109,1,0,54935,13640,12916,True +26,1792295120338,1792295125611,Stop,51713,50133,1580,1879.3,210,3394.1,61.6,1575,1470.5,1071.1,73,2.88,0.408,0.279,2864,,,,116,1,0,54935,13640,12916,True +27,1792295125764,1792295132360,Stop,52772,51708,1064,1813.7,318,4781.9,66.3,1059,1384.4,765.0,116,2.74,0.463,0.243,4228,,,,153,1,0,54935,13640,12913,True +28,1792295132476,1792295151954,Stop,53254,52767,487,1414.8,1122,18062.8,62.1,482,1041.9,462.6,480,2.34,0.567,0.201,12078,,,,116,1,0,54935,13640,12881,True +29,1792295152099,1792295156252,Stop,54694,53249,1445,1680.1,190,2473.3,76.4,1440,1289.4,1116.8,72,2.64,0.622,0.172,2539,,,,145,1,0,54935,13640,12881,True +30,1792295156370,1792295231506,Stop,55120,54689,431,1351.0,4971,73785.1,67.4,426,964.0,441.9,1892,2.63,0.549,0.21,45931,,,,118,1,0,54956,13424,12880,True +31,1792295231641,1792295246555,Stop,60446,55115,5331,4552.4,711,10361.9,68.5,5326,4137.6,1287.2,238,2.99,0.467,0.248,6878,,,,135,1,0,54956,13640,12885,True +32,1792295246680,1792295259313,Stop,61250,60441,809,1707.1,940,10926.8,85.9,804,1302.6,617.2,294,3.2,0.591,0.19,7860,,,,125,1,0,54920,13640,12908,True +33,1792295259499,1792295265912,Stop,62242,61245,997,1674.4,295,4738.1,62.1,992,1255.8,789.9,114,2.59,0.491,0.236,3596,,,,186,0,0,54920,13640,12908,True +34,1792295266089,1792295279455,Stop,62636,62237,399,1362.7,863,12003.0,71.8,394,988.8,398.5,294,2.94,0.52,0.225,7483,,,,177,1,0,54920,13640,12881,True +35,1792295279637,1792295293484,Stop,63592,62631,961,1681.7,778,12165.2,63.9,956,1271.3,752.0,304,2.56,0.525,0.219,8213,,,,182,1,0,54920,13424,12892,True +36,1792295293612,1792295311273,Stop,65487,63587,1900,1891.6,1204,15769.5,76.3,1895,1470.7,1288.5,392,3.07,0.533,0.219,10587,,,,128,1,0,54920,13640,12905,True +37,1792295311458,1792295328396,Stop,66826,65482,1344,1765.1,1106,15172.6,72.8,1339,1351.9,990.5,364,3.04,0.524,0.224,9575,,,,185,1,0,54920,13640,12923,True +38,1792295328581,1792295347051,Stop,68030,66821,1209,1798.9,1124,16671.6,67.4,1204,1385.0,869.3,399,2.82,0.504,0.229,10454,,,,185,1,0,54920,13640,12904,True +39,1792295347827,1792295373562,Stop,69723,68025,1698,1940.4,1567,23794.7,65.8,1693,1503.2,1126.3,591,2.65,0.535,0.216,15464,,,,776,536,0,54920,13424,12912,True +40,1792295373706,1792295388623,Stop,71523,69718,1805,1955.0,807,12961.5,62.2,1800,1517.1,1186.5,328,2.46,0.544,0.212,9134,,,,144,1,0,54920,13640,12912,True +41,1792295388795,1792295406443,Stop,72442,71518,924,1636.8,1147,16010.9,71.6,919,1228.2,748.2,388,2.96,0.513,0.227,10157,,,,172,1,0,54920,13640,12906,True +42,1792295406637,1792295430564,Stop,73676,72437,1239,1804.8,1572,22122.4,71.0,1234,1375.9,896.9,559,2.81,0.539,0.21,14442,,,,194,1,0,54920,13640,12918,True +43,1792295430701,1792295436055,Stop,75340,73671,1669,1887.7,205,3466.0,58.9,1664,1467.2,1134.1,77,2.66,0.431,0.261,2639,,,,137,1,0,54920,13640,12918,True +44,1792295436225,1792295474907,Stop,75764,75335,429,1564.1,2851,37117.8,76.8,424,1156.1,366.8,881,3.24,0.526,0.22,21915,,,,170,1,0,54920,13424,12902,True +45,1792295475090,1792295484230,Stop,78740,75759,2981,3257.3,474,5882.2,80.4,2976,2833.6,1050.3,138,3.43,0.494,0.232,4195,,,,183,1,0,54980,13424,12851,True +46,1792295484377,1792295489073,Stop,79308,78735,573,1610.8,210,3085.7,67.7,568,1202.9,472.2,67,3.13,0.416,0.258,2105,,,,147,1,0,54980,13424,12851,True +47,1792295489242,1792295503269,Stop,79745,79303,442,1622.3,790,12404.8,63.6,437,1202.6,363.4,286,2.76,0.452,0.251,7793,,,,169,0,0,54980,13640,12844,True +48,1792295503423,1792295508430,Stop,80647,79740,907,1745.9,213,3260.7,65.0,902,1300.6,693.5,69,3.09,0.369,0.285,2852,,,,154,1,0,54980,13640,12844,True +49,1792295508571,1792295518323,Stop,81729,80642,1087,1898.6,491,7853.1,62.4,1082,1448.0,747.2,173,2.84,0.431,0.263,5665,,,,141,1,0,54980,13640,12850,True +50,1792295518529,1792295530897,Stop,82315,81724,591,1618.4,652,10749.5,60.6,586,1208.5,484.9,243,2.68,0.445,0.258,6568,,,,206,1,0,54920,13640,12909,True diff --git a/docs/e2e-data/945-analysis.txt b/docs/e2e-data/945-analysis.txt new file mode 100644 index 00000000..cc4ab618 --- /dev/null +++ b/docs/e2e-data/945-analysis.txt @@ -0,0 +1,70 @@ +== Session 945-codex-crm: 84 generations in strata-next.log, 84 prefill phases in inference.log, 0 join mismatches + +== Time shares (first request start to last request end = 1525 s) + time to first text (prefill + first token) 227.9 s 14.9 % + decode after the first token 1282.7 s 84.1 % + between requests (agent + tools) 14.7 s 1.0 % + of which command execution seen in Codex events 0.1 s 0.0 % + queue wait: 0 by construction (one client, one generation at a time; strata-next /metrics queue_used was 0) + +== HEADLINE: weighted decode tok/s over the whole session + 74.8 tok/s = 95997 tokens after the first / 1282.7 s decode time (84 requests; per-request median 73.55) + reference lines (earlier vanilla Strata Codex tic-tac-toe runs, 256K, INT8 K+V, same host): native 115.7 tok/s (about 110 at 180k fill), KAR PLE 150.1-150.3 tok/s (about 160); 98-99 % of CLI input tokens cached + engine tokens per verify round (accepted drafts + 1), all requests: 3.36 + +== Context growth (prompt tokens per request) + requests 1- 7: prompt avg 18556 max 30131 reused avg 13750 re-prefilled avg 4805 ttft avg 4.46s + requests 8- 14: prompt avg 35275 max 39387 reused avg 32768 re-prefilled avg 2507 ttft avg 2.71s + requests 15- 21: prompt avg 44423 max 47062 reused avg 42130 re-prefilled avg 2293 ttft avg 2.33s + requests 22- 28: prompt avg 50534 max 55559 reused avg 47981 re-prefilled avg 2553 ttft avg 2.68s + requests 29- 35: prompt avg 58717 max 62779 reused avg 57051 re-prefilled avg 1666 ttft avg 2.05s + requests 36- 42: prompt avg 68243 max 71541 reused avg 65828 re-prefilled avg 2415 ttft avg 2.58s + requests 43- 49: prompt avg 76027 max 79065 reused avg 73728 re-prefilled avg 2299 ttft avg 2.43s + requests 50- 56: prompt avg 82968 max 85438 reused avg 81042 re-prefilled avg 1926 ttft avg 2.33s + requests 57- 63: prompt avg 90497 max 94935 reused avg 87771 re-prefilled avg 2726 ttft avg 2.88s + requests 64- 70: prompt avg 102981 max 107837 reused avg 100059 re-prefilled avg 2922 ttft avg 3.00s + requests 71- 77: prompt avg 112001 max 114486 reused avg 110006 re-prefilled avg 1994 ttft avg 2.34s + requests 78- 84: prompt avg 119214 max 123239 reused avg 116736 re-prefilled avg 2478 ttft avg 2.78s + context reached: 123239 tokens (request 84) + +== Reuse effectiveness + prompt tokens 6016105, reused 5801984 (96.4 %), re-prefilled 214121 + requests with no reuse and a prompt above 4000 tokens: 1 (re-prefilled 10008 tokens) + codex-side usage: {"input_tokens": 6016105, "cached_input_tokens": 5801984, "output_tokens": 96081} + +== Prefill cost against re-prefilled tokens (engine PREFILL-PROFILE chunks, > 16 tokens per chunk) + re-prefilled 64-512: 1 requests, engine prefill 259 tok/s, ttft median 1.11s + re-prefilled 512-2048: 36 requests, engine prefill 995 tok/s, ttft median 1.74s + re-prefilled 2048-8192: 45 requests, engine prefill 1038 tok/s, ttft median 3.16s + re-prefilled 8192-32768: 2 requests, engine prefill 1140 tok/s, ttft median 8.40s + +== Decode speed against context length (requests with > 4 generated tokens) + context 4000-16000: 2 requests, decode median 64.6 tok/s (p10 56.0, p90 73.2) + context 16000-48000: 20 requests, decode median 78.6 tok/s (p10 66.8, p90 86.2) + context 48000-96000: 42 requests, decode median 73.95 tok/s (p10 65.3, p90 82.0) + context 96000-inf: 20 requests, decode median 68.1 tok/s (p10 61.8, p90 80.0) + tokens per verify round (accepted drafts + 1): median 3.5, p10 2.82, p90 4.08 + expert entries served from VRAM per request: median 43.0 %, PCIe 27.0 % + +== Slowest 10 requests (time to first text + decode) + # 5 prompt 18505 reused 16384 ttft 2.19s decode 8277 tok in 98.68s re-prefilled 2121 tokens after reusing 16384; 8277 generated tokens + # 2 prompt 10328 reused 8192 ttft 2.39s decode 6023 tok in 82.25s re-prefilled 2136 tokens after reusing 8192; 6023 generated tokens + # 27 prompt 51084 reused 49152 ttft 1.76s decode 4363 tok in 48.47s 4363 generated tokens + # 64 prompt 95693 reused 94208 ttft 1.79s decode 2772 tok in 47.36s 2772 generated tokens + # 6 prompt 26841 reused 18432 ttft 7.11s decode 3254 tok in 39.33s re-prefilled 8409 tokens after reusing 18432; 3254 generated tokens + # 65 prompt 100503 reused 94208 ttft 5.79s decode 2482 tok in 37.35s re-prefilled 6295 tokens after reusing 94208; 2482 generated tokens + # 60 prompt 89577 reused 88064 ttft 1.81s decode 2989 tok in 38.68s 2989 generated tokens + # 79 prompt 115701 reused 114688 ttft 1.69s decode 2335 tok in 37.10s 2335 generated tokens + # 11 prompt 35237 reused 32768 ttft 2.92s decode 2091 tok in 25.66s re-prefilled 2469 tokens after reusing 32768; 2091 generated tokens + # 35 prompt 62779 reused 59392 ttft 3.28s decode 1861 tok in 24.62s re-prefilled 3387 tokens after reusing 59392; 1861 generated tokens + +== Ideal against actual (every turn re-reads only its new suffix) + re-prefilled tokens actual 214121, ideal (new tokens only; a chain of linear turns) about 28409 + at the engine's measured 1060 tok/s for large chunks: actual prefill about 202 s, ideal about 27 s; time to first text actually spent 228 s + +== Memory (env.tsv, inference process) + samples 153: RSS MiB first 53723 / max 60383 / last 60383; VRAM MiB first 13290 / max 13736 / last 13736; MemAvailable MiB first 13991 / min 7443 / last 7459 + +== Codex events + {"item.completed.agent_message": 32, "item.completed.command_execution": 60, "item.completed.error": 1, "item.completed.file_change": 19, "item.started.command_execution": 60, "item.started.file_change": 19, "thread.started": 1, "turn.completed": 1, "turn.started": 1} + command executions 60, exit != 0: 2, duration median 0.0 s, max 0.1 s, total 0 s diff --git a/docs/e2e-data/945-env.tsv b/docs/e2e-data/945-env.tsv new file mode 100644 index 00000000..7e03601f --- /dev/null +++ b/docs/e2e-data/945-env.tsv @@ -0,0 +1,460 @@ +epoch name vmrss_mib vmhwm_mib rssanon_mib rssshmem_mib vmlck_mib gpu_used_mib mem_available_mib +1792306269 inference 53723 53723 49690 3836 0 13290 13991 +1792306269 strata 94 94 82 0 0 13290 13991 +1792306269 daemon 10 10 0 0 0 13290 13991 +1792306279 inference 54642 54642 50597 3836 0 13686 13266 +1792306279 strata 99 99 84 0 0 13686 13266 +1792306279 daemon 10 10 0 0 0 13686 13266 +1792306289 inference 54919 54919 50874 3836 0 13734 12976 +1792306289 strata 101 101 86 0 0 13734 12976 +1792306289 daemon 10 10 0 0 0 13734 12976 +1792306299 inference 54919 54919 50874 3836 0 13734 12978 +1792306299 strata 101 101 86 0 0 13734 12978 +1792306299 daemon 10 10 0 0 0 13734 12978 +1792306309 inference 54919 54919 50874 3836 0 13736 12983 +1792306309 strata 101 101 86 0 0 13736 12983 +1792306309 daemon 10 10 0 0 0 13736 12983 +1792306319 inference 54919 54919 50874 3836 0 13736 12987 +1792306319 strata 101 101 86 0 0 13736 12987 +1792306319 daemon 10 10 0 0 0 13736 12987 +1792306329 inference 54919 54919 50874 3836 0 13736 12988 +1792306329 strata 101 101 86 0 0 13736 12988 +1792306329 daemon 10 10 0 0 0 13736 12988 +1792306339 inference 54920 54920 50875 3836 0 13736 12984 +1792306339 strata 101 101 86 0 0 13736 12984 +1792306339 daemon 10 10 0 0 0 13736 12984 +1792306349 inference 54921 54921 50876 3836 0 13736 12973 +1792306349 strata 101 101 86 0 0 13736 12973 +1792306349 daemon 10 10 0 0 0 13736 12973 +1792306359 inference 54923 54923 50877 3836 0 13736 12976 +1792306359 strata 101 101 86 0 0 13736 12976 +1792306359 daemon 10 10 0 0 0 13736 12976 +1792306369 inference 55175 55175 51130 3836 0 13516 12735 +1792306369 strata 102 102 87 0 0 13516 12735 +1792306369 daemon 10 10 0 0 0 13516 12735 +1792306379 inference 55350 55350 51304 3836 0 13736 12567 +1792306379 strata 102 102 87 0 0 13736 12567 +1792306379 daemon 10 10 0 0 0 13736 12567 +1792306389 inference 55353 55353 51307 3836 0 13736 12560 +1792306389 strata 103 103 88 0 0 13736 12560 +1792306389 daemon 10 10 0 0 0 13736 12560 +1792306399 inference 55496 55496 51451 3836 0 13736 12417 +1792306399 strata 104 104 89 0 0 13736 12417 +1792306399 daemon 10 10 0 0 0 13736 12417 +1792306409 inference 55509 55509 51464 3836 0 13736 12392 +1792306409 strata 104 104 89 0 0 13736 12392 +1792306409 daemon 10 10 0 0 0 13736 12392 +1792306420 inference 55509 55509 51464 3836 0 13736 12387 +1792306420 strata 104 104 89 0 0 13736 12387 +1792306420 daemon 10 10 0 0 0 13736 12387 +1792306430 inference 55509 55509 51464 3836 0 13736 12381 +1792306430 strata 104 104 89 0 0 13736 12381 +1792306430 daemon 10 10 0 0 0 13736 12381 +1792306440 inference 55509 55509 51464 3836 0 13736 12384 +1792306440 strata 104 104 89 0 0 13736 12384 +1792306440 daemon 10 10 0 0 0 13736 12384 +1792306450 inference 55509 55509 51464 3836 0 13736 12387 +1792306450 strata 104 104 89 0 0 13736 12387 +1792306450 daemon 10 10 0 0 0 13736 12387 +1792306460 inference 55511 55511 51465 3836 0 13736 12384 +1792306460 strata 104 104 89 0 0 13736 12384 +1792306460 daemon 10 10 0 0 0 13736 12384 +1792306470 inference 55512 55512 51467 3836 0 13736 12378 +1792306470 strata 104 104 89 0 0 13736 12378 +1792306470 daemon 10 10 0 0 0 13736 12378 +1792306480 inference 55514 55514 51468 3836 0 13736 12380 +1792306480 strata 104 104 89 0 0 13736 12380 +1792306480 daemon 10 10 0 0 0 13736 12380 +1792306490 inference 55515 55515 51470 3836 0 13736 12385 +1792306490 strata 104 104 89 0 0 13736 12385 +1792306490 daemon 10 10 0 0 0 13736 12385 +1792306500 inference 55540 55540 51494 3836 0 13516 12345 +1792306500 strata 104 104 90 0 0 13516 12345 +1792306500 daemon 10 10 0 0 0 13516 12345 +1792306510 inference 56085 56085 52039 3836 0 13736 11804 +1792306510 strata 104 104 89 0 0 13736 11804 +1792306510 daemon 10 10 0 0 0 13736 11804 +1792306520 inference 56086 56086 52041 3836 0 13736 11804 +1792306520 strata 104 104 89 0 0 13736 11804 +1792306520 daemon 10 10 0 0 0 13736 11804 +1792306530 inference 56089 56089 52043 3836 0 13736 11799 +1792306530 strata 104 104 89 0 0 13736 11799 +1792306530 daemon 10 10 0 0 0 13736 11799 +1792306540 inference 56090 56090 52045 3836 0 13736 11794 +1792306540 strata 104 104 89 0 0 13736 11794 +1792306540 daemon 10 10 0 0 0 13736 11794 +1792306550 inference 56233 56233 52188 3836 0 13736 11653 +1792306550 strata 105 105 90 0 0 13736 11653 +1792306550 daemon 10 10 0 0 0 13736 11653 +1792306560 inference 56238 56238 52192 3836 0 13736 11662 +1792306560 strata 105 105 90 0 0 13736 11662 +1792306560 daemon 10 10 0 0 0 13736 11662 +1792306570 inference 56239 56239 52193 3836 0 13736 11654 +1792306570 strata 105 105 90 0 0 13736 11654 +1792306570 daemon 10 10 0 0 0 13736 11654 +1792306580 inference 56382 56382 52337 3836 0 13736 11517 +1792306580 strata 106 106 91 0 0 13736 11517 +1792306580 daemon 10 10 0 0 0 13736 11517 +1792306590 inference 56384 56384 52338 3836 0 13736 11507 +1792306590 strata 106 106 91 0 0 13736 11507 +1792306590 daemon 10 10 0 0 0 13736 11507 +1792306600 inference 56528 56528 52482 3836 0 13736 11352 +1792306600 strata 107 107 93 0 0 13736 11352 +1792306600 daemon 10 10 0 0 0 13736 11352 +1792306610 inference 56529 56529 52484 3836 0 13736 11360 +1792306610 strata 107 107 93 0 0 13736 11360 +1792306610 daemon 10 10 0 0 0 13736 11360 +1792306620 inference 56674 56674 52628 3836 0 13736 11214 +1792306620 strata 108 108 93 0 0 13736 11214 +1792306620 daemon 10 10 0 0 0 13736 11214 +1792306630 inference 56675 56675 52629 3836 0 13736 11214 +1792306630 strata 108 108 93 0 0 13736 11214 +1792306630 daemon 10 10 0 0 0 13736 11214 +1792306640 inference 56676 56676 52630 3836 0 13736 11208 +1792306640 strata 108 108 93 0 0 13736 11208 +1792306640 daemon 10 10 0 0 0 13736 11208 +1792306650 inference 56821 56821 52775 3836 0 13736 11070 +1792306650 strata 109 109 94 0 0 13736 11070 +1792306650 daemon 10 10 0 0 0 13736 11070 +1792306660 inference 56822 56822 52776 3836 0 13516 11070 +1792306660 strata 109 109 94 0 0 13516 11070 +1792306660 daemon 10 10 0 0 0 13516 11070 +1792306670 inference 56825 56825 52779 3836 0 13736 11065 +1792306670 strata 109 109 94 0 0 13736 11065 +1792306670 daemon 10 10 0 0 0 13736 11065 +1792306680 inference 56963 56963 52917 3836 0 13736 10919 +1792306680 strata 110 110 95 0 0 13736 10919 +1792306680 daemon 10 10 0 0 0 13736 10919 +1792306690 inference 56976 56976 52930 3836 0 13736 10898 +1792306690 strata 110 110 95 0 0 13736 10898 +1792306690 daemon 10 10 0 0 0 13736 10898 +1792306700 inference 56977 56977 52931 3836 0 13736 10899 +1792306700 strata 110 110 95 0 0 13736 10899 +1792306700 daemon 10 10 0 0 0 13736 10899 +1792306710 inference 57121 57121 53075 3836 0 13736 10746 +1792306710 strata 110 110 95 0 0 13736 10746 +1792306710 daemon 10 10 0 0 0 13736 10746 +1792306721 inference 57266 57266 53220 3836 0 13736 10612 +1792306721 strata 110 110 96 0 0 13736 10612 +1792306721 daemon 10 10 0 0 0 13736 10612 +1792306731 inference 57270 57270 53224 3836 0 13736 10569 +1792306731 strata 110 110 96 0 0 13736 10569 +1792306731 daemon 10 10 0 0 0 13736 10569 +1792306741 inference 57404 57404 53358 3836 0 13736 10461 +1792306741 strata 111 111 96 0 0 13736 10461 +1792306741 daemon 10 10 0 0 0 13736 10461 +1792306751 inference 57406 57406 53360 3836 0 13516 10465 +1792306751 strata 111 111 96 0 0 13516 10465 +1792306751 daemon 10 10 0 0 0 13516 10465 +1792306761 inference 57421 57421 53375 3836 0 13736 10458 +1792306761 strata 111 111 96 0 0 13736 10458 +1792306761 daemon 10 10 0 0 0 13736 10458 +1792306771 inference 57563 57563 53517 3836 0 13736 10323 +1792306771 strata 111 111 97 0 0 13736 10323 +1792306771 daemon 10 10 0 0 0 13736 10323 +1792306781 inference 57566 57566 53520 3836 0 13516 10298 +1792306781 strata 112 112 97 0 0 13516 10298 +1792306781 daemon 10 10 0 0 0 13516 10298 +1792306791 inference 57713 57713 53667 3836 0 13516 10172 +1792306791 strata 112 112 97 0 0 13516 10172 +1792306791 daemon 10 10 0 0 0 13516 10172 +1792306801 inference 57717 57717 53671 3836 0 13736 10167 +1792306801 strata 112 112 97 0 0 13736 10167 +1792306801 daemon 10 10 0 0 0 13736 10167 +1792306811 inference 57719 57719 53673 3836 0 13736 10167 +1792306811 strata 112 112 97 0 0 13736 10167 +1792306811 daemon 10 10 0 0 0 13736 10167 +1792306821 inference 57720 57720 53674 3836 0 13736 10164 +1792306821 strata 112 112 97 0 0 13736 10164 +1792306821 daemon 10 10 0 0 0 13736 10164 +1792306831 inference 57722 57722 53676 3836 0 13736 10158 +1792306831 strata 112 112 97 0 0 13736 10158 +1792306831 daemon 10 10 0 0 0 13736 10158 +1792306841 inference 57723 57723 53677 3836 0 13736 10153 +1792306841 strata 112 112 97 0 0 13736 10153 +1792306841 daemon 10 10 0 0 0 13736 10153 +1792306851 inference 58150 58150 54104 3836 0 13736 9728 +1792306851 strata 112 112 97 0 0 13736 9728 +1792306851 daemon 10 10 0 0 0 13736 9728 +1792306861 inference 58152 58152 54106 3836 0 13516 9710 +1792306861 strata 112 112 98 0 0 13516 9710 +1792306861 daemon 10 10 0 0 0 13516 9710 +1792306871 inference 58155 58155 54109 3836 0 13736 9716 +1792306871 strata 112 112 97 0 0 13736 9716 +1792306871 daemon 10 10 0 0 0 13736 9716 +1792306881 inference 58298 58298 54252 3836 0 13736 9558 +1792306881 strata 113 113 98 0 0 13736 9558 +1792306881 daemon 10 10 0 0 0 13736 9558 +1792306891 inference 58303 58303 54257 3836 0 13736 9550 +1792306891 strata 113 113 98 0 0 13736 9550 +1792306891 daemon 10 10 0 0 0 13736 9550 +1792306901 inference 58303 58303 54257 3836 0 13736 9562 +1792306901 strata 113 113 98 0 0 13736 9562 +1792306901 daemon 10 10 0 0 0 13736 9562 +1792306911 inference 58305 58305 54259 3836 0 13516 9558 +1792306911 strata 113 113 98 0 0 13516 9558 +1792306911 daemon 10 10 0 0 0 13516 9558 +1792306921 inference 58474 58474 54428 3836 0 13736 9385 +1792306921 strata 113 113 98 0 0 13736 9385 +1792306921 daemon 10 10 0 0 0 13736 9385 +1792306931 inference 58474 58474 54428 3836 0 13736 9393 +1792306931 strata 113 113 98 0 0 13736 9393 +1792306931 daemon 10 10 0 0 0 13736 9393 +1792306941 inference 58608 58608 54562 3836 0 13736 9256 +1792306941 strata 113 113 99 0 0 13736 9256 +1792306941 daemon 10 10 0 0 0 13736 9256 +1792306951 inference 58610 58610 54564 3836 0 13736 9253 +1792306951 strata 113 113 99 0 0 13736 9253 +1792306951 daemon 10 10 0 0 0 13736 9253 +1792306961 inference 58611 58611 54565 3836 0 13736 9261 +1792306961 strata 113 113 99 0 0 13736 9261 +1792306961 daemon 10 10 0 0 0 13736 9261 +1792306971 inference 58755 58755 54709 3836 0 13736 9135 +1792306971 strata 114 114 99 0 0 13736 9135 +1792306971 daemon 10 10 0 0 0 13736 9135 +1792306981 inference 58758 58758 54712 3836 0 13736 9122 +1792306981 strata 114 114 99 0 0 13736 9122 +1792306981 daemon 10 10 0 0 0 13736 9122 +1792306991 inference 58759 58759 54713 3836 0 13516 9124 +1792306991 strata 114 114 99 0 0 13516 9124 +1792306991 daemon 10 10 0 0 0 13516 9124 +1792307001 inference 58903 58903 54857 3836 0 13736 8975 +1792307001 strata 114 114 99 0 0 13736 8975 +1792307001 daemon 10 10 0 0 0 13736 8975 +1792307011 inference 58904 58904 54858 3836 0 13736 8969 +1792307011 strata 114 114 99 0 0 13736 8969 +1792307011 daemon 10 10 0 0 0 13736 8969 +1792307021 inference 59049 59049 55003 3836 0 13736 8823 +1792307021 strata 114 114 100 0 0 13736 8823 +1792307021 daemon 10 10 0 0 0 13736 8823 +1792307032 inference 59050 59050 55004 3836 0 13736 8803 +1792307032 strata 114 114 100 0 0 13736 8803 +1792307032 daemon 10 10 0 0 0 13736 8803 +1792307042 inference 59051 59051 55005 3836 0 13736 8823 +1792307042 strata 114 114 100 0 0 13736 8823 +1792307042 daemon 10 10 0 0 0 13736 8823 +1792307052 inference 59195 59195 55149 3836 0 13736 8670 +1792307052 strata 115 115 100 0 0 13736 8670 +1792307052 daemon 10 10 0 0 0 13736 8670 +1792307062 inference 59199 59199 55153 3836 0 13736 8675 +1792307062 strata 115 115 100 0 0 13736 8675 +1792307062 daemon 10 10 0 0 0 13736 8675 +1792307072 inference 59201 59201 55155 3836 0 13736 8667 +1792307072 strata 116 116 101 0 0 13736 8667 +1792307072 daemon 10 10 0 0 0 13736 8667 +1792307082 inference 59202 59202 55156 3836 0 13736 8667 +1792307082 strata 116 116 101 0 0 13736 8667 +1792307082 daemon 10 10 0 0 0 13736 8667 +1792307092 inference 59346 59346 55300 3836 0 13736 8516 +1792307092 strata 116 116 101 0 0 13736 8516 +1792307092 daemon 10 10 0 0 0 13736 8516 +1792307102 inference 59489 59489 55443 3836 0 13736 8379 +1792307102 strata 116 116 101 0 0 13736 8379 +1792307102 daemon 10 10 0 0 0 13736 8379 +1792307112 inference 59491 59491 55445 3836 0 13736 8363 +1792307112 strata 116 116 101 0 0 13736 8363 +1792307112 daemon 10 10 0 0 0 13736 8363 +1792307122 inference 59492 59492 55446 3836 0 13516 8363 +1792307122 strata 117 117 102 0 0 13516 8363 +1792307122 daemon 10 10 0 0 0 13516 8363 +1792307132 inference 59492 59492 55446 3836 0 13736 8363 +1792307132 strata 117 117 102 0 0 13736 8363 +1792307132 daemon 10 10 0 0 0 13736 8363 +1792307142 inference 59492 59492 55446 3836 0 13516 8368 +1792307142 strata 117 117 102 0 0 13516 8368 +1792307142 daemon 10 10 0 0 0 13516 8368 +1792307152 inference 59639 59639 55593 3836 0 13516 8199 +1792307152 strata 117 117 102 0 0 13516 8199 +1792307152 daemon 10 10 0 0 0 13516 8199 +1792307162 inference 59783 59783 55737 3836 0 13736 8065 +1792307162 strata 117 117 102 0 0 13736 8065 +1792307162 daemon 10 10 0 0 0 13736 8065 +1792307172 inference 59787 59787 55741 3836 0 13736 8058 +1792307172 strata 117 117 102 0 0 13736 8058 +1792307172 daemon 10 10 0 0 0 13736 8058 +1792307182 inference 59787 59787 55741 3836 0 13736 8064 +1792307182 strata 117 117 102 0 0 13736 8064 +1792307182 daemon 10 10 0 0 0 13736 8064 +1792307192 inference 59931 59931 55885 3836 0 13736 7927 +1792307192 strata 117 117 102 0 0 13736 7927 +1792307192 daemon 10 10 0 0 0 13736 7927 +1792307202 inference 59934 59934 55888 3836 0 13736 7929 +1792307202 strata 117 117 103 0 0 13736 7929 +1792307202 daemon 10 10 0 0 0 13736 7929 +1792307212 inference 59936 59936 55890 3836 0 13736 7916 +1792307212 strata 117 117 103 0 0 13736 7916 +1792307212 daemon 10 10 0 0 0 13736 7916 +1792307222 inference 60078 60078 56032 3836 0 13736 7790 +1792307222 strata 117 117 103 0 0 13736 7790 +1792307222 daemon 10 10 0 0 0 13736 7790 +1792307232 inference 60087 60087 56041 3836 0 13736 7769 +1792307232 strata 118 118 103 0 0 13736 7769 +1792307232 daemon 10 10 0 0 0 13736 7769 +1792307242 inference 60087 60087 56041 3836 0 13736 7785 +1792307242 strata 118 118 103 0 0 13736 7785 +1792307242 daemon 10 10 0 0 0 13736 7785 +1792307252 inference 60120 60120 56074 3836 0 13736 7740 +1792307252 strata 118 118 103 0 0 13736 7740 +1792307252 daemon 10 10 0 0 0 13736 7740 +1792307262 inference 60120 60120 56074 3836 0 13736 7734 +1792307262 strata 118 118 104 0 0 13736 7734 +1792307262 daemon 10 10 0 0 0 13736 7734 +1792307272 inference 60122 60122 56076 3836 0 13736 7729 +1792307272 strata 119 119 104 0 0 13736 7729 +1792307272 daemon 10 10 0 0 0 13736 7729 +1792307282 inference 60123 60123 56077 3836 0 13736 7736 +1792307282 strata 119 119 104 0 0 13736 7736 +1792307282 daemon 10 10 0 0 0 13736 7736 +1792307292 inference 60154 60154 56108 3836 0 13736 7701 +1792307292 strata 119 119 104 0 0 13736 7701 +1792307292 daemon 10 10 0 0 0 13736 7701 +1792307302 inference 60154 60154 56108 3836 0 13736 7710 +1792307302 strata 119 119 104 0 0 13736 7710 +1792307302 daemon 10 10 0 0 0 13736 7710 +1792307312 inference 60184 60184 56138 3836 0 13736 7671 +1792307312 strata 120 120 105 0 0 13736 7671 +1792307312 daemon 10 10 0 0 0 13736 7671 +1792307323 inference 60185 60185 56139 3836 0 13736 7677 +1792307323 strata 121 121 107 0 0 13736 7677 +1792307323 daemon 10 10 0 0 0 13736 7677 +1792307333 inference 60186 60186 56140 3836 0 13736 7679 +1792307333 strata 121 121 107 0 0 13736 7679 +1792307333 daemon 10 10 0 0 0 13736 7679 +1792307343 inference 60187 60187 56141 3836 0 13736 7674 +1792307343 strata 121 121 107 0 0 13736 7674 +1792307343 daemon 10 10 0 0 0 13736 7674 +1792307353 inference 60189 60189 56143 3836 0 13736 7676 +1792307353 strata 121 121 107 0 0 13736 7676 +1792307353 daemon 10 10 0 0 0 13736 7676 +1792307363 inference 60330 60330 56284 3836 0 13736 7529 +1792307363 strata 122 122 107 0 0 13736 7529 +1792307363 daemon 10 10 0 0 0 13736 7529 +1792307373 inference 60330 60330 56284 3836 0 13516 7530 +1792307373 strata 122 122 107 0 0 13516 7530 +1792307373 daemon 10 10 0 0 0 13516 7530 +1792307383 inference 60330 60330 56284 3836 0 13736 7527 +1792307383 strata 122 122 107 0 0 13736 7527 +1792307383 daemon 10 10 0 0 0 13736 7527 +1792307393 inference 60330 60330 56284 3836 0 13516 7505 +1792307393 strata 123 123 108 0 0 13516 7505 +1792307393 daemon 10 10 0 0 0 13516 7505 +1792307403 inference 60330 60330 56284 3836 0 13516 7500 +1792307403 strata 123 123 108 0 0 13516 7500 +1792307403 daemon 10 10 0 0 0 13516 7500 +1792307413 inference 60330 60330 56284 3836 0 13736 7514 +1792307413 strata 123 123 108 0 0 13736 7514 +1792307413 daemon 10 10 0 0 0 13736 7514 +1792307423 inference 60330 60330 56284 3836 0 13736 7517 +1792307423 strata 123 123 108 0 0 13736 7517 +1792307423 daemon 10 10 0 0 0 13736 7517 +1792307433 inference 60330 60330 56284 3836 0 13736 7509 +1792307433 strata 123 123 108 0 0 13736 7509 +1792307433 daemon 10 10 0 0 0 13736 7509 +1792307443 inference 60330 60330 56284 3836 0 13736 7514 +1792307443 strata 123 123 108 0 0 13736 7514 +1792307443 daemon 10 10 0 0 0 13736 7514 +1792307453 inference 60330 60330 56284 3836 0 13518 7514 +1792307453 strata 123 123 108 0 0 13518 7514 +1792307453 daemon 10 10 0 0 0 13518 7514 +1792307463 inference 60360 60360 56314 3836 0 13736 7474 +1792307463 strata 123 123 108 0 0 13736 7474 +1792307463 daemon 10 10 0 0 0 13736 7474 +1792307473 inference 60360 60360 56314 3836 0 13736 7489 +1792307473 strata 123 123 108 0 0 13736 7489 +1792307473 daemon 10 10 0 0 0 13736 7489 +1792307483 inference 60360 60360 56314 3836 0 13736 7488 +1792307483 strata 123 123 108 0 0 13736 7488 +1792307483 daemon 10 10 0 0 0 13736 7488 +1792307493 inference 60360 60360 56314 3836 0 13736 7491 +1792307493 strata 123 123 108 0 0 13736 7491 +1792307493 daemon 10 10 0 0 0 13736 7491 +1792307503 inference 60376 60376 56330 3836 0 13736 7466 +1792307503 strata 123 123 108 0 0 13736 7466 +1792307503 daemon 10 10 0 0 0 13736 7466 +1792307513 inference 60377 60377 56331 3836 0 13736 7470 +1792307513 strata 123 123 108 0 0 13736 7470 +1792307513 daemon 10 10 0 0 0 13736 7470 +1792307523 inference 60383 60383 56337 3836 0 13736 7466 +1792307523 strata 124 124 109 0 0 13736 7466 +1792307523 daemon 10 10 0 0 0 13736 7466 +1792307533 inference 60383 60383 56337 3836 0 13736 7475 +1792307533 strata 124 124 109 0 0 13736 7475 +1792307533 daemon 10 10 0 0 0 13736 7475 +1792307543 inference 60383 60383 56337 3836 0 13736 7463 +1792307543 strata 124 124 109 0 0 13736 7463 +1792307543 daemon 10 10 0 0 0 13736 7463 +1792307553 inference 60383 60383 56337 3836 0 13736 7471 +1792307553 strata 124 124 109 0 0 13736 7471 +1792307553 daemon 10 10 0 0 0 13736 7471 +1792307563 inference 60383 60383 56337 3836 0 13736 7443 +1792307563 strata 124 124 109 0 0 13736 7443 +1792307563 daemon 10 10 0 0 0 13736 7443 +1792307573 inference 60383 60383 56337 3836 0 13736 7449 +1792307573 strata 124 124 110 0 0 13736 7449 +1792307573 daemon 10 10 0 0 0 13736 7449 +1792307583 inference 60383 60383 56337 3836 0 13736 7461 +1792307583 strata 125 125 110 0 0 13736 7461 +1792307583 daemon 10 10 0 0 0 13736 7461 +1792307593 inference 60383 60383 56337 3836 0 13736 7471 +1792307593 strata 125 125 110 0 0 13736 7471 +1792307593 daemon 10 10 0 0 0 13736 7471 +1792307603 inference 60383 60383 56337 3836 0 13736 7470 +1792307603 strata 125 125 110 0 0 13736 7470 +1792307603 daemon 10 10 0 0 0 13736 7470 +1792307613 inference 60383 60383 56337 3836 0 13736 7466 +1792307613 strata 125 125 110 0 0 13736 7466 +1792307613 daemon 10 10 0 0 0 13736 7466 +1792307624 inference 60383 60383 56337 3836 0 13736 7473 +1792307624 strata 125 125 110 0 0 13736 7473 +1792307624 daemon 10 10 0 0 0 13736 7473 +1792307634 inference 60383 60383 56337 3836 0 13736 7473 +1792307634 strata 125 125 111 0 0 13736 7473 +1792307634 daemon 10 10 0 0 0 13736 7473 +1792307644 inference 60383 60383 56337 3836 0 13736 7454 +1792307644 strata 126 126 111 0 0 13736 7454 +1792307644 daemon 10 10 0 0 0 13736 7454 +1792307654 inference 60383 60383 56337 3836 0 13736 7450 +1792307654 strata 126 126 111 0 0 13736 7450 +1792307654 daemon 10 10 0 0 0 13736 7450 +1792307664 inference 60383 60383 56337 3836 0 13736 7459 +1792307664 strata 126 126 111 0 0 13736 7459 +1792307664 daemon 10 10 0 0 0 13736 7459 +1792307674 inference 60383 60383 56337 3836 0 13736 7458 +1792307674 strata 127 127 112 0 0 13736 7458 +1792307674 daemon 10 10 0 0 0 13736 7458 +1792307684 inference 60383 60383 56337 3836 0 13736 7457 +1792307684 strata 127 127 112 0 0 13736 7457 +1792307684 daemon 10 10 0 0 0 13736 7457 +1792307694 inference 60383 60383 56337 3836 0 13736 7456 +1792307694 strata 127 127 112 0 0 13736 7456 +1792307694 daemon 10 10 0 0 0 13736 7456 +1792307704 inference 60383 60383 56337 3836 0 13736 7455 +1792307704 strata 127 127 112 0 0 13736 7455 +1792307704 daemon 10 10 0 0 0 13736 7455 +1792307714 inference 60383 60383 56337 3836 0 13736 7449 +1792307714 strata 127 127 112 0 0 13736 7449 +1792307714 daemon 10 10 0 0 0 13736 7449 +1792307724 inference 60383 60383 56337 3836 0 13736 7453 +1792307724 strata 127 127 112 0 0 13736 7453 +1792307724 daemon 10 10 0 0 0 13736 7453 +1792307734 inference 60383 60383 56337 3836 0 13516 7458 +1792307734 strata 127 127 112 0 0 13516 7458 +1792307734 daemon 10 10 0 0 0 13516 7458 +1792307744 inference 60383 60383 56337 3836 0 13516 7459 +1792307744 strata 128 128 113 0 0 13516 7459 +1792307744 daemon 10 10 0 0 0 13516 7459 +1792307754 inference 60383 60383 56337 3836 0 13736 7467 +1792307754 strata 128 128 113 0 0 13736 7467 +1792307754 daemon 10 10 0 0 0 13736 7467 +1792307764 inference 60383 60383 56337 3836 0 13736 7460 +1792307764 strata 128 128 113 0 0 13736 7460 +1792307764 daemon 10 10 0 0 0 13736 7460 +1792307774 inference 60383 60383 56337 3836 0 13736 7451 +1792307774 strata 128 128 113 0 0 13736 7451 +1792307774 daemon 10 10 0 0 0 13736 7451 +1792307784 inference 60383 60383 56337 3836 0 13736 7461 +1792307784 strata 128 128 113 0 0 13736 7461 +1792307784 daemon 10 10 0 0 0 13736 7461 +1792307794 inference 60383 60383 56337 3836 0 13736 7459 +1792307794 strata 128 128 113 0 0 13736 7459 +1792307794 daemon 10 10 0 0 0 13736 7459 diff --git a/docs/e2e-data/945-trace.csv b/docs/e2e-data/945-trace.csv new file mode 100644 index 00000000..3de7dbcd --- /dev/null +++ b/docs/e2e-data/945-trace.csv @@ -0,0 +1,85 @@ +idx,t_start_ms,t_done_ms,finish,prompt_tokens,reused_tokens,reprefilled_tokens,ttft_ms,decode_tokens,decode_ms,decode_tok_s,engine_prefill_tokens,engine_prefill_ms,engine_prefill_tok_s,rounds,tokens_per_round,vram_expert_share,pcie_expert_share,swaps,prefix_hit,prefix_resume,prefix_import_ms,gap_before_ms,tool_exec_in_gap_ms,queue_wait_ms,inference_rss_mib,gpu_mib,mem_available_mib,join_ok +0,1792306270036,1792306280884,Stop,10008,0,10008,9686.4,66,1161.6,56.0,10007,9301.7,1075.8,20,3.3,0.265,0.322,2385,no,0,,,,0,54642,13686,13266,True +1,1792306280960,1792306365599,Stop,10328,8192,2136,2385.9,6023,82252.9,73.2,2135,2112.3,1010.7,2053,2.93,0.521,0.221,50534,yes,8192,1.3,76,0,0,55175,13516,12735,True +2,1792306365725,1792306383902,Stop,16561,10240,6321,5262.5,839,12914.1,64.9,6320,5036.7,1254.8,341,2.46,0.557,0.205,9185,yes,10240,1.8,126,0,0,55350,13736,12567,True +3,1792306383990,1792306397598,Stop,17518,16384,1134,1440.1,844,12167.7,69.3,1133,1236.6,916.2,336,2.51,0.596,0.186,9051,yes,16384,1.5,88,1,0,55496,13736,12417,True +4,1792306397725,1792306498596,Stop,18505,16384,2121,2190.6,8277,98681.0,83.9,2120,1970.6,1075.8,2460,3.36,0.535,0.218,60139,yes,16384,1.6,127,0,0,55540,13516,12345,True +5,1792306498664,1792306545106,Stop,26841,18432,8409,7109.2,3254,39332.4,82.7,8408,6850.1,1227.4,1014,3.21,0.555,0.208,25085,yes,18432,2.4,68,0,0,56233,13736,11653,True +6,1792306545166,1792306552326,Stop,30131,26624,3507,3126.4,268,4033.7,66.2,3506,2875.3,1219.4,93,2.88,0.45,0.249,2977,yes,26624,2.3,60,0,0,56233,13736,11653,True +7,1792306552420,1792306571749,Stop,30468,28672,1796,1757.0,1569,17572.8,89.2,1795,1514.9,1184.9,320,4.9,0.427,0.266,9114,yes,28672,2.1,94,1,0,56239,13736,11654,True +8,1792306571822,1792306595592,Stop,32095,28672,3423,3339.0,1689,20431.2,82.6,3422,3081.7,1110.4,470,3.59,0.473,0.249,12022,yes,28672,2.4,73,0,0,56528,13736,11352,True +9,1792306595664,1792306615168,Stop,33844,30720,3124,3171.8,1334,16332.7,81.6,3123,2917.4,1070.5,352,3.79,0.426,0.27,9147,yes,30720,2.4,72,0,0,56674,13736,11214,True +10,1792306615242,1792306643827,Stop,35237,32768,2469,2924.8,2091,25660.5,81.4,2468,2673.9,923.0,554,3.77,0.436,0.268,13994,yes,32768,2.3,74,0,0,56676,13736,11208,True +11,1792306643902,1792306660531,Stop,37388,34816,2572,3004.5,1064,13624.4,78.0,2571,2753.9,933.6,290,3.67,0.419,0.275,7577,yes,34816,2.4,75,0,0,56822,13516,11070,True +12,1792306660607,1792306672364,Stop,38511,36864,1647,1738.4,817,10019.3,81.4,1646,1497.0,1099.5,213,3.84,0.413,0.274,5757,yes,36864,2.4,76,0,0,56825,13736,11065,True +13,1792306672440,1792306688249,Stop,39387,36864,2523,3005.9,1049,12803.2,81.9,2522,2760.4,913.6,291,3.6,0.462,0.25,7497,yes,36864,2.5,76,0,0,56976,13736,10898,True +14,1792306688327,1792306706858,Stop,40496,38912,1584,1732.7,1449,16798.6,86.2,1583,1481.5,1068.5,398,3.64,0.504,0.233,10315,yes,38912,2.4,78,0,0,57121,13736,10746,True +15,1792306707150,1792306714274,Stop,42669,38912,3757,3347.3,259,3776.9,68.3,3756,3133.5,1198.7,77,3.36,0.377,0.284,2501,yes,38912,2.6,292,70,0,57121,13736,10746,True +16,1792306714455,1792306725474,Stop,43661,40960,2701,3048.9,553,7969.2,69.3,2700,2820.9,957.1,169,3.27,0.405,0.276,4932,yes,40960,2.3,181,0,0,57266,13736,10612,True +17,1792306725653,1792306732901,Stop,44852,43008,1844,1772.1,367,5475.4,66.8,1843,1544.3,1193.4,129,2.84,0.478,0.242,4239,yes,43008,2.3,179,1,0,57270,13736,10569,True +18,1792306733077,1792306749836,Stop,45594,43008,2586,2982.5,978,13776.4,70.9,2585,2744.9,941.7,317,3.09,0.476,0.245,8722,yes,43008,2.3,176,0,0,57406,13516,10465,True +19,1792306749919,1792306755989,Stop,46630,45056,1574,1663.1,350,4406.8,79.2,1573,1438.8,1093.3,89,3.93,0.398,0.276,3115,yes,45056,2.4,83,0,0,57406,13516,10465,True +20,1792306756103,1792306764635,Stop,47062,45056,2006,1768.5,510,6763.8,75.3,2005,1545.4,1297.4,138,3.7,0.391,0.283,4381,yes,45056,2.4,114,1,0,57421,13736,10458,True +21,1792306764819,1792306773148,Stop,47789,45056,2733,3122.3,386,5206.7,73.9,2732,2890.5,945.2,108,3.57,0.405,0.279,3619,yes,45056,2.4,184,1,0,57563,13736,10323,True +22,1792306773333,1792306780636,Stop,48541,47104,1437,1701.6,389,5602.0,69.3,1436,1484.8,967.1,116,3.35,0.397,0.274,3682,yes,47104,2.3,185,1,0,57566,13516,10298,True +23,1792306780877,1792306786049,Stop,49818,47104,2714,2986.1,150,2185.7,68.2,2713,2750.8,986.3,45,3.33,0.392,0.279,2134,yes,47104,2.4,241,15,0,57713,13516,10172,True +24,1792306786202,1792306789993,Stop,50236,49152,1084,1580.7,167,2210.7,75.1,1083,1354.1,799.8,39,4.28,0.354,0.29,1987,yes,49152,2.3,153,1,0,57713,13516,10172,True +25,1792306790174,1792306793279,Stop,50716,49152,1564,1735.7,101,1369.6,73.0,1563,1518.9,1029.0,26,3.88,0.373,0.282,1365,yes,49152,2.3,181,1,0,57713,13516,10172,True +26,1792306793458,1792306843695,Stop,51084,49152,1932,1763.1,4363,48474.0,90.0,1931,1562.6,1235.8,1208,3.61,0.552,0.21,29545,yes,49152,2.4,179,0,0,57723,13736,10153,True +27,1792306843891,1792306861009,Stop,55559,49152,6407,5884.3,749,11233.9,66.6,6406,5650.7,1133.7,249,3.01,0.444,0.258,6726,yes,49152,2.8,196,2,0,58152,13516,9710,True +28,1792306861106,1792306872977,Stop,56366,55296,1070,1600.4,898,10270.8,87.3,1069,1373.3,778.4,244,3.68,0.506,0.233,6839,yes,55296,2.3,97,0,0,58155,13736,9716,True +29,1792306873167,1792306877581,Stop,57362,55296,2066,2184.9,151,2228.8,67.3,2065,1950.4,1058.8,51,2.96,0.42,0.264,2076,yes,55296,2.4,190,1,0,58298,13736,9558,True +30,1792306877702,1792306885339,Stop,57582,57344,238,1114.5,427,6522.7,65.3,237,913.6,259.4,161,2.65,0.511,0.226,4371,yes,57344,2.3,121,1,0,58298,13736,9558,True +31,1792306885418,1792306889337,Stop,58205,57344,861,1477.5,192,2441.9,78.2,860,1231.3,698.4,56,3.43,0.455,0.252,1934,yes,57344,2.4,79,0,0,58303,13736,9550,True +32,1792306889520,1792306911445,Stop,58546,57344,1202,1581.8,1476,20342.4,72.5,1201,1361.7,882.0,456,3.24,0.446,0.257,11788,yes,57344,2.3,183,1,0,58305,13516,9558,True +33,1792306911640,1792306937274,Stop,60184,57344,2840,3079.1,1467,22554.8,65.0,2839,2847.1,997.2,549,2.67,0.52,0.224,14138,yes,57344,2.5,195,1,0,58608,13736,9256,True +34,1792306937402,1792306965302,Stop,62779,59392,3387,3282.8,1861,24616.9,75.6,3386,3027.3,1118.5,538,3.46,0.474,0.247,14109,yes,59392,2.5,128,1,0,58611,13736,9261,True +35,1792306965438,1792306973087,Stop,64719,61440,3279,3285.2,336,4363.7,76.8,3278,3042.5,1077.4,86,3.91,0.388,0.284,3100,yes,61440,2.5,136,1,0,58755,13736,9135,True +36,1792306973199,1792306990676,Stop,65112,63488,1624,1768.7,1225,15707.9,77.9,1623,1540.1,1053.8,337,3.64,0.466,0.248,8897,yes,63488,2.4,112,0,0,58759,13516,9124,True +37,1792306990781,1792307017081,Stop,66394,63488,2906,3125.6,1915,23174.1,82.6,2905,2889.6,1005.3,453,4.23,0.449,0.259,11659,yes,63488,2.6,105,0,0,59049,13736,8823,True +38,1792307017191,1792307042990,Stop,68366,65536,2830,3098.3,1863,22700.9,82.0,2829,2865.0,987.4,442,4.21,0.434,0.265,11441,yes,65536,2.5,110,0,0,59051,13736,8823,True +39,1792307043132,1792307057458,Stop,70308,67584,2724,3130.5,880,11195.9,78.5,2723,2895.9,940.3,209,4.21,0.404,0.276,5718,yes,67584,2.6,142,1,0,59199,13736,8675,True +40,1792307057596,1792307062610,Stop,71267,69632,1635,1771.0,217,3243.2,66.6,1634,1548.9,1054.9,62,3.5,0.347,0.297,2128,yes,69632,2.4,138,1,0,59199,13736,8675,True +41,1792307062721,1792307085432,Stop,71541,69632,1909,1853.2,1631,20857.8,78.1,1908,1622.1,1176.3,432,3.78,0.432,0.264,11193,yes,69632,2.4,111,0,0,59202,13736,8667,True +42,1792307085647,1792307094736,Stop,73343,69632,3711,3417.5,349,5671.8,61.4,3710,3173.5,1169.1,112,3.12,0.358,0.29,3581,yes,69632,2.6,215,1,0,59346,13736,8516,True +43,1792307094944,1792307115890,Stop,73789,71680,2109,2473.1,1308,18472.7,70.8,2108,2222.1,948.7,390,3.35,0.411,0.275,10498,yes,71680,2.5,208,1,0,59491,13736,8363,True +44,1792307116032,1792307122157,Stop,75176,73728,1448,1705.2,341,4419.7,76.9,1447,1477.3,979.5,89,3.83,0.406,0.276,2906,yes,73728,2.4,142,1,0,59492,13516,8363,True +45,1792307122370,1792307140963,Stop,75626,73728,1898,1802.2,1321,16790.4,78.6,1897,1573.9,1205.3,357,3.7,0.433,0.267,9373,yes,73728,2.4,213,0,0,59492,13516,8368,True +46,1792307141185,1792307152379,Stop,77257,73728,3529,3329.1,583,7864.9,74.0,3528,3084.6,1143.7,167,3.49,0.427,0.268,4924,yes,73728,2.6,222,1,0,59639,13516,8199,True +47,1792307152597,1792307170199,Stop,77938,75776,2162,2628.0,1070,14974.0,71.4,2161,2376.5,909.3,322,3.32,0.438,0.263,8772,yes,75776,2.5,218,1,0,59787,13736,8058,True +48,1792307170318,1792307187880,Stop,79065,77824,1241,1677.0,1234,15884.8,77.6,1240,1449.6,855.4,342,3.61,0.442,0.261,8901,yes,77824,2.4,119,0,0,59931,13736,7927,True +49,1792307188115,1792307194278,Stop,80561,77824,2737,3168.7,223,2995.0,74.1,2736,2931.6,933.3,57,3.91,0.352,0.3,2125,yes,77824,2.6,235,1,0,59931,13736,7927,True +50,1792307194501,1792307219296,Stop,80886,79872,1014,1644.0,1572,23151.4,67.9,1013,1412.8,717.0,516,3.05,0.458,0.253,13145,yes,79872,2.5,223,1,0,60078,13736,7790,True +51,1792307219493,1792307224291,Stop,82672,79872,2800,3162.7,111,1635.1,67.3,2799,2918.8,959.0,35,3.17,0.377,0.288,1729,yes,79872,2.6,197,1,0,60078,13736,7790,True +52,1792307224434,1792307228865,Stop,83024,81920,1104,1670.4,209,2760.4,75.4,1103,1431.5,770.5,56,3.73,0.366,0.281,2210,yes,81920,2.5,143,1,0,60087,13736,7769,True +53,1792307229055,1792307248061,Stop,83373,81920,1453,1713.1,1310,17293.1,75.7,1452,1493.9,972.0,360,3.64,0.425,0.274,9223,yes,81920,2.5,190,1,0,60120,13736,7740,True +54,1792307248307,1792307259743,Stop,84826,81920,2906,3215.6,534,8219.9,64.8,2905,2975.8,976.2,169,3.16,0.391,0.28,4801,yes,81920,2.6,246,1,0,60120,13736,7734,True +55,1792307259894,1792307264167,Stop,85438,83968,1470,1746.6,186,2526.1,73.2,1469,1512.8,971.0,48,3.88,0.34,0.299,1942,yes,83968,2.5,151,0,0,60120,13736,7734,True +56,1792307264402,1792307286503,Stop,85722,83968,1754,1835.5,1612,20265.2,79.5,1753,1597.2,1097.5,440,3.66,0.454,0.258,11409,yes,83968,2.5,235,1,0,60123,13736,7736,True +57,1792307286742,1792307309244,Stop,87474,83968,3506,3347.1,1573,19155.5,82.1,3505,3104.5,1129.0,333,4.72,0.406,0.273,8843,yes,83968,2.7,239,1,0,60184,13736,7671,True +58,1792307309499,1792307315509,Stop,89280,86016,3264,3370.5,196,2639.1,73.9,3263,3119.6,1046.0,48,4.08,0.337,0.299,2074,yes,86016,2.7,255,1,0,60184,13736,7671,True +59,1792307315754,1792307356249,Stop,89577,88064,1513,1811.9,2989,38683.0,77.2,1512,1575.4,959.8,854,3.5,0.462,0.254,21179,yes,88064,2.5,245,1,0,60189,13736,7676,True +60,1792307356511,1792307371568,Stop,92812,88064,4748,4751.6,746,10305.0,72.3,4747,4505.9,1053.5,206,3.62,0.395,0.286,5797,yes,88064,2.8,262,2,0,60330,13516,7530,True +61,1792307371834,1792307390162,Stop,93685,92160,1525,1805.8,1143,16521.8,69.1,1524,1568.4,971.7,357,3.2,0.446,0.261,9276,yes,92160,2.6,266,1,0,60330,13516,7505,True +62,1792307390424,1792307403041,Stop,94935,92160,2775,3213.3,645,9403.6,68.5,2774,2962.2,936.5,186,3.47,0.392,0.278,5331,yes,92160,2.7,262,2,0,60330,13516,7500,True +63,1792307403300,1792307452449,Stop,95693,94208,1485,1787.8,2772,47361.2,58.5,1484,1542.4,962.1,1147,2.42,0.533,0.218,28372,yes,94208,2.6,259,0,0,60330,13518,7514,True +64,1792307452616,1792307495757,Stop,100503,94208,6295,5793.3,2482,37348.3,66.4,6294,5517.6,1140.7,833,2.98,0.474,0.248,21174,yes,94208,2.8,167,1,0,60360,13736,7491,True +65,1792307495934,1792307507904,Stop,103062,100352,2710,3152.4,659,8818.2,74.6,2709,2885.3,938.9,185,3.56,0.434,0.265,5606,yes,100352,2.7,177,1,0,60376,13736,7466,True +66,1792307508052,1792307515103,Stop,103778,102400,1378,1737.1,426,5314.3,80.0,1377,1494.9,921.1,106,4.02,0.408,0.274,3282,yes,102400,2.5,148,0,0,60377,13736,7470,True +67,1792307515376,1792307535418,Stop,104315,102400,1915,1872.3,1313,18170.3,72.2,1914,1628.9,1175.0,371,3.54,0.426,0.272,9656,yes,102400,2.6,273,1,0,60383,13736,7475,True +68,1792307535569,1792307560038,Stop,105685,102400,3285,3310.7,1608,21157.8,76.0,3284,3061.6,1072.6,435,3.7,0.429,0.271,11289,yes,102400,2.7,151,0,0,60383,13736,7443,True +69,1792307560329,1792307565910,Stop,107837,104448,3389,3350.7,141,2230.8,62.8,3388,3095.2,1094.6,43,3.28,0.323,0.306,1835,yes,104448,2.7,291,1,0,60383,13736,7443,True +70,1792307566092,1792307579980,Stop,108922,106496,2426,3009.4,902,10878.1,82.8,2425,2745.3,883.3,193,4.67,0.419,0.266,5676,yes,106496,2.6,182,7,0,60383,13736,7461,True +71,1792307580254,1792307607316,Stop,109922,108544,1378,1757.4,1854,25304.8,73.2,1377,1522.5,904.4,547,3.39,0.447,0.259,13592,yes,108544,2.6,274,1,0,60383,13736,7470,True +72,1792307607599,1792307618646,Stop,111878,108544,3334,3387.3,488,7659.5,63.6,3333,3128.0,1065.5,170,2.87,0.459,0.25,5015,yes,108544,2.7,283,1,0,60383,13736,7473,True +73,1792307618843,1792307628111,Stop,112472,110592,1880,1860.7,459,7407.5,61.8,1879,1617.1,1162.0,158,2.91,0.424,0.267,4361,yes,110592,2.6,197,1,0,60383,13736,7473,True +74,1792307628266,1792307635034,Stop,112988,110592,2396,2992.4,297,3775.9,78.4,2395,2727.3,878.2,75,3.96,0.405,0.277,2792,yes,110592,2.6,155,0,0,60383,13736,7473,True +75,1792307635189,1792307650079,Stop,113342,112640,702,1525.2,1044,13365.2,78.0,701,1282.5,546.6,254,4.11,0.433,0.264,6860,yes,112640,2.6,155,0,0,60383,13736,7450,True +76,1792307650368,1792307659811,Stop,114486,112640,1846,1871.0,502,7572.1,66.2,1845,1622.0,1137.5,132,3.8,0.324,0.31,3907,yes,112640,2.7,289,1,0,60383,13736,7459,True +77,1792307660103,1792307669777,Stop,115092,112640,2452,3110.2,445,6563.5,67.6,2451,2854.0,858.8,145,3.07,0.449,0.253,4292,yes,112640,2.7,292,0,0,60383,13736,7458,True +78,1792307670026,1792307708814,Stop,115701,114688,1013,1690.8,2335,37097.6,62.9,1012,1434.3,705.6,827,2.82,0.463,0.249,20763,yes,114688,2.6,249,0,0,60383,13736,7455,True +79,1792307709107,1792307733756,Stop,118130,114688,3442,3260.3,1469,21389.3,68.6,3441,2994.1,1149.3,433,3.39,0.433,0.265,11321,yes,114688,2.8,293,1,0,60383,13516,7458,True +80,1792307734052,1792307744165,Stop,119690,116736,2954,3175.3,409,6937.1,58.8,2953,2905.7,1016.3,158,2.59,0.478,0.24,4702,yes,116736,2.7,296,1,0,60383,13516,7459,True +81,1792307744411,1792307756346,Stop,120200,118784,1416,1768.2,811,10167.0,79.7,1415,1500.9,942.8,243,3.34,0.53,0.219,6845,yes,118784,2.7,246,1,0,60383,13736,7467,True +82,1792307756579,1792307770560,Stop,122451,118784,3667,3426.1,665,10554.8,62.9,3666,3154.2,1162.3,248,2.68,0.51,0.226,6994,yes,118784,2.7,233,1,0,60383,13736,7451,True +83,1792307770852,1792307795440,Stop,123239,120832,2407,3010.9,1251,21576.5,57.9,2406,2726.2,882.5,486,2.57,0.484,0.244,13002,yes,120832,2.8,292,1,0,60383,13736,7459,True diff --git a/docs/e2e-run.md b/docs/e2e-run.md index c787f895..ce036011 100644 --- a/docs/e2e-run.md +++ b/docs/e2e-run.md @@ -16,23 +16,26 @@ leleka-cli load-mtp (through leleka-daemon 127.0.0.1:18080) loads the model; str ## 1. Binaries (built in WSL, never on the server) `cargo build --release --locked -p strata-desktop-core --bin leleka-inference --bin leleka-daemon --bin leleka-cli -p strata-control --bin strata-next -p leleka-deploy --bin leleka` -from tree `da187a9` (the later commits only touch the client scripts; rustc 1.99.0, WSL2 Ubuntu 24.04, `CARGO_TARGET_DIR` outside the tree). Only the first four were copied to -`rnr5090:~/work/leleka-e2e/bin-sm120/` (`scp`, mode 0755). The sm86 binaries were built, run with `--help` in WSL (RTX 3080 Laptop, cc 8.6, -`ldd`: libc, libm, libgcc_s) and not run against a model here. +(rustc 1.99.0, WSL2 Ubuntu 24.04, `CARGO_TARGET_DIR` outside the tree), sm_120 default and `--features strata-desktop-core/sm86`. Only the first four were copied to +`rnr5090:~/work/leleka-e2e/bin-sm120/` (`scp`, mode 0755). The sm86 binaries were built and started with `--help` in WSL (RTX 3080 Laptop, cc 8.6, `ldd`: libc, libm, libgcc_s), not run against a model here. -| binary | sm_120 (default) bytes | sm_120 sha256 | `--features sm86` bytes | sm86 sha256 | +Final build, tree `73e77f8` (= `claude/port-gpu-bringup` head `4f7c461`-era merge + this branch; the Codex jobs 943b / 945 ran the earlier build listed second): + +| binary | sm_120 bytes | sm_120 sha256 | sm86 bytes | sm86 sha256 | | --- | ---: | --- | ---: | --- | -| leleka-inference | 68,432,360 | `2506b49ca2576a7c24220481cfb96a9d51224da8230a1b803114e83b38cae059` | 119,298,624 | `02cbbce483977e43abd22e8610b14757dda25b9c9221ffa995a2ef7233273d52` | -| leleka-daemon | 23,295,656 | `5d113eb8404fbe06f9a0f53ee9ce7fd01fe03f39d5d1e08e3bf0a0799833ba9b` | 23,295,240 | `0162f9088265b6cd3385c6fc263468a2dd0c9daa26910b5293500374ef9e8ae0` | -| leleka-cli | 10,431,080 | `f465280ed9c730cd313b481cc62efbeb6d049d90f805e69a09f3f12d814f2ba0` | 10,431,040 | `bdaa1ca5f9eec1178345e09be8c03f84fb67f38f6466e3fb40e4b2a5596e4c7c` | -| strata-next | 28,747,720 | `5eb6238e72b416f0deb945c32d9de5939b75cb6cb97b3ade3c35a97425363a4c` | 28,747,816 | `23ce07613392014dbed90bcddf166f7a41f17a065d3d0536b0b09765255178a9` | -| leleka (deploy, not copied) | 2,892,048 | `db4ce35308bdf427b062c161ebd0049e01c358a0bab6ec8252c465e775aaf6c8` | 2,892,048 | same | +| leleka-inference | 69,249,120 | `0eb83374e9782ded5c2d8d62d2552b4efd8c37142ea62d3d2309f9fcfe40eb26` | 120,106,704 | `30e08783873e7dc952020a8f93cf9232ef7ccb4c7f07ed5a18fbb8b81e6f0a2d` | +| leleka-daemon | 23,340,736 | `f7908fc6f4d5924bb9b3ebbd1ef7e7158fcc8bdde72d5efe515a896973b17cbb` | 23,340,024 | `a73a1c0e8ecc7241436a81c2da85fa9b8ce6369712a7fbc1ad87a75e2ed1a63d` | +| leleka-cli | 10,462,568 | `19bf908a56e900677b46488a11c1860cc7e524a1d9615b72a1effa712b5f2d3b` | 10,462,472 | `8c44891388e859e8c1525bfa0fc8b8df10e3d24b73950470b0620f3bdb7b7f2c` | +| strata-next | 28,834,064 | `ce98d23fd4e9efcbd3c46ca322641c1cbec8b3af142762866467143b3533b9b7` | 28,834,048 | `2fa5573f1c2062e50e6e9e8c6e0a4af704906222ba3ef6f92efacc6f9721d0f2` | +| leleka (deploy supervisor, not copied) | 2,938,592 | `b2be6e21e19975387141f314ecc92c681bb8a91e48338b102ca432d96a87d053` | 2,938,592 | same | +| leleka-runtime-tests (replay smoke, server: `leleka-runtime-tests-73e77f8`) | 79,533,344 | `4d0b400d951f0f485a5b31c66c8952669b11a64323dc46896b937b4a1a49a321` | | | -(The `strata-next` sm_120 file differs from the sm86 one although the feature does not touch it: Cargo unifies features per build, byte -identity across the two builds is not expected.) The `leleka` supervisor (native sealed memfd) is not used by these jobs: inside a holder -job a second 55 GB memfd would not fit, so `scripts/e2e/run-e2e.sh` starts the same processes with the holder's descriptor -(`--kar-archive-fd $LELEKA_STRA169_KAR_FD`), the flags of `deploy/rust-runtime/profiles/rtx5090-32g.json` (`--gpu-budget 25769803776`, -`--context-tokens 262144`, resident expert source) and the bring-up expert-tier environment of the 98x jobs. +Binaries of the Codex jobs 943b / 945 and the replay job 947 (the server copies in `bin-sm120/`): `leleka-inference` `484b7622274ec80cab5357dd304de41c5a311163161a5daf7e4771fe8f1c4eae`, +`leleka-daemon` `8d681a3a3a88d5b354481766998fc5a72780e8d0e942c57e3280baaecdd8d0bd`, `leleka-cli` `8615325793196b3740a584916e70b09bedaa5c16a3e1d03ba955cae5749bbd0c`, +`strata-next` `ac0bfa40215844148785680697c693c01616c7ec0bcb34f65e3623af849c0768`, `leleka-runtime-tests` `a4dfb8530b76a19e7114c64ee0ebf1062d9a52d533cb46310fd31a4d73bbfc2e`. +Cargo unifies features per build, so byte identity of `strata-next` / `leleka-daemon` between the sm_120 and sm86 builds is not expected. The `leleka` supervisor (native sealed memfd) is not used by these +jobs: inside a holder job a second 55 GB memfd would not fit, so `scripts/e2e/run-e2e.sh` starts the same processes with the holder's descriptor (`--kar-archive-fd $LELEKA_STRA169_KAR_FD`), the flags of +`deploy/rust-runtime/profiles/rtx5090-32g.json` (`--gpu-budget 25769803776`, `--context-tokens 262144`, resident expert source) and the bring-up expert-tier environment of the 98x jobs. ## 2. How to rerun @@ -147,32 +150,97 @@ need the quality gate of `AGENTS.md`): schema-driven constrained decoding for to | no leaked processes | `pgrep`, `nvidia-smi --query-compute-apps` after every job | none | | memory stable over 40+ requests | `env.tsv`, soak samples | +0 MiB RSS, +0 MiB VRAM | -## 7. Not done: the real Codex CLI runs (three.js tic-tac-toe, CRM) +## 7. The real Codex CLI (0.163.0) against the stack -The coordinator asked for two long Codex CLI sessions (Three.js tic-tac-toe, then a CRM) against this stack. They were **not run**: both need files -to be downloaded (the Codex release binary, the pinned three.js build and a Playwright chromium for the browser checks; the CRM needs only the Codex binary, -it is specified as Python-stdlib + SQLite so the agent needs nothing else offline), and a download needs the user's explicit confirmation in chat, which -a relayed message does not replace. Nothing was fetched. Neither the server nor the laptop (Windows or WSL) has `codex`, `node` or a browser. +Operator-approved downloads, made by the coordinator and verified: Codex CLI `rust-v0.163.0` `codex-x86_64-unknown-linux-musl` (unpacked binary sha256 +`399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215`, `codex --version` = codex-cli 0.163.0), three.js 0.170.0 (`three.module.min.js`, sha256 +`08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7`), and on the laptop Node 22.16 + Playwright 1.49.1 + Chromium 131 (the server has no node or browser: the +agent verifies with Python only, and the six browser checks run afterwards on the laptop). Config: isolated `CODEX_HOME`, `wire_api = "responses"`, `approval_policy = "never"`, +`sandbox_mode = "workspace-write"` (no network), effort medium, `model_context_window = 262144`, `web_search = "disabled"`, key from a freshly generated test key in `E2E_API_KEY`. +The engine ran with the shipped options (KAR PLE level 2, `--backend-mode original`, spec_min_p 0, expert tier 2048 slots adaptive, INT8 K+V 32768 resident cells), **greedy** +(Codex sends no sampling and the config has no `sampling` block: the Original server's default too), profiling on (`LELEKA_SERVE_PROFILE=1`, `LELEKA_BRINGUP_TRACE=1`), engine capture on. +Prompts: tic-tac-toe `scripts/e2e/codex/prompt-threejs.txt` sha256 `f57248412f69b4a6a76aab00c2ff33ee3ce676849768f847d412c7e9e9d8a074` (own equivalent of the old private prompt, without the +LeaseVibe part); CRM `prompt-crm.txt` sha256 `2ab4d92db393334f1ac953086116cefb9744b522b98bfd4ea6efd7e02e319af9` (phase 1 build, phase 2 seven-item refactor-and-extend to make the agent read and edit many files). -What is ready (`scripts/e2e/codex/`, committed; the job templates are `jobs/943-e2e-codex-ttt.sh` and `jobs/945-e2e-codex-crm.sh`): +What Codex needed from the stack, found before spending GPU time (a mock `/v1/responses` server, `scripts/e2e/codex/mock_responses.py`): its default request carries the hosted tool +`{"type":"web_search"}` (refused with 400 by design, so `web_search = "disabled"` is part of the config, as `scripts/install-qwen-native.py` already does), a `namespace` tool +`multi_agent_v1` (10 KB, accepted), `exec_command` (a string `cmd` parameter, **not** the array `command` of the older `shell` tool: the "shell.command as a string" failure of section 5 cannot occur with +this Codex), `write_stdin`, `view_image`, goal tools, `parallel_tool_calls: true`, a 17 KB developer message, `include: [reasoning.encrypted_content]`; about 9.3k tokens before the first user word. +`apply_patch` is a shell command (`apply_patch < 55.0 GB, VRAM 13.2 -> 13.6 GB, MemAvailable 14.4 -> 12.8 GB | RSS 53.7 -> **60.4 GB**, VRAM 13.3 -> 13.7 GB, MemAvailable 14.0 -> **7.4 GB** (flat from about minute 10) | +| tool-call failures | none at the API (0 `generation failed`); 5 of 53 commands exited non-zero (missing `node`, a malformed `apply_patch` heredoc, grep, a probe, `git status`), all handled by the agent | none at the API; 2 of 60 commands exited 1: a malformed `apply_patch` ("must end with *** End Patch") that Codex returned to the model, which re-sent it correctly | -To run them, the operator must approve and provide (each into its own new empty directory, out of Git, checksums recorded here): +Reading: a real agent session is dominated by **decode (84-86 % of wall time)**. The engine reuses 96.5 % of the prompt, close to the 98-99 % of the vanilla runs, yet both sessions decode at +72-75 tok/s against 116-150 for the vanilla runs on the same host. Decode speed is flat from 4k to 123k of context, so the gap is not a context effect; what differs is the engine +configuration (shipped spec_min_p 0, tier hits 43-49 % from VRAM) and the accepted drafts per round (2.9-3.4 tokens per verify round); suffix-draft share is not logged. The prefix cache +(CRM) served 83 of 84 prompts from a stored checkpoint (`hits=83 misses=1`, 7.3 of a 7.5 GiB budget used, 23 evictions) but resumes at a 2048-token grid node, so every turn re-reads +the partial block (about 2.2k tokens per turn against a roughly 340-token real suffix); the conversation cache of the tic-tac-toe run re-read about 1.1k per turn. -1. the Codex CLI Linux x86_64 musl release binary from `github.com/openai/codex/releases` -> `rnr5090:~/work/codex-e2e/bin/codex` (record file name, URL, size, sha256 and the published checksum); -2. for the game: a pinned `three.module.min.js` -> `~/work/codex-e2e/vendor/`, and Node + `playwright` + chromium -> `~/work/codex-e2e/node` (`CODEX_NODE_DIR`). +MemAvailable dips: the CRM session's 7.4 GB minimum is the prefix cache filling its auto budget (75 % of available minus 4 GiB at open = 7,476 MiB, used 7,330 MiB) plus 6.7 GB of engine RSS +growth over the session; it stayed above the cache's 3 GiB insertion floor (4.4 GiB headroom at the minimum), the cache evicted inside its budget, nothing was shed and nothing failed. +The memory-safety agent was given these numbers. -Then `cp scripts/e2e/codex/jobs/943-e2e-codex-ttt.sh ~/work/gpu-runs/holder2/jobs/` (and 945 for the CRM). If Codex cannot talk to the stack, the first things to look at are the Responses features -it sends beyond what the simple scenario already exercises (all of `reasoning`, `include`, `parallel_tool_calls`, `prompt_cache_key`, `text.verbosity`, `service_tier`, reasoning-item replay and `function_call_output` replay were accepted), custom/freeform -tools (a Lark `apply_patch` is rejected with 400, `delivery-gap-audit.md` section 4) and `local_shell`/hosted tools (rejected). +**Defect 7 (fixed: output cap 4096 -> 32768).** Job 943: at 14.3k context the model wrote the whole `index.html` in one tool call; the runtime facade cut every generation at 4,096 tokens +(the Original server has no such cap: `max_tokens` 0 = the rest of the context). Codex saw `response.failed` ("tool parameter is incomplete"), reconnected twice with the identical request +(greedy, same cut) and then `turn.failed` ("incomplete: max_output_tokens"), exit 1. The decoded captured tokens show a coherent design monologue followed by an unfinished HTML file, not a +repetition loop. `leleka_backend_api::MAX_OUTPUT_TOKENS = 32768` is now the single cap of `RuntimeServer`, the engine request check, `strata-next`'s runtime default and the `leleka-deploy` +generated config. Also fixed on the way: `/v1/status` always carried `prefix_cache: null`, which broke the `http_surface` golden after the prefix-cache merge. + +**Does Codex recover by itself?** Tool-level errors: yes (a rejected `apply_patch` came back as a tool result and the model corrected it; failed commands were retried or worked around). A +truncated generation: no (Codex re-sends the identical request twice, which is deterministic under greedy decoding, then fails the turn). The model-side `shell.command`-as-string failure of +section 5 did not occur because this Codex has no such tool. + +**CUPTI hook.** The tracer of `claude/ledger` (`~/work/cupti-trace/libleleka_cupti_trace.so`, trigger file `~/work/codex-e2e/cupti/cupti.trigger`, helper `scripts/e2e/cupti_trigger.sh`) was injected +into the engine of job 945 and stayed armed and idle (nobody fired a window during the 25-minute session); the 943b run had it off. Armed-idle overhead is therefore not measured separately. + +**Per-request data.** `docs/e2e-data/{943b,945}-trace.csv` (one row per generation: prompt / reused / re-prefilled tokens, TTFT, decode tokens and tok/s, rounds, tokens per round, tier +shares, prefix-cache resume, gap before the request and the command time inside it, RSS / VRAM / MemAvailable), `*-analysis.txt` (the session report of `scripts/e2e/analyze_session.py`: time shares, +context growth, prefill cost against context, slowest requests with causes, ideal against actual) and `*-env.tsv` (10 s samples). Captures of the prompt and generated token ids for offline +replay are private: `rnr5090:~/work/codex-e2e/capture/{943b-codex-ttt,945-codex-crm}/`. + +**Replay.** Both sessions were captured by the engine (`LELEKA_CAPTURE_DIR`: prompt ids and generated ids of every completed request, plus sampling fields) and are replayable offline by the ignored test +`original_serve_replay_smoke` (`crates/leleka-runtime/src/backend_original_serve_replay.rs`; greedy, recorded output length as the budget, one stack, requests in order, so the conversation or prefix cache +behaves as in the live session). Job `947-e2e-replay.sh` (template `scripts/e2e/codex/jobs/`) replays 943b with the conversation cache and 945 with `LELEKA_REPLAY_PREFIX_MIB=auto`; its logs go to +`rnr5090:~/work/leleka-e2e/runs/947-replay/{ttt,crm}.log` (`REPLAY #n ...` per request, `REPLAY SUMMARY weighted_decode_tok_s=...`). **It had not run when this was written**: the serial queue was held by a long +ledger job (9003, running more than three hours), so there is no replay number in this report; the live numbers above are the baseline to compare it with. The adaptive-spec and decode-parity agents were told +where the corpora and the harness are. + +### 7b. Reference-equivalent reruns (943c, 945c) and replay arms (948): queued, not run when this was written + +The sessions above ran the **shipped** options, which are not the configuration of the reference runs (115.7 / ~150 tok/s: the Original with `--spec 4 --spec-min-p 0.5`, INT8 K+V with 32,768 +resident cells, the automatic per-layer expert cache of about 9,971 slots). Differences found: + +| setting | jobs 943b / 945 (shipped) | reference / reruns 943c, 945c | +| --- | --- | --- | +| expert cache | `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048` (run-e2e default, 43-49 % of entries from VRAM) | `auto`, per layer, profile of the 98x/990 jobs, `--gpu-budget` 30 GiB (as the 98x auto-cache jobs) | +| `--spec-min-p` | not passed (engine default 0 = full window) | 0.5 | +| MTP draft vocabulary | **not bound**: `leleka-inference` was started without `--mtp-rt-dir`, so `rt_directory` was None and the MTP chain step drafted over the full 248k-row head (about +0.18 ms per step, 3-4 steps per round; ledger agent) | bound: `--mtp-rt-dir ~/leleka-gates/assets/data/mtp-rt` (`draft_vocab.bin`, 106,299 rows, the Original's) | +| MTP depth / seed / tier adaptation | depth 4 (Original default), seed and adaptive tier at the head defaults | same | + +Confirmed from the command lines in `run-e2e.sh` at the time: 943b and 945 had no `--mtp-rt-dir`. Changes made: `run-e2e.sh` now always passes `--mtp-rt-dir $A/data/mtp-rt` (`E2E_NO_RT_DIR=1` reproduces the old +behaviour); `leleka-deploy` generates `--mtp-rt-dir ` in the engine command (test `server_engine_command_matches_the_documented_one` updated) so `leleka up` binds the draft vocabulary; the replay test honours +`LELEKA_ORIGINAL_SERVE_RT_DIR`. Jobs (all in `jobs/PRIORITY` below the adaptive-spec and ledger jobs): `943c-e2e-codex-ttt` (conversation cache) and `945c-e2e-codex-crm` (`--prefix-cache-mib auto`), both with +auto slots, `--spec-min-p 0.5`, the draft vocabulary, the head build, CUPTI off; `948-e2e-replay-arms` (first 30 requests of the 943b capture, four arms: 2048 / auto slots x spec_min_p 0 / 0.5, plus auto + 0.5 without the +draft vocabulary, each with weighted decode tok/s, tokens per round and tier shares); `947-e2e-replay` is the baseline replay of the full 943b and 945 captures with the shipped options. Results go to +`rnr5090:~/work/leleka-e2e/runs/{943c-codex-ttt,945c-codex-crm,947-replay,948-replay-arms}/`; if the sessions reach 115+ tok/s the production profile +(`deploy/rust-runtime/profiles/rtx5090-32g.json`) should carry: expert slots `auto` per layer with the shipped profile file, `--spec-min-p 0.5`, `--gpu-budget` as the 98x auto-cache jobs (30 GiB), and the draft vocabulary (done). ## 8. Job template @@ -186,6 +254,7 @@ bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh; echo "run-e2e rc=$?" ## 9. Open at the time of writing -* Job 946 (`E2E_SCENARIOS=long`, tools off, plus one informational tools-on request) is queued behind other agents' jobs; its table row (8.5k-token turn-1 TTFT, suffix and shared-prefix reuse) is not in section 4. -* The Codex runs of section 7. +* Job 946 (`E2E_SCENARIOS=long`, tools off) did run later but is not analysed here; its row (8.5k-token turn-1 TTFT, suffix and shared-prefix reuse) is not in section 4. The 24k-token `xlong` scenario covers cache reuse. +* Job 947 (replay of both Codex captures): queued, see section 7. +* Codex runs at the typical 180k context, with the CUPTI tracer fired in a window, and with Qwen-style sampling instead of greedy. * Daemon-side items from `delivery-gap-audit.md` not exercised here: SIGTERM drain, engine restart/re-attach under load, `leleka up`. diff --git a/docs/laptop-profile.md b/docs/laptop-profile.md index 2eea5dd6..a3925171 100644 --- a/docs/laptop-profile.md +++ b/docs/laptop-profile.md @@ -183,3 +183,68 @@ thread, where the Original stages through pinned buffers with helper threads. working-set trimming); it needs a Windows CUDA toolkit install (not present), so it was not tried. 6. Statistics: n = 6 per arm (2 passes x 3 prompts), single process per arm, uncontrolled page-cache state; the charter's paired-A/B requirements (>= 30 repeats, CIs) are not met. Treat the ratios as indicative. + +## Update 2026-10-24 (branch `claude/laptop-opt`, head 1823923 + harness): state, ceilings, what is and is not measured + +**Work stopped early by the coordinator** (the 5090 runtime has priority): the integrated head was benchmarked only in the OEM power +profile, nothing was tuned, `rtx3080-16g.json` is unchanged. The results below are what exists; the open list says what a rerun must do. + +### Machine state is the dominant variable + +| state | GPU | H2D pinned | VRAM | bf16 GEMM | how recognised | +| --- | --- | --- | --- | --- | --- | +| OEM profile (found 2026-10-17, 10-23) | P5, **30 W** limit, memory 810 MHz, SM 210-1,800 MHz | 3.1 GB/s | 40 GB/s | 6-8 TFLOP/s | `nvidia-smi -q -d PERFORMANCE,POWER`: SW Power Cap + SW Thermal Slowdown active even at idle, limit 30 W (default 115, max 140) | +| Turbo (set by the operator 2026-10-24) | P0, 100-135 W, memory 7,151 MHz, SM 1,840 MHz | **11.8 GB/s** (pageable 7.4-7.8) | **445 GB/s** | **44 TFLOP/s** | no throttle reasons | + +Every earlier laptop number in this document (and in `prefill-throughput.md`, `memory-safety.md`, the Original rows above) was taken in an +undefined one of the two states and is not comparable to another; the 5.6-12.6 tok/s rows of 2026-10-16/17 cannot be paired with anything +measured later without a same-state rerun. Full ceiling tables for both states: `docs/roofline.md` 1.5 / 1.6; Turbo ideals: decode 29-38 tok/s +(43-46 at 3 tokens per window), prefill link-bound 480 tok/s at chunk 2048 and 1,900 tok/s at 8192 (pinned), 305 / 1,220 pageable. + +**Stability incident.** The laptop took two BSODs (0x19C `WIN32K_POWER_WATCHDOG_TIMEOUT`, 2026-10-16 and 2026-10-23) after about 1.5 h of +sessions in the 30 W profile; during run A1 the whole machine stalled twice (33 and 27 min gaps in `mem.tsv`). Do not run long GPU jobs in the OEM +profile. `scripts/laptop/lap_run.sh` now wraps every laptop GPU job: preflight (refuses unless the limit is >= 100 W, no SW power cap / thermal +slowdown at idle, not P5), a 1 Hz watchdog (`monitor.sh`: kills the job on the OEM signature = P5 + memory < 2 GHz + throttle reasons 0x4/0x20, a limit +< 100 W, > 90 C, or a 10 s gap between samples), `timeout` 900 s, a 120 s cool-down between runs, and `~/LAPTOP_GPU.lock`. A plain P5 with the +idle reason (0x1) during model load is a clock ramp (it tripped the first version of the rule in `T1_short` at 51 C, 17 W; the job was killed and +no result was taken); the rule was narrowed accordingly. + +### Measured: integrated head 1823923, OEM 30 W profile (run `A0_short`, n = 6, not a performance claim) + +Production-like configuration (harness `original_serve_laptop_bench`, `scripts/laptop/lap_run.sh`): KAR level 2 read-only file, mapped experts, +VRAM tier `auto` + profile (seed on, adaptive on, pcie_frac 0 for the pageable bank), MTP depth 4 with the draft vocabulary bound +(`LELEKA_ORIGINAL_SERVE_RT_DIR=~/laptop/data/mtp-rt`), spec-min-p 0.5, INT8 KV (32,768 resident), chunk 2048, 7 CPU workers, conversation cache off, +`benchmarks/laptop/prompts.txt` (88 / 83 / 78 tokens, 128 new, greedy). Page cache emptied first (`posix_fadvise(DONTNEED)` on the shards and the +archive, no root needed), GPU clocks during the run: SM mean 1,268 MHz, memory 797 MHz, 29 W. + +| pass | prefill tok/s (p1 / p2 / p3) | TTFT s | decode tok/s per request | decode weighted | +| --- | --- | --- | --- | --- | +| 0 (cold) | 5.5 / 3.6 / 4.9 | 16.9 / 24.6 / 16.3 | 2.72 / 2.45 / 3.22 | 2.76 | +| 1 (cache warming) | 3.8 / 3.3 / 7.1 | 24.0 / 26.6 / 11.6 | 1.76 / 3.96 / 5.15 | 2.95 | + +Load to ready 271 s (the two shards are SHA-256-verified one after the other in 181.7 s, the 55 GB archive and the MTP pack in 89 s: the load is +bound by single-threaded hashing and by the cold page cache). Peak VRAM 14,201 MiB, peak RSS 33.2 GB (anon 2.5, file 31.4, shmem 3.9), process +VmSwap 1.8 GB, VM swap used 2.5 GB, MemAvailable minimum 30.6 GB. Tier statistics: 55 % of the expert entries from VRAM, 45 % from the CPU pool, 0 % +over PCIe. Observations (not conclusions): the rate rises with each request while the page cache fills, i.e. a start from a cold cache pays disk reads +for every miss; the VM already swaps anonymous pages (1.8-2.5 GB) with 40 GB of WSL RAM. Contexts of 8k / 32k / 64k / 180k were not run +(`prompt-{8192,16384,32768,65536,180000}.ids` are generated by `cargo run -p leleka-tokenizer --example long_prompts`). + +### Recommended laptop configuration (from the evidence above and the earlier agents' runs; none of it re-tuned here) + +* Power: Turbo mode (P0, >= 100 W) is a precondition for any laptop claim; in the OEM profile expect 2.5-5 tok/s decode and 4-7 tok/s prefill. +* `.wslconfig`: `memory=40GB swap=8GB` (as applied). Keep >= 6 GB free + reclaimable; `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB` only after a measurement + that it beats the page cache (it was neutral or negative at 11.4 GiB in the 2026-10-16 runs). +* Engine: the `rtx3080-16g` profile as shipped (tier auto + profile, seed on, `--mtp-rt-dir` = the MTP pack, spec-min-p 0.5, INT8 KV, chunk 2048, + 7 workers, prefix cache off until the pool acceptance tests; `LELEKA_ORIGINAL_SERVE_PCIE_FRAC` unset = 0 over the pageable bank). +* `LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=512` buys 264 slots (3,133 -> 3,397) at a risk of the per-request verifier not fitting; untested on this head. + +### Open (in the order I would run them, each <= 15 min with `lap_run.sh`, Turbo only) + +1. Baseline in Turbo: the same 6 requests, then 8k / 32k / 64k contexts, 3 interleaved repetitions (decode weighted, prefill, TTFT, peaks). +2. Page-cache residency after load: the loader hashes shard 0, shard 1, the archive in that order, so the archive evicts the experts; read the + profile-ranked experts back (or hash the archive first / in parallel threads: 271 s -> about 100 s) and compare the first-request TTFT and decode. +3. One change at a time: slots (`DECODE_RESERVE_MIB` 512), `PCIE_FRAC` 0.1-0.25 with the file pages registered (`cuMemHostRegister` of the + read-only mapping measured 12 GB/s versus 7.5 pageable), `CPU_WORKERS` 4 / 6 / 7 (the DRAM sum saturates at 4-8 readers), chunk 4096 / 8192, + seed swaps 1,024, prefix cache budget under the memory governor. +4. Stability: 30 mixed requests and the 1-hour soak in 15-minute segments with `LELEKA_LAPTOP_SEQUENCE` / `LELEKA_LAPTOP_SOAK_S` + (`mem.tsv` at 1 Hz holds RSS, VRAM, swap, clocks, power, temperature). diff --git a/docs/memory-safety-unsafe.md b/docs/memory-safety-unsafe.md index e028a148..dcc7c5fa 100644 --- a/docs/memory-safety-unsafe.md +++ b/docs/memory-safety-unsafe.md @@ -258,12 +258,15 @@ size, 17 complex types, 10 `unnecessary unsafe block` in `rust_simd.rs` and neig 1. **D4 (scratch zero fence)** compiles and is logically right under the documented CUDA semantics (a memset to device memory is asynchronous with respect to the host and only ordered on the legacy default stream). It needs a GPU run of the `original = false` full-forward construction to be observed; its cost is one context synchronize at construction. -2. **Probable cross-stream race, not fixed:** `mtp_original_full_round.rs::stage_first_residual_direct` fills rows 1..T of the +2. **Cross-stream race, FIXED in claude/memory-safety (needs a GPU run to observe; model-free test of the ordering):** the issue was `mtp_original_full_round.rs::stage_first_residual_direct` fills rows 1..T of the verifier's R bank with `copy_sync` (`cuMemcpy`, device to device) on the legacy default stream, and the draft graph then runs on a **non-blocking** stream. A device-to-device `cuMemcpy` does not block the host and the legacy stream does not order against non-blocking streams, so the graph could read a row before it is copied. The copy is 40 KB per row, issued before graph capture and launch, so the window is microseconds against milliseconds; it never showed in parity runs. A `cuCtxSynchronize` after the copies would close it but would also wait for a pending verifier commit, which needs a paired A/B before landing. + Fix: `copy_rows_then_fence` issues the copies and then `cuStreamSynchronize(0)` (`Module::fence_legacy_stream`), which waits for the legacy-stream + copies only and not for work on non-blocking streams, so a pending verifier commit is not waited for; tests `stage_fence_tests` pin copy-then-fence order, no fence after a failed copy, + and that a failed fence is an error. 3. **`HostStage::close` and `Ring::new`'s `old.close()?` call `cuMemHostUnregister` with no context entered** (`mmq_original_ring.rs`). If the driver answers `CUDA_ERROR_INVALID_CONTEXT`, the pinned ring leaks (deliberately: the allocation is not returned to the allocator) and `close` returns an error. A fix would wrap those calls in `context.enter()`. Not changed diff --git a/docs/memory-safety.md b/docs/memory-safety.md index 90435f78..c5ff951f 100644 --- a/docs/memory-safety.md +++ b/docs/memory-safety.md @@ -219,16 +219,39 @@ The server profile: `auto`, 4096/2048/1024 MiB, lock `try`, heal on. The laptop soft floor at the second request (`normal -> shed: available 61543 MiB below the soft floor 61596 MiB`); the next request found the cache evicted from **702 MiB to 351 MiB, `MemAvailable` 61,471 -> 61,885 MiB and RSS -305 MiB** (the freed blocks went back to the OS: `malloc_trim` after an eviction); the ballast then crossed the hard floor (`shed -> reject`), `admit` answered `503 memory_pressure`, `retry_after=15s`, and the next request found the cache emptied. The recovery phase of that smoke compared against a baseline that had drifted (file-mapped expert pages warmed up during the test) and never reached the 1 GiB hysteresis margin, so the smoke reported `failed` on its own expectation, not on the - governor (`reject -> shed` happened after the ballast was freed, as designed). The smoke now re-centres the floors before the recovery phase; the re-run is job 914 (section 5.5). + governor (`reject -> shed` happened after the ballast was freed, as designed). The smoke now re-centres the floors before the recovery phase; the re-run is in section 5.5. * **Job 917 (reader), first attempt, not a result.** The request decoded one token (the filler prompt ends in EOS) and the reader thread only ran for ~4 s (0 GiB through the cache), so decode speed 6.9 / 7.9 / 8.0 tok/s (A/B/C) says nothing; - the memfd stayed at 0 swapped MiB and `pswpin/out` at 0 throughout. The scenario now decodes a fixed 64 tokens without stopping at EOS and lasts until the reader has streamed its 40 GiB; the re-run is job 914 (section 5.5). + the memfd stayed at 0 swapped MiB and `pswpin/out` at 0 throughout. The scenario now decodes a fixed 64 tokens without stopping at EOS and lasts until the reader has streamed its 40 GiB; the re-run is in section 5.5. -### 5.5 Queued, not yet run (holder queue FIFO: roughly ten other agents' jobs were ahead) +### 5.5 Job 914 (binary a7): shed with recovery, and decode speed next to a 40 GiB competing reader -Job `914-mem-shed2` (binary `mem-a7`, `scripts/memory/jobs/914-mem-shed2.sh`, already in `holder2/jobs`): (1) the shed smoke again with the recovery phase fixed: it must end `MEM-RESULT scenario=shed failed=[]`, -including `MEM-SHED recovered` and `prefix_budget_mib` restored; (2) the reader scenario with a fixed 64 decoded tokens and a reader that streams 40 GiB of the KAR file through the page cache: it prints `MEM-READER phase=A/B/C` -lines with decode tok/s, `memfd_swapped_mib` and `pswpin/pswpout` per request and the B/A ratio. Until it has run, the claim "decode speed does not drop next to a competing reader, memfd stays resident" rests on job 910 (memfd 0 MiB swapped for 75 s next -to a 40 GiB reader, no swap traffic) and on the WSL2 A/B (5.3); there is no 5090 decode-speed number for it. Read the logs in `~/work/gpu-runs/holder2/jobs/914-mem-shed2.log`. +* **Shed path, complete.** Floors 1.5 / 3 GiB below the memory the host had (63,350 MiB), prefix budget 6 GiB, ballast 2.3 GiB: `normal -> shed` at the soft floor, the next request found the cache evicted 351 -> 0 MiB with `MemAvailable` 62,089 -> 62,442 MiB + and RSS -312 MiB; the ballast crossed the hard floor (`shed -> reject`), `admit` answered 503 `memory_pressure`, `retry_after=15s`; with the ballast freed and the floors re-centred the level went `reject -> shed -> normal` in 4 samples, the request after it was + served and the **prefix budget was back at 6,144 MiB**. `MEM-RESULT scenario=shed failed=[]`. `MemAvailable` never below 58 GiB. +* **Reader, decode speed.** 6 requests without the reader (A), 54 requests while a thread streamed 40 GiB of the KAR file through the page cache (B), 6 after (C); 64 decoded tokens each, no EOS stop: + A **18.12** tok/s, B **19.30** tok/s (B/A 1.07: no drop while the reader ran), C 15.95 (the first two requests after the reader ran at 11 tok/s, the following four at 17.1-19.6: the 40 GiB of KAR file evicted part of the *file-mapped expert pages* + from the page cache and they were read back once; that is the mapped bank, not the memfd). `memfd_swapped_mib` = 0 on every request, `pswpin/out` 0 (one page of swap-in in B), `MemAvailable` 62.0-62.3 GiB throughout. Same conclusion as job 910: with the host not short of memory a + page-cache reader does not move the memfd; the conditions that do are in 5.3. + +### 5.6 Does the daemon RSS leak? Evidence from the e2e sessions, and the long soak (NOT YET RUN) + +What exists: the `leak` scenario of the memory smoke (time-bounded mixed workload: shared growing sessions, unshared 8k-30k sessions, 100k/180k prompts every 120 requests, 8% cancels, 4% over-long refusals, prefix cache `auto` under constant churn), +sampled every 30 s: `VmRSS` split into `RssAnon` / `RssFile` / `RssShmem`, `VmSwap`, `MemAvailable`, `Cached`, `Shmem`, active/inactive file, VRAM used and accounted, the prefix store, `mallinfo2` (arena, in use, free, mmapped), threads, fds; a TSV per run +(`~/work/gpu-runs/mem-logs/*.tsv`, outside Git); at the end it prints, per series, the slope in MiB per 1000 requests after a 25% warm-up with its 95% interval and the Theil-Sen slope (`MEM-LEAK-FIT` lines); +`scripts/memory/leak_fit.py RUN.tsv` re-fits any run offline and `--compare` lines up arms. Jobs: `919` 7-minute check of the scenario, `920` the 3 h 03 min run (default allocator, `malloc_trim` after every eviction), `921` 45 min with `MALLOC_ARENA_MAX=2`, +`922` 45 min with `LELEKA_MEMORY_NO_TRIM=1` (what the trim buys); compare 921 and 922 with the first 45 min of 920 (`leak_fit.py --compare 920.tsv:default 921.tsv:arena2 922.tsv:notrim --tmax 2700`). File-mapped experts, so `MemAvailable` stays ~58 GiB (the 15 GiB rule); +an anonymous or shmem leak shows the same as with the resident bank. + +Queue state: 919 was a duplicate of 920 and is skipped; 920, 921 and 922 were moved to `holder2/jobs-deferred/` by the coordinator so that they do not block the speed jobs for hours; 920 will run in a quiet window (overnight), 921/922 only if 920 shows a slope. **The soak below is therefore not measured.** **What the evidence says today** (fits of the committed e2e data with `scripts/memory/fit_e2e_env.py`, RSS against request count; `docs/e2e-data/945-*`, `943b-*`): + +| session | span | series | slope (MiB / 1000 requests) | note | +| --- | --- | --- | --- | --- | +| 945 CRM (resident bank, 84 requests, ctx to 123k) | whole run | RssAnon | +70,029 [+66,617, +73,441] | the prefix store filling: +6,647 MiB RssAnon vs +6,748 MiB store | +| 945 | requests >= 70 (store full; 23 samples, 13 requests, 6 min) | RssAnon / VmRSS | **0.0** (56,337 / 60,383 MiB at every sample) | too short to bound a small slope: 13 requests | +| 943b tic-tac-toe (conversation cache, 51 requests, ctx to 82k) | last 40% of requests (37 samples) | RssAnon | +464 [-587, +1,515], Theil-Sen 0.0 | first 50,894 -> last 50,879 MiB | + +RssShmem is constant in both (3,836 MiB), RssFile is 0, so there is no anonymous or shmem growth after the cache fills and no file growth at all. That is consistent with no leak; the intervals (hundreds of MiB per 1000 requests) are far too wide to exclude a slow one, which is what the soak is for. The bisect (prefix cache off, CPU pool lookahead off, seed off, K/V imports) is +prepared as environment switches of the smoke (`LELEKA_MEM_PREFIX_MIB=0`, `LELEKA_ORIGINAL_SERVE_SEED=off`) and has to wait for a slope to bisect. ### 5.3 Swap A/B under real pressure (WSL2 laptop, cgroup v1 memory controller, 9 GiB limit; sealed memfd 6 GiB, anonymous hog 5 GiB, a reader streaming a 12 GiB file; kernel 5.15) @@ -311,7 +334,32 @@ copy site, Miri and clippy results, residual risks). Summary: (340), `leleka-runtime` (166) and `native-cpu-expert` (153) were not cleaned up wholesale. -## 8. Open +## 8. The real Codex CRM session (e2e job 945): what the memory did, and what changed in the budget + +Session: `--prefix-cache-mib auto`, resident expert bank, sealed memfd from the holder, 84 requests, context 10k -> 123k tokens, 25 minutes (`~/work/leleka-e2e/runs/945-codex-crm/env.tsv`, `inference.log`). +**That build (`leleka-e2e/bin-sm120`) predates this branch: no governor ran.** What the numbers say: + +| time | VmRSS | RssAnon | RssShmem | RssFile | MemAvailable | +| --- | ---: | ---: | ---: | ---: | ---: | +| 0 s (after load) | 53,723 MiB | 49,690 | 3,836 | 0 | 13,991 MiB | +| 592 s (ctx 55k) | 58,152 | 54,106 | 3,836 | 0 | 9,710 | +| 1194 s (ctx 95k) | 60,360 | 56,314 | 3,836 | 0 | 7,474 | +| 1395 s (ctx 115k) | 60,383 | 56,337 | 3,836 | 0 | 7,459 | + +* **Real, not reclaimable.** The growth is `RssAnon` (+6,647 MiB); `RssShmem` is constant (the pinned K/V image and head, 3,836 MiB), `RssFile` is 0 (the resident bank is anonymous), and the 51 GB memfd is outside the process RSS *and* outside + `MemAvailable` (shmem is not counted there). `MemAvailable` fell by 6,532 MiB: one for one with the anonymous growth. There was no reclaimable page cache to give back (the shard cache had been dropped after the load); the dip was the prefix store + filling its budget (582 MiB at the first request, 7,330 of 7,476 MiB at the end, 58 admitted, 23 evicted) and it plateaued exactly when the store reached the budget. That also answers "does the RSS leak" for this run: RSS growth (6,647 MiB) = store growth (6,748 MiB) within 1.5%; the + soak in section 5.6 tests the plateau itself. +* **Why nothing shed or refused.** (1) No governor in that build. (2) With it, the old rule would not have shed either: the budget was 75% of (14,064 - 4,096) = 7,476 MiB, which leaves 6.9 GiB available with the cache full (observed 7.46 GiB) against floors of 4 GiB (shed) and 2 GiB (reject). The + plan *designed* a minimum of 7 GiB available, and the operator's 15 GiB cannot hold in resident mode at all (idle is already 14 GiB). +* **Was the startup plan using the real post-load footprint?** Partly. The plan subtracts a predicted footprint from the available memory *before* the load. Real: 68,762 -> 13,991 MiB = **54,771 MiB**; predicted (bank 46.85 GiB + K/V 3.09 GiB + 2.5 GiB other) = 53,700 MiB: 1.1 GiB short, because the "other" constant had been measured + with the file-mapped bank (2.19 GiB); with the resident bank it is 3.55 GiB. The cache budget itself was never taken from the prediction: it is recomputed at open from the real `MemAvailable` (so the 1.1 GiB error did not enter it), but the *refusal* decision and the logged plan used the optimistic number. +* **Changes.** `OTHER_FIXED_ESTIMATE_RESIDENT` = 3.6 GiB for the resident bank (2.5 GiB stays for the mapped one); `Policy::reserve` 1 -> **2 GiB** (the first long request plus the store's own overhead grew the process ~1 GiB beyond the plan); the caches stop *admitting* at + `soft_floor + reserve` (6 GiB) instead of at a 3 GiB insertion floor, i.e. before a shed is needed; and after the stack opens `note_post_load` compares the plan with the measured availability, logs a WARNING above 512 MiB error and publishes it as `plan_check` + in the report. For the CRM host state the `auto` budget becomes **6.0 GiB** (was 7.3) and ~8 GiB stay available with the cache full (was 7.4); a 180k session (2.6 GB of blocks + 127 MiB per node) still fits. The file-mapped bank was already accounted + since section 2.2 (hot half of RAM kept out of the elastic memory); the resident bank is a fixed item of the plan. + +## 9. Open * The `OTHER_FIXED_ESTIMATE` (rings, staging, pool scratch, empty checkpoints) in `memory_governor.rs` is a measured constant, not a formula; re-measure when those owners change. * A hard guarantee that the memfd is never swapped needs `LimitMEMLOCK=infinity` (the deploy unit sets it) or `CAP_IPC_LOCK`; without it the guard detects and heals but cannot prevent. 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/docs/quality-gate.md b/docs/quality-gate.md index ee594ea6..d83fc544 100644 --- a/docs/quality-gate.md +++ b/docs/quality-gate.md @@ -1,15 +1,10 @@ # Model quality gate: the Rust/CUDA port (Original mode17 serve path) against the unmodified Original Status: measured on the RTX 5090 (driver 595.99.02, CUDA 13.2.86), 2026-10-17/18. Branch `claude/quality-gate` (port = `claude/port-gpu-bringup` -6b94e7c, seed on by default, + the stop-set fix below). Model: Qwen3.8-Flash-Next IQ3_S, KAR level-2 PLE, MTP pack `data/mtp-rt`. +6b94e7c, seed on by default, + the stop-set fix below; merged with the bring-up head 4f7c461 afterwards). Model: Qwen3.8-Flash-Next IQ3_S, KAR level-2 PLE, MTP pack `data/mtp-rt`. Original = `stra169-ladder/build-sm120/strata` (sha256 714deada...), the build behind jobs 809/980; the `numerics-orig` build (diagnostic dump patches compiled in) reproduces it bit for bit on the reads (arm R6: all 612 rows, difference exactly 0). -**Pending at the time of writing (queued behind other agents' jobs, run `q_analyze.py` and `q_ladder.py` when they finish):** -`9968-quality-orig-retrieval-read` (Original log-probabilities along its 100k/180k answers), `9969-quality-port-retrieval-fixed` (port after the stop-set -fix, free and forced along those answers: section R of the report) and `9970-quality-ladder-p1` (layer-by-layer localisation of the one outlier row, section 9.2). -Everything else in this document is measured. - ## 1. Method **Teacher forcing, both directions.** A *path* is the prompt followed by the tokens an engine produced. Both engines are made to decode along @@ -93,11 +88,11 @@ The port's own envelope (arms against P1) is the same size as the Original's: p9 input token is `` (248068). Original (windows read, batched-prompt read, near-CPU, GGUF, all configurations): 198 at -0.51..-0.74 over 271 at -0.65..-0.92, except two configurations that put 271 first (R3 by 0.03, R4 repeat 1 by 0.45); port: 271 at -0.21..-0.35, 198 at -1.23..-1.66 in all six arms, including the all-CPU-experts arm. So the port's value lies 0.3-0.7 nats beyond the Original's most extreme -configuration (d_top1 up to 1.36 against the R1 value). All other 3671 pooled port rows are inside the envelope. Localisation: section 8. +configuration (d_top1 up to 1.36 against the R1 value). All other 3671 pooled port rows are inside the envelope. Localisation (section 9.2): the residual stream of that row is ordinary, so it is a high-gain row, not a fault. **Verdict of section 3:** the port's deviation distribution equals the Original's self-deviation (pooled medians, p99 within +6 %, flip rate 2.15 % vs 2.22 %, flip margins <= 0.41 except one 0.56 whose port margin is 0.02, i.e. a coin flip in both engines); one row (above) is outside and not yet explained -at layer level. No evidence of a systematic numerical error in the dense path, the KAR PLE source, the expert paths (CPU, VRAM static, adaptive, PCIe 0) +at the logit level but localised in section 9.2 as a normal-sized residual difference on a high-gain row. No evidence of a systematic numerical error in the dense path, the KAR PLE source, the expert paths (CPU, VRAM static, adaptive, PCIe 0) or the speculative window shapes. ## 4. Open question 1: corpus prompt 2 (diverges at token 4; the Original stops at 90, the port runs to 128) @@ -176,39 +171,57 @@ themselves (P5 against P1 is smaller than P2/P3/P4 against P1), and it adds no r backend, the smokes and the laptop probe used the GGUF `tokenizer.ggml.eos_token_id` alone = 248046. Evidence from the 100k/180k retrieval run (job 9966, before): after the answer `...**4817-QX**.` the model emits `<|endoftext|>`; the Original stops (83 and 63 tokens), the port went on emitting `<|im_start|>` until `max_new` (87 tokens at 100k, where it later hit `<|im_end|>`; **600 tokens at 180k**). After: `original_stop_tokens()` returns - {eos, 248044} for the request and the text sink; unit test `the_stop_set_is_the_originals_endoftext_and_im_end`. After-evidence (job 9969) - is in section 10 if the queue has run it. -2. **Outlier row `` at position 66 of prompt 1 (open).** A 1.1-nat disagreement on a 0.4-nat near tie, in all configurations of the port and - outside every configuration of the Original; the other special-token row (`` input, position 68) agrees to 0.000 but is a 0.99-confidence row, - so it does not test the hypothesis. Hypothesis: the input handling of special token ids (embedding / PLE hash row of 248068). Job 9970 - (`9970-quality-ladder-p1.sh`, `q_ladder.py`) dumps the residual after every layer half in both engines for that path and reports the first frame at which the row departs. + {eos, 248044} for the request and the text sink; unit test `the_stop_set_is_the_originals_endoftext_and_im_end`. After (job 9969, same prompts, same 600-token allowance): the free run stops on `<|endoftext|>` after **83** tokens at 100k (the Original's length) and + **68** at 180k (was 600); the forced run produces exactly the Original's 83 and 63 tokens and stops there. Re-confirmed. +2. **Outlier row `` at position 66 of prompt 1: localised, not a defect.** Job 9970 dumped the residual after every layer half in both engines (port + teacher-forced, `numerics-orig` Original through the windows, same path: prompt 1 + its first 22 tokens, 25 common rows). Relative L2 of port against Original + at position 66, frame by frame: **0 at frame 0** (embedding / PLE of the `` input identical, which rules out the special-token input hypothesis), + 1.2e-3 at frame 1 and then within 0.8-2.3x of the median over the other 24 rows at every frame (rank 4-17 of 25), 0.134 at the last frame against a median of 0.099 + (rank 8/25). Rows 88, 77 and 81 differ more (mean 0.42 / 0.34 / 0.25 over frames 8-95) without any argmax flip. There is no frame where the row departs from the + others, so there is no layer-level fault to fix: the 0.13 residual difference is the usual size (earlier port-vs-Original ladders: 0.055-0.09 median at the last + frames), and this row is a high-gain row for the 198/271 pair (a 0.4-nat tie in the Original, whose own configurations already move it by 0.9 nats of margin). + The port's six arms agree with each other because they share one dense path whose offset from the Original is fixed, while the Original's envelope arms share the Original's. + Residual risk: one row of 612 per arm lies outside the Original's envelope; the evidence is that it is rounding on a sensitive row. A second sample of rows + whose input is a decode-time special token (thinking-mode traffic) would tighten this; not done. ## 10. Long-context retrieval at 100k and 180k tokens (same ids as jobs 915/916: `long-180k/prompt{100000,180000}.ids`, needle `4817-QX`) -Port (job 9966, integrated defaults: adaptive tier + seed, chunk 8192, int8 KV streamed, 600 new tokens) against the Original (job 9964, static tier, -`--prefill 8192`, same KV streaming, `GEN 600`): +Port (jobs 9966 before / 9969 after the stop-set fix; integrated defaults: adaptive tier + seed, chunk 8192, int8 KV streamed, up to 600 new tokens) against the +Original (job 9964: static tier, `--prefill 8192`, same KV streaming, `GEN 600`). -| prompt | engine | answer | tokens | first differing token | -| --- | --- | --- | --- | --- | -| 100k | Original | "......Remember this: the secret passcode is 4817-QX... The secret passcode is **4817-QX**." then stop | 83 | | -| 100k | port | same wording until token 61 (one word differs), same final answer, then `<|endoftext|><|im_start|>x3<|im_end|>` | 87 | 61 | -| 180k | Original | same structure, passcode **4817-QX**, stop | 63 | | -| 180k | port | passcode **4817-QX**, then `<|endoftext|>` and 500+ junk tokens (the stop-set defect) | 600 | 30 | +| prompt | engine | answer | tokens | +| --- | --- | --- | --- | +| 100k | Original | `` ... "Remember this: the secret passcode is 4817-QX" ... `` "The secret passcode is **4817-QX**." then `<|endoftext|>` | 83 | +| 100k | port, before fix | same, then `<|endoftext|><|im_start|>` x3 `<|im_end|>` | 87 | +| 100k | port, after fix | same, stops on `<|endoftext|>` | 83 | +| 180k | Original | same structure, **4817-QX**, stop | 63 | +| 180k | port, before fix | **4817-QX**, then `<|endoftext|>` and junk to the limit | 600 | +| 180k | port, after fix | **4817-QX**, stops on `<|endoftext|>` | 68 | -Both engines retrieve the passcode at 100k and 180k; the wording diverges at token 61 / 30 (a different word choice inside the same sentence). The first 5 tokens are -identical, as are all tokens before the divergence. The teacher-forced comparison at the divergence (the Original reading its own 83/63-token answers -behind the batched prompt: job 9968; the port forced along them: job 9969) is queued; its table is `q_analyze.py` section R once the data exist. +**Retrieval verdict: both engines retrieve the passcode at 100k and 180k.** The free answers first differ at token 61 (100k) and 30 (180k): at those rows +the Original has 1151 at -0.717 over 6941 at -0.778 (100k; port -0.756 / -0.763) and 430 at -1.086 over 506 at -1.142 (180k; port 506 -1.112 over 430 -1.145), +i.e. margins of 0.06 and 0.06 in the Original and 0.01 and 0.03 in the port: coin flips, not a long-context error. + +Teacher-forced along the Original's whole answers (Original: batched prompt, the answer through the verify windows, job 9968; port: forced pass, job 9969), top-16 per row: + +| prompt | rows | d_top1 med / p99 / max | dmax16 p99 / max | flips | stop token lp / rank (Original; port) | +| --- | --- | --- | --- | --- | --- | +| 100k | 82 | 0.000 / 0.230 / 0.328 | 2.77 / 3.30 | 0 | -0.003 / 1 ; -0.005 / 1 | +| 180k | 62 | 0.000 / 0.100 / 0.137 | 1.46 / 1.55 | 1 (Original margin 0.124) | -0.003 / 1 ; -0.003 / 1 | + +Against the short-context tolerances: 180k is inside; at 100k the p99 (0.23, the largest or second largest of 82 values) is 0.01 over the 0.22 line, the maximum 0.33 is inside 0.43, no flips. +The forced runs produced exactly 83 and 63 tokens and stopped on the stop token. The Original's row at position 99999 (first answer row) is not logged by its resumed request. ## 11. Rerun ``` # data and requests (server): scripts/quality/q_prep.py builds cases/ and force/ from the job-809 Original log and the port logs -# Original: holder jobs scripts/quality/jobs/991..995, 9964, 9967, 9968 (orig_run in q-common.sh); port: 9216-9218, 9966, 9969, 9970, 9973 +# Original: holder jobs scripts/quality/jobs/991..995, 9964, 9967, 9968, 9970 (orig_run in q-common.sh); port: 9216-9218, 9966, 9969, 9970, 9973 python3 scripts/quality/q_analyze.py ~/work/gpu-runs/quality --md report.md # envelope, port arms, divergences, EOS, verdict, long prompt python3 scripts/quality/q_ladder.py ~/work/gpu-runs/quality/ladder 66 # layer-level localisation of one row ``` -Binaries: port test exe built in WSL from `claude/quality-gate` (`q-4`, sha256 8618cc61...). Everything under `scripts/quality/` is offline analysis or holder +Binaries: port test exe built in WSL from `claude/quality-gate` (`q-4`, sha256 8618cc61..., built from 97227d8). Everything under `scripts/quality/` is offline analysis or holder jobs; nothing there runs in production serving. ## 12. Caveats diff --git a/docs/roofline.md b/docs/roofline.md index b9cde6f0..b46f522f 100644 --- a/docs/roofline.md +++ b/docs/roofline.md @@ -136,6 +136,37 @@ The laptop ceilings above are what the current machine state delivers; the opera and re-run `tools/microbench/run_laptop.sh` (about 6 minutes) before laptop targets are fixed. Everything laptop-related in sections 5-6 is therefore given in both columns. +### 1.6 RTX 3080 laptop, Turbo mode (re-run 2026-10-24, branch `claude/laptop-opt`) + +The 2026-10-23 re-run (same binaries) was made twice: first in the OEM profile again (power limit 30 W, P5, memory 810 MHz, SW power cap + SW thermal +slowdown active even at idle: every number identical to 1.5 within 5 %, i.e. 1.5 is that profile's property, not a measurement error), then, after the +operator set Turbo mode, with the guarded runner `scripts/laptop/lap_run.sh` (preflight: P0, limit 130-140 W, no throttle reason; 1 Hz watchdog; logs +`~/lopt/results/MB{1,2,3}_*`, joined as `roofline-laptop-turbo-2026-10-24.log`). Mean clocks during the GPU suite: SM 1,839 MHz, memory 7,151 MHz, 118 W, +max 77 C. PCIe link gen 4 x8 (the card is wired x8 here). + +| quantity | OEM 30 W profile (1.5) | **Turbo (measured 2026-10-24)** | nameplate (A) | +| --- | --- | --- | --- | +| H2D pinned (hostalloc), 2 MB / 8 MB, 1 stream | 3.1 GB/s | **11.8 / 12.0 GB/s** (2 and 3 streams: same) | gen4 x8 about 13-14 GB/s | +| H2D registered file mapping (`cuMemHostRegister` of the page cache) | 3.0-3.1 | **12.0 / 11.0** | | +| H2D registered anonymous 4 KiB pages | 3.1 | **9.8 / 11.3** | | +| H2D pageable (driver stages through its own pinned buffer), 2 MB / 8 MB | 3.1 | **7.4 / 7.8 GB/s** (host 275 us / 1,070 us per call, the calling thread is blocked) | | +| D2H pinned / both directions | 3.2-3.3 / 3.2 | **12.4-12.7 / 12.1** (sum, not 2x) | | +| 3 pieces per expert, 16 experts per call, pinned | 3.1 | **11.6-11.9** (1 expert per call: 11.2, 160 us host per expert) | | +| VRAM read / write / copy | 40 / 41 / 36 | **445 / 437 / 426 GB/s** | 448 | +| bf16 GEMM T = 8192 (gdn_qkv, qsa_q, 8192^3) | 5-8 TFLOP/s | **44.2 / 44.3 / 44.1 TFLOP/s**; fp16 43; int8 128-153 TOPS | 38-42 (A) | +| bf16 GEMV T = 1 gdn_qkv (52 MB) / expert_down T = 10 | 38 GB/s | **390 GB/s** / 252 GB/s | | +| host DRAM read, 1 / 2 / 4 / 8 / 16 threads (stream) | 14.8 / 21.9 / 24.6 / 26.5 / 26.3 | **13.8 / 18.2 / 20.4 / 20.1 / 23.8 GB/s** (2 MB random blobs: 8.7 / 14.0 / 19.9 / 20.6 / 24.3) | DDR4-3200 dual channel 51 peak | +| PCIe pinned copy while N CPU readers stream blobs (PCIe + CPU = sum) | 3.0 + 9.8..21.5 = 12.8..24.2 | N=0: 9.1; **N=1: 7.7 + 9.0 = 16.6; N=4: 5.8 + 13.7 = 19.5; N=8: 5.8 + 16.0 = 21.8; N=16: 3.5 + 17.1 = 20.6** | | +| kernel launch / graph chain gap / doorbell round trip | 3.5 / 2.05 / 4.2 us | 3.5 / **1.0** / **3.0 us** | WDDM-virtualised | +| graph of 1000 empty nodes | 1.3 ms | 0.73 ms | | +| thread ping-pong spin / futex | 0.15 / 1.85 us | 0.16 / 2.4 us | | + +Reading for the engine: with Turbo the GPU side becomes 11x faster (VRAM, compute) and the link 3.8x faster, but **host DRAM (about 24 GB/s mixed, +not the 51 GB/s nameplate) and the link share it: while the CPU leg streams blobs the PCIe copy drops from 9-12 to 5.8 GB/s and the sum saturates at +about 20-22 GB/s.** The 7-worker CPU expert pool and PCIe misses therefore compete for the same DRAM bandwidth, and the optimum worker count is the smallest +one that reaches the sum (4-8 readers), as on the server. The pageable path (the mapped bank without registered pages) tops out at 7.4-7.8 GB/s with a +blocked host thread; registering the file pages (`cuMemHostRegister`, 0.06 s for 2 GiB, file mapping read-only) gets the pinned 12 GB/s. + ## 2. Model accounting (counted from `data/iq3_s/index.txt`, `native_experts.txt`, `include/strata/core/layout.hpp`) * 48 layers: **36 GDN** (all layers with l mod 4 != 3) and **12 QSA** (3, 7, ..., 47); hidden 2560, four hyper-connection streams (R = 10240 @@ -298,6 +329,16 @@ its floor. Chain of 4 steps + seed: 1.5 ms floor, 2.2 ms port, 1.2 ms Original. ### 5.2 RTX 3080 laptop +**Turbo ideals (section 1.6 numbers, added 2026-10-24).** Dense chain 5.5 GB at 445 GB/s = **12.4 ms** per window (plus launch gaps, about 1.0 us per graph +node). Misses at 3,133-4,400 VRAM slots (hit rate 0.50-0.55, about 1.0-1.2 GB per window) over the PCIe + CPU sum of 20-22 GB/s: **50-60 ms**; the serial +window is therefore about 65-70 ms, and with 2.0-2.5 accepted tokens per window the decode ideal is **29-38 tok/s** (3 tokens per round: 43-46 tok/s; with +perfect overlap of chain and misses 40-50). Prefill is bound by streaming the bank (50.3 GB per chunk) over the link: pinned/registered 11.8 GB/s = 4.3 s per +chunk (**480 tok/s at 2048, 1,900 tok/s at 8192**); through the pageable path 7.5 GB/s = 6.7 s (305 / 1,220 tok/s). The bf16 GEMM floor is 2.3 s per 8192 chunk +(3,500 tok/s) so it is link-bound at every chunk size; the page cache holds only about 30-34 of the 50 GB, so a chunk also pays NVMe reads for the rest unless the +bank is read ahead. + +The two columns below are the OEM 30 W profile (section 1.5) and nameplate. + Two columns, because the machine is power-capped (1.5). Laptop VRAM is 16 GB: dense weights 5.2 GB + KV + workspace leaves about 9 GB, i.e. about 4,400 expert slots (18 % of the bank), hit rate about 0.55 **A** (between 0.41 at 2048 and 0.68 at 9,971 slots). The experts are file-mapped (page cache), the bank (50.3 GB) exceeds the WSL page cache (about 34 GB available), so a chunk's expert bytes come from RAM *and* disk. diff --git a/scripts/e2e/analyze_session.py b/scripts/e2e/analyze_session.py index 321e7d81..8751c983 100644 --- a/scripts/e2e/analyze_session.py +++ b/scripts/e2e/analyze_session.py @@ -71,15 +71,21 @@ for i, r in enumerate(reqs): r["suffix"] = r["prompt"] - r["reused"] # ---- engine log ------------------------------------------------------------------------------------------------------------- -blocks, cur = [], None +blocks, cur, pending_prefix = [], None, {} tier_re = re.compile(r"expert tier: (\d+) layer groups, entries vram (\d+) .*? pcie (\d+) .*? cpu (\d+) .*?, (\d+) adaptations, (\d+) swaps") for l in lines("inference.log"): m = re.search(r"prefill_phase start n=(\d+) resume=(\d+)", l) if m: cur = {"n": int(m[1]), "resume": int(m[2]), "pf_tokens": 0, "pf_ms": 0.0, "pf_chunks": 0, "rounds_win": 0, "win_ms": 0.0, "produced": None, "rounds": None, "reused": None, "tier": None, "prefix": {}, "cancelled": False} + cur["prefix"].update(pending_prefix) + pending_prefix = {} blocks.append(cur) continue + m = re.search(r"prefix request: (.*)", l) + if m: + pending_prefix = dict(re.findall(r"(\w+)=(\S+)", m[1])) + continue if cur is None: continue m = re.search(r"PREFILL-PROFILE first=(\d+) tokens=(\d+) total_ms=([\d.]+)", l) @@ -100,9 +106,6 @@ for l in lines("inference.log"): continue if "serve_request err Cancelled" in l: cur["cancelled"] = True - m = re.search(r"prefix request: (.*)", l) - if m: - cur["prefix"].update(dict(re.findall(r"(\w+)=(\S+)", m[1]))) m = re.search(r"prefix request done: (.*)", l) if m: cur["prefix"].update(dict(re.findall(r"(\w+)=(\S+)", m[1]))) diff --git a/scripts/e2e/codex/check_ttt.mjs b/scripts/e2e/codex/check_ttt.mjs index ba892b73..742c979c 100644 --- a/scripts/e2e/codex/check_ttt.mjs +++ b/scripts/e2e/codex/check_ttt.mjs @@ -44,13 +44,48 @@ const box = await page.evaluate(() => { check('2 visible WebGL canvas', box && box.w > 100 && box.h > 100, JSON.stringify(box)); const status = async () => (await page.evaluate(() => document.getElementById('status')?.textContent ?? '')).trim(); -// The board layout is the game's own: the nine regions of a lattice around the canvas centre must map to nine different cells. -if (!box) { await browser.close(); server.close(); console.log('SUMMARY ' + results.filter((r) => r.ok).length + '/6'); process.exit(1); } -const cx = box.x + box.w / 2, cy = box.y + box.h / 2, step = Math.min(box.w, box.h) / 6; -const pts = []; -for (let r = -1; r <= 1; r++) for (let c = -1; c <= 1; c++) pts.push([cx + c * step, cy + r * step]); -const click = async (i) => { await page.mouse.click(pts[i][0], pts[i][1]); await page.waitForTimeout(250); }; const restart = async () => { const b = await page.$('#restart'); if (b) await b.click(); await page.waitForTimeout(200); }; +// The board layout is the game's own (camera, perspective, size): find the nine cells by probing. Click a dense grid over the +// canvas; a point that changes the status text placed a mark (then restart). The accepted points form nine clusters. +const initial = await status(); +const accepted = []; +const N = 28; +for (let gy = 0; gy < N; gy++) { + for (let gx = 0; gx < N; gx++) { + const x = box.x + (gx + 0.5) * box.w / N, y = box.y + (gy + 0.5) * box.h / N; + await page.mouse.click(x, y); + await page.waitForTimeout(40); + if ((await status()) !== initial) { accepted.push([x, y]); await restart(); } + } +} +let pts = []; +if (accepted.length >= 9) { + // Rows are thirds of the accepted y-range, columns thirds of that row's x-range; each cell is the accepted point nearest to the third's centre. + const ys = accepted.map((p) => p[1]); + const y0 = Math.min(...ys), y1 = Math.max(...ys); + for (let r = 0; r < 3; r++) { + const lo = y0 + (r * (y1 - y0 + 1)) / 3, hi = y0 + ((r + 1) * (y1 - y0 + 1)) / 3; + const band = accepted.filter((p) => p[1] >= lo && p[1] < hi); + if (!band.length) continue; + const x0 = Math.min(...band.map((p) => p[0])), x1 = Math.max(...band.map((p) => p[0])); + const cy = band.reduce((a, p) => a + p[1], 0) / band.length; + for (let c = 0; c < 3; c++) { + const cx = x0 + ((c + 0.5) * (x1 - x0 + 1)) / 3; + pts.push(band.reduce((best, p) => (Math.hypot(p[0] - cx, p[1] - cy) < Math.hypot(best[0] - cx, best[1] - cy) ? p : best), band[0])); + } + } +} +console.log(`probe: ${accepted.length} accepted clicks, ${pts.length} cell centres`); +if (pts.length !== 9) { + check('3 row win via real clicks', false, 'could not find nine clickable cells'); + check('4 moves blocked after the win', false, 'no cells'); + check('5 restart to empty board (X to move)', false, 'no cells'); + check('6 draw via real clicks', false, 'no cells'); + await browser.close(); server.close(); + console.log('SUMMARY ' + results.filter((r) => r.ok).length + '/6'); + process.exit(1); +} +const click = async (i) => { await page.mouse.click(pts[i][0], pts[i][1]); await page.waitForTimeout(Number(process.env.CLICK_WAIT_MS ?? 250)); }; // 3: row win via real clicks: X takes 0,1,2; O takes 3,4 for (const i of [0, 3, 1, 4, 2]) await click(i); @@ -66,7 +101,7 @@ await restart(); const s5 = await status(); check('5 restart to empty board (X to move)', /X/i.test(s5) && !/win|draw/i.test(s5), s5); // 6: draw via real clicks: X O X / X O O / O X X -for (const i of [0, 1, 2, 4, 3, 5, 7, 6, 8]) await click(i); +for (const i of [0, 1, 2, 4, 3, 5, 7, 6, 8]) { await click(i); if (process.env.TRACE) console.log(" click", i, "->", await status()); } const s6 = await status(); check('6 draw via real clicks', /draw/i.test(s6), s6); diff --git a/scripts/e2e/codex/jobs/943c-e2e-codex-ttt.sh b/scripts/e2e/codex/jobs/943c-e2e-codex-ttt.sh new file mode 100644 index 00000000..cf302eb6 --- /dev/null +++ b/scripts/e2e/codex/jobs/943c-e2e-codex-ttt.sh @@ -0,0 +1,21 @@ +set -uo pipefail +# claude/e2e (rerun with the reference-equivalent config, auto expert cache + spec-min-p 0.5): the real Codex CLI (0.163.0) writes a Three.js tic-tac-toe game (rerun after the 32768 output cap) against the production stack +# (leleka-inference Original serve, default conversation cache, behind strata-next). Profiling on, engine log kept. +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 +export E2E_OUT=$HOME/work/leleka-e2e/runs/943c-codex-ttt +export CODEX_TIMEOUT_S=5400 +export LELEKA_BRINGUP_TRACE=1 # PREFILL-PROFILE / round lines in the engine log +# reference-equivalent engine configuration (the vanilla Strata Codex runs): automatic per-layer expert cache with the 98x/990 profile, +# --spec-min-p 0.5 (MTP depth 4 is the Original's default), INT8 K+V 32768 resident cells (default), adaptive tier, seed default; the gpu budget +# the way the 98x/99x auto-cache jobs did (30 GiB), so the auto-sized cache has the free VRAM the Original had +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=32212254720 +export E2E_ENGINE_ARGS="--spec-min-p 0.5" +export E2E_SAMPLE_S=10 +export LELEKA_CAPTURE_DIR=$HOME/work/codex-e2e/capture/943c-codex-ttt # PRIVATE: prompt + generated token ids of every request, for offline replay (never in Git) # RSS / VRAM / MemAvailable every 10 s +export E2E_STATUS_FILE=$HOME/work/codex-e2e/STATUS.txt +export E2E_RUN_CMD="bash $HOME/work/leleka-e2e/scripts/e2e/codex/run-codex.sh ttt" +rm -rf $E2E_OUT $LELEKA_CAPTURE_DIR +date -u +%FT%TZ; sha256sum $E2E_BIN/* $HOME/work/codex-e2e/bin/codex $HOME/work/codex-e2e/vendor/three.module.min.js +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh +echo "run-e2e rc=$?" +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/945c-e2e-codex-crm.sh b/scripts/e2e/codex/jobs/945c-e2e-codex-crm.sh new file mode 100644 index 00000000..6b28e1da --- /dev/null +++ b/scripts/e2e/codex/jobs/945c-e2e-codex-crm.sh @@ -0,0 +1,21 @@ +set -uo pipefail +# claude/e2e (rerun with the reference-equivalent config, auto expert cache + spec-min-p 0.5): the real Codex CLI (0.163.0) builds a CRM (Python stdlib + SQLite) with the PREFIX CACHE on (--prefix-cache-mib auto, +# replaces the conversation cache). Long-horizon session; profiling on, engine log kept. +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 +export E2E_OUT=$HOME/work/leleka-e2e/runs/945c-codex-crm +export CODEX_TIMEOUT_S=10200 +export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 +# reference-equivalent engine configuration (the vanilla Strata Codex runs): automatic per-layer expert cache with the 98x/990 profile, +# --spec-min-p 0.5 (MTP depth 4 is the Original's default), INT8 K+V 32768 resident cells (default), adaptive tier, seed default; the gpu budget +# the way the 98x/99x auto-cache jobs did (30 GiB), so the auto-sized cache has the free VRAM the Original had +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=32212254720 +export E2E_ENGINE_ARGS="--prefix-cache-mib auto --spec-min-p 0.5" +export E2E_SAMPLE_S=10 +export LELEKA_CAPTURE_DIR=$HOME/work/codex-e2e/capture/945c-codex-crm # PRIVATE: prompt + generated token ids of every request, for offline replay (never in Git) +export E2E_STATUS_FILE=$HOME/work/codex-e2e/STATUS.txt +export E2E_RUN_CMD="bash $HOME/work/leleka-e2e/scripts/e2e/codex/run-codex.sh crm" +rm -rf $E2E_OUT $LELEKA_CAPTURE_DIR +date -u +%FT%TZ; sha256sum $E2E_BIN/* $HOME/work/codex-e2e/bin/codex +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh +echo "run-e2e rc=$?" +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/947-e2e-replay.sh b/scripts/e2e/codex/jobs/947-e2e-replay.sh new file mode 100644 index 00000000..ae281e62 --- /dev/null +++ b/scripts/e2e/codex/jobs/947-e2e-replay.sh @@ -0,0 +1,22 @@ +set -uo pipefail +# claude/e2e: offline replay of the captured real Codex sessions (943b tic-tac-toe: conversation cache; 945 CRM: prefix cache auto) +# through the Original serve stack in one process each: greedy, recorded output length as the budget. Reports weighted decode tok/s. +A=$HOME/leleka-gates/assets; G=$HOME/work/gpu-runs +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +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_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$G/baseline/profile.bin LELEKA_GRAPH_EXEC_REUSE=off LELEKA_SERVE_PROFILE=1 +export LELEKA_ORIGINAL_SERVE_REPLAY=yes +BIN=$HOME/work/leleka-e2e/bin-sm120/leleka-runtime-tests +mkdir -p $HOME/work/leleka-e2e/runs/947-replay +date -u +%FT%TZ; sha256sum $BIN +echo "=== replay 943b-codex-ttt (conversation cache)" +LELEKA_REPLAY_DIR=$HOME/work/codex-e2e/capture/943b-codex-ttt $BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke > $HOME/work/leleka-e2e/runs/947-replay/ttt.log 2>&1 +grep -E '^REPLAY (SUMMARY|config)|test result|panicked' $HOME/work/leleka-e2e/runs/947-replay/ttt.log +echo "=== replay 945-codex-crm (prefix cache auto)" +LELEKA_REPLAY_PREFIX_MIB=auto LELEKA_REPLAY_DIR=$HOME/work/codex-e2e/capture/945-codex-crm $BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke > $HOME/work/leleka-e2e/runs/947-replay/crm.log 2>&1 +grep -E '^REPLAY (SUMMARY|config)|test result|panicked' $HOME/work/leleka-e2e/runs/947-replay/crm.log +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/948-e2e-replay-arms.sh b/scripts/e2e/codex/jobs/948-e2e-replay-arms.sh new file mode 100644 index 00000000..f6a981bf --- /dev/null +++ b/scripts/e2e/codex/jobs/948-e2e-replay-arms.sh @@ -0,0 +1,31 @@ +set -uo pipefail +# claude/e2e: replay of the first 30 requests (context 9k -> ~45k) of the real tic-tac-toe Codex session (capture 943b, conversation cache), four configurations +# on the head build: expert tier 2048 slots vs auto-sized (per layer, profile of the 98x jobs), spec_min_p 0 (shipped default) vs 0.5 (the reference runs). +# Each arm is one process (model load ~7 min). Prints REPLAY SUMMARY weighted_decode_tok_s, tokens per round (rounds, tokens) and tier shares. +A=$HOME/leleka-gates/assets; G=$HOME/work/gpu-runs +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +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_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$G/baseline/profile.bin LELEKA_GRAPH_EXEC_REUSE=off LELEKA_SERVE_PROFILE=1 +export LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 +export LELEKA_REPLAY_DIR=$HOME/work/codex-e2e/capture/943b-codex-ttt LELEKA_REPLAY_COUNT=30 +BIN=$HOME/work/leleka-e2e/bin-sm120/leleka-runtime-tests-73e77f8 +OUT=$HOME/work/leleka-e2e/runs/948-replay-arms; mkdir -p $OUT +date -u +%FT%TZ; sha256sum $BIN +arm() { # name slots min_p + echo "=== arm $1: slots=$2 spec_min_p=$3"; date -u +%FT%TZ + LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=$2 LELEKA_REPLAY_SPEC_MIN_P=$3 $BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke > $OUT/$1.log 2>&1 + grep -E '^REPLAY (SUMMARY|config)|test result|panicked' $OUT/$1.log | cut -c1-400 + awk '/^REPLAY #[0-9]+ file/{for(i=1;i<=NF;i++){split($i,k,"="); if(k[1]=="produced")p+=k[2]; if(k[1]=="rounds")r+=k[2]}} END{if(r>0) printf "tokens_per_round=%.2f (%d tokens / %d rounds)\n", p/r, p, r}' $OUT/$1.log + grep -E 'entries vram' $OUT/$1.log | tail -1 | cut -c1-300 +} +export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt # the Original draft vocabulary (all arms; arm F drops it) +arm A-2048-p0 2048 0 +arm D-2048-p05 2048 0.5 +arm B-auto-p0 auto 0 +arm C-auto-p05 auto 0.5 +(unset LELEKA_ORIGINAL_SERVE_RT_DIR; arm F-auto-p05-nort auto 0.5) +date -u +%FT%TZ diff --git a/scripts/e2e/run-e2e.sh b/scripts/e2e/run-e2e.sh index 1310675e..4643dd41 100644 --- a/scripts/e2e/run-e2e.sh +++ b/scripts/e2e/run-e2e.sh @@ -83,6 +83,9 @@ cat >"$STATE/strata.json" </dev/null; } stop_one() { # name pid grace @@ -129,7 +132,7 @@ eval "\"$BIN/leleka-inference\" --listen 127.0.0.1:18766 --token-env LELEKA_RUNT --gpu 0 --gpu-budget ${E2E_GPU_BUDGET:-25769803776} --context-tokens 262144 \ --kar-archive-fd $FD --kar-provenance \"$A/qwen-iq3-s-l2-v4.kar.provenance.json\" \ --mtp-pack \"$A/data/mtp-rt\" --mtp-staging \"$G/mtp-staging-own\" \ - --backend-mode original ${E2E_ENGINE_ARGS:-} >\"$OUT/inference.log\" 2>&1 &" + --backend-mode original $RT_ARG ${E2E_ENGINE_ARGS:-} >\"$OUT/inference.log\" 2>&1 &" PID_INF=$! unset CUDA_INJECTION64_PATH sleep 3 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/laptop/lap_run.sh b/scripts/laptop/lap_run.sh new file mode 100644 index 00000000..5329ffb9 --- /dev/null +++ b/scripts/laptop/lap_run.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# One laptop run of the integrated head (docs/laptop-profile.md, claude/laptop-opt): production-like configuration of the +# Original serve stack on the RTX 3080 laptop (mapped experts, VRAM tier auto + profile, KAR level 2 as a read-only file, +# MTP depth 4 with the draft vocabulary bound, spec-min-p 0.5, INT8 KV, seed on by default), holding ~/LAPTOP_GPU.lock. +# +# lap_run.sh LABEL TEST_BIN [NAME=VALUE ...] (RUN_CMD="..." runs that command instead of the test, same safeguards) +# +# Environment (all optional): +# PROMPTS file with one comma-separated token-ID line per prompt (default ~/lopt/prompts/short.ids) +# OUT results directory (default ~/lopt/results) +# COLD=1 evict the model files from the page cache first (posix_fadvise DONTNEED; no root needed) +# MON_INTERVAL sampling period of monitor.sh (default 1 s) +# NAME=VALUE arguments are exported, so any LELEKA_* switch of the test (and the engine) passes through. +# Safeguards (the laptop BSODed twice, 0x19C WIN32K_POWER_WATCHDOG_TIMEOUT, under the OEM 30 W profile): before the run the GPU +# state is recorded and the run is REFUSED (exit 4) when the power limit is below 100 W, a SW power cap / SW thermal slowdown is +# active at idle or the state is P5; during the run monitor.sh samples at 1 Hz and kills the run on P5 under load, a limit below +# 100 W, more than 90 C or a stall of the machine (> 10 s between samples; then stop all GPU work). The run is bounded by +# RUN_TIMEOUT (seconds, default 900) and a cool-down of COOLDOWN seconds (default 120) is kept after the previous run +# (stamp file ~/lopt/last_gpu_run). +# Writes OUT/LABEL.{env,stderr,timing,outputs,mem.tsv,mem.peak,gpu} and prints the request lines and the peaks. +set -uo pipefail +label="$1"; bin="$2"; shift 2 +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +M="${MODEL_DIR:-$HOME/laptop/model}" +OUT="${OUT:-$HOME/lopt/results}" +mkdir -p "$OUT"; mkdir -p -m 700 "$HOME/laptop/mtp-staging" +export LD_LIBRARY_PATH="$(ls -d "$HOME"/cublas-12.9.1.4/x/*/lib 2>/dev/null | head -1):${LD_LIBRARY_PATH:-}" +export PATH="$HOME/cuda-toolkits/13.2.2/bin:$PATH" +export LELEKA_LAPTOP_BENCH=yes +export LELEKA_STRA169_IQ3S_SHARD0="$M/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" +export LELEKA_STRA169_IQ3S_SHARD1="$M/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" +export LELEKA_LAPTOP_KAR_FILE="$M/qwen-iq3-s-l2-v4.kar" LELEKA_STRA169_KAR_PROVENANCE="$M/qwen-iq3-s-l2-v4.kar.provenance.json" +export LELEKA_STRA169_MTP_PACK="$HOME/laptop/data/mtp-rt" LELEKA_STRA169_MTP_STAGING="$HOME/laptop/mtp-staging" +export LELEKA_ORIGINAL_SERVE_RT_DIR="${LELEKA_ORIGINAL_SERVE_RT_DIR-$HOME/laptop/data/mtp-rt}" # the draft vocabulary (--mtp-rt-dir) +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS="${LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS:-auto}" +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE="${LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE:-$HOME/laptop/data/expert-profile.bin}" +export LELEKA_LAPTOP_PROMPT_IDS="${PROMPTS:-$HOME/lopt/prompts/short.ids}" +export LELEKA_LAPTOP_PROMPT_CACHE="${LELEKA_LAPTOP_PROMPT_CACHE:-0}" +export LELEKA_LAPTOP_MAX_NEW="${LELEKA_LAPTOP_MAX_NEW:-128}" LELEKA_LAPTOP_REPEAT="${LELEKA_LAPTOP_REPEAT:-2}" +export LELEKA_BRINGUP_TRACE="${LELEKA_BRINGUP_TRACE:-1}" +for kv in "$@"; do export "${kv?}"; done + +gpu_state() { + nvidia-smi --query-gpu=pstate,clocks.sm,clocks.max.sm,clocks.mem,clocks.max.mem,power.draw,power.limit,temperature.gpu,pcie.link.gen.current,pcie.link.width.current --format=csv,noheader + nvidia-smi -q -d PERFORMANCE | grep -E "SW Power Cap|SW Thermal|HW Slowdown|HW Thermal|HW Power" | tr -s ' ' | head -5 | paste -sd';' +} +preflight() { + local q lim + q="$(nvidia-smi -q -d PERFORMANCE,POWER)" + lim="$(awk -F: '/Current Power Limit/ && $2 !~ /N\/A/ {gsub(/[ W]/, "", $2); print $2; exit}' <<< "$q")" + echo "preflight: $(nvidia-smi --query-gpu=pstate,clocks.sm,clocks.mem,power.draw,temperature.gpu --format=csv,noheader) limit=${lim:-?} W" + if ! awk -v l="${lim:-0}" 'BEGIN {exit !(l+0 >= 100)}'; then echo "REFUSED: power limit ${lim:-?} W < 100 W"; return 1; fi + if grep -E "SW Power Cap|SW Thermal Slowdown" <<< "$q" | grep -q ": Active"; then echo "REFUSED: SW power cap / thermal slowdown active at idle"; return 1; fi + if grep -E "Performance State" <<< "$q" | grep -q "P5"; then echo "REFUSED: performance state P5"; return 1; fi +} +until mkdir "$HOME/LAPTOP_GPU.lock" 2>/dev/null; do echo "laptop GPU lock held by: $(cat "$HOME/LAPTOP_GPU.lock/owner" 2>/dev/null)"; sleep 20; done +echo "claude/laptop-opt $label $(date -u +%FT%TZ)" > "$HOME/LAPTOP_GPU.lock/owner" +trap 'rm -rf "$HOME/LAPTOP_GPU.lock"; date +%s > "$HOME/lopt/last_gpu_run"' EXIT +last=$(cat "$HOME/lopt/last_gpu_run" 2>/dev/null || echo 0); wait_s=$(( ${COOLDOWN:-120} - ($(date +%s) - last) )) +if [ "$wait_s" -gt 0 ]; then echo "cool-down ${wait_s} s"; sleep "$wait_s"; fi +if ! preflight | tee "$OUT/$label.preflight"; then echo "refused: see $OUT/$label.preflight"; exit 4; fi + +if [[ "${COLD:-}" == 1 ]]; then + python3 -I - "$M"/*.gguf "$M"/*.kar <<'PY' +import os, sys +for p in sys.argv[1:]: + fd = os.open(p, os.O_RDONLY) + os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED) + os.close(fd) +PY +fi +{ echo "# $label $(date -u +%FT%TZ) cold=${COLD:-0}"; echo "MemAvailable_MiB=$(awk '$1=="MemAvailable:" {printf "%d", $2/1024}' /proc/meminfo) Cached_MiB=$(awk '$1=="Cached:" {printf "%d", $2/1024}' /proc/meminfo)" + echo "gpu_before: $(gpu_state)"; } > "$OUT/$label.gpu" +env | grep -E '^LELEKA_' | sort > "$OUT/$label.env" +sha256sum "$bin" 2>/dev/null | cut -c1-16 >> "$OUT/$label.env" + +if [[ -n "${RUN_CMD:-}" ]]; then # any other GPU job under the same safeguards (microbenchmarks, ...) + timeout -s TERM -k 20 "${RUN_TIMEOUT:-900}" bash -c "$RUN_CMD" > "$OUT/$label.stdout" 2> "$OUT/$label.stderr" & +else + timeout -s TERM -k 20 "${RUN_TIMEOUT:-900}" "$bin" --ignored --exact backend::original_serve_laptop::original_serve_laptop_bench --nocapture --test-threads 1 \ + > "$OUT/$label.stdout" 2> "$OUT/$label.stderr" & +fi +tpid=$! +sleep 1 +pid="$(pgrep -P "$tpid" | head -1)"; pid="${pid:-$tpid}" # the test itself, not the timeout wrapper +bash "$here/monitor.sh" "$pid" "$OUT/$label.mem.tsv" > "$OUT/$label.mem.peak" & +mon=$! +wait "$tpid"; rc=$? +wait "$mon" || true +{ echo "gpu_after: $(gpu_state)"; echo "exit=$rc"; [ -f "$OUT/$label.mem.tsv.abort" ] && echo "ABORT: $(cat "$OUT/$label.mem.tsv.abort")"; } >> "$OUT/$label.gpu" +cat "$OUT/$label.mem.peak" >> "$OUT/$label.gpu" +grep -hE '^LAPTOP (load|config|request|tier|failed|done)' "$OUT/$label.stderr" "$OUT/$label.stdout" \ + | sed -E 's/ (VmRSS|VmHWM|RssAnon|RssFile|RssShmem|VmLck|VmPin|VmSwap|MemAvailable|SwapFree)=/ \1=/g' > "$OUT/$label.timing" +grep -hE '^LAPTOP output' "$OUT/$label.stderr" | sed 's/^LAPTOP //' > "$OUT/$label.outputs" +grep -E '^LAPTOP (request|failed|done)' "$OUT/$label.timing" | sed -E 's/; VmRSS.*//' +cat "$OUT/$label.mem.peak" +echo "exit=$rc label=$label" diff --git a/scripts/laptop/lap_sum.py b/scripts/laptop/lap_sum.py new file mode 100644 index 00000000..6482d7b8 --- /dev/null +++ b/scripts/laptop/lap_sum.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Summarise laptop bench runs (scripts/laptop/lap_run.sh output, docs/laptop-profile.md). + + lap_sum.py [--skip-pass0] OUT/LABEL.timing [...] + +Per label and per prompt (index and token count): requests, mean prefill tok/s, mean TTFT, decode tok/s weighted +(sum of produced tokens over sum of decode time, the charter's weighting) and the median/min/max of the per-request +decode rate. A final line per label gives the weighted decode over every request. Offline tooling only. +""" +import re +import statistics +import sys +from collections import defaultdict + +LINE = re.compile(r"^LAPTOP request p(\d+) pass=(\d+) prompt=(\d+) produced=(\d+) rounds=(\d+) ttft_ms=([\d.]+) prompt_ms=([\d.]+) " + r"decode_ms=([\d.]+) total_ms=([\d.]+) prefill_tok_s=([\d.]+) decode_tok_s=([\d.]+)") + + +def load(path): + rows = [] + for line in open(path, encoding="utf-8", errors="replace"): + m = LINE.match(line.strip()) + if m: + p, ps, n, prod, rounds, ttft, pms, dms, tot, pre, dec = m.groups() + rows.append(dict(p=int(p), pas=int(ps), n=int(n), prod=int(prod), rounds=int(rounds), ttft=float(ttft), pms=float(pms), + dms=float(dms), pre=float(pre), dec=float(dec))) + return rows + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + skip0 = "--skip-pass0" in sys.argv + for path in args: + rows = load(path) + if skip0: + rows = [r for r in rows if r["pas"] > 0] + print(f"== {path}: {len(rows)} requests") + by = defaultdict(list) + for r in rows: + by[(r["p"], r["n"])].append(r) + print(f"{'prompt':>6} {'tokens':>7} {'n':>3} {'prefill tok/s':>14} {'TTFT s':>8} {'decode w. tok/s':>16} {'median':>7} {'min-max':>13} {'tok/round':>9}") + for (p, n), rs in sorted(by.items(), key=lambda kv: kv[0][1]): + w = sum(r["prod"] for r in rs) / max(sum(r["dms"] for r in rs) / 1e3, 1e-9) + decs = [r["dec"] for r in rs] + tpr = sum(r["prod"] for r in rs) / max(sum(r["rounds"] for r in rs), 1) + print(f"{'p' + str(p):>6} {n:>7} {len(rs):>3} {statistics.mean(r['pre'] for r in rs):>14.1f} {statistics.mean(r['ttft'] for r in rs) / 1e3:>8.2f} " + f"{w:>16.2f} {statistics.median(decs):>7.2f} {min(decs):>6.2f}-{max(decs):<6.2f} {tpr:>9.2f}") + if rows: + w = sum(r["prod"] for r in rows) / max(sum(r["dms"] for r in rows) / 1e3, 1e-9) + print(f" all: weighted decode {w:.2f} tok/s over {sum(r['prod'] for r in rows)} tokens") + + +if __name__ == "__main__": + main() diff --git a/scripts/laptop/monitor.sh b/scripts/laptop/monitor.sh index 972a435c..ade81a6b 100644 --- a/scripts/laptop/monitor.sh +++ b/scripts/laptop/monitor.sh @@ -1,18 +1,50 @@ #!/usr/bin/env bash -# Sample one process's memory and the GPU's VRAM once a second until it exits (laptop profile benches). +# Sample one process's memory and the GPU once a second until it exits (laptop profile benches), and enforce the laptop +# safeguards: the monitored process is killed (TERM, then KILL after 20 s) and ABORT is written to OUT.tsv.abort when +# * the GPU is in P5 with the memory clock below 2 GHz AND the SW power cap / SW thermal slowdown reasons (0x4 | 0x20) active: the OEM +# profile (a plain P5 with reason 0x1 "idle" while the model is being loaded into VRAM is a clock ramp, seen in T1_short, and is not +# aborted), or the power limit is below 100 W, +# or the GPU temperature exceeds 90 C (the OEM silent profile and the thermal state that preceded the BSODs of 2026-10-16/23); +# * two consecutive samples are more than 10 s apart (the machine stalled): STALL is written, all GPU work must stop. # monitor.sh PID OUT.tsv # Columns: unix time, VRAM used MiB (nvidia-smi, whole GPU), VmRSS, RssAnon, RssFile, RssShmem, VmLck, VmPin (MiB), -# MemAvailable (MiB, whole VM). Prints the peaks when the process is gone. +# MemAvailable (MiB, whole VM), VmSwap of the process (MiB), swap used by the VM (MiB), GPU SM and memory clock (MHz), +# board power (W), performance state, clocks_throttle_reasons.active (hex bitmask), power limit (W), temperature (C), utilisation (%). +# MON_INTERVAL (seconds, default 1) sets the sampling period. Prints the peaks and the mean clocks when the process is gone. set -u pid="$1"; out="$2" -printf 't\tvram\trss\tanon\tfile\tshmem\tlck\tpin\tavail\n' > "$out" +interval="${MON_INTERVAL:-1}" +printf 't\tvram\trss\tanon\tfile\tshmem\tlck\tpin\tavail\tvmswap\tswapused\tsm_mhz\tmem_mhz\tpower_w\tpstate\tthrottle\tlimit_w\ttemp_c\tutil\n' > "$out" +rm -f "$out.abort" field() { awk -v k="$1:" '$1==k {printf "%d", $2/1024}' "/proc/$pid/status" 2>/dev/null; } +abort() { + echo "$1" > "$out.abort"; echo "MONITOR ABORT: $1" >&2 + pkill -TERM -P "$pid" 2>/dev/null; kill -TERM "$pid" 2>/dev/null + ( sleep 20; pkill -KILL -P "$pid" 2>/dev/null; kill -KILL "$pid" 2>/dev/null ) & +} +prev=$(date +%s); aborted=0 while kill -0 "$pid" 2>/dev/null; do - vram=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | head -1) + gpu=$(nvidia-smi --query-gpu=memory.used,clocks.sm,clocks.mem,power.draw,pstate,clocks_throttle_reasons.active,power.limit,temperature.gpu,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -1 | tr -d ' ') + IFS=, read -r vram smc memc pw ps thr lim temp util <<< "$gpu" + swapused=$(awk '$1=="SwapTotal:" {t=$2} $1=="SwapFree:" {f=$2} END {printf "%d", (t-f)/1024}' /proc/meminfo) avail=$(awk '$1=="MemAvailable:" {printf "%d", $2/1024}' /proc/meminfo) - printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%s)" "${vram:-0}" "$(field VmRSS)" "$(field RssAnon)" \ - "$(field RssFile)" "$(field RssShmem)" "$(field VmLck)" "$(field VmPin)" "$avail" >> "$out" - sleep 1 + now=$(date +%s) + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$now" "${vram:-0}" "$(field VmRSS)" "$(field RssAnon)" \ + "$(field RssFile)" "$(field RssShmem)" "$(field VmLck)" "$(field VmPin)" "$avail" "$(field VmSwap)" "$swapused" \ + "${smc:-0}" "${memc:-0}" "${pw:-0}" "${ps:-}" "${thr:-}" "${lim:-0}" "${temp:-0}" "${util:-0}" >> "$out" + if [ "$aborted" = 0 ]; then + if [ $((now - prev)) -gt 10 ]; then abort "STALL: $((now - prev)) s between samples"; aborted=1 + elif awk -v l="${lim:-0}" 'BEGIN {exit !(l+0 > 0 && l+0 < 100)}'; then abort "power limit ${lim} W"; aborted=1 + elif [ "${temp:-0}" -gt 90 ] 2>/dev/null; then abort "temperature ${temp} C"; aborted=1 + elif [ "${ps:-}" = P5 ] && [ "${memc:-0}" -lt 2000 ] 2>/dev/null && [ $(( ${thr:-0x0} & 0x24 )) -ne 0 ] 2>/dev/null; then + abort "P5, memory ${memc} MHz, SW power cap / thermal slowdown active (reasons ${thr}): the OEM profile"; aborted=1 + fi + fi + prev=$now + sleep "$interval" done -awk -F'\t' 'NR>1 {for (i=2;i<=9;i++) if ($i+0>m[i]) m[i]=$i+0; if (min==""||$9+01 {for (i=2;i<=11;i++) if ($i+0>m[i]) m[i]=$i+0; if (min==""||$9+0tm) tm=$18+0; + if ($12+0>0) {n++; sm+=$12; mm+=$13; pw+=$14}} + END {printf "peak MiB: vram=%d rss=%d anon=%d file=%d shmem=%d lck=%d pin=%d; min MemAvailable=%d; peak VmSwap=%d, VM swap used=%d; mean clocks sm=%d mem=%d MHz power=%.0f W; max temp=%d C\n", + m[2],m[3],m[4],m[5],m[6],m[7],m[8],min,m[10],m[11],(n?sm/n:0),(n?mm/n:0),(n?pw/n:0),tm}' "$out" +[ -f "$out.abort" ] && cat "$out.abort" diff --git a/scripts/memory/fit_e2e_env.py b/scripts/memory/fit_e2e_env.py new file mode 100644 index 00000000..78fef496 --- /dev/null +++ b/scripts/memory/fit_e2e_env.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Fit the RSS of an e2e run (docs/e2e-data/NNN-env.tsv + NNN-trace.csv) against the request count: fit_e2e_env.py ENV.tsv TRACE.csv (offline analysis).""" +import csv,sys +sys.path.insert(0,"/mnt/c/Users/pavel/work/leleka-memory/scripts/memory") +import leak_fit as lf +env=[l.rstrip("\n").split("\t") for l in open(sys.argv[1])] +hdr=env[0]; rows=[dict(zip(hdr,r)) for r in env[1:] if r[1]=="inference"] +tr=list(csv.DictReader(open(sys.argv[2]))) +done=[int(r["t_done_ms"])/1000 for r in tr] +def reqs(t): return sum(1 for d in done if d<=t) +pts=[] +for r in rows: + t=int(r["epoch"]); pts.append((reqs(t), int(r["rssanon_mib"]), int(r["vmrss_mib"]), int(r["mem_available_mib"]), t)) +print(len(pts),"samples; requests",pts[0][0],"->",pts[-1][0]) +for name,start_req in (("whole run",0),("last 40% of requests",int(pts[-1][0]*0.6)),("after the store is full (>= request 70)",70)): + sel=[p for p in pts if p[0]>=start_req] + for lbl,k in (("RssAnon",1),("VmRSS",2),("MemAvailable",3)): + pp=[(p[0],p[k]*1048576.0) for p in sel] + f=lf.ols(pp) + s,lo,hi=(v*1000/1048576.0 for v in f) + print(f"{name:<32}{lbl:<13} {s:+9.1f} MiB/1000req [{lo:+.1f},{hi:+.1f}] theil-sen {lf.theil_sen(pp)*1000/1048576.0:+.1f} n={len(pp)} first {pp[0][1]/1048576:.0f} last {pp[-1][1]/1048576:.0f}") diff --git a/scripts/memory/jobs/919-mem-leak-check.sh b/scripts/memory/jobs/919-mem-leak-check.sh new file mode 100644 index 00000000..653fccd2 --- /dev/null +++ b/scripts/memory/jobs/919-mem-leak-check.sh @@ -0,0 +1,11 @@ +set -uo pipefail +# claude/memory-safety: RSS slope / leak question (arm: default). Mixed requests for 11000 s (8k..180k prompts, shared and unshared sessions, prefix-cache churn under an auto budget, +# cancels, over-long refusals), sampled every 30 s: RSS anon/file/shmem, swap, meminfo, VRAM, prefix store, glibc heap; OLS + Theil-Sen slope per 1000 requests after a 25% warm-up. +# File-mapped experts (MemAvailable stays ~58 GiB; the 15 GiB rule): an anon/shmem leak shows the same as with the resident bank. +source ~/work/mem-jobs/mem-common.sh +cd $HOME/work/leleka-mem-bin +preflight 45 +watch_start +run_mem leak-919-check backend::original_serve_memory_smoke::original_serve_memory_smoke LELEKA_MEM_SCENARIO=leak LELEKA_MEM_LEAK_SECS=420 LELEKA_MEM_LEAK_SAMPLE_S=10 LELEKA_MEM_BIG_EVERY=1000 LELEKA_MEM_PREFIX_MIB=auto LELEKA_MEM_LEAK_TSV=$RAWDIR/919-check.tsv LELEKA_MEM_SESSIONS=8 LELEKA_MEM_SESSION_CAP=40000 LELEKA_MEM_BIG=100000,180000 LELEKA_MEM_BIG_EVERY=120 +watch_stop +holder_state diff --git a/scripts/memory/jobs/920-mem-leak-3h.sh b/scripts/memory/jobs/920-mem-leak-3h.sh new file mode 100644 index 00000000..7be7fa29 --- /dev/null +++ b/scripts/memory/jobs/920-mem-leak-3h.sh @@ -0,0 +1,11 @@ +set -uo pipefail +# claude/memory-safety: RSS slope / leak question (arm: default). Mixed requests for 11000 s (8k..180k prompts, shared and unshared sessions, prefix-cache churn under an auto budget, +# cancels, over-long refusals), sampled every 30 s: RSS anon/file/shmem, swap, meminfo, VRAM, prefix store, glibc heap; OLS + Theil-Sen slope per 1000 requests after a 25% warm-up. +# File-mapped experts (MemAvailable stays ~58 GiB; the 15 GiB rule): an anon/shmem leak shows the same as with the resident bank. +source ~/work/mem-jobs/mem-common.sh +cd $HOME/work/leleka-mem-bin +preflight 45 +watch_start +run_mem leak-920-mem-leak-3h backend::original_serve_memory_smoke::original_serve_memory_smoke LELEKA_MEM_SCENARIO=leak LELEKA_MEM_LEAK_SECS=11000 LELEKA_MEM_PREFIX_MIB=auto LELEKA_MEM_LEAK_TSV=$RAWDIR/920-mem-leak-3h.tsv LELEKA_MEM_SESSIONS=8 LELEKA_MEM_SESSION_CAP=40000 LELEKA_MEM_BIG=100000,180000 LELEKA_MEM_BIG_EVERY=120 +watch_stop +holder_state diff --git a/scripts/memory/jobs/921-mem-leak-arena2.sh b/scripts/memory/jobs/921-mem-leak-arena2.sh new file mode 100644 index 00000000..341659a7 --- /dev/null +++ b/scripts/memory/jobs/921-mem-leak-arena2.sh @@ -0,0 +1,11 @@ +set -uo pipefail +# claude/memory-safety: RSS slope / leak question (arm: MALLOC_ARENA_MAX=2). Mixed requests for 2700 s (8k..180k prompts, shared and unshared sessions, prefix-cache churn under an auto budget, +# cancels, over-long refusals), sampled every 30 s: RSS anon/file/shmem, swap, meminfo, VRAM, prefix store, glibc heap; OLS + Theil-Sen slope per 1000 requests after a 25% warm-up. +# File-mapped experts (MemAvailable stays ~58 GiB; the 15 GiB rule): an anon/shmem leak shows the same as with the resident bank. +source ~/work/mem-jobs/mem-common.sh +cd $HOME/work/leleka-mem-bin +preflight 45 +watch_start +run_mem leak-921-mem-leak-arena2 backend::original_serve_memory_smoke::original_serve_memory_smoke MALLOC_ARENA_MAX=2 LELEKA_MEM_SCENARIO=leak LELEKA_MEM_LEAK_SECS=2700 LELEKA_MEM_PREFIX_MIB=auto LELEKA_MEM_LEAK_TSV=$RAWDIR/921-mem-leak-arena2.tsv LELEKA_MEM_SESSIONS=8 LELEKA_MEM_SESSION_CAP=40000 LELEKA_MEM_BIG=100000,180000 LELEKA_MEM_BIG_EVERY=120 +watch_stop +holder_state diff --git a/scripts/memory/jobs/922-mem-leak-notrim.sh b/scripts/memory/jobs/922-mem-leak-notrim.sh new file mode 100644 index 00000000..1afc67f3 --- /dev/null +++ b/scripts/memory/jobs/922-mem-leak-notrim.sh @@ -0,0 +1,11 @@ +set -uo pipefail +# claude/memory-safety: RSS slope / leak question (arm: LELEKA_MEMORY_NO_TRIM=1). Mixed requests for 2700 s (8k..180k prompts, shared and unshared sessions, prefix-cache churn under an auto budget, +# cancels, over-long refusals), sampled every 30 s: RSS anon/file/shmem, swap, meminfo, VRAM, prefix store, glibc heap; OLS + Theil-Sen slope per 1000 requests after a 25% warm-up. +# File-mapped experts (MemAvailable stays ~58 GiB; the 15 GiB rule): an anon/shmem leak shows the same as with the resident bank. +source ~/work/mem-jobs/mem-common.sh +cd $HOME/work/leleka-mem-bin +preflight 45 +watch_start +run_mem leak-922-mem-leak-notrim backend::original_serve_memory_smoke::original_serve_memory_smoke LELEKA_MEMORY_NO_TRIM=1 LELEKA_MEM_SCENARIO=leak LELEKA_MEM_LEAK_SECS=2700 LELEKA_MEM_PREFIX_MIB=auto LELEKA_MEM_LEAK_TSV=$RAWDIR/922-mem-leak-notrim.tsv LELEKA_MEM_SESSIONS=8 LELEKA_MEM_SESSION_CAP=40000 LELEKA_MEM_BIG=100000,180000 LELEKA_MEM_BIG_EVERY=120 +watch_stop +holder_state diff --git a/scripts/memory/jobs/mem-common.sh b/scripts/memory/jobs/mem-common.sh index 2a9e5f69..567c889e 100644 --- a/scripts/memory/jobs/mem-common.sh +++ b/scripts/memory/jobs/mem-common.sh @@ -12,7 +12,7 @@ export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_ export LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 export LELEKA_ORIGINAL_SERVE_CAPACITY=${LELEKA_ORIGINAL_SERVE_CAPACITY:-8192} LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 export LELEKA_MEM_SMOKE=yes LELEKA_SERVE_PROFILE=1 -BIN=${BIN:-$HOME/work/leleka-mem-bin/mem-a4} +BIN=${BIN:-$HOME/work/leleka-mem-bin/mem-a8} RAWDIR=$G/mem-logs avail_gib() { awk '/MemAvailable/{printf "%d", $2/1048576}' /proc/meminfo; } swap_used_mib() { awk '/SwapTotal/{t=$2} /SwapFree/{f=$2} END{printf "%d", (t-f)/1024}' /proc/meminfo; } diff --git a/scripts/memory/leak_fit.py b/scripts/memory/leak_fit.py new file mode 100644 index 00000000..c81c13c4 --- /dev/null +++ b/scripts/memory/leak_fit.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Offline fit of the TSV written by the `leak` scenario of the memory smoke (docs/memory-safety.md, section 5.6). + + leak_fit.py RUN.tsv [--warmup-pct 25] [--tmax SECONDS] [--label NAME] + leak_fit.py --compare control.tsv:NAME arm.tsv:NAME ... [--tmax 2700] [--warmup-pct 25] + +Per series (RSS anon/file/shmem, swap, VRAM, prefix store, glibc heap in use / free / arena): slope in MiB per 1000 requests after the +warm-up with a 95% interval (OLS, samples taken as independent: a lower bound of the uncertainty) and the Theil-Sen slope; `--compare` prints the +level (median of the last third) of the series that fragmentation moves, for arms run with different allocator settings. +Offline analysis only; the engine does not need Python. +""" +import argparse +import math +import statistics + +SERIES = ["rss", "rss_anon", "rss_file", "rss_shmem", "swap", "vram_used", "vram_acct", "prefix_store", "malloc_arena", "malloc_in_use", "malloc_free", "malloc_mmapped", "avail"] +MIB = 1048576.0 + + +def load(path, tmax=None): + with open(path) as f: + header = f.readline().rstrip("\n").split("\t") + rows = [dict(zip(header, map(float, line.split("\t")))) for line in f if line.strip()] + if tmax is not None: + rows = [r for r in rows if r["t_s"] <= tmax] + return rows + + +def ols(points): + n = len(points) + mx = sum(p[0] for p in points) / n + my = sum(p[1] for p in points) / n + sxx = sum((p[0] - mx) ** 2 for p in points) + if sxx == 0: + return None + slope = sum((p[0] - mx) * (p[1] - my) for p in points) / sxx + icpt = my - slope * mx + sse = sum((p[1] - icpt - slope * p[0]) ** 2 for p in points) + se = math.sqrt(sse / (n - 2) / sxx) + return slope, slope - 1.96 * se, slope + 1.96 * se + + +def theil_sen(points): + slopes = [(b[1] - a[1]) / (b[0] - a[0]) for i, a in enumerate(points) for b in points[i + 1:] if b[0] != a[0]] + return statistics.median(slopes) if slopes else 0.0 + + +def report(rows, warm_pct, label): + skip = int(len(rows) * warm_pct / 100) + tail = rows[skip:] + print(f"== {label}: {len(rows)} samples, {int(rows[-1]['req'])} requests, {rows[-1]['t_s']:.0f} s; fit on {len(tail)} samples after {warm_pct}% warm-up") + print(f"{'series':<15}{'slope MiB/1000req':>20}{'95% interval':>28}{'theil-sen':>12}{'first MiB':>12}{'last MiB':>12}") + for name in SERIES: + if name not in tail[0]: + continue + pts = [(r["req"], r[name]) for r in tail] + if len(pts) < 8: + print(f"{name:<15} too few samples") + continue + fit = ols(pts) + if fit is None: + continue + s, lo, hi = (v * 1000 / MIB for v in fit) + zero = " zero inside" if lo <= 0 <= hi else "" + print(f"{name:<15}{s:>+20.3f}{'[%+.3f, %+.3f]' % (lo, hi):>28}{theil_sen(pts) * 1000 / MIB:>+12.3f}{pts[0][1] / MIB:>12.0f}{pts[-1][1] / MIB:>12.0f}{zero}") + + +def level(rows, name): + last = rows[len(rows) * 2 // 3:] + return statistics.median(r[name] for r in last) / MIB + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("files", nargs="*") + ap.add_argument("--warmup-pct", type=float, default=25) + ap.add_argument("--tmax", type=float, default=None) + ap.add_argument("--label", default=None) + ap.add_argument("--compare", nargs="*") + a = ap.parse_args() + if a.compare: + arms = [] + for spec in a.compare: + path, _, name = spec.partition(":") + rows = load(path, a.tmax) + arms.append((name or path, rows)) + report(rows, a.warmup_pct, name or path) + print("\nlevel after warm-up (median of the last third of each arm), MiB") + print(f"{'arm':<24}" + "".join(f"{n:>16}" for n in ["rss_anon", "malloc_in_use", "malloc_free", "malloc_arena", "rss"])) + for name, rows in arms: + print(f"{name:<24}" + "".join(f"{level(rows, n):>16.0f}" for n in ["rss_anon", "malloc_in_use", "malloc_free", "malloc_arena", "rss"])) + return + for path in a.files: + report(load(path, a.tmax), a.warmup_pct, a.label or path) + + +if __name__ == "__main__": + main() diff --git a/scripts/quality/q_lib.py b/scripts/quality/q_lib.py index 9a68cabc..4ea435b4 100644 --- a/scripts/quality/q_lib.py +++ b/scripts/quality/q_lib.py @@ -1,128 +1,129 @@ -"""Parsers and metrics of the model quality gate (docs/quality-gate.md). Offline analysis only; no runtime use. - -A *row* is one engine's output at one position of one token path: the top-k log-probabilities of the next token given the -tokens up to and including `pos`. Both engines print them in the same tab-separated form (verify.cpp `window_logprobs`): - pos target lp(target) top1 lp(top1) match lp(extra) lp(target without extra) id:lp ... (descending) -""" -import json, math, os, re, statistics - -class Row: - __slots__ = ("pos", "target", "lp_target", "topk") - def __init__(self, pos, target, lp_target, topk): - self.pos, self.target, self.lp_target, self.topk = pos, target, lp_target, topk # topk: [(id, lp)] descending - @property - def top1(self): return self.topk[0][0] - @property - def margin(self): return self.topk[0][1] - self.topk[1][1] - def lp(self, token): - for t, v in self.topk: - if t == token: return v - return None - def rank(self, token): - for i, (t, _) in enumerate(self.topk): - if t == token: return i + 1 - return None - -def parse_row(line): - f = line.rstrip("\n").split("\t") - if len(f) < 9 or not f[0].lstrip("-").isdigit(): return None - topk = [(int(a.split(":")[0]), float(a.split(":")[1])) for a in f[8:] if ":" in a] - if len(topk) < 2: return None - return Row(int(f[0]), int(f[1]), float(f[2]), topk) - -def load_orig_logpos(run_dir): - """The Original's STRATA_LOGPOS file as one {pos: Row} dict per request, in request order (a request starts when the - position does not increase).""" - segments, prev = [], None - for line in open(os.path.join(run_dir, "logpos"), errors="replace"): - row = parse_row(line) - if row is None: continue - if prev is None or row.pos <= prev: segments.append({}) - prev = row.pos - segments[-1][row.pos] = row - names = [n for n in open(os.path.join(run_dir, "reqs.txt.names")).read().split("\n") if n] - return segments, names - -def load_case(cases_dir, name): - return [int(x) for x in open(os.path.join(cases_dir, name + ".ids")).read().strip().split(",")] - -def orig_reads(run_dir, cases_dir): - """{label: (case name, request keys, {pos: Row})} for the teacher-forced read requests of an Original run; repeated labels - get a '#k' suffix. Rows of the read requests only.""" - segments, names = load_orig_logpos(run_dir) - out, seen = {}, {} - for seg, label in zip(segments, names): - if not label.startswith("read:"): continue - spec = label[5:] - case = spec.split(":")[0] - k = seen.get(spec, 0); seen[spec] = k + 1 - out[spec + ("" if k == 0 else f"#{k}")] = (case, spec.split(":")[1:], seg) - return out - -def parse_port_log(path): - """The port smoke log -> list of runs {index, pass, forced, windows:[(position, inputs, [Row])], output:[ids] or None}. - Rows are attached to the window announced by the preceding `DBG logprobs window` line.""" - runs, cur, win = [], None, None - for line in open(path, errors="replace"): - m = re.match(r"DBG corpus (\d+) pass=(\d+) begin forced=(true|false)", line) - if m: - cur = {"index": int(m[1]), "pass": int(m[2]), "forced": m[3] == "true", "windows": [], "output": None, "notes": []} - runs.append(cur); win = None; continue - if cur is None: continue - m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\] argmax_ids=\[([0-9, -]*)\]", line) - if m: - win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], []) - cur["windows"].append(win); continue - m = re.match(r"DBG corpus (\d+) output(?: pass=(\d+))? \((\d+) tokens, rounds (\d+)\): ([0-9 ]*)", line) - if m and int(m[1]) == cur["index"] and int(m[2] or 0) == cur["pass"]: - cur["output"] = [int(x) for x in m[5].split()]; continue - if line.startswith("DBG corpus") and "forced:" in line: cur["notes"].append(line.strip()); continue - row = parse_row(line) - if row is not None and win is not None and len(win[2]) < len(win[1]): - win[2].append(row) - return runs - -def valid_rows(windows, truth): - """{pos: Row} of the rows whose consumed tokens (the window's inputs up to the row) equal the token path `truth` - (the first occurrence of a position wins). A row after a rejected draft token is conditioned on text that is not on - the path and is skipped.""" - out = {} - for position, inputs, rows in windows: - for r, row in enumerate(rows): - if position + r >= len(truth) or inputs[: r + 1] != truth[position : position + r + 1]: break - out.setdefault(position + r, row) - return out - -def compare(ref, other, first_pos=0, last_pos=10**9): - """Per common position of two {pos: Row} dicts, in [first_pos, last_pos].""" - res = [] - for pos in sorted(set(ref) & set(other)): - if not first_pos <= pos <= last_pos: continue - a, b = ref[pos], other[pos] - common = [t for t, _ in a.topk if b.lp(t) is not None] - dmax = max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan")) - d1 = abs(a.topk[0][1] - b.lp(a.top1)) if b.lp(a.top1) is not None else float("nan") - res.append({"pos": pos, "dmax": dmax, "ncommon": len(common), "flip": a.top1 != b.top1, - "ref_margin": a.margin, "other_margin": b.margin, "ref_top1": a.top1, "other_top1": b.top1, - "other_rank_of_ref_top1": b.rank(a.top1), "ref_rank_of_other_top1": a.rank(b.top1), - "d_target": abs(a.lp_target - b.lp_target), "d_top1": d1}) - return res - -def quantile(values, q): - v = sorted(x for x in values if not math.isnan(x)) - if not v: return float("nan") - k = (len(v) - 1) * q; lo, hi = int(math.floor(k)), int(math.ceil(k)) - return v[lo] + (v[hi] - v[lo]) * (k - lo) - -def _qs(v): - v = [x for x in v if not math.isnan(x)] - return {"median": quantile(v, .5), "p90": quantile(v, .9), "p99": quantile(v, .99), "max": max(v, default=float("nan"))} - -def summary(rows): - """Distribution of the three per-position deviations: dmax (max over the common top-k, the tail included), d_top1 (the - reference's argmax token) and d_target (the token on the path); plus the argmax flips and the reference margin at each.""" - flips = [r for r in rows if r["flip"]] - return {"n": len(rows), "dmax": _qs([r["dmax"] for r in rows]), "d_top1": _qs([r["d_top1"] for r in rows]), - "d_target": _qs([r["d_target"] for r in rows]), "flips": len(flips), - "flip_margins": sorted(round(r["ref_margin"], 3) for r in flips), - "flip_pos": [(r.get("case"), r["pos"], round(r["ref_margin"], 3), round(r["other_margin"], 3)) for r in flips]} +"""Parsers and metrics of the model quality gate (docs/quality-gate.md). Offline analysis only; no runtime use. + +A *row* is one engine's output at one position of one token path: the top-k log-probabilities of the next token given the +tokens up to and including `pos`. Both engines print them in the same tab-separated form (verify.cpp `window_logprobs`): + pos target lp(target) top1 lp(top1) match lp(extra) lp(target without extra) id:lp ... (descending) +""" +import json, math, os, re, statistics + +class Row: + __slots__ = ("pos", "target", "lp_target", "topk") + def __init__(self, pos, target, lp_target, topk): + self.pos, self.target, self.lp_target, self.topk = pos, target, lp_target, topk # topk: [(id, lp)] descending + @property + def top1(self): return self.topk[0][0] + @property + def margin(self): return self.topk[0][1] - self.topk[1][1] + def lp(self, token): + for t, v in self.topk: + if t == token: return v + return None + def rank(self, token): + for i, (t, _) in enumerate(self.topk): + if t == token: return i + 1 + return None + +def parse_row(line): + f = line.rstrip("\n").split("\t") + if len(f) < 9 or not f[0].lstrip("-").isdigit(): return None + topk = [(int(a.split(":")[0]), float(a.split(":")[1])) for a in f[8:] if ":" in a] + if len(topk) < 2: return None + return Row(int(f[0]), int(f[1]), float(f[2]), topk) + +def load_orig_logpos(run_dir): + """The Original's STRATA_LOGPOS file as one {pos: Row} dict per request, in request order (a request starts when the + position does not increase).""" + segments, prev = [], None + for line in open(os.path.join(run_dir, "logpos"), errors="replace"): + row = parse_row(line) + if row is None: continue + if prev is None or row.pos != prev + 1: segments.append({}) + prev = row.pos + segments[-1][row.pos] = row + nf = os.path.join(run_dir, "reqs.txt.names") + names = [n for n in open(nf).read().split(chr(10)) if n] if os.path.exists(nf) else [] + return segments, names + +def load_case(cases_dir, name): + return [int(x) for x in open(os.path.join(cases_dir, name + ".ids")).read().strip().split(",")] + +def orig_reads(run_dir, cases_dir): + """{label: (case name, request keys, {pos: Row})} for the teacher-forced read requests of an Original run; repeated labels + get a '#k' suffix. Rows of the read requests only.""" + segments, names = load_orig_logpos(run_dir) + out, seen = {}, {} + for seg, label in zip(segments, names): + if not label.startswith("read:"): continue + spec = label[5:] + case = spec.split(":")[0] + k = seen.get(spec, 0); seen[spec] = k + 1 + out[spec + ("" if k == 0 else f"#{k}")] = (case, spec.split(":")[1:], seg) + return out + +def parse_port_log(path): + """The port smoke log -> list of runs {index, pass, forced, windows:[(position, inputs, [Row])], output:[ids] or None}. + Rows are attached to the window announced by the preceding `DBG logprobs window` line.""" + runs, cur, win = [], None, None + for line in open(path, errors="replace"): + m = re.match(r"DBG corpus (\d+) pass=(\d+) begin forced=(true|false)", line) + if m: + cur = {"index": int(m[1]), "pass": int(m[2]), "forced": m[3] == "true", "windows": [], "output": None, "notes": []} + runs.append(cur); win = None; continue + if cur is None: continue + m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\] argmax_ids=\[([0-9, -]*)\]", line) + if m: + win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], []) + cur["windows"].append(win); continue + m = re.match(r"DBG corpus (\d+) output(?: pass=(\d+))? \((\d+) tokens, rounds (\d+)\): ([0-9 ]*)", line) + if m and int(m[1]) == cur["index"] and int(m[2] or 0) == cur["pass"]: + cur["output"] = [int(x) for x in m[5].split()]; continue + if line.startswith("DBG corpus") and "forced:" in line: cur["notes"].append(line.strip()); continue + row = parse_row(line) + if row is not None and win is not None and len(win[2]) < len(win[1]): + win[2].append(row) + return runs + +def valid_rows(windows, truth): + """{pos: Row} of the rows whose consumed tokens (the window's inputs up to the row) equal the token path `truth` + (the first occurrence of a position wins). A row after a rejected draft token is conditioned on text that is not on + the path and is skipped.""" + out = {} + for position, inputs, rows in windows: + for r, row in enumerate(rows): + if position + r >= len(truth) or inputs[: r + 1] != truth[position : position + r + 1]: break + out.setdefault(position + r, row) + return out + +def compare(ref, other, first_pos=0, last_pos=10**9): + """Per common position of two {pos: Row} dicts, in [first_pos, last_pos].""" + res = [] + for pos in sorted(set(ref) & set(other)): + if not first_pos <= pos <= last_pos: continue + a, b = ref[pos], other[pos] + common = [t for t, _ in a.topk if b.lp(t) is not None] + dmax = max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan")) + d1 = abs(a.topk[0][1] - b.lp(a.top1)) if b.lp(a.top1) is not None else float("nan") + res.append({"pos": pos, "dmax": dmax, "ncommon": len(common), "flip": a.top1 != b.top1, + "ref_margin": a.margin, "other_margin": b.margin, "ref_top1": a.top1, "other_top1": b.top1, + "other_rank_of_ref_top1": b.rank(a.top1), "ref_rank_of_other_top1": a.rank(b.top1), + "d_target": abs(a.lp_target - b.lp_target), "d_top1": d1}) + return res + +def quantile(values, q): + v = sorted(x for x in values if not math.isnan(x)) + if not v: return float("nan") + k = (len(v) - 1) * q; lo, hi = int(math.floor(k)), int(math.ceil(k)) + return v[lo] + (v[hi] - v[lo]) * (k - lo) + +def _qs(v): + v = [x for x in v if not math.isnan(x)] + return {"median": quantile(v, .5), "p90": quantile(v, .9), "p99": quantile(v, .99), "max": max(v, default=float("nan"))} + +def summary(rows): + """Distribution of the three per-position deviations: dmax (max over the common top-k, the tail included), d_top1 (the + reference's argmax token) and d_target (the token on the path); plus the argmax flips and the reference margin at each.""" + flips = [r for r in rows if r["flip"]] + return {"n": len(rows), "dmax": _qs([r["dmax"] for r in rows]), "d_top1": _qs([r["d_top1"] for r in rows]), + "d_target": _qs([r["d_target"] for r in rows]), "flips": len(flips), + "flip_margins": sorted(round(r["ref_margin"], 3) for r in flips), + "flip_pos": [(r.get("case"), r["pos"], round(r["ref_margin"], 3), round(r["other_margin"], 3)) for r in flips]} diff --git a/scripts/quality/q_port.py b/scripts/quality/q_port.py index 8180d669..76fe079f 100644 --- a/scripts/quality/q_port.py +++ b/scripts/quality/q_port.py @@ -358,7 +358,7 @@ def retrieval_section(q, out, result): from q_lib import orig_reads run = "RET-orig-read" pf = os.path.join(q.d, "runs", "RET-port-forced", "port.log") - if run not in q.reads or not os.path.exists(pf): + if not os.path.exists(os.path.join(q.d, "runs", run, "logpos")) or not os.path.exists(pf): return import re reqs = [n for n in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if n and n != "QUIT"] @@ -380,7 +380,7 @@ def retrieval_section(q, out, result): line = [l for l in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if l.startswith("GEN 1 ")][1 if n == 100000 else 3] path = [int(x) for x in line[len("GEN 1 "):].split(",")] rows = valid_rows(p["windows"], path) - lo, hi = n - 1, len(path) - 2 + lo, hi = n, len(path) - 2 # the resumed Original request logs from the first answer row's input (position n) cmp_ = compare(o, rows, lo, hi) if not cmp_: continue