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). diff --git a/docs/experiments/cpu-service-5090.md b/docs/experiments/cpu-service-5090.md new file mode 100644 index 00000000..fb3e4961 --- /dev/null +++ b/docs/experiments/cpu-service-5090.md @@ -0,0 +1,82 @@ +# 5090 decode: CPU expert service inside the verify window (claude/cpu-service) + +Date 2026-10-31. RTX 5090, Ryzen 9 9950X3D, frozen corpus, upstream ranked profile, 5 turns to ~245k, seed OFF, auto slots (12,192). Base = `main` 8c8c6725d. Labels: M measured in the run named, E estimate. +Follows [vram-footprint3-5090](vram-footprint3-5090.md) section 5 ("the ~3 ms window deficit is not a hit-rate deficit"). + +## 1. Result + +| item | class | status | effect (paired, 5 rotated blocks) | +| --- | --- | --- | --- | +| register-built single-token IQ3_S / IQ3_XXS dot (`rust_iq::dot_single_iq3`) + vectorized finiteness scan of the group's CPU output (`all_finite`) | lossless, bitwise (353/353 rows) | **default ON** on the branch; `LELEKA_IQ_SINGLE=legacy` and `LELEKA_SINK_SCAN=legacy` restore main | tok/s **+6.34 %** (5/5 blocks, +3.8..+10.3), ms/round **-0.27** (5/5, -0.03..-0.41), ms/token -5.7 % | +| `LELEKA_OPEN_CACHE=on` (existing opt-in) on top | lossless, bitwise | stays opt-in | over the new path: +0.75 % tok/s (2/5 positive), ms/round -0.01: neutral | +| PCIe share 0.35 (vanilla's PcieAuto value) on top | placement | stays off, no gate run | over the new path: **-1.37 %** tok/s (2/5), ms/round **+0.43** (5/5 worse): negative | + +Harness caveat found on the way: `scripts/e2e/run-e2e.sh` exports `LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55` by default, so every harness A/B of ours (footprint2/3, this one, the baseline pair) ran PCIe share 0.55, not the product default 0.45 (`original_serve_residency.rs`). M (file read). + +## 2. Attribution of the window deficit (before the change) + +Per round, turns 3-5, the 9 base runs of `runs/footprint3-ab` (27 requests), from `DBG profile request` spans. M. + +| span | ms/round | note | +| --- | ---: | --- | +| `window.verifier` | 12.00 | | +| `drv.doorbell_wait` (GPU reaches the next layer's router) | 8.15 | vanilla "GPU-reach wait" 8.5-9.0 (`runs/s1-decode/v-nsk-prof`) | +| host work in the 48 layer callbacks | 3.31 | vanilla "per-layer host" 1.24-1.48 incl. its CPU 1.10-1.33 | +| - `cpu.compute` (the two pool phases) | 1.99 | **~81 us per CPU expert** (window regression, 6,637 windows); vanilla 44 us (its PcieAuto line) | +| - `cpu.sink` minus compute and zero (the `any(!is_finite)` scan of rows x 10 x 2,560 floats, every layer) | 0.59 | 0.30 ms per window per row; vanilla has no such scan | +| - `cpu.open` (per-expert source scope) | 0.33 | | +| - `pool.spans` + `pool.publish_plan` + `pool.split` + `cpu.zero` | 0.39 | | +| `drv.sync_compute` (last layer + head) | 0.45 | | + +Window-level regression (base windows; total = GPU wait + host): +81 us host per CPU expert but only +38 us on the window, because the GPU's own MoE work after the doorbell (~55 us a layer: +shared expert, VRAM experts) runs under the host's callback; +67 us per PCIe expert; +1.13 ms per extra row. So host time pays fully only on layers whose CPU work outlasts the GPU's. + +Cause of the 81 us: `dot_single` (one token per expert, ~90 % of CPU experts) decoded every 32 weights into stack arrays (`decode` -> `decoded`, a store-forward stall per half and a runtime +format `match`) before loading them: 0.94-1.0 GB/s per core on the laptop i9-11900H against 3.4-3.7 GB/s for the same tree with the grid words placed with `_mm256_setr_epi32` +(`iq3_single_bench`, 48 experts past L3, gate+up 1,430 -> 400 us per expert per core). M (laptop). + +## 3. Change + +* `crates/native-cpu-expert/src/rust_iq.rs`: `dot_single_iq3::<21|18>`: the same byte layout (lane l = grid word l), the same `signs32` mask, the same per-half scale broadcast, the same two i32 accumulators, + per-block FMA and `hsum_ggml`; only the decode-to-register path changes. Test `iq3_single_trees_are_bitwise_equal` (random blocks, 8 activation magnitudes, both formats, bit compare). +* `crates/cuda-driver/src/original_verify_mapped.rs`: `all_finite`, the same predicate as a branch-free exponent fold (vectorizes; 4.3x faster on the laptop for 76,800 floats). Test against `is_finite` with all special values. + +## 4. Identity, `runs/cpu-service-id` (job `cpu-service-id`, ends 2026-10-31T19:17Z) + +Replay of `night5-long-256k` (5 requests, 48 forced tokens), static tier, 8,000 slots (7.3 % of entries on the CPU, 4.6 % PCIe), one test binary `dt/rt-cpuservice`: + +| comparison (`q_pair`, 353 rows) | identical | different | flips | +| --- | ---: | ---: | ---: | +| legacy A/A | 353 | 0 | 0 | +| new A/A | 353 | 0 | 0 | +| new vs legacy (both arms) | 353 | 0 | 0 | +| open cache vs legacy (both arms) | 353 | 0 | 0 | + +`q_tail_gate` PASS (all zeros) in each process. The paths did differ: `cpu.compute` 929 -> 587 ms (request 1, one CPU worker), replay decode 19.7-20.0 -> 22.8 tok/s. M. + +## 5. Paired A/B, `runs/cpu-service-ab` (job `cpu-service-ab`, 20 VALID runs, one binary `dt/bin-cpuservice` = code bba658f20) + +Blocks of four (cs-base, cs-new, cs-oc, cs-p35), order rotated, arms by environment only. M. + +| arm | runs | all-turn tok/s (range, SD) | tokens/round T1..T5 | ms/round mean | windows 20+ of T3-5: total / host pool / GPU wait / CPU experts / PCIe experts | +| --- | ---: | --- | --- | ---: | --- | +| cs-base (= main) | 5 | 140.8 (139.2-141.8, 0.86 %) | 2.10 1.96 2.00 1.85 2.02 | 14.09 | 11.9-12.2 / 3.45-3.72 / 8.24-8.31 / 24.5-27.1 / 11.4-13.6 | +| cs-new | 5 | 149.7 (147.1-153.5, 1.57 %) | 2.02 2.24 2.17 1.87 2.03 | 13.82 | 11.5-11.8 / 2.40-2.70 / 8.82-9.00 / 25.5-28.6 / 11.8-14.7 | +| cs-oc | 5 | 150.8 (148.3-153.4, 1.43 %) | 2.02 2.24 2.18 1.96 2.02 | 13.81 | 11.4-11.8 / 2.35-2.59 / 8.86-9.09 | +| cs-p35 | 5 | 147.6 (146.5-148.5, 0.45 %) | 2.07 2.31 2.25 1.84 2.04 | 14.25 | 11.5-12.2 / 2.45-3.23 / 8.78-8.86 / 29-40 / 4.1-7.8 | + +Reading it: + +* Host time in the window fell by ~1.0 ms (pool 3.5 -> 2.5 per window; per round `cpu.compute` 1.9-2.1 -> 1.5-1.7, scan overhead ~0.95 -> ~0.25), but the GPU wait rose by ~0.6 ms: on many layers the + host now finishes before the GPU's own MoE work, which was hidden before. Net window -0.4 ms, round -0.27 ms (-1.9 %). M. +* The rest of the tok/s gain is tokens/round (1.99 -> 2.07 averaged over turns): with a cheaper CPU leg the adaptive window policy picks wider windows (rows per window 2.34-2.43 -> 2.42-2.63). The + greedy arithmetic is unchanged (section 4); the end-to-end text differs between runs of every arm (also between base runs) because window width and swap timing are timing-dependent policies. + ms/token: 7.08 -> 6.68 (-5.7 %). E for the causal split, M for the numbers. +* `LELEKA_OPEN_CACHE=on` is bitwise and saves ~0.05 ms of `cpu.open` per round: inside the noise. Not a default change from this result. +* PCIe 0.35 moves 5-8 PCIe experts a window to the CPU and is slower than 0.55 with the new kernel (+0.43 ms/round, 5/5): our PCIe leg is cheaper than vanilla's relative to its CPU. Not gated, not proposed. + +## 6. What remains against vanilla (E, from the spans) + +Window: ours 11.5-11.8 ms against vanilla 10.5-10.7. GPU reach is equal (8.4-9.0 both); the remaining ~1 ms is host work on CPU layers: `cpu.compute` 1.5-1.7 ms for ~26 experts +(~61 us each against vanilla's 44 us; the down projection, the per-group token quantization and two pool barriers per layer are the candidates, not attributed), `cpu.open` 0.3, +spans/publish/split 0.3, scan 0.25. Outside the window: draft round 1.4 against 0.9 ms, untouched here. The multi-token path (`dot_multi512_tn`, ~10 % of CPU experts) still decodes through stack arrays. diff --git a/scripts/e2e/decode/cpu-service-ab.sh b/scripts/e2e/decode/cpu-service-ab.sh new file mode 100644 index 00000000..54d0a91c --- /dev/null +++ b/scripts/e2e/decode/cpu-service-ab.sh @@ -0,0 +1,181 @@ +#!/usr/bin/env bash +# claude/cpu-service: paired, interleaved 5-turn ~245k session (seed OFF, frozen corpus, upstream ranked profile, auto expert slots). ONE binary (dt/$BINDIR, default bin-cpuservice), arms by +# environment only: +# cs-base LELEKA_IQ_SINGLE=legacy LELEKA_SINK_SCAN=legacy: the generic single-token IQ3 tree and the element-wise finiteness scan (= main) +# cs-new defaults of the branch: register-built single-token IQ3_S/IQ3_XXS dot (bitwise the generic tree) and the vectorized scan +# cs-oc cs-new + LELEKA_OPEN_CACHE=on (existing opt-in: an admitted expert's validated spans reused, no per-use source scope) +# cs-p35 cs-new + LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.35 (the other arms run the harness default 0.55 of run-e2e.sh, NOT the product's 0.45) (vanilla's PcieAuto settles there at 44 us per CPU expert; PLACEMENT class: changes which device computes a missed +# expert, so it needs the relative placement gate before any default change) +# HOLDER JOB (rnr5090). Install: cp scripts/e2e/decode/cpu-service-ab.sh /data/leleka-e2e/decode/dt/jobs/ ; stub ~/work/gpu-runs/holder2/jobs/cpu-service-ab.sh +# (#!/usr/bin/env bash / exec bash /data/leleka-e2e/decode/dt/jobs/cpu-service-ab.sh). gpu.lock per arm, ~4-5 min an arm. +# ARMS default: 5 blocks of the four arms, order rotated (block k = runs 4k-3..4k) = 20 runs, ~100 min. +# Validity per run: no turn failed, 5 turns, final-turn input tokens >= 200000, turn-5 mean window.ple < 5 ms. An INVALID run is never used. +# Reported: decode tok/s per turn, tokens/round, ms/round, and per window (windows 20+ of turns 3-5) the CPU-pool time, its join, the GPU wait, CPU/PCIe experts. +set -uo pipefail +D=/data/leleka-e2e/decode/dt +LOCK=/data/leleka-e2e/gpu.lock +OUTR=/data/leleka-e2e/runs/cpu-service-ab +CORPUS=/data/leleka-e2e/decode/corpus/src/crates +UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin # ranked upstream profile; run-e2e.sh refuses any other digest +RUN_TAG=${RUN_TAG:-} # suffix of the run directories (a rerun next to earlier ones) +ARMS=${ARMS:-"cs-base cs-new cs-oc cs-p35 cs-new cs-oc cs-p35 cs-base cs-oc cs-p35 cs-base cs-new cs-p35 cs-base cs-new cs-oc cs-base cs-new cs-oc cs-p35"} +BINDIR=${BINDIR:-bin-cpuservice} +SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000" +for f in "$UP" "$D/tools/long-session.py" "$D/scripts/e2e/run-e2e.sh" "$D/$BINDIR/leleka-inference" "$CORPUS/backend-api/src/lib.rs"; do + [ -r "$f" ] || { echo "missing $f" >&2; exit 3; } +done + +ours() { # $1 tag, $2 arm + local tag=$1 arm=$2 + ( export E2E_BIN=$D/$BINDIR E2E_OUT=$OUTR/$tag + mkdir -p "$E2E_OUT" + export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 + export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=${GPU_BUDGET:-32819404800} + export E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0" + export E2E_SAMPLE_S=10 LELEKA_CHAIN=all + export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP + unset LELEKA_FOOTPRINT_LEGACY LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_IQ_SINGLE LELEKA_SINK_SCAN LELEKA_OPEN_CACHE LELEKA_ORIGINAL_SERVE_PCIE_FRAC + export LELEKA_ORIGINAL_SERVE_SEED=off + case $arm in + cs-base) export LELEKA_IQ_SINGLE=legacy LELEKA_SINK_SCAN=legacy ;; + cs-new) ;; + cs-oc) export LELEKA_OPEN_CACHE=on ;; + cs-p35) export LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.35 ;; + *) echo "unknown ours arm $arm" >&2; exit 2 ;; + esac + { echo "arm=$arm tag=$tag"; date -u +%FT%TZ; free -g | sed -n 2p; uptime; sha256sum "$UP" "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next + cat "$E2E_BIN/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt + env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } >"$E2E_OUT/env-arm.txt" + export E2E_RUN_CMD="python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS" + ( while sleep 5; do echo "$(date +%T) $(grep -E "SwapFree|MemAvailable|^Cached|Shmem:|Dirty" /proc/meminfo | tr -s " " | tr " +" " ") $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory) $(awk "/pswpin|pgmajfault/{printf \"%s=%s \",\$1,\$2}" /proc/vmstat)"; done > "$E2E_OUT/memsample.txt" 2>/dev/null ) & SAMP=$! + bash "$D/scripts/e2e/run-e2e.sh" 2>&1 | grep -a -E "^\{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit" | cut -c1-300 + kill $SAMP 2>/dev/null + echo "run-e2e done $tag $(date -u +%FT%TZ)" ) +} + +validity() { # $1 run dir + python3 -I - "$1" <<'PY' +import json, os, re, sys +d = sys.argv[1] +f = os.path.join(d, "long-session.json") +verdict = "INVALID: no long-session.json" +if os.path.exists(f): + t = json.load(open(f)) + final = (t[-1].get("input_tokens") or 0) if t else 0 + if any("error" in r for r in t): + verdict = "INVALID: a turn failed" + elif len(t) < 5 or final < 200000: + verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final) + else: + verdict = "VALID: 5 turns, final-turn input tokens %d" % final + wins, last = [], [] + for ln in open(os.path.join(d, "inference.log"), errors="replace"): + if ln.startswith("DBG window "): + last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif "leleka-serve request outcome" in ln: + wins.append(last); last = [] + w = wins[-1] if wins else [] + ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1) + verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w)) + if not w: + verdict = "INVALID: no turn-5 window lines (trace env missing?)" + elif ple >= 5: + verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple +open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n") +print(os.path.basename(d), verdict) +PY +} + +n=0 +for arm in $ARMS; do + n=$((n + 1)); tag="$arm-r$n$RUN_TAG" + got=0 + for _ in $(seq 1 1080); do + if mkdir "$LOCK" 2>/dev/null; then echo "cpu-service-ab $tag $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi + sleep 5 + done + [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; } + echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p + if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then + echo "GPU busy, skipping $tag"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; continue + fi + case $arm in + cs-base|cs-new|cs-oc|cs-p35) ours "$tag" "$arm" ;; + *) echo "unknown arm $arm" >&2; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; exit 2 ;; + esac + validity "$OUTR/$tag" + echo "arm done $tag $(date -u +%FT%TZ)" + rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null + sleep 15 +done + +# summary: per run, per arm, per block (block k = runs 4k-3..4k, one run of each arm) the candidate against the base of its block, and the window decomposition +python3 -I - "$OUTR" <<'PY' +import glob, json, os, re, statistics, sys +root = sys.argv[1] +def run_number(path): + tail = re.sub(r"\D+$", "", path.rsplit("-r", 1)[-1]) + return int(tail) if tail.isdigit() else 0 +def load(d): + sess = json.load(open(os.path.join(d, "long-session.json"))) + reqs, prof, wins, cur = [], None, [], [] + for ln in open(os.path.join(d, "inference.log"), errors="replace"): + if ln.startswith("DBG profile request:"): + prof = {m[0]: float(m[1].split("/")[0]) for m in re.findall(r"(\S+?)=([\d.]+/\d+)", ln)} + elif ln.startswith("DBG window "): + cur.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif "leleka-serve request outcome" in ln: + m = re.search(r"produced=(\d+) rounds=(\d+)", ln) + reqs.append((int(m.group(1)), int(m.group(2)), prof)); prof = None; wins.append(cur); cur = [] + rows = [] + for i, t in enumerate(sess): + produced, rounds, p = reqs[i] if i < len(reqs) else (0, 0, None) + tps = t.get("decode_tok_s") or 0.0 + out = t.get("output_tokens") or produced + span = lambda k: (p.get(k, 0.0) / rounds) if p and rounds else float("nan") + rows.append(dict(tps=tps, tok_round=(produced / rounds if rounds else float("nan")), + ms_round=(1000.0 * out / tps / rounds if rounds and tps else float("nan")), + compute=span("cpu.compute"), sink=span("cpu.sink"), open=span("cpu.open"), pool=span("pool.cpu"), bell=span("drv.doorbell_wait"), verifier=span("window.verifier"))) + late = [w for ws in wins[2:5] for w in ws[20:]] + keys = ("total", "pool", "join", "gpu_wait_and_head", "experts", "entries", "pcie_experts", "rows") + wavg = {k: statistics.mean(w.get(k, 0.0) for w in late) for k in keys} if late else {} + return rows, wavg +def arm(n): return re.sub(r"-r\d+.*$", "", n) +runs = {} +for d in sorted(glob.glob(os.path.join(root, "*-r[0-9]*")), key=run_number): + name = os.path.basename(d) + v = os.path.join(d, "VALIDITY.txt") + if not os.path.exists(v) or not open(v).read().startswith("VALID"): + print(name, "not used:", open(v).read().strip() if os.path.exists(v) else "no VALIDITY.txt"); continue + runs[name] = load(d) +for n, (rows, w) in runs.items(): + print("%-16s tok/s %s | tok/round %s | ms/round %s | turns 3-5 per round: compute %.2f sink %.2f open %.2f pool %.2f bell %.2f verifier %.2f" % ((n, + " ".join("%.1f" % r["tps"] for r in rows), " ".join("%.2f" % r["tok_round"] for r in rows), " ".join("%.2f" % r["ms_round"] for r in rows)) + + tuple(statistics.mean(r[k] for r in rows[2:]) for k in ("compute", "sink", "open", "pool", "bell", "verifier")))) + if w: + print(" windows 20+ of turns 3-5: total %.2f pool %.2f join %.2f gpu_wait %.2f | cpu experts %.1f entries %.1f pcie %.1f rows %.2f" % tuple(w[k] for k in ("total", "pool", "join", "gpu_wait_and_head", "experts", "entries", "pcie_experts", "rows"))) +by = {} +for n in runs: by.setdefault(arm(n), []).append(n) +for a, ns in sorted(by.items()): + allrows = [runs[n][0] for n in ns] + mean = lambda f: [statistics.mean(f(r[t]) for r in allrows) for t in range(5)] + alltps = [statistics.mean(x["tps"] for x in r) for r in allrows] + print("ARM %s (%d runs): tok/s per turn %s all-turn %.1f (runs %.1f..%.1f, sd %.2f %%) | tokens/round %s | ms/round %s mean %.2f" % (a, len(ns), + " ".join("%.1f" % x for x in mean(lambda r: r["tps"])), statistics.mean(alltps), min(alltps), max(alltps), 100 * statistics.pstdev(alltps) / statistics.mean(alltps), + " ".join("%.2f" % x for x in mean(lambda r: r["tok_round"])), " ".join("%.2f" % x for x in mean(lambda r: r["ms_round"])), statistics.mean(mean(lambda r: r["ms_round"])))) +for cand, ref in (("cs-new", "cs-base"), ("cs-oc", "cs-base"), ("cs-p35", "cs-base"), ("cs-oc", "cs-new"), ("cs-p35", "cs-new")): + diffs, msd = [], [] + for k in range(1, 40): + blk = [n for n in runs if (run_number(n) + 3) // 4 == k] + b = [n for n in blk if arm(n) == ref]; c = [n for n in blk if arm(n) == cand] + if len(b) == 1 and len(c) == 1: + rb, rc = runs[b[0]][0], runs[c[0]][0] + mb, mc = statistics.mean(x["tps"] for x in rb), statistics.mean(x["tps"] for x in rc) + ab, ac = statistics.mean(x["ms_round"] for x in rb), statistics.mean(x["ms_round"] for x in rc) + diffs.append(100 * (mc / mb - 1)); msd.append(ac - ab) + print("block %d %s vs %s: all-turn tok/s %.1f vs %.1f (%+.2f %%), ms/round %.2f vs %.2f (%+.2f)" % (k, cand, ref, mc, mb, diffs[-1], ac, ab, msd[-1])) + if diffs: + print("%s over %s: %d blocks, tok/s mean %+.2f %% (min %+.2f max %+.2f, %d/%d positive); ms/round mean %+.2f (min %+.2f max %+.2f)" % (cand, ref, len(diffs), statistics.mean(diffs), min(diffs), max(diffs), + sum(d > 0 for d in diffs), len(diffs), statistics.mean(msd), min(msd), max(msd))) +PY diff --git a/scripts/e2e/decode/cpu-service-id.sh b/scripts/e2e/decode/cpu-service-id.sh new file mode 100644 index 00000000..388ae6ea --- /dev/null +++ b/scripts/e2e/decode/cpu-service-id.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# claude/cpu-service identity gate: the register-built single-token IQ3_S/IQ3_XXS dot and the vectorized finiteness scan (defaults of the branch), and LELEKA_OPEN_CACHE=on, against the +# same binary with LELEKA_IQ_SINGLE=legacy LELEKA_SINK_SCAN=legacy (= main's arithmetic and guard), at an EQUAL FIXED slot count. Expectation: BITWISE identity (0 flips, max |dlogprob| 0). +# HOLDER JOB (copy of footprint3-id.sh): teacher-forced replay of the 256k-class capture night5-long-256k (5 requests, recorded replies, decode capped at 48 tokens each), production shape, +# top-16 logprobs of every row, STATIC tier, EXPERT_SLOTS=8000 per-layer (many CPU-served experts: the changed kernel runs on most layers), seed OFF, LELEKA_SPEC=4, RT directory set, +# ONE test binary (dt/rt-cpuservice) for every process: +# p1 idLegacy LELEKA_IQ_SINGLE=legacy LELEKA_SINK_SCAN=legacy, two identical arms I1 I2 (the A/A noise floor, expected 0) +# p2 idNew defaults, two arms +# p3 idOC defaults + LELEKA_OPEN_CACHE=on, two arms +# ~8 GPU-min a process, one at a time under gpu.lock; about 30 min. +# Install: cp scripts/e2e/decode/cpu-service-id.sh /data/leleka-e2e/decode/dt/jobs/; stub ~/work/gpu-runs/holder2/jobs/cpu-service-id.sh (exec bash that file). +set -uo pipefail +LOCK=/data/leleka-e2e/gpu.lock +D=/data/leleka-e2e/decode/dt +O=/data/leleka-e2e/runs/cpu-service-id +mkdir -p $O +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +A=$HOME/leleka-gates/assets +G=$HOME/work/gpu-runs +CAP=/data/leleka-e2e/sm120/capture +export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json +export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf +export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 +export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 +export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin +export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all +export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0 +unset LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_FOOTPRINT_LEGACY LELEKA_IQ_SINGLE LELEKA_SINK_SCAN LELEKA_OPEN_CACHE +for f in $D/rt-cpuservice $D/tools/q_pair.py $D/tools/q_tail_gate.py $CAP/night5-long-256k; do + [ -e "$f" ] || { echo "missing $f" >&2; exit 3; } +done +sha256sum $D/rt-cpuservice +shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan" +run() { # label bin extra-env arms + BIN=$D/$2 + got=0 + for i in $(seq 1 1080); do + if mkdir $LOCK 2>/dev/null; then echo "cpu-service identity $1 $(date -u +%FT%TZ)" >$LOCK/owner; got=1; break; fi + sleep 5 + done + [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; return 3; } + avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "=== $1 bin=$2 extra=[$3] MemAvailable GiB: $avail"; free -g | sed -n 2,3p + if [ "$avail" -lt 60 ]; then echo "abort: less than 60 GiB available"; rm -f $LOCK/owner; rmdir $LOCK; return 4; fi + date -u +%FT%TZ + env $3 LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP/night5-long-256k LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16 \ + LELEKA_REPLAY_MAX_NEW=48 LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS=$4 \ + nice -n 5 $BIN --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke > $O/$1.full 2>&1 + echo "rc=$? label=$1"; date -u +%FT%TZ + grep -a -E "^REPLAY|test result|panicked|FAILED|expert cache [0-9]+ slots|leleka-serve dense weights" $O/$1.full | cut -c1-300 | tail -10 + rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null + sleep 15 +} +run idLegacy rt-cpuservice "LELEKA_IQ_SINGLE=legacy LELEKA_SINK_SCAN=legacy" "I1=$shape,I2=$shape" +run idNew rt-cpuservice "LELEKA_X=1" "I1=$shape,I2=$shape" +run idOC rt-cpuservice "LELEKA_OPEN_CACHE=on" "I1=$shape,I2=$shape" +T=$D/tools +PROCS="idLegacy idNew idOC" +for p in $PROCS; do echo "== q_tail_gate $p"; python3 $T/q_tail_gate.py $O/$p.full $CAP/night5-long-256k 2>&1 | tail -12; done +python3 - <