diff --git a/architecture-baseline.json b/architecture-baseline.json index ac71e524..88e794bf 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -59,7 +59,7 @@ "instant-now:leleka-igpu": 1, "instant-now:leleka-memory": 1, "instant-now:leleka-model-format": 10, - "instant-now:leleka-native-cpu-expert": 30, + "instant-now:leleka-native-cpu-expert": 27, "instant-now:leleka-npu-service": 5, "instant-now:leleka-obs": 3, "instant-now:strata-control": 22, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs index dfde79fc..b41c0086 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs @@ -209,6 +209,8 @@ pub(in crate::qwen_forward) use prefetch_off_file_exists::scatter; mod direct_parts; use direct_parts::{GroupWork, borrow_experts, compute_into_sink, group_formats, plan_expert_ids, prefetch_group}; mod cpu_expert_pool; +mod pool_layer_trace; +use pool_layer_trace::GroupTraceInfo; mod direct_tier; mod direct_tier_drop; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/cpu_expert_pool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/cpu_expert_pool.rs index 32afb59d..3f37cd30 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/cpu_expert_pool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/cpu_expert_pool.rs @@ -87,7 +87,9 @@ impl CpuExpertPool<'_> { window_trace::lap(window_trace::JOIN, clock); drop(sink_span); let record = (group.any_mapped && failure.is_none() && !plan.is_empty()).then_some(group.use_pass); - tier.finish_group(record, (group.started, plan.len())); + let entries = plan.iter().map(|j| j.pairs.len()).sum(); + let info = GroupTraceInfo { layer: rows.layer, tokens: rows.ids.len() / TOP_K, entries, wall: pool_time }; + tier.finish_group(record, (group.started, plan.len()), &info); sink_result(written, failure) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs index 9256b97d..7e1214be 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs @@ -211,14 +211,36 @@ impl DirectTier { } } + /// `LELEKA_POOL_TIMING=layers`: the per-phase thread times of the group the pool just computed, as one log line. + fn emit_layer_trace( + &mut self, + info: &GroupTraceInfo, + experts: usize, + stages: Option<[f64; leleka_native_cpu_expert::POOL_TIMING_STAGES]>, + ) { + let phases = self.pool.take_trace(); + if phases.is_empty() { + return; + } + let size = super::pool_layer_trace::PoolSize { workers: self.pool.workers(), experts }; + eprintln!("{}", super::pool_layer_trace::line((info, &size), stages, &phases)); + } + /// The pool's stage timings of the group, and the prefetch policy's measurement when the group ran over a mapped /// source. - pub(super) fn finish_group(&mut self, record: Option, group: (std::time::Instant, usize)) { - if let Some(stages) = self.pool.take_timing() { + pub(super) fn finish_group( + &mut self, + record: Option, + group: (std::time::Instant, usize), + info: &GroupTraceInfo, + ) { + let stages = self.pool.take_timing(); + if let Some(stages) = stages { for (name, ms) in leleka_native_cpu_expert::POOL_TIMING_NAMES.iter().copied().zip(stages) { super::super::original_serve_profile::add(name, ms); } } + self.emit_layer_trace(info, group.1, stages); let (started, groups) = group; if let Some(use_pass) = record.filter(|_| groups > 0) { self.prefetch.record(use_pass, started.elapsed().as_secs_f64() * 1e3 / groups as f64); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs new file mode 100644 index 00000000..442646fd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs @@ -0,0 +1,103 @@ +//! `LELEKA_POOL_TIMING=layers` (test tooling, off by default): one `leleka-serve pool-layer {json}` line per layer +//! window of the CPU expert pool. It splits the time of the pool's group into the dispatch of each phase (gate/up = +//! mode 5, down = mode 6): when the threads woke, when the last task of each ended, how long each computed, how the +//! tasks spread over the threads and how long a task took. All times are microseconds from the publication of the +//! phase; `[a,b,c,d]` is min, p50, p90, max over the threads (`task`: over the tasks). + +use leleka_native_cpu_expert::{PhaseTrace, POOL_TIMING_STAGES}; + +/// What the engine knows about the group the pool just computed. +pub(super) struct GroupTraceInfo { + pub(super) layer: usize, + pub(super) tokens: usize, + pub(super) entries: usize, + pub(super) wall: std::time::Duration, +} + +/// The pool's size and the group's expert count. +pub(super) struct PoolSize { + pub(super) workers: usize, + pub(super) experts: usize, +} + +fn quantile(sorted: &[f64], p: f64) -> f64 { + if sorted.is_empty() { + return 0.0; + } + let at = ((sorted.len() - 1) as f64 * p).round() as usize; + sorted[at] +} + +/// `[min,p50,p90,max]` of the values. +fn spread(mut v: Vec) -> String { + v.sort_by(f64::total_cmp); + format!("[{:.1},{:.1},{:.1},{:.1}]", quantile(&v, 0.0), quantile(&v, 0.5), quantile(&v, 0.9), quantile(&v, 1.0)) +} + +fn us(ns: u64) -> f64 { + ns as f64 / 1e3 +} + +fn phase_json(p: &PhaseTrace) -> String { + let wake = spread(p.threads.iter().map(|t| us(t.wake_ns)).collect()); + let last = spread(p.threads.iter().map(|t| us(t.last_ns)).collect()); + let busy = spread(p.threads.iter().map(|t| us(t.busy_ns)).collect()); + let per = spread(p.threads.iter().map(|t| f64::from(t.tasks)).collect()); + let task = spread(p.task_ns.iter().map(|&n| us(u64::from(n))).collect()); + let host = p.threads.iter().find(|t| t.host).map_or(0, |t| t.tasks); + format!( + "{{\"m\":{},\"tasks\":{},\"wall\":{:.1},\"wake\":{wake},\"last\":{last},\"busy\":{busy},\"per\":{per},\ + \"host\":{host},\"idle\":{},\"task\":{task}}}", + p.mode, + p.tasks, + us(p.wall_ns), + p.idle + ) +} + +fn stages_json(stages: Option<[f64; POOL_TIMING_STAGES]>) -> String { + let Some(s) = stages else { return "[]".to_owned() }; + let items: Vec = s.iter().map(|ms| format!("{:.1}", ms * 1e3)).collect(); + format!("[{}]", items.join(",")) +} + +/// The line for one group (`stages` are the pool's host stage times in ms, `POOL_TIMING_NAMES` order). +pub(super) fn line( + (info, size): (&GroupTraceInfo, &PoolSize), + stages: Option<[f64; POOL_TIMING_STAGES]>, + phases: &[PhaseTrace], +) -> String { + let ph: Vec = phases.iter().map(phase_json).collect(); + format!( + "leleka-serve pool-layer {{\"layer\":{},\"tok\":{},\"experts\":{},\"entries\":{},\"workers\":{},\"wall\":{:.1},\ + \"stages\":{},\"ph\":[{}]}}", + info.layer, + info.tokens, + size.experts, + info.entries, + size.workers, + info.wall.as_secs_f64() * 1e6, + stages_json(stages), + ph.join(",") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_spread_is_min_median_p90_max() { + assert_eq!(spread((1..=10).map(f64::from).collect()), "[1.0,6.0,9.0,10.0]"); + assert_eq!(spread(Vec::new()), "[0.0,0.0,0.0,0.0]"); + } + + #[test] + fn a_group_without_stages_prints_an_empty_stage_list() { + let info = GroupTraceInfo { layer: 7, tokens: 3, entries: 30, wall: std::time::Duration::from_micros(250) }; + let text = line((&info, &PoolSize { workers: 15, experts: 21 }), None, &[]); + let head = "leleka-serve pool-layer {\"layer\":7,\"tok\":3,\"experts\":21,\"entries\":30,\"workers\":15,"; + assert!(text.starts_with(head)); + assert!(text.ends_with("\"wall\":250.0,\"stages\":[],\"ph\":[]}")); + } +} diff --git a/crates/native-cpu-expert/src/ffi.rs b/crates/native-cpu-expert/src/ffi.rs index b1575645..b932f15c 100644 --- a/crates/native-cpu-expert/src/ffi.rs +++ b/crates/native-cpu-expert/src/ffi.rs @@ -11,6 +11,9 @@ impl NativePool { pub(super) fn workers(&self) -> Result { self.pool.as_ref().ok_or(Error::Closed)?.workers() } + pub(super) fn take_trace(&mut self) -> Vec { + self.pool.as_mut().map(super::rust_pool::NativePool::take_trace).unwrap_or_default() + } pub(super) fn take_timing(&mut self) -> Option<[f64; super::rust_pool::TIMING_STAGES]> { self.pool.as_mut().and_then(super::rust_pool::NativePool::take_timing) } diff --git a/crates/native-cpu-expert/src/gate_up_format.rs b/crates/native-cpu-expert/src/gate_up_format.rs index 3279ad7c..baf479fa 100644 --- a/crates/native-cpu-expert/src/gate_up_format.rs +++ b/crates/native-cpu-expert/src/gate_up_format.rs @@ -146,6 +146,10 @@ impl DirectCpuPool { pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { self.native.take_timing() } + /// The phases dispatched since the last call, with per-thread times (`LELEKA_POOL_TIMING=layers`; else empty). + pub fn take_trace(&mut self) -> Vec { + self.native.take_trace() + } /// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts, /// all of the same gate/up and down formats). Only the pairs' rows of `out` are written. pub fn compute_group( diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index e983b990..77bd16fa 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -53,6 +53,7 @@ mod rust_weight_iq; mod rust_weight_quant; pub use rust_kq::{MatrixDims, bf16_rows, bf16_rows_multi}; pub use rust_platform::advise_will_need; +pub use rust_pool::{PhaseTrace, ThreadTrace}; const H: usize = 2560; const FF: usize = 640; diff --git a/crates/native-cpu-expert/src/rust_pool.rs b/crates/native-cpu-expert/src/rust_pool.rs index e1b5e339..b5413197 100644 --- a/crates/native-cpu-expert/src/rust_pool.rs +++ b/crates/native-cpu-expert/src/rust_pool.rs @@ -63,6 +63,7 @@ struct Shared { sleep_cv: Condvar, spin: Duration, n: usize, + tr: Option, batch: UnsafeCell, act: Vec>, nact: Vec>, @@ -84,6 +85,7 @@ pub(super) struct NativePool { shared: Arc, workers: Vec>, timing: Option<[f64; TIMING_STAGES]>, + phases: Vec, } mod exec; @@ -97,4 +99,6 @@ mod stage; #[allow(unused_imports)] use shared::tasks_per_thread; mod native_pool; +mod trace; +pub use trace::{PhaseTrace, ThreadTrace}; mod native_pool_group_compute; diff --git a/crates/native-cpu-expert/src/rust_pool/native_pool.rs b/crates/native-cpu-expert/src/rust_pool/native_pool.rs index 65dbed60..2cc722d1 100644 --- a/crates/native-cpu-expert/src/rust_pool/native_pool.rs +++ b/crates/native-cpu-expert/src/rust_pool/native_pool.rs @@ -24,9 +24,11 @@ impl NativePool { } pub fn new(workers: i32) -> Result { let (stack, cores, n) = Self::plan(workers)?; - let shared = Self::new_shared(n)?; - let timing = std::env::var("LELEKA_POOL_TIMING").is_ok_and(|v| v == "1").then_some([0.0; TIMING_STAGES]); - let mut out = Self { shared, workers: Vec::new(), timing }; + // LELEKA_POOL_TIMING: `1` the host's stage times, `layers` those and the per-thread times of every phase + let mode = std::env::var("LELEKA_POOL_TIMING").unwrap_or_default(); + let shared = Self::new_shared(n, mode == "layers")?; + let timing = (mode == "1" || mode == "layers").then_some([0.0; TIMING_STAGES]); + let mut out = Self { shared, workers: Vec::new(), timing, phases: Vec::new() }; out.workers.try_reserve_exact(n).map_err(|_| Error::Allocation)?; for i in 0..n { let core = cores.get(i).copied().unwrap_or(-1); @@ -34,7 +36,7 @@ impl NativePool { } Ok(out) } - fn new_shared(n: usize) -> Result> { + fn new_shared(n: usize, traced: bool) -> Result> { let spin = std::env::var("STRATA_POOL_SPIN_US") .map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64)) .unwrap_or(Duration::from_millis(20)); @@ -49,6 +51,7 @@ impl NativePool { sleep_cv: Condvar::new(), spin, n, + tr: traced.then(|| trace::TraceState::new(n)), batch: UnsafeCell::new(Self::empty_batch()?), act: allocated(MAX_JOBS)?, nact: allocated(MAX_JOBS)?, @@ -73,7 +76,7 @@ impl NativePool { thread::Builder::new() .name(format!("strata-expert-{i}")) .stack_size(stack) - .spawn(move || shared.worker(core)) + .spawn(move || shared.worker(core, i)) .map_err(|_| Error::Allocation) } pub fn workers(&self) -> Result { @@ -96,9 +99,12 @@ impl NativePool { lap(1); let (e, tasks) = self.publish_phase(mode, rows); lap(2); - self.shared.drain(e); + self.shared.drain(e, self.shared.n); lap(3); self.shared.wait_done(tasks); + if let Some(tr) = &self.shared.tr { + self.phases.push(tr.snapshot(mode, tasks)); + } lap(4); self.shared.wait_parked(); lap(5); @@ -122,11 +128,18 @@ impl NativePool { b.tasks = tasks; } self.shared.done.0.store(0, Ordering::Relaxed); + if let Some(tr) = &self.shared.tr { + tr.begin(); + } let e = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1); self.shared.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release); self.shared.publish(); (e, tasks) } + /// The phases dispatched since the last call (`LELEKA_POOL_TIMING=layers`; empty when off). + pub fn take_trace(&mut self) -> Vec { + std::mem::take(&mut self.phases) + } /// The summed stage times since the last call (see `TIMING_STAGES`), zeroed; `None` when timing is off. pub fn take_timing(&mut self) -> Option<[f64; TIMING_STAGES]> { self.timing.as_mut().map(|t| std::mem::replace(t, [0.0; TIMING_STAGES])) diff --git a/crates/native-cpu-expert/src/rust_pool/shared.rs b/crates/native-cpu-expert/src/rust_pool/shared.rs index 9fdeb4d7..b88e2360 100644 --- a/crates/native-cpu-expert/src/rust_pool/shared.rs +++ b/crates/native-cpu-expert/src/rust_pool/shared.rs @@ -3,6 +3,11 @@ #[allow(unused_imports)] use super::*; +/// The clock of the park/stall deadlines (one site for the three waits). +fn stall_clock() -> Instant { + Instant::now() +} + impl Shared { pub(super) fn publish(&self) { self.epoch.0.fetch_add(1, Ordering::SeqCst); @@ -28,17 +33,22 @@ impl Shared { } } } - pub(super) fn drain(&self, epoch: u32) { + /// Drain the phase of `epoch`; `slot` names this thread in the trace (workers 0..n, the host n). + pub(super) fn drain(&self, epoch: u32, slot: usize) { while let Some(i) = self.claim(epoch) { + let t0 = self.tr.as_ref().map(trace::TraceState::clock); // SAFETY: admission covers whole immutable blobs and output rows. The claim // uniquely owns [g0,g1); batch remains alive through done+parked barriers. unsafe { self.execute(i); } + if let (Some(tr), Some(t0)) = (&self.tr, t0) { + tr.task_done(slot, i, t0); + } self.done.0.fetch_add(1, Ordering::Release); } } - pub(super) fn worker(&self, core: i32) { + pub(super) fn worker(&self, core: i32, slot: usize) { super::super::rust_platform::pin(core); let mut seen = 0u32; self.parked.0.fetch_add(1, Ordering::AcqRel); @@ -48,13 +58,13 @@ impl Shared { } seen = self.epoch.0.load(Ordering::Acquire); self.parked.0.fetch_sub(1, Ordering::AcqRel); - self.drain(seen); + self.drain(seen, slot); self.parked.0.fetch_add(1, Ordering::AcqRel); } } /// Spin (then sleep) until the epoch moves past `seen`; false when the pool is stopping. fn await_epoch(&self, seen: u32) -> bool { - let parked_at = Instant::now(); + let parked_at = stall_clock(); let mut spins = 0u32; while self.epoch.0.load(Ordering::Acquire) == seen { if self.stop.0.load(Ordering::Relaxed) { @@ -79,7 +89,7 @@ impl Shared { } pub(super) fn wait_parked(&self) { let mut spins = 0u32; - let mut t = Instant::now(); + let mut t = stall_clock(); while self.parked.0.load(Ordering::Acquire) != self.n as u32 { std::hint::spin_loop(); spins = spins.wrapping_add(1); @@ -87,7 +97,7 @@ impl Shared { continue; } if spins == 1024 { - t = Instant::now(); + t = stall_clock(); } else if t.elapsed() > Duration::from_secs(60) { eprintln!("strata: the CPU expert pool stalled waiting for workers to park"); std::process::abort(); @@ -97,7 +107,7 @@ impl Shared { pub(super) fn wait_done(&self, n: usize) { let mut spins = 0u32; let mut seen = 0u32; - let mut t = Instant::now(); + let mut t = stall_clock(); loop { let d = self.done.0.load(Ordering::Acquire); if d >= n as u32 { @@ -109,7 +119,7 @@ impl Shared { continue; } if spins == 1024 || d != seen { - t = Instant::now(); + t = stall_clock(); seen = d; } else if t.elapsed() > Duration::from_secs(60) { eprintln!("strata: the CPU expert pool stalled waiting for jobs"); diff --git a/crates/native-cpu-expert/src/rust_pool/trace.rs b/crates/native-cpu-expert/src/rust_pool/trace.rs new file mode 100644 index 00000000..ecab33e0 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_pool/trace.rs @@ -0,0 +1,146 @@ +//! `LELEKA_POOL_TIMING=layers`: per-phase thread timers of the CPU expert pool (test tooling; off by default, the +//! pool then reads no clock). Every thread that drains a phase (the workers and the host) records when it claimed +//! its first task, when it finished its last one, how long it computed and how many tasks it took; the host +//! snapshots the phase when all tasks are done. Times are nanoseconds from the publication of the phase. + +use super::*; + +/// Tasks of one phase never exceed 3 per thread of 16 threads; the table keeps a margin. +const TASK_TABLE: usize = 256; + +#[derive(Default)] +struct Slot { + first: AtomicU64, + last: AtomicU64, + busy: AtomicU64, + tasks: AtomicU32, +} + +/// What one drain thread did in a phase. +#[derive(Clone, Copy, Debug)] +pub struct ThreadTrace { + /// The thread is the host (the caller of `compute_group`), not a worker. + pub host: bool, + /// Publication to its first claimed task. + pub wake_ns: u64, + /// Publication to the end of its last task. + pub last_ns: u64, + /// Time spent computing tasks. + pub busy_ns: u64, + pub tasks: u32, +} + +/// One dispatched phase (mode 5 gate/up, mode 6 down). +#[derive(Clone, Debug)] +pub struct PhaseTrace { + pub mode: u32, + pub tasks: usize, + /// Publication to the last task done. + pub wall_ns: u64, + /// Threads that took at least one task. + pub threads: Vec, + /// Threads (workers and host) that took none. + pub idle: usize, + /// Duration of every task, in task order. + pub task_ns: Vec, +} + +pub(super) struct TraceState { + start: Instant, + slots: Vec, + task_ns: Vec, + published: AtomicU64, +} + +impl TraceState { + /// `n` workers and the host. + pub(super) fn new(n: usize) -> Self { + Self { + start: Instant::now(), + slots: (0..=n).map(|_| Slot::default()).collect(), + task_ns: (0..TASK_TABLE).map(|_| AtomicU32::new(0)).collect(), + published: AtomicU64::new(0), + } + } + fn now_ns(&self) -> u64 { + self.start.elapsed().as_nanos() as u64 + } + /// Host, workers parked: clear the slots and stamp the publication. + pub(super) fn begin(&self) { + for s in &self.slots { + s.tasks.store(0, Ordering::Relaxed); + s.busy.store(0, Ordering::Relaxed); + } + self.published.store(self.now_ns(), Ordering::Release); + } + /// The clock before a task (only called when tracing). + pub(super) fn clock(&self) -> u64 { + self.now_ns() + } + /// Thread `slot` finished task `task`, which began at `t0`. + pub(super) fn task_done(&self, slot: usize, task: usize, t0: u64) { + let t1 = self.now_ns(); + let s = &self.slots[slot]; + if s.tasks.load(Ordering::Relaxed) == 0 { + s.first.store(t0, Ordering::Relaxed); + } + s.tasks.fetch_add(1, Ordering::Relaxed); + s.busy.fetch_add(t1 - t0, Ordering::Relaxed); + s.last.store(t1, Ordering::Relaxed); + self.task_ns[task % TASK_TABLE].store((t1 - t0).min(u32::MAX as u64) as u32, Ordering::Relaxed); + } + /// Host, after `wait_done`: every task's record is visible (the done counter orders it). + pub(super) fn snapshot(&self, mode: u32, tasks: usize) -> PhaseTrace { + let published = self.published.load(Ordering::Acquire); + let host_slot = self.slots.len() - 1; + let mut threads = Vec::new(); + for (i, s) in self.slots.iter().enumerate().filter(|(_, s)| s.tasks.load(Ordering::Relaxed) > 0) { + threads.push(ThreadTrace { + host: i == host_slot, + wake_ns: s.first.load(Ordering::Relaxed).saturating_sub(published), + last_ns: s.last.load(Ordering::Relaxed).saturating_sub(published), + busy_ns: s.busy.load(Ordering::Relaxed), + tasks: s.tasks.load(Ordering::Relaxed), + }); + } + PhaseTrace { + mode, + tasks, + wall_ns: self.now_ns().saturating_sub(published), + idle: self.slots.len() - threads.len(), + threads, + task_ns: (0..tasks.min(TASK_TABLE)).map(|i| self.task_ns[i].load(Ordering::Relaxed)).collect(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_snapshot_names_the_threads_that_took_tasks_and_counts_the_idle_ones() { + let tr = TraceState::new(2); + tr.begin(); + let t0 = tr.clock(); + tr.task_done(0, 0, t0); + tr.task_done(2, 1, t0); + tr.task_done(2, 2, t0); + let p = tr.snapshot(5, 3); + assert_eq!((p.mode, p.tasks, p.threads.len(), p.idle), (5, 3, 2, 1)); + assert!(!p.threads[0].host && p.threads[1].host); + assert_eq!((p.threads[0].tasks, p.threads[1].tasks), (1, 2)); + assert_eq!(p.task_ns.len(), 3); + assert!(p.threads.iter().all(|t| t.last_ns >= t.busy_ns.min(t.last_ns))); + } + + #[test] + fn begin_clears_the_previous_phase() { + let tr = TraceState::new(1); + tr.begin(); + tr.task_done(0, 0, tr.clock()); + tr.begin(); + let p = tr.snapshot(6, 0); + assert_eq!((p.threads.len(), p.idle), (0, 2)); + } +} diff --git a/scripts/e2e/codex/prefill/pool_layer_report.py b/scripts/e2e/codex/prefill/pool_layer_report.py new file mode 100644 index 00000000..d8d8a1a3 --- /dev/null +++ b/scripts/e2e/codex/prefill/pool_layer_report.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Summary of the `leleka-serve pool-layer` lines of an engine log (offline analysis, stdlib only; never part of serving). + + pool_layer_report.py ENGINE_LOG [--skip N] [--split 16] [--tokens 1,2,3,4] + +The engine writes one line per layer window of the CPU expert pool when it runs with `LELEKA_POOL_TIMING=layers` +(`pool_layer_trace.rs`). Per token count T and layer band (layers < SPLIT, layers >= SPLIT) this prints the percentiles of +the group wall (the pool's dispatch as the engine saw it) and, for each phase (m5 gate/up, m6 down), the percentiles of: + wall publication to the last task done + wake the slowest thread's publication-to-first-task (a thread that was not parked in its spin is late) + last the last thread's end of work; "tail" = last - median thread's last (a straggler) + busy median thread's compute time; task = p50 / p90 / max of single tasks + idle threads that took no task, host = tasks the host took itself +and the median host stage split of the group (`POOL_TIMING_NAMES`, microseconds). The first SKIP lines are dropped (warm-up). +""" +import json +import sys + +STAGES = ["pre", "gu_park0", "gu_publish", "gu_drain", "gu_wait_done", "gu_park1", "requant", "dn_park0", "dn_publish", + "dn_drain", "dn_wait_done", "dn_park1", "post"] + + +def q(values, p): + if not values: + return 0.0 + v = sorted(values) + return v[min(len(v) - 1, int(round((len(v) - 1) * p)))] + + +def pct(values): + return "%6.1f %6.1f %6.1f" % (q(values, 0.5), q(values, 0.75), q(values, 0.9)) + + +def load(path, skip): + rows = [] + for line in open(path, errors="replace"): + i = line.find("leleka-serve pool-layer ") + if i >= 0: + try: + rows.append(json.loads(line[i + len("leleka-serve pool-layer "):])) + except ValueError: + pass + return rows[skip:] + + +def phase_rows(group, mode): + return [p for g in group for p in g["ph"] if p["m"] == mode] + + +def report_phase(group, mode): + ph = phase_rows(group, mode) + if not ph: + return + tail = [p["last"][3] - p["last"][1] for p in ph] + print(" m%d wall p50/p75/p90 %s" % (mode, pct([p["wall"] for p in ph]))) + print(" wake max p50/p75/p90 %s" % pct([p["wake"][3] for p in ph])) + print(" last max p50/p75/p90 %s tail(last-p50 thread) %s" % (pct([p["last"][3] for p in ph]), pct(tail))) + print(" busy p50 p50/p75/p90 %s task p50/p90/max us %.1f/%.1f/%.1f" % ( + pct([p["busy"][1] for p in ph]), q([p["task"][1] for p in ph], 0.5), q([p["task"][2] for p in ph], 0.5), + q([p["task"][3] for p in ph], 0.5))) + print(" tasks %d idle threads p50 %d host tasks p50 %d" % ( + ph[0]["tasks"], q([p["idle"] for p in ph], 0.5), q([p["host"] for p in ph], 0.5))) + + +def report_band(rows, label): + if not rows: + return + print(" %s n=%d experts p50 %d entries p50 %d" % ( + label, len(rows), q([g["experts"] for g in rows], 0.5), q([g["entries"] for g in rows], 0.5))) + print(" group wall p50/p75/p90 %s us" % pct([g["wall"] for g in rows])) + for mode in (5, 6): + report_phase(rows, mode) + st = [g["stages"] for g in rows if len(g["stages"]) == len(STAGES)] + if st: + print(" stage p50 us: " + " ".join("%s %.1f" % (n, q([s[i] for s in st], 0.5)) for i, n in enumerate(STAGES))) + + +def main(): + args = sys.argv[1:] + if not args: + print(__doc__) + return 2 + skip = int(args[args.index("--skip") + 1]) if "--skip" in args else 0 + split = int(args[args.index("--split") + 1]) if "--split" in args else 16 + tokens = [int(x) for x in args[args.index("--tokens") + 1].split(",")] if "--tokens" in args else [1, 2, 3, 4] + rows = load(args[0], skip) + print("%s: %d pool-layer lines (after skipping %d); workers %s" % ( + args[0], len(rows), skip, sorted({g["workers"] for g in rows}))) + for t in tokens: + sel = [g for g in rows if g["tok"] == t] + print("T=%d groups %d" % (t, len(sel))) + report_band([g for g in sel if g["layer"] < split], "layers 0-%d" % (split - 1)) + report_band([g for g in sel if g["layer"] >= split], "layers %d-47" % split) + return 0 + + +if __name__ == "__main__": + sys.exit(main())