diff --git a/crates/cuda-driver/src/original_verify_mapped.rs b/crates/cuda-driver/src/original_verify_mapped.rs index 63c1e5d5..8fe57ed3 100644 --- a/crates/cuda-driver/src/original_verify_mapped.rs +++ b/crates/cuda-driver/src/original_verify_mapped.rs @@ -41,6 +41,30 @@ mod enabled { unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } + /// Every value finite (no infinity, no NaN): the same predicate as `!any(|v| !v.is_finite())`, written as a branch-free + /// fold over the exponent bits so it vectorizes (the per-element early exit of `any` does not); it runs over a whole + /// verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode critical path. + /// `LELEKA_SINK_SCAN=legacy` (A/B arm) keeps the element-wise `any` scan. + pub(crate) fn all_finite(rows:&[f32])->bool{ + static LEGACY:std::sync::OnceLock=std::sync::OnceLock::new(); + if *LEGACY.get_or_init(||std::env::var("LELEKA_SINK_SCAN").as_deref()==Ok("legacy")){return !rows.iter().any(|v|!v.is_finite())} + let mut bad=0u32; + for chunk in rows.chunks(256){let mut m=0u32;for v in chunk{m|=u32::from(v.to_bits()&0x7f80_0000==0x7f80_0000);}bad|=m;} + bad==0 + } + #[cfg(test)] + #[test] + fn all_finite_is_the_is_finite_predicate(){ + let specials=[0.0f32,-0.0,1.0,-3.0e38,f32::MAX,f32::MIN_POSITIVE,1e-45,f32::INFINITY,f32::NEG_INFINITY,f32::NAN,-f32::NAN,f32::from_bits(0x7f80_0001),f32::from_bits(0xffc0_0000)]; + for len in [0usize,1,7,255,256,257,1000]{ + for at in [0usize,len/2,len.saturating_sub(1)]{ + for &s in &specials{ + let mut v=vec![0.5f32;len];if len>0{v[at]=s;} + assert_eq!(all_finite(&v),!v.iter().any(|x|!x.is_finite()),"len {len} at {at} value {:#x}",s.to_bits()); + } + } + } + } pub(crate) struct MappedAllocation { library: Option, host: Option, @@ -134,7 +158,7 @@ mod enabled { // Only the controller's just-observed group doorbell can construct // this borrow. GPU miss consumers still wait for its unpublished M. let rows=unsafe{std::slice::from_raw_parts_mut(p as *mut f32,count)}; - let result=produce(rows)?;if rows.iter().any(|v|!v.is_finite()){return Err(Error::NonFiniteMmqOutput("Original Verifier CPU misses"))}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(result) + let result=produce(rows)?;if !all_finite(rows){return Err(Error::NonFiniteMmqOutput("Original Verifier CPU misses"))}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(result) } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { diff --git a/crates/native-cpu-expert/src/rust_iq.rs b/crates/native-cpu-expert/src/rust_iq.rs index 45535944..445f88bf 100644 --- a/crates/native-cpu-expert/src/rust_iq.rs +++ b/crates/native-cpu-expert/src/rust_iq.rs @@ -65,13 +65,55 @@ unsafe fn dot_multi512_tn(row:&[u8],ys:&[&[Q8K]],out: } for k in 0..N {out[k]=_mm512_reduce_add_ps(af[k]);} }} +/// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS (A/B arm); the default is the +/// register-built tree below (`dot_single_iq3`), the same integer lanes and float operations, so the same bits. +fn iq3_single_fast()->bool { + static ON:std::sync::OnceLock=std::sync::OnceLock::new(); + *ON.get_or_init(||std::env::var("LELEKA_IQ_SINGLE").as_deref()!=Ok("legacy")) +} // GGML AVX2 T1: two alternating exact integer accumulators, factor AFTER final reduction. #[target_feature(enable="avx2,fma,f16c")] pub(super) unsafe fn dot_single(t:i32,row:&[u8],y:&[Q8K])->f32 {unsafe { if t==23{return iq4xs(row,y);} + if (t==21||t==18)&&iq3_single_fast(){return if t==21{dot_single_iq3::<21>(row,y)}else{dot_single_iq3::<18>(row,y)};} + dot_single_generic(t,row,y) +}} +// The generic tree (decode into stack arrays, then load): the pre-2026-10-31 path of every single-token IQ row. +#[target_feature(enable="avx2,fma,f16c")] +unsafe fn dot_single_generic(t:i32,row:&[u8],y:&[Q8K])->f32 {unsafe { let mut af=_mm256_setzero_ps();for (i,b) in row.chunks_exact(format_bytes(t)).enumerate(){let mut a=[_mm256_setzero_si256();2];for j in 0..4 {for h in 0..2 {let (g,s,sc)=decoded(t,b,j,h);let q=_mm256_loadu_si256(y[i].qs.as_ptr().add(64*j+32*h).cast());a[h]=_mm256_add_epi32(a[h],_mm256_madd_epi16(_mm256_maddubs_epi16(g,_mm256_sign_epi8(q,s)),sc));}}let d=half(u16(b,0))*y[i].d;af=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(_mm256_add_epi32(a[0],a[1])),af);} factor(t)*hsum_ggml(af) }} +/// IQ3_S (21) / IQ3_XXS (18), one token: `dot_single_generic`'s tree with the 32 magnitude bytes of a half built in a +/// register (`_mm256_setr_epi32` of the eight grid words: lane l = grid word l, the bytes `decode` writes at 4l..4l+4), +/// the same sign mask (`signs32`), the same per-half 16-bit scale broadcast, the same two exact i32 accumulators and the +/// same per-block FMA and final reduction. Only where the bytes live between decode and use changes (no stack round trip, +/// no per-half `match`), so every lane, and the result, is bit for bit the generic one's (`iq3_single_trees_are_bitwise_equal`). +/// Bounds: `row` is walked by `chunks_exact(format_bytes(T))`, every offset below is inside a 110/98-byte block, `y[i]` is checked. +#[target_feature(enable="avx2,fma,f16c")] +unsafe fn dot_single_iq3(row:&[u8],y:&[Q8K])->f32 {unsafe { + let mut af=_mm256_setzero_ps(); + for (i,b) in row.chunks_exact(format_bytes(T)).enumerate(){ + let yi=&y[i];let mut a=[_mm256_setzero_si256();2]; + for j in 0..4 {for h in 0..2 { + let q=&b[2+16*j+8*h..2+16*j+8*h+8]; + let (g,s,sc)=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];let s0=2*(if h==0{sv&15}else{sv>>4})as i16+1; + (_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),s0) + } 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) + }; + let v=_mm256_loadu_si256(yi.qs.as_ptr().add(64*j+32*h).cast()); + a[h]=_mm256_add_epi32(a[h],_mm256_madd_epi16(_mm256_maddubs_epi16(g,_mm256_sign_epi8(v,signs32(s))),_mm256_set1_epi16(sc))); + }} + let d=half(u16(b,0))*yi.d;af=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(_mm256_add_epi32(a[0],a[1])),af); + } + factor(T)*hsum_ggml(af) +}} #[target_feature(enable="avx2,fma,f16c")] unsafe fn iq4xs(row:&[u8],y:&[Q8K])->f32 {unsafe { let values=_mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast());let m4=_mm_set1_epi8(15);let mut af=_mm256_setzero_ps(); @@ -114,6 +156,66 @@ mod tests { } let h=[acc[0]+acc[4],acc[1]+acc[5],acc[2]+acc[6],acc[3]+acc[7]];(h[0]+h[1])+(h[2]+h[3]) } + fn random_rows(t:i32,nb:usize,rows:usize,seed:&mut u64)->Vec { + let bytes=format_bytes(t);let mut row=vec![0u8;rows*nb*bytes];for v in row.iter_mut(){*v=xorshift(seed)as u8;} + for b in row.chunks_exact_mut(bytes){let e=8+(xorshift(seed)%8)as u16;let m=(xorshift(seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} + row + } + fn random_act(nb:usize,scale:f32,seed:&mut u64)->Vec { + let x:Vec=(0..nb*256).map(|_|((xorshift(seed)%20001)as f32-10000.0)*scale).collect();let mut y=vec![Q8K::default();nb];q8_k(&x,&mut y);y + } + // The register-built IQ3 single-token tree against the generic one: every row of random blocks (all grid indices, high + // bits, sign words and scales) and activations of several magnitudes, compared bit for bit. + #[test] + fn iq3_single_trees_are_bitwise_equal() { + if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} + let mut seed=0x1d3_5eed_0bad_cafeu64;let nb=10usize; + for t in [21,18] { + for round in 0..8 { + let rows=64;let w=random_rows(t,nb,rows,&mut seed);let y=random_act(nb,0.0001+round as f32*0.37,&mut seed); + for r in w.chunks_exact(nb*format_bytes(t)) { + // SAFETY: avx2_ok() above; every row is nb whole blocks and y has nb blocks. + let (a,b)=unsafe {(dot_single_generic(t,r,&y),if t==21{dot_single_iq3::<21>(r,&y)}else{dot_single_iq3::<18>(r,&y)})}; + assert_eq!(a.to_bits(),b.to_bits(),"type {t} round {round}"); + } + } + } + } + // Throughput of one token's gate+up rows (FF=640 rows x 2 matrices of H=2560) over 48 distinct experts (past the L3), + // generic against register-built, one thread. `cargo test --release -p leleka-native-cpu-expert iq3_single_bench -- --ignored --nocapture` + #[test] + #[ignore = "benchmark"] + fn iq3_single_bench() { + if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP");return;} + let mut seed=42u64;let nb=10usize;let t=21;let experts=48usize;let rows=1280usize; + let w=random_rows(t,nb,rows*experts,&mut seed);let y=random_act(nb,0.01,&mut seed);let rb=nb*format_bytes(t); + for pass in 0..3 { + for (name,fast) in [("generic",false),("iq3",true)] { + let start=std::time::Instant::now();let mut s=0.0f32; + for r in w.chunks_exact(rb){s+=unsafe {if fast{dot_single_iq3::<21>(r,&y)}else{dot_single_generic(t,r,&y)}};} + let el=start.elapsed().as_secs_f64(); + eprintln!("pass {pass} {name}: {:.1} us per expert gate+up, {:.2} GB/s (sum {s})",el*1e6/experts as f64,w.len()as f64/el/1e9); + } + 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];} + 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); + } + // 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; + for r in dn.chunks_exact(20*18){let mut o=[0.0f32];unsafe {iq4nl(r,&[hq.as_slice()],&mut o,true);}s+=o[0];} + let el=start.elapsed().as_secs_f64(); + eprintln!("pass {pass} iq4nl down x1: {:.1} us per expert down, {:.2} GB/s (sum {s})",el*1e6/experts as f64,dn.len()as f64/el/1e9); + } + } + fn random_iq4nl(rows:usize,nb:usize,seed:&mut u64)->Vec { + let mut v=vec![0u8;rows*nb*18];for x in v.iter_mut(){*x=xorshift(seed)as u8;} + for b in v.chunks_exact_mut(18){let e=8+(xorshift(seed)%8)as u16;let m=(xorshift(seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());}v + } + fn random_q8zero(nb:usize,seed:&mut u64)->Vec { + 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 + } // 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).