From 3f63fd0567e3a2a8cb38481be327b40f2150f66f Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:00:33 -0800 Subject: [PATCH 1/8] feat(cuda): the Inkling model's matrix products on the GPU, behind the Products trait; golden checks on the tiny and the real model --- crates/dluth-cuda/Cargo.toml | 4 + crates/dluth-cuda/src/inkling.rs | 185 ++++++++++++++++++ crates/dluth-cuda/src/lib.rs | 1 + .../dluth-cuda/tests/inkling_golden_cuda.rs | 86 ++++++++ 4 files changed, 276 insertions(+) create mode 100644 crates/dluth-cuda/src/inkling.rs create mode 100644 crates/dluth-cuda/tests/inkling_golden_cuda.rs diff --git a/crates/dluth-cuda/Cargo.toml b/crates/dluth-cuda/Cargo.toml index 8e26aaf..73feeb5 100644 --- a/crates/dluth-cuda/Cargo.toml +++ b/crates/dluth-cuda/Cargo.toml @@ -14,10 +14,14 @@ workspace = true [dependencies] # The Backend trait this crate implements for a CUDA device, and its buffer and error types. dluth-core = { version = "0.0.0", path = "../dluth-core" } +# The Inkling forward pass, whose matrix products this crate computes on the device. +dluth-model = { version = "0.0.0", path = "../dluth-model" } [dev-dependencies] # The CPU reference that every GPU kernel's result is compared with. dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" } +# Reads the recorded runs of the reference implementation that the golden tests compare with. +serde_json = "1.0.154" [build-dependencies] # Generates Rust declarations for the CUDA driver API from NVIDIA's own header at build time, diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs new file mode 100644 index 0000000..df57134 --- /dev/null +++ b/crates/dluth-cuda/src/inkling.rs @@ -0,0 +1,185 @@ +//! The Inkling model's matrix products on the GPU. +//! +//! `CudaProducts` implements the model crate's `Products` trait: the forward pass stays the +//! one written and checked on the CPU, and only its matrix products, which are almost all +//! the bytes a token reads, run on the device. Each product copies its input vector to the +//! device, launches a kernel, waits, and copies the result back. That round trip is the +//! price of this first step; later steps keep more of a token on the device. +//! +//! Weights are copied to the device the first time a matrix is used, in the form the file +//! stores them, and stay there. + +use crate::blockmat::{BlockFormat, BlockMat, BlockMatrices, Job, JOB_BYTES}; +use crate::device::CudaDevice; +use crate::error::CudaError; +use crate::matmat::{Bf16Matrix, Matmat}; +use crate::module::Module; +use dluth_core::{Backend, Buffer, CoreError}; +use dluth_model::inkling::{ExpertFormat, ExpertMatrices, Products}; +use dluth_model::ModelError; +use std::collections::HashMap; + +/// Threads per row for the matrix kernels: the measured best on the real shapes. +const SEGS: u32 = 16; + +fn failed(e: impl std::fmt::Display) -> ModelError { + ModelError::Device(e.to_string()) +} + +/// A device buffer that is replaced by a larger one when more room is needed. +struct Growing { + buffer: Option, +} + +impl Growing { + fn at_least(&mut self, dev: &CudaDevice, bytes: usize) -> Result { + match self.buffer { + Some(b) if b.bytes >= bytes => Ok(b), + old => { + if let Some(b) = old { + dev.free(b)?; + } + // Room to spare, so a slightly larger request does not allocate again. + let b = dev.alloc(bytes.next_power_of_two().max(4096))?; + self.buffer = Some(b); + Ok(b) + } + } + } +} + +/// The matrix products of an Inkling forward pass, computed on a CUDA device. +pub struct CudaProducts<'m> { + dev: &'m CudaDevice, + matmat: Matmat<'m>, + blockmat: BlockMat<'m>, + /// Weights already on the device, by where their bytes start in the weight file's + /// mapping: the device copy and how many bytes it holds. + uploaded: HashMap, + /// Bytes of weights on the device. + weight_bytes: usize, + x: Growing, + y: Growing, + jobs: Growing, +} + +impl<'m> CudaProducts<'m> { + pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { + Ok(CudaProducts { + dev, + matmat: Matmat::new(dev, module)?, + blockmat: BlockMat::new(dev, module)?, + uploaded: HashMap::new(), + weight_bytes: 0, + x: Growing { buffer: None }, + y: Growing { buffer: None }, + jobs: Growing { buffer: None }, + }) + } + + /// Bytes of weights copied to the device so far. + pub fn weight_bytes(&self) -> usize { + self.weight_bytes + } + + /// The device copy of `bytes`, made on first use. A slice is recognised by where it + /// starts, so the same matrix must always be passed with the same length. + fn on_device(&mut self, bytes: &[u8]) -> Result { + let key = bytes.as_ptr() as usize; + if let Some(&buffer) = self.uploaded.get(&key) { + if buffer.bytes != bytes.len() { + return Err(ModelError::Device(format!( + "a weight slice of {} bytes was first used with {} bytes", + bytes.len(), + buffer.bytes + ))); + } + return Ok(buffer); + } + let buffer = self.dev.alloc(bytes.len()).map_err(failed)?; + self.dev.upload(&buffer, bytes).map_err(failed)?; + self.uploaded.insert(key, buffer); + self.weight_bytes += bytes.len(); + Ok(buffer) + } + + fn send(&mut self, values: &[f32]) -> Result { + let buffer = self.x.at_least(self.dev, values.len() * 4).map_err(failed)?; + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + self.dev.upload(&buffer, &bytes).map_err(failed)?; + Ok(buffer) + } + + /// Waits for the device and copies `out.len()` floats back from `buffer`. + fn receive(&self, buffer: &Buffer, out: &mut [f32]) -> Result<(), ModelError> { + self.dev.synchronize().map_err(failed)?; + let mut bytes = vec![0u8; out.len() * 4]; + self.dev.download(buffer, &mut bytes).map_err(failed)?; + for (o, chunk) in out.iter_mut().zip(bytes.as_chunks::<4>().0) { + *o = f32::from_le_bytes(*chunk); + } + Ok(()) + } +} + +impl Products for CudaProducts<'_> { + fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &[f32], out: &mut [f32]) -> Result<(), ModelError> { + if w.len() != rows * cols * 2 || x.len() != cols || out.len() != rows { + return Err(ModelError::Device(format!( + "a BF16 product of {rows} by {cols} with {} weight bytes, {} inputs and {} outputs", + w.len(), + x.len(), + out.len() + ))); + } + let weights = self.on_device(w)?; + let dx = self.send(x)?; + let dy = self.y.at_least(self.dev, rows * 4).map_err(failed)?; + self.matmat.bf16(Bf16Matrix { buffer: &weights, offset: 0, rows, cols }, &dx, 1, &dy, SEGS).map_err(failed)?; + self.receive(&dy, out) + } + + fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { + let (rows, cols) = m.shape(); + if jobs.is_empty() || out.len() != jobs.len() * rows || jobs.iter().any(|(_, x)| x.len() != cols) { + return Err(ModelError::Device(format!( + "{} expert products of {rows} by {cols} with {} outputs", + jobs.len(), + out.len() + ))); + } + let (values, scales) = (self.on_device(m.values())?, self.on_device(m.scales())?); + let (per_values, per_scales) = m.bytes_per_expert(); + let inputs: Vec = jobs.iter().flat_map(|(_, x)| x.iter().copied()).collect(); + let dx = self.send(&inputs)?; + let dy = self.y.at_least(self.dev, out.len() * 4).map_err(failed)?; + let scratch = self.jobs.at_least(self.dev, jobs.len() * JOB_BYTES).map_err(failed)?; + let list: Vec = jobs + .iter() + .enumerate() + .map(|(j, &(expert, _))| Job { + values: expert * per_values, + scales: expert * per_scales, + factor: m.factor(expert), + vectors: vec![(j * cols, j)], + }) + .collect(); + let format = match m.format() { + ExpertFormat::Nvfp4 => BlockFormat::Nvfp4, + ExpertFormat::Mxfp8 => BlockFormat::Mxfp8, + }; + let matrices = BlockMatrices { format, values: &values, scales: &scales, rows, cols }; + self.blockmat.run(matrices, &list, &dx, &dy, &scratch, SEGS).map_err(failed)?; + self.receive(&dy, out) + } +} + +impl Drop for CudaProducts<'_> { + fn drop(&mut self) { + // Everything goes back to the device; a failure leaves it to the context's end. + let scratch = [self.x.buffer, self.y.buffer, self.jobs.buffer]; + for buffer in self.uploaded.values().copied().chain(scratch.into_iter().flatten()) { + let _ = self.dev.free(buffer); + } + } +} diff --git a/crates/dluth-cuda/src/lib.rs b/crates/dluth-cuda/src/lib.rs index b4e2f4b..70b4104 100644 --- a/crates/dluth-cuda/src/lib.rs +++ b/crates/dluth-cuda/src/lib.rs @@ -11,6 +11,7 @@ pub mod blockmat; mod device; mod error; mod image; +pub mod inkling; pub mod matmat; mod module; pub mod probe; diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs new file mode 100644 index 0000000..d65d160 --- /dev/null +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -0,0 +1,86 @@ +//! The Inkling forward pass with its matrix products on the GPU, against the same recorded +//! runs of the reference implementation that the CPU model is checked with. +//! GPU tests; they need an NVIDIA GPU of the architecture the kernels were built for. + +#[path = "../../dluth-model/tests/common/mod.rs"] +mod common; + +use dluth_cuda::inkling::CudaProducts; +use dluth_cuda::{CudaDevice, Module}; +use dluth_model::inkling::{load_config, InklingCpu}; +use dluth_model::weights::Weights; +use std::path::{Path, PathBuf}; + +#[test] +fn the_tiny_model_matches_the_reference_with_products_on_the_gpu() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let golden: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("golden.json")).unwrap()).unwrap(); + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + // The same bar as the CPU model's test: four times the reference's own difference. + let tol = 4.0 * golden["reference_self_difference"].as_f64().unwrap() as f32; + assert!(tol > 0.0 && tol < 0.005, "tolerance {tol}"); + for case in golden["cases"].as_array().unwrap() { + let products = CudaProducts::new(&dev, &module).unwrap(); + let mut model = + InklingCpu::with_products(load_config(&dir).unwrap(), &weights, 64, Box::new(products)).unwrap(); + let report = common::check_case(&mut |token, pos| model.forward_token(token, pos).unwrap(), case, tol); + eprintln!("{}: {report:?}", case["prompt"]); + assert_eq!(report.tie_at, None, "{}", case["prompt"]); + assert_eq!(report.tokens_checked, 24, "{}", case["prompt"]); + } +} + +#[test] +fn the_tiny_model_on_the_gpu_stays_close_to_the_cpu_model() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let products = CudaProducts::new(&dev, &module).unwrap(); + let mut gpu = InklingCpu::with_products(load_config(&dir).unwrap(), &weights, 64, Box::new(products)).unwrap(); + let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let mut worst = 0.0f32; + // Past the window, the reach and the position where queries start to be scaled. + for pos in 0..40 { + let token = ((pos * 37 + 11) % 256) as u32; + let (a, b) = (gpu.forward_token(token, pos).unwrap(), cpu.forward_token(token, pos).unwrap()); + for (x, y) in a.iter().zip(&b) { + worst = worst.max((x - y).abs()); + } + } + eprintln!("largest difference between the scores of the two: {worst}"); + // Only the order of additions inside each product differs. The scores are of the order + // of 10; the reference's own two ways of computing differ by about 0.001 here. + assert!(worst < 0.01, "{worst}"); + assert!(worst > 0.0, "bit-identical scores would mean the GPU was not used"); +} + +#[test] +fn the_real_model_matches_the_reference_with_products_on_the_gpu() { + let Ok(dir) = std::env::var("DLUTH_INKLING2_MINI") else { + eprintln!("skip: DLUTH_INKLING2_MINI not set"); + return; + }; + let dir = PathBuf::from(dir); + let golden: serde_json::Value = + serde_json::from_str(include_str!("../../../tests/fixtures/inkling2-mini-greedy.json")).unwrap(); + assert_eq!(golden["reference_dtype"], "float32"); + let noise = golden["reference_self_check"]["top5"].as_f64().unwrap() as f32; + let tol = 4.0 * noise; + assert!(noise > 0.0 && noise < 5e-5, "tolerance {tol} from a self-difference of {noise}"); + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + for case in golden["cases"].as_array().unwrap() { + let products = CudaProducts::new(&dev, &module).unwrap(); + let mut model = + InklingCpu::with_products(load_config(&dir).unwrap(), &weights, 256, Box::new(products)).unwrap(); + let started = std::time::Instant::now(); + let report = common::check_case(&mut |token, pos| model.forward_token(token, pos).unwrap(), case, tol); + eprintln!("golden {}: {report:?} in {:.1} s", case["prompt"], started.elapsed().as_secs_f64()); + assert_eq!(report.tie_at, None, "{}", case["prompt"]); + assert_eq!(report.tokens_checked, 32, "{}", case["prompt"]); + } +} From ac6c920a1580855b697cdd99ada536fdf0f6cb7c Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:37 -0800 Subject: [PATCH 2/8] feat(cuda): timing counters for the GPU products and a generation program that reports where a token's time goes --- crates/dluth-cuda/examples/generate.rs | 79 ++++++++++++++++++++++++++ crates/dluth-cuda/src/inkling.rs | 34 ++++++++++- 2 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 crates/dluth-cuda/examples/generate.rs diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs new file mode 100644 index 0000000..190496d --- /dev/null +++ b/crates/dluth-cuda/examples/generate.rs @@ -0,0 +1,79 @@ +//! Generates text from Inkling 2 Mini with the matrix products on the GPU, and says how +//! fast it went and where the time was spent. +//! +//! cargo run --release -p dluth-cuda --example generate -- "" [max new tokens] +//! +//! Greedy, reasoning effort "none". Speed is counted from the first generated token to the +//! last, so loading the weights and reading the prompt are not in it. + +use dluth_cuda::inkling::CudaProducts; +use dluth_cuda::{CudaDevice, Module}; +use dluth_model::inkling::prompt::{single_turn, Effort}; +use dluth_model::inkling::{load_config, InklingCpu}; +use dluth_model::tokenizer::Tokenizer; +use dluth_model::weights::Weights; +use std::path::PathBuf; +use std::time::Instant; + +fn main() { + let mut args = std::env::args().skip(1); + let dir = PathBuf::from(args.next().expect("a model directory")); + let prompt = args.next().expect("a prompt"); + let max_new: usize = args.next().map_or(128, |n| n.parse().expect("a number of tokens")); + + let weights = Weights::open_dir(&dir).expect("the weights"); + let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).expect("the tokenizer"); + let cfg = load_config(&dir).expect("the configuration"); + let eos = cfg.eos; + let ids = tokenizer.encode(&single_turn(&prompt, Effort::None)).expect("the prompt's tokens"); + + let dev = CudaDevice::open(0).expect("a CUDA device"); + let module = Module::load_embedded(&dev).expect("the embedded kernels"); + let products = CudaProducts::new(&dev, &module).expect("the product kernels"); + let stats = products.stats(); + let mut model = + InklingCpu::with_products(cfg, &weights, ids.len() + max_new, Box::new(products)).expect("the model"); + + let started = Instant::now(); + let mut first = None; + let mut at_first = Default::default(); + let generated = model + .generate_greedy_with(&ids, max_new, eos, |_| { + if first.is_none() { + first = Some(Instant::now()); + at_first = *stats.borrow(); + } + }) + .expect("generation"); + let finished = Instant::now(); + let first = first.unwrap_or(finished); + println!("{}", tokenizer.decode(&generated)); + + let decoded = generated.len().saturating_sub(1); + let seconds = (finished - first).as_secs_f64(); + let total = *stats.borrow(); + println!( + "prompt: {} tokens in {:.1} s (weights are copied to the device as they are first used)", + ids.len(), + (first - started).as_secs_f64() + ); + println!("generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", decoded as f64 / seconds); + if decoded > 0 { + let per = |n: usize| n as f64 / decoded as f64; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0 / decoded as f64; + let bf16 = total.bf16_time - at_first.bf16_time; + let experts = total.expert_time - at_first.expert_time; + println!("per generated token: {:.1} ms in all", seconds * 1000.0 / decoded as f64); + println!( + " BF16 products: {:.0} of them, {:.1} ms", + per(total.bf16_products - at_first.bf16_products), + ms(bf16) + ); + println!( + " expert launches: {:.0} of them, {:.1} ms", + per(total.expert_launches - at_first.expert_launches), + ms(experts) + ); + println!(" everything else, on the CPU: {:.1} ms", seconds * 1000.0 / decoded as f64 - ms(bf16) - ms(experts)); + } +} diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs index df57134..106c6a3 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs @@ -17,7 +17,10 @@ use crate::module::Module; use dluth_core::{Backend, Buffer, CoreError}; use dluth_model::inkling::{ExpertFormat, ExpertMatrices, Products}; use dluth_model::ModelError; +use std::cell::RefCell; use std::collections::HashMap; +use std::rc::Rc; +use std::time::{Duration, Instant}; /// Threads per row for the matrix kernels: the measured best on the real shapes. const SEGS: u32 = 16; @@ -26,6 +29,15 @@ fn failed(e: impl std::fmt::Display) -> ModelError { ModelError::Device(e.to_string()) } +/// How often the products were asked for and how long they took, round trips included. +#[derive(Clone, Copy, Debug, Default)] +pub struct Stats { + pub bf16_products: usize, + pub bf16_time: Duration, + pub expert_launches: usize, + pub expert_time: Duration, +} + /// A device buffer that is replaced by a larger one when more room is needed. struct Growing { buffer: Option, @@ -61,6 +73,7 @@ pub struct CudaProducts<'m> { x: Growing, y: Growing, jobs: Growing, + stats: Rc>, } impl<'m> CudaProducts<'m> { @@ -74,9 +87,16 @@ impl<'m> CudaProducts<'m> { x: Growing { buffer: None }, y: Growing { buffer: None }, jobs: Growing { buffer: None }, + stats: Rc::default(), }) } + /// A handle on the running totals, which stays readable after the products have been + /// handed to a model. + pub fn stats(&self) -> Rc> { + self.stats.clone() + } + /// Bytes of weights copied to the device so far. pub fn weight_bytes(&self) -> usize { self.weight_bytes @@ -133,10 +153,15 @@ impl Products for CudaProducts<'_> { ))); } let weights = self.on_device(w)?; + let started = Instant::now(); let dx = self.send(x)?; let dy = self.y.at_least(self.dev, rows * 4).map_err(failed)?; self.matmat.bf16(Bf16Matrix { buffer: &weights, offset: 0, rows, cols }, &dx, 1, &dy, SEGS).map_err(failed)?; - self.receive(&dy, out) + self.receive(&dy, out)?; + let mut stats = self.stats.borrow_mut(); + stats.bf16_products += 1; + stats.bf16_time += started.elapsed(); + Ok(()) } fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { @@ -150,6 +175,7 @@ impl Products for CudaProducts<'_> { } let (values, scales) = (self.on_device(m.values())?, self.on_device(m.scales())?); let (per_values, per_scales) = m.bytes_per_expert(); + let started = Instant::now(); let inputs: Vec = jobs.iter().flat_map(|(_, x)| x.iter().copied()).collect(); let dx = self.send(&inputs)?; let dy = self.y.at_least(self.dev, out.len() * 4).map_err(failed)?; @@ -170,7 +196,11 @@ impl Products for CudaProducts<'_> { }; let matrices = BlockMatrices { format, values: &values, scales: &scales, rows, cols }; self.blockmat.run(matrices, &list, &dx, &dy, &scratch, SEGS).map_err(failed)?; - self.receive(&dy, out) + self.receive(&dy, out)?; + let mut stats = self.stats.borrow_mut(); + stats.expert_launches += 1; + stats.expert_time += started.elapsed(); + Ok(()) } } From 1bf918968935c426301dab04bb7fe2f786d6f5af Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:08:31 -0800 Subject: [PATCH 3/8] docs: learning note on moving the model to the GPU in steps; three planted bugs for the GPU products --- .../20-the-model-on-the-gpu-in-steps.md | 53 +++++++++++++++++++ .../68-cuda-expert-factor-dropped.patch | 16 ++++++ .../mutants/69-cuda-always-first-expert.patch | 16 ++++++ .../mutants/70-cuda-expert-first-vector.patch | 16 ++++++ 4 files changed, 101 insertions(+) create mode 100644 docs/learning/20-the-model-on-the-gpu-in-steps.md create mode 100644 tools/mutants/68-cuda-expert-factor-dropped.patch create mode 100644 tools/mutants/69-cuda-always-first-expert.patch create mode 100644 tools/mutants/70-cuda-expert-first-vector.patch diff --git a/docs/learning/20-the-model-on-the-gpu-in-steps.md b/docs/learning/20-the-model-on-the-gpu-in-steps.md new file mode 100644 index 0000000..f544775 --- /dev/null +++ b/docs/learning/20-the-model-on-the-gpu-in-steps.md @@ -0,0 +1,53 @@ +# 20. Moving the model to the GPU without writing it twice + +The kernels of notes 18 and 19 multiply matrices at the speed of memory. The model is a great deal more +than its matrix products: blends across depth, normalizations, short convolutions, attention over a +history, the choice of experts. This note is about how the model gets onto the GPU without a second copy of +all that. + +## One forward pass, and a seam in it + +The obvious way to port a model is to write its forward pass again for the device. Then there are two +forward passes, and every rule of the model has to be right twice. Worse, the second one has to be finished +before any of it can be checked. + +Instead the forward pass that was checked against the reference (note 15) got one seam. Wherever it +multiplied a matrix by a vector, it now asks a `Products` object to do it: + +- `bf16(w, rows, cols, x, out)` for the BF16 projections and the output table; +- `experts(matrices, jobs, out)` for a layer's chosen experts, one (expert, vector) job each. + +`CpuProducts` does what the code did before, so the CPU model's results are unchanged to the last digit. +`CudaProducts` does the same products on the GPU. Everything else, for now, still runs on the CPU, and the +same golden checks run with either. A matrix is handed over as the slice of the weight file it lives in; +the GPU side recognises it by where the slice starts and copies it to the device the first time it is used. + +## What the first step costs and buys + +Each product on the GPU is a round trip: copy the input vector to the device, launch, wait, copy the result +back. On a GB10, generating 90 tokens: + +| Per generated token | Count | Time | +|---|---|---| +| BF16 products | 689 | 26.8 ms | +| Expert launches | 96 | 13.0 ms | +| Everything else, on the CPU | | 20.6 ms | +| Total | | 60.4 ms: 16.6 tokens per second | + +The CPU model manages 2.6 tokens per second on a fast laptop. The products alone, at the rate the kernels +read weights, would take about 22 ms; the rest of their 40 ms is the round trips, about 18 microseconds +each. So the table is also the to-do list: keep vectors on the device between products, and move the +largest pieces of "everything else" there one at a time. After each move the model still runs and is still +checked. + +## How we know it is right + +With products on the GPU the tiny model matches the reference at all 72 recorded tokens, and the real +Inkling 2 Mini matches its 32-bit reference recording at all 96, to 0.00006 in log-probability against a +bar of 0.00015. A test in the model crate counts that every product of a token goes through the seam. Three +planted bugs in the GPU side each fail the tiny model's check: an expert's factor left out, the first +expert read whichever was chosen, and every job multiplying the first vector. + +The tiny model passes more narrowly than the real one (0.0042 against 0.0044). Its random weights amplify +the rounding differences between two orders of addition, which is why its bar is derived from how much the +reference differs from itself (note 14). diff --git a/tools/mutants/68-cuda-expert-factor-dropped.patch b/tools/mutants/68-cuda-expert-factor-dropped.patch new file mode 100644 index 0000000..b912ca9 --- /dev/null +++ b/tools/mutants/68-cuda-expert-factor-dropped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda the_tiny_model_matches +# needs: gpu +# Bug: the GPU products leave out each expert's factor. +diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs +index 106c6a3..822d19d 100644 +--- a/crates/dluth-cuda/src/inkling.rs ++++ b/crates/dluth-cuda/src/inkling.rs +@@ -186,7 +186,7 @@ impl Products for CudaProducts<'_> { + .map(|(j, &(expert, _))| Job { + values: expert * per_values, + scales: expert * per_scales, +- factor: m.factor(expert), ++ factor: 1.0, + vectors: vec![(j * cols, j)], + }) + .collect(); diff --git a/tools/mutants/69-cuda-always-first-expert.patch b/tools/mutants/69-cuda-always-first-expert.patch new file mode 100644 index 0000000..b40aca8 --- /dev/null +++ b/tools/mutants/69-cuda-always-first-expert.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda the_tiny_model_matches +# needs: gpu +# Bug: the GPU products read the first expert of the layer whichever was chosen. +diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs +index 106c6a3..4ad66d2 100644 +--- a/crates/dluth-cuda/src/inkling.rs ++++ b/crates/dluth-cuda/src/inkling.rs +@@ -184,7 +184,7 @@ impl Products for CudaProducts<'_> { + .iter() + .enumerate() + .map(|(j, &(expert, _))| Job { +- values: expert * per_values, ++ values: 0, + scales: expert * per_scales, + factor: m.factor(expert), + vectors: vec![(j * cols, j)], diff --git a/tools/mutants/70-cuda-expert-first-vector.patch b/tools/mutants/70-cuda-expert-first-vector.patch new file mode 100644 index 0000000..230be70 --- /dev/null +++ b/tools/mutants/70-cuda-expert-first-vector.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda the_tiny_model_matches +# needs: gpu +# Bug: every expert job on the GPU multiplies the first input vector. +diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs +index 106c6a3..d50b3c3 100644 +--- a/crates/dluth-cuda/src/inkling.rs ++++ b/crates/dluth-cuda/src/inkling.rs +@@ -187,7 +187,7 @@ impl Products for CudaProducts<'_> { + values: expert * per_values, + scales: expert * per_scales, + factor: m.factor(expert), +- vectors: vec![(j * cols, j)], ++ vectors: vec![(0, j)], + }) + .collect(); + let format = match m.format() { From 0b10d02737599d97f20255a2a5c8e67819e351f2 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:51:22 -0800 Subject: [PATCH 4/8] feat(cuda): the expert activation and the weighted sum of experts on the device --- crates/dluth-cuda/kernels/expert_ops.cu | 32 +++++++ crates/dluth-cuda/src/expert_ops.rs | 102 +++++++++++++++++++++ crates/dluth-cuda/src/lib.rs | 1 + crates/dluth-cuda/tests/expert_ops.rs | 113 ++++++++++++++++++++++++ 4 files changed, 248 insertions(+) create mode 100644 crates/dluth-cuda/kernels/expert_ops.cu create mode 100644 crates/dluth-cuda/src/expert_ops.rs create mode 100644 crates/dluth-cuda/tests/expert_ops.rs diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu new file mode 100644 index 0000000..c23c4c7 --- /dev/null +++ b/crates/dluth-cuda/kernels/expert_ops.cu @@ -0,0 +1,32 @@ +// The two small steps of an expert layer that sit between and after its matrix products. +// They are cheap arithmetic, but on the CPU they cost a round trip to the device and well +// over a million tanh and exp calls per token; here they keep the whole expert stage on +// the device. + +// The activation inside an expert, for a run of (gate, up) pairs: +// act[i] = softcap(gate, gate_cap) * sigmoid(gate) * softcap(up, up_cap) +// where gate = both[2i], up = both[2i + 1] and softcap(x, c) = c * tanh(x / c). +// The sigmoid sees the raw gate, not the limited one. +// CPU reference: dluth_kernels::cpu::capped_gate_mul. +extern "C" __global__ void capped_gate_pairs(const float* both, float* act, unsigned int pairs, + float gate_cap, float up_cap) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= pairs) return; + float2 gu = reinterpret_cast(both)[i]; + float gate = gate_cap * tanhf(gu.x / gate_cap); + float up = up_cap * tanhf(gu.y / up_cap); + act[i] = gate * (1.0f / (1.0f + expf(-gu.x))) * up; +} + +// The weighted sum of the chosen experts' outputs: +// y[r] = sum over j of weights[j] * outs[j][r] +// `outs` is count vectors of width floats, one after another. The sum runs in the order of +// j, like the CPU reference (the loop in the model's expert step). +extern "C" __global__ void weighted_sum(const float* outs, const float* weights, float* y, + unsigned int count, unsigned int width) { + unsigned int r = blockIdx.x * blockDim.x + threadIdx.x; + if (r >= width) return; + float total = 0.0f; + for (unsigned int j = 0; j < count; ++j) total += weights[j] * outs[(size_t)j * width + r]; + y[r] = total; +} diff --git a/crates/dluth-cuda/src/expert_ops.rs b/crates/dluth-cuda/src/expert_ops.rs new file mode 100644 index 0000000..e7d229f --- /dev/null +++ b/crates/dluth-cuda/src/expert_ops.rs @@ -0,0 +1,102 @@ +//! The small steps of an expert layer: the activation between its two matrix products and +//! the weighted sum after them. + +use crate::device::CudaDevice; +use crate::error::CudaError; +use crate::module::{Kernel, Module}; +use dluth_core::{Buffer, CoreError}; +use std::ffi::c_void; + +fn unknown(e: CoreError) -> CudaError { + CudaError::Refused(e.to_string()) +} + +/// The expert-step kernels of a loaded module. +pub struct ExpertOps<'m> { + dev: &'m CudaDevice, + gate: Kernel<'m>, + sum: Kernel<'m>, +} + +impl<'m> ExpertOps<'m> { + pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { + Ok(ExpertOps { dev, gate: module.kernel("capped_gate_pairs")?, sum: module.kernel("weighted_sum")? }) + } + + /// Starts `act[i] = softcap(gate_i, gate_cap) * sigmoid(gate_i) * softcap(up_i, up_cap)` + /// for `pairs` pairs and returns without waiting. `both` holds the pairs as + /// gate, up, gate, up, ...; `act` receives one float per pair. + pub fn capped_gate_pairs( + &self, + both: &Buffer, + act: &Buffer, + pairs: usize, + gate_cap: f32, + up_cap: f32, + ) -> Result<(), CudaError> { + let refuse = |why: String| Err(CudaError::Refused(format!("capped_gate_pairs: {why}"))); + let (both_have, act_have) = (self.dev.size_of(both).map_err(unknown)?, self.dev.size_of(act).map_err(unknown)?); + if pairs == 0 || pairs > u32::MAX as usize / 2 || pairs * 8 > both_have || pairs * 4 > act_have { + return refuse(format!("{pairs} pairs with buffers of {both_have} and {act_have} bytes")); + } + // Written as "not greater than zero" so that a cap that is not a number is refused too. + if !(gate_cap > 0.0 && up_cap > 0.0) || !gate_cap.is_finite() || !up_cap.is_finite() { + return refuse(format!("caps of {gate_cap} and {up_cap}; both must be positive")); + } + if both.handle == act.handle { + return refuse("the same buffer for input and output".into()); + } + let (mut pb, mut pa, mut n, mut gc, mut uc) = (both.handle, act.handle, pairs as u32, gate_cap, up_cap); + let mut args = [ + &mut pb as *mut u64 as *mut c_void, + &mut pa as *mut u64 as *mut c_void, + &mut n as *mut u32 as *mut c_void, + &mut gc as *mut f32 as *mut c_void, + &mut uc as *mut f32 as *mut c_void, + ]; + // SAFETY: the arguments match capped_gate_pairs(const float*, float*, unsigned, + // float, float). The kernel reads 2 * pairs floats from `both` (as 8-byte pairs; + // device buffers are aligned far beyond that) and writes pairs floats to `act`; + // both extents were checked against the real buffer sizes. + unsafe { self.gate.launch(((pairs as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) } + } + + /// Starts `y[r] = sum_j weights[j] * outs[j][r]` over `count` vectors of `width` floats + /// and returns without waiting. + pub fn weighted_sum( + &self, + outs: &Buffer, + weights: &Buffer, + y: &Buffer, + count: usize, + width: usize, + ) -> Result<(), CudaError> { + let refuse = |why: String| Err(CudaError::Refused(format!("weighted_sum: {why}"))); + let have = |b: &Buffer| self.dev.size_of(b).map_err(unknown); + let (outs_have, weights_have, y_have) = (have(outs)?, have(weights)?, have(y)?); + if count == 0 || width == 0 || count > 1 << 16 || width > 1 << 24 { + return refuse(format!("{count} vectors of {width}")); + } + if count * width * 4 > outs_have || count * 4 > weights_have || width * 4 > y_have { + return refuse(format!( + "{count} vectors of {width} with buffers of {outs_have}, {weights_have} and {y_have} bytes" + )); + } + if y.handle == outs.handle || y.handle == weights.handle { + return refuse("the output buffer is also an input".into()); + } + let (mut po, mut pw, mut py, mut c, mut w) = + (outs.handle, weights.handle, y.handle, count as u32, width as u32); + let mut args = [ + &mut po as *mut u64 as *mut c_void, + &mut pw as *mut u64 as *mut c_void, + &mut py as *mut u64 as *mut c_void, + &mut c as *mut u32 as *mut c_void, + &mut w as *mut u32 as *mut c_void, + ]; + // SAFETY: the arguments match weighted_sum(const float*, const float*, float*, + // unsigned, unsigned). The kernel reads count * width floats from `outs` and count + // from `weights`, and writes width floats to `y`; all checked above. + unsafe { self.sum.launch(((width as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) } + } +} diff --git a/crates/dluth-cuda/src/lib.rs b/crates/dluth-cuda/src/lib.rs index 70b4104..efb6054 100644 --- a/crates/dluth-cuda/src/lib.rs +++ b/crates/dluth-cuda/src/lib.rs @@ -10,6 +10,7 @@ pub mod blockmat; mod device; mod error; +pub mod expert_ops; mod image; pub mod inkling; pub mod matmat; diff --git a/crates/dluth-cuda/tests/expert_ops.rs b/crates/dluth-cuda/tests/expert_ops.rs new file mode 100644 index 0000000..8a1f492 --- /dev/null +++ b/crates/dluth-cuda/tests/expert_ops.rs @@ -0,0 +1,113 @@ +//! The expert layer's small steps on the GPU against the CPU reference. +//! GPU tests; they need an NVIDIA GPU of the architecture the kernels were built for. + +use dluth_core::{Backend, Buffer}; +use dluth_cuda::expert_ops::ExpertOps; +use dluth_cuda::{CudaDevice, CudaError, Module}; + +fn upload(dev: &CudaDevice, values: &[f32]) -> Buffer { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + let buf = dev.alloc(bytes.len()).unwrap(); + dev.upload(&buf, &bytes).unwrap(); + buf +} + +fn download(dev: &CudaDevice, buf: &Buffer, n: usize) -> Vec { + dev.synchronize().unwrap(); + let mut bytes = vec![0u8; n * 4]; + dev.download(buf, &mut bytes).unwrap(); + bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect() +} + +#[test] +fn the_activation_matches_the_cpu_reference() { + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let ops = ExpertOps::new(&dev, &module).unwrap(); + // Small, ordinary and far beyond the caps, both signs, and exact zeros; a count that is + // not a multiple of the block size. + let pairs = 3001; + let (gate_cap, up_cap) = (4.0f32, 25.0f32); + let (mut gate, mut up) = (Vec::new(), Vec::new()); + for i in 0..pairs { + let t = i as f32 / pairs as f32; + gate.push(match i % 5 { + 0 => 0.0, + 1 => (t - 0.5) * 0.02, + 2 => (t - 0.5) * 12.0, + 3 => 300.0 * (t - 0.5), + _ => -1000.0 * t, + }); + up.push(((i * 7919) % 2000) as f32 * 0.05 - 50.0); + } + let both: Vec = gate.iter().zip(&up).flat_map(|(g, u)| [*g, *u]).collect(); + let (d_both, d_act) = (upload(&dev, &both), dev.alloc(pairs * 4).unwrap()); + ops.capped_gate_pairs(&d_both, &d_act, pairs, gate_cap, up_cap).unwrap(); + let got = download(&dev, &d_act, pairs); + let mut want = vec![0.0f32; pairs]; + dluth_kernels::cpu::capped_gate_mul(&gate, &up, gate_cap, up_cap, &mut want); + // Three factors, each from a library function (tanh, exp) that two implementations may + // round differently in the last bit or two: a few parts in ten million of the result. + // Results stay below gate_cap * up_cap = 100. + for i in 0..pairs { + let bound = 8.0 * f32::EPSILON * want[i].abs().max(f32::MIN_POSITIVE); + assert!((got[i] - want[i]).abs() <= bound, "pair {i} ({}, {}): {} vs {}", gate[i], up[i], got[i], want[i]); + } + // The cases the formula exists for: a huge gate is capped, a hugely negative one is shut. + assert!(want.iter().any(|w| w.abs() > 90.0) && want.contains(&0.0)); +} + +#[test] +fn the_weighted_sum_matches_the_cpu_loop() { + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let ops = ExpertOps::new(&dev, &module).unwrap(); + let (count, width) = (8, 2305); + let outs: Vec = (0..count * width).map(|i| ((i * 2654435761usize) % 2001) as f32 * 0.001 - 1.0).collect(); + let weights: Vec = (0..count).map(|j| 0.25 + j as f32 * 0.37).collect(); + let (d_outs, d_weights, d_y) = (upload(&dev, &outs), upload(&dev, &weights), dev.alloc(width * 4).unwrap()); + ops.weighted_sum(&d_outs, &d_weights, &d_y, count, width).unwrap(); + let got = download(&dev, &d_y, width); + for r in 0..width { + let mut want = 0.0f32; + let mut size = 0.0f32; + for j in 0..count { + want += weights[j] * outs[j * width + r]; + size += (weights[j] * outs[j * width + r]).abs(); + } + // The same order of additions. The device may fuse a multiply and an add into one + // rounding where the CPU rounds twice: at most one rounding of difference per term. + let bound = count as f32 * (f32::EPSILON / 2.0) * size; + assert!((got[r] - want).abs() <= bound, "row {r}: {} vs {want}", got[r]); + } +} + +#[test] +fn requests_that_would_leave_the_buffers_are_refused() { + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let ops = ExpertOps::new(&dev, &module).unwrap(); + let (both, act) = (dev.alloc(10 * 8).unwrap(), dev.alloc(10 * 4).unwrap()); + for (what, result) in [ + ("more pairs than the input holds", ops.capped_gate_pairs(&both, &act, 11, 4.0, 25.0)), + ("no pairs", ops.capped_gate_pairs(&both, &act, 0, 4.0, 25.0)), + ("a cap of zero", ops.capped_gate_pairs(&both, &act, 10, 0.0, 25.0)), + ("a cap that is not a number", ops.capped_gate_pairs(&both, &act, 10, 4.0, f32::NAN)), + ("output over the input", ops.capped_gate_pairs(&both, &both, 10, 4.0, 25.0)), + ] { + assert!(matches!(result, Err(CudaError::Refused(_))), "{what} was not refused"); + } + let small = dev.alloc(5 * 4).unwrap(); + assert!(matches!(ops.capped_gate_pairs(&both, &small, 10, 4.0, 25.0), Err(CudaError::Refused(_)))); + + let (outs, weights, y) = (dev.alloc(3 * 6 * 4).unwrap(), dev.alloc(3 * 4).unwrap(), dev.alloc(6 * 4).unwrap()); + for (what, result) in [ + ("more vectors than the input holds", ops.weighted_sum(&outs, &weights, &y, 4, 6)), + ("wider vectors than the output holds", ops.weighted_sum(&outs, &weights, &y, 2, 7)), + ("no vectors", ops.weighted_sum(&outs, &weights, &y, 0, 6)), + ("no width", ops.weighted_sum(&outs, &weights, &y, 3, 0)), + ("output over the input", ops.weighted_sum(&outs, &weights, &outs, 3, 6)), + ] { + assert!(matches!(result, Err(CudaError::Refused(_))), "{what} was not refused"); + } +} From 1a04fe98533c87518351a220db19294088840907 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:06:52 -0800 Subject: [PATCH 5/8] feat: a layer's experts are one request to the products and stay on the device from input to weighted sum; the GPU-against-CPU check uses the measured bar --- Cargo.lock | 2 + crates/dluth-cuda/src/inkling.rs | 120 +++++++++++++----- .../dluth-cuda/tests/inkling_golden_cuda.rs | 34 +++-- crates/dluth-model/src/inkling/mod.rs | 2 +- crates/dluth-model/src/inkling/model.rs | 92 ++++++++------ .../dluth-model/tests/tiny_inkling_golden.rs | 12 +- 6 files changed, 178 insertions(+), 84 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ff683a7..eb27323 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,6 +121,8 @@ dependencies = [ "bindgen", "dluth-core", "dluth-kernels", + "dluth-model", + "serde_json", ] [[package]] diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs index 106c6a3..14f7f8f 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs @@ -2,9 +2,11 @@ //! //! `CudaProducts` implements the model crate's `Products` trait: the forward pass stays the //! one written and checked on the CPU, and only its matrix products, which are almost all -//! the bytes a token reads, run on the device. Each product copies its input vector to the -//! device, launches a kernel, waits, and copies the result back. That round trip is the -//! price of this first step; later steps keep more of a token on the device. +//! the bytes a token reads, run on the device. A BF16 product copies its input vector to +//! the device, launches a kernel, waits, and copies the result back. That round trip is the +//! price of doing this in steps; each step keeps more of a token on the device. A layer's +//! experts already stay there from their input to their weighted sum: two matrix products, +//! the activation between them and the sum, with one copy in and one copy out. //! //! Weights are copied to the device the first time a matrix is used, in the form the file //! stores them, and stay there. @@ -12,10 +14,11 @@ use crate::blockmat::{BlockFormat, BlockMat, BlockMatrices, Job, JOB_BYTES}; use crate::device::CudaDevice; use crate::error::CudaError; +use crate::expert_ops::ExpertOps; use crate::matmat::{Bf16Matrix, Matmat}; use crate::module::Module; use dluth_core::{Backend, Buffer, CoreError}; -use dluth_model::inkling::{ExpertFormat, ExpertMatrices, Products}; +use dluth_model::inkling::{ExpertFormat, ExpertLayer, ExpertMatrices, Products}; use dluth_model::ModelError; use std::cell::RefCell; use std::collections::HashMap; @@ -65,6 +68,7 @@ pub struct CudaProducts<'m> { dev: &'m CudaDevice, matmat: Matmat<'m>, blockmat: BlockMat<'m>, + ops: ExpertOps<'m>, /// Weights already on the device, by where their bytes start in the weight file's /// mapping: the device copy and how many bytes it holds. uploaded: HashMap, @@ -72,7 +76,13 @@ pub struct CudaProducts<'m> { weight_bytes: usize, x: Growing, y: Growing, + /// The expert stage's intermediate results and its two job lists. + both: Growing, + act: Growing, + outs: Growing, + route: Growing, jobs: Growing, + jobs_second: Growing, stats: Rc>, } @@ -82,11 +92,17 @@ impl<'m> CudaProducts<'m> { dev, matmat: Matmat::new(dev, module)?, blockmat: BlockMat::new(dev, module)?, + ops: ExpertOps::new(dev, module)?, uploaded: HashMap::new(), weight_bytes: 0, x: Growing { buffer: None }, y: Growing { buffer: None }, + both: Growing { buffer: None }, + act: Growing { buffer: None }, + outs: Growing { buffer: None }, + route: Growing { buffer: None }, jobs: Growing { buffer: None }, + jobs_second: Growing { buffer: None }, stats: Rc::default(), }) } @@ -123,6 +139,16 @@ impl<'m> CudaProducts<'m> { Ok(buffer) } + /// The device copies of a layer's expert values and scales, made on first use, and + /// the format they are in. + fn stored(&mut self, m: &ExpertMatrices) -> Result<(Buffer, Buffer, BlockFormat), ModelError> { + let format = match m.format() { + ExpertFormat::Nvfp4 => BlockFormat::Nvfp4, + ExpertFormat::Mxfp8 => BlockFormat::Mxfp8, + }; + Ok((self.on_device(m.values())?, self.on_device(m.scales())?, format)) + } + fn send(&mut self, values: &[f32]) -> Result { let buffer = self.x.at_least(self.dev, values.len() * 4).map_err(failed)?; let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); @@ -164,38 +190,61 @@ impl Products for CudaProducts<'_> { Ok(()) } - fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { - let (rows, cols) = m.shape(); - if jobs.is_empty() || out.len() != jobs.len() * rows || jobs.iter().any(|(_, x)| x.len() != cols) { + fn expert_layer( + &mut self, + layer: &ExpertLayer, + chosen: &[(usize, f32)], + input: &[f32], + out: &mut [f32], + ) -> Result<(), ModelError> { + let ((pairs2, h), (h_out, inner)) = (layer.first.shape(), layer.second.shape()); + let n = chosen.len(); + if n == 0 || input.len() != h || out.len() != h_out || h != h_out || pairs2 != 2 * inner { return Err(ModelError::Device(format!( - "{} expert products of {rows} by {cols} with {} outputs", - jobs.len(), + "{n} experts of {pairs2} by {h} then {h_out} by {inner}, with {} inputs and {} outputs", + input.len(), out.len() ))); } - let (values, scales) = (self.on_device(m.values())?, self.on_device(m.scales())?); - let (per_values, per_scales) = m.bytes_per_expert(); + let (values1, scales1, format1) = self.stored(layer.first)?; + let (values2, scales2, format2) = self.stored(layer.second)?; + let first = BlockMatrices { format: format1, values: &values1, scales: &scales1, rows: pairs2, cols: h }; + let second = BlockMatrices { format: format2, values: &values2, scales: &scales2, rows: h, cols: inner }; let started = Instant::now(); - let inputs: Vec = jobs.iter().flat_map(|(_, x)| x.iter().copied()).collect(); - let dx = self.send(&inputs)?; - let dy = self.y.at_least(self.dev, out.len() * 4).map_err(failed)?; - let scratch = self.jobs.at_least(self.dev, jobs.len() * JOB_BYTES).map_err(failed)?; - let list: Vec = jobs - .iter() - .enumerate() - .map(|(j, &(expert, _))| Job { - values: expert * per_values, - scales: expert * per_scales, - factor: m.factor(expert), - vectors: vec![(j * cols, j)], - }) - .collect(); - let format = match m.format() { - ExpertFormat::Nvfp4 => BlockFormat::Nvfp4, - ExpertFormat::Mxfp8 => BlockFormat::Mxfp8, + let dev = self.dev; + // Everything the kernels read is copied before the first launch, so no buffer is + // written while a kernel may still be reading it. + let dx = self.send(input)?; + let weights: Vec = chosen.iter().flat_map(|&(_, w)| w.to_le_bytes()).collect(); + let d_route = self.route.at_least(dev, weights.len()).map_err(failed)?; + dev.upload(&d_route, &weights).map_err(failed)?; + let d_both = self.both.at_least(dev, n * pairs2 * 4).map_err(failed)?; + let d_act = self.act.at_least(dev, n * inner * 4).map_err(failed)?; + let d_outs = self.outs.at_least(dev, n * h * 4).map_err(failed)?; + let dy = self.y.at_least(dev, h * 4).map_err(failed)?; + let jobs_first = self.jobs.at_least(dev, n * JOB_BYTES).map_err(failed)?; + let jobs_second = self.jobs_second.at_least(dev, n * JOB_BYTES).map_err(failed)?; + + // Each expert's first matrix reads the same input; its second reads its own activation. + let jobs = |m: &ExpertMatrices, vector: &dyn Fn(usize) -> usize| -> Vec { + let (per_values, per_scales) = m.bytes_per_expert(); + chosen + .iter() + .enumerate() + .map(|(j, &(expert, _))| Job { + values: expert * per_values, + scales: expert * per_scales, + factor: m.factor(expert), + vectors: vec![(vector(j), j)], + }) + .collect() }; - let matrices = BlockMatrices { format, values: &values, scales: &scales, rows, cols }; - self.blockmat.run(matrices, &list, &dx, &dy, &scratch, SEGS).map_err(failed)?; + self.blockmat.run(first, &jobs(layer.first, &|_| 0), &dx, &d_both, &jobs_first, SEGS).map_err(failed)?; + self.ops.capped_gate_pairs(&d_both, &d_act, n * inner, layer.gate_cap, layer.up_cap).map_err(failed)?; + self.blockmat + .run(second, &jobs(layer.second, &|j| j * inner), &d_act, &d_outs, &jobs_second, SEGS) + .map_err(failed)?; + self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h).map_err(failed)?; self.receive(&dy, out)?; let mut stats = self.stats.borrow_mut(); stats.expert_launches += 1; @@ -207,7 +256,16 @@ impl Products for CudaProducts<'_> { impl Drop for CudaProducts<'_> { fn drop(&mut self) { // Everything goes back to the device; a failure leaves it to the context's end. - let scratch = [self.x.buffer, self.y.buffer, self.jobs.buffer]; + let scratch = [ + self.x.buffer, + self.y.buffer, + self.both.buffer, + self.act.buffer, + self.outs.buffer, + self.route.buffer, + self.jobs.buffer, + self.jobs_second.buffer, + ]; for buffer in self.uploaded.values().copied().chain(scratch.into_iter().flatten()) { let _ = self.dev.free(buffer); } diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index d65d160..8d477cf 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -32,29 +32,45 @@ fn the_tiny_model_matches_the_reference_with_products_on_the_gpu() { } } +fn log_softmax(x: &[f32]) -> Vec { + let max = x.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let log_sum = x.iter().map(|v| (v - max).exp()).sum::().ln(); + x.iter().map(|v| v - max - log_sum).collect() +} + +/// Text the recordings do not cover: 40 tokens of a fixed pattern, past the window, the +/// reach and the position where queries start to be scaled. The CPU model, which is checked +/// against the reference, stands in for the reference here, with the same bar: the five most +/// likely tokens' log-probabilities within four times the reference's own difference from +/// itself, and the same most likely token except at a near-tie. #[test] fn the_tiny_model_on_the_gpu_stays_close_to_the_cpu_model() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let golden: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("golden.json")).unwrap()).unwrap(); + let tol = 4.0 * golden["reference_self_difference"].as_f64().unwrap() as f32; let weights = Weights::open_dir(&dir).unwrap(); let dev = CudaDevice::open(0).expect("GPU"); let module = Module::load_embedded(&dev).unwrap(); let products = CudaProducts::new(&dev, &module).unwrap(); let mut gpu = InklingCpu::with_products(load_config(&dir).unwrap(), &weights, 64, Box::new(products)).unwrap(); let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); - let mut worst = 0.0f32; - // Past the window, the reach and the position where queries start to be scaled. + let (mut worst, mut identical) = (0.0f32, true); for pos in 0..40 { let token = ((pos * 37 + 11) % 256) as u32; let (a, b) = (gpu.forward_token(token, pos).unwrap(), cpu.forward_token(token, pos).unwrap()); - for (x, y) in a.iter().zip(&b) { - worst = worst.max((x - y).abs()); + identical &= a == b; + let (a, b) = (log_softmax(&a), log_softmax(&b)); + let mut order: Vec = (0..b.len()).collect(); + order.sort_by(|&i, &j| b[j].total_cmp(&b[i])); + for &i in &order[..5] { + worst = worst.max((a[i] - b[i]).abs()); + assert!((a[i] - b[i]).abs() < tol, "position {pos} token {i}: {} vs {}", a[i], b[i]); } + let top = (0..a.len()).max_by(|&i, &j| a[i].total_cmp(&a[j])).unwrap(); + assert!(top == order[0] || b[order[0]] - b[order[1]] < tol, "position {pos}: {top} vs {}", order[0]); } - eprintln!("largest difference between the scores of the two: {worst}"); - // Only the order of additions inside each product differs. The scores are of the order - // of 10; the reference's own two ways of computing differ by about 0.001 here. - assert!(worst < 0.01, "{worst}"); - assert!(worst > 0.0, "bit-identical scores would mean the GPU was not used"); + eprintln!("largest log-probability difference between the two: {worst} (bar {tol})"); + assert!(!identical, "bit-identical scores would mean the GPU was not used"); } #[test] diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 1757423..7ef4657 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -5,4 +5,4 @@ pub mod model; pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; -pub use model::{CpuProducts, ExpertMatrices, InklingCpu, Products}; +pub use model::{CpuProducts, ExpertLayer, ExpertMatrices, InklingCpu, Products}; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 8693fee..4fbbac5 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -146,10 +146,29 @@ pub trait Products { /// `out[r] = sum_c w[r][c] * x[c]` for a BF16 matrix of `rows` by `cols`. fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &[f32], out: &mut [f32]) -> Result<(), ModelError>; - /// One product per job: job `j` is (which expert, its input vector), and its result, - /// the expert's matrix times the vector times the expert's factor, goes to the `rows` - /// floats of `out` starting at `j * rows`. - fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError>; + /// The chosen experts of one layer for one input. Each entry of `chosen` is (which + /// expert, its weight). An expert's first matrix turns `input` into alternating gate + /// and up values; the capped activation combines each pair; its second matrix maps the + /// result back. `out` receives the sum of the experts' results, each times its weight, + /// added in the order of `chosen`. + fn expert_layer( + &mut self, + layer: &ExpertLayer, + chosen: &[(usize, f32)], + input: &[f32], + out: &mut [f32], + ) -> Result<(), ModelError>; +} + +/// What `Products::expert_layer` needs to know about a layer's experts. +pub struct ExpertLayer<'a, 'w> { + /// Hidden state to alternating gate and up rows. + pub first: &'a ExpertMatrices<'w>, + /// Inner width back to the hidden state. + pub second: &'a ExpertMatrices<'w>, + /// The limits of the activation's gate and up factors. + pub gate_cap: f32, + pub up_cap: f32, } /// The products on the CPU: the reference every other implementation is compared with. @@ -161,16 +180,36 @@ impl Products for CpuProducts { Ok(()) } - fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { - let rows = m.shape().0; + fn expert_layer( + &mut self, + layer: &ExpertLayer, + chosen: &[(usize, f32)], + input: &[f32], + out: &mut [f32], + ) -> Result<(), ModelError> { + let (h, inner) = (layer.second.shape().0, layer.second.shape().1); assert!( - out.len() == jobs.len() * rows, - "experts: {} outputs for {} jobs of {rows} rows", - out.len(), - jobs.len() + out.len() == h && input.len() == layer.first.shape().1, + "expert_layer: {} inputs, {} outputs", + input.len(), + out.len() ); - for (&(expert, x), out) in jobs.iter().zip(out.chunks_exact_mut(rows)) { - m.apply(expert, x, out); + let mut both = vec![0.0f32; 2 * inner]; + let (mut gate, mut up, mut act) = (vec![0.0f32; inner], vec![0.0f32; inner], vec![0.0f32; inner]); + let mut one = vec![0.0f32; h]; + out.fill(0.0); + for &(expert, weight) in chosen { + layer.first.apply(expert, input, &mut both); + // Gate and up values alternate. + for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { + gate[i] = pair[0]; + up[i] = pair[1]; + } + cpu::capped_gate_mul(&gate, &up, layer.gate_cap, layer.up_cap, &mut act); + layer.second.apply(expert, &act, &mut one); + for (t, o) in out.iter_mut().zip(&one) { + *t += weight * o; + } } Ok(()) } @@ -794,37 +833,14 @@ fn attention( /// The experts for one token: choose a few, run each, add up their weighted outputs. fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f32]) -> Result, ModelError> { - let (h, inner) = (cfg.hidden, cfg.expert_width); + let h = cfg.hidden; let mut scores = vec![0.0f32; cfg.experts]; p.bf16(layer.router, cfg.experts, h, input, &mut scores)?; let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); - // Every chosen expert's first matrix reads the same input. - let jobs: Vec<(usize, &[f32])> = chosen.iter().map(|&(expert, _)| (expert, input)).collect(); - let mut both = vec![0.0f32; chosen.len() * 2 * inner]; - p.experts(&layer.first, &jobs, &mut both)?; - - // Gate and up values alternate. Each expert's second matrix reads its own result. - let mut acts = vec![0.0f32; chosen.len() * inner]; - let (mut gate, mut up) = (vec![0.0f32; inner], vec![0.0f32; inner]); - for (both, act) in both.chunks_exact(2 * inner).zip(acts.chunks_exact_mut(inner)) { - for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { - gate[i] = pair[0]; - up[i] = pair[1]; - } - cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, act); - } - let jobs: Vec<(usize, &[f32])> = - chosen.iter().zip(acts.chunks_exact(inner)).map(|(&(e, _), act)| (e, act)).collect(); - let mut outs = vec![0.0f32; chosen.len() * h]; - p.experts(&layer.second, &jobs, &mut outs)?; - let mut total = vec![0.0f32; h]; - for (&(_, weight), out) in chosen.iter().zip(outs.chunks_exact(h)) { - for (t, o) in total.iter_mut().zip(out) { - *t += weight * o; - } - } + let layer = ExpertLayer { first: &layer.first, second: &layer.second, gate_cap: cfg.gate_cap, up_cap: cfg.up_cap }; + p.expert_layer(&layer, &chosen, input, &mut total)?; Ok(total) } diff --git a/crates/dluth-model/tests/tiny_inkling_golden.rs b/crates/dluth-model/tests/tiny_inkling_golden.rs index 004b3f6..38f0a4b 100644 --- a/crates/dluth-model/tests/tiny_inkling_golden.rs +++ b/crates/dluth-model/tests/tiny_inkling_golden.rs @@ -54,14 +54,16 @@ impl dluth_model::inkling::Products for Counting { self.inner.bf16(w, rows, cols, x, out) } - fn experts( + fn expert_layer( &mut self, - m: &dluth_model::inkling::ExpertMatrices, - jobs: &[(usize, &[f32])], + layer: &dluth_model::inkling::ExpertLayer, + chosen: &[(usize, f32)], + input: &[f32], out: &mut [f32], ) -> Result<(), dluth_model::error::ModelError> { - self.expert_jobs.set(self.expert_jobs.get() + jobs.len()); - self.inner.experts(m, jobs, out) + // Two matrices per chosen expert. + self.expert_jobs.set(self.expert_jobs.get() + 2 * chosen.len()); + self.inner.expert_layer(layer, chosen, input, out) } } From 109aa688a1ecfe4fb7aaffeb02b3c231d73ea010 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:24:05 -0800 Subject: [PATCH 6/8] docs: note 20 covers the expert layer on the device; planted bugs for the GPU products and the expert-step kernels --- .../20-the-model-on-the-gpu-in-steps.md | 41 +++++++++++-------- .../68-cuda-expert-factor-dropped.patch | 20 ++++----- .../mutants/69-cuda-always-first-expert.patch | 20 ++++----- .../mutants/70-cuda-expert-first-vector.patch | 22 +++++----- tools/mutants/72-gate-sigmoid-of-capped.patch | 16 ++++++++ .../mutants/73-weighted-sum-unweighted.patch | 15 +++++++ .../74-cuda-route-weights-dropped.patch | 16 ++++++++ 7 files changed, 102 insertions(+), 48 deletions(-) create mode 100644 tools/mutants/72-gate-sigmoid-of-capped.patch create mode 100644 tools/mutants/73-weighted-sum-unweighted.patch create mode 100644 tools/mutants/74-cuda-route-weights-dropped.patch diff --git a/docs/learning/20-the-model-on-the-gpu-in-steps.md b/docs/learning/20-the-model-on-the-gpu-in-steps.md index f544775..082c482 100644 --- a/docs/learning/20-the-model-on-the-gpu-in-steps.md +++ b/docs/learning/20-the-model-on-the-gpu-in-steps.md @@ -15,39 +15,46 @@ Instead the forward pass that was checked against the reference (note 15) got on multiplied a matrix by a vector, it now asks a `Products` object to do it: - `bf16(w, rows, cols, x, out)` for the BF16 projections and the output table; -- `experts(matrices, jobs, out)` for a layer's chosen experts, one (expert, vector) job each. +- `expert_layer(layer, chosen, input, out)` for a layer's chosen experts: both matrix products of each, the + activation between them, and the weighted sum of the results. `CpuProducts` does what the code did before, so the CPU model's results are unchanged to the last digit. `CudaProducts` does the same products on the GPU. Everything else, for now, still runs on the CPU, and the same golden checks run with either. A matrix is handed over as the slice of the weight file it lives in; the GPU side recognises it by where the slice starts and copies it to the device the first time it is used. -## What the first step costs and buys +## What each step costs and buys -Each product on the GPU is a round trip: copy the input vector to the device, launch, wait, copy the result -back. On a GB10, generating 90 tokens: +A BF16 product on the GPU is a round trip: copy the input vector to the device, launch, wait, copy the +result back. A layer's experts stay on the device from their input to their weighted sum: one copy in, four +launches, one copy out. On a GB10, generating 90 tokens, per generated token: -| Per generated token | Count | Time | +| | Experts as two round trips | Experts kept on the device | |---|---|---| -| BF16 products | 689 | 26.8 ms | -| Expert launches | 96 | 13.0 ms | -| Everything else, on the CPU | | 20.6 ms | -| Total | | 60.4 ms: 16.6 tokens per second | +| BF16 products (689 round trips) | 26.8 ms | 26.8 ms | +| Experts | 13.0 ms | 10.5 ms | +| Everything else, on the CPU | 20.6 ms | 13.1 ms | +| Total | 60.4 ms: 16.6 tokens per second | 50.3 ms: 19.9 tokens per second | -The CPU model manages 2.6 tokens per second on a fast laptop. The products alone, at the rate the kernels -read weights, would take about 22 ms; the rest of their 40 ms is the round trips, about 18 microseconds -each. So the table is also the to-do list: keep vectors on the device between products, and move the -largest pieces of "everything else" there one at a time. After each move the model still runs and is still -checked. +The CPU model manages 2.6 tokens per second on a fast laptop. Keeping the experts on the device did more +for the CPU column than for its own: the activation between an expert's two matrices is about 1.3 million +`tanh` and `exp` calls per token, and they no longer run on the CPU. + +The products alone, at the rate the kernels read weights, would take about 22 ms. So the table is also the +to-do list: keep vectors on the device between BF16 products, and move the largest pieces of "everything +else" there one at a time, measuring each. A first guess at what the CPU time was made of turned out wrong +when it was timed, which is the reason for measuring before moving anything. ## How we know it is right With products on the GPU the tiny model matches the reference at all 72 recorded tokens, and the real Inkling 2 Mini matches its 32-bit reference recording at all 96, to 0.00006 in log-probability against a -bar of 0.00015. A test in the model crate counts that every product of a token goes through the seam. Three +bar of 0.00015. A test in the model crate counts that every product of a token goes through the seam. Four planted bugs in the GPU side each fail the tiny model's check: an expert's factor left out, the first -expert read whichever was chosen, and every job multiplying the first vector. +expert read whichever was chosen, every second matrix reading the first expert's activation, and every +expert given the first one's weight. The two small kernels of the expert stage are tested against their +CPU functions, with a planted bug each. -The tiny model passes more narrowly than the real one (0.0042 against 0.0044). Its random weights amplify +The tiny model passes more narrowly than the real one (0.0033 against 0.0044). Its random weights amplify the rounding differences between two orders of addition, which is why its bar is derived from how much the reference differs from itself (note 14). diff --git a/tools/mutants/68-cuda-expert-factor-dropped.patch b/tools/mutants/68-cuda-expert-factor-dropped.patch index b912ca9..a8cc4b0 100644 --- a/tools/mutants/68-cuda-expert-factor-dropped.patch +++ b/tools/mutants/68-cuda-expert-factor-dropped.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: the GPU products leave out each expert's factor. diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs -index 106c6a3..822d19d 100644 +index 14f7f8f..580511b 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs -@@ -186,7 +186,7 @@ impl Products for CudaProducts<'_> { - .map(|(j, &(expert, _))| Job { - values: expert * per_values, - scales: expert * per_scales, -- factor: m.factor(expert), -+ factor: 1.0, - vectors: vec![(j * cols, j)], - }) - .collect(); +@@ -234,7 +234,7 @@ impl Products for CudaProducts<'_> { + .map(|(j, &(expert, _))| Job { + values: expert * per_values, + scales: expert * per_scales, +- factor: m.factor(expert), ++ factor: 1.0, + vectors: vec![(vector(j), j)], + }) + .collect() diff --git a/tools/mutants/69-cuda-always-first-expert.patch b/tools/mutants/69-cuda-always-first-expert.patch index b40aca8..7a58683 100644 --- a/tools/mutants/69-cuda-always-first-expert.patch +++ b/tools/mutants/69-cuda-always-first-expert.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: the GPU products read the first expert of the layer whichever was chosen. diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs -index 106c6a3..4ad66d2 100644 +index 14f7f8f..13c84bc 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs -@@ -184,7 +184,7 @@ impl Products for CudaProducts<'_> { - .iter() - .enumerate() - .map(|(j, &(expert, _))| Job { -- values: expert * per_values, -+ values: 0, - scales: expert * per_scales, - factor: m.factor(expert), - vectors: vec![(j * cols, j)], +@@ -232,7 +232,7 @@ impl Products for CudaProducts<'_> { + .iter() + .enumerate() + .map(|(j, &(expert, _))| Job { +- values: expert * per_values, ++ values: 0, + scales: expert * per_scales, + factor: m.factor(expert), + vectors: vec![(vector(j), j)], diff --git a/tools/mutants/70-cuda-expert-first-vector.patch b/tools/mutants/70-cuda-expert-first-vector.patch index 230be70..b373521 100644 --- a/tools/mutants/70-cuda-expert-first-vector.patch +++ b/tools/mutants/70-cuda-expert-first-vector.patch @@ -1,16 +1,16 @@ # test: cargo test --release -p dluth-cuda --test inkling_golden_cuda the_tiny_model_matches # needs: gpu -# Bug: every expert job on the GPU multiplies the first input vector. +# Bug: every expert's second matrix on the GPU reads the first expert's activation. diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs -index 106c6a3..d50b3c3 100644 +index 14f7f8f..4293c1c 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs -@@ -187,7 +187,7 @@ impl Products for CudaProducts<'_> { - values: expert * per_values, - scales: expert * per_scales, - factor: m.factor(expert), -- vectors: vec![(j * cols, j)], -+ vectors: vec![(0, j)], - }) - .collect(); - let format = match m.format() { +@@ -242,7 +242,7 @@ impl Products for CudaProducts<'_> { + self.blockmat.run(first, &jobs(layer.first, &|_| 0), &dx, &d_both, &jobs_first, SEGS).map_err(failed)?; + self.ops.capped_gate_pairs(&d_both, &d_act, n * inner, layer.gate_cap, layer.up_cap).map_err(failed)?; + self.blockmat +- .run(second, &jobs(layer.second, &|j| j * inner), &d_act, &d_outs, &jobs_second, SEGS) ++ .run(second, &jobs(layer.second, &|_| 0), &d_act, &d_outs, &jobs_second, SEGS) + .map_err(failed)?; + self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h).map_err(failed)?; + self.receive(&dy, out)?; diff --git a/tools/mutants/72-gate-sigmoid-of-capped.patch b/tools/mutants/72-gate-sigmoid-of-capped.patch new file mode 100644 index 0000000..0d69f06 --- /dev/null +++ b/tools/mutants/72-gate-sigmoid-of-capped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test expert_ops the_activation +# needs: gpu +# Bug: the expert activation on the GPU takes the sigmoid of the capped gate, not the raw one. +diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu +index c23c4c7..14b1f18 100644 +--- a/crates/dluth-cuda/kernels/expert_ops.cu ++++ b/crates/dluth-cuda/kernels/expert_ops.cu +@@ -15,7 +15,7 @@ extern "C" __global__ void capped_gate_pairs(const float* both, float* act, unsi + float2 gu = reinterpret_cast(both)[i]; + float gate = gate_cap * tanhf(gu.x / gate_cap); + float up = up_cap * tanhf(gu.y / up_cap); +- act[i] = gate * (1.0f / (1.0f + expf(-gu.x))) * up; ++ act[i] = gate * (1.0f / (1.0f + expf(-gate))) * up; + } + + // The weighted sum of the chosen experts' outputs: diff --git a/tools/mutants/73-weighted-sum-unweighted.patch b/tools/mutants/73-weighted-sum-unweighted.patch new file mode 100644 index 0000000..6786f5b --- /dev/null +++ b/tools/mutants/73-weighted-sum-unweighted.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-cuda --test expert_ops the_weighted_sum +# needs: gpu +# Bug: the experts' outputs are added without their weights. +diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu +index c23c4c7..ca3d48c 100644 +--- a/crates/dluth-cuda/kernels/expert_ops.cu ++++ b/crates/dluth-cuda/kernels/expert_ops.cu +@@ -27,6 +27,6 @@ extern "C" __global__ void weighted_sum(const float* outs, const float* weights, + unsigned int r = blockIdx.x * blockDim.x + threadIdx.x; + if (r >= width) return; + float total = 0.0f; +- for (unsigned int j = 0; j < count; ++j) total += weights[j] * outs[(size_t)j * width + r]; ++ for (unsigned int j = 0; j < count; ++j) total += outs[(size_t)j * width + r]; + y[r] = total; + } diff --git a/tools/mutants/74-cuda-route-weights-dropped.patch b/tools/mutants/74-cuda-route-weights-dropped.patch new file mode 100644 index 0000000..d9c8c01 --- /dev/null +++ b/tools/mutants/74-cuda-route-weights-dropped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda the_tiny_model_matches +# needs: gpu +# Bug: the GPU products weight every chosen expert by the first expert's weight. +diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs +index 14f7f8f..3bf6841 100644 +--- a/crates/dluth-cuda/src/inkling.rs ++++ b/crates/dluth-cuda/src/inkling.rs +@@ -215,7 +215,7 @@ impl Products for CudaProducts<'_> { + // Everything the kernels read is copied before the first launch, so no buffer is + // written while a kernel may still be reading it. + let dx = self.send(input)?; +- let weights: Vec = chosen.iter().flat_map(|&(_, w)| w.to_le_bytes()).collect(); ++ let weights: Vec = chosen.iter().flat_map(|_| chosen[0].1.to_le_bytes()).collect(); + let d_route = self.route.at_least(dev, weights.len()).map_err(failed)?; + dev.upload(&d_route, &weights).map_err(failed)?; + let d_both = self.both.at_least(dev, n * pairs2 * 4).map_err(failed)?; From fc49cb6bbc766d483c5f608ef9391f5b0d0c13fc Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:25:23 -0800 Subject: [PATCH 7/8] test: two planted bugs regenerated after the expert step moved --- tools/mutants/45-inkling-router-bias.patch | 10 ++++---- .../mutants/47-inkling-gate-up-swapped.patch | 24 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/tools/mutants/45-inkling-router-bias.patch b/tools/mutants/45-inkling-router-bias.patch index 9d51879..301e5a6 100644 --- a/tools/mutants/45-inkling-router-bias.patch +++ b/tools/mutants/45-inkling-router-bias.patch @@ -3,15 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: experts are chosen without the routing bias. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 8693fee..3caca5c 100644 +index 4fbbac5..564caa0 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -797,7 +797,7 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 - let (h, inner) = (cfg.hidden, cfg.expert_width); +@@ -836,7 +836,7 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 + let h = cfg.hidden; let mut scores = vec![0.0f32; cfg.experts]; p.bf16(layer.router, cfg.experts, h, input, &mut scores)?; - let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); + let chosen = router::choose(&scores, &vec![0.0; cfg.experts], cfg.experts_per_token, cfg.route_scale); - // Every chosen expert's first matrix reads the same input. - let jobs: Vec<(usize, &[f32])> = chosen.iter().map(|&(expert, _)| (expert, input)).collect(); + let mut total = vec![0.0f32; h]; + let layer = ExpertLayer { first: &layer.first, second: &layer.second, gate_cap: cfg.gate_cap, up_cap: cfg.up_cap }; diff --git a/tools/mutants/47-inkling-gate-up-swapped.patch b/tools/mutants/47-inkling-gate-up-swapped.patch index 21a8f3a..8107c89 100644 --- a/tools/mutants/47-inkling-gate-up-swapped.patch +++ b/tools/mutants/47-inkling-gate-up-swapped.patch @@ -3,17 +3,17 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: an expert reads its gate and up rows the wrong way round. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 8693fee..4c08d29 100644 +index 4fbbac5..287e4d4 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -809,8 +809,8 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 - let (mut gate, mut up) = (vec![0.0f32; inner], vec![0.0f32; inner]); - for (both, act) in both.chunks_exact(2 * inner).zip(acts.chunks_exact_mut(inner)) { - for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { -- gate[i] = pair[0]; -- up[i] = pair[1]; -+ gate[i] = pair[1]; -+ up[i] = pair[0]; - } - cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, act); - } +@@ -202,8 +202,8 @@ impl Products for CpuProducts { + layer.first.apply(expert, input, &mut both); + // Gate and up values alternate. + for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { +- gate[i] = pair[0]; +- up[i] = pair[1]; ++ gate[i] = pair[1]; ++ up[i] = pair[0]; + } + cpu::capped_gate_mul(&gate, &up, layer.gate_cap, layer.up_cap, &mut act); + layer.second.apply(expert, &act, &mut one); From 05927ba9c0fcd274bda5bdb2a024e8bd308f2fc8 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:00 -0800 Subject: [PATCH 8/8] fix: the CPU expert layer checks the first matrix's rows; no allocation per product on the GPU side; a refusal for aliased buffers; note states each model's bar; review fixes --- crates/dluth-cuda/examples/generate.rs | 2 +- crates/dluth-cuda/src/expert_ops.rs | 4 ++-- crates/dluth-cuda/src/inkling.rs | 18 ++++++++++++------ crates/dluth-cuda/tests/expert_ops.rs | 4 +++- crates/dluth-model/src/inkling/model.rs | 2 +- .../20-the-model-on-the-gpu-in-steps.md | 4 +++- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 190496d..190da1c 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -57,8 +57,8 @@ fn main() { ids.len(), (first - started).as_secs_f64() ); - println!("generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", decoded as f64 / seconds); if decoded > 0 { + println!("generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", decoded as f64 / seconds); let per = |n: usize| n as f64 / decoded as f64; let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0 / decoded as f64; let bf16 = total.bf16_time - at_first.bf16_time; diff --git a/crates/dluth-cuda/src/expert_ops.rs b/crates/dluth-cuda/src/expert_ops.rs index e7d229f..2ef5413 100644 --- a/crates/dluth-cuda/src/expert_ops.rs +++ b/crates/dluth-cuda/src/expert_ops.rs @@ -82,8 +82,8 @@ impl<'m> ExpertOps<'m> { "{count} vectors of {width} with buffers of {outs_have}, {weights_have} and {y_have} bytes" )); } - if y.handle == outs.handle || y.handle == weights.handle { - return refuse("the output buffer is also an input".into()); + if y.handle == outs.handle || y.handle == weights.handle || outs.handle == weights.handle { + return refuse("one buffer used for two of the three arguments".into()); } let (mut po, mut pw, mut py, mut c, mut w) = (outs.handle, weights.handle, y.handle, count as u32, width as u32); diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs index 14f7f8f..8108a86 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs @@ -83,6 +83,9 @@ pub struct CudaProducts<'m> { route: Growing, jobs: Growing, jobs_second: Growing, + /// Host bytes on their way to or from the device, kept so that a product does not + /// allocate. + staging: Vec, stats: Rc>, } @@ -103,6 +106,7 @@ impl<'m> CudaProducts<'m> { route: Growing { buffer: None }, jobs: Growing { buffer: None }, jobs_second: Growing { buffer: None }, + staging: Vec::new(), stats: Rc::default(), }) } @@ -151,17 +155,19 @@ impl<'m> CudaProducts<'m> { fn send(&mut self, values: &[f32]) -> Result { let buffer = self.x.at_least(self.dev, values.len() * 4).map_err(failed)?; - let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); - self.dev.upload(&buffer, &bytes).map_err(failed)?; + self.staging.clear(); + self.staging.extend(values.iter().flat_map(|v| v.to_le_bytes())); + self.dev.upload(&buffer, &self.staging).map_err(failed)?; Ok(buffer) } /// Waits for the device and copies `out.len()` floats back from `buffer`. - fn receive(&self, buffer: &Buffer, out: &mut [f32]) -> Result<(), ModelError> { + fn receive(&mut self, buffer: &Buffer, out: &mut [f32]) -> Result<(), ModelError> { self.dev.synchronize().map_err(failed)?; - let mut bytes = vec![0u8; out.len() * 4]; - self.dev.download(buffer, &mut bytes).map_err(failed)?; - for (o, chunk) in out.iter_mut().zip(bytes.as_chunks::<4>().0) { + self.staging.clear(); + self.staging.resize(out.len() * 4, 0); + self.dev.download(buffer, &mut self.staging).map_err(failed)?; + for (o, chunk) in out.iter_mut().zip(self.staging.as_chunks::<4>().0) { *o = f32::from_le_bytes(*chunk); } Ok(()) diff --git a/crates/dluth-cuda/tests/expert_ops.rs b/crates/dluth-cuda/tests/expert_ops.rs index 8a1f492..7ef22b4 100644 --- a/crates/dluth-cuda/tests/expert_ops.rs +++ b/crates/dluth-cuda/tests/expert_ops.rs @@ -54,7 +54,7 @@ fn the_activation_matches_the_cpu_reference() { assert!((got[i] - want[i]).abs() <= bound, "pair {i} ({}, {}): {} vs {}", gate[i], up[i], got[i], want[i]); } // The cases the formula exists for: a huge gate is capped, a hugely negative one is shut. - assert!(want.iter().any(|w| w.abs() > 90.0) && want.contains(&0.0)); + assert!(got.iter().any(|g| g.abs() > 90.0) && got.contains(&0.0)); } #[test] @@ -107,6 +107,8 @@ fn requests_that_would_leave_the_buffers_are_refused() { ("no vectors", ops.weighted_sum(&outs, &weights, &y, 0, 6)), ("no width", ops.weighted_sum(&outs, &weights, &y, 3, 0)), ("output over the input", ops.weighted_sum(&outs, &weights, &outs, 3, 6)), + ("output over the weights", ops.weighted_sum(&outs, &y, &y, 1, 6)), + ("the vectors as their own weights", ops.weighted_sum(&outs, &outs, &y, 3, 6)), ] { assert!(matches!(result, Err(CudaError::Refused(_))), "{what} was not refused"); } diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 4fbbac5..2cd0054 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -189,7 +189,7 @@ impl Products for CpuProducts { ) -> Result<(), ModelError> { let (h, inner) = (layer.second.shape().0, layer.second.shape().1); assert!( - out.len() == h && input.len() == layer.first.shape().1, + out.len() == h && input.len() == layer.first.shape().1 && layer.first.shape().0 == 2 * inner, "expert_layer: {} inputs, {} outputs", input.len(), out.len() diff --git a/docs/learning/20-the-model-on-the-gpu-in-steps.md b/docs/learning/20-the-model-on-the-gpu-in-steps.md index 082c482..f84c257 100644 --- a/docs/learning/20-the-model-on-the-gpu-in-steps.md +++ b/docs/learning/20-the-model-on-the-gpu-in-steps.md @@ -55,6 +55,8 @@ expert read whichever was chosen, every second matrix reading the first expert's expert given the first one's weight. The two small kernels of the expert stage are tested against their CPU functions, with a planted bug each. -The tiny model passes more narrowly than the real one (0.0033 against 0.0044). Its random weights amplify +Each model has its own bar, four times what its reference differs from itself by. The tiny model passes +more narrowly against its bar (0.0033 against 0.0044) than the real model against its own (0.00006 against +0.00015). The tiny model's random weights amplify the rounding differences between two orders of addition, which is why its bar is derived from how much the reference differs from itself (note 14).