cpu-service2: pool stage timing (LELEKA_POOL_TIMING=1, cpu.t.* spans), cpu.admit span, tasks-per-thread knob; bit-exact AVX2 q8_k and vectorized token check (LELEKA_Q8K=legacy), register-built multi-token AVX-512 IQ3 decode (LELEKA_IQ_MULTI=legacy); CPU dispatch bench
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
bb2366944f
commit
a2cd2b3acc
@@ -372,6 +372,7 @@ impl DirectTier {
|
||||
between(pool, &opened)?;
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
if !opened[i].2 {
|
||||
let _admit = super::original_serve_profile::span("cpu.admit");
|
||||
source.retarget(&members[i][..]).map_err(binding_error)?;
|
||||
admit_job(source, &mut held[Self::index(layer, expert)?], &opened[i].0)?;
|
||||
}
|
||||
@@ -391,6 +392,7 @@ impl DirectTier {
|
||||
between(pool, &opened)?;
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
if !opened[i].2 {
|
||||
let _admit = super::original_serve_profile::span("cpu.admit");
|
||||
let at = Self::index(layer, expert)?;
|
||||
binding.with_moe_routed_source(&members[i], binding_error, |source| {
|
||||
let admitted = admit_job(source, &mut held[at], &opened[i].0);
|
||||
@@ -640,6 +642,11 @@ impl CpuExpertPool<'_> {
|
||||
});
|
||||
window_trace::lap(window_trace::JOIN, clock);
|
||||
drop(sink_span);
|
||||
if let Some(stages) = tier.pool.take_timing() {
|
||||
for (name, ms) in leleka_native_cpu_expert::POOL_TIMING_NAMES.iter().copied().zip(stages) {
|
||||
super::original_serve_profile::add(name, ms);
|
||||
}
|
||||
}
|
||||
if any_mapped && failure.is_none() && !plan.is_empty() {
|
||||
tier.prefetch.record(use_pass, group_started.elapsed().as_secs_f64() * 1e3 / plan.len() as f64);
|
||||
if let Some(line) = tier.prefetch.status_line() {
|
||||
|
||||
@@ -5,6 +5,7 @@ pub(super) struct NativePool {pool:Option<super::rust_pool::NativePool>}
|
||||
impl NativePool {
|
||||
pub(super) fn new(workers:i32)->Result<Self>{Ok(Self{pool:Some(super::rust_pool::NativePool::new(workers)?)})}
|
||||
pub(super) fn workers(&self)->Result<usize>{self.pool.as_ref().ok_or(Error::Closed)?.workers()}
|
||||
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)}
|
||||
/// 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<()> {
|
||||
|
||||
@@ -127,6 +127,9 @@ pub const MAX_OUT_ROWS: usize = 128;
|
||||
/// 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.
|
||||
/// Names of the stages `DirectCpuPool::take_timing` reports, in order.
|
||||
pub const POOL_TIMING_STAGES: usize = rust_pool::TIMING_STAGES;
|
||||
pub const POOL_TIMING_NAMES: [&str; POOL_TIMING_STAGES] = ["cpu.t.pre", "cpu.t.gu_park0", "cpu.t.gu_publish", "cpu.t.gu_drain", "cpu.t.gu_wait_done", "cpu.t.gu_park1", "cpu.t.requant", "cpu.t.dn_park0", "cpu.t.dn_publish", "cpu.t.dn_drain", "cpu.t.dn_wait_done", "cpu.t.dn_park1", "cpu.t.post"];
|
||||
pub struct DirectCpuPool {
|
||||
native: ffi::NativePool, workers: usize, failed: bool,
|
||||
/// session.cpp `SessionLoopScratch`: the caller (the host loop, which drains beside the workers) is pinned
|
||||
@@ -150,6 +153,8 @@ impl DirectCpuPool {
|
||||
}
|
||||
}
|
||||
pub fn workers(&self) -> usize { self.workers }
|
||||
/// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`).
|
||||
pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { self.native.take_timing() }
|
||||
/// 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<()> {
|
||||
|
||||
@@ -51,14 +51,41 @@ pub(super) unsafe fn dot_multi512(t:i32,row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {
|
||||
macro_rules! by_n {($T:literal)=>{match ys.len(){1=>dot_multi512_tn::<$T,1>(row,ys,out),2=>dot_multi512_tn::<$T,2>(row,ys,out),3=>dot_multi512_tn::<$T,3>(row,ys,out),4=>dot_multi512_tn::<$T,4>(row,ys,out),5=>dot_multi512_tn::<$T,5>(row,ys,out),6=>dot_multi512_tn::<$T,6>(row,ys,out),7=>dot_multi512_tn::<$T,7>(row,ys,out),8=>dot_multi512_tn::<$T,8>(row,ys,out),_=>panic!("dot_multi512: 1..=8 tokens")}}}
|
||||
match t {16=>by_n!(16),17=>by_n!(17),18=>by_n!(18),21=>by_n!(21),22=>by_n!(22),_=>unreachable!()}
|
||||
}}
|
||||
/// `LELEKA_IQ_MULTI=legacy` keeps the stack-array decode in the multi-token AVX-512 IQ3 tree (A/B arm).
|
||||
fn iq3_multi_fast()->bool{static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var("LELEKA_IQ_MULTI").as_deref()!=Ok("legacy"))}
|
||||
/// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l, `decode`'s bytes 4l..4l+4),
|
||||
/// the sign word `decode` returns and its (uniform) 16-bit scale.
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
unsafe fn iq3_half<const T:i32>(b:&[u8],j:usize,h:usize)->(__m256i,u32,i16) {
|
||||
let q=&b[2+16*j+8*h..2+16*j+8*h+8];
|
||||
if T==21 {
|
||||
let high=b[66+2*j+h]as usize;let w=|l:usize|IQ3S_GRID[q[l]as usize|(((high>>l)&1)<<8)]as i32;
|
||||
let sv=b[106+j];
|
||||
(_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),u32(b,74+8*j+4*h),2*(if h==0{sv&15}else{sv>>4})as i16+1)
|
||||
} else {
|
||||
let w=|l:usize|IQ3XXS_GRID[q[l]as usize]as i32;let ws=u32(b,66+8*j+4*h);let mut signs=0u32;for l in 0..4 {signs|=(KSIGNS_IQ2XS[((ws>>(7*l))&127)as usize]as u32)<<(8*l);}
|
||||
(_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),signs,2*(ws>>28)as i16+1)
|
||||
}
|
||||
}
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot_multi512_tn<const T:i32,const N:usize>(row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe {
|
||||
unsafe fn dot_multi512_tn<const T:i32,const N:usize>(row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe {dot_multi512_impl::<T,N>(row,ys,out,iq3_multi_fast())}}
|
||||
/// `fast`: the register-built IQ3 halves (bitwise the stack-array decode, `iq3_multi_trees_are_bitwise_equal`).
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot_multi512_impl<const T:i32,const N:usize>(row:&[u8],ys:&[&[Q8K]],out:&mut [f32],fast:bool) {unsafe {
|
||||
let t=T;
|
||||
assert!(N<=8&&ys.len()==N&&out.len()==N);let nb=ys[0].len();assert_eq!(row.len(),nb*format_bytes(t));let mut af=[_mm512_setzero_ps();8];let zero=_mm512_setzero_si512();
|
||||
for i in 0..nb {let b=&row[i*format_bytes(t)..][..format_bytes(t)];prefetch(b.as_ptr());let mut ai=[_mm512_setzero_si512();8];
|
||||
for j in 0..4 {let (g0,s0,sc0)=decode(t,b,j,0);let (g1,s1,sc1)=decode(t,b,j,1);let mut g=[0u8;64];g[..32].copy_from_slice(&g0);g[32..].copy_from_slice(&g1);let mut sc=[0i16;32];sc[..16].copy_from_slice(&sc0);sc[16..].copy_from_slice(&sc1);
|
||||
for j in 0..4 {
|
||||
// IQ3 formats (`iq3_multi_fast`): both halves' grid words straight into the 512-bit register, lane order = `decode`'s byte order
|
||||
let reg=(T==21||T==18)&&fast&&!super::rust_simd::dispatch().gather;
|
||||
let (gv,sv,m)=if reg {
|
||||
let (g0,s0,c0)=iq3_half::<T>(b,j,0);let (g1,s1,c1)=iq3_half::<T>(b,j,1);
|
||||
(_mm512_inserti64x4::<1>(_mm512_castsi256_si512(g0),g1),_mm512_inserti64x4::<1>(_mm512_castsi256_si512(_mm256_set1_epi16(c0)),_mm256_set1_epi16(c1)),s0 as u64|((s1 as u64)<<32))
|
||||
} else {
|
||||
let (g0,s0,sc0)=decode(t,b,j,0);let (g1,s1,sc1)=decode(t,b,j,1);let mut g=[0u8;64];g[..32].copy_from_slice(&g0);g[32..].copy_from_slice(&g1);let mut sc=[0i16;32];sc[..16].copy_from_slice(&sc0);sc[16..].copy_from_slice(&sc1);
|
||||
let gv=if super::rust_simd::dispatch().gather&&(t==18||t==21){let q=&b[2+16*j..];let mut idx=_mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast()));if t==21{let m=b[66+2*j]as u16|((b[67+2*j]as u16)<<8);idx=_mm512_mask_add_epi32(idx,m,idx,_mm512_set1_epi32(256));}_mm512_i32gather_epi32::<4>(idx,if t==18{IQ3XXS_GRID.as_ptr().cast()}else{IQ3S_GRID.as_ptr().cast()})}else{_mm512_loadu_si512(g.as_ptr().cast())};
|
||||
let sv=_mm512_loadu_si512(sc.as_ptr().cast());let m=s0 as u64|((s1 as u64)<<32);
|
||||
(gv,sv,m)};
|
||||
for k in 0..N {let y=ys[k];let v=_mm512_loadu_si512(y[i].qs.as_ptr().add(64*j).cast());let sy=_mm512_mask_sub_epi8(v,m,zero,v);ai[k]=_mm512_add_epi32(ai[k],_mm512_madd_epi16(_mm512_maddubs_epi16(gv,sy),sv));}
|
||||
}
|
||||
let dx=half(u16(b,0))*factor(t);for k in 0..N {let y=ys[k];af[k]=_mm512_fmadd_ps(_mm512_set1_ps(dx*y[i].d),_mm512_cvtepi32_ps(ai[k]),af[k]);}
|
||||
@@ -198,9 +225,13 @@ mod tests {
|
||||
}
|
||||
if super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok() {
|
||||
let y2=random_act(nb,0.01,&mut seed);let ys=[y.as_slice(),y2.as_slice()];let start=std::time::Instant::now();let mut s=0.0f32;
|
||||
for r in w.chunks_exact(rb){let mut o=[0.0f32;2];unsafe {dot_multi512(t,r,&ys,&mut o);}s+=o[0];}
|
||||
for r in w.chunks_exact(rb){let mut o=[0.0f32;2];unsafe {dot_multi512_impl::<21,2>(r,&ys,&mut o,false);}s+=o[0];}
|
||||
let el=start.elapsed().as_secs_f64();
|
||||
eprintln!("pass {pass} multi512 x2: {:.1} us per expert gate+up (sum {s})",el*1e6/experts as f64);
|
||||
eprintln!("pass {pass} multi512 x2 stack: {:.1} us per expert gate+up (sum {s})",el*1e6/experts as f64);
|
||||
let start=std::time::Instant::now();let mut s=0.0f32;
|
||||
for r in w.chunks_exact(rb){let mut o=[0.0f32;2];unsafe {dot_multi512_impl::<21,2>(r,&ys,&mut o,true);}s+=o[0];}
|
||||
let el=start.elapsed().as_secs_f64();
|
||||
eprintln!("pass {pass} multi512 x2 register: {:.1} us per expert gate+up (sum {s})",el*1e6/experts as f64);
|
||||
}
|
||||
// the down rows of the same experts: H=2560 rows of IQ4_NL over FF=640 (20 blocks of 18 bytes), one token
|
||||
let dn=random_iq4nl(2560*experts,20,&mut seed);let hq=random_q8zero(20,&mut seed);let start=std::time::Instant::now();let mut s=0.0f32;
|
||||
@@ -216,6 +247,19 @@ mod tests {
|
||||
fn random_q8zero(nb:usize,seed:&mut u64)->Vec<Q8Zero> {
|
||||
let mut v=vec![Q8Zero::default();nb];for b in v.iter_mut(){b.d=0x3c00;for q in b.qs.iter_mut(){*q=xorshift(seed)as i8;}}v
|
||||
}
|
||||
#[test]
|
||||
fn iq3_multi_trees_are_bitwise_equal() {
|
||||
if !(super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok()){eprintln!("SKIP: AVX-512");return;}
|
||||
let mut seed=0x3e3e_5eed_7777_0001u64;let nb=10usize;
|
||||
macro_rules! cmp {($T:literal,$N:literal,$w:expr,$ys:expr)=>{{let mut a=[0.0f32;$N];let mut b=[0.0f32;$N];
|
||||
for r in $w.chunks_exact(nb*format_bytes($T)) {unsafe {dot_multi512_impl::<$T,$N>(r,&$ys[..$N],&mut a,false);dot_multi512_impl::<$T,$N>(r,&$ys[..$N],&mut b,true);}
|
||||
for k in 0..$N {assert_eq!(a[k].to_bits(),b[k].to_bits(),"type {} tokens {} token {k}",$T,$N);}}}}}
|
||||
for round in 0..6 {
|
||||
let acts:Vec<Vec<Q8K>>=(0..4).map(|k|random_act(nb,0.0003+(round*4+k) as f32*0.21,&mut seed)).collect();let ys:Vec<&[Q8K]>=acts.iter().map(|y|y.as_slice()).collect();
|
||||
let w21=random_rows(21,nb,32,&mut seed);let w18=random_rows(18,nb,32,&mut seed);
|
||||
cmp!(21,1,w21,ys);cmp!(21,2,w21,ys);cmp!(21,3,w21,ys);cmp!(21,4,w21,ys);cmp!(18,1,w18,ys);cmp!(18,2,w18,ys);cmp!(18,3,w18,ys);cmp!(18,4,w18,ys);
|
||||
}
|
||||
}
|
||||
// IQ4_XS gate/up rows at two or more tokens on the AVX2 tree take the multi-token kernel (iq_avx2.cpp iq256_gu_rows, native_expert.cpp
|
||||
// `!cpu512 && iq256_supported(23)`), not ggml's single-token dot: its last bits differ, and a Q2_0 down projection (not requantized
|
||||
// to int8 as IQ4_NL's is) exposed it in KAB1 (STRA-324: cases 23-42-r2/r3/r8).
|
||||
|
||||
@@ -38,6 +38,8 @@ struct Shared {
|
||||
// panicking worker never reaches `done`, so the host aborts after 60 s instead of returning to the caller.
|
||||
unsafe impl Sync for Shared {}
|
||||
unsafe impl Send for Shared {}
|
||||
/// `!any(|v| !v.is_finite())` as a branch-free exponent fold that vectorizes (`LELEKA_Q8K=legacy` keeps the element-wise scan).
|
||||
fn all_finite(v:&[f32])->bool{if !super::rust_quant::q8k_fast(){return !v.iter().any(|x|!x.is_finite());}let mut bad=0u32;for c in v.chunks(256){let mut m=0u32;for x in c{m|=u32::from(x.to_bits()&0x7f80_0000==0x7f80_0000);}bad|=m;}bad==0}
|
||||
fn allocated<T:Default>(n:usize)->Result<Vec<T>>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,T::default);Ok(v)}
|
||||
impl Shared {
|
||||
fn publish(&self){self.epoch.0.fetch_add(1,Ordering::SeqCst);if self.sleepers.0.load(Ordering::SeqCst)!=0{let _lock=self.sleep_mu.lock().unwrap_or_else(|p|p.into_inner());self.sleep_cv.notify_all();}}
|
||||
@@ -84,15 +86,30 @@ impl Shared {
|
||||
fn wait_parked(&self){let mut spins=0u32;let mut t=Instant::now();while self.parked.0.load(Ordering::Acquire)!=self.n as u32 {std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue;}if spins==1024{t=Instant::now();}else if t.elapsed()>Duration::from_secs(60){eprintln!("strata: the CPU expert pool stalled waiting for workers to park");std::process::abort();}}}
|
||||
fn wait_done(&self,n:usize){let mut spins=0u32;let mut seen=0u32;let mut t=Instant::now();loop{let d=self.done.0.load(Ordering::Acquire);if d>=n as u32{return;}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue;}if spins==1024||d!=seen{t=Instant::now();seen=d;}else if t.elapsed()>Duration::from_secs(60){eprintln!("strata: the CPU expert pool stalled waiting for jobs");std::process::abort();}}}
|
||||
}
|
||||
pub(super) struct NativePool{shared:Arc<Shared>,workers:Vec<thread::JoinHandle<()>>}
|
||||
/// `LELEKA_POOL_TIMING=1`: wall time of the host's stages of `compute_borrowed`, summed over calls until taken (ms):
|
||||
/// 0 pre (validation, token quantization, job table), 1-5 gate/up phase (park wait before, publish, host drain, wait done, park wait after),
|
||||
/// 6 host requantization, 7-11 down phase (same five), 12 post (output check). Off: no clock is read.
|
||||
pub const TIMING_STAGES:usize=13;
|
||||
/// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is an A/B knob: every row is
|
||||
/// computed by the same code whatever task holds it, so the output does not depend on it.
|
||||
fn tasks_per_thread()->usize{static V:std::sync::OnceLock<usize>=std::sync::OnceLock::new();*V.get_or_init(||std::env::var("LELEKA_POOL_TASKS_PER_THREAD").ok().and_then(|v|v.parse().ok()).filter(|v|(1..=16).contains(v)).unwrap_or(3))}
|
||||
pub(super) struct NativePool{shared:Arc<Shared>,workers:Vec<thread::JoinHandle<()>>,timing:Option<[f64;TIMING_STAGES]>}
|
||||
impl NativePool {
|
||||
pub fn new(workers:i32)->Result<Self>{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)?,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)
|
||||
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};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<usize>{Ok(self.workers.len())}
|
||||
fn phase(&mut self,mode:u32,rows:usize){self.shared.wait_parked();let tasks=3*(self.shared.n+1);/* SAFETY: wait_parked() above proves every worker finished its previous drain and holds no claim, so the host is the only accessor of `batch` until the Release store of `head` below publishes it. */unsafe {let b=&mut*self.shared.batch.get();b.mode=mode;b.rows=rows;b.tasks=tasks;}self.shared.done.0.store(0,Ordering::Relaxed);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();self.shared.drain(e);self.shared.wait_done(tasks);self.shared.wait_parked();}
|
||||
fn phase(&mut self,mode:u32,rows:usize){self.phase_timed(mode,rows,0)}
|
||||
/// `at`: first of the five timing stages of this phase (ignored when timing is off).
|
||||
fn phase_timed(&mut self,mode:u32,rows:usize,at:usize){
|
||||
let on=self.timing.is_some();let mut t=[None;6];let mut lap=|i:usize|{if on{t[i]=Some(Instant::now());}};
|
||||
lap(0);self.shared.wait_parked();lap(1);let tasks=tasks_per_thread()*(self.shared.n+1);/* SAFETY: wait_parked() above proves every worker finished its previous drain and holds no claim, so the host is the only accessor of `batch` until the Release store of `head` below publishes it. */unsafe {let b=&mut*self.shared.batch.get();b.mode=mode;b.rows=rows;b.tasks=tasks;}self.shared.done.0.store(0,Ordering::Relaxed);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();lap(2);self.shared.drain(e);lap(3);self.shared.wait_done(tasks);lap(4);self.shared.wait_parked();lap(5);
|
||||
if let Some(acc)=self.timing.as_mut(){for i in 0..5{if let (Some(a),Some(b))=(t[i],t[i+1]){acc[at+i]+=b.duration_since(a).as_secs_f64()*1e3;}}}
|
||||
}
|
||||
/// 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]))}
|
||||
pub fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> {
|
||||
if !(1..=MAX_JOBS).contains(&jobs.len()){return Err(Error::Shape);}let gu=jobs[0].gu;let down=jobs[0].down;if jobs.iter().any(|j|j.gu!=gu||j.down!=down){return Err(Error::Shape);}let f=NativeFmt::new(gu.kind(),down.kind())?;
|
||||
// Validate the ENTIRE batch before touching quantized operands or publication.
|
||||
@@ -107,10 +124,11 @@ impl NativePool {
|
||||
/// 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);
|
||||
self.phase_timed(5,count*FF,1);let t=self.timing.is_some().then(Instant::now);
|
||||
// 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);
|
||||
if let (Some(t),Some(acc))=(t,self.timing.as_mut()){acc[6]+=t.elapsed().as_secs_f64()*1e3;}
|
||||
self.phase_timed(6,count*H,7);
|
||||
}
|
||||
/// 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
|
||||
@@ -132,7 +150,7 @@ impl NativePool {
|
||||
/// 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;
|
||||
let t_pre=self.timing.is_some().then(Instant::now);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.
|
||||
@@ -146,21 +164,24 @@ impl NativePool {
|
||||
written[row/64]|=1<<(row%64);used[token]=true;
|
||||
}
|
||||
}
|
||||
if tokens.iter().any(|x|!x.is_finite()){return Err(Error::NonFinite);}
|
||||
if !all_finite(tokens){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);}}
|
||||
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 if super::rust_quant::q8k_fast(){super::rust_quant::q8_k_avx2(x,&mut tn[t].q);}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);}
|
||||
}
|
||||
}
|
||||
if let (Some(t),Some(acc))=(t_pre,self.timing.as_mut()){acc[0]+=t.elapsed().as_secs_f64()*1e3;}
|
||||
self.run_published(f,experts.len());
|
||||
let t_post=self.timing.is_some().then(Instant::now);
|
||||
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);}}}
|
||||
if let (Some(t),Some(acc))=(t_post,self.timing.as_mut()){acc[12]+=t.elapsed().as_secs_f64()*1e3;}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,33 @@ pub(super) fn q8_k(x:&[f32],y:&mut [Q8K]) {
|
||||
y.d=1.0/iscale;
|
||||
}
|
||||
}
|
||||
/// `LELEKA_Q8K=legacy` keeps the scalar `q8_k` on the borrowed-group path (A/B arm); the default there is `q8_k_avx2`.
|
||||
pub(super) fn q8k_fast()->bool{static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var("LELEKA_Q8K").as_deref()!=Ok("legacy"))}
|
||||
/// `q8_k` with the 256 products, roundings and the clamp in 256-bit lanes: the same IEEE multiply `iscale*x`, the same magic-number
|
||||
/// `nearest_int` (add 12582912, mantissa bits), `min(127)`; the signed maximum is the FIRST element of largest magnitude (the scalar loop's
|
||||
/// strict `>`), `d = 1/iscale`, `bsums` summed as before, and an all-zero block leaves `bsums` as the scalar one does. Inputs must be finite
|
||||
/// (the caller's check), so no NaN reaches the maximum. Bitwise `q8_k` (`q8_k_avx2_is_bitwise_q8_k`).
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q8_k_avx2(x:&[f32],y:&mut [Q8K]) {unsafe {
|
||||
assert_eq!(x.len(),256*y.len());
|
||||
for (xb,y) in x.chunks_exact(256).zip(y) {
|
||||
let sign=_mm256_set1_ps(-0.0);let mut m=_mm256_setzero_ps();
|
||||
for c in 0..32 {m=_mm256_max_ps(m,_mm256_andnot_ps(sign,_mm256_loadu_ps(xb.as_ptr().add(8*c))));}
|
||||
let mut h=_mm_max_ps(_mm256_extractf128_ps::<1>(m),_mm256_castps256_ps128(m));h=_mm_max_ps(h,_mm_movehl_ps(h,h));h=_mm_max_ss(h,_mm_movehdup_ps(h));
|
||||
let amax=_mm_cvtss_f32(h);
|
||||
if amax==0.0 {y.d=0.0;y.qs.fill(0);continue;}
|
||||
let max=*xb.iter().find(|v|v.abs()==amax).unwrap_or(&amax);
|
||||
let iscale=-127.0/max;let vs=_mm256_set1_ps(iscale);let magic=_mm256_set1_ps(12_582_912.0);let mant=_mm256_set1_epi32(0x007f_ffff);let bias=_mm256_set1_epi32(0x0040_0000);let top=_mm256_set1_epi32(127);
|
||||
let q=|c:usize|{let v=_mm256_add_ps(_mm256_mul_ps(vs,_mm256_loadu_ps(xb.as_ptr().add(8*c))),magic);_mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(v),mant),bias),top)};
|
||||
for g in 0..8 {
|
||||
let a=_mm256_packs_epi32(q(4*g),q(4*g+1));let b=_mm256_packs_epi32(q(4*g+2),q(4*g+3));
|
||||
let p=_mm256_permutevar8x32_epi32(_mm256_packs_epi16(a,b),_mm256_setr_epi32(0,4,1,5,2,6,3,7));
|
||||
_mm256_storeu_si256(y.qs.as_mut_ptr().add(32*g).cast(),p);
|
||||
}
|
||||
for (sum,q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)){*sum=q.iter().map(|&v|v as i32).sum::<i32>() as i16;}
|
||||
y.d=1.0/iscale;
|
||||
}
|
||||
}}
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q8_zero(x:&[f32],y:&mut [Q8Zero]) {unsafe {
|
||||
assert_eq!(x.len(),32*y.len());
|
||||
@@ -99,3 +126,26 @@ mod tests {
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod q8k_tests {
|
||||
use super::*;
|
||||
fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s}
|
||||
#[test]
|
||||
fn q8_k_avx2_is_bitwise_q8_k() {
|
||||
if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP");return;}
|
||||
let mut seed=0x7a11_5eed_0102_0304u64;
|
||||
for round in 0..400 {
|
||||
let nb=10;let scale=[1e-6f32,1e-3,0.5,3.0,1e3,3e4][round%6];
|
||||
let mut x:Vec<f32>=(0..nb*256).map(|_|((xorshift(&mut seed)%200001)as f32-100000.0)*scale/1e5).collect();
|
||||
// ties of magnitude with both signs, zero blocks, rounding-half cases
|
||||
if round%5==1 {x[3]=7.0*scale;x[200]=-7.0*scale;for v in x[256..512].iter_mut(){*v=0.0;}}
|
||||
if round%5==2 {let m=x[..256].iter().fold(0.0f32,|a,v|a.max(v.abs()));x[10]=-m;x[11]=m;}
|
||||
if round%5==3 {for (i,v) in x.iter_mut().enumerate().take(256){*v=(i as f32-128.0)*0.5;}}
|
||||
let mut a=vec![Q8K::default();nb];let mut b=vec![Q8K::default();nb];
|
||||
for (i,(p,q)) in a.iter_mut().zip(b.iter_mut()).enumerate(){p.bsums=[i as i16;16];q.bsums=[i as i16;16];}
|
||||
q8_k(&x,&mut a);unsafe {q8_k_avx2(&x,&mut b);}
|
||||
for (i,(p,q)) in a.iter().zip(&b).enumerate(){assert_eq!(p.d.to_bits(),q.d.to_bits(),"d round {round} block {i}");assert_eq!(p.qs,q.qs,"qs round {round} block {i}");assert_eq!(p.bsums,q.bsums,"bsums round {round} block {i}");}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Model-free timing of the serve path's CPU expert dispatch (`DirectCpuPool::compute_group`, the call one verify-window layer makes):
|
||||
//! IQ3_S gate/up and IQ4_NL down experts of the Flash-Next shape (H 2560, FF 640) with random valid blocks, cycled over EXPERTS distinct
|
||||
//! experts (default 256, ~600 MB, past every L3) so every call reads its weights from DRAM as the decode does. Prints microseconds per call
|
||||
//! and, with LELEKA_POOL_TIMING=1, the host's stage split (see `POOL_TIMING_NAMES`).
|
||||
//!
|
||||
//! BENCH_WORKERS (default 15) BENCH_EXPERTS (default 256) BENCH_CALLS (default 2000)
|
||||
//! LELEKA_POOL_TIMING=1 cargo test --release -p leleka-native-cpu-expert --test cpu_service_bench -- --ignored --nocapture
|
||||
use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, POOL_TIMING_NAMES};
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
const TOP_K: usize = 10;
|
||||
|
||||
fn env_usize(name: &str, default: usize) -> usize {
|
||||
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Random blocks of `block` bytes with a finite FP16 scale of 2^-12..2^-9 in the first two bytes.
|
||||
fn blocks(rng: &mut Rng, count: usize, block: usize) -> Vec<u8> {
|
||||
let mut v = vec![0u8; count * block];
|
||||
for chunk in v.chunks_exact_mut(8) {
|
||||
chunk.copy_from_slice(&rng.next().to_le_bytes());
|
||||
}
|
||||
for b in v.chunks_exact_mut(block) {
|
||||
let e = 3 + (rng.next() % 4) as u16;
|
||||
let m = (rng.next() & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
struct Expert {
|
||||
gate: Vec<u8>,
|
||||
up: Vec<u8>,
|
||||
down: Vec<u8>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark; no model"]
|
||||
fn cpu_service_bench() {
|
||||
let workers = env_usize("BENCH_WORKERS", 15) as i32;
|
||||
let n_experts = env_usize("BENCH_EXPERTS", 256);
|
||||
let calls = env_usize("BENCH_CALLS", 2000);
|
||||
let mut rng = Rng(0x5eed_cafe_f00d_1234);
|
||||
let experts: Vec<Expert> = (0..n_experts)
|
||||
.map(|_| Expert { gate: blocks(&mut rng, FF * H / 256, 110), up: blocks(&mut rng, FF * H / 256, 110), down: blocks(&mut rng, H * FF / 32, 18) })
|
||||
.collect();
|
||||
let mut pool = match DirectCpuPool::new(workers) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!("SKIP: pool did not start ({e:?})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let tokens_max = 4usize;
|
||||
let tokens: Vec<f32> = (0..tokens_max * H).map(|_| (rng.next() % 2001) as f32 / 1000.0 - 1.0).collect();
|
||||
let mut out = vec![0.0f32; tokens_max * TOP_K * H];
|
||||
// (label, rows in the window, per expert: the token rows it serves)
|
||||
let shapes: [(&str, usize, &[&[usize]]); 5] = [
|
||||
("1 expert x 1 token", 1, &[&[0]]),
|
||||
("2 experts x 1 token", 2, &[&[0], &[1]]),
|
||||
("3 experts x 1 token", 3, &[&[0], &[1], &[2]]),
|
||||
("1 expert x 2 tokens", 2, &[&[0, 1]]),
|
||||
("1 expert x 3 tokens", 3, &[&[0, 1, 2]]),
|
||||
];
|
||||
for pass in 0..2 {
|
||||
for (label, rows, members) in shapes {
|
||||
let mut next = 0usize;
|
||||
let _ = pool.take_timing();
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..calls {
|
||||
let pairs: Vec<Vec<(usize, usize)>> = members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect();
|
||||
let group_experts: Vec<BorrowedExpert<'_>> = pairs
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let x = &experts[next % n_experts];
|
||||
next += 1;
|
||||
BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: p }
|
||||
})
|
||||
.collect();
|
||||
let group = BorrowedGroup { tokens: &tokens[..rows * H], experts: &group_experts, stride: TOP_K };
|
||||
pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..rows * TOP_K * H]).expect("compute_group");
|
||||
}
|
||||
let us = start.elapsed().as_secs_f64() * 1e6 / calls as f64;
|
||||
let n = members.len() as f64;
|
||||
let mut line = format!("pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", us / n, n * 2.33e6 / us / 1e3);
|
||||
if let Some(t) = pool.take_timing() {
|
||||
line.push_str(" |");
|
||||
for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) {
|
||||
line.push_str(&format!(" {}={:.1}", name.trim_start_matches("cpu.t."), ms * 1e3 / calls as f64));
|
||||
}
|
||||
}
|
||||
eprintln!("{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user