From d8460a0e8d1e1bb3fe6d7323f9d70534fafa1335 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 15 Oct 2026 00:10:43 +0200 Subject: [PATCH] feat: add the leleka-gptoss-igpu crate: GPU prefill of gpt-oss that fills the CPU decoder's KV cache (STRA-219, phase C) - gptoss: PrefillAccelerator hook, Model::prefill_reuse_accelerated, layer/weight views, embed, next_from_hidden (shared with the CPU forward pass), State KV export/import - igpu: threaded weight repacking (131 s -> 6 s of upload for 24 layers), explicit half rounding of block scales (the compiler folds the pack/unpack round trip away), matmul_rows, buffer reads/writes at offsets - teacher-forced gate with GPU prefill: best token 97.1% vs llama.cpp, mean KL 0.0100, NLL +0.0148; vs the CPU decoder KL 0.0067 (see docs/igpu-prefill.md). Experimental, not wired into the worker. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 11 + Cargo.toml | 4 +- .../gpt-oss-20b-teacher-forced/README.md | 8 + crates/gptoss-igpu/Cargo.toml | 19 + .../gptoss-igpu/examples/dump_logprobs_gpu.rs | 80 ++++ crates/gptoss-igpu/examples/gpu_prefill.rs | 182 ++++++++ crates/gptoss-igpu/examples/layer0_probe.rs | 133 ++++++ crates/gptoss-igpu/src/lib.rs | 436 ++++++++++++++++++ crates/gptoss/src/lib.rs | 225 ++++++++- crates/igpu/src/lib.rs | 209 +++++++-- crates/igpu/src/shaders.rs | 24 +- crates/igpu/tests/moe.rs | 2 +- crates/igpu/tests/norm.rs | 2 +- docs/igpu-prefill.md | 62 +++ 14 files changed, 1343 insertions(+), 54 deletions(-) create mode 100644 crates/gptoss-igpu/Cargo.toml create mode 100644 crates/gptoss-igpu/examples/dump_logprobs_gpu.rs create mode 100644 crates/gptoss-igpu/examples/gpu_prefill.rs create mode 100644 crates/gptoss-igpu/examples/layer0_probe.rs create mode 100644 crates/gptoss-igpu/src/lib.rs create mode 100644 docs/igpu-prefill.md diff --git a/Cargo.lock b/Cargo.lock index e8dc7106..f4540ac4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1289,6 +1289,17 @@ dependencies = [ "leleka-gguf", ] +[[package]] +name = "leleka-gptoss-igpu" +version = "0.1.0" +dependencies = [ + "leleka-cpu-kernels", + "leleka-cpu-sys", + "leleka-gguf", + "leleka-gptoss", + "leleka-igpu", +] + [[package]] name = "leleka-harmony" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 521129d4..63796a34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/igpu", "crates/tokenizer", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/igpu", "crates/tokenizer", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/tokenizer", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/tokenizer", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md b/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md index 84de5bee..48e9c27c 100644 --- a/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md +++ b/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md @@ -39,3 +39,11 @@ not a proof. Against the committed reference: best-token agreement at least 95%, mean KL at most 0.012, and mean next-token NLL within 0.02 of llama.cpp's. A change that makes the third row of its own A/B (new vs old build) much larger than 0.005 mean KL is suspect. + +## GPU prefill (experimental, 2026-10-15) + +`cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- ids.txt gpu.jsonl 20` +prefills the ids on the integrated GPU (every position's hidden state), projects each on the CPU and writes the +same format. Against `llama-reference.jsonl`: best token agrees 97.1% (372/383), mean KL 0.0100, NLL 1.2976 vs +1.2828. Against the CPU decoder's own dump: 97.4% (373/383), mean KL 0.0067, NLL 1.2976 vs 1.2979. Details and +caveats in `docs/igpu-prefill.md`. diff --git a/crates/gptoss-igpu/Cargo.toml b/crates/gptoss-igpu/Cargo.toml new file mode 100644 index 00000000..e18b8b83 --- /dev/null +++ b/crates/gptoss-igpu/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "leleka-gptoss-igpu" +version = "0.1.0" +description = "Integrated-GPU prefill for the Leleka gpt-oss decoder: runs the prompt through all layers on the GPU and hands the KV cache to the CPU decoder" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +leleka-gptoss = { path = "../gptoss" } +leleka-igpu = { path = "../igpu" } + +[dev-dependencies] +leleka-cpu-kernels = { path = "../cpu-kernels" } +leleka-cpu-sys = { path = "../cpu-sys" } +leleka-gguf = { path = "../gguf" } + +[lints] +workspace = true diff --git a/crates/gptoss-igpu/examples/dump_logprobs_gpu.rs b/crates/gptoss-igpu/examples/dump_logprobs_gpu.rs new file mode 100644 index 00000000..55382f80 --- /dev/null +++ b/crates/gptoss-igpu/examples/dump_logprobs_gpu.rs @@ -0,0 +1,80 @@ +//! Teacher-forced log-probabilities with the prompt prefilled on the GPU: the same output format as +//! `dump_logprobs` of the CPU decoder, so `compare_logprobs` can compare it with llama.cpp's reference. +//! Every position's hidden state comes from the GPU prefill; the output projection runs on the CPU. +//! +//! Run: `cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- [top_n] [batch]` + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Model, State}; +use leleka_gptoss_igpu::GpuPrefill; +use std::fs::File; +use std::io::{BufReader, BufWriter, Write}; +use std::path::Path; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() < 3 { + eprintln!("usage: dump_logprobs_gpu [top_n] [batch]"); + std::process::exit(2); + } + let ids: Vec = std::fs::read_to_string(&args[1]) + .expect("ids file") + .trim() + .split(',') + .map(|s| s.trim().parse().expect("token id")) + .collect(); + let top_n: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(20); + let batch: usize = args + .get(4) + .and_then(|s| s.parse().ok()) + .unwrap_or(leleka_gptoss_igpu::DEFAULT_BATCH); + let path = Path::new(&args[0]); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let model = Model::load( + std::sync::Arc::new(Mapping::open(path).expect("map model")), + &gguf, + Dispatch::from_env().expect("kernel level"), + std::thread::available_parallelism().map_or(1, |n| n.get()), + ) + .expect("load model"); + let e = model.config.n_embd; + let mut state = State::new(&model.config, ids.len() + 1); + let mut accel = GpuPrefill::new().expect("a GPU").with_batch(batch); + let hidden = accel + .prefill_all_hidden(&model, &mut state, &ids, 0) + .expect("gpu prefill"); + eprintln!("{}", accel.timings().report()); + let mut out = BufWriter::new(File::create(&args[2]).expect("output file")); + for pos in 0..ids.len() { + model + .next_from_hidden(&mut state, &hidden[pos * e..(pos + 1) * e]) + .expect("output projection"); + let logits = &state.logits; + let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum(); + let mut order: Vec = (0..logits.len()).collect(); + order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a]).then(a.cmp(b))); + let top: Vec = order + .iter() + .take(top_n) + .map(|i| format!("[{},{:.6}]", i, f64::from(logits[*i] - max) - z.ln())) + .collect(); + let next = ids + .get(pos + 1) + .map_or("null".to_owned(), |n| n.to_string()); + writeln!( + out, + "{{\"pos\":{pos},\"next\":{next},\"top\":[{}]}}", + top.join(",") + ) + .expect("write"); + } + eprintln!("wrote {} positions", ids.len()); +} diff --git a/crates/gptoss-igpu/examples/gpu_prefill.rs b/crates/gptoss-igpu/examples/gpu_prefill.rs new file mode 100644 index 00000000..92e8c23d --- /dev/null +++ b/crates/gptoss-igpu/examples/gpu_prefill.rs @@ -0,0 +1,182 @@ +//! Prefill the same prompt on the CPU and on the GPU and compare what they leave behind: the last-token +//! distribution (top-1, KL divergence, largest logit gap), the KV caches, and the next few greedy tokens +//! decoded by the CPU from each cache. Also reports the times. Correctness probe, not a benchmark: one +//! run, the machine state is not controlled. +//! +//! Run: `cargo run --release -p leleka-gptoss-igpu --example gpu_prefill -- [decode_tokens] [batch]` + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Model, State}; +use leleka_gptoss_igpu::GpuPrefill; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::time::Instant; + +fn log_softmax(logits: &[f32]) -> Vec { + let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum(); + logits.iter().map(|l| f64::from(l - max) - z.ln()).collect() +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() < 2 { + eprintln!("usage: gpu_prefill [decode_tokens] [batch]"); + std::process::exit(2); + } + let prompt: Vec = if let Some(n) = args[1].strip_prefix("synth:") { + let mut s = 0x2545_F491_4F6C_DD1Du64; + (0..n.parse::().expect("synth:N")) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + 1000 + (s % 60_000) as u32 + }) + .collect() + } else { + args[1] + .split(',') + .map(|s| s.trim().parse().expect("token ids are integers")) + .collect() + }; + let decode: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(8); + let batch: usize = args + .get(3) + .and_then(|s| s.parse().ok()) + .unwrap_or(leleka_gptoss_igpu::DEFAULT_BATCH); + let path = Path::new(&args[0]); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + let model = Model::load( + std::sync::Arc::new(Mapping::open(path).expect("map model")), + &gguf, + Dispatch::from_env().expect("kernel level"), + threads, + ) + .expect("load model"); + let capacity = prompt.len() + decode + 1; + + // CPU + let mut cpu = State::new(&model.config, capacity); + let t = Instant::now(); + let cpu_reuse = model.prefill_reuse(&mut cpu, &prompt).expect("cpu prefill"); + let cpu_s = t.elapsed().as_secs_f64(); + println!( + "cpu prefill: {} tokens in {:.2} s ({:.1} tok/s), next {}", + prompt.len(), + cpu_s, + prompt.len() as f64 / cpu_s, + cpu_reuse.next + ); + + // GPU + let mut accel = GpuPrefill::new().expect("a GPU").with_batch(batch); + println!("gpu: {}, batch {batch}", accel.adapter_name()); + let mut gpu_state = State::new(&model.config, capacity); + let t = Instant::now(); + let gpu_reuse = model + .prefill_reuse_accelerated(&mut gpu_state, &prompt, &mut accel, 1, &mut |_, _| true) + .expect("gpu prefill") + .expect("not cancelled"); + let gpu_s = t.elapsed().as_secs_f64(); + println!( + "gpu prefill: {} tokens in {:.2} s ({:.1} tok/s), next {}\n {}", + prompt.len(), + gpu_s, + prompt.len() as f64 / gpu_s, + gpu_reuse.next, + accel.timings().report() + ); + + // distributions after the last prompt token + let (lp_cpu, lp_gpu) = (log_softmax(&cpu.logits), log_softmax(&gpu_state.logits)); + let kl: f64 = lp_cpu + .iter() + .zip(&lp_gpu) + .map(|(p, q)| p.exp() * (p - q)) + .sum(); + let max_gap = cpu + .logits + .iter() + .zip(&gpu_state.logits) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + println!( + "last token: top-1 {} (cpu {} gpu {}), KL(cpu||gpu) {kl:.6}, max logit gap {max_gap:.4}", + if cpu_reuse.next == gpu_reuse.next { + "agree" + } else { + "DIFFER" + }, + cpu_reuse.next, + gpu_reuse.next + ); + + // caches: fraction of halves that differ, largest relative difference + for l in [0usize, 1, model.config.blocks / 2, model.config.blocks - 1] { + let (ck, cv) = cpu.kv_rows(l, 0, prompt.len()); + let (gk, gv) = gpu_state.kv_rows(l, 0, prompt.len()); + let diff = |a: &[u16], b: &[u16]| { + a.iter().zip(b).filter(|(x, y)| x != y).count() as f64 / a.len() as f64 + }; + println!( + "layer {l}: halves differing keys {:.4} values {:.4}", + diff(&ck, &gk), + diff(&cv, &gv) + ); + let stats = |a: &[u16], b: &[u16]| { + let (mut max_ulp, mut num, mut den) = (0i32, 0f64, 0f64); + for (x, y) in a.iter().zip(b) { + max_ulp = max_ulp.max((i32::from(*x) - i32::from(*y)).abs()); + let (fx, fy) = (f64::from(half(*x)), f64::from(half(*y))); + num += (fx - fy) * (fx - fy); + den += fx * fx; + } + format!( + "max {max_ulp} ulp, relative rms error {:.2e}", + (num / den).sqrt() + ) + }; + println!( + " keys {} | values {}", + stats(&ck, &gk), + stats(&cv, &gv) + ); + } + + // greedy continuation from each cache + let (mut a, mut b) = (cpu_reuse.next, gpu_reuse.next); + let (mut seq_a, mut seq_b) = (vec![a], vec![b]); + for i in 0..decode { + a = model + .forward(&mut cpu, a, prompt.len() + i) + .expect("cpu decode"); + b = model + .forward(&mut gpu_state, b, prompt.len() + i) + .expect("gpu-cache decode"); + seq_a.push(a); + seq_b.push(b); + } + println!("continuation from cpu cache: {seq_a:?}"); + println!("continuation from gpu cache: {seq_b:?}"); +} + +fn half(bits: u16) -> f32 { + let sign = if bits & 0x8000 != 0 { -1.0f32 } else { 1.0 }; + let exp = i32::from((bits >> 10) & 0x1F); + let man = f32::from(bits & 0x3FF); + match exp { + 0 => sign * man * 2f32.powi(-24), + 31 => f32::NAN, + _ => sign * (1.0 + man / 1024.0) * 2f32.powi(exp - 15), + } +} diff --git a/crates/gptoss-igpu/examples/layer0_probe.rs b/crates/gptoss-igpu/examples/layer0_probe.rs new file mode 100644 index 00000000..9c870dcc --- /dev/null +++ b/crates/gptoss-igpu/examples/layer0_probe.rs @@ -0,0 +1,133 @@ +//! Locate where the GPU and CPU first diverge: the first layer's norm, quantization and K projection for a +//! few tokens, stage by stage. +//! +//! Run: `cargo run --release -p leleka-gptoss-igpu --example layer0_probe -- ` + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Kind, Model, ops}; +use leleka_igpu::{Gpu, WeightKind}; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; + +fn main() { + let path = std::env::args().nth(1).expect("model path"); + let path = Path::new(&path); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let d = Dispatch::from_env().expect("kernel level"); + let model = Model::load( + std::sync::Arc::new(Mapping::open(path).expect("map model")), + &gguf, + d, + 4, + ) + .expect("load model"); + let c = &model.config; + let e = c.n_embd; + let tokens = [1000u32, 5000, 20000, 41234, 777, 13, 99999, 55555]; + let m = tokens.len(); + let lv = model.layer_view(0); + let mut x = vec![0.0f32; m * e]; + for (t, row) in x.chunks_exact_mut(e).enumerate() { + model.embed(tokens[t], row).unwrap(); + } + // CPU stages + let mut h = vec![0.0f32; m * e]; + let mut q = vec![0u8; m * e / 32 * 34]; + for t in 0..m { + ops::rms_norm( + &x[t * e..(t + 1) * e], + lv.attn_norm, + c.rms_eps, + &mut h[t * e..(t + 1) * e], + ); + } + d.quantize_q8_0(&h, &mut q).unwrap(); + let wk = &lv.wk; + assert_eq!(wk.kind, Kind::Q8_0); + let rb = wk.cols / 32 * 34; + let mut cpu_k = vec![0.0f32; m * wk.rows]; + for t in 0..m { + for r in 0..wk.rows { + cpu_k[t * wk.rows + r] = d + .dot_q8_0_q8_0(&wk.data[r * rb..(r + 1) * rb], &q[t * rb..(t + 1) * rb]) + .unwrap() + + lv.bk[r]; + } + } + // GPU stages + let gpu = Gpu::new().expect("gpu"); + let xb = gpu.buf_f32(&x); + let wb = gpu.buf_f32(lv.attn_norm); + let hb = gpu.zeros(m * e); + let act = gpu.new_activations(m, e).unwrap(); + let wkm = gpu + .upload_matrix(WeightKind::Q8_0, wk.rows, wk.cols, wk.data) + .unwrap(); + let bias = gpu.buf_f32(lv.bk); + let kb = gpu.zeros(m * wk.rows); + let mut rec = gpu.recorder(); + rec.rmsnorm_quant(&xb, &wb, c.rms_eps, m, e, &hb, &act) + .unwrap(); + rec.matmul(&wkm, &act, &kb, Some(&bias), false).unwrap(); + rec.submit().unwrap(); + let gh = gpu.read_f32(&hb).unwrap(); + let (words, scales) = gpu.read_activations(&act).unwrap(); + let gk = gpu.read_f32(&kb).unwrap(); + + let rel = |a: &[f32], b: &[f32]| { + let (mut num, mut den, mut max) = (0f64, 0f64, 0f64); + for (x, y) in a.iter().zip(b) { + let (x, y) = (f64::from(*x), f64::from(*y)); + num += (x - y) * (x - y); + den += x * x; + max = max.max((x - y).abs()); + } + ((num / den).sqrt(), max) + }; + println!( + "norm output: relative rms {:.2e}, max abs {:.2e}", + rel(&h, &gh).0, + rel(&h, &gh).1 + ); + let (mut flips, mut scale_diff, mut worst) = (0usize, 0usize, 0i32); + for b in 0..m * e / 32 { + let blk = &q[b * 34..(b + 1) * 34]; + let cs = f32::from_bits(0) + half(u16::from_le_bytes([blk[0], blk[1]])); + if (scales[b] - cs).abs() > 0.0 { + scale_diff += 1; + } + for i in 0..32 { + let g = words[b * 8 + i / 4].to_le_bytes()[i % 4] as i8; + let cq = blk[2 + i] as i8; + let diff = (i32::from(g) - i32::from(cq)).abs(); + worst = worst.max(diff); + flips += usize::from(diff != 0); + } + } + println!( + "quantized: {flips} of {} values differ (worst {worst}), {scale_diff} of {} scales differ", + m * e, + m * e / 32 + ); + let (r, max) = rel(&cpu_k, &gk); + println!("K projection: relative rms {r:.2e}, max abs {max:.2e}"); +} + +fn half(bits: u16) -> f32 { + let sign = if bits & 0x8000 != 0 { -1.0f32 } else { 1.0 }; + let exp = i32::from((bits >> 10) & 0x1F); + let man = f32::from(bits & 0x3FF); + match exp { + 0 => sign * man * 2f32.powi(-24), + 31 => f32::NAN, + _ => sign * (1.0 + man / 1024.0) * 2f32.powi(exp - 15), + } +} diff --git a/crates/gptoss-igpu/src/lib.rs b/crates/gptoss-igpu/src/lib.rs new file mode 100644 index 00000000..37b96a1e --- /dev/null +++ b/crates/gptoss-igpu/src/lib.rs @@ -0,0 +1,436 @@ +//! Prefill of the gpt-oss decoder on the integrated GPU (STRA-219). +//! +//! The prompt goes through all layers on the GPU, layer after layer: one layer's weights are repacked and +//! uploaded, every batch of prompt tokens runs through that layer, and the layer's keys and values come back +//! as half-precision rows for the CPU decoder's cache ([`State::store_kv`]). So only one layer of weights is +//! resident on the GPU at a time and the hidden states of the prompt stay there between layers. The CPU +//! then computes the output projection of the last token and decodes as usual, from the cache this +//! produced. +//! +//! The kernels follow the CPU decoder's arithmetic (same quantization of activations, same half-precision +//! cache, same tables) but sum in other orders, so results agree to float accuracy and an occasional +//! quantization step, not bit for bit: this path is *experimental* until its teacher-forced quality gate +//! passes (`benchmarks/quality`). + +use leleka_gptoss::{ + Kind, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, State, + WeightView, +}; +use leleka_igpu::{ + AttentionShape, Buf, Gpu, GpuActivations, GpuError, GpuMatrix, SwigluParams, WeightKind, +}; +use std::time::{Duration, Instant}; + +/// Prompt tokens per GPU batch unless changed with [`GpuPrefill::with_batch`]. +pub const DEFAULT_BATCH: usize = 512; + +/// Where the time of the last prefill went (wall clock, summed over layers and batches). +#[derive(Clone, Debug, Default)] +pub struct Timings { + pub tokens: usize, + /// Repacking and uploading weights. + pub upload: Duration, + /// Attention half of the layers (norm, projections, attention, router), including the wait for it. + pub attention: Duration, + /// Expert half (grouped products, activation, combine), including the wait for it. + pub experts: Duration, + /// Reading the keys and values back into the CPU cache. + pub readback: Duration, + pub total: Duration, +} + +impl Timings { + pub fn report(&self) -> String { + let s = |d: Duration| d.as_secs_f64(); + format!( + "{} tokens in {:.2} s: upload {:.2} | attention {:.2} | experts {:.2} | readback {:.2}", + self.tokens, + s(self.total), + s(self.upload), + s(self.attention), + s(self.experts), + s(self.readback) + ) + } +} + +pub struct GpuPrefill { + gpu: Gpu, + batch: usize, + timings: Timings, +} + +fn gpu_error(e: GpuError) -> ModelError { + ModelError::Invalid(format!("GPU: {e}")) +} + +fn upload(gpu: &Gpu, w: &WeightView<'_>) -> Result { + let kind = match w.kind { + Kind::Q8_0 => WeightKind::Q8_0, + Kind::Mxfp4 => WeightKind::Mxfp4, + }; + gpu.upload_matrix(kind, w.rows, w.cols, w.data) + .map_err(gpu_error) +} + +/// One layer's weights on the GPU. +struct GpuLayer { + attn_norm: Buf, + wq: GpuMatrix, + wk: GpuMatrix, + wv: GpuMatrix, + wo: GpuMatrix, + bq: Buf, + bk: Buf, + bv: Buf, + bo: Buf, + sinks: Buf, + post_norm: Buf, + router_w: Buf, + router_b: Buf, + gate: GpuMatrix, + up: GpuMatrix, + down: GpuMatrix, + gate_b: Buf, + up_b: Buf, + down_b: Buf, +} + +impl GpuLayer { + fn new(gpu: &Gpu, v: &LayerView<'_>) -> Result { + Ok(Self { + attn_norm: gpu.buf_f32(v.attn_norm), + wq: upload(gpu, &v.wq)?, + wk: upload(gpu, &v.wk)?, + wv: upload(gpu, &v.wv)?, + wo: upload(gpu, &v.wo)?, + bq: gpu.buf_f32(v.bq), + bk: gpu.buf_f32(v.bk), + bv: gpu.buf_f32(v.bv), + bo: gpu.buf_f32(v.bo), + sinks: gpu.buf_f32(v.sinks), + post_norm: gpu.buf_f32(v.post_norm), + router_w: gpu.buf_f32(v.router_w), + router_b: gpu.buf_f32(v.router_b), + gate: upload(gpu, &v.gate)?, + up: upload(gpu, &v.up)?, + down: upload(gpu, &v.down)?, + gate_b: gpu.buf_f32(v.gate_b), + up_b: gpu.buf_f32(v.up_b), + down_b: gpu.buf_f32(v.down_b), + }) + } +} + +/// Buffers reused by every batch of every layer. +struct Scratch { + h: Buf, + act: GpuActivations, + q: Buf, + k: Buf, + v: Buf, + attn: Buf, + act_attn: GpuActivations, + ids: Buf, + weights: Buf, + gate: Buf, + up: Buf, + act_ff: GpuActivations, + down: Buf, +} + +impl GpuPrefill { + /// Open the GPU. Fails when there is none (or only a software adapter). + pub fn new() -> Result { + Ok(Self { + gpu: Gpu::new()?, + batch: DEFAULT_BATCH, + timings: Timings::default(), + }) + } + + /// Prompt tokens per GPU batch (larger batches reuse each uploaded weight over more tokens; the + /// scratch buffers grow with it). + pub fn with_batch(mut self, tokens: usize) -> Self { + self.batch = tokens.max(1); + self + } + + pub fn adapter_name(&self) -> String { + self.gpu.adapter_name() + } + + /// Timings of the most recent prefill. + pub fn timings(&self) -> &Timings { + &self.timings + } + + /// The kernels are written for gpt-oss-20b's shapes; reject anything else up front. + fn check(model: &Model) -> Result<(), ModelError> { + let c = &model.config; + let ok = c.head_dim == 64 + && c.n_head == c.n_head_kv * 8 + && c.n_expert == leleka_igpu::ROUTER_EXPERTS + && c.n_expert_used == leleka_igpu::ROUTER_USED + && c.n_embd.is_multiple_of(32) + && c.n_ff.is_multiple_of(32); + if ok { + Ok(()) + } else { + Err(ModelError::Unsupported( + "the GPU prefill is written for head dimension 64, 8 query heads per KV head and 32 experts with 4 used".into(), + )) + } + } + + fn scratch(&self, model: &Model) -> Result { + let c = &model.config; + let (e, qw, kw, ff) = (c.n_embd, c.q_width(), c.kv_width(), c.n_ff); + let b = self.batch; + let g = &self.gpu; + let entries = b * c.n_expert_used; + Ok(Scratch { + h: g.zeros(b * e), + act: g.new_activations(b, e).map_err(gpu_error)?, + q: g.zeros(b * qw), + k: g.zeros(b * kw), + v: g.zeros(b * kw), + attn: g.zeros(b * qw), + act_attn: g.new_activations(b, qw).map_err(gpu_error)?, + ids: g.zeros(entries), + weights: g.zeros(entries), + gate: g.zeros(entries * ff), + up: g.zeros(entries * ff), + act_ff: g.new_activations(entries, ff).map_err(gpu_error)?, + down: g.zeros(entries * e), + }) + } +} + +impl PrefillAccelerator for GpuPrefill { + fn prefill( + &mut self, + model: &Model, + state: &mut State, + tokens: &[u32], + pos0: usize, + progress: &mut dyn FnMut(f64) -> bool, + ) -> Result>, ModelError> { + self.run(model, state, tokens, pos0, progress, false) + } +} + +impl GpuPrefill { + /// As the [`PrefillAccelerator`] implementation, but returns the hidden states of every token + /// (`tokens.len() * n_embd` floats) instead of the last one only; for quality evaluation. + pub fn prefill_all_hidden( + &mut self, + model: &Model, + state: &mut State, + tokens: &[u32], + pos0: usize, + ) -> Result, ModelError> { + Ok(self + .run(model, state, tokens, pos0, &mut |_| true, true)? + .expect("not cancelled")) + } + + fn run( + &mut self, + model: &Model, + state: &mut State, + tokens: &[u32], + pos0: usize, + progress: &mut dyn FnMut(f64) -> bool, + all_hidden: bool, + ) -> Result>, ModelError> { + Self::check(model)?; + let started = Instant::now(); + self.timings = Timings { + tokens: tokens.len(), + ..Timings::default() + }; + let c = &model.config; + let (e, hd, qw, kw, ff) = (c.n_embd, c.head_dim, c.q_width(), c.kv_width(), c.n_ff); + let n = tokens.len(); + if n == 0 || pos0 + n > state.capacity() { + return Err(ModelError::ContextFull { + position: pos0 + n, + capacity: state.capacity(), + }); + } + let gpu = &self.gpu; + + // embeddings and rotation tables, one buffer per batch + let batches: Vec<(usize, usize)> = (0..n) + .step_by(self.batch) + .map(|b0| (b0, self.batch.min(n - b0))) + .collect(); + let mut xs = Vec::with_capacity(batches.len()); + let mut rots = Vec::with_capacity(batches.len()); + for (b0, m) in &batches { + let mut x = vec![0.0f32; m * e]; + for (t, row) in x.chunks_exact_mut(e).enumerate() { + model.embed(tokens[b0 + t], row)?; + } + xs.push(gpu.buf_f32(&x)); + let mut table = vec![0.0f32; m * hd]; + for t in 0..*m { + let mut pairs = vec![(0.0f32, 0.0f32); hd / 2]; + c.yarn.rotation((pos0 + b0 + t) as u32, hd, &mut pairs); + for (i, (cos, sin)) in pairs.iter().enumerate() { + table[t * hd + 2 * i] = *cos; + table[t * hd + 2 * i + 1] = *sin; + } + } + rots.push(gpu.buf_f32(&table)); + } + + let s = self.scratch(model)?; + let positions = pos0 + n; + let kcache = gpu.zeros(positions * kw / 2); + let vcache = gpu.zeros(positions * kw / 2); + let scale = 1.0 / (hd as f32).sqrt(); + let activation = SwigluParams { + alpha: SWIGLU_ALPHA, + limit: SWIGLU_LIMIT, + }; + + for l in 0..c.blocks { + let t0 = Instant::now(); + let lw = GpuLayer::new(gpu, &model.layer_view(l))?; + if pos0 > 0 { + let (k, v) = state.kv_rows(l, 0, pos0); + gpu.write_u32(&kcache, 0, &pack_halves(&k)) + .map_err(gpu_error)?; + gpu.write_u32(&vcache, 0, &pack_halves(&v)) + .map_err(gpu_error)?; + } + self.timings.upload += t0.elapsed(); + let window = if c.is_sliding(l) { c.sliding_window } else { 0 }; + + for (bi, (b0, m)) in batches.iter().enumerate() { + let (b0, m) = (*b0, *m); + let t1 = Instant::now(); + let mut rec = gpu.recorder(); + rec.rmsnorm_quant(&xs[bi], &lw.attn_norm, c.rms_eps, m, e, &s.h, &s.act) + .map_err(gpu_error)?; + rec.matmul_rows(&lw.wq, &s.act, m, &s.q, Some(&lw.bq), false) + .map_err(gpu_error)?; + rec.matmul_rows(&lw.wk, &s.act, m, &s.k, Some(&lw.bk), false) + .map_err(gpu_error)?; + rec.matmul_rows(&lw.wv, &s.act, m, &s.v, Some(&lw.bv), false) + .map_err(gpu_error)?; + rec.rope(&s.q, &rots[bi], m, c.n_head, hd) + .map_err(gpu_error)?; + rec.rope(&s.k, &rots[bi], m, c.n_head_kv, hd) + .map_err(gpu_error)?; + rec.kv_store(&s.k, &kcache, m, kw, pos0 + b0) + .map_err(gpu_error)?; + rec.kv_store(&s.v, &vcache, m, kw, pos0 + b0) + .map_err(gpu_error)?; + rec.attention( + AttentionShape { + m, + pos0: pos0 + b0, + window, + kv_width: kw, + q_width: qw, + scale, + }, + &s.q, + &kcache, + &vcache, + &lw.sinks, + &s.attn, + ) + .map_err(gpu_error)?; + rec.quantize(&s.attn, m, qw, &s.act_attn) + .map_err(gpu_error)?; + rec.matmul_rows(&lw.wo, &s.act_attn, m, &xs[bi], Some(&lw.bo), true) + .map_err(gpu_error)?; + rec.rmsnorm_quant(&xs[bi], &lw.post_norm, c.rms_eps, m, e, &s.h, &s.act) + .map_err(gpu_error)?; + rec.router(&s.h, &lw.router_w, &lw.router_b, m, e, &s.ids, &s.weights) + .map_err(gpu_error)?; + rec.submit().map_err(gpu_error)?; + let chosen = gpu + .read_u32_at(&s.ids, 0, m * c.n_expert_used) + .map_err(gpu_error)?; + self.timings.attention += t1.elapsed(); + + let t2 = Instant::now(); + let plan = gpu + .plan_moe(&chosen, c.n_expert_used, c.n_expert) + .map_err(gpu_error)?; + let entries = plan.entries(); + let mut rec = gpu.recorder(); + rec.moe_matmul(&lw.gate, &s.act, &plan, true, Some(&lw.gate_b), &s.gate) + .map_err(gpu_error)?; + rec.moe_matmul(&lw.up, &s.act, &plan, true, Some(&lw.up_b), &s.up) + .map_err(gpu_error)?; + rec.swiglu_quant(&s.gate, &s.up, entries, ff, activation, &s.act_ff) + .map_err(gpu_error)?; + rec.moe_matmul(&lw.down, &s.act_ff, &plan, false, Some(&lw.down_b), &s.down) + .map_err(gpu_error)?; + rec.moe_combine(&s.down, &plan, &s.weights, &xs[bi], e) + .map_err(gpu_error)?; + rec.submit().map_err(gpu_error)?; + self.timings.experts += t2.elapsed(); + } + + let t3 = Instant::now(); + let first = pos0 * kw / 2; + let words = n * kw / 2; + let keys = gpu.read_u32_at(&kcache, first, words).map_err(gpu_error)?; + let values = gpu.read_u32_at(&vcache, first, words).map_err(gpu_error)?; + state.store_kv(l, pos0, &unpack_halves(&keys), &unpack_halves(&values)); + self.timings.readback += t3.elapsed(); + if !progress((l + 1) as f64 / c.blocks as f64) { + self.timings.total = started.elapsed(); + return Ok(None); + } + } + + let hidden = if all_hidden { + let mut all = Vec::with_capacity(n * e); + for (x, (_, m)) in xs.iter().zip(&batches) { + all.extend(gpu.read_f32_at(x, 0, m * e).map_err(gpu_error)?); + } + all + } else { + let (last, m) = (xs.len() - 1, batches[batches.len() - 1].1); + gpu.read_f32_at(&xs[last], (m - 1) * e, e) + .map_err(gpu_error)? + }; + self.timings.total = started.elapsed(); + Ok(Some(hidden)) + } +} + +/// Two halves per word, the first in the low bits (the layout the kernels use). +fn pack_halves(halves: &[u16]) -> Vec { + halves + .chunks(2) + .map(|p| u32::from(p[0]) | (u32::from(*p.get(1).unwrap_or(&0)) << 16)) + .collect() +} + +fn unpack_halves(words: &[u32]) -> Vec { + words + .iter() + .flat_map(|w| [(w & 0xFFFF) as u16, (w >> 16) as u16]) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn halves_round_trip_through_words() { + let halves = [1u16, 2, 0xFFFF, 0x8000, 7, 9]; + assert_eq!(unpack_halves(&pack_halves(&halves)), halves); + assert_eq!(pack_halves(&[0x1234, 0xABCD]), vec![0xABCD_1234]); + } +} diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index 5b996d51..395f0392 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -1,4 +1,5 @@ -//! gpt-oss decoder on the Leleka CPU kernels. Decode runs one token at a time and prefill runs chunks of\n//! tokens through the same code, so every weight row is read once per chunk. half-precision KV cache. +//! gpt-oss decoder on the Leleka CPU kernels. Decode runs one token at a time and prefill runs chunks of +//! tokens through the same code, so every weight row is read once per chunk. The KV cache is half precision. //! //! Weights stay in the (memory-mapped) model file as ggml blocks and are read in place; only the small //! F32 tensors (norms, biases, router, sinks) are copied. Layer structure and constants follow @@ -25,8 +26,8 @@ const BLOCK: usize = 32; const Q8_0_BYTES: usize = 34; const MXFP4_BYTES: usize = 17; /// Activation constants of the experts (llama.cpp's `swiglu_oai` defaults for gpt-oss). -const SWIGLU_ALPHA: f32 = 1.702; -const SWIGLU_LIMIT: f32 = 7.0; +pub const SWIGLU_ALPHA: f32 = 1.702; +pub const SWIGLU_LIMIT: f32 = 7.0; /// Smallest chunk of rows a participant claims at once. const MIN_CHUNK_ROWS: usize = 16; /// Tokens per prefill chunk unless changed with [Model::set_prefill_chunk]. @@ -150,11 +151,11 @@ impl Config { }) } - fn q_width(&self) -> usize { + pub fn q_width(&self) -> usize { self.n_head * self.head_dim } - fn kv_width(&self) -> usize { + pub fn kv_width(&self) -> usize { self.n_head_kv * self.head_dim } @@ -164,12 +165,58 @@ impl Config { } } +/// Block format of a weight matrix. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Kind { +pub enum Kind { Q8_0, Mxfp4, } +/// A read-only view of a row-major quantized matrix in ggml blocks (`rows` rows of `cols` columns). +#[derive(Clone, Copy, Debug)] +pub struct WeightView<'a> { + pub kind: Kind, + pub rows: usize, + pub cols: usize, + pub data: &'a [u8], +} + +impl<'a> From<&'a QMatrix> for WeightView<'a> { + fn from(m: &'a QMatrix) -> Self { + Self { + kind: m.kind, + rows: m.rows, + cols: m.cols, + data: m.data(), + } + } +} + +/// Read-only access to the weights of one layer, for prefill accelerators. The expert matrices hold +/// `n_expert * n_ff` (gate, up) or `n_expert * n_embd` (down) rows, expert after expert; their biases are laid +/// out the same way. +pub struct LayerView<'a> { + pub attn_norm: &'a [f32], + pub wq: WeightView<'a>, + pub wk: WeightView<'a>, + pub wv: WeightView<'a>, + pub wo: WeightView<'a>, + pub bq: &'a [f32], + pub bk: &'a [f32], + pub bv: &'a [f32], + pub bo: &'a [f32], + pub sinks: &'a [f32], + pub post_norm: &'a [f32], + pub router_w: &'a [f32], + pub router_b: &'a [f32], + pub gate: WeightView<'a>, + pub up: WeightView<'a>, + pub down: WeightView<'a>, + pub gate_b: &'a [f32], + pub up_b: &'a [f32], + pub down_b: &'a [f32], +} + /// A row-major quantized matrix viewed in place in the shared model bytes. #[derive(Clone)] struct QMatrix { @@ -407,6 +454,69 @@ impl Model { &self.dispatch } + /// The weights of layer `l`, for prefill accelerators. + pub fn layer_view(&self, l: usize) -> LayerView<'_> { + let layer = &self.layers[l]; + LayerView { + attn_norm: &layer.attn_norm, + wq: (&layer.wq).into(), + wk: (&layer.wk).into(), + wv: (&layer.wv).into(), + wo: (&layer.wo).into(), + bq: &layer.bq, + bk: &layer.bk, + bv: &layer.bv, + bo: &layer.bo, + sinks: &layer.sinks, + post_norm: &layer.post_norm, + router_w: &layer.router_w, + router_b: &layer.router_b, + gate: (&layer.gate).into(), + up: (&layer.up).into(), + down: (&layer.down).into(), + gate_b: &layer.gate_b, + up_b: &layer.up_b, + down_b: &layer.down_b, + } + } + + /// Dequantize the embedding of `token` into `out` (`n_embd` floats). + pub fn embed(&self, token: u32, out: &mut [f32]) -> Result<(), ModelError> { + if token as usize >= self.config.vocab || out.len() != self.config.n_embd { + return Err(ModelError::TokenOutOfRange(token)); + } + let row_bytes = self.embd.row_bytes(); + dequantize_q8_0_row( + &self.embd.data()[token as usize * row_bytes..(token as usize + 1) * row_bytes], + out, + ); + Ok(()) + } + + /// Final norm, output projection and greedy choice from the hidden state of the last token: fills + /// `state.logits` and returns the greedy token. Shared by the CPU forward pass and accelerators. + pub fn next_from_hidden(&self, state: &mut State, hidden: &[f32]) -> Result { + if hidden.len() != self.config.n_embd { + return Err(ModelError::Invalid(format!( + "hidden state of {} values", + hidden.len() + ))); + } + let mut h = vec![0.0f32; hidden.len()]; + ops::rms_norm(hidden, &self.output_norm, self.config.rms_eps, &mut h); + let hq = self.quantize(&h)?; + state.logits = self + .run_region(vec![MatvecJob { + matrix: self.output.clone(), + first_row: 0, + rows: self.config.vocab, + acts: vec![hq], + bias: None, + }])? + .remove(0); + Ok(argmax(&state.logits) as u32) + } + pub fn threads(&self) -> usize { self.pool.participants() } @@ -497,6 +607,34 @@ impl State { &self.tokens } + /// Copy the keys and values of `layer` at positions `from..to` (half precision, `[position][kv_width]`). + pub fn kv_rows(&self, layer: usize, from: usize, to: usize) -> (Vec, Vec) { + let width = self.k[layer].read().expect("KV cache lock").len() / self.capacity; + let k = self.k[layer].read().expect("KV cache lock"); + let v = self.v[layer].read().expect("KV cache lock"); + ( + k[from * width..to * width].to_vec(), + v[from * width..to * width].to_vec(), + ) + } + + /// Store keys and values (`[position][kv_width]` halves) of `layer` for positions `pos0..`. The cached + /// token list is not changed: call [`State::set_cached_tokens`] once all layers are in. + pub fn store_kv(&mut self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]) { + let mut k = self.k[layer].write().expect("KV cache lock"); + let width = k.len() / self.capacity; + debug_assert!(keys.len() == values.len() && keys.len().is_multiple_of(width)); + k[pos0 * width..pos0 * width + keys.len()].copy_from_slice(keys); + self.v[layer].write().expect("KV cache lock")[pos0 * width..pos0 * width + values.len()] + .copy_from_slice(values); + } + + /// Record that the cache holds exactly `tokens` (their keys and values were stored by the caller). + pub fn set_cached_tokens(&mut self, tokens: &[u32]) { + self.tokens.clear(); + self.tokens.extend_from_slice(tokens); + } + /// Forget every cached position at or after len (the cache contents are overwritten when the /// positions are fed again). pub fn truncate(&mut self, len: usize) { @@ -504,6 +642,21 @@ impl State { } } +/// A prefill that runs on other hardware (the integrated GPU). It runs `tokens` at positions `pos0..` +/// through all layers, stores their keys and values into `state` (it must not change the cached token list), +/// and returns the hidden state of the last token, or `None` when `progress` (given the finished fraction +/// of the work, in 0..=1) asked to stop. +pub trait PrefillAccelerator { + fn prefill( + &mut self, + model: &Model, + state: &mut State, + tokens: &[u32], + pos0: usize, + progress: &mut dyn FnMut(f64) -> bool, + ) -> Result>, ModelError>; +} + /// What [`Model::prefill_reuse`] did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Reuse { @@ -750,6 +903,53 @@ impl Model { })) } + /// As [`Model::prefill_reuse_with`] with the long middle part run by `accelerator` when at least + /// `min_tokens` prompt tokens need computing; shorter prompts take the CPU path. The accelerator + /// returns the hidden state of the last token after storing every layer's keys and values; the output + /// projection and the greedy choice run here ([`Model::next_from_hidden`]). `progress` receives the + /// number of prompt tokens finished (reused ones included) and the total. + pub fn prefill_reuse_accelerated( + &self, + state: &mut State, + prompt: &[u32], + accelerator: &mut dyn PrefillAccelerator, + min_tokens: usize, + progress: &mut dyn FnMut(usize, usize) -> bool, + ) -> Result, ModelError> { + if prompt.is_empty() { + return Err(ModelError::Invalid("empty prompt".into())); + } + let common = state + .tokens + .iter() + .zip(prompt) + .take_while(|(a, b)| a == b) + .count(); + let reused = common.min(prompt.len() - 1); + if prompt.len() - reused < min_tokens { + return self.prefill_reuse_with(state, prompt, progress); + } + state.truncate(reused); + let total = prompt.len(); + let hidden = + accelerator.prefill(self, state, &prompt[reused..], reused, &mut |fraction| { + progress( + reused + ((total - reused) as f64 * fraction) as usize, + total, + ) + })?; + let Some(hidden) = hidden else { + return Ok(None); + }; + state.set_cached_tokens(prompt); + let next = self.next_from_hidden(state, &hidden)?; + Ok(Some(Reuse { + reused, + computed: total - reused, + next, + })) + } + /// Tokens per prefill chunk. pub fn prefill_chunk(&self) -> usize { self.prefill_chunk @@ -1066,18 +1266,7 @@ impl Model { let mut next = None; if want_logits { - ops::rms_norm(&xs[n - 1], &self.output_norm, c.rms_eps, &mut h); - let hq = self.quantize(&h)?; - state.logits = self - .run_region(vec![MatvecJob { - matrix: self.output.clone(), - first_row: 0, - rows: c.vocab, - acts: vec![hq], - bias: None, - }])? - .remove(0); - next = Some(argmax(&state.logits) as u32); + next = Some(self.next_from_hidden(state, &xs[n - 1])?); } lap!(lm_head); state.profile.tokens += n as u32; diff --git a/crates/igpu/src/lib.rs b/crates/igpu/src/lib.rs index c00e31f1..2bcba7ab 100644 --- a/crates/igpu/src/lib.rs +++ b/crates/igpu/src/lib.rs @@ -256,33 +256,83 @@ fn le_words(bytes: &[u8]) -> Vec { .collect() } +/// Blocks per thread's share of a repack, a multiple of 4 so that packed scale words never straddle two +/// shares; 0 means "do it on this thread" (small inputs). +fn repack_share(blocks: usize) -> usize { + const SERIAL_BELOW: usize = 1 << 14; + if blocks < SERIAL_BELOW { + return 0; + } + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + blocks.div_ceil(threads).next_multiple_of(4) +} + +fn q8_0_share(blocks: &[u8], quants: &mut [u32], scales: &mut [u32]) { + let n = blocks.len() / Q8_0_BYTES; + for (i, block) in blocks.as_chunks::().0.iter().enumerate() { + let half = u32::from(u16::from_le_bytes([block[0], block[1]])); + scales[i / 2] |= half << (16 * (i % 2)); + for (j, word) in block[2..].as_chunks::<4>().0.iter().enumerate() { + quants[i * 8 + j] = u32::from_le_bytes(*word); + } + } + debug_assert!(n.div_ceil(2) <= scales.len()); +} + /// ggml Q8_0 blocks (half scale, 32 int8) to int8 words (8 per block) and half scales packed two per word. pub fn repack_q8_0(blocks: &[u8]) -> (Vec, Vec) { let n = blocks.len() / Q8_0_BYTES; - let mut quants = Vec::with_capacity(n * 8); - let mut halves = Vec::with_capacity(n); - for block in blocks.as_chunks::().0 { - halves.push(u16::from_le_bytes([block[0], block[1]])); - quants.extend(le_words(&block[2..])); + let blocks = &blocks[..n * Q8_0_BYTES]; + let mut quants = vec![0u32; n * 8]; + let mut scales = vec![0u32; n.div_ceil(2)]; + let share = repack_share(n); + if share == 0 { + q8_0_share(blocks, &mut quants, &mut scales); + } else { + std::thread::scope(|scope| { + for ((b, q), s) in blocks + .chunks(share * Q8_0_BYTES) + .zip(quants.chunks_mut(share * 8)) + .zip(scales.chunks_mut(share / 2)) + { + scope.spawn(move || q8_0_share(b, q, s)); + } + }); } - let scales = halves - .chunks(2) - .map(|p| u32::from(p[0]) | u32::from(*p.get(1).unwrap_or(&0)) << 16) - .collect(); (quants, scales) } +fn mxfp4_share(blocks: &[u8], nibbles: &mut [u32], exponents: &mut [u32]) { + for (i, block) in blocks.as_chunks::().0.iter().enumerate() { + exponents[i / 4] |= u32::from(block[0]) << (8 * (i % 4)); + for (j, word) in block[1..].as_chunks::<4>().0.iter().enumerate() { + nibbles[i * 4 + j] = u32::from_le_bytes(*word); + } + } +} + /// ggml MXFP4 blocks (E8M0 scale byte, 16 nibble bytes) to nibble words (4 per block) and E8M0 bytes packed /// four per word. pub fn repack_mxfp4(blocks: &[u8]) -> (Vec, Vec) { let n = blocks.len() / MXFP4_BYTES; - let mut nibbles = Vec::with_capacity(n * 4); - let mut exponents = Vec::with_capacity(n); - for block in blocks.as_chunks::().0 { - exponents.push(block[0]); - nibbles.extend(le_words(&block[1..])); + let blocks = &blocks[..n * MXFP4_BYTES]; + let mut nibbles = vec![0u32; n * 4]; + let mut exponents = vec![0u32; n.div_ceil(4)]; + let share = repack_share(n); + if share == 0 { + mxfp4_share(blocks, &mut nibbles, &mut exponents); + } else { + std::thread::scope(|scope| { + for ((b, nb), ex) in blocks + .chunks(share * MXFP4_BYTES) + .zip(nibbles.chunks_mut(share * 4)) + .zip(exponents.chunks_mut(share / 4)) + { + scope.spawn(move || mxfp4_share(b, nb, ex)); + } + }); } - (nibbles, le_words(&exponents)) + (nibbles, exponents) } /// ggml Q8_0 activation blocks to int8 words and f32 scales. @@ -376,11 +426,14 @@ impl Gpu { "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()), + quantize: pipeline("quantize", shaders::with_helpers(shaders::QUANTIZE)), + swiglu_quant: pipeline("swiglu quant", shaders::with_helpers(shaders::SWIGLU_QUANT)), 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()), + rmsnorm_quant: pipeline( + "rmsnorm quant", + shaders::with_helpers(shaders::RMSNORM_QUANT), + ), rope: pipeline("rope", shaders::ROPE.to_owned()), kv_store: pipeline("kv store", shaders::KV_STORE.to_owned()), attention: pipeline("attention", shaders::ATTENTION.to_owned()), @@ -434,7 +487,12 @@ impl Gpu { } } - fn read_bytes(&self, buffer: &wgpu::Buffer, bytes: usize) -> Result, GpuError> { + fn read_bytes( + &self, + buffer: &wgpu::Buffer, + offset: usize, + bytes: usize, + ) -> Result, GpuError> { let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: bytes as u64, @@ -442,7 +500,7 @@ impl Gpu { mapped_at_creation: false, }); let mut encoder = self.device.create_command_encoder(&Default::default()); - encoder.copy_buffer_to_buffer(buffer, 0, &read, 0, bytes as u64); + encoder.copy_buffer_to_buffer(buffer, offset as u64, &read, 0, bytes as u64); self.queue.submit([encoder.finish()]); let slice = read.slice(..); let (sender, receiver) = std::sync::mpsc::channel(); @@ -463,22 +521,60 @@ impl Gpu { pub fn read_f32(&self, buf: &Buf) -> Result, GpuError> { Ok( - bytemuck::cast_slice(&self.read_bytes(&buf.buffer, buf.len.max(1) * 4)?)[..buf.len] + bytemuck::cast_slice(&self.read_bytes(&buf.buffer, 0, buf.len.max(1) * 4)?)[..buf.len] .to_vec(), ) } + /// `count` floats of `buf` starting at element `first`. + pub fn read_f32_at(&self, buf: &Buf, first: usize, count: usize) -> Result, GpuError> { + if first + count > buf.len || count == 0 { + return Err(GpuError::Shape(format!( + "reading {count} floats at {first} of {}", + buf.len + ))); + } + Ok(bytemuck::cast_slice(&self.read_bytes(&buf.buffer, first * 4, count * 4)?).to_vec()) + } + + /// `count` words of `buf` starting at element `first`. + pub fn read_u32_at(&self, buf: &Buf, first: usize, count: usize) -> Result, GpuError> { + if first + count > buf.len || count == 0 { + return Err(GpuError::Shape(format!( + "reading {count} words at {first} of {}", + buf.len + ))); + } + Ok(bytemuck::cast_slice(&self.read_bytes(&buf.buffer, first * 4, count * 4)?).to_vec()) + } + + /// Overwrite words of `buf` starting at element `first`. + pub fn write_u32(&self, buf: &Buf, first: usize, data: &[u32]) -> Result<(), GpuError> { + if first + data.len() > buf.len { + return Err(GpuError::Shape(format!( + "writing {} words at {first} of {}", + data.len(), + buf.len + ))); + } + if !data.is_empty() { + self.queue + .write_buffer(&buf.buffer, (first * 4) as u64, bytemuck::cast_slice(data)); + } + Ok(()) + } + pub fn read_u32(&self, buf: &Buf) -> Result, GpuError> { Ok( - bytemuck::cast_slice(&self.read_bytes(&buf.buffer, buf.len.max(1) * 4)?)[..buf.len] + bytemuck::cast_slice(&self.read_bytes(&buf.buffer, 0, buf.len.max(1) * 4)?)[..buf.len] .to_vec(), ) } /// The int8 words and f32 block scales of device-resident activations. pub fn read_activations(&self, a: &GpuActivations) -> Result<(Vec, Vec), GpuError> { - let quants = self.read_bytes(&a.quants, a.m * a.blocks * 8 * 4)?; - let scales = self.read_bytes(&a.scales, a.m * a.blocks * 4)?; + let quants = self.read_bytes(&a.quants, 0, a.m * a.blocks * 8 * 4)?; + let scales = self.read_bytes(&a.scales, 0, a.m * a.blocks * 4)?; Ok(( bytemuck::cast_slice(&quants).to_vec(), bytemuck::cast_slice(&scales).to_vec(), @@ -719,14 +815,28 @@ impl Recorder<'_> { bias: Option<&Buf>, accumulate: bool, ) -> Result<(), GpuError> { - if w.blocks != a.blocks { + self.matmul_rows(w, a, a.m, out, bias, accumulate) + } + + /// As [`Recorder::matmul`] for the first `m` rows of `a` (scratch activations are sized for the largest + /// batch). + pub fn matmul_rows( + &mut self, + w: &GpuMatrix, + a: &GpuActivations, + m: usize, + out: &Buf, + bias: Option<&Buf>, + accumulate: bool, + ) -> Result<(), GpuError> { + if w.blocks != a.blocks || m > a.m { return Err(GpuError::Shape(format!( - "weights have {} blocks per row, activations {}", - w.blocks, a.blocks + "weights have {} blocks per row, activations {}; {m} of {} rows", + w.blocks, a.blocks, a.m ))); } - let (m, n) = (a.m, w.rows); - if out.len < m * n || bias.is_some_and(|b| b.len < n) { + let n = w.rows; + if m == 0 || out.len < m * n || bias.is_some_and(|b| b.len < n) { return Err(GpuError::Shape(format!( "output of {} floats or bias too small for {m} x {n}", out.len @@ -1216,6 +1326,47 @@ mod tests { 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 || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }; + 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"); + + 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" + ); + } + } + #[test] fn empty_inputs_repack_to_nothing() { assert!(repack_q8_0(&[]).0.is_empty()); diff --git a/crates/igpu/src/shaders.rs b/crates/igpu/src/shaders.rs index 6cfbe7ad..5a64520b 100644 --- a/crates/igpu/src/shaders.rs +++ b/crates/igpu/src/shaders.rs @@ -229,7 +229,7 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid } aq[(row * p.nb + b) * 8u + wd] = packed; } - asc[row * p.nb + b] = unpack2x16float(pack2x16float(vec2(d, 0.0))).x; + asc[row * p.nb + b] = f16_round(d); } } "#; @@ -419,7 +419,7 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid } aq[flat * 8u + wd] = packed; } - asc[flat] = unpack2x16float(pack2x16float(vec2(d, 0.0))).x; + asc[flat] = f16_round(d); } "#; @@ -467,7 +467,7 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid } aq[flat * 8u + wd] = packed; } - asc[flat] = unpack2x16float(pack2x16float(vec2(d, 0.0))).x; + asc[flat] = f16_round(d); } "#; @@ -567,3 +567,21 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid x[flat] += acc; } "#; + +/// `f16_round(x)`: round a non-negative float to the nearest half-precision value (ties to even), as a +/// float. ggml stores the scale of a Q8_0 block as a half, so the product must use the rounded scale. The +/// round trip through `pack2x16float`/`unpack2x16float` is not usable: the compiler folds it away. +const F16_ROUND: &str = r#" +fn f16_round(x: f32) -> f32 { + if (x < 6.103515625e-5) { + return round(x * 16777216.0) / 16777216.0; + } + let b = bitcast(x); + return bitcast((b + 0x0FFFu + ((b >> 13u) & 1u)) & 0xFFFFE000u); +} +"#; + +/// A kernel source with the shared helper functions in front. +pub fn with_helpers(source: &str) -> String { + format!("{F16_ROUND}{source}") +} diff --git a/crates/igpu/tests/moe.rs b/crates/igpu/tests/moe.rs index f723dfda..c54cb275 100644 --- a/crates/igpu/tests/moe.rs +++ b/crates/igpu/tests/moe.rs @@ -42,7 +42,7 @@ fn compare_quantized(gpu: &Gpu, act: &leleka_igpu::GpuActivations, cpu: &[u8], w 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(), + scales[b] == want, "{what}: block {b} scale {} vs {want}", scales[b] ); diff --git a/crates/igpu/tests/norm.rs b/crates/igpu/tests/norm.rs index 5becf0e1..fb99fbcf 100644 --- a/crates/igpu/tests/norm.rs +++ b/crates/igpu/tests/norm.rs @@ -61,7 +61,7 @@ fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) { 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).abs() <= 2e-3 * cpu_scale.abs(), + gpu_scale == cpu_scale, "row {r} block {b}: scale {gpu_scale} vs {cpu_scale}" ); for i in 0..32 { diff --git a/docs/igpu-prefill.md b/docs/igpu-prefill.md new file mode 100644 index 00000000..83cf0ef2 --- /dev/null +++ b/docs/igpu-prefill.md @@ -0,0 +1,62 @@ +# Integrated-GPU prefill (STRA-219) — experimental + +Status: **experimental, off by default, not wired into the worker yet.** Crates: `leleka-igpu` (WGSL kernels on +`wgpu`, Vulkan or DX12), `leleka-gptoss-igpu` (the layer driver, implements `leleka_gptoss::PrefillAccelerator`). +Production serving stays Python-free and works without a GPU; the GPU path is an optional accelerator for the +prompt-processing phase only. + +## What runs where + +* Prefill of a long prompt: all layers on the GPU, layer after layer. One layer's weights are repacked + (threaded) and uploaded, every batch of up to 512 tokens runs through it, and the layer's keys and values are + read back as half-precision rows into the CPU decoder's cache (`State::store_kv`). Only one layer of weights is + on the GPU at a time; the hidden states of the prompt stay there between layers. +* The output projection of the last token and all decoding stay on the CPU (decode is memory-bandwidth bound and + the iGPU shares that bandwidth: ~40 GB/s measured on both sides, see `experiments/igpu-spike`). +* Prompts shorter than the threshold passed to `Model::prefill_reuse_accelerated` and prefix-cache hits take the + CPU path (the cached prefix is uploaded to the GPU per layer when the GPU continues a prompt). + +## Kernels (all tested against the CPU decoder's own functions, `crates/igpu/tests`) + +int8 `dot4I8Packed` GEMM over Q8_0 and MXFP4 weights with bias and residual-accumulate epilogues, grouped MoE +GEMM with a tile table and row gather, RMSNorm+Q8_0 quantize, Q8_0 quantize, SwiGLU-OAI+quantize, RoPE (the +decoder's own rotation table), half-precision KV store, grouped-query attention with sinks (full and sliding), +router logits + top-4 + softmax, slot-ordered expert combine. + +Two findings worth keeping: the compiler folds `unpack2x16float(pack2x16float(x))` to `x`, so Q8_0 block scales +are rounded to half with an explicit bit-level round-to-nearest-even (`f16_round`); and dynamically indexed +private arrays spill, so the generated GEMM code uses named scalars. + +## Numerics and quality gate + +Not bit-identical to the CPU path: activations are quantized to int8 with the same rule (scales rounded to half +exactly like ggml), but the GPU sums in other orders and its division/inverse square root are not exactly +rounded, so about 0.04% of quantized values land one step away. Teacher-forced comparison on the 383-token gate +text (`benchmarks/quality/gpt-oss-20b-teacher-forced`, 2026-10-15, Core Ultra 7 265U, Intel iGPU via Vulkan, +batch 512): + +| Pair | best token agrees | mean KL (shared top-20) | NLL (ours vs reference) | +| --- | --- | --- | --- | +| GPU prefill vs llama.cpp | 97.1% (372/383) | 0.0100 | 1.2976 vs 1.2828 (+0.0148) | +| GPU prefill vs Leleka CPU (AVX-VNNI) | 97.4% (373/383) | 0.0067 | 1.2976 vs 1.2979 | +| CPU (AVX-VNNI) vs llama.cpp (from the gate README) | 97.1% | 0.0080 | +0.0061 | + +The GPU path meets the gate's pass criteria (≥95% agreement, KL ≤ 0.012, NLL within 0.02) and differs from the +CPU path by about the CPU's own scalar-vs-SIMD noise floor (0.0048). One text, one machine: a gate, not a proof. +Greedy continuations of a 128-token synthetic prompt were identical from both caches (8 tokens). + +## Speed (first measurements, no claim yet) + +Not a performance result: no paired A/B at the workloads in the charter, single runs, uncontrolled machine. +128-token synthetic prompt: CPU 7.0 s (18 tok/s), GPU 11.3 s (6.2 s of it repacking and uploading weights). 383-token gate +text on the GPU: 17.0 s (upload 4.7, attention half 2.9, experts 8.7; the CPU was not timed on it). So at short prompts the +GPU path is not faster; the upload per prefill, the partially filled expert tiles and per-batch synchronization +are the visible costs, and attention over long contexts needs the scoring loop optimized (one full layer over a +512-token batch ending at position 4096 takes about 0.52 s). Measured TOPS of the GEMM alone is in +`crates/igpu/examples/gemm_bench.rs`. + +## Next + +Long-prompt A/B (2k-8k tokens) against the CPU path with token counts and distributions as the charter requires; +overlap weight upload with GPU work; optional resident weights when free RAM allows; attention scoring +optimization; the worker-side switch with free-RAM admission (Phase D).