From a97b08b949d6cf27b3403967cbcc9ef039c1b981 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 12:37:40 +0200 Subject: [PATCH 1/7] diag(serve): time the window's host work and the CPU pool phases under LELEKA_BRINGUP_TRACE One DBG window line per verifier window: PLE/ledger setup, sampling setup, the verifier run, the pool callbacks (GPU split + PCIe spans, plan, prepare/copy, start, join, re-validate, scatter) and the remaining GPU wait. The smoke corpus also prints the output ids of every repeat pass. Co-Authored-By: Claude Opus 5.5 --- .../src/backend_original_serve_smoke.rs | 2 + .../src/qwen_forward/original_serve_host.rs | 38 +++++++++++-- .../src/qwen_forward/original_serve_pool.rs | 53 +++++++++++++++++++ .../qwen_forward/original_serve_residency.rs | 2 + 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/crates/leleka-runtime/src/backend_original_serve_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_smoke.rs index b774a212..bc3462ad 100644 --- a/crates/leleka-runtime/src/backend_original_serve_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_smoke.rs @@ -211,6 +211,8 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { Ok(outcome) => { if pass == 0 { eprintln!("DBG corpus {index} output ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::>().join(" ")); + } else { + eprintln!("DBG corpus {index} output pass={pass} ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::>().join(" ")); } let ttft = first.unwrap_or(total); let decode_s = (total - ttft).as_secs_f64(); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs index f259ae46..30a51902 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs @@ -274,6 +274,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { where R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, { + let window_clock = super::original_serve_pool::window_trace::now(); + let _ = super::original_serve_pool::window_trace::take(); let session_position = self.position()?; self.ledger.begin_window(position, inputs, consumed, session_position)?; let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; @@ -284,6 +286,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { } else { None }; + let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3); + let mut verifier_ms = 0.0f64; let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled()); let mut pool_error: Option = None; let mut driver_failure: Option = None; @@ -300,13 +304,23 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { enabled, || if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) }, |sampling| { - verifier + let verifier_clock = super::original_serve_pool::window_trace::now(); + let ran = verifier .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { - pool.run_group(rows, sink, copy).map_err(|error| { + let group_clock = super::original_serve_pool::window_trace::now(); + let ran = pool.run_group(rows, sink, copy).map_err(|error| { pool_error = Some(error); leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") - }) - }) + }); + if let Some(c) = group_clock { + super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); + } + ran + }); + if let Some(c) = verifier_clock { + verifier_ms = c.elapsed().as_secs_f64() * 1e3; + } + ran .map_err(|error| { let failure = ServeFailure::from(error); let class = failure.error; @@ -315,6 +329,22 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { }) }, ); + if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { + let total = c.elapsed().as_secs_f64() * 1e3; + let sums = super::original_serve_pool::window_trace::take(); + let parts: Vec = super::original_serve_pool::window_trace::NAMES + .iter() + .zip(sums) + .map(|(name, v)| format!("{name}={v:.2}")) + .collect(); + eprintln!( + "DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", + inputs.len(), + total - ple_ms - verifier_ms, + verifier_ms - sums[super::original_serve_pool::window_trace::POOL], + parts.join(" ") + ); + } match result { Ok(window) => { self.window_origin = Some(origin); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index ea8f8241..7c5e2512 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -28,6 +28,50 @@ const EXPERTS: i32 = 512; const JOBS_PER_BATCH: usize = 12; const BATCH_ALLOWANCE: usize = 48 << 20; +/// Bring-up timing of the window's host work (`LELEKA_BRINGUP_TRACE` only): per-window sums in ms, printed +/// and reset by the host after each window. Remove together with the other DBG lines. +pub(in crate::qwen_forward) mod window_trace { + use std::cell::Cell; + use std::time::Instant; + pub(in crate::qwen_forward) const NAMES: [&str; 10] = + ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries"]; + pub(in crate::qwen_forward) const POOL: usize = 0; + pub(in crate::qwen_forward) const GPU_SPLIT: usize = 1; + pub(in crate::qwen_forward) const PLAN: usize = 2; + pub(in crate::qwen_forward) const PREPARE: usize = 3; + pub(in crate::qwen_forward) const START: usize = 4; + pub(in crate::qwen_forward) const JOIN: usize = 5; + pub(in crate::qwen_forward) const VALIDATE: usize = 6; + pub(in crate::qwen_forward) const SCATTER: usize = 7; + pub(in crate::qwen_forward) const EXPERTS: usize = 8; + pub(in crate::qwen_forward) const ENTRIES: usize = 9; + thread_local! { static SUMS: Cell<[f64; 10]> = const { Cell::new([0.0; 10]) }; } + /// A clock only when tracing. + pub(in crate::qwen_forward) fn now() -> Option { + crate::bringup_trace_enabled().then(Instant::now) + } + /// Add the time since `from` to `slot` and restart the clock. + pub(in crate::qwen_forward) fn lap(slot: usize, from: &mut Option) { + if let Some(at) = from { + let next = Instant::now(); + add(slot, (next - *at).as_secs_f64() * 1e3); + *at = next; + } + } + pub(in crate::qwen_forward) fn add(slot: usize, value: f64) { + if crate::bringup_trace_enabled() { + SUMS.with(|s| { + let mut v = s.get(); + v[slot] += value; + s.set(v); + }); + } + } + pub(in crate::qwen_forward) fn take() -> [f64; 10] { + SUMS.with(|s| s.replace([0.0; 10])) + } +} + /// The expert tier of a window group. pub(in crate::qwen_forward) trait OriginalServePool<'ctx> { /// Complete every routed `(row, slot)` of this group into `sink` before returning; an error leaves @@ -160,7 +204,11 @@ impl CpuExpertPool<'_> { } let binding = self.binding; let layer = rows.layer as u32; + let mut clock = window_trace::now(); let plan = plan_experts_where(rows.ids, count, include)?; + window_trace::lap(window_trace::PLAN, &mut clock); + window_trace::add(window_trace::EXPERTS, plan.len() as f64); + window_trace::add(window_trace::ENTRIES, plan.iter().map(|j| j.pairs.len()).sum::() as f64); // Every batch is prepared, run and joined before the next; results are held until the whole // group is complete so the mapped destination is written in one bounded pass. let mut results: Vec<(usize, Box<[f32]>)> = Vec::new(); @@ -185,8 +233,11 @@ impl CpuExpertPool<'_> { })?; jobs.push(prepared); } + window_trace::lap(window_trace::PREPARE, &mut clock); let pending = self.cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?; + window_trace::lap(window_trace::START, &mut clock); let completed = pending.join().map_err(runtime_error)?; + window_trace::lap(window_trace::JOIN, &mut clock); if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } @@ -210,6 +261,7 @@ impl CpuExpertPool<'_> { })?; results.push((batch_index * JOBS_PER_BATCH + k, done.into_values())); } + window_trace::lap(window_trace::VALIDATE, &mut clock); } let mut failure = None; let written = sink.with_output(|out| { @@ -230,6 +282,7 @@ impl CpuExpertPool<'_> { } Ok(()) }); + window_trace::lap(window_trace::SCATTER, &mut clock); match (written, failure) { (Ok(()), None) => Ok(()), (_, Some(error)) => Err(error), diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 335dd696..52301863 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -335,6 +335,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { if layer >= LAYERS || rows.ids.is_empty() || rows.ids.len() % TOP_K != 0 { return Err(Error::InvalidDimension); } + let mut clock = super::original_serve_pool::window_trace::now(); if !self.state.usage.is_empty() { for &e in rows.ids { if (0..EXPERTS as i32).contains(&e) { @@ -368,6 +369,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { _ => stats.cpu_entries += 1, } } + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); self.cpu.run_entries(rows, sink, Some(&include)) } fn apply_pending(&mut self) -> Result<()> { From ae2cbf454fc53f5e250a270fd81f0dd37d344c88 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 12:48:27 +0200 Subject: [PATCH 2/7] perf(cpu-expert): borrowed single-dispatch group path (DirectCpuPool) The native pool computes a whole layer group straight from borrowed gate/up/down matrices into the caller's output rows: the caller's thread publishes the group and drains beside the workers (pool.cpp host_works_), every token is quantized once (expert_source.cpp act_multi), and every borrow ends when compute_group returns (a caught panic stops and joins the pool first). Jobs now carry the three role pointers instead of one blob; the owned PreparedJob path points them into its blob, so its kernels read the same row bytes as before. tests/borrowed_group_parity.rs: the borrowed path is bit-identical to the owned batches-of-12 path on all 10 gate/up x down format pairs (120 synthetic groups, 1..8 rows, shared experts, partial CPU masks), and refuses bad extents, overlapping or out-of-range destinations and non-finite inputs without writing. Co-Authored-By: Claude Opus 5.5 --- crates/native-cpu-expert/src/ffi.rs | 9 + crates/native-cpu-expert/src/lib.rs | 33 ++ crates/native-cpu-expert/src/rust_pool.rs | 66 +++- .../tests/borrowed_group_parity.rs | 291 ++++++++++++++++++ 4 files changed, 388 insertions(+), 11 deletions(-) create mode 100644 crates/native-cpu-expert/tests/borrowed_group_parity.rs diff --git a/crates/native-cpu-expert/src/ffi.rs b/crates/native-cpu-expert/src/ffi.rs index 50af1300..42d62014 100644 --- a/crates/native-cpu-expert/src/ffi.rs +++ b/crates/native-cpu-expert/src/ffi.rs @@ -5,6 +5,15 @@ pub(super) struct NativePool {pool:Option} impl NativePool { pub(super) fn new(workers:i32)->Result{Ok(Self{pool:Some(super::rust_pool::NativePool::new(workers)?)})} pub(super) fn workers(&self)->Result{self.pool.as_ref().ok_or(Error::Closed)?.workers()} + /// A caught panic drops (stops and joins) the native pool before returning, so no worker can still + /// touch the borrowed group afterwards; the pool is then closed. + pub(super) fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> { + let pool=self.pool.as_mut().ok_or(Error::Closed)?; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_borrowed(gu,down,group,out))) { + Ok(result)=>result, + Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} + } + } pub(super) fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> { let pool=self.pool.as_mut().ok_or(Error::Closed)?; match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_batch(jobs))) { diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index e62db5a6..2396192d 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -106,6 +106,39 @@ impl PreparedJob { .ok_or(Error::BudgetExceeded) } } +/// One routed expert of a borrowed group: its three encoded matrices in place (no copy) and the +/// `(token, slot)` pairs that selected it, in the order its rows are computed. +#[derive(Clone, Copy)] +pub struct BorrowedExpert<'a> { pub gate: &'a [u8], pub up: &'a [u8], pub down: &'a [u8], pub pairs: &'a [(usize, usize)] } +/// A whole layer group: `tokens` are its activation rows (`rows * 2560` floats), each pair's result goes +/// to output row `token * stride + slot`. +#[derive(Clone, Copy)] +pub struct BorrowedGroup<'a> { pub tokens: &'a [f32], pub experts: &'a [BorrowedExpert<'a>], pub stride: usize } +/// Output rows a borrowed group may address (8 rows x top-10 is 80). +pub const MAX_OUT_ROWS: usize = 128; + +/// Actor-owned synchronous pool for borrowed groups: the calling thread publishes the group and drains +/// beside the workers (pool.cpp `host_works_`), so nothing crosses a thread boundary by value and every +/// borrow ends when `compute_group` returns. The encoded bytes are the caller's admitted matrices: this +/// crate checks extents, pair bounds, disjoint destinations and finite inputs/outputs, never the source. +pub struct DirectCpuPool { native: ffi::NativePool, workers: usize, failed: bool, _actor: PhantomData> } +impl DirectCpuPool { + pub fn new(workers: i32) -> Result { + let native = ffi::NativePool::new(workers)?; + let workers = native.workers()?; + Ok(Self { native, workers, failed: false, _actor: PhantomData }) + } + pub fn workers(&self) -> usize { self.workers } + /// 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(&mut self, gu: GateUpFormat, down: DownFormat, group: &BorrowedGroup<'_>, out: &mut [f32]) -> Result<()> { + if self.failed { return Err(Error::Closed); } + let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out); + if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } + result + } +} + pub struct CompletedJob { values: Box<[f32]> } impl CompletedJob { pub fn into_values(self) -> Box<[f32]> { self.values } } diff --git a/crates/native-cpu-expert/src/rust_pool.rs b/crates/native-cpu-expert/src/rust_pool.rs index 626791dc..f4971de3 100644 --- a/crates/native-cpu-expert/src/rust_pool.rs +++ b/crates/native-cpu-expert/src/rust_pool.rs @@ -10,11 +10,11 @@ impl Default for NativeAct{fn default()->Self{Self{q:[Q8K::default();10],padding #[repr(C,align(64))]struct Scratch{a1:ActQ,a2:ActQ,ff:[f32;FF]} impl Default for Scratch{fn default()->Self{Self{a1:ActQ::default(),a2:ActQ::default(),ff:[0.0;FF]}}} #[repr(C)] -#[derive(Clone,Copy)]struct Job{blob:*const u8,rows:i32,act:[*const ActQ;MAX_ROWS],output:[*mut f32;MAX_ROWS],nact:[*const u8;MAX_ROWS]} -impl Default for Job{fn default()->Self{Self{blob:std::ptr::null(),rows:0,act:[std::ptr::null();MAX_ROWS],output:[std::ptr::null_mut();MAX_ROWS],nact:[std::ptr::null();MAX_ROWS]}}} +#[derive(Clone,Copy)]struct Job{gate:*const u8,up:*const u8,down:*const u8,rows:i32,act:[*const ActQ;MAX_ROWS],output:[*mut f32;MAX_ROWS],nact:[*const u8;MAX_ROWS]} +impl Default for Job{fn default()->Self{Self{gate:std::ptr::null(),up:std::ptr::null(),down:std::ptr::null(),rows:0,act:[std::ptr::null();MAX_ROWS],output:[std::ptr::null_mut();MAX_ROWS],nact:[std::ptr::null();MAX_ROWS]}}} #[repr(C,align(64))]struct SingleSplit{ff:[f32;FF],a2:ActQ} impl Default for SingleSplit{fn default()->Self{Self{ff:[0.0;FF],a2:ActQ::default()}}} -const _: ()=assert!(std::mem::size_of::()==208); +const _: ()=assert!(std::mem::size_of::()==224); const _: ()=assert!(std::mem::size_of::()==9728); const _: ()=assert!(std::mem::size_of::()==6144); struct Batch{jobs:[Job;MAX_JOBS],format:NativeFmt,count:usize,mode:u32,rows:usize,tasks:usize} @@ -22,6 +22,8 @@ struct Shared { head:Line,done:Line,parked:Line,epoch:Line,stop:Line,sleepers:Line, sleep_mu:Mutex<()>,sleep_cv:Condvar,spin:Duration,n:usize, batch:UnsafeCell,act:Vec>,nact:Vec>,split:Vec>, + // Borrowed groups quantize every token once (expert_source.cpp act_multi/nact_multi), not once per job row. + tok_act:Vec>,tok_nact:Vec>, // Keep the original per-worker scratch reservation even though native phases // require only split storage; it remains owned until all worker joins complete. _scratch:Vec,_single_split:Vec, @@ -43,16 +45,16 @@ impl Shared { }} unsafe fn execute(&self,i:usize){unsafe { let b=&*self.batch.get();let per=if b.mode==5{FF}else{H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks; - while at()).q.as_slice();MAX_ROWS];for t in 0..nr{yy[t]=(&*j.nact[t].cast::()).q.as_slice();}let d=dispatch();if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq512{super::rust_iq::dot_multi512(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi512(f.gu,ur,&yy[..nr],&mut u[..nr]);}else if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq256{super::rust_iq::dot_multi256(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi256(f.gu,ur,&yy[..nr],&mut u[..nr]);}else{for t in 0..nr{g[t]=super::rust_iq::dot_single(f.gu,gr,yy[t]);u[t]=super::rust_iq::dot_single(f.gu,ur,yy[t]);}}} let dst=std::ptr::addr_of_mut!((*slot).ff).cast::();for t in 0..nr{dst.add(t*FF+r).write(silu(g[t],u[t]));} } } else { - for r in r0..r1{let row=&blob[f.down_off+r*f.down_row..f.down_off+(r+1)*f.down_row]; + for r in r0..r1{let row=&down[r*f.down_row..(r+1)*f.down_row]; if f.down==42{let base=std::ptr::addr_of!((*slot).a2).cast::();let mut aa=[&*base;MAX_ROWS];for t in 0..nr{aa[t]=&*base.add(t);}if dispatch().avx512{super::rust_q2::dot512(row,&aa[..nr],&mut g[..nr]);}else{super::rust_q2::dot256(row,&aa[..nr],&mut g[..nr]);}} else{let base=std::ptr::addr_of!((*slot).hq).cast::();let empty:&[super::rust_types::Q8Zero]=&[];let mut yy=[empty;MAX_ROWS];for t in 0..nr{yy[t]=&(*base.add(t)).q;}let d=dispatch();let single=(nr as i32),workers:VecResult{if !(0..=15).contains(&workers){return Err(Error::Shape);}let stack=super::rust_platform::stack_size()?;if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);}let cores=super::rust_platform::cores(true);if workers==0&&cores.len()>15{return Err(Error::Unsupported);}let n=if workers>0{workers as usize}else{cores.len().max(1)}; let spin=std::env::var("STRATA_POOL_SPIN_US").map(|s|Duration::from_micros(super::rust_simd::atoi(&s).max(0)as u64)).unwrap_or(Duration::from_millis(20)); - let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs:[Job::default();MAX_JOBS],format:NativeFmt::new(18,42)?,count:0,mode:0,rows:0,tasks:1}),act:allocated(MAX_JOBS)?,nact:allocated(MAX_JOBS)?,split:allocated(MAX_JOBS)?,_scratch:allocated(n+1)?,_single_split:allocated(16)?}); + let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs:[Job::default();MAX_JOBS],format:NativeFmt::new(18,42)?,count:0,mode:0,rows:0,tasks:1}),act:allocated(MAX_JOBS)?,nact:allocated(MAX_JOBS)?,split:allocated(MAX_JOBS)?,tok_act:allocated(1)?,tok_nact:allocated(1)?,_scratch:allocated(n+1)?,_single_split:allocated(16)?}); let mut out=Self{shared,workers:Vec::new()};out.workers.try_reserve_exact(n).map_err(|_|Error::Allocation)?;for i in 0..n{let shared=Arc::clone(&out.shared);let core=cores.get(i).copied().unwrap_or(-1);out.workers.push(thread::Builder::new().name(format!("strata-expert-{i}")).stack_size(stack).spawn(move||shared.worker(core)).map_err(|_|Error::Allocation)?);}Ok(out) } pub fn workers(&self)->Result{Ok(self.workers.len())} @@ -86,11 +88,53 @@ impl NativePool { self.shared.wait_parked(); // SAFETY: all workers parked; jobs remain exclusively borrowed until both // phases finish and workers park again. NativePool::Drop joins before owners. - unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=jobs.len();for (e,j) in jobs.iter_mut().enumerate(){b.jobs[e]=Job{blob:j.blob.as_ptr(),rows:j.rows as i32,..Job::default()};for t in 0..j.rows{let x=&j.input[t*H..(t+1)*H];b.jobs[e].output[t]=j.output.as_mut_ptr().add(t*H);b.jobs[e].act[t]=(*self.shared.act[e].get()).as_ptr().add(t);b.jobs[e].nact[t]=(*self.shared.nact[e].get()).as_ptr().add(t).cast();let ptr=(*self.shared.act[e].get()).as_mut_ptr().add(t);if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut*ptr);}else{super::rust_quant::q8_one_avx2(x,&mut*ptr);}}else{let ptr=(*self.shared.nact[e].get()).as_mut_ptr().add(t);super::rust_quant::q8_k(x,&mut(*ptr).q);}}}} - self.phase(5,jobs.len()*FF); - unsafe {for (e,j) in jobs.iter().enumerate(){let s=&mut*self.shared.split[e].get();for t in 0..j.rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}} - self.phase(6,jobs.len()*H); + unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=jobs.len();for (e,j) in jobs.iter_mut().enumerate(){let p=j.blob.as_ptr();b.jobs[e]=Job{gate:p,up:p.add(f.up_off),down:p.add(f.down_off),rows:j.rows as i32,..Job::default()};for t in 0..j.rows{let x=&j.input[t*H..(t+1)*H];b.jobs[e].output[t]=j.output.as_mut_ptr().add(t*H);b.jobs[e].act[t]=(*self.shared.act[e].get()).as_ptr().add(t);b.jobs[e].nact[t]=(*self.shared.nact[e].get()).as_ptr().add(t).cast();let ptr=(*self.shared.act[e].get()).as_mut_ptr().add(t);if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut*ptr);}else{super::rust_quant::q8_one_avx2(x,&mut*ptr);}}else{let ptr=(*self.shared.nact[e].get()).as_mut_ptr().add(t);super::rust_quant::q8_k(x,&mut(*ptr).q);}}}} + self.run_published(f,jobs.len()); if jobs.iter().any(|j|j.output.iter().any(|v|!v.is_finite())){Err(Error::NonFinite)}else{Ok(())} } + /// Gate/up phase, the host requantization of every job's hidden rows, then the down phase, over the + /// `count` jobs already described in the batch (workers parked). + fn run_published(&mut self,f:NativeFmt,count:usize){ + self.phase(5,count*FF); + // SAFETY: all workers parked after phase 5; job rows were admitted before publication. + unsafe {let b=&*self.shared.batch.get();for e in 0..count{let rows=b.jobs[e].rows as usize;let s=&mut*self.shared.split[e].get();for t in 0..rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}} + self.phase(6,count*H); + } + /// One whole group straight from borrowed encoded matrices into the caller's output rows: a single + /// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns; + /// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of + /// each pair receives that expert's row; the pairs of all experts must name distinct rows. + pub fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> { + let f=NativeFmt::new(gu,down)?;let experts=group.experts;let tokens=group.tokens;let stride=group.stride; + if !(1..=MAX_JOBS).contains(&experts.len())||tokens.len()%H!=0||!(1..=MAX_ROWS).contains(&(tokens.len()/H))||stride==0||out.len()%H!=0{return Err(Error::Shape);} + let ntok=tokens.len()/H;let out_rows=out.len()/H;if out_rows>super::MAX_OUT_ROWS{return Err(Error::Shape);} + // Validate the ENTIRE group (extents, pair bounds, disjoint destinations, finite inputs) first. + let mut written=[0u64;super::MAX_OUT_ROWS/64];let mut used=[false;MAX_ROWS]; + for x in experts{ + if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off||!(1..=MAX_ROWS).contains(&x.pairs.len()){return Err(Error::Shape);} + for &(token,slot) in x.pairs{ + if token>=ntok||slot>=stride{return Err(Error::Shape);} + let row=token.checked_mul(stride).and_then(|r|r.checked_add(slot)).ok_or(Error::Shape)?; + if row>=out_rows||written[row/64]>>(row%64)&1!=0{return Err(Error::Shape);} + written[row/64]|=1<<(row%64);used[token]=true; + } + } + if tokens.iter().any(|x|!x.is_finite()){return Err(Error::NonFinite);} + self.shared.wait_parked(); + // SAFETY: all workers parked; the borrowed matrices, tokens and `out` outlive this call, which returns + // only after both phases finished and the workers parked again. Destinations are pairwise disjoint rows. + unsafe { + let ta=&mut*self.shared.tok_act[0].get();let tn=&mut*self.shared.tok_nact[0].get(); + for t in (0..ntok).filter(|&t|used[t]){let x=&tokens[t*H..(t+1)*H];if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut ta[t]);}else{super::rust_quant::q8_one_avx2(x,&mut ta[t]);}}else{super::rust_quant::q8_k(x,&mut tn[t].q);}} + let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();let base=out.as_mut_ptr(); + for (e,x) in experts.iter().enumerate(){ + b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),rows:x.pairs.len() as i32,..Job::default()}; + for (t,&(token,slot)) in x.pairs.iter().enumerate(){b.jobs[e].act[t]=ta.as_ptr().add(token);b.jobs[e].nact[t]=tn.as_ptr().add(token).cast();b.jobs[e].output[t]=base.add((token*stride+slot)*H);} + } + } + self.run_published(f,experts.len()); + for x in experts{for &(token,slot) in x.pairs{let at=(token*stride+slot)*H;if out[at..at+H].iter().any(|v|!v.is_finite()){return Err(Error::NonFinite);}}} + Ok(()) + } } impl Drop for NativePool{fn drop(&mut self){self.shared.stop.0.store(true,Ordering::Release);self.shared.publish();for t in self.workers.drain(..){let _=t.join();}}} diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs new file mode 100644 index 00000000..6f20eb2e --- /dev/null +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -0,0 +1,291 @@ +//! The borrowed single-dispatch group path (`DirectCpuPool::compute_group`) against the owned path the +//! serve pool used before (`PreparedJob` copies, batches of 12 through `CpuPool::start`/`join`, scatter): +//! every output bit must be identical, on every gate/up x down format pair, for groups of 1..=8 rows whose +//! experts are shared between rows. Synthetic encoded blobs: random codes, random finite FP16 block scales. +//! +//! cargo test --release -p leleka-native-cpu-expert --test borrowed_group_parity +//! (the ignored `group_path_cost` prints the model-free cost of both paths) +use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob}; +use std::time::Instant; + +const H: usize = 2560; +const FF: usize = 640; +const TOP_K: usize = 10; +const OLD_BATCH: usize = 12; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + fn unit(&mut self) -> f32 { + (self.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + } +} + +fn gate_up_block(f: GateUpFormat) -> (usize, usize) { + match f { + GateUpFormat::Iq3Xxs => (256, 98), + GateUpFormat::Iq3S => (256, 110), + GateUpFormat::Iq2S => (256, 82), + GateUpFormat::Iq4Xs => (256, 136), + GateUpFormat::Q2_0 => (64, 18), + } +} +fn down_block(f: DownFormat) -> (usize, usize) { + match f { + DownFormat::Iq4Nl => (32, 18), + DownFormat::Q2_0 => (64, 18), + } +} + +/// Random codes; every block starts with a finite FP16 scale in [2^-10, 2^-5). +fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec { + let mut out: Vec = (0..bytes).map(|_| rng.next() as u8).collect(); + for at in (0..bytes).step_by(block) { + let exponent = 5 + rng.below(5) as u16; + let half = (rng.below(2) as u16) << 15 | exponent << 10 | (rng.next() as u16 & 0x3ff); + out[at..at + 2].copy_from_slice(&half.to_le_bytes()); + } + out +} + +struct Expert { + gate: Vec, + up: Vec, + down: Vec, +} +fn bank(rng: &mut Rng, gu: GateUpFormat, down: DownFormat, count: usize) -> Vec { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + (0..count) + .map(|_| Expert { + gate: matrix(rng, H / gq * gb * FF, gb), + up: matrix(rng, H / gq * gb * FF, gb), + down: matrix(rng, FF / dq * db * H, db), + }) + .collect() +} + +/// A router output: `rows` rows of 10 distinct experts out of `experts`, plus the CPU mask. +fn route(rng: &mut Rng, rows: usize, experts: usize, cpu_share: usize) -> (Vec, Vec) { + let mut ids = Vec::new(); + for _ in 0..rows { + let mut row: Vec = Vec::new(); + while row.len() < TOP_K { + let e = rng.below(experts); + if !row.contains(&e) { + row.push(e); + } + } + ids.extend(row); + } + let include = (0..ids.len()).map(|_| rng.below(100) < cpu_share).collect(); + (ids, include) +} + +/// Experts in first-use order with their ascending `(row, slot)` pairs (original_serve_pool::plan_experts_where). +fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> { + let mut jobs: Vec<(usize, Vec<(usize, usize)>)> = Vec::new(); + for (i, &e) in ids.iter().enumerate() { + if !include[i] { + continue; + } + let pair = (i / TOP_K, i % TOP_K); + match jobs.iter_mut().find(|(x, _)| *x == e) { + Some((_, pairs)) => pairs.push(pair), + None => jobs.push((e, vec![pair])), + } + } + jobs +} + +/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with +/// a join between them, scatter every expert's rows into the output. +fn owned_path(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { + for batch in jobs.chunks(OLD_BATCH) { + let mut prepared = Vec::with_capacity(batch.len()); + for (e, pairs) in batch { + let x = &bank[*e]; + let mut input = Vec::with_capacity(pairs.len() * H); + for &(row, _) in pairs { + input.extend_from_slice(&tokens[row * H..(row + 1) * H]); + } + prepared.push( + PreparedJob::new(gu, down, x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice(), input.into_boxed_slice(), pairs.len()) + .expect("owned job"), + ); + } + let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); + for (job, (_, pairs)) in done.into_iter().zip(batch) { + let values = job.into_values(); + for (i, &(row, slot)) in pairs.iter().enumerate() { + let at = (row * TOP_K + slot) * H; + out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); + } + } + } +} + +fn borrowed_path(pool: &mut DirectCpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { + let experts: Vec> = + jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect(); + pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out).expect("borrowed group"); +} + +const PAIRS: [(GateUpFormat, DownFormat); 10] = [ + (GateUpFormat::Iq3Xxs, DownFormat::Iq4Nl), + (GateUpFormat::Iq3S, DownFormat::Iq4Nl), + (GateUpFormat::Iq2S, DownFormat::Iq4Nl), + (GateUpFormat::Iq4Xs, DownFormat::Iq4Nl), + (GateUpFormat::Q2_0, DownFormat::Iq4Nl), + (GateUpFormat::Iq3Xxs, DownFormat::Q2_0), + (GateUpFormat::Iq3S, DownFormat::Q2_0), + (GateUpFormat::Iq2S, DownFormat::Q2_0), + (GateUpFormat::Iq4Xs, DownFormat::Q2_0), + (GateUpFormat::Q2_0, DownFormat::Q2_0), +]; + +#[test] +fn borrowed_group_is_bit_identical_to_the_owned_batches() { + let workers = std::env::var("PARITY_WORKERS").ok().and_then(|v| v.parse().ok()).unwrap_or(4); + let mut owned = CpuPool::new(workers).expect("owned pool"); + let mut direct = DirectCpuPool::new(workers).expect("direct pool"); + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let mut groups = 0; + for (gu, down) in PAIRS { + // a small bank so rows share experts and batches of 12 are crossed + let bank = bank(&mut rng, gu, down, 40); + for rows in [1usize, 2, 3, 4, 6, 8] { + for share in [100usize, 50] { + let (ids, include) = route(&mut rng, rows, bank.len(), share); + let jobs = plan(&ids, &include); + if jobs.is_empty() { + continue; + } + let tokens: Vec = (0..rows * H).map(|_| rng.unit()).collect(); + // different sentinels: rows the plan leaves out must stay untouched by both paths + let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; + let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; + owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a); + borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b); + let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); + assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); + let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); + assert!(b.iter().filter(|v| v.is_finite()).count() == computed * H, "{gu:?} x {down:?}: only planned rows written, all finite"); + groups += 1; + } + } + } + eprintln!("bit-identical groups: {groups}"); +} + +#[test] +fn borrowed_group_refuses_bad_shapes_without_touching_out() { + let mut direct = DirectCpuPool::new(2).expect("direct pool"); + let mut rng = Rng(7); + let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + let bank = bank(&mut rng, gu, down, 2); + let tokens = vec![0.25f32; 2 * H]; + let mut out = vec![-3.0f32; 2 * TOP_K * H]; + let pairs_a = [(0usize, 1usize)]; + let duplicate = [(0usize, 1usize)]; + let out_of_rows = [(2usize, 0usize)]; + let wide_slot = [(0usize, TOP_K)]; + let x = |pairs| BorrowedExpert { gate: &bank[0].gate, up: &bank[0].up, down: &bank[0].down, pairs }; + let y = |pairs| BorrowedExpert { gate: &bank[1].gate, up: &bank[1].up, down: &bank[1].down, pairs }; + for experts in [vec![x(&pairs_a), y(&duplicate)], vec![x(&out_of_rows)], vec![x(&wide_slot)], vec![]] { + let group = BorrowedGroup { tokens: &tokens, experts: &experts, stride: TOP_K }; + assert!(direct.compute_group(gu, down, &group, &mut out).is_err()); + } + let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a }; + assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out).is_err()); + let wrong_format = [x(&pairs_a)]; + assert!(direct.compute_group(GateUpFormat::Iq3Xxs, down, &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, &mut out).is_err()); + let mut nan = tokens.clone(); + nan[5] = f32::NAN; + assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out).is_err()); + assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); + // and the pool still serves a good group afterwards + let good = [x(&pairs_a)]; + direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out).expect("good group"); + assert!(out[H..2 * H].iter().all(|v| v.is_finite())); +} + +/// The previous runtime prepare step per expert also copied each role out of the source (`block`) and +/// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again. +fn owned_path_with_source_copy(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { + let (_, gb) = gate_up_block(gu); + let (_, db) = down_block(down); + let scan = |bytes: &[u8], block: usize| bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00); + for batch in jobs.chunks(OLD_BATCH) { + let mut prepared = Vec::with_capacity(batch.len()); + for (e, pairs) in batch { + let x = &bank[*e]; + let (g, u, d) = (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); + assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); + let mut input = Vec::with_capacity(pairs.len() * H); + for &(row, _) in pairs { + input.extend_from_slice(&tokens[row * H..(row + 1) * H]); + } + prepared.push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")); + } + let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); + for (job, (_, pairs)) in done.into_iter().zip(batch) { + let values = job.into_values(); + for (i, &(row, slot)) in pairs.iter().enumerate() { + let at = (row * TOP_K + slot) * H; + out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); + } + } + } +} + +/// Model-free cost of one decode round's CPU share: 48 groups of `GROUP_ROWS` rows, `GROUP_SHARE`% of the +/// entries on the CPU, experts drawn from a bank larger than the LLC. Same workers for both paths. +#[test] +#[ignore = "benchmark; prints the cost of both group paths"] +fn group_path_cost() { + let env = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default); + let workers = env("BENCH_WORKERS", 15) as i32; + let rows = env("GROUP_ROWS", 4); + let share = env("GROUP_SHARE", 50); + let rounds = env("ROUNDS", 5); + let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + let mut rng = Rng(42); + let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256)); + let mut owned = CpuPool::new(workers).expect("owned pool"); + let mut direct = DirectCpuPool::new(workers).expect("direct pool"); + let groups: Vec<(Vec, Vec<(usize, Vec<(usize, usize)>)>)> = (0..48 * rounds) + .map(|_| { + let (ids, include) = route(&mut rng, rows, bank.len(), share); + ((0..rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include)) + }) + .collect(); + let experts: usize = groups.iter().map(|(_, j)| j.len()).sum(); + let mut out = vec![0.0f32; rows * TOP_K * H]; + for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] { + let started = Instant::now(); + for (tokens, jobs) in &groups { + match arm { + "borrowed" => borrowed_path(&mut direct, gu, down, &bank, tokens, jobs, &mut out), + "owned" => owned_path(&mut owned, gu, down, &bank, tokens, jobs, &mut out), + _ => owned_path_with_source_copy(&mut owned, gu, down, &bank, tokens, jobs, &mut out), + } + } + let ms = started.elapsed().as_secs_f64() * 1e3; + let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9; + eprintln!( + "BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 groups), {:.1} GB/s of expert bytes", + experts as f64 / groups.len() as f64, + ms / rounds as f64, + gb / (ms / 1e3) + ); + } +} From 3b9525af87c692870958dbe10f946cacce207baf Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 12:48:27 +0200 Subject: [PATCH 3/7] perf(serve): zero-copy CPU expert tier over the resident bank, one dispatch per group CpuExpertPool now opens one source scope per CPU expert (binding, actual gate/up/down descriptors and formats, the resident bank spans of exactly that expert), admits an expert's encoded rows once (the same finite-scale guard PreparedJob::new applied to every copy; the admitted spans are retained so the bytes cannot move) and computes the whole group in one DirectCpuPool dispatch writing the mapped destination in place. Previously every expert was copied twice (~2.7 MB each), prepared on the coordinator, run in batches of 12 with a join between them, re-validated by re-opening the source and scattered. LELEKA_CPU_POOL=legacy keeps the previous path (A/B arm); LELEKA_CPU_POOL=crosscheck runs both on every group and fails on any differing bit. Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/cpu_expert_miss.rs | 2 +- .../src/qwen_forward/original_serve_pool.rs | 298 ++++++++++++++++-- 2 files changed, 269 insertions(+), 31 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/cpu_expert_miss.rs b/crates/leleka-runtime/src/qwen_forward/cpu_expert_miss.rs index 37c409c4..c97e71af 100644 --- a/crates/leleka-runtime/src/qwen_forward/cpu_expert_miss.rs +++ b/crates/leleka-runtime/src/qwen_forward/cpu_expert_miss.rs @@ -118,7 +118,7 @@ fn native_error(error:leleka_native_cpu_expert::Error)->CpuMissError { E::Allocation|E::BudgetExceeded=>CpuMissError::Allocation,E::NonFinite=>CpuMissError::NonFinite, E::NativeFailure|E::Closed=>CpuMissError::NativeFailure } } -fn validate_triplet([gate,up,down]:[MoeWeightDescriptor;3])->Result<(GateUpFormat,DownFormat)> { +pub(crate) fn validate_triplet([gate,up,down]:[MoeWeightDescriptor;3])->Result<(GateUpFormat,DownFormat)> { if gate.expert.is_none() || gate.expert!=up.expert || gate.expert!=down.expert || gate.layer!=up.layer || gate.layer!=down.layer || gate.role!=0 || up.role!=1 || down.role!=2 || gate.columns!=H || up.columns!=H || gate.rows!=FF || up.rows!=FF || down.columns!=FF || down.rows!=H || gate.raw_kind!=up.raw_kind || gate.bytes!=up.bytes { return Err(CpuMissError::Shape); } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index 7c5e2512..2174210c 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -14,11 +14,13 @@ //! (`original_serve_residency::GpuExpertPool`), which hands this pool only the entries it must compute. use super::{ contract::{Error, Result}, - cpu_expert_miss::{runtime_error, CpuMissWorkspace}, + cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace}, input::binding_error, }; -use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole}; use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink}; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; +use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool}; const HIDDEN: usize = 2560; const TOP_K: usize = 10; @@ -161,17 +163,75 @@ pub(in crate::qwen_forward) fn scatter(out: &mut [f32], job: &ExpertJob, values: Ok(()) } +/// How the CPU tier runs a group (`LELEKA_CPU_POOL`, read once when the pool opens). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) enum PoolPath { + /// Default: every routed expert of the group computed straight from the resident expert bank in one + /// dispatch over the worker pool, written in place into the mapped destination (no expert copy). + Direct, + /// `LELEKA_CPU_POOL=legacy` (A/B arm): owned copies of every expert, batches of 12, re-validation, scatter. + Legacy, + /// `LELEKA_CPU_POOL=crosscheck` (diagnostic): the direct path, then the legacy path on the same group, + /// every computed float compared bit for bit; a difference fails the group. + Crosscheck, +} +impl PoolPath { + pub(in crate::qwen_forward) fn from_env() -> Self { + match std::env::var("LELEKA_CPU_POOL").as_deref() { + Ok("legacy") => Self::Legacy, + Ok("crosscheck") => Self::Crosscheck, + _ => Self::Direct, + } + } +} + +/// The direct path's state: the synchronous worker pool and the admitted experts. An expert's three +/// encoded matrices are admitted (every block's FP16 scale finite: the guard `PreparedJob::new` applied to +/// each copy) the first time it is routed to the CPU; the admitted spans are retained, so their bank memory +/// stays alive and a later span of the same expert at the same address is the same immutable bytes. +struct DirectTier { + pool: DirectCpuPool, + admitted: Vec>, +} + /// The all-CPU expert tier over the pinned model's mapped routed weights. pub(in crate::qwen_forward) struct CpuExpertPool<'a> { binding: &'a ModelBinding, - cpu: CpuMissWorkspace, + direct: Option, + legacy: Option, + crosscheck: CrosscheckCounts, +} +#[derive(Default)] +struct CrosscheckCounts { + groups: u64, + rows: u64, } impl<'a> CpuExpertPool<'a> { pub(in crate::qwen_forward) fn new(binding: &'a ModelBinding, workers: i32) -> Result { + Self::with_path(binding, workers, PoolPath::from_env()) + } + pub(in crate::qwen_forward) fn with_path(binding: &'a ModelBinding, workers: i32, path: PoolPath) -> Result { if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != TOP_K as u32 { return Err(Error::IdentityMismatch); } - Ok(Self { binding, cpu: CpuMissWorkspace::new(binding, workers).map_err(runtime_error)? }) + let direct = match path { + PoolPath::Legacy => None, + PoolPath::Direct | PoolPath::Crosscheck => { + let pool = DirectCpuPool::new(workers).map_err(|e| runtime_error(native_cpu_error(e)))?; + let mut admitted = Vec::new(); + admitted.try_reserve_exact(48 * EXPERTS as usize).map_err(|_| Error::InputAllocation)?; + admitted.resize_with(48 * EXPERTS as usize, || None); + Some(DirectTier { pool, admitted }) + } + }; + let legacy = match path { + PoolPath::Direct => None, + PoolPath::Legacy | PoolPath::Crosscheck => Some(CpuMissWorkspace::new(binding, workers).map_err(runtime_error)?), + }; + if path != PoolPath::Direct { + eprintln!("leleka-serve cpu expert pool: {path:?} path (LELEKA_CPU_POOL)"); + } + Ok(Self { binding, direct, legacy, crosscheck: CrosscheckCounts::default() }) } } impl<'ctx> OriginalServePool<'ctx> for CpuExpertPool<'_> { @@ -202,13 +262,161 @@ impl CpuExpertPool<'_> { { return Err(Error::InvalidDimension); } - let binding = self.binding; - let layer = rows.layer as u32; let mut clock = window_trace::now(); let plan = plan_experts_where(rows.ids, count, include)?; window_trace::lap(window_trace::PLAN, &mut clock); window_trace::add(window_trace::EXPERTS, plan.len() as f64); window_trace::add(window_trace::ENTRIES, plan.iter().map(|j| j.pairs.len()).sum::() as f64); + if self.direct.is_some() { + self.run_direct(&rows, sink, include, &plan, &mut clock)?; + if self.legacy.is_some() { + let results = self.legacy_results(&rows, &plan, &mut clock)?; + return self.compare(sink, &plan, &results); + } + return Ok(()); + } + let results = self.legacy_results(&rows, &plan, &mut clock)?; + let mut failure = None; + let written = sink.with_output(|out| { + if out.len() != count * TOP_K * HIDDEN { + failure = Some(Error::InvalidDimension); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + if let Some(mask) = include { + for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) { + out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0); + } + } + for (job_index, values) in &results { + if let Err(error) = scatter(out, &plan[*job_index], values) { + failure = Some(error); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + } + Ok(()) + }); + window_trace::lap(window_trace::SCATTER, &mut clock); + sink_result(written, failure) + } + + /// The direct path: per expert one source scope (binding, actual gate/up/down descriptors, their + /// formats, the resident bank spans of exactly this expert), then the whole group in one synchronous + /// dispatch writing every computed row in place. + fn run_direct( + &mut self, + rows: &OriginalVerifyCpuRows<'_>, + sink: &mut OriginalVerifyCpuSink<'_, '_>, + include: Option<&[bool]>, + plan: &[ExpertJob], + clock: &mut Option, + ) -> Result<()> { + let binding = self.binding; + let layer = rows.layer as u32; + let count = rows.ids.len() / TOP_K; + let tier = self.direct.as_mut().ok_or(Error::IdentityMismatch)?; + let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); + sources.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; + let mut formats = None; + // One bound route per window row (its own top-10); every job first seen in that row shares it. + let mut bound: [Option; 8] = std::array::from_fn(|_| None); + for job in plan { + let (first_row, first_slot) = job.pairs[0]; + if bound.get(first_row).ok_or(Error::InvalidDimension)?.is_none() { + bound[first_row] = Some(binding.moe_expert_weights(layer, selection(rows.ids, first_row)?).map_err(binding_error)?); + } + let weights = bound[first_row].as_ref().ok_or(Error::IdentityMismatch)?; + let members = [(weights, first_slot)]; + let admitted = &mut tier.admitted[layer as usize * EXPERTS as usize + job.expert as usize]; + let (spans, format) = binding.with_moe_routed_source(&members, binding_error, |source| { + let operation = (|| { + source.validate_binding(binding).map_err(binding_error)?; + let keys = [ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if keys.iter().any(|k| k.layer != layer || k.expert != Some(job.expert as u32)) { + return Err(Error::IdentityMismatch); + } + let format = validate_triplet(keys).map_err(runtime_error)?; + let spans = [ + source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + let same = |held: &[ResidentExpertBankSpan; 3]| { + held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len()) + }; + if !admitted.as_ref().is_some_and(same) { + // First use (or a different span): admit every row of the actual matrices. + *admitted = None; + let checked = [ + source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if !same(&checked) { + return Err(Error::IdentityMismatch); + } + *admitted = Some(checked); + } + Ok((spans, format)) + })(); + let finish = source.finish().map_err(binding_error); + match operation { + Err(e) => Err(e), + Ok(v) => finish.map(|()| v), + } + })?; + if *formats.get_or_insert(format) != format { + return Err(Error::IdentityMismatch); + } + sources.push(spans); + } + let mut experts: Vec> = Vec::new(); + experts.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; + for (job, spans) in plan.iter().zip(&sources) { + experts.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &job.pairs }); + } + window_trace::lap(window_trace::PREPARE, clock); + let mut failure = None; + let written = sink.with_output(|out| { + if out.len() != count * TOP_K * HIDDEN { + failure = Some(Error::InvalidDimension); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + if let Some(mask) = include { + for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) { + out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0); + } + } + if let Some((gu, down)) = formats { + // At most 80 distinct experts per group, so one dispatch (MAX_JOBS is 96). + for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) { + let group = BorrowedGroup { tokens: rows.activation, experts: chunk, stride: TOP_K }; + if let Err(e) = tier.pool.compute_group(gu, down, &group, out) { + failure = Some(runtime_error(native_cpu_error(e))); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + } + } + Ok(()) + }); + window_trace::lap(window_trace::JOIN, clock); + sink_result(written, failure) + } + + /// The legacy path's results: owned copies, batches of `JOBS_PER_BATCH` joined in turn, every result + /// re-validated against a re-opened source. `(plan index, rows)` for the caller to scatter. + fn legacy_results( + &mut self, + rows: &OriginalVerifyCpuRows<'_>, + plan: &[ExpertJob], + clock: &mut Option, + ) -> Result)>> { + let binding = self.binding; + let layer = rows.layer as u32; + let cpu = self.legacy.as_mut().ok_or(Error::IdentityMismatch)?; // Every batch is prepared, run and joined before the next; results are held until the whole // group is complete so the mapped destination is written in one bounded pass. let mut results: Vec<(usize, Box<[f32]>)> = Vec::new(); @@ -227,17 +435,17 @@ impl CpuExpertPool<'_> { inputs.push(&rows.activation[row * HIDDEN..(row + 1) * HIDDEN]); } let prepared = binding.with_moe_routed_source(&members, binding_error, |source| { - let prepared = self.cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; + let prepared = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; source.finish().map_err(binding_error)?; Ok(prepared) })?; jobs.push(prepared); } - window_trace::lap(window_trace::PREPARE, &mut clock); - let pending = self.cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?; - window_trace::lap(window_trace::START, &mut clock); + window_trace::lap(window_trace::PREPARE, clock); + let pending = cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?; + window_trace::lap(window_trace::START, clock); let completed = pending.join().map_err(runtime_error)?; - window_trace::lap(window_trace::JOIN, &mut clock); + window_trace::lap(window_trace::JOIN, clock); if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } @@ -261,33 +469,63 @@ impl CpuExpertPool<'_> { })?; results.push((batch_index * JOBS_PER_BATCH + k, done.into_values())); } - window_trace::lap(window_trace::VALIDATE, &mut clock); + window_trace::lap(window_trace::VALIDATE, clock); } + Ok(results) + } + + /// Crosscheck: the direct rows already in the destination against the legacy rows, bit for bit. + fn compare(&mut self, sink: &mut OriginalVerifyCpuSink<'_, '_>, plan: &[ExpertJob], results: &[(usize, Box<[f32]>)]) -> Result<()> { + let mut differing = 0usize; + let mut compared = 0usize; let mut failure = None; - let written = sink.with_output(|out| { - if out.len() != count * TOP_K * HIDDEN { - failure = Some(Error::InvalidDimension); - return Err(leleka_cuda_driver::Error::InvalidQwenShape); - } - if let Some(mask) = include { - for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) { - out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0); - } - } - for (job_index, values) in &results { - if let Err(error) = scatter(out, &plan[*job_index], values) { - failure = Some(error); + let read = sink.with_output(|out| { + for (job_index, values) in results { + let job = &plan[*job_index]; + if values.len() != job.pairs.len() * HIDDEN { + failure = Some(Error::InvalidDimension); return Err(leleka_cuda_driver::Error::InvalidQwenShape); } + for (i, &(row, slot)) in job.pairs.iter().enumerate() { + let at = output_offset(row, slot); + let direct = out.get(at..at + HIDDEN).ok_or(leleka_cuda_driver::Error::InvalidQwenShape)?; + differing += direct.iter().zip(&values[i * HIDDEN..(i + 1) * HIDDEN]).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + compared += 1; + } } Ok(()) }); - window_trace::lap(window_trace::SCATTER, &mut clock); - match (written, failure) { - (Ok(()), None) => Ok(()), - (_, Some(error)) => Err(error), - (Err(_), None) => Err(Error::CudaExecution), + sink_result(read, failure)?; + self.crosscheck.groups += 1; + self.crosscheck.rows += compared as u64; + if differing != 0 { + eprintln!("CROSSCHECK cpu pool: {differing} floats differ in a group of {} experts", plan.len()); + return Err(Error::IdentityMismatch); } + if self.crosscheck.groups % 48 == 0 { + eprintln!("CROSSCHECK cpu pool: {} groups, {} expert rows bit-identical (direct vs legacy)", self.crosscheck.groups, self.crosscheck.rows); + } + Ok(()) + } +} + +fn sink_result(written: leleka_cuda_driver::Result<()>, failure: Option) -> Result<()> { + match (written, failure) { + (Ok(()), None) => Ok(()), + (_, Some(error)) => Err(error), + (Err(_), None) => Err(Error::CudaExecution), + } +} + +fn native_cpu_error(error: leleka_native_cpu_expert::Error) -> super::cpu_expert_miss::CpuMissError { + use super::cpu_expert_miss::CpuMissError as C; + use leleka_native_cpu_expert::Error as E; + match error { + E::Shape => C::Shape, + E::Unsupported => C::Unsupported, + E::Allocation | E::BudgetExceeded => C::Allocation, + E::NonFinite => C::NonFinite, + E::NativeFailure | E::Closed => C::NativeFailure, } } From 49d27973b03f2d01f17d923451697b1a14e7d519 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 12:51:20 +0200 Subject: [PATCH 4/7] perf(serve): admit PCIe and swap expert sources once, like the CPU tier's The VRAM tier's PCIe copies and adaptive swaps took their spans from original_expert_spans, which scans every block scale of the expert's three matrices (~2.7 MB) on every call. With the direct CPU tier they now go through the same admitted_expert: binding, descriptors and bank spans validated per call, the rows scanned on first use with the checked spans retained, and the bank eligibility checked as before. The legacy arm (LELEKA_CPU_POOL=legacy) keeps the per-call scan. Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/original_serve_pool.rs | 131 ++++++++++-------- .../qwen_forward/original_serve_residency.rs | 23 ++- 2 files changed, 97 insertions(+), 57 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index 2174210c..e605cf90 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -17,10 +17,10 @@ use super::{ cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace}, input::binding_error, }; -use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink}; use leleka_model_format::qwen4exp::ResidentExpertBankSpan; -use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool}; +use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat}; const HIDDEN: usize = 2560; const TOP_K: usize = 10; @@ -299,9 +299,8 @@ impl CpuExpertPool<'_> { sink_result(written, failure) } - /// The direct path: per expert one source scope (binding, actual gate/up/down descriptors, their - /// formats, the resident bank spans of exactly this expert), then the whole group in one synchronous - /// dispatch writing every computed row in place. + /// The direct path: per expert one source scope (`admitted_expert`), then the whole group in one + /// synchronous dispatch writing every computed row in place. fn run_direct( &mut self, rows: &OriginalVerifyCpuRows<'_>, @@ -317,57 +316,10 @@ impl CpuExpertPool<'_> { let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); sources.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; let mut formats = None; - // One bound route per window row (its own top-10); every job first seen in that row shares it. - let mut bound: [Option; 8] = std::array::from_fn(|_| None); for job in plan { - let (first_row, first_slot) = job.pairs[0]; - if bound.get(first_row).ok_or(Error::InvalidDimension)?.is_none() { - bound[first_row] = Some(binding.moe_expert_weights(layer, selection(rows.ids, first_row)?).map_err(binding_error)?); - } - let weights = bound[first_row].as_ref().ok_or(Error::IdentityMismatch)?; - let members = [(weights, first_slot)]; - let admitted = &mut tier.admitted[layer as usize * EXPERTS as usize + job.expert as usize]; - let (spans, format) = binding.with_moe_routed_source(&members, binding_error, |source| { - let operation = (|| { - source.validate_binding(binding).map_err(binding_error)?; - let keys = [ - source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - if keys.iter().any(|k| k.layer != layer || k.expert != Some(job.expert as u32)) { - return Err(Error::IdentityMismatch); - } - let format = validate_triplet(keys).map_err(runtime_error)?; - let spans = [ - source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - let same = |held: &[ResidentExpertBankSpan; 3]| { - held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len()) - }; - if !admitted.as_ref().is_some_and(same) { - // First use (or a different span): admit every row of the actual matrices. - *admitted = None; - let checked = [ - source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - if !same(&checked) { - return Err(Error::IdentityMismatch); - } - *admitted = Some(checked); - } - Ok((spans, format)) - })(); - let finish = source.finish().map_err(binding_error); - match operation { - Err(e) => Err(e), - Ok(v) => finish.map(|()| v), - } - })?; + let expert = u32::try_from(job.expert).map_err(|_| Error::InvalidExpert)?; + let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?; + let (spans, format) = admitted_expert(binding, layer, expert, admitted)?; if *formats.get_or_insert(format) != format { return Err(Error::IdentityMismatch); } @@ -406,6 +358,15 @@ impl CpuExpertPool<'_> { sink_result(written, failure) } + /// The PCIe tier's source spans of `expert`, through the same per-call validation and one-time row + /// admission as the CPU's own experts; `None` on the legacy path (the caller keeps its full scan). + pub(in crate::qwen_forward) fn admitted_spans(&mut self, layer: u32, expert: u32) -> Option> { + let binding = self.binding; + let tier = self.direct.as_mut()?; + let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize)?; + Some(admitted_expert(binding, layer, expert, admitted).map(|(spans, _)| spans)) + } + /// The legacy path's results: owned copies, batches of `JOBS_PER_BATCH` joined in turn, every result /// re-validated against a re-opened source. `(plan index, rows)` for the caller to scatter. fn legacy_results( @@ -509,6 +470,66 @@ impl CpuExpertPool<'_> { } } +/// One routed expert's resident source, opened and validated on every call (binding, the actual +/// gate/up/down descriptors of exactly this layer and expert, their formats, the bank spans) while its +/// encoded rows are admitted only on first use: `admitted` retains the checked spans, so the bank bytes +/// they address stay alive and immutable, and a later span at the same address needs no new scan. +pub(in crate::qwen_forward) fn admitted_expert( + binding: &ModelBinding, + layer: u32, + expert: u32, + admitted: &mut Option<[ResidentExpertBankSpan; 3]>, +) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat))> { + if layer >= 48 || expert >= EXPERTS as u32 { + return Err(Error::InvalidExpert); + } + // A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`). + let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32); + let bound = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; + let members = [(&bound, 0)]; + binding.with_moe_routed_source(&members, binding_error, |source| { + let operation = (|| { + source.validate_binding(binding).map_err(binding_error)?; + let keys = [ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if keys.iter().any(|k| k.layer != layer || k.expert != Some(expert)) { + return Err(Error::IdentityMismatch); + } + let format = validate_triplet(keys).map_err(runtime_error)?; + let spans = [ + source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + let same = |held: &[ResidentExpertBankSpan; 3]| { + held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len()) + }; + if !admitted.as_ref().is_some_and(same) { + // First use (or a different span): admit every row of the actual matrices. + *admitted = None; + let checked = [ + source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if !same(&checked) { + return Err(Error::IdentityMismatch); + } + *admitted = Some(checked); + } + Ok((spans, format)) + })(); + let finish = source.finish().map_err(binding_error); + match operation { + Err(e) => Err(e), + Ok(v) => finish.map(|()| v), + } + }) +} + fn sink_result(written: leleka_cuda_driver::Result<()>, failure: Option) -> Result<()> { match (written, failure) { (Ok(()), None) => Ok(()), diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 52301863..a8f2d22a 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -355,7 +355,17 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { let mut spans = Vec::new(); spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?; for &e in &split.pcie_experts { - spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?); + // The direct CPU tier's admission (rows scanned once per expert) serves the PCIe sources too. + match self.cpu.admitted_spans(layer as u32, e) { + Some(admitted) => { + let admitted = admitted?; + if !self.bank.eligible(&admitted) { + return Err(Error::IdentityMismatch); + } + spans.push(admitted); + } + None => spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?), + } } let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans }); sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?; @@ -387,7 +397,16 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps); for swap in &swaps { let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; - let spans = self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?; + let spans = match self.cpu.admitted_spans(swap.layer as u32, swap.incoming as u32) { + Some(admitted) => { + let admitted = admitted?; + if !self.bank.eligible(&admitted) { + return Err(Error::IdentityMismatch); + } + admitted + } + None => self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?, + }; self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?; } self.cache.arm_swaps().map_err(|e| driver_error(&e))?; From e32c39090af4d691e7c13b67e628425252529618 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 13:19:48 +0200 Subject: [PATCH 5/7] perf(serve): prefetch a file-mapped expert source on all pool workers before admission and compute With the mapped low-RAM source (load_mapped_expert_source, the Original's --mmap-experts) the direct CPU tier opens every CPU expert of the group first without scanning it, then advises all their pages (MADV_WILLNEED) and faults them in on every pool worker and the caller in one read-only phase (expert_source.cpp prefetch on its fetch threads), and only then admits first-use experts and computes. The resident source skips the phase. Trace slot 'fetch' times it. Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/original_serve_pool.rs | 56 ++++++++++++++++--- .../src/qwen4exp_expert_source_bank.rs | 5 ++ crates/native-cpu-expert/src/ffi.rs | 7 +++ crates/native-cpu-expert/src/lib.rs | 8 +++ crates/native-cpu-expert/src/rust_platform.rs | 10 ++++ crates/native-cpu-expert/src/rust_pool.rs | 23 +++++++- .../tests/borrowed_group_parity.rs | 6 ++ 7 files changed, 105 insertions(+), 10 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index e605cf90..31f9e5a3 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -35,8 +35,8 @@ const BATCH_ALLOWANCE: usize = 48 << 20; pub(in crate::qwen_forward) mod window_trace { use std::cell::Cell; use std::time::Instant; - pub(in crate::qwen_forward) const NAMES: [&str; 10] = - ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries"]; + pub(in crate::qwen_forward) const NAMES: [&str; 11] = + ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries", "fetch"]; pub(in crate::qwen_forward) const POOL: usize = 0; pub(in crate::qwen_forward) const GPU_SPLIT: usize = 1; pub(in crate::qwen_forward) const PLAN: usize = 2; @@ -47,7 +47,8 @@ pub(in crate::qwen_forward) mod window_trace { pub(in crate::qwen_forward) const SCATTER: usize = 7; pub(in crate::qwen_forward) const EXPERTS: usize = 8; pub(in crate::qwen_forward) const ENTRIES: usize = 9; - thread_local! { static SUMS: Cell<[f64; 10]> = const { Cell::new([0.0; 10]) }; } + pub(in crate::qwen_forward) const FETCH: usize = 10; + thread_local! { static SUMS: Cell<[f64; 11]> = const { Cell::new([0.0; 11]) }; } /// A clock only when tracing. pub(in crate::qwen_forward) fn now() -> Option { crate::bringup_trace_enabled().then(Instant::now) @@ -69,8 +70,8 @@ pub(in crate::qwen_forward) mod window_trace { }); } } - pub(in crate::qwen_forward) fn take() -> [f64; 10] { - SUMS.with(|s| s.replace([0.0; 10])) + pub(in crate::qwen_forward) fn take() -> [f64; 11] { + SUMS.with(|s| s.replace([0.0; 11])) } } @@ -316,13 +317,18 @@ impl CpuExpertPool<'_> { let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); sources.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; let mut formats = None; + let mut ready: Vec = Vec::new(); + ready.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; + let mut mapped = false; for job in plan { let expert = u32::try_from(job.expert).map_err(|_| Error::InvalidExpert)?; let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?; - let (spans, format) = admitted_expert(binding, layer, expert, admitted)?; + let (spans, format, admitted_now) = open_expert(binding, layer, expert, admitted, false)?; if *formats.get_or_insert(format) != format { return Err(Error::IdentityMismatch); } + ready.push(admitted_now); + mapped |= spans.iter().any(ResidentExpertBankSpan::file_mapped); sources.push(spans); } let mut experts: Vec> = Vec::new(); @@ -331,6 +337,24 @@ impl CpuExpertPool<'_> { experts.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &job.pairs }); } window_trace::lap(window_trace::PREPARE, clock); + if let (true, Some((gu, down))) = (mapped, formats) { + // The file-mapped source (the Original's --mmap-experts): every page of the group's experts is + // advised and faulted in on all workers at once, before the admission scans and the compute. + for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) { + tier.pool.prefetch(gu, down, chunk).map_err(|e| runtime_error(native_cpu_error(e)))?; + } + } + window_trace::lap(window_trace::FETCH, clock); + // First use: admit every row of the experts not yet admitted (their pages are now resident). + for ((job, spans), _) in plan.iter().zip(&sources).zip(&ready).filter(|(_, ready)| !**ready) { + let expert = job.expert as u32; + let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?; + let (again, _, _) = open_expert(binding, layer, expert, admitted, true)?; + if again.iter().zip(spans).any(|(a, b)| a.bytes().as_ptr() != b.bytes().as_ptr() || a.bytes().len() != b.bytes().len()) { + return Err(Error::IdentityMismatch); + } + } + window_trace::lap(window_trace::PREPARE, clock); let mut failure = None; let written = sink.with_output(|out| { if out.len() != count * TOP_K * HIDDEN { @@ -480,6 +504,19 @@ pub(in crate::qwen_forward) fn admitted_expert( expert: u32, admitted: &mut Option<[ResidentExpertBankSpan; 3]>, ) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat))> { + let (spans, format, _) = open_expert(binding, layer, expert, admitted, true)?; + Ok((spans, format)) +} + +/// `admitted_expert` that, with `admit` false, leaves a not yet admitted expert unscanned and says so +/// (third value false): the caller prefetches it and admits it before any consumer reads it. +fn open_expert( + binding: &ModelBinding, + layer: u32, + expert: u32, + admitted: &mut Option<[ResidentExpertBankSpan; 3]>, + admit: bool, +) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat), bool)> { if layer >= 48 || expert >= EXPERTS as u32 { return Err(Error::InvalidExpert); } @@ -508,8 +545,11 @@ pub(in crate::qwen_forward) fn admitted_expert( held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len()) }; if !admitted.as_ref().is_some_and(same) { - // First use (or a different span): admit every row of the actual matrices. *admitted = None; + if !admit { + return Ok((spans, format, false)); + } + // First use (or a different span): admit every row of the actual matrices. let checked = [ source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?, source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?, @@ -520,7 +560,7 @@ pub(in crate::qwen_forward) fn admitted_expert( } *admitted = Some(checked); } - Ok((spans, format)) + Ok((spans, format, true)) })(); let finish = source.finish().map_err(binding_error); match operation { diff --git a/crates/model-format/src/qwen4exp_expert_source_bank.rs b/crates/model-format/src/qwen4exp_expert_source_bank.rs index 00cd6bce..d2a6b9ae 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank.rs @@ -579,6 +579,11 @@ impl ResidentExpertBankSpan { pub fn raw_kind(&self) -> u32 { self.member.raw_kind() } + /// The bytes are a read-only shared mapping of the verified shard (the low-RAM source), so a read + /// may fault the page in from the file. + pub fn file_mapped(&self) -> bool { + self.member.file_mapped() + } pub fn belongs_to(&self, member: &ResidentExpertBankMember) -> bool { self.member.descriptor == member.descriptor && Rc::ptr_eq(&self.member.tensor, &member.tensor) diff --git a/crates/native-cpu-expert/src/ffi.rs b/crates/native-cpu-expert/src/ffi.rs index 42d62014..6b9d3607 100644 --- a/crates/native-cpu-expert/src/ffi.rs +++ b/crates/native-cpu-expert/src/ffi.rs @@ -14,6 +14,13 @@ impl NativePool { Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} } } + pub(super) fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> { + let pool=self.pool.as_mut().ok_or(Error::Closed)?; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.prefetch_borrowed(gu,down,experts))) { + Ok(result)=>result, + Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} + } + } pub(super) fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> { let pool=self.pool.as_mut().ok_or(Error::Closed)?; match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_batch(jobs))) { diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index 2396192d..3fffce16 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -137,6 +137,14 @@ impl DirectCpuPool { if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } result } + /// Read every page of the experts' matrices on all workers after `MADV_WILLNEED` on all of them (for a + /// file-mapped source; the pairs are ignored). Nothing is computed or written. + pub fn prefetch(&mut self, gu: GateUpFormat, down: DownFormat, experts: &[BorrowedExpert<'_>]) -> Result<()> { + if self.failed { return Err(Error::Closed); } + let result = self.native.prefetch_borrowed(gu.kind(), down.kind(), experts); + if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } + result + } } pub struct CompletedJob { values: Box<[f32]> } diff --git a/crates/native-cpu-expert/src/rust_platform.rs b/crates/native-cpu-expert/src/rust_platform.rs index b4856cd9..04fea067 100644 --- a/crates/native-cpu-expert/src/rust_platform.rs +++ b/crates/native-cpu-expert/src/rust_platform.rs @@ -11,6 +11,7 @@ unsafe extern "C" { fn pthread_self()->usize; fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32; fn sysconf(name:i32)->i64; + fn madvise(addr:*mut u8,len:usize,advice:i32)->i32; } pub(super) fn stack_size()->Result { #[cfg(not(target_env="gnu"))] {return Err(Error::Unsupported);} @@ -30,6 +31,15 @@ pub(super) fn cores(skip_first:bool)->Vec { let mut seen=Vec::new();let mut physical=Vec::new();for cpu in allowed {let key=(read_cpu(cpu,"physical_package_id"),read_cpu(cpu,"core_id"));if key.0>=0&&key.1>=0 {if seen.contains(&key){continue;}seen.push(key);}physical.push(cpu);} if skip_first&&!physical.is_empty(){physical.remove(0);}physical } +/// `madvise(MADV_WILLNEED)` over the pages of `bytes`: the kernel starts reading a file-mapped range in the +/// background (expert_source.cpp `warm`). Advice only; a failure changes nothing. +pub(super) fn will_need(bytes:&[u8]) { + if bytes.is_empty(){return;} + let page=4096usize;let start=bytes.as_ptr() as usize&!(page-1);let end=bytes.as_ptr() as usize+bytes.len(); + // SAFETY: advice over pages that contain the caller's live borrowed range; MADV_WILLNEED (3) never + // changes the contents or the mapping. + unsafe {let _=madvise(start as *mut u8,end-start,3);} +} pub(super) fn pin(core:i32) { if core<0{return;}let mut set=[0usize;16];if core as usize>=1024{return;}set[core as usize/64]|=1usize<<(core as usize%64); // Original intentionally ignores OS affinity refusal; it does not change math. diff --git a/crates/native-cpu-expert/src/rust_pool.rs b/crates/native-cpu-expert/src/rust_pool.rs index f4971de3..41cfe87e 100644 --- a/crates/native-cpu-expert/src/rust_pool.rs +++ b/crates/native-cpu-expert/src/rust_pool.rs @@ -44,10 +44,14 @@ impl Shared { unsafe {self.execute(i);}self.done.0.fetch_add(1,Ordering::Release); }} unsafe fn execute(&self,i:usize){unsafe { - let b=&*self.batch.get();let per=if b.mode==5{FF}else{H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks; + let b=&*self.batch.get();let per=match b.mode{5=>FF,6=>H,_=>2*FF+H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks; while at()).q.as_slice();MAX_ROWS];for t in 0..nr{yy[t]=(&*j.nact[t].cast::()).q.as_slice();}let d=dispatch();if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq512{super::rust_iq::dot_multi512(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi512(f.gu,ur,&yy[..nr],&mut u[..nr]);}else if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq256{super::rust_iq::dot_multi256(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi256(f.gu,ur,&yy[..nr],&mut u[..nr]);}else{for t in 0..nr{g[t]=super::rust_iq::dot_single(f.gu,gr,yy[t]);u[t]=super::rust_iq::dot_single(f.gu,ur,yy[t]);}}} @@ -100,6 +104,21 @@ impl NativePool { unsafe {let b=&*self.shared.batch.get();for e in 0..count{let rows=b.jobs[e].rows as usize;let s=&mut*self.shared.split[e].get();for t in 0..rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}} self.phase(6,count*H); } + /// Fault the borrowed matrices in on every worker (and the caller) after `MADV_WILLNEED` on all of + /// them: a file-mapped source's misses become many outstanding reads instead of one serial stream + /// (expert_source.cpp `prefetch` on its fetch threads). Reads only; nothing is computed or written. + pub fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> { + let f=NativeFmt::new(gu,down)?; + if !(1..=MAX_JOBS).contains(&experts.len()){return Err(Error::Shape);} + for x in experts{if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off{return Err(Error::Shape);}} + for x in experts{for m in [x.gate,x.up,x.down]{super::rust_platform::will_need(m);}} + self.shared.wait_parked(); + // SAFETY: all workers parked; the borrowed matrices outlive this call, which returns only after the + // phase finished and the workers parked again. The phase only reads them. + unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();for (e,x) in experts.iter().enumerate(){b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),..Job::default()};}} + self.phase(7,experts.len()*(2*FF+H)); + Ok(()) + } /// One whole group straight from borrowed encoded matrices into the caller's output rows: a single /// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns; /// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs index 6f20eb2e..eb99e68d 100644 --- a/crates/native-cpu-expert/tests/borrowed_group_parity.rs +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -174,6 +174,12 @@ fn borrowed_group_is_bit_identical_to_the_owned_batches() { let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a); + if share != 100 { + // the file-mapped source's prefetch phase reads only: the group computes the same bits + let refs: Vec> = + jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect(); + direct.prefetch(gu, down, &refs).expect("prefetch"); + } borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b); let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); From 6f0d4e0f967fb295b6ee126747e7a5124c5e99bb Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 15:13:59 +0200 Subject: [PATCH 6/7] diag(serve): trace the PCIe span validation of the VRAM tier separately (pcie_spans, pcie_experts) Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/original_serve_pool.rs | 12 +++++++----- .../src/qwen_forward/original_serve_residency.rs | 3 +++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index 31f9e5a3..ea6f5b6d 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -35,8 +35,8 @@ const BATCH_ALLOWANCE: usize = 48 << 20; pub(in crate::qwen_forward) mod window_trace { use std::cell::Cell; use std::time::Instant; - pub(in crate::qwen_forward) const NAMES: [&str; 11] = - ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries", "fetch"]; + pub(in crate::qwen_forward) const NAMES: [&str; 13] = + ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries", "fetch", "pcie_spans", "pcie_experts"]; pub(in crate::qwen_forward) const POOL: usize = 0; pub(in crate::qwen_forward) const GPU_SPLIT: usize = 1; pub(in crate::qwen_forward) const PLAN: usize = 2; @@ -48,7 +48,9 @@ pub(in crate::qwen_forward) mod window_trace { pub(in crate::qwen_forward) const EXPERTS: usize = 8; pub(in crate::qwen_forward) const ENTRIES: usize = 9; pub(in crate::qwen_forward) const FETCH: usize = 10; - thread_local! { static SUMS: Cell<[f64; 11]> = const { Cell::new([0.0; 11]) }; } + pub(in crate::qwen_forward) const PCIE_SPANS: usize = 11; + pub(in crate::qwen_forward) const PCIE_EXPERTS: usize = 12; + thread_local! { static SUMS: Cell<[f64; 13]> = const { Cell::new([0.0; 13]) }; } /// A clock only when tracing. pub(in crate::qwen_forward) fn now() -> Option { crate::bringup_trace_enabled().then(Instant::now) @@ -70,8 +72,8 @@ pub(in crate::qwen_forward) mod window_trace { }); } } - pub(in crate::qwen_forward) fn take() -> [f64; 11] { - SUMS.with(|s| s.replace([0.0; 11])) + pub(in crate::qwen_forward) fn take() -> [f64; 13] { + SUMS.with(|s| s.replace([0.0; 13])) } } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index a58d5a19..5b0bd6a9 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -359,6 +359,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { self.pcie_num, sink.staging_capacity(), )?; + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); let mut spans = Vec::new(); spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?; for &e in &split.pcie_experts { @@ -374,6 +375,8 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { None => spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?), } } + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock); + super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64); let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans }); sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?; let include: Vec = split.kinds.iter().map(|&k| k < 0).collect(); From 0a1d4e771e9151ed81b6b9801524f0a7813079cc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 15:30:35 +0200 Subject: [PATCH 7/7] perf(serve): retain each admitted expert's bound route instead of rebinding it per call admitted_expert bound a fresh top-10 route (moe_expert_weights: artifact borrow, topology and seven tensor descriptors) for every CPU and PCIe expert of every group. The route is immutable bound metadata, so it is now kept beside the admitted spans; every use still opens the source scope, which checks the route against the binding and layer and validates the actual gate/up/down descriptors and bank spans. Co-Authored-By: Claude Opus 5.5 --- .../src/qwen_forward/original_serve_pool.rs | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index ea6f5b6d..f3814bc7 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -17,7 +17,7 @@ use super::{ cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace}, input::binding_error, }; -use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole}; use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink}; use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat}; @@ -194,7 +194,16 @@ impl PoolPath { /// stays alive and a later span of the same expert at the same address is the same immutable bytes. struct DirectTier { pool: DirectCpuPool, - admitted: Vec>, + admitted: Vec, +} + +/// One routed expert's retained state: its admitted spans and the route bound to it (a top-10 that selects +/// it in slot 0). The route is immutable bound metadata; every use still opens a source scope that checks +/// it against the binding and the actual descriptors. +#[derive(Default)] +pub(in crate::qwen_forward) struct Admission { + spans: Option<[ResidentExpertBankSpan; 3]>, + route: Option, } /// The all-CPU expert tier over the pinned model's mapped routed weights. @@ -223,7 +232,7 @@ impl<'a> CpuExpertPool<'a> { let pool = DirectCpuPool::new(workers).map_err(|e| runtime_error(native_cpu_error(e)))?; let mut admitted = Vec::new(); admitted.try_reserve_exact(48 * EXPERTS as usize).map_err(|_| Error::InputAllocation)?; - admitted.resize_with(48 * EXPERTS as usize, || None); + admitted.resize_with(48 * EXPERTS as usize, Admission::default); Some(DirectTier { pool, admitted }) } }; @@ -504,7 +513,7 @@ pub(in crate::qwen_forward) fn admitted_expert( binding: &ModelBinding, layer: u32, expert: u32, - admitted: &mut Option<[ResidentExpertBankSpan; 3]>, + admitted: &mut Admission, ) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat))> { let (spans, format, _) = open_expert(binding, layer, expert, admitted, true)?; Ok((spans, format)) @@ -516,16 +525,20 @@ fn open_expert( binding: &ModelBinding, layer: u32, expert: u32, - admitted: &mut Option<[ResidentExpertBankSpan; 3]>, + admission: &mut Admission, admit: bool, ) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat), bool)> { if layer >= 48 || expert >= EXPERTS as u32 { return Err(Error::InvalidExpert); } - // A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`). - let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32); - let bound = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; - let members = [(&bound, 0)]; + if admission.route.is_none() { + // A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`). + let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32); + admission.route = Some(binding.moe_expert_weights(layer, selected).map_err(binding_error)?); + } + let Admission { spans: admitted, route } = admission; + let bound = route.as_ref().ok_or(Error::IdentityMismatch)?; + let members = [(bound, 0)]; binding.with_moe_routed_source(&members, binding_error, |source| { let operation = (|| { source.validate_binding(binding).map_err(binding_error)?;