From 64885782fb0c5fcb11a312e5da763aae1595392a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 00:04:38 +0100 Subject: [PATCH] STRA-338 size-nce: igpu tests and examples within the function limits 12 functions over a limit in crates/igpu test and example code -> 0 (3 example mains, src/tests.rs threaded_repacking, tests/attention.rs attention_case, tests/gemm.rs check and the epilogue test, tests/moe.rs router and grouped products, tests/norm.rs check, tests/real_weights.rs compare and the real-weights test). Split into arrange/run/compare helpers; test names, module paths, assertions, messages and example output lines unchanged. The allowlist entry of src/tests.rs threaded_repacking_equals_the_plain_definition is removed. Only src/shaders/gemm.rs (WGSL text) stays allowlisted and is untouched. --- crates/igpu/examples/attn_bench.rs | 113 ++++++++---- crates/igpu/examples/dot4_peak.rs | 116 ++++++++---- crates/igpu/examples/gemm_bench.rs | 170 ++++++++++++------ crates/igpu/src/tests.rs | 79 +++++--- crates/igpu/tests/attention.rs | 190 +++++++++++++------- crates/igpu/tests/gemm.rs | 222 ++++++++++++++++------- crates/igpu/tests/moe.rs | 279 ++++++++++++++++++++--------- crates/igpu/tests/norm.rs | 97 ++++++---- crates/igpu/tests/real_weights.rs | 237 ++++++++++++++++-------- limits-allowlist.json | 10 -- 10 files changed, 1022 insertions(+), 491 deletions(-) diff --git a/crates/igpu/examples/attn_bench.rs b/crates/igpu/examples/attn_bench.rs index 6f676098..7fa75745 100644 --- a/crates/igpu/examples/attn_bench.rs +++ b/crates/igpu/examples/attn_bench.rs @@ -3,48 +3,85 @@ //! //! Reports milliseconds for one layer's attention over a batch of `m` tokens ending at position `end`. -use leleka_igpu::{AttentionShape, Gpu}; +use leleka_igpu::{AttentionShape, Buf, Gpu}; + +const KV_WIDTH: usize = 512; +const Q_WIDTH: usize = 4096; +const CACHE_POSITIONS: usize = 8192; +/// (end, m, window) of each timed case. +const CASES: [(usize, usize, usize); 5] = [ + (512, 512, 0), + (2048, 512, 0), + (4096, 512, 0), + (4096, 512, 128), + (8192, 512, 0), +]; + +struct Layer { + kcache: Buf, + vcache: Buf, + sinks: Buf, +} + +fn allocate_layer(gpu: &Gpu) -> Layer { + let kcache = gpu.zeros(CACHE_POSITIONS * KV_WIDTH / 2); + let vcache = gpu.zeros(CACHE_POSITIONS * KV_WIDTH / 2); + let sinks = gpu.zeros(64); + Layer { + kcache, + vcache, + sinks, + } +} + +fn case_shape(end: usize, m: usize, window: usize) -> AttentionShape { + AttentionShape { + m, + pos0: end - m, + window, + kv_width: KV_WIDTH, + q_width: Q_WIDTH, + scale: 0.125, + } +} + +fn run_attention( + gpu: &Gpu, + layer: &Layer, + shape: AttentionShape, + buffers: (&Buf, &Buf), + count: usize, +) { + let (q, out) = buffers; + let mut rec = gpu.recorder(); + for _ in 0..count { + rec.attention(shape, q, &layer.kcache, &layer.vcache, &layer.sinks, out) + .unwrap(); + } + rec.submit().unwrap(); +} + +/// Milliseconds of one layer's attention: one warm-up run, then the mean of five. +fn time_attention(gpu: &Gpu, layer: &Layer, end: usize, m: usize, window: usize) -> f64 { + let q = gpu.zeros(m * Q_WIDTH); + let out = gpu.zeros(m * Q_WIDTH); + let shape = case_shape(end, m, window); + run_attention(gpu, layer, shape, (&q, &out), 1); + let start = std::time::Instant::now(); + run_attention(gpu, layer, shape, (&q, &out), 5); + start.elapsed().as_secs_f64() / 5.0 * 1e3 +} + +fn print_row(end: usize, m: usize, window: usize, ms: f64) { + println!("{end:>6} {m:>6} {window:>7} {ms:>10.2}"); +} fn main() { let gpu = Gpu::new().expect("a GPU"); println!("adapter: {}", gpu.adapter_name()); - let (kw, qw) = (512usize, 4096usize); - let cap = 8192usize; - let kcache = gpu.zeros(cap * kw / 2); - let vcache = gpu.zeros(cap * kw / 2); - let sinks = gpu.zeros(64); + let layer = allocate_layer(&gpu); println!("{:>6} {:>6} {:>7} {:>10}", "end", "m", "window", "ms"); - for (end, m, window) in [ - (512usize, 512usize, 0usize), - (2048, 512, 0), - (4096, 512, 0), - (4096, 512, 128), - (8192, 512, 0), - ] { - let q = gpu.zeros(m * qw); - let out = gpu.zeros(m * qw); - let shape = AttentionShape { - m, - pos0: end - m, - window, - kv_width: kw, - q_width: qw, - scale: 0.125, - }; - let run = |count: usize| { - let mut rec = gpu.recorder(); - for _ in 0..count { - rec.attention(shape, &q, &kcache, &vcache, &sinks, &out) - .unwrap(); - } - rec.submit().unwrap(); - }; - run(1); - let start = std::time::Instant::now(); - run(5); - println!( - "{end:>6} {m:>6} {window:>7} {:>10.2}", - start.elapsed().as_secs_f64() / 5.0 * 1e3 - ); + for (end, m, window) in CASES { + print_row(end, m, window, time_attention(&gpu, &layer, end, m, window)); } } diff --git a/crates/igpu/examples/dot4_peak.rs b/crates/igpu/examples/dot4_peak.rs index 56344a58..034c3b58 100644 --- a/crates/igpu/examples/dot4_peak.rs +++ b/crates/igpu/examples/dot4_peak.rs @@ -39,45 +39,65 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { +const THREADS: u64 = 1 << 18; +const ITERS: u32 = 4096; + +fn request_adapter() -> wgpu::Adapter { let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default()); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })) - .expect("an adapter"); - println!("adapter: {}", adapter.get_info().name); - let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + .expect("an adapter") +} + +fn request_device(adapter: &wgpu::Adapter) -> (wgpu::Device, wgpu::Queue) { + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { required_limits: adapter.limits(), ..Default::default() })) - .expect("device"); + .expect("device") +} + +fn create_pipeline(device: &wgpu::Device) -> wgpu::ComputePipeline { let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()), }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: None, layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None, - }); - let threads = 1 << 18; - let iters = 4096u32; - let out = device.create_buffer(&wgpu::BufferDescriptor { + }) +} + +fn create_output_buffer(device: &wgpu::Device) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { label: None, - size: threads * 4, + size: THREADS * 4, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false, - }); - let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + }) +} + +fn create_params_buffer(device: &wgpu::Device) -> wgpu::Buffer { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, - contents: bytemuck::cast_slice(&[iters, 0u32, 0, 0]), + contents: bytemuck::cast_slice(&[ITERS, 0u32, 0, 0]), usage: wgpu::BufferUsages::UNIFORM, - }); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + }) +} + +fn create_bind_group( + device: &wgpu::Device, + pipeline: &wgpu::ComputePipeline, + out: &wgpu::Buffer, + params: &wgpu::Buffer, +) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &pipeline.get_bind_group_layout(0), entries: &[ @@ -90,27 +110,61 @@ fn main() { resource: params.as_entire_binding(), }, ], - }); - let run = |count: usize| { - let mut encoder = device.create_command_encoder(&Default::default()); + }) +} + +struct Peak { + device: wgpu::Device, + queue: wgpu::Queue, + pipeline: wgpu::ComputePipeline, + bind: wgpu::BindGroup, +} + +impl Peak { + fn run(&self, count: usize) { + let mut encoder = self.device.create_command_encoder(&Default::default()); for _ in 0..count { let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(&pipeline); - pass.set_bind_group(0, &bind, &[]); - pass.dispatch_workgroups((threads / 64) as u32, 1, 1); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.bind, &[]); + pass.dispatch_workgroups((THREADS / 64) as u32, 1, 1); } - queue.submit([encoder.finish()]); - device.poll(wgpu::PollType::Wait).expect("poll"); - }; - run(1); - let start = std::time::Instant::now(); - run(3); - let seconds = start.elapsed().as_secs_f64() / 3.0; + self.queue.submit([encoder.finish()]); + self.device.poll(wgpu::PollType::Wait).expect("poll"); + } +} + +fn create_peak(adapter: &wgpu::Adapter) -> Peak { + let (device, queue) = request_device(adapter); + let pipeline = create_pipeline(&device); + let out = create_output_buffer(&device); + let params = create_params_buffer(&device); + let bind = create_bind_group(&device, &pipeline, &out, ¶ms); + Peak { + device, + queue, + pipeline, + bind, + } +} + +fn print_report(seconds: f64) { // 16 dot4 per iteration, 4 multiplies and 4 adds each - let ops = threads as f64 * f64::from(iters) * 16.0 * 8.0; + let ops = THREADS as f64 * f64::from(ITERS) * 16.0 * 8.0; println!( "{:.3} s per dispatch, {:.2} TOPS (dot4I8Packed, 8 ops each, no memory traffic)", seconds, ops / seconds / 1e12 ); } + +fn main() { + let adapter = request_adapter(); + println!("adapter: {}", adapter.get_info().name); + let peak = create_peak(&adapter); + peak.run(1); + let start = std::time::Instant::now(); + peak.run(3); + let seconds = start.elapsed().as_secs_f64() / 3.0; + print_report(seconds); +} diff --git a/crates/igpu/examples/gemm_bench.rs b/crates/igpu/examples/gemm_bench.rs index 8f1f7431..50e61558 100644 --- a/crates/igpu/examples/gemm_bench.rs +++ b/crates/igpu/examples/gemm_bench.rs @@ -4,82 +4,136 @@ //! Reports milliseconds per product and the integer throughput (2 * m * n * k operations). use leleka_cpu_kernels::Dispatch; -use leleka_igpu::{Gpu, WeightKind}; +use leleka_igpu::{Gpu, GpuActivations, GpuMatrix, WeightKind}; -fn main() { - // LELEKA_IGPU_TILE=TMxTN picks the outputs per thread (default 4x4, the measured best) - let (tm, tn) = std::env::var("LELEKA_IGPU_TILE") +const BLOCKS: usize = 90; // K = 2880, gpt-oss' hidden size + +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } +} + +/// LELEKA_IGPU_TILE=TMxTN picks the outputs per thread (default 4x4, the measured best). +fn read_tile() -> (u32, u32) { + std::env::var("LELEKA_IGPU_TILE") .ok() .and_then(|s| { s.split_once('x') .map(|(a, b)| (a.parse().ok(), b.parse().ok())) }) .and_then(|(a, b)| Some((a?, b?))) - .unwrap_or((4, 4)); + .unwrap_or((4, 4)) +} + +fn draw_q8_0_weights(rng: &mut Rng, n: usize) -> Vec { + (0..n * BLOCKS) + .flat_map(|_| { + let mut b = vec![0x00, 0x2C]; // half 0.0625 + b.extend((0..32).map(|_| rng.next_u64() as u8)); + b + }) + .collect() +} + +fn draw_mxfp4_weights(rng: &mut Rng, n: usize) -> Vec { + (0..n * BLOCKS) + .flat_map(|_| { + let mut b = vec![120u8]; + b.extend((0..16).map(|_| rng.next_u64() as u8)); + b + }) + .collect() +} + +fn draw_weights(rng: &mut Rng, kind: WeightKind, n: usize) -> Vec { + match kind { + WeightKind::Q8_0 => draw_q8_0_weights(rng, n), + WeightKind::Mxfp4 => draw_mxfp4_weights(rng, n), + } +} + +fn draw_activations(d: &Dispatch, rng: &mut Rng, m: usize) -> Vec { + let x: Vec = (0..m * BLOCKS * 32) + .map(|_| (rng.next_u64() % 1000) as f32 / 100.0 - 5.0) + .collect(); + let mut q = vec![0u8; m * BLOCKS * 34]; + d.quantize_q8_0(&x, &mut q).expect("quantize"); + q +} + +/// The median of five timings of ten products. +fn time_median(gpu: &Gpu, wm: &GpuMatrix, am: &GpuActivations) -> f64 { + let mut times: Vec = (0..5) + .map(|_| gpu.time_matmul(wm, am, 10).expect("run")) + .collect(); + times.sort_by(|a, b| a.total_cmp(b)); + times[2] +} + +fn print_header() { + println!( + "{:<8} {:>5} {:>6} {:>10} {:>9}", + "weights", "m", "n", "ms/product", "TOPS" + ); +} + +fn print_row(kind: WeightKind, m: usize, n: usize, t: f64) { + let ops = 2.0 * m as f64 * n as f64 * (BLOCKS * 32) as f64; + println!( + "{:<8} {:>5} {:>6} {:>10.3} {:>9.2}", + format!("{kind:?}"), + m, + n, + t * 1e3, + ops / t / 1e12 + ); +} + +fn bench_product( + gpu: &Gpu, + d: &Dispatch, + rng: &mut Rng, + wm: &GpuMatrix, + shape: (WeightKind, usize, usize), +) { + let (kind, n, m) = shape; + let q = draw_activations(d, rng, m); + let am = gpu + .upload_activations(m, BLOCKS * 32, &q) + .expect("upload activations"); + print_row(kind, m, n, time_median(gpu, wm, &am)); +} + +fn bench_weights(gpu: &Gpu, d: &Dispatch, rng: &mut Rng, kind: WeightKind, n: usize) { + let w = draw_weights(rng, kind, n); + let wm = gpu.upload_matrix(kind, n, BLOCKS * 32, &w).expect("upload"); + for m in [8usize, 16, 32, 64, 128, 256] { + bench_product(gpu, d, rng, &wm, (kind, n, m)); + } +} + +fn main() { + let (tm, tn) = read_tile(); let gpu = Gpu::with_tile(tm, tn).expect("a GPU"); println!( "adapter: {}, tile {tm}x{tn} outputs per thread", gpu.adapter_name() ); let d = Dispatch::best(); - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - let mut next = move || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - seed - }; - let blocks = 90; // K = 2880, gpt-oss' hidden size - println!( - "{:<8} {:>5} {:>6} {:>10} {:>9}", - "weights", "m", "n", "ms/product", "TOPS" - ); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15u64); + print_header(); for (kind, n) in [ (WeightKind::Mxfp4, 2880usize), (WeightKind::Mxfp4, 5760), (WeightKind::Q8_0, 4096), (WeightKind::Q8_0, 2880), ] { - let w: Vec = match kind { - WeightKind::Q8_0 => (0..n * blocks) - .flat_map(|_| { - let mut b = vec![0x00, 0x2C]; // half 0.0625 - b.extend((0..32).map(|_| next() as u8)); - b - }) - .collect(), - WeightKind::Mxfp4 => (0..n * blocks) - .flat_map(|_| { - let mut b = vec![120u8]; - b.extend((0..16).map(|_| next() as u8)); - b - }) - .collect(), - }; - let wm = gpu.upload_matrix(kind, n, blocks * 32, &w).expect("upload"); - for m in [8usize, 16, 32, 64, 128, 256] { - let x: Vec = (0..m * blocks * 32) - .map(|_| (next() % 1000) as f32 / 100.0 - 5.0) - .collect(); - let mut q = vec![0u8; m * blocks * 34]; - d.quantize_q8_0(&x, &mut q).expect("quantize"); - let am = gpu - .upload_activations(m, blocks * 32, &q) - .expect("upload activations"); - let mut times: Vec = (0..5) - .map(|_| gpu.time_matmul(&wm, &am, 10).expect("run")) - .collect(); - times.sort_by(|a, b| a.total_cmp(b)); - let t = times[2]; - let ops = 2.0 * m as f64 * n as f64 * (blocks * 32) as f64; - println!( - "{:<8} {:>5} {:>6} {:>10.3} {:>9.2}", - format!("{kind:?}"), - m, - n, - t * 1e3, - ops / t / 1e12 - ); - } + bench_weights(&gpu, &d, &mut rng, kind, n); } } diff --git a/crates/igpu/src/tests.rs b/crates/igpu/src/tests.rs index f8c3fb51..753b0eab 100644 --- a/crates/igpu/src/tests.rs +++ b/crates/igpu/src/tests.rs @@ -40,41 +40,64 @@ fn activations_get_float_scales() { assert_eq!(quants.len(), 8); } -/// The straightforward definitions, to check the threaded repackers against on inputs large enough to be -/// split (ragged sizes included). -#[test] -fn threaded_repacking_equals_the_plain_definition() { - let mut seed = 0x1234_5678_9ABC_DEF1u64; - let mut next = move || { +/// A xorshift generator of bytes, so the inputs are the same on every run. +fn xorshift_bytes(mut seed: u64) -> impl FnMut() -> u8 { + move || { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; seed as u8 - }; + } +} + +/// The straightforward definition of the Q8_0 repacking. +fn plain_repack_q8_0(q8: &[u8]) -> (Vec, Vec) { + let mut want_q = Vec::new(); + let mut halves = Vec::new(); + for b in q8.as_chunks::().0 { + halves.push(u16::from_le_bytes([b[0], b[1]])); + want_q.extend(le_words(&b[2..])); + } + let want_s: Vec = halves + .chunks(2) + .map(|p| u32::from(p[0]) | (u32::from(*p.get(1).unwrap_or(&0)) << 16)) + .collect(); + (want_q, want_s) +} + +/// The straightforward definition of the MXFP4 repacking. +fn plain_repack_mxfp4(mx: &[u8]) -> (Vec, Vec) { + let mut want_n = Vec::new(); + let mut want_e = Vec::new(); + for b in mx.as_chunks::().0 { + want_e.push(b[0]); + want_n.extend(le_words(&b[1..])); + } + (want_n, le_words(&want_e)) +} + +fn assert_q8_0_repacking_matches(q8: &[u8], n: usize) { + let (quants, scales) = repack_q8_0(q8); + let (want_q, want_s) = plain_repack_q8_0(q8); + assert!(quants == want_q && scales == want_s, "q8_0, {n} blocks"); +} + +fn assert_mxfp4_repacking_matches(mx: &[u8], n: usize) { + let (nibbles, exponents) = repack_mxfp4(mx); + let (want_n, want_e) = plain_repack_mxfp4(mx); + assert!(nibbles == want_n && exponents == want_e, "mxfp4, {n} blocks"); +} + +/// The straightforward definitions, to check the threaded repackers against on inputs large enough to be +/// split (ragged sizes included). +#[test] +fn threaded_repacking_equals_the_plain_definition() { + let mut next = xorshift_bytes(0x1234_5678_9ABC_DEF1u64); for n in [20_000usize, 40_001, 65_536 + 3] { let q8: Vec = (0..n * Q8_0_BYTES).map(|_| next()).collect(); - let (quants, scales) = repack_q8_0(&q8); - let mut want_q = Vec::new(); - let mut halves = Vec::new(); - for b in q8.as_chunks::().0 { - halves.push(u16::from_le_bytes([b[0], b[1]])); - want_q.extend(le_words(&b[2..])); - } - let want_s: Vec = halves - .chunks(2) - .map(|p| u32::from(p[0]) | (u32::from(*p.get(1).unwrap_or(&0)) << 16)) - .collect(); - assert!(quants == want_q && scales == want_s, "q8_0, {n} blocks"); - + assert_q8_0_repacking_matches(&q8, n); let mx: Vec = (0..n * MXFP4_BYTES).map(|_| next()).collect(); - let (nibbles, exponents) = repack_mxfp4(&mx); - let mut want_n = Vec::new(); - let mut want_e = Vec::new(); - for b in mx.as_chunks::().0 { - want_e.push(b[0]); - want_n.extend(le_words(&b[1..])); - } - assert!(nibbles == want_n && exponents == le_words(&want_e), "mxfp4, {n} blocks"); + assert_mxfp4_repacking_matches(&mx, n); } } diff --git a/crates/igpu/tests/attention.rs b/crates/igpu/tests/attention.rs index 084eefc1..5e6a2b4b 100644 --- a/crates/igpu/tests/attention.rs +++ b/crates/igpu/tests/attention.rs @@ -110,82 +110,136 @@ fn kv_store_rounds_to_half_like_the_cpu() { assert!(words[(pos0 + m) * kw / 2..].iter().all(|w| *w == 0)); } -fn attention_case(gpu: &Gpu, pos0: usize, m: usize, window: usize, seed: u64) { - let d = Dispatch::best(); - let (kv_heads, group, hd) = (2usize, 8usize, 64usize); - let (kw, qw) = (kv_heads * hd, kv_heads * group * hd); - let positions = pos0 + m; +const KV_HEADS: usize = 2; +const GROUP: usize = 8; +const HEAD_DIM: usize = 64; +const KV_WIDTH: usize = KV_HEADS * HEAD_DIM; +const Q_WIDTH: usize = KV_HEADS * GROUP * HEAD_DIM; + +#[derive(Clone, Copy)] +struct Case { + pos0: usize, + m: usize, + window: usize, +} + +struct Inputs { + q: Vec, + sinks: Vec, + kh: Vec, + vh: Vec, + kwords: Vec, + vwords: Vec, +} + +fn attention_scale() -> f32 { + 1.0 / (HEAD_DIM as f32).sqrt() +} + +fn draw_inputs(d: &Dispatch, case: Case, seed: u64) -> Inputs { + let positions = case.pos0 + case.m; let mut rng = Rng(seed); - let q: Vec = (0..m * qw).map(|_| rng.unit() * 1.5).collect(); - let k: Vec = (0..positions * kw).map(|_| rng.unit() * 1.5).collect(); - let v: Vec = (0..positions * kw).map(|_| rng.unit()).collect(); - let sinks: Vec = (0..kv_heads * group).map(|_| rng.unit() * 2.0).collect(); - let (kh, kwords) = pack_halves(&d, &k); - let (vh, vwords) = pack_halves(&d, &v); + let q: Vec = (0..case.m * Q_WIDTH).map(|_| rng.unit() * 1.5).collect(); + let k: Vec = (0..positions * KV_WIDTH) + .map(|_| rng.unit() * 1.5) + .collect(); + let v: Vec = (0..positions * KV_WIDTH).map(|_| rng.unit()).collect(); + let sinks: Vec = (0..KV_HEADS * GROUP).map(|_| rng.unit() * 2.0).collect(); + let (kh, kwords) = pack_halves(d, &k); + let (vh, vwords) = pack_halves(d, &v); + Inputs { + q, + sinks, + kh, + vh, + kwords, + vwords, + } +} + +fn run_gpu_attention(gpu: &Gpu, case: Case, inputs: &Inputs) -> Vec { let (qb, kb, vb, sb) = ( - gpu.buf_f32(&q), - gpu.buf_u32(&kwords), - gpu.buf_u32(&vwords), - gpu.buf_f32(&sinks), + gpu.buf_f32(&inputs.q), + gpu.buf_u32(&inputs.kwords), + gpu.buf_u32(&inputs.vwords), + gpu.buf_f32(&inputs.sinks), ); - let out = gpu.zeros(m * qw); - let scale = 1.0 / (hd as f32).sqrt(); + let out = gpu.zeros(case.m * Q_WIDTH); + let shape = AttentionShape { + m: case.m, + pos0: case.pos0, + window: case.window, + kv_width: KV_WIDTH, + q_width: Q_WIDTH, + scale: attention_scale(), + }; let mut rec = gpu.recorder(); - rec.attention( - AttentionShape { - m, - pos0, - window, - kv_width: kw, - q_width: qw, - scale, + rec.attention(shape, &qb, &kb, &vb, &sb, &out).unwrap(); + rec.submit().unwrap(); + gpu.read_f32(&out).unwrap() +} + +fn first_attended(pos: usize, window: usize) -> usize { + if window != 0 { + (pos + 1).saturating_sub(window) + } else { + 0 + } +} + +fn query_start(t: usize, kvh: usize) -> usize { + t * Q_WIDTH + kvh * GROUP * HEAD_DIM +} + +fn cpu_group_output(d: &Dispatch, inputs: &Inputs, case: Case, t: usize, kvh: usize) -> Vec { + let pos = case.pos0 + t; + let first = first_attended(pos, case.window); + let attended = pos + 1 - first; + let mut scores = vec![0.0f32; GROUP * attended]; + let mut want = vec![0.0f32; GROUP * HEAD_DIM]; + let start = first * KV_WIDTH + kvh * HEAD_DIM; + let qs = query_start(t, kvh); + ops::attend_group_with_sink( + Group { + queries: &inputs.q[qs..qs + GROUP * HEAD_DIM], + sinks: &inputs.sinks[kvh * GROUP..(kvh + 1) * GROUP], + scale: attention_scale(), }, - &qb, - &kb, - &vb, - &sb, - &out, + KvRows { + keys: &inputs.kh[start..], + values: &inputs.vh[start..], + stride: KV_WIDTH, + }, + attended, + d, + &mut scores, + &mut want, ) .unwrap(); - rec.submit().unwrap(); - let got = gpu.read_f32(&out).unwrap(); + want +} + +fn assert_group_matches(got: &[f32], want: &[f32], case: Case, t: usize, kvh: usize) { + let (pos0, m, window) = (case.pos0, case.m, case.window); + let qs = query_start(t, kvh); + for (i, w) in want.iter().enumerate() { + let g = got[qs + i]; + assert!( + (g - w).abs() <= 2e-5 * (1.0 + w.abs()), + "pos0 {pos0} m {m} window {window}: token {t} kv head {kvh} element {i}: gpu {g} vs cpu {w}" + ); + } +} + +fn attention_case(gpu: &Gpu, pos0: usize, m: usize, window: usize, seed: u64) { + let d = Dispatch::best(); + let case = Case { pos0, m, window }; + let inputs = draw_inputs(&d, case, seed); + let got = run_gpu_attention(gpu, case, &inputs); for t in 0..m { - let pos = pos0 + t; - let first = if window != 0 { - (pos + 1).saturating_sub(window) - } else { - 0 - }; - let attended = pos + 1 - first; - for kvh in 0..kv_heads { - let mut scores = vec![0.0f32; group * attended]; - let mut want = vec![0.0f32; group * hd]; - let start = first * kw + kvh * hd; - let qs = t * qw + kvh * group * hd; - ops::attend_group_with_sink( - Group { - queries: &q[qs..qs + group * hd], - sinks: &sinks[kvh * group..(kvh + 1) * group], - scale, - }, - KvRows { - keys: &kh[start..], - values: &vh[start..], - stride: kw, - }, - attended, - &d, - &mut scores, - &mut want, - ) - .unwrap(); - for (i, w) in want.iter().enumerate() { - let g = got[qs + i]; - assert!( - (g - w).abs() <= 2e-5 * (1.0 + w.abs()), - "pos0 {pos0} m {m} window {window}: token {t} kv head {kvh} element {i}: gpu {g} vs cpu {w}" - ); - } + for kvh in 0..KV_HEADS { + let want = cpu_group_output(&d, &inputs, case, t, kvh); + assert_group_matches(&got, &want, case, t, kvh); } } } diff --git a/crates/igpu/tests/gemm.rs b/crates/igpu/tests/gemm.rs index b1457a85..d438c0a9 100644 --- a/crates/igpu/tests/gemm.rs +++ b/crates/igpu/tests/gemm.rs @@ -6,7 +6,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::simd::{e8m0_half, f16_to_f32}; -use leleka_igpu::{Gpu, WeightKind}; +use leleka_igpu::{Buf, Gpu, GpuActivations, GpuMatrix, WeightKind}; struct Rng(u64); @@ -61,51 +61,103 @@ fn quantize(d: &Dispatch, rng: &mut Rng, m: usize, blocks: usize) -> Vec { out } +#[derive(Clone, Copy)] +struct Shape { + kind: WeightKind, + m: usize, + n: usize, + blocks: usize, +} + +fn draw_weights(rng: &mut Rng, kind: WeightKind, n: usize, blocks: usize) -> Vec { + match kind { + WeightKind::Q8_0 => q8_weights(rng, n, blocks), + WeightKind::Mxfp4 => mxfp4_weights(rng, n, blocks), + } +} + +fn weight_block_bytes(kind: WeightKind) -> usize { + match kind { + WeightKind::Q8_0 => 34, + WeightKind::Mxfp4 => 17, + } +} + +fn run_gpu_matmul(gpu: &Gpu, shape: Shape, w: &[u8], a: &[u8]) -> Vec { + let Shape { kind, m, n, blocks } = shape; + let wm = gpu.upload_matrix(kind, n, blocks * 32, w).unwrap(); + let am = gpu.upload_activations(m, blocks * 32, a).unwrap(); + gpu.matmul(&wm, &am).unwrap() +} + +fn half_scale(row: &[u8], b: usize) -> f64 { + f64::from(f16_to_f32(u16::from_le_bytes([ + row[b * 34], + row[b * 34 + 1], + ]))) +} + +fn weight_scale(kind: WeightKind, wrow: &[u8], b: usize) -> f64 { + match kind { + WeightKind::Q8_0 => half_scale(wrow, b), + WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])), + } +} + +/// Exact value of one output and the sum of the absolute terms, from the CPU integer block sums. +fn reference_output( + d: &Dispatch, + kind: WeightKind, + wrow: &[u8], + arow: &[u8], + blocks: usize, +) -> (f64, f64) { + let mut sums = vec![0i32; blocks]; + match kind { + WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), + WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), + } + let (mut exact, mut magnitude) = (0f64, 0f64); + for (b, sum) in sums.iter().enumerate() { + let term = f64::from(*sum) * half_scale(arow, b) * weight_scale(kind, wrow, b); + exact += term; + magnitude += term.abs(); + } + (exact, magnitude) +} + +fn assert_output_close( + shape: Shape, + at: (usize, usize), + gpu_value: f32, + exact: f64, + magnitude: f64, +) { + let Shape { kind, m, n, blocks } = shape; + let (i, j) = at; + let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23); + let error = (f64::from(gpu_value) - exact).abs(); + assert!( + error <= tolerance.max(1e-30), + "{kind:?} {m}x{n}x{blocks} blocks, output ({i},{j}): gpu {gpu_value} vs exact {exact} (tolerance {tolerance})" + ); +} + fn check(gpu: &Gpu, kind: WeightKind, m: usize, n: usize, blocks: usize, seed: u64) { let d = Dispatch::best(); let mut rng = Rng(seed); - let (w, block_bytes) = match kind { - WeightKind::Q8_0 => (q8_weights(&mut rng, n, blocks), 34), - WeightKind::Mxfp4 => (mxfp4_weights(&mut rng, n, blocks), 17), - }; + let shape = Shape { kind, m, n, blocks }; + let w = draw_weights(&mut rng, kind, n, blocks); let a = quantize(&d, &mut rng, m, blocks); - let wm = gpu.upload_matrix(kind, n, blocks * 32, &w).unwrap(); - let am = gpu.upload_activations(m, blocks * 32, &a).unwrap(); - let got = gpu.matmul(&wm, &am).unwrap(); + let got = run_gpu_matmul(gpu, shape, &w, &a); assert_eq!(got.len(), m * n); - let mut sums = vec![0i32; blocks]; + let block_bytes = weight_block_bytes(kind); for i in 0..m { let arow = &a[i * blocks * 34..(i + 1) * blocks * 34]; for j in 0..n { let wrow = &w[j * blocks * block_bytes..(j + 1) * blocks * block_bytes]; - match kind { - WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), - WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), - } - let (mut exact, mut magnitude) = (0f64, 0f64); - for b in 0..blocks { - let sa = f64::from(f16_to_f32(u16::from_le_bytes([ - arow[b * 34], - arow[b * 34 + 1], - ]))); - let sw = match kind { - WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([ - wrow[b * 34], - wrow[b * 34 + 1], - ]))), - WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])), - }; - let term = f64::from(sums[b]) * sa * sw; - exact += term; - magnitude += term.abs(); - } - let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23); - let error = (f64::from(got[i * n + j]) - exact).abs(); - assert!( - error <= tolerance.max(1e-30), - "{kind:?} {m}x{n}x{blocks} blocks, output ({i},{j}): gpu {} vs exact {exact} (tolerance {tolerance})", - got[i * n + j] - ); + let (exact, magnitude) = reference_output(&d, kind, wrow, arow, blocks); + assert_output_close(shape, (i, j), got[i * n + j], exact, magnitude); } } } @@ -178,9 +230,17 @@ fn shapes_that_do_not_fit_are_refused_without_touching_the_gpu_state() { assert!(w.cols() == 64 && w.rows() == 1 && a.rows() == 1); } -#[test] -fn bias_and_accumulation_are_added_in_the_epilogue() { - let Some(gpu) = gpu() else { return }; +struct EpilogueOperands { + wm: GpuMatrix, + am: GpuActivations, + plain: Vec, + bias: Vec, + start: Vec, + m: usize, + n: usize, +} + +fn arrange_epilogue(gpu: &Gpu) -> EpilogueOperands { let d = Dispatch::best(); let mut rng = Rng(77); let (m, n, blocks) = (9usize, 21usize, 4usize); @@ -193,30 +253,66 @@ fn bias_and_accumulation_are_added_in_the_epilogue() { let plain = gpu.matmul(&wm, &am).unwrap(); let bias: Vec = (0..n).map(|_| rng.unit()).collect(); let start: Vec = (0..m * n).map(|_| rng.unit()).collect(); - let bias_buf = gpu.buf_f32(&bias); - for (use_bias, accumulate) in [(true, false), (false, true), (true, true)] { - let out = gpu.buf_f32(&start); - let mut rec = gpu.recorder(); - rec.matmul(&wm, &am, &out, use_bias.then_some(&bias_buf), accumulate) - .unwrap(); - rec.submit().unwrap(); - let got = gpu.read_f32(&out).unwrap(); - for i in 0..m { - for j in 0..n { - let mut want = plain[i * n + j]; - if use_bias { - want += bias[j]; - } - if accumulate { - want += start[i * n + j]; - } - let g = got[i * n + j]; - // the same f32 adds in the same order inside the kernel: equal up to the one rounding - assert!( - (g - want).abs() <= 1e-5 * (1.0 + want.abs()), - "bias={use_bias} acc={accumulate} ({i},{j}): {g} vs {want}" - ); + EpilogueOperands { + wm, + am, + plain, + bias, + start, + m, + n, + } +} + +fn run_epilogue( + gpu: &Gpu, + ops: &EpilogueOperands, + bias_buf: &Buf, + use_bias: bool, + accumulate: bool, +) -> Vec { + let out = gpu.buf_f32(&ops.start); + let mut rec = gpu.recorder(); + rec.matmul( + &ops.wm, + &ops.am, + &out, + use_bias.then_some(bias_buf), + accumulate, + ) + .unwrap(); + rec.submit().unwrap(); + gpu.read_f32(&out).unwrap() +} + +fn assert_epilogue(ops: &EpilogueOperands, got: &[f32], use_bias: bool, accumulate: bool) { + let n = ops.n; + for i in 0..ops.m { + for j in 0..n { + let mut want = ops.plain[i * n + j]; + if use_bias { + want += ops.bias[j]; } + if accumulate { + want += ops.start[i * n + j]; + } + let g = got[i * n + j]; + // the same f32 adds in the same order inside the kernel: equal up to the one rounding + assert!( + (g - want).abs() <= 1e-5 * (1.0 + want.abs()), + "bias={use_bias} acc={accumulate} ({i},{j}): {g} vs {want}" + ); } } } + +#[test] +fn bias_and_accumulation_are_added_in_the_epilogue() { + let Some(gpu) = gpu() else { return }; + let ops = arrange_epilogue(&gpu); + let bias_buf = gpu.buf_f32(&ops.bias); + for (use_bias, accumulate) in [(true, false), (false, true), (true, true)] { + let got = run_epilogue(&gpu, &ops, &bias_buf, use_bias, accumulate); + assert_epilogue(&ops, &got, use_bias, accumulate); + } +} diff --git a/crates/igpu/tests/moe.rs b/crates/igpu/tests/moe.rs index c54cb275..b7a6aebe 100644 --- a/crates/igpu/tests/moe.rs +++ b/crates/igpu/tests/moe.rs @@ -6,7 +6,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::simd::{e8m0_half, f16_to_f32}; use leleka_gptoss::ops; -use leleka_igpu::{Gpu, SwigluParams, WeightKind}; +use leleka_igpu::{Buf, Gpu, GpuActivations, GpuMatrix, MoePlan, SwigluParams, WeightKind}; struct Rng(u64); @@ -106,37 +106,66 @@ fn swiglu_quant_matches_the_cpu_activation() { compare_quantized(&gpu, &out, &cpu, "swiglu"); } +const ROUTER_TOKENS: usize = 50; +const ROUTER_WIDTH: usize = 2880; + +struct RouterInputs { + h: Vec, + w: Vec, + bias: Vec, +} + +fn draw_router_inputs(rng: &mut Rng) -> RouterInputs { + let (m, e) = (ROUTER_TOKENS, ROUTER_WIDTH); + let h: Vec = (0..m * e).map(|_| rng.unit()).collect(); + let w: Vec = (0..32 * e).map(|_| rng.unit() * 0.05).collect(); + let bias: Vec = (0..32).map(|_| rng.unit() * 0.5).collect(); + RouterInputs { h, w, bias } +} + +fn run_gpu_router(gpu: &Gpu, r: &RouterInputs) -> (Vec, Vec) { + let m = ROUTER_TOKENS; + let (hb, wb, bb) = (gpu.buf_f32(&r.h), gpu.buf_f32(&r.w), gpu.buf_f32(&r.bias)); + let (ids, weights) = (gpu.zeros(m * 4), gpu.zeros(m * 4)); + let mut rec = gpu.recorder(); + rec.router(&hb, &wb, &bb, m, ROUTER_WIDTH, &ids, &weights) + .unwrap(); + rec.submit().unwrap(); + (gpu.read_u32(&ids).unwrap(), gpu.read_f32(&weights).unwrap()) +} + +fn cpu_route(d: &Dispatch, r: &RouterInputs, t: usize) -> Vec<(usize, f32)> { + let e = ROUTER_WIDTH; + let mut logits = vec![0.0f32; 32]; + d.rows_dot(&r.h[t * e..(t + 1) * e], &r.w, e, 32, &mut logits) + .unwrap(); + for (l, b) in logits.iter_mut().zip(&r.bias) { + *l += b; + } + ops::route_top_k(&logits, 4) +} + +fn assert_route(got_ids: &[u32], got_w: &[f32], want: &[(usize, f32)], t: usize) { + for (slot, (ex, weight)) in want.iter().enumerate() { + assert_eq!(got_ids[t * 4 + slot] as usize, *ex, "token {t} slot {slot}"); + assert!( + (got_w[t * 4 + slot] - weight).abs() <= 1e-5, + "token {t} slot {slot}: {} vs {weight}", + got_w[t * 4 + slot] + ); + } +} + #[test] fn router_picks_the_cpu_experts_and_weights() { let Some(gpu) = gpu() else { return }; let d = Dispatch::best(); let mut rng = Rng(13); - let (m, e) = (50usize, 2880usize); - let h: Vec = (0..m * e).map(|_| rng.unit()).collect(); - let w: Vec = (0..32 * e).map(|_| rng.unit() * 0.05).collect(); - let bias: Vec = (0..32).map(|_| rng.unit() * 0.5).collect(); - let (hb, wb, bb) = (gpu.buf_f32(&h), gpu.buf_f32(&w), gpu.buf_f32(&bias)); - let (ids, weights) = (gpu.zeros(m * 4), gpu.zeros(m * 4)); - let mut rec = gpu.recorder(); - rec.router(&hb, &wb, &bb, m, e, &ids, &weights).unwrap(); - rec.submit().unwrap(); - let (got_ids, got_w) = (gpu.read_u32(&ids).unwrap(), gpu.read_f32(&weights).unwrap()); - for t in 0..m { - let mut logits = vec![0.0f32; 32]; - d.rows_dot(&h[t * e..(t + 1) * e], &w, e, 32, &mut logits) - .unwrap(); - for (l, b) in logits.iter_mut().zip(&bias) { - *l += b; - } - let want = ops::route_top_k(&logits, 4); - for (slot, (ex, weight)) in want.iter().enumerate() { - assert_eq!(got_ids[t * 4 + slot] as usize, *ex, "token {t} slot {slot}"); - assert!( - (got_w[t * 4 + slot] - weight).abs() <= 1e-5, - "token {t} slot {slot}: {} vs {weight}", - got_w[t * 4 + slot] - ); - } + let r = draw_router_inputs(&mut rng); + let (got_ids, got_w) = run_gpu_router(&gpu, &r); + for t in 0..ROUTER_TOKENS { + let want = cpu_route(&d, &r, t); + assert_route(&got_ids, &got_w, &want, t); } } @@ -163,101 +192,165 @@ fn reference(d: &Dispatch, w: &[u8], a: &[u8], blocks: usize) -> (f64, f64) { (exact, magnitude) } -#[test] -fn grouped_expert_products_and_combine_match_the_cpu() { - let Some(gpu) = gpu() else { return }; - let d = Dispatch::best(); - let mut rng = Rng(14); - let (experts, n, blocks, m, used) = (6usize, 40usize, 5usize, 70usize, 4usize); - let e = 64usize; // width of the expert outputs for the combine - let w = mxfp4_rows(&mut rng, experts * n, blocks); - let wm = gpu - .upload_matrix(WeightKind::Mxfp4, experts * n, blocks * 32, &w) - .unwrap(); - let bias: Vec = (0..experts * n).map(|_| rng.unit()).collect(); - let bb = gpu.buf_f32(&bias); - let x: Vec = (0..m * blocks * 32).map(|_| rng.unit() * 4.0).collect(); - let mut a = vec![0u8; m * blocks * 34]; - d.quantize_q8_0(&x, &mut a).unwrap(); - let am = gpu.upload_activations(m, blocks * 32, &a).unwrap(); - // each token picks `used` distinct experts +const EXPERTS: usize = 6; +const COLUMNS: usize = 40; +const BLOCKS: usize = 5; +const TOKENS: usize = 70; +const USED: usize = 4; +const WIDTH: usize = 64; // width of the expert outputs for the combine + +struct Grouped { + w: Vec, + wm: GpuMatrix, + bias: Vec, + bb: Buf, + a: Vec, + am: GpuActivations, + chosen: Vec, +} + +/// Each token picks `USED` distinct experts. +fn pick_experts(rng: &mut Rng) -> Vec { let mut chosen = Vec::new(); - for _ in 0..m { + for _ in 0..TOKENS { let mut picks = Vec::new(); - while picks.len() < used { - let ex = (rng.next() % experts as u64) as u32; + while picks.len() < USED { + let ex = (rng.next() % EXPERTS as u64) as u32; if !picks.contains(&ex) { picks.push(ex); } } chosen.extend(picks); } - let plan = gpu.plan_moe(&chosen, used, experts).unwrap(); - assert_eq!(plan.entries(), m * used); - let out = gpu.zeros(plan.entries() * n); + chosen +} + +fn arrange_grouped(gpu: &Gpu, d: &Dispatch, rng: &mut Rng) -> Grouped { + let (n, blocks, m) = (COLUMNS, BLOCKS, TOKENS); + let w = mxfp4_rows(rng, EXPERTS * n, blocks); + let wm = gpu + .upload_matrix(WeightKind::Mxfp4, EXPERTS * n, blocks * 32, &w) + .unwrap(); + let bias: Vec = (0..EXPERTS * n).map(|_| rng.unit()).collect(); + let bb = gpu.buf_f32(&bias); + let x: Vec = (0..m * blocks * 32).map(|_| rng.unit() * 4.0).collect(); + let mut a = vec![0u8; m * blocks * 34]; + d.quantize_q8_0(&x, &mut a).unwrap(); + let am = gpu.upload_activations(m, blocks * 32, &a).unwrap(); + let chosen = pick_experts(rng); + Grouped { + w, + wm, + bias, + bb, + a, + am, + chosen, + } +} + +fn run_grouped_products(gpu: &Gpu, g: &Grouped, plan: &MoePlan) -> Vec { + let out = gpu.zeros(plan.entries() * COLUMNS); let mut rec = gpu.recorder(); - rec.moe_matmul(&wm, &am, &plan, true, Some(&bb), &out) + rec.moe_matmul(&g.wm, &g.am, plan, true, Some(&g.bb), &out) .unwrap(); rec.submit().unwrap(); - let got = gpu.read_f32(&out).unwrap(); - // entry order: by expert, tokens ascending, slots ascending + gpu.read_f32(&out).unwrap() +} + +fn assert_expert_column(d: &Dispatch, g: &Grouped, got: &[f32], at: (usize, usize, usize, usize)) { + let (entry, ex, t, c) = at; + let (n, blocks) = (COLUMNS, BLOCKS); + let wrow = &g.w[(ex * n + c) * blocks * 17..(ex * n + c + 1) * blocks * 17]; + let arow = &g.a[t * blocks * 34..(t + 1) * blocks * 34]; + let (exact, magnitude) = reference(d, wrow, arow, blocks); + let want = exact + f64::from(g.bias[ex * n + c]); + let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23) + 1e-6; + let gv = f64::from(got[entry * n + c]); + assert!( + (gv - want).abs() <= tolerance, + "expert {ex} token {t} column {c}: gpu {gv} vs {want} (tolerance {tolerance})" + ); +} + +/// Entry order: by expert, tokens ascending, slots ascending. +fn assert_products(d: &Dispatch, g: &Grouped, got: &[f32], entries: usize) { let mut entry = 0usize; - for ex in 0..experts { - for (i, pick) in chosen.iter().enumerate() { + for ex in 0..EXPERTS { + for (i, pick) in g.chosen.iter().enumerate() { if *pick as usize != ex { continue; } - let t = i / used; - for c in 0..n { - let wrow = &w[(ex * n + c) * blocks * 17..(ex * n + c + 1) * blocks * 17]; - let arow = &a[t * blocks * 34..(t + 1) * blocks * 34]; - let (exact, magnitude) = reference(&d, wrow, arow, blocks); - let want = exact + f64::from(bias[ex * n + c]); - let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23) + 1e-6; - let g = f64::from(got[entry * n + c]); - assert!( - (g - want).abs() <= tolerance, - "expert {ex} token {t} column {c}: gpu {g} vs {want} (tolerance {tolerance})" - ); + for c in 0..COLUMNS { + assert_expert_column(d, g, got, (entry, ex, i / USED, c)); } entry += 1; } } - assert_eq!(entry, plan.entries()); + assert_eq!(entry, entries); +} - // the combine: down outputs are random, weights random; result = x + sum over slots in order - let down: Vec = (0..plan.entries() * e).map(|_| rng.unit()).collect(); - let weights: Vec = (0..m * used).map(|_| rng.unit().abs()).collect(); - let resid: Vec = (0..m * e).map(|_| rng.unit()).collect(); +struct CombineInputs { + down: Vec, + weights: Vec, + resid: Vec, +} + +/// The combine: down outputs are random, weights random; result = x + sum over slots in order. +fn draw_combine_inputs(rng: &mut Rng, entries: usize) -> CombineInputs { + let down: Vec = (0..entries * WIDTH).map(|_| rng.unit()).collect(); + let weights: Vec = (0..TOKENS * USED).map(|_| rng.unit().abs()).collect(); + let resid: Vec = (0..TOKENS * WIDTH).map(|_| rng.unit()).collect(); + CombineInputs { + down, + weights, + resid, + } +} + +fn run_gpu_combine(gpu: &Gpu, plan: &MoePlan, c: &CombineInputs) -> Vec { let (db, wb, xb) = ( - gpu.buf_f32(&down), - gpu.buf_f32(&weights), - gpu.buf_f32(&resid), + gpu.buf_f32(&c.down), + gpu.buf_f32(&c.weights), + gpu.buf_f32(&c.resid), ); let mut rec = gpu.recorder(); - rec.moe_combine(&db, &plan, &wb, &xb, e).unwrap(); + rec.moe_combine(&db, plan, &wb, &xb, WIDTH).unwrap(); rec.submit().unwrap(); - let got = gpu.read_f32(&xb).unwrap(); - // entry index of each (token, slot): count earlier picks of the same expert - let mut next = vec![0usize; experts]; - let mut start = vec![0usize; experts]; + gpu.read_f32(&xb).unwrap() +} + +fn expert_starts(chosen: &[u32]) -> Vec { + let mut start = vec![0usize; EXPERTS]; let mut total = 0; for (ex, first) in start.iter_mut().enumerate() { *first = total; total += chosen.iter().filter(|p| **p as usize == ex).count(); } + start +} + +/// Entry index of each (token, slot): count earlier picks of the same expert. +fn entry_of_choices(chosen: &[u32]) -> Vec { + let start = expert_starts(chosen); + let mut next = [0usize; EXPERTS]; let mut entry_of = vec![0usize; chosen.len()]; for (i, pick) in chosen.iter().enumerate() { entry_of[i] = start[*pick as usize] + next[*pick as usize]; next[*pick as usize] += 1; } - for t in 0..m { + entry_of +} + +fn assert_combined(got: &[f32], c: &CombineInputs, entry_of: &[usize]) { + let e = WIDTH; + for t in 0..TOKENS { for r in 0..e { let mut acc = 0.0f32; - for s in 0..used { - acc += weights[t * used + s] * down[entry_of[t * used + s] * e + r]; + for s in 0..USED { + acc += c.weights[t * USED + s] * c.down[entry_of[t * USED + s] * e + r]; } - let want = resid[t * e + r] + acc; + let want = c.resid[t * e + r] + acc; assert!( (got[t * e + r] - want).abs() <= 1e-5 * (1.0 + want.abs()), "token {t} element {r}: {} vs {want}", @@ -267,6 +360,22 @@ fn grouped_expert_products_and_combine_match_the_cpu() { } } +#[test] +fn grouped_expert_products_and_combine_match_the_cpu() { + let Some(gpu) = gpu() else { return }; + let d = Dispatch::best(); + let mut rng = Rng(14); + let g = arrange_grouped(&gpu, &d, &mut rng); + let plan = gpu.plan_moe(&g.chosen, USED, EXPERTS).unwrap(); + assert_eq!(plan.entries(), TOKENS * USED); + let got = run_grouped_products(&gpu, &g, &plan); + assert_products(&d, &g, &got, plan.entries()); + + let c = draw_combine_inputs(&mut rng, plan.entries()); + let got = run_gpu_combine(&gpu, &plan, &c); + assert_combined(&got, &c, &entry_of_choices(&g.chosen)); +} + #[test] fn bad_plans_are_refused() { let Some(gpu) = gpu() else { return }; diff --git a/crates/igpu/tests/norm.rs b/crates/igpu/tests/norm.rs index fb99fbcf..70488292 100644 --- a/crates/igpu/tests/norm.rs +++ b/crates/igpu/tests/norm.rs @@ -26,13 +26,21 @@ impl Rng { } } -fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) { - let d = Dispatch::best(); - let mut rng = Rng(seed); +struct GpuNorm { + h: Vec, + words: Vec, + scales: Vec, +} + +fn draw_norm_inputs(rng: &mut Rng, rows: usize, e: usize) -> (Vec, Vec) { let x: Vec = (0..rows * e).map(|_| rng.unit()).collect(); let w: Vec = (0..e).map(|_| 0.5 + rng.unit().abs() * 0.25).collect(); - let eps = 1e-5f32; - let (xb, wb) = (gpu.buf_f32(&x), gpu.buf_f32(&w)); + (x, w) +} + +fn run_gpu_rmsnorm(gpu: &Gpu, x: &[f32], w: &[f32], eps: f32, rows: usize) -> GpuNorm { + let e = w.len(); + let (xb, wb) = (gpu.buf_f32(x), gpu.buf_f32(w)); let normalized = gpu.zeros(rows * e); let act = gpu.new_activations(rows, e).unwrap(); let mut rec = gpu.recorder(); @@ -41,37 +49,64 @@ fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) { rec.submit().unwrap(); let h = gpu.read_f32(&normalized).unwrap(); let (words, scales) = gpu.read_activations(&act).unwrap(); + GpuNorm { h, words, scales } +} + +fn assert_normalized_row(h: &[f32], want: &[f32], r: usize) { + let e = want.len(); + for (i, wv) in want.iter().enumerate() { + let g = h[r * e + i]; + assert!( + (g - wv).abs() <= 1e-5 * (1.0 + wv.abs()), + "row {r} element {i}: gpu {g} vs cpu {wv}" + ); + } +} + +/// Compare one quantized block with the CPU block; returns the number of values off by one step. +fn compare_block(got: &GpuNorm, blk: &[u8], r: usize, b: usize, blocks: usize) -> usize { + let cpu_scale = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]])); + let gpu_scale = got.scales[r * blocks + b]; + assert!( + gpu_scale == cpu_scale, + "row {r} block {b}: scale {gpu_scale} vs {cpu_scale}" + ); + let mut flips = 0usize; + for i in 0..32 { + let g = got.words[(r * blocks + b) * 8 + i / 4].to_le_bytes()[i % 4] as i8; + let c = blk[2 + i] as i8; + let diff = (i32::from(g) - i32::from(c)).abs(); + assert!(diff <= 1, "row {r} block {b} element {i}: {g} vs {c}"); + flips += usize::from(diff != 0); + } + flips +} + +/// Compare the quantized blocks of one row with the CPU quantizer; returns the values off by one step. +fn compare_row_blocks(d: &Dispatch, got: &GpuNorm, want: &[f32], r: usize) -> usize { + let blocks = want.len() / 32; + let mut q = vec![0u8; blocks * 34]; + d.quantize_q8_0(want, &mut q).unwrap(); + let mut flips = 0usize; + for b in 0..blocks { + flips += compare_block(got, &q[b * 34..(b + 1) * 34], r, b, blocks); + } + flips +} + +fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) { + let d = Dispatch::best(); + let mut rng = Rng(seed); + let (x, w) = draw_norm_inputs(&mut rng, rows, e); + let eps = 1e-5f32; + let got = run_gpu_rmsnorm(gpu, &x, &w, eps, rows); - let blocks = e / 32; let mut flips = 0usize; for r in 0..rows { let mut want = vec![0f32; e]; rms_norm(&x[r * e..(r + 1) * e], &w, eps, &mut want); - for (i, wv) in want.iter().enumerate() { - let g = h[r * e + i]; - assert!( - (g - wv).abs() <= 1e-5 * (1.0 + wv.abs()), - "row {r} element {i}: gpu {g} vs cpu {wv}" - ); - } - let mut q = vec![0u8; blocks * 34]; - d.quantize_q8_0(&want, &mut q).unwrap(); - for b in 0..blocks { - let blk = &q[b * 34..(b + 1) * 34]; - let cpu_scale = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]])); - let gpu_scale = scales[r * blocks + b]; - assert!( - gpu_scale == cpu_scale, - "row {r} block {b}: scale {gpu_scale} vs {cpu_scale}" - ); - for i in 0..32 { - let g = words[(r * blocks + b) * 8 + i / 4].to_le_bytes()[i % 4] as i8; - let c = blk[2 + i] as i8; - let diff = (i32::from(g) - i32::from(c)).abs(); - assert!(diff <= 1, "row {r} block {b} element {i}: {g} vs {c}"); - flips += usize::from(diff != 0); - } - } + assert_normalized_row(&got.h, &want, r); + flips += compare_row_blocks(&d, &got, &want, r); } let total = rows * e; assert!( diff --git a/crates/igpu/tests/real_weights.rs b/crates/igpu/tests/real_weights.rs index 9c9bb9b1..2c38633e 100644 --- a/crates/igpu/tests/real_weights.rs +++ b/crates/igpu/tests/real_weights.rs @@ -11,61 +11,107 @@ use std::fs::File; use std::io::BufReader; use std::path::Path; -fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, label: &str) { - let blocks = 90; - let block_bytes = if kind == WeightKind::Q8_0 { 34 } else { 17 }; - assert_eq!(weights.len(), rows * blocks * block_bytes, "{label}"); - let d = Dispatch::best(); +const BLOCKS: usize = 90; + +fn weight_block_bytes(kind: WeightKind) -> usize { + if kind == WeightKind::Q8_0 { 34 } else { 17 } +} + +fn draw_activations(m: usize) -> Vec { let mut state = 0x1234_5678_9ABC_DEF1u64; - let x: Vec = (0..m * blocks * 32) + (0..m * BLOCKS * 32) .map(|_| { state ^= state << 13; state ^= state >> 7; state ^= state << 17; ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 6.0 }) - .collect(); - let mut a = vec![0u8; m * blocks * 34]; + .collect() +} + +fn run_gpu_matmul( + gpu: &Gpu, + kind: WeightKind, + weights: &[u8], + rows: usize, + a: &[u8], + m: usize, +) -> Vec { + let wm = gpu.upload_matrix(kind, rows, BLOCKS * 32, weights).unwrap(); + let am = gpu.upload_activations(m, BLOCKS * 32, a).unwrap(); + gpu.matmul(&wm, &am).unwrap() +} + +fn half_scale(row: &[u8], b: usize) -> f64 { + f64::from(f16_to_f32(u16::from_le_bytes([ + row[b * 34], + row[b * 34 + 1], + ]))) +} + +fn weight_scale(kind: WeightKind, wrow: &[u8], b: usize) -> f64 { + match kind { + WeightKind::Q8_0 => half_scale(wrow, b), + WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])), + } +} + +/// Exact value of one output and the sum of the absolute terms, from the CPU integer block sums. +fn reference_output(d: &Dispatch, kind: WeightKind, wrow: &[u8], arow: &[u8]) -> (f64, f64) { + let mut sums = vec![0i32; BLOCKS]; + match kind { + WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), + WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), + } + let (mut exact, mut magnitude) = (0f64, 0f64); + for (b, sum) in sums.iter().enumerate() { + let term = f64::from(*sum) * half_scale(arow, b) * weight_scale(kind, wrow, b); + exact += term; + magnitude += term.abs(); + } + (exact, magnitude) +} + +/// Assert one output is within the float32 accumulation bound; returns the error as a share of the tolerance. +fn compare_output( + label: &str, + at: (usize, usize), + gpu_value: f32, + exact: f64, + magnitude: f64, +) -> f64 { + let tolerance = (magnitude * (BLOCKS as f64 + 8.0) * 2f64.powi(-23)).max(1e-30); + let error = (f64::from(gpu_value) - exact).abs(); + let (i, j) = at; + assert!( + error <= tolerance, + "{label} ({i},{j}): gpu {gpu_value} vs exact {exact}" + ); + error / tolerance +} + +fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, label: &str) { + let block_bytes = weight_block_bytes(kind); + assert_eq!(weights.len(), rows * BLOCKS * block_bytes, "{label}"); + let d = Dispatch::best(); + let x = draw_activations(m); + let mut a = vec![0u8; m * BLOCKS * 34]; d.quantize_q8_0(&x, &mut a).unwrap(); - let wm = gpu.upload_matrix(kind, rows, blocks * 32, weights).unwrap(); - let am = gpu.upload_activations(m, blocks * 32, &a).unwrap(); - let got = gpu.matmul(&wm, &am).unwrap(); - let mut sums = vec![0i32; blocks]; + let got = run_gpu_matmul(gpu, kind, weights, rows, &a, m); let mut worst = 0f64; // every activation row against a spread of weight rows (all rows would take minutes on one core) for i in 0..m { - let arow = &a[i * blocks * 34..(i + 1) * blocks * 34]; + let arow = &a[i * BLOCKS * 34..(i + 1) * BLOCKS * 34]; for j in (0..rows).step_by(7).chain([rows - 1]) { - let wrow = &weights[j * blocks * block_bytes..(j + 1) * blocks * block_bytes]; - match kind { - WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), - WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(), - } - let (mut exact, mut magnitude) = (0f64, 0f64); - for b in 0..blocks { - let sa = f64::from(f16_to_f32(u16::from_le_bytes([ - arow[b * 34], - arow[b * 34 + 1], - ]))); - let sw = match kind { - WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([ - wrow[b * 34], - wrow[b * 34 + 1], - ]))), - WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])), - }; - let term = f64::from(sums[b]) * sa * sw; - exact += term; - magnitude += term.abs(); - } - let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23); - let error = (f64::from(got[i * rows + j]) - exact).abs(); - worst = worst.max(error / tolerance.max(1e-30)); - assert!( - error <= tolerance.max(1e-30), - "{label} ({i},{j}): gpu {} vs exact {exact}", - got[i * rows + j] - ); + let wrow = &weights[j * BLOCKS * block_bytes..(j + 1) * BLOCKS * block_bytes]; + let (exact, magnitude) = reference_output(&d, kind, wrow, arow); + worst = worst.max(compare_output( + label, + (i, j), + got[i * rows + j], + exact, + magnitude, + )); } } eprintln!( @@ -74,6 +120,71 @@ fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, l ); } +/// The gpt-oss file: its metadata and the mapping of its bytes. +struct Model { + gguf: Gguf, + map: Mapping, +} + +impl Model { + fn open(path: &Path) -> Model { + let size = std::fs::metadata(path).unwrap().len(); + let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap(); + let map = Mapping::open(path).unwrap(); + Model { gguf, map } + } + + fn tensor(&self, name: &str) -> (&[u8], Vec) { + let t = self + .gguf + .tensor(name) + .unwrap_or_else(|| panic!("tensor {name}")); + let start = self.gguf.absolute_offset(t) as usize; + ( + &self.map.as_bytes()[start..start + t.bytes as usize], + t.dims.clone(), + ) + } +} + +const EXPERT_BYTES: usize = 2880 * 90 * 17; + +/// Attention query projection of layer 3 (Q8_0): 4096 rows of 2880. +fn compare_attention_query(gpu: &Gpu, model: &Model) { + let (q, dims) = model.tensor("blk.3.attn_q.weight"); + assert_eq!(dims, vec![2880, 4096]); + compare(gpu, WeightKind::Q8_0, q, 4096, 37, "blk.3.attn_q (Q8_0)"); +} + +/// One expert's gate and up projections of layer 5 (MXFP4): 2880 rows of 2880 each. +fn compare_expert_gate(gpu: &Gpu, model: &Model) { + let (gate, dims) = model.tensor("blk.5.ffn_gate_exps.weight"); + assert_eq!(dims, vec![2880, 2880, 32]); + let expert = &gate[11 * EXPERT_BYTES..12 * EXPERT_BYTES]; + compare( + gpu, + WeightKind::Mxfp4, + expert, + 2880, + 29, + "blk.5.ffn_gate_exps[11] (MXFP4)", + ); +} + +/// The last layer's down projection, last expert. +fn compare_expert_down(gpu: &Gpu, model: &Model) { + let (down, _) = model.tensor("blk.23.ffn_down_exps.weight"); + let expert = &down[31 * EXPERT_BYTES..32 * EXPERT_BYTES]; + compare( + gpu, + WeightKind::Mxfp4, + expert, + 2880, + 8, + "blk.23.ffn_down_exps[31] (MXFP4)", + ); +} + #[test] fn real_attention_and_expert_weights_match_the_cpu_kernels() { let Some(path) = std::env::var_os("LELEKA_GPTOSS_GGUF") else { @@ -84,40 +195,8 @@ fn real_attention_and_expert_weights_match_the_cpu_kernels() { eprintln!("skipped: no GPU"); return; }; - let path = Path::new(&path); - let size = std::fs::metadata(path).unwrap().len(); - let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap(); - let map = Mapping::open(path).unwrap(); - let bytes = map.as_bytes(); - let tensor = |name: &str| { - let t = gguf.tensor(name).unwrap_or_else(|| panic!("tensor {name}")); - let start = gguf.absolute_offset(t) as usize; - (&bytes[start..start + t.bytes as usize], t.dims.clone()) - }; - // attention query projection of layer 3 (Q8_0): 4096 rows of 2880 - let (q, dims) = tensor("blk.3.attn_q.weight"); - assert_eq!(dims, vec![2880, 4096]); - compare(&gpu, WeightKind::Q8_0, q, 4096, 37, "blk.3.attn_q (Q8_0)"); - // one expert's gate and up projections of layer 5 (MXFP4): 2880 rows of 2880 each - let (gate, dims) = tensor("blk.5.ffn_gate_exps.weight"); - assert_eq!(dims, vec![2880, 2880, 32]); - let expert = 2880 * 90 * 17; - compare( - &gpu, - WeightKind::Mxfp4, - &gate[11 * expert..12 * expert], - 2880, - 29, - "blk.5.ffn_gate_exps[11] (MXFP4)", - ); - // the last layer's down projection, last expert - let (down, _) = tensor("blk.23.ffn_down_exps.weight"); - compare( - &gpu, - WeightKind::Mxfp4, - &down[31 * expert..32 * expert], - 2880, - 8, - "blk.23.ffn_down_exps[31] (MXFP4)", - ); + let model = Model::open(Path::new(&path)); + compare_attention_query(&gpu, &model); + compare_expert_gate(&gpu, &model); + compare_expert_down(&gpu, &model); } diff --git a/limits-allowlist.json b/limits-allowlist.json index 96954c7c..301283f8 100644 --- a/limits-allowlist.json +++ b/limits-allowlist.json @@ -1058,16 +1058,6 @@ "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", "owner": "STRA-338" }, - { - "path": "crates/igpu/src/tests.rs", - "name": "threaded_repacking_equals_the_plain_definition", - "fn_lines": 34, - "complexity": 6, - "nesting": 2, - "width": 0, - "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", - "owner": "STRA-338" - }, { "path": "crates/openvino/src/library.rs", "name": "OpenVino::load",