diff --git a/crates/igpu/src/lib.rs b/crates/igpu/src/lib.rs index ac151e4f..c00e31f1 100644 --- a/crates/igpu/src/lib.rs +++ b/crates/igpu/src/lib.rs @@ -112,6 +112,11 @@ pub struct Gpu { info: wgpu::AdapterInfo, gemm_q8: wgpu::ComputePipeline, gemm_mxfp4: wgpu::ComputePipeline, + gemm_moe: wgpu::ComputePipeline, + quantize: wgpu::ComputePipeline, + swiglu_quant: wgpu::ComputePipeline, + router: wgpu::ComputePipeline, + moe_combine: wgpu::ComputePipeline, rmsnorm_quant: wgpu::ComputePipeline, rope: wgpu::ComputePipeline, kv_store: wgpu::ComputePipeline, @@ -175,6 +180,54 @@ struct Quad { d: u32, } +/// Experts the router chooses among, and how many it picks per token (gpt-oss-20b). +pub const ROUTER_EXPERTS: usize = 32; +pub const ROUTER_USED: usize = 4; + +/// The activation's two constants (`alpha`, `limit`). +#[derive(Clone, Copy, Debug)] +pub struct SwigluParams { + pub alpha: f32, + pub limit: f32, +} + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct SwigluUniform { + rows: u32, + n: u32, + nb: u32, + alpha: f32, + limit: f32, + pad: [u32; 3], +} + +/// Which tokens go to which expert for one layer, laid out for the grouped products: entries (a token's +/// choice of an expert) sorted by expert, tokens ascending within an expert, cut into tiles of at most one +/// workgroup's rows. +pub struct MoePlan { + tiles: Buf, + rowmap: Buf, + entry_of: Buf, + tile_count: usize, + entries: usize, + experts: usize, + tokens: usize, + used: usize, +} + +impl MoePlan { + /// Number of (token, expert) entries. + pub fn entries(&self) -> usize { + self.entries + } + + /// Row counts per expert, for tests and diagnostics. + pub fn tiles(&self) -> usize { + self.tile_count + } +} + /// Workgroup counts for `threads` threads in workgroups of `wg`, split over two dimensions when the count /// exceeds the 65535 limit of one (shaders recover the flat group index as `y * num_workgroups.x + x`). fn groups_1d(threads: usize, wg: usize) -> (u32, u32, u32) { @@ -314,8 +367,19 @@ impl Gpu { usage: wgpu::BufferUsages::STORAGE, }); Ok(Self { - gemm_q8: pipeline("gemm q8_0", shaders::gemm(WeightKind::Q8_0, tm, tn)), - gemm_mxfp4: pipeline("gemm mxfp4", shaders::gemm(WeightKind::Mxfp4, tm, tn)), + gemm_q8: pipeline("gemm q8_0", shaders::gemm(WeightKind::Q8_0, tm, tn, false)), + gemm_mxfp4: pipeline( + "gemm mxfp4", + shaders::gemm(WeightKind::Mxfp4, tm, tn, false), + ), + gemm_moe: pipeline( + "gemm moe mxfp4", + shaders::gemm(WeightKind::Mxfp4, tm, tn, true), + ), + quantize: pipeline("quantize", shaders::QUANTIZE.to_owned()), + swiglu_quant: pipeline("swiglu quant", shaders::SWIGLU_QUANT.to_owned()), + router: pipeline("router", shaders::ROUTER.to_owned()), + moe_combine: pipeline("moe combine", shaders::MOE_COMBINE.to_owned()), rmsnorm_quant: pipeline("rmsnorm quant", shaders::RMSNORM_QUANT.to_owned()), rope: pipeline("rope", shaders::ROPE.to_owned()), kv_store: pipeline("kv store", shaders::KV_STORE.to_owned()), @@ -506,6 +570,62 @@ impl Gpu { }) } + /// Group the router's choices (`chosen[t * used + slot]` = expert of token `t`'s `slot`) by expert for the + /// grouped products. + pub fn plan_moe( + &self, + chosen: &[u32], + used: usize, + experts: usize, + ) -> Result { + if used == 0 + || !chosen.len().is_multiple_of(used) + || chosen.iter().any(|e| *e as usize >= experts) + { + return Err(GpuError::Shape(format!( + "{} choices for {used} slots and {experts} experts", + chosen.len() + ))); + } + let tokens = chosen.len() / used; + let mut per_expert: Vec> = vec![Vec::new(); experts]; + for (i, expert) in chosen.iter().enumerate() { + per_expert[*expert as usize].push((i / used) as u32); + } + let rows_per_tile = 8 * self.tile.0 as usize; + let mut rowmap = Vec::with_capacity(chosen.len()); + let mut tiles = Vec::new(); + let mut first = vec![0usize; experts]; + for (expert, list) in per_expert.iter().enumerate() { + first[expert] = rowmap.len(); + for (c, chunk) in list.chunks(rows_per_tile).enumerate() { + tiles.extend([ + expert as u32, + (first[expert] + c * rows_per_tile) as u32, + chunk.len() as u32, + 0, + ]); + } + rowmap.extend_from_slice(list); + } + let mut next = first.clone(); + let mut entry_of = vec![0u32; chosen.len()]; + for (i, expert) in chosen.iter().enumerate() { + entry_of[i] = next[*expert as usize] as u32; + next[*expert as usize] += 1; + } + Ok(MoePlan { + tile_count: tiles.len() / 4, + tiles: self.buf_u32(&tiles), + rowmap: self.buf_u32(&rowmap), + entry_of: self.buf_u32(&entry_of), + entries: chosen.len(), + experts, + tokens, + used, + }) + } + /// A recorder that batches kernel launches into one submission. pub fn recorder(&self) -> Recorder<'_> { Recorder { @@ -697,6 +817,213 @@ impl Recorder<'_> { Ok(()) } + /// Quantize `rows` rows of `e` floats of `x` to Q8_0 into `act`. + pub fn quantize( + &mut self, + x: &Buf, + rows: usize, + e: usize, + act: &GpuActivations, + ) -> Result<(), GpuError> { + if e == 0 || !e.is_multiple_of(BLOCK) || act.m < rows || act.blocks != e / BLOCK { + return Err(GpuError::Shape(format!("quantize of {rows} x {e}"))); + } + if x.len < rows * e { + return Err(GpuError::Shape("a quantize buffer is too small".into())); + } + let gpu = self.gpu; + self.run_simple( + &gpu.quantize, + &Quad { + a: rows as u32, + b: e as u32, + c: (e / BLOCK) as u32, + d: 0, + }, + &[&x.buffer, &act.quants, &act.scales], + groups_1d(rows * e / BLOCK, 64), + ); + Ok(()) + } + + /// The expert activation of `gate` and `up` (`rows` x `n` each) quantized to Q8_0 into `act`. + pub fn swiglu_quant( + &mut self, + gate: &Buf, + up: &Buf, + rows: usize, + n: usize, + activation: SwigluParams, + act: &GpuActivations, + ) -> Result<(), GpuError> { + if n == 0 || !n.is_multiple_of(BLOCK) || act.m < rows || act.blocks != n / BLOCK { + return Err(GpuError::Shape(format!("swiglu of {rows} x {n}"))); + } + if gate.len < rows * n || up.len < rows * n { + return Err(GpuError::Shape("a swiglu buffer is too small".into())); + } + let gpu = self.gpu; + self.run_simple( + &gpu.swiglu_quant, + &SwigluUniform { + rows: rows as u32, + n: n as u32, + nb: (n / BLOCK) as u32, + alpha: activation.alpha, + limit: activation.limit, + pad: [0; 3], + }, + &[&gate.buffer, &up.buffer, &act.quants, &act.scales], + groups_1d(rows * n / BLOCK, 64), + ); + Ok(()) + } + + /// Router logits and top-4 selection for 32 experts: `ids` and `weights` receive `[m][4]` entries. + #[allow(clippy::too_many_arguments)] // mirrors the kernel's bindings + pub fn router( + &mut self, + h: &Buf, + weights: &Buf, + bias: &Buf, + m: usize, + e: usize, + ids: &Buf, + expert_weights: &Buf, + ) -> Result<(), GpuError> { + if m == 0 + || m > 65535 + || h.len < m * e + || weights.len < ROUTER_EXPERTS * e + || bias.len < ROUTER_EXPERTS + || ids.len < m * ROUTER_USED + || expert_weights.len < m * ROUTER_USED + { + return Err(GpuError::Shape(format!("router of {m} x {e}"))); + } + let gpu = self.gpu; + self.run_simple( + &gpu.router, + &Quad { + a: m as u32, + b: e as u32, + c: 0, + d: 0, + }, + &[ + &h.buffer, + &weights.buffer, + &bias.buffer, + &ids.buffer, + &expert_weights.buffer, + ], + (m as u32, 1, 1), + ); + Ok(()) + } + + /// A product over the expert weights `w` (`experts * n` rows) for the compact rows of `plan`: compact row + /// `i` of `out` (`[entries][n]`) is the activation row `plan.rowmap[i]` of `a` when `gather` is set, + /// else row `i` of `a`, times the rows of its expert; plus the expert's slice of `bias` when given. + pub fn moe_matmul( + &mut self, + w: &GpuMatrix, + a: &GpuActivations, + plan: &MoePlan, + gather: bool, + bias: Option<&Buf>, + out: &Buf, + ) -> Result<(), GpuError> { + if w.kind != WeightKind::Mxfp4 { + return Err(GpuError::Shape( + "grouped products are built for MXFP4 experts".into(), + )); + } + if w.blocks != a.blocks || !w.rows.is_multiple_of(plan.experts) { + return Err(GpuError::Shape(format!( + "{} weight rows for {} experts, {} vs {} blocks", + w.rows, plan.experts, w.blocks, a.blocks + ))); + } + let n = w.rows / plan.experts; + if (!gather && a.m < plan.entries) + || out.len < plan.entries * n + || bias.is_some_and(|b| b.len < w.rows) + { + return Err(GpuError::Shape(format!( + "grouped product of {} entries x {n}", + plan.entries + ))); + } + if plan.entries == 0 { + return Ok(()); + } + let dims = Dims { + m: plan.entries as u32, + n: n as u32, + nb: w.blocks as u32, + flags: u32::from(bias.is_some()) | (u32::from(gather) << 2), + }; + let dims_buf = self.uniform(&dims); + let bias_buffer = bias.map_or(&self.gpu.no_bias, |b| &b.buffer); + let groups = ( + n.div_ceil(8 * self.gpu.tile.1 as usize) as u32, + plan.tile_count as u32, + 1, + ); + let gpu = self.gpu; + self.dispatch( + &gpu.gemm_moe, + &[ + entry(0, &dims_buf), + entry(1, &w.quants), + entry(2, &w.scales), + entry(3, &a.quants), + entry(4, &a.scales), + entry(5, &out.buffer), + entry(6, bias_buffer), + entry(7, &plan.tiles.buffer), + entry(8, &plan.rowmap.buffer), + ], + groups, + ); + Ok(()) + } + + /// Add each token's weighted expert outputs (`down`, compact `[entries][e]`) to its residual row of `x`, + /// in slot order. + pub fn moe_combine( + &mut self, + down: &Buf, + plan: &MoePlan, + expert_weights: &Buf, + x: &Buf, + e: usize, + ) -> Result<(), GpuError> { + let m = plan.tokens; + if down.len < plan.entries * e || expert_weights.len < m * plan.used || x.len < m * e { + return Err(GpuError::Shape(format!("moe combine of {m} x {e}"))); + } + let gpu = self.gpu; + self.run_simple( + &gpu.moe_combine, + &Quad { + a: m as u32, + b: e as u32, + c: plan.used as u32, + d: 0, + }, + &[ + &down.buffer, + &plan.entry_of.buffer, + &expert_weights.buffer, + &x.buffer, + ], + groups_1d(m * e, 256), + ); + Ok(()) + } + /// Launch a kernel whose bindings are one uniform block followed by storage buffers 1, 2, ... fn run_simple( &mut self, diff --git a/crates/igpu/src/shaders.rs b/crates/igpu/src/shaders.rs index c2cf4681..6cfbe7ad 100644 --- a/crates/igpu/src/shaders.rs +++ b/crates/igpu/src/shaders.rs @@ -19,7 +19,7 @@ pub const TILE_N: u32 = 4; /// Q8_0 weights: 8 int8 words per block, scales as half floats, two per word. MXFP4 weights: 4 nibble /// words per block (byte `j` holds element `j` low and element `j + 16` high, as in ggml), scales as E8M0 /// bytes, four per word. -pub fn gemm(kind: WeightKind, tm: u32, tn: u32) -> String { +pub fn gemm(kind: WeightKind, tm: u32, tn: u32, moe: bool) -> String { let bm = 8 * tm; let bn = 8 * tn; let mut declare_acc = String::new(); @@ -35,7 +35,7 @@ pub fn gemm(kind: WeightKind, tm: u32, tn: u32) -> String { multiply += &format!(" s_{i}_{j} += dot4I8Packed(a{i}, b{j});\n"); scale += &format!(" acc_{i}_{j} += f32(s_{i}_{j}) * (sa{i} * sw{j});\n"); store += &format!( - " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < dims.m && cc < dims.n) {{ var v = acc_{i}_{j}; if ((dims.flags & 1u) != 0u) {{ v += bias[cc]; }} if ((dims.flags & 2u) != 0u) {{ v += c[r * dims.n + cc]; }} c[r * dims.n + cc] = v; }} }}\n" + " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < rows_valid && cc < dims.n) {{ var v = acc_{i}_{j}; if ((dims.flags & 1u) != 0u) {{ v += bias[wbase + cc]; }} if ((dims.flags & 2u) != 0u) {{ v += c[(out_base + r) * dims.n + cc]; }} c[(out_base + r) * dims.n + cc] = v; }} }}\n" ); } } @@ -57,17 +57,34 @@ pub fn gemm(kind: WeightKind, tm: u32, tn: u32) -> String { let (weight_word, weight_scale) = match kind { WeightKind::Q8_0 => ( // eight int8 words per block, read as they are - "wq[(col0 + r) * dims.nb * 8u + kb * 8u + w]".to_owned(), + "wq[(wbase + col0 + r) * dims.nb * 8u + kb * 8u + w]".to_owned(), // half float: two scales per word - "let s = (col0 + r) * dims.nb + kb; let word = ws[s / 2u]; let pair = unpack2x16float(word); sw_tile[r] = select(pair.x, pair.y, (s & 1u) == 1u);".to_owned(), + "let s = (wbase + col0 + r) * dims.nb + kb; let word = ws[s / 2u]; let pair = unpack2x16float(word); sw_tile[r] = select(pair.x, pair.y, (s & 1u) == 1u);".to_owned(), ), WeightKind::Mxfp4 => ( // output word w: elements 4w..4w+3; words 0..3 take the low nibbles of nibble word w, words // 4..7 the high nibbles of nibble word w - 4 - "decode_mxfp4(wq[((col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)".to_owned(), - "let s = (col0 + r) * dims.nb + kb; let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; sw_tile[r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));".to_owned(), + "decode_mxfp4(wq[((wbase + col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)".to_owned(), + "let s = (wbase + col0 + r) * dims.nb + kb; let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; sw_tile[r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));".to_owned(), ), }; + // Plain products tile the activation rows by workgroup row. The grouped (mixture-of-experts) variant + // takes its tile from a table: the expert, the first compact row and the row count; the weight rows + // start at `expert * n`, the activation row of compact row `i` is `rowmap[i]` (or `i` itself when + // flag 4 is clear), and the output is the compact `[entries][n]` array. + let (extra_bindings, setup, a_row) = if moe { + ( + "@group(0) @binding(7) var tiles: array;\n@group(0) @binding(8) var rowmap: array;", + " let tile_at = wid.y * 4u;\n let expert = tiles[tile_at];\n let start = tiles[tile_at + 1u];\n let rows_valid = tiles[tile_at + 2u];\n let row0 = 0u;\n let wbase = expert * dims.n;\n let out_base = start;", + "select(start + r, rowmap[start + r], (dims.flags & 4u) != 0u)", + ) + } else { + ( + "", + " let row0 = wid.y * BM;\n let rows_valid = dims.m;\n let wbase = 0u;\n let out_base = 0u;", + "(row0 + r)", + ) + }; format!( r#" requires packed_4x8_integer_dot_product; @@ -80,6 +97,7 @@ struct Dims {{ m: u32, n: u32, nb: u32, flags: u32 }} // flags: 1 adds bias[n] @group(0) @binding(4) var asc: array; @group(0) @binding(5) var c: array; @group(0) @binding(6) var bias: array; +{extra_bindings} const BM: u32 = {bm}u; const BN: u32 = {bn}u; @@ -113,7 +131,7 @@ fn main(@builtin(local_invocation_id) lid: vec3, let tx = lid.x; let ty = lid.y; let flat = ty * 8u + tx; - let row0 = wid.y * BM; +{setup} let col0 = wid.x * BN; {declare_acc} for (var kb = 0u; kb < dims.nb; kb++) {{ @@ -122,7 +140,7 @@ fn main(@builtin(local_invocation_id) lid: vec3, let r = idx / 8u; let w = idx % 8u; var v = 0u; - if (row0 + r < dims.m) {{ v = aq[(row0 + r) * dims.nb * 8u + kb * 8u + w]; }} + if (row0 + r < rows_valid) {{ v = aq[{a_row} * dims.nb * 8u + kb * 8u + w]; }} tile_a[w * BM + (r % {tm}u) * 8u + r / {tm}u] = v; }} for (var i = 0u; i < {loads_b}u; i++) {{ @@ -135,7 +153,7 @@ fn main(@builtin(local_invocation_id) lid: vec3, }} if (flat < BM) {{ var v = 0.0; - if (row0 + flat < dims.m) {{ v = asc[(row0 + flat) * dims.nb + kb]; }} + if (row0 + flat < rows_valid) {{ let r = flat; v = asc[{a_row} * dims.nb + kb]; }} sa_tile[flat] = v; }} if (flat < BN) {{ @@ -152,6 +170,9 @@ fn main(@builtin(local_invocation_id) lid: vec3, "#, ta = bm * 8, tb = bn * 8, + extra_bindings = extra_bindings, + setup = setup, + a_row = a_row, ) } @@ -364,3 +385,185 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid o[t * p.qw + head * HD + 2u * lane + 1u] = acc1 / l; } "#; + +/// Quantize `rows` rows of `e` floats to Q8_0 (the quantizer of [`RMSNORM_QUANT`] without the norm). +/// +/// Bindings: 0 params `{rows, e, nb, pad}`; 1 input; 2 quantized words; 3 block scales (half-rounded f32). +/// One thread per block. +pub const QUANTIZE: &str = r#" +struct P { rows: u32, e: u32, nb: u32, pad: u32 } +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var x: array; +@group(0) @binding(2) var aq: array; +@group(0) @binding(3) var asc: array; + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3, + @builtin(num_workgroups) nwg: vec3) { + let flat = (wid.y * nwg.x + wid.x) * 64u + lid.x; + if (flat >= p.rows * p.nb) { return; } + let row = flat / p.nb; + let b = flat % p.nb; + var amax = 0.0; + for (var i = 0u; i < 32u; i++) { + amax = max(amax, abs(x[row * p.e + b * 32u + i])); + } + let d = amax / 127.0; + var id = 0.0; + if (d != 0.0) { id = 1.0 / d; } + for (var wd = 0u; wd < 8u; wd++) { + var packed = 0u; + for (var j = 0u; j < 4u; j++) { + let q = i32(clamp(round(x[row * p.e + b * 32u + wd * 4u + j] * id), -127.0, 127.0)); + packed |= (u32(q) & 255u) << (8u * j); + } + aq[flat * 8u + wd] = packed; + } + asc[flat] = unpack2x16float(pack2x16float(vec2(d, 0.0))).x; +} +"#; + +/// The gpt-oss expert activation (`gate` clamped from above, `linear` clamped to `[-limit, limit]`, +/// `gate * sigmoid(alpha * gate) * (linear + 1)`) followed by Q8_0 quantization of each row. +/// +/// Bindings: 0 params `{rows, n, nb, alpha, limit, pad, pad, pad}`; 1 gate (`[rows][n]`); 2 up; 3 quantized +/// words; 4 block scales. One thread per block. +pub const SWIGLU_QUANT: &str = r#" +struct P { rows: u32, n: u32, nb: u32, alpha: f32, limit: f32, p0: u32, p1: u32, p2: u32 } +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var gate: array; +@group(0) @binding(2) var up: array; +@group(0) @binding(3) var aq: array; +@group(0) @binding(4) var asc: array; + +fn act(g: f32, u: f32) -> f32 { + let x = min(g, p.limit); + let y = clamp(u, -p.limit, p.limit); + let sigmoid = 1.0 / (1.0 + exp(p.alpha * -x)); + return x * sigmoid * (1.0 + y); +} + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3, + @builtin(num_workgroups) nwg: vec3) { + let flat = (wid.y * nwg.x + wid.x) * 64u + lid.x; + if (flat >= p.rows * p.nb) { return; } + let row = flat / p.nb; + let b = flat % p.nb; + let base = row * p.n + b * 32u; + var amax = 0.0; + for (var i = 0u; i < 32u; i++) { + amax = max(amax, abs(act(gate[base + i], up[base + i]))); + } + let d = amax / 127.0; + var id = 0.0; + if (d != 0.0) { id = 1.0 / d; } + for (var wd = 0u; wd < 8u; wd++) { + var packed = 0u; + for (var j = 0u; j < 4u; j++) { + let k = base + wd * 4u + j; + let q = i32(clamp(round(act(gate[k], up[k]) * id), -127.0, 127.0)); + packed |= (u32(q) & 255u) << (8u * j); + } + aq[flat * 8u + wd] = packed; + } + asc[flat] = unpack2x16float(pack2x16float(vec2(d, 0.0))).x; +} +"#; + +/// Router logits (`h x w^T + bias`), the 4 largest (ties to the lower index) and the softmax over exactly +/// those, for 32 experts: `ids[t][slot]`, `weights[t][slot]` in descending logit order. +/// +/// Bindings: 0 params `{m, e, pad, pad}`; 1 normalized rows `[m][e]`; 2 router weights `[32][e]`; 3 router +/// bias `[32]`; 4 chosen expert ids; 5 their weights. One workgroup per token; 256 threads = 32 experts x 8 +/// partial sums. +pub const ROUTER: &str = r#" +struct P { m: u32, e: u32, p0: u32, p1: u32 } +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var h: array; +@group(0) @binding(2) var w: array; +@group(0) @binding(3) var bias: array; +@group(0) @binding(4) var ids: array; +@group(0) @binding(5) var wts: array; + +var partial: array; +var logits: array; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3) { + let t = wid.x; + let ex = lid.x / 8u; + let part = lid.x % 8u; + var s = 0.0; + for (var i = part; i < p.e; i += 8u) { + s += h[t * p.e + i] * w[ex * p.e + i]; + } + partial[lid.x] = s; + workgroupBarrier(); + if (lid.x < 32u) { + var total = 0.0; + for (var j = 0u; j < 8u; j++) { total += partial[lid.x * 8u + j]; } + logits[lid.x] = total + bias[lid.x]; + } + workgroupBarrier(); + if (lid.x == 0u) { + var taken = 0u; // bit set per expert already chosen + var chosen: array; + var value: array; + for (var k = 0u; k < 4u; k++) { + var best = 0u; + var best_value = -3.0e38; + var found = false; + for (var j = 0u; j < 32u; j++) { + if ((taken & (1u << j)) == 0u && (!found || logits[j] > best_value)) { + best = j; + best_value = logits[j]; + found = true; + } + } + taken |= 1u << best; + chosen[k] = best; + value[k] = best_value; + } + let top = value[0]; + var sum = 0.0; + var ex_v: array; + for (var k = 0u; k < 4u; k++) { + ex_v[k] = exp(value[k] - top); + sum += ex_v[k]; + } + for (var k = 0u; k < 4u; k++) { + ids[t * 4u + k] = chosen[k]; + wts[t * 4u + k] = ex_v[k] / sum; + } + } +} +"#; + +/// `x[t][r] += sum over slots (in slot order) of weight[t][slot] * down[entry[t][slot]][r]`: the weighted +/// sum of a token's expert outputs added to the residual. +/// +/// Bindings: 0 params `{m, e, k, pad}`; 1 expert outputs `[entries][e]`; 2 entry index per (token, slot); +/// 3 weights `[m][k]`; 4 residual `x` (`[m][e]`, read-write). One thread per element. +pub const MOE_COMBINE: &str = r#" +struct P { m: u32, e: u32, k: u32, pad: u32 } +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var down: array; +@group(0) @binding(2) var entry_of: array; +@group(0) @binding(3) var wts: array; +@group(0) @binding(4) var x: array; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3, + @builtin(num_workgroups) nwg: vec3) { + let flat = (wid.y * nwg.x + wid.x) * 256u + lid.x; + if (flat >= p.m * p.e) { return; } + let t = flat / p.e; + let r = flat % p.e; + var acc = 0.0; + for (var k = 0u; k < p.k; k++) { + acc += wts[t * p.k + k] * down[entry_of[t * p.k + k] * p.e + r]; + } + x[flat] += acc; +} +"#; diff --git a/crates/igpu/tests/moe.rs b/crates/igpu/tests/moe.rs new file mode 100644 index 00000000..f723dfda --- /dev/null +++ b/crates/igpu/tests/moe.rs @@ -0,0 +1,276 @@ +//! The mixture-of-experts pieces on the GPU against the CPU decoder: quantize, the expert activation with +//! quantization, router top-k, the grouped expert products and the weighted combine. +//! +//! Skipped (with a message) when the machine has no GPU adapter. + +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}; + +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 - 0.5) * 2.0 + } +} + +fn gpu() -> Option { + match Gpu::new() { + Ok(g) => Some(g), + Err(e) => { + eprintln!("skipped: {e}"); + None + } + } +} + +/// Compare GPU Q8_0 activations with the CPU blocks: scales within half rounding, values within one step, +/// and at most 1% of the values off by one. +fn compare_quantized(gpu: &Gpu, act: &leleka_igpu::GpuActivations, cpu: &[u8], what: &str) { + let (words, scales) = gpu.read_activations(act).unwrap(); + let blocks = cpu.len() / 34; + let mut flips = 0usize; + for b in 0..blocks { + let blk = &cpu[b * 34..(b + 1) * 34]; + let want = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]])); + assert!( + (scales[b] - want).abs() <= 2e-3 * want.abs(), + "{what}: block {b} scale {} vs {want}", + scales[b] + ); + for i in 0..32 { + let g = words[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, "{what}: block {b} element {i}: {g} vs {c}"); + flips += usize::from(diff != 0); + } + } + assert!( + flips * 100 <= blocks * 32, + "{what}: {flips} of {} values off by one", + blocks * 32 + ); + eprintln!("{what}: {flips} of {} values off by one", blocks * 32); +} + +#[test] +fn quantize_matches_the_cpu_quantizer() { + let Some(gpu) = gpu() else { return }; + let d = Dispatch::best(); + let mut rng = Rng(11); + let (rows, e) = (37usize, 2880usize); + let x: Vec = (0..rows * e).map(|_| rng.unit() * 6.0).collect(); + let mut cpu = vec![0u8; rows * e / 32 * 34]; + d.quantize_q8_0(&x, &mut cpu).unwrap(); + let xb = gpu.buf_f32(&x); + let act = gpu.new_activations(rows, e).unwrap(); + let mut rec = gpu.recorder(); + rec.quantize(&xb, rows, e, &act).unwrap(); + rec.submit().unwrap(); + compare_quantized(&gpu, &act, &cpu, "quantize"); +} + +#[test] +fn swiglu_quant_matches_the_cpu_activation() { + let Some(gpu) = gpu() else { return }; + let d = Dispatch::best(); + let mut rng = Rng(12); + let (rows, n) = (21usize, 2880usize); + let gate: Vec = (0..rows * n).map(|_| rng.unit() * 12.0).collect(); + let up: Vec = (0..rows * n).map(|_| rng.unit() * 12.0).collect(); + let (alpha, limit) = (1.702f32, 7.0f32); + let mut act = vec![0.0f32; rows * n]; + d.swiglu_oai(&gate, &up, alpha, limit, &mut act).unwrap(); + // the CPU kernel against the scalar definition, so a GPU/CPU gap can be attributed + for i in (0..act.len()).step_by(997) { + let want = ops::swiglu_oai(gate[i], up[i], alpha, limit); + assert!((act[i] - want).abs() <= 1e-5 * (1.0 + want.abs())); + } + let mut cpu = vec![0u8; rows * n / 32 * 34]; + d.quantize_q8_0(&act, &mut cpu).unwrap(); + let (gb, ub) = (gpu.buf_f32(&gate), gpu.buf_f32(&up)); + let out = gpu.new_activations(rows, n).unwrap(); + let mut rec = gpu.recorder(); + rec.swiglu_quant(&gb, &ub, rows, n, SwigluParams { alpha, limit }, &out) + .unwrap(); + rec.submit().unwrap(); + compare_quantized(&gpu, &out, &cpu, "swiglu"); +} + +#[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] + ); + } + } +} + +fn mxfp4_rows(rng: &mut Rng, rows: usize, blocks: usize) -> Vec { + let mut v = Vec::new(); + for _ in 0..rows * blocks { + v.push(112 + (rng.next() % 24) as u8); + v.extend((0..16).map(|_| rng.next() as u8)); + } + v +} + +/// Exact reference of one output: integer block sums from the CPU kernel times the scales, in f64. +fn reference(d: &Dispatch, w: &[u8], a: &[u8], blocks: usize) -> (f64, f64) { + let mut sums = vec![0i32; blocks]; + d.mxfp4_q8_0_block_sums(w, a, &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([a[b * 34], a[b * 34 + 1]]))); + let term = f64::from(sums[b]) * sa * f64::from(e8m0_half(w[b * 17])); + exact += term; + magnitude += term.abs(); + } + (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 + let mut chosen = Vec::new(); + for _ in 0..m { + let mut picks = Vec::new(); + 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); + let mut rec = gpu.recorder(); + rec.moe_matmul(&wm, &am, &plan, true, Some(&bb), &out) + .unwrap(); + rec.submit().unwrap(); + let got = gpu.read_f32(&out).unwrap(); + // entry order: by expert, tokens ascending, slots ascending + let mut entry = 0usize; + for ex in 0..experts { + for (i, pick) in 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})" + ); + } + entry += 1; + } + } + assert_eq!(entry, plan.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(); + let (db, wb, xb) = ( + gpu.buf_f32(&down), + gpu.buf_f32(&weights), + gpu.buf_f32(&resid), + ); + let mut rec = gpu.recorder(); + rec.moe_combine(&db, &plan, &wb, &xb, e).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]; + let mut total = 0; + for (ex, first) in start.iter_mut().enumerate() { + *first = total; + total += chosen.iter().filter(|p| **p as usize == ex).count(); + } + 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 { + 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]; + } + let want = resid[t * e + r] + acc; + assert!( + (got[t * e + r] - want).abs() <= 1e-5 * (1.0 + want.abs()), + "token {t} element {r}: {} vs {want}", + got[t * e + r] + ); + } + } +} + +#[test] +fn bad_plans_are_refused() { + let Some(gpu) = gpu() else { return }; + assert!(gpu.plan_moe(&[0, 1, 2], 2, 4).is_err()); // not a multiple of the slots + assert!(gpu.plan_moe(&[0, 9], 2, 4).is_err()); // expert out of range + assert!(gpu.plan_moe(&[0, 1], 0, 4).is_err()); +}