From 8f4a45dba9e731707fbdfbcfc13da079a502f40d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 10:51:18 +0200 Subject: [PATCH] test(serve): model-free device proof of the VRAM expert tier Synthetic IQ4_XS/IQ4_NL experts in a six-slot cache, one verify-window layer group through OriginalExpertTierProbe: the resident experts' entries become VRAM groups in routing order, every CPU entry is bit-identical to the all-CPU run, GPU entries are within the Original's 3e-2 relative L1 of the CPU path, and a plan naming another expert's slot is refused. RTX 5090: passed, worst GPU-vs-CPU relative L1 1.155e-2. Co-Authored-By: Claude Opus 5.5 --- crates/leleka-runtime/Cargo.toml | 2 + crates/leleka-runtime/src/qwen_forward/mod.rs | 2 + .../original_serve_residency_gpu.rs | 206 ++++++++++++++++++ 3 files changed, 210 insertions(+) create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_residency_gpu.rs diff --git a/crates/leleka-runtime/Cargo.toml b/crates/leleka-runtime/Cargo.toml index bd55e9fa..8059ae5e 100644 --- a/crates/leleka-runtime/Cargo.toml +++ b/crates/leleka-runtime/Cargo.toml @@ -32,3 +32,5 @@ workspace = true [dev-dependencies] serde_json = "1" +# Model-free device probe of the VRAM expert tier (test builds only). +leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver", "expert-tier-probe"] } diff --git a/crates/leleka-runtime/src/qwen_forward/mod.rs b/crates/leleka-runtime/src/qwen_forward/mod.rs index 4c4966e2..d9d6493d 100644 --- a/crates/leleka-runtime/src/qwen_forward/mod.rs +++ b/crates/leleka-runtime/src/qwen_forward/mod.rs @@ -96,6 +96,8 @@ pub(crate) mod original_serve_pool; // The VRAM expert tier of that window (R4 residency, PCIe share, adaptive swaps, prompt-path slot loan). #[cfg(all(target_os="linux",target_arch="x86_64"))] pub(crate) mod original_serve_residency; +#[cfg(all(test,target_os="linux",target_arch="x86_64"))] +mod original_serve_residency_gpu; #[cfg(all(target_os="linux",target_arch="x86_64"))] pub(crate) mod original_serve_ledger; #[cfg(all(target_os="linux",target_arch="x86_64"))] diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency_gpu.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency_gpu.rs new file mode 100644 index 00000000..d0ef4969 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency_gpu.rs @@ -0,0 +1,206 @@ +//! Model-free device proof of the VRAM expert tier (`LELEKA_EXPERT_TIER_GPU=yes`, one GPU, <= 4 GiB, no +//! model files): synthetic native experts (IQ4_XS gate/up, IQ4_NL down: two of the formats the pinned pack +//! uses) in a small expert cache, one verify-window layer group run through `OriginalExpertTierProbe` (the +//! recorded `post` launches and the verifier's host protocol), once with every expert on the native CPU +//! kernels and once with the tier's split (`split_group` + `publish_gpu_plan`). +//! +//! Proves: placement (exactly the resident experts' entries become VRAM groups, in routing order), the +//! hit/miss split (every CPU entry of the tier run is bit-identical to the all-CPU run: the CPU's rows are +//! copied, the GPU's zeroed and replaced), and that a GPU-computed expert matches the CPU's within the +//! Original's documented bound (`native_expert_parity`: CPU and GPU each within 3e-2 relative L1 of the float +//! reference, so the GPU's relative L1 distance to the CPU path is gated at 3e-2 here and reported), and that +//! a plan naming a slot of another expert is refused before the GPU reads it. +//! +//! Not proven here (needs the registered model bank): the PCIe DMA share and the adaptive slot swaps on the +//! device; their policies are unit-tested in `original_serve_residency`. +use super::original_serve_residency::split_group; +use leleka_cuda_driver::{ + Driver, OriginalExpertCache, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyExpertFormats, + OriginalVerifyGpuPlan, +}; +use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob}; + +const H: usize = 2560; +const FF: usize = 640; +const K: usize = 10; +const LAYER: usize = 5; +const GATE: usize = H / 256 * 136 * FF; +const DOWN: usize = FF / 32 * 18 * H; +const BLOB: usize = 2 * GATE + DOWN; + +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 unit(&mut self) -> f32 { + (self.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + } +} + +/// One synthetic native expert `gate | up | down`: random quant bits under small finite block scales. +fn expert_blob(seed: u64) -> Vec { + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let mut blob: Vec = (0..BLOB).map(|_| rng.next() as u8).collect(); + // f16 d of every block: IQ4_XS 136-byte blocks (gate, up), IQ4_NL 18-byte blocks (down) + let scale = |rng: &mut Rng| -> [u8; 2] { + // 0.004 .. 0.008 (f16 exponent 2^-8), positive + let mantissa = (rng.next() % 1024) as u16; + ((0x1C00u16) | mantissa).to_le_bytes() + }; + for at in (0..2 * GATE).step_by(136) { + let d = scale(&mut rng); + blob[at..at + 2].copy_from_slice(&d); + } + for at in (2 * GATE..BLOB).step_by(18) { + let d = scale(&mut rng); + blob[at..at + 2].copy_from_slice(&d); + } + blob +} + +/// The native CPU path for the entries `include` selects; every other entry's row is zeros. +fn cpu_rows(pool: &mut CpuPool, blobs: &dyn Fn(i32) -> Vec, ids: &[i32], activation: &[f32], include: &[bool]) -> Vec { + let mut out = vec![0.0f32; ids.len() * H]; + let mut experts: Vec = Vec::new(); + for (i, &e) in ids.iter().enumerate() { + if include[i] && !experts.contains(&e) { + experts.push(e); + } + } + for chunk in experts.chunks(8) { + let mut jobs = Vec::new(); + let mut members = Vec::new(); + for &e in chunk { + let entries: Vec = (0..ids.len()).filter(|&i| include[i] && ids[i] == e).collect(); + let mut input = Vec::new(); + for &i in &entries { + input.extend_from_slice(&activation[(i / K) * H..(i / K + 1) * H]); + } + let blob = blobs(e); + jobs.push( + PreparedJob::new( + GateUpFormat::Iq4Xs, + DownFormat::Iq4Nl, + blob[..GATE].into(), + blob[GATE..2 * GATE].into(), + blob[2 * GATE..].into(), + input.into_boxed_slice(), + entries.len(), + ) + .expect("synthetic expert"), + ); + members.push(entries); + } + let done = pool.start(jobs, 96 << 20).expect("cpu batch").join().expect("cpu join"); + for (job, entries) in done.into_iter().zip(members) { + let values = job.into_values(); + for (r, &i) in entries.iter().enumerate() { + out[i * H..(i + 1) * H].copy_from_slice(&values[r * H..(r + 1) * H]); + } + } + } + out +} + +fn rel(a: &[f32], b: &[f32]) -> f64 { + let n: f64 = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(*y)).abs()).sum(); + let d: f64 = b.iter().map(|y| f64::from(*y).abs()).sum(); + n / (d + 1e-30) +} + +#[test] +#[ignore = "needs a CUDA device; LELEKA_EXPERT_TIER_GPU=yes"] +fn the_vram_tier_computes_the_resident_experts_and_leaves_the_misses_bit_identical() { + assert_eq!(std::env::var("LELEKA_EXPERT_TIER_GPU").ok().as_deref(), Some("yes")); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device"); + let context = device.create_context(4 << 30).expect("context"); + let formats = OriginalVerifyExpertFormats::new([(23, 20); 48], H, FF).expect("formats"); + assert_eq!(formats.blob_bytes(LAYER).unwrap(), BLOB, "the native layout of the synthetic expert"); + let mut probe = context.original_expert_tier_probe(4, BLOB, formats).expect("probe"); + // six slots; experts 3, 40, 41, 100 resident in layer 5 (and 3 of layer 6, never routed here) + let mut cache: OriginalExpertCache<'_> = context.original_expert_cache_uniform(6, 48, 512, BLOB).expect("cache"); + let blobs = |e: i32| expert_blob(e as u64 + 1000 * LAYER as u64); + for (layer, e) in [(LAYER, 3usize), (LAYER, 40), (LAYER, 41), (6, 3), (LAYER, 100)] { + let slot = cache.admit(layer, e).expect("admit"); + assert!(slot >= 0); + let bytes = if layer == LAYER { blobs(e as i32) } else { expert_blob(77) }; + cache.probe_fill_slot(slot as usize, &bytes).expect("fill"); + } + assert_eq!(cache.resident_slot(LAYER, 40), Some(1)); + assert_eq!(cache.resident_slot(LAYER, 7), None); + // three window rows over 16 experts of layer 5; 3 and 40 routed in every row, 100 never + let ids: Vec = [ + [3, 40, 7, 8, 9, 10, 11, 12, 13, 14], + [15, 3, 16, 7, 40, 41, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 7, 8, 40, 3, 9], + ] + .concat(); + let mut rng = Rng(42); + let activation: Vec = (0..3 * H).map(|_| rng.unit()).collect(); + let mut cpu = CpuPool::new(8).expect("cpu pool"); + + // all-CPU reference: no plan, the run loop's empty plan + let reference = probe + .run_group(LAYER, &activation, &ids, |rows: OriginalVerifyCpuRows<'_>, sink: &mut OriginalVerifyCpuSink<'_, '_>, _copy| { + let values = cpu_rows(&mut cpu, &blobs, rows.ids, rows.activation, &vec![true; rows.ids.len()]); + sink.with_output(|out| { + out.copy_from_slice(&values); + Ok(()) + }) + }) + .expect("all-CPU group"); + + // the tier's split + let mut placed = None; + let tier = probe + .run_group(LAYER, &activation, &ids, |rows, sink, copy| { + let split = split_group(rows.ids, K, sink.plan_capacity(), |e| cache.resident_slot(LAYER, e as usize), 0, sink.staging_capacity()) + .map_err(|_| leleka_cuda_driver::Error::InvalidQwenShape)?; + sink.publish_gpu_plan(&split.plan, &cache, None, copy)?; + let include: Vec = split.kinds.iter().map(|&k| k < 0).collect(); + let values = cpu_rows(&mut cpu, &blobs, rows.ids, rows.activation, &include); + placed = Some(split); + sink.with_output(|out| { + out.copy_from_slice(&values); + Ok(()) + }) + }) + .expect("tier group"); + let split = placed.expect("split"); + + // placement: 3 (entries 0, 11, 28), 40 (1, 14, 27), 41 (15), in routing order; nothing else on the GPU + assert_eq!(split.plan.vram(), &[(0, vec![0, 11, 28]), (1, vec![1, 14, 27]), (2, vec![15])]); + assert!(split.plan.pcie().is_empty()); + let gpu: Vec = (0..ids.len()).filter(|&i| split.kinds[i] == 0).collect(); + assert_eq!(gpu, vec![0, 1, 11, 14, 15, 27, 28]); + let mut worst = 0.0f64; + for i in 0..ids.len() { + let (t, r) = (&tier[i * H..(i + 1) * H], &reference[i * H..(i + 1) * H]); + assert!(t.iter().all(|x| x.is_finite()), "entry {i} not finite"); + if split.kinds[i] < 0 { + assert!(t.iter().zip(r).all(|(a, b)| a.to_bits() == b.to_bits()), "CPU entry {i} differs from the all-CPU run"); + } else { + let e = rel(t, r); + assert!(r.iter().any(|x| *x != 0.0) && t.iter().any(|x| *x != 0.0), "entry {i} is zero"); + assert!(e < 3e-2, "GPU entry {i} (expert {}) relative L1 {e:.3e} vs the CPU path", ids[i]); + worst = worst.max(e); + } + } + eprintln!("expert tier probe: 7 GPU entries, worst GPU-vs-CPU relative L1 {worst:.3e} (gate 3e-2); 23 CPU entries bit-identical"); + + // integrity: a plan naming the slot of expert 41 for an entry routed to expert 7 is refused before any read + let refused = probe.run_group(LAYER, &activation, &ids, |_rows, sink, copy| { + let mut wrong = OriginalVerifyGpuPlan::new(); + wrong.push_vram(2, vec![2]); + sink.publish_gpu_plan(&wrong, &cache, None, copy) + }); + assert!(refused.is_err(), "a slot of another expert must be refused"); + drop(probe); + cache.close().expect("cache close"); + context.close().expect("context close"); +}