From 54d48f832dd783c6df150105f5fc52a2a6d30ebc Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:52:56 -0800 Subject: [PATCH 1/5] perf(cuda): a blend's normalizing, mixing and following normalization in one launch, for up to four queries --- crates/dluth-cuda/kernels/small_ops.cu | 97 ++++++++++++++++ crates/dluth-cuda/src/ops.rs | 144 +++++++++++++++++------- crates/dluth-cuda/src/small.rs | 97 ++++++++++++++++ crates/dluth-cuda/tests/small.rs | 99 ++++++++++++++++ crates/dluth-model/src/inkling/model.rs | 96 +++++++++++----- 5 files changed, 464 insertions(+), 69 deletions(-) diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu index 0d40107..d58de41 100644 --- a/crates/dluth-cuda/kernels/small_ops.cu +++ b/crates/dluth-cuda/kernels/small_ops.cu @@ -144,3 +144,100 @@ extern "C" __global__ void vec_copy(const float* x, float* out, unsigned int n) unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) out[i] = x[i]; } + +// A whole blend across depth for up to four queries at once, from the candidates as they +// are (not normalized beforehand), each optionally followed by a normalization with +// learned weights. For position b of a batch and query q: +// n_j = candidate_j[b] / sqrt(mean(candidate_j[b]^2) + blend_eps) +// weights = softmax over j of (query_q . n_j) * scale +// mixed = sum over j of weights_j * n_j +// out_q[b] = mixed if norm_q is null +// = mixed / sqrt(mean(mixed^2) + norm_eps) * norm_q otherwise +// One block of threads per (position, query). Each candidate is its own buffer holding the +// batch; each query and each norm is one vector of `width`; each output holds the batch. +// CPU reference: depthmix::normalize, depthmix::mix_normalized and cpu::rmsnorm, one after +// the other. Here a candidate's dot product with the query is taken before the candidate +// is scaled, and the sums are added in a different order. +#define BLEND_QUERIES 4 +extern "C" __global__ void blend_many( + const float* c0, const float* c1, const float* c2, const float* c3, const float* c4, const float* c5, + const float* c6, const float* c7, const float* c8, const float* c9, const float* c10, const float* c11, + const float* c12, const float* c13, const float* c14, const float* c15, + const float* q0, const float* q1, const float* q2, const float* q3, + const float* w0, const float* w1, const float* w2, const float* w3, + float* o0, float* o1, float* o2, float* o3, + unsigned int count, unsigned int width, float scale, float blend_eps, float norm_eps, + unsigned int batch, unsigned int queries) { + __shared__ float squares[BLEND_MAX][256]; + __shared__ float dots[BLEND_MAX][256]; + __shared__ float coefficient[BLEND_MAX]; + unsigned int b = blockIdx.x / queries; + unsigned int which = blockIdx.x % queries; + if (b >= batch) return; + const float* candidates[BLEND_MAX] = {c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15}; + const float* all_queries[BLEND_QUERIES] = {q0, q1, q2, q3}; + const float* all_norms[BLEND_QUERIES] = {w0, w1, w2, w3}; + float* all_outs[BLEND_QUERIES] = {o0, o1, o2, o3}; + const float* query = all_queries[which]; + const float* norm = all_norms[which]; + float* out = all_outs[which] + (size_t)b * width; + size_t at = (size_t)b * width; + + float mine_squares[BLEND_MAX]; + float mine_dots[BLEND_MAX]; + for (unsigned int j = 0; j < count; ++j) mine_squares[j] = mine_dots[j] = 0.0f; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) { + float q = query[i]; + for (unsigned int j = 0; j < count; ++j) { + float x = candidates[j][at + i]; + mine_squares[j] += x * x; + mine_dots[j] += q * x; + } + } + for (unsigned int j = 0; j < count; ++j) { + squares[j][threadIdx.x] = mine_squares[j]; + dots[j][threadIdx.x] = mine_dots[j]; + } + __syncthreads(); + if (threadIdx.x == 0) { + float best = -INFINITY; + for (unsigned int j = 0; j < count; ++j) { + float s = 0.0f, d = 0.0f; + for (unsigned int t = 0; t < blockDim.x; ++t) { + s += squares[j][t]; + d += dots[j][t]; + } + float inverse = 1.0f / sqrtf(s / (float)width + blend_eps); + squares[j][0] = inverse; + dots[j][0] = d * inverse * scale; + best = fmaxf(best, dots[j][0]); + } + float sum = 0.0f; + for (unsigned int j = 0; j < count; ++j) { + coefficient[j] = expf(dots[j][0] - best); + sum += coefficient[j]; + } + // The weight of a candidate times the factor that normalizes it. + for (unsigned int j = 0; j < count; ++j) coefficient[j] = coefficient[j] / sum * squares[j][0]; + } + __syncthreads(); + float mixed_squares = 0.0f; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) { + float total = 0.0f; + for (unsigned int j = 0; j < count; ++j) total += coefficient[j] * candidates[j][at + i]; + out[i] = total; + mixed_squares += total * total; + } + if (norm == nullptr) return; + __syncthreads(); + squares[0][threadIdx.x] = mixed_squares; + __syncthreads(); + if (threadIdx.x == 0) { + float s = 0.0f; + for (unsigned int t = 0; t < blockDim.x; ++t) s += squares[0][t]; + coefficient[0] = 1.0f / sqrtf(s / (float)width + norm_eps); + } + __syncthreads(); + float factor = coefficient[0]; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) out[i] = out[i] * factor * norm[i]; +} diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index e777e21..afb9405 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -26,7 +26,7 @@ use crate::expert_ops::ExpertOps; use crate::floats::Floats; use crate::matmat::{Bf16Matrix, Matmat}; use crate::module::Module; -use crate::small::{Small, BLEND_MAX, MANY}; +use crate::small::{Small, BLEND_MAX, BLEND_QUERIES}; use dluth_core::{bf16_to_f32, Backend, Buffer}; use dluth_kernels::{cpu, router}; use dluth_model::inkling::{ExpertFormat, ExpertMatrices, Gate, InklingConfig, KvConv, Layer, Ops, BLEND_EPS}; @@ -115,8 +115,8 @@ impl DeviceVec { /// Candidates normalized for blending: for each position of a batch, `count` vectors of /// `width`, one after another. pub struct DeviceBlend { - data: DeviceVec, - count: usize, + /// The candidates as they were given. Normalizing them is part of each blend. + candidates: Vec, width: usize, batch: usize, } @@ -615,6 +615,59 @@ impl<'m> CudaOps<'m> { } } +impl CudaOps<'_> { + /// A blend of more candidates than one launch takes, step by step: normalize them into + /// one buffer, score them for each query, weigh and add them, normalize the result. + fn blend_in_steps( + &mut self, + blend: &DeviceBlend, + queries: &[&[f32]], + norms: &[Option<&[f32]>], + eps: f32, + ) -> Result, ModelError> { + let (count, width, batch) = (blend.candidates.len(), blend.width, blend.batch); + // Each position's candidates one after another, position after position. + let data = self.vecs(batch, count * width)?; + for b in 0..batch { + for (j, candidate) in blend.candidates.iter().enumerate() { + let out = data.part((b * count + j) * width, width); + self.rmsnorm_plain(candidate.part(b * width, width), out, BLEND_EPS)?; + } + } + let mut outs = Vec::with_capacity(queries.len()); + for (query, norm) in queries.iter().zip(norms) { + let query = self.param(query)?; + let scores = self.vec(batch * count)?; + for b in 0..batch { + self.small + .blend_scores( + Floats::first(&query, width), + data.part(b * count * width, count * width), + scores.part(b * count, count), + count, + width, + ) + .map_err(failed)?; + } + self.attention.softmax_runs(scores.all(), batch, count).map_err(failed)?; + let mixed = self.vecs(batch, width)?; + self.expert_ops + .weighted_sum(&data.0.buffer, &scores.0.buffer, &mixed.0.buffer, count, width, batch) + .map_err(failed)?; + outs.push(match norm { + Some(weights) => { + let weights = self.param(weights)?; + let out = self.vecs(batch, width)?; + self.small.rmsnorm(mixed.all(), Floats::first(&weights, width), out.all(), eps).map_err(failed)?; + out + } + None => mixed, + }); + } + Ok(outs) + } +} + impl<'m> Ops for CudaOps<'m> { type V = DeviceVec; type Blend = DeviceBlend; @@ -723,49 +776,53 @@ impl<'m> Ops for CudaOps<'m> { if count == 0 || candidates.iter().any(|c| c.width() != width || c.count() != batch) { return Err(ModelError::Device(format!("a blend of {count} candidates of unequal or no size"))); } - // Each position's candidates one after another, position after position. - let data = self.vecs(batch, count * width)?; - if count <= MANY { - let runs: Vec = candidates.iter().map(|c| c.all()).collect(); - self.small.normalize_many(&runs, data.all(), BLEND_EPS, batch).map_err(failed)?; - } else { - for b in 0..batch { - for (j, candidate) in candidates.iter().enumerate() { - let out = data.part((b * count + j) * width, width); - self.rmsnorm_plain(candidate.part(b * width, width), out, BLEND_EPS)?; - } - } - } - Ok(DeviceBlend { data, count, width, batch }) + // Nothing is started here: each blend normalizes the candidates as it reads them. + Ok(DeviceBlend { candidates: candidates.iter().map(|c| (*c).clone()).collect(), width, batch }) } fn mix(&mut self, blend: &DeviceBlend, query: &[f32]) -> Result { - let (count, width, batch) = (blend.count, blend.width, blend.batch); - let query = self.param(query)?; - let out = self.vecs(batch, width)?; - if count <= BLEND_MAX { - self.small - .blend_mix(Floats::first(&query, width), blend.data.all(), out.all(), count, width) - .map_err(failed)?; - return Ok(out); + let mut one = self.mix_many(blend, &[query], &[None], 0.0)?; + one.pop().ok_or_else(|| ModelError::Device("a blend returned nothing".into())) + } + + fn mix_many( + &mut self, + blend: &DeviceBlend, + queries: &[&[f32]], + norms: &[Option<&[f32]>], + eps: f32, + ) -> Result, ModelError> { + let (count, width, batch) = (blend.candidates.len(), blend.width, blend.batch); + if queries.len() != norms.len() { + return Err(ModelError::Capacity(format!("{} queries with {} norms", queries.len(), norms.len()))); } - let scores = self.vec(batch * count)?; - for b in 0..batch { + if count > BLEND_MAX { + return self.blend_in_steps(blend, queries, norms, eps); + } + let mut outs = Vec::with_capacity(queries.len()); + for (some_queries, some_norms) in queries.chunks(BLEND_QUERIES).zip(norms.chunks(BLEND_QUERIES)) { + let mut query_buffers = Vec::with_capacity(some_queries.len()); + let mut norm_buffers = Vec::with_capacity(some_queries.len()); + for (query, norm) in some_queries.iter().zip(some_norms) { + query_buffers.push(self.param(query)?); + norm_buffers.push(match norm { + Some(weights) => Some(self.param(weights)?), + None => None, + }); + } + let mine: Vec = + (0..some_queries.len()).map(|_| self.vecs(batch, width)).collect::>()?; + let candidates: Vec = blend.candidates.iter().map(|c| c.all()).collect(); + let query_runs: Vec = query_buffers.iter().map(|b| Floats::first(b, width)).collect(); + let norm_runs: Vec> = + norm_buffers.iter().map(|b| b.as_ref().map(|b| Floats::first(b, width))).collect(); + let out_runs: Vec = mine.iter().map(|v| v.all()).collect(); self.small - .blend_scores( - Floats::first(&query, width), - blend.data.part(b * count * width, count * width), - scores.part(b * count, count), - count, - width, - ) + .blend_many(&candidates, &query_runs, &norm_runs, &out_runs, width, batch, BLEND_EPS, eps) .map_err(failed)?; + outs.extend(mine); } - self.attention.softmax_runs(scores.all(), batch, count).map_err(failed)?; - self.expert_ops - .weighted_sum(&blend.data.0.buffer, &scores.0.buffer, &out.0.buffer, count, width, batch) - .map_err(failed)?; - Ok(out) + Ok(outs) } fn merge( @@ -1042,6 +1099,15 @@ impl<'m> Ops for TimedOps<'m> { fn mix(&mut self, blend: &DeviceBlend, query: &[f32]) -> Result { self.timed("blend: mix", |o| o.mix(blend, query)) } + fn mix_many( + &mut self, + blend: &DeviceBlend, + queries: &[&[f32]], + norms: &[Option<&[f32]>], + eps: f32, + ) -> Result, ModelError> { + self.timed("blend: mix", |o| o.mix_many(blend, queries, norms, eps)) + } fn merge( &mut self, cfg: &InklingConfig, diff --git a/crates/dluth-cuda/src/small.rs b/crates/dluth-cuda/src/small.rs index e0098de..7c838a3 100644 --- a/crates/dluth-cuda/src/small.rs +++ b/crates/dluth-cuda/src/small.rs @@ -29,6 +29,8 @@ fn grid(n: usize) -> (u32, u32, u32) { pub const BLEND_MAX: usize = 16; /// Most vectors one `normalize_many` takes. pub const MANY: usize = 8; +/// Most queries one `blend_many` takes. +pub const BLEND_QUERIES: usize = 4; /// The small-operation kernels of a loaded module. pub struct Small<'m> { @@ -41,6 +43,7 @@ pub struct Small<'m> { blend_mix: Kernel<'m>, normalize_many: Kernel<'m>, copy: Kernel<'m>, + blend_many: Kernel<'m>, } impl<'m> Small<'m> { @@ -55,6 +58,7 @@ impl<'m> Small<'m> { blend_mix: module.kernel("blend_mix")?, normalize_many: module.kernel("normalize_many")?, copy: module.kernel("vec_copy")?, + blend_many: module.kernel("blend_many")?, }) } @@ -243,6 +247,99 @@ impl<'m> Small<'m> { unsafe { self.normalize_many.launch(((count * batch) as u32, 1, 1), (256, 1, 1), &mut args) } } + /// A whole blend for up to `BLEND_QUERIES` queries in one launch, from candidates that + /// have not been normalized: for each position of the batch and each query, normalize + /// the candidates, blend them as the query asks, and, where a norm is given for the + /// query, normalize the blend with those weights. + /// + /// Each of the up to `BLEND_MAX` candidates holds `batch` vectors of `width`; each + /// query and each norm is one vector of `width`; each output receives `batch` vectors. + #[allow(clippy::too_many_arguments)] + pub fn blend_many( + &self, + candidates: &[Floats], + queries: &[Floats], + norms: &[Option], + outs: &[Floats], + width: usize, + batch: usize, + blend_eps: f32, + norm_eps: f32, + ) -> Result<(), CudaError> { + let what = "blend_many"; + let (count, asked) = (candidates.len(), queries.len()); + if count == 0 || count > BLEND_MAX || asked == 0 || asked > BLEND_QUERIES { + return refuse( + what, + format!("{count} candidates for {asked} queries; at most {BLEND_MAX} and {BLEND_QUERIES}"), + ); + } + if norms.len() != asked || outs.len() != asked { + return refuse(what, format!("{asked} queries with {} norms and {} outputs", norms.len(), outs.len())); + } + if width == 0 || width > 1 << 24 || batch == 0 || batch > 1 << 12 { + return refuse(what, format!("{batch} positions of {width}")); + } + let finite = |e: f32| e >= 0.0 && e.is_finite(); + if !finite(blend_eps) || !finite(norm_eps) { + return refuse(what, format!("eps of {blend_eps} and {norm_eps}")); + } + let mut reads: Vec<&Floats> = Vec::new(); + for candidate in candidates { + if candidate.len != batch * width { + return refuse(what, format!("a candidate of {} floats for {batch} of {width}", candidate.len)); + } + candidate.check(self.dev, what, batch * width)?; + reads.push(candidate); + } + for vector in queries.iter().chain(norms.iter().flatten()) { + if vector.len != width { + return refuse(what, format!("a query or norm of {} floats for a width of {width}", vector.len)); + } + vector.check(self.dev, what, width)?; + reads.push(vector); + } + for (i, out) in outs.iter().enumerate() { + if out.len != batch * width { + return refuse(what, format!("an output of {} floats for {batch} of {width}", out.len)); + } + out.check(self.dev, what, batch * width)?; + if reads.iter().any(|read| read.overlaps(out)) || outs[..i].iter().any(|other| other.overlaps(out)) { + return refuse(what, "an output overlaps an input or another output".into()); + } + } + // Unused slots are null: the kernel only touches the first `count` candidates and + // the first `asked` of the rest, and a null norm means no normalization. + let mut c = [0u64; BLEND_MAX]; + let (mut q, mut w, mut o) = ([0u64; BLEND_QUERIES], [0u64; BLEND_QUERIES], [0u64; BLEND_QUERIES]); + c.iter_mut().zip(candidates).for_each(|(slot, f)| *slot = f.address()); + q.iter_mut().zip(queries).for_each(|(slot, f)| *slot = f.address()); + w.iter_mut().zip(norms).for_each(|(slot, f)| *slot = f.map_or(0, |f| f.address())); + o.iter_mut().zip(outs).for_each(|(slot, f)| *slot = f.address()); + let (mut n, mut wd, mut scale) = (count as u32, width as u32, 1.0 / (width as f32).sqrt()); + let (mut be, mut ne, mut b, mut nq) = (blend_eps, norm_eps, batch as u32, asked as u32); + let mut args: Vec<*mut c_void> = Vec::with_capacity(35); + args.extend(c.iter_mut().chain(&mut q).chain(&mut w).chain(&mut o).map(ptr)); + args.extend([ + num(&mut n), + num(&mut wd), + real(&mut scale), + real(&mut be), + real(&mut ne), + num(&mut b), + num(&mut nq), + ]); + // SAFETY: the arguments match blend_many(16 candidate pointers, 4 query pointers, + // 4 norm pointers, 4 output pointers, unsigned, unsigned, float, float, float, + // unsigned, unsigned), 35 in all. One block of 256 threads (the size of the + // kernel's shared rows) per (position, query) reads batch * width floats of each of + // the first `count` candidates (at most BLEND_MAX, the number of shared rows), + // `width` floats of its query and of its norm unless that is null, and writes + // batch * width floats to its output. All were checked; no output overlaps + // anything read or another output. + unsafe { self.blend_many.launch(((batch * asked) as u32, 1, 1), (256, 1, 1), &mut args) } + } + /// `out[i] = (1 - tanh(forget[i])) * x[i] + tanh(gain[i]) * message[i]`. pub fn gate_merge( &self, diff --git a/crates/dluth-cuda/tests/small.rs b/crates/dluth-cuda/tests/small.rs index 1762be7..9d838c3 100644 --- a/crates/dluth-cuda/tests/small.rs +++ b/crates/dluth-cuda/tests/small.rs @@ -167,6 +167,90 @@ fn a_whole_blend_in_one_launch_matches_the_cpu() { } } +/// The whole blend in one launch, from candidates that were not normalized beforehand: +/// against the CPU's three steps (normalize the candidates, blend, normalize the blend). +#[test] +fn a_blend_from_raw_candidates_for_several_queries_matches_the_cpu() { + use dluth_cuda::small::{BLEND_MAX, BLEND_QUERIES}; + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let small = Small::new(&dev, &module).unwrap(); + let mut rng = Lcg(21); + // One candidate and one query; the real shapes (9 candidates of 2304, 1, 3 and 4 + // queries, batches of 1 and 16); the most a launch takes; a width below the threads. + for (count, width, batch, asked) in [ + (1, 5, 1, 1), + (9, 2304, 1, 3), + (9, 2304, 16, 4), + (4, 2304, 3, 1), + (BLEND_MAX, 700, 2, BLEND_QUERIES), + (3, 100, 5, 2), + ] { + // Candidates of very different sizes, so that normalizing them matters; one of them + // all zeros at one position. + let mut candidates: Vec> = + (0..count).map(|j| rng.vec(batch * width, [1.0, 0.02, 30.0, 400.0][j % 4])).collect(); + if count > 1 { + candidates[1][..width].fill(0.0); + } + let queries: Vec> = (0..asked).map(|_| rng.vec(width, 0.6)).collect(); + // Every other query's blend is normalized with weights; the rest are left as mixed. + let norms: Vec>> = (0..asked).map(|q| (q % 2 == 0).then(|| rng.vec(width, 2.0))).collect(); + let d_candidates: Vec = candidates.iter().map(|c| upload(&dev, c)).collect(); + let d_queries: Vec = queries.iter().map(|q| upload(&dev, q)).collect(); + let d_norms: Vec> = norms.iter().map(|n| n.as_ref().map(|n| upload(&dev, n))).collect(); + let d_outs: Vec = (0..asked).map(|_| dev.alloc(batch * width * 4).unwrap()).collect(); + small + .blend_many( + &d_candidates.iter().map(|b| Floats::first(b, batch * width)).collect::>(), + &d_queries.iter().map(|b| Floats::first(b, width)).collect::>(), + &d_norms.iter().map(|b| b.as_ref().map(|b| Floats::first(b, width))).collect::>(), + &d_outs.iter().map(|b| Floats::first(b, batch * width)).collect::>(), + width, + batch, + 1e-6, + 1e-5, + ) + .unwrap(); + for q in 0..asked { + let got = download(&dev, &d_outs[q], batch * width); + for b in 0..batch { + let mine: Vec<&[f32]> = candidates.iter().map(|c| &c[b * width..(b + 1) * width]).collect(); + let normalized = depthmix::normalize(&mine, 1e-6); + let mut mixed = vec![0.0f32; width]; + depthmix::mix_normalized(&queries[q], &normalized, width, &mut mixed); + let want = match &norms[q] { + Some(weights) => { + let mut out = vec![0.0f32; width]; + cpu::rmsnorm(&mixed, weights, 1e-5, &mut out); + out + } + None => mixed, + }; + // As for the blend alone: scores are sums of `width` products added in + // another order, which moves the weights by a few roundings times the size + // of a score. The terms are of size below 2, times a norm weight below 2. + let bound = 256.0 * (width as f32).sqrt() * f32::EPSILON; + for i in 0..width { + let g = got[b * width + i]; + assert!( + (g - want[i]).abs() <= bound, + "{count} of {width}, query {q}, position {b}, element {i}: {g} vs {}", + want[i] + ); + } + } + } + // Queries differ, so their blends do; positions differ, so theirs do. + if asked > 1 { + assert_ne!(download(&dev, &d_outs[0], width), download(&dev, &d_outs[1], width)); + } + for buffer in d_candidates.into_iter().chain(d_queries).chain(d_norms.into_iter().flatten()).chain(d_outs) { + dev.free(buffer).unwrap(); + } + } +} + #[test] fn several_vectors_normalized_in_one_launch_match_the_cpu() { let dev = CudaDevice::open(0).expect("GPU"); @@ -290,6 +374,21 @@ fn requests_that_would_leave_the_buffers_are_refused() { refused("no positions", small.normalize_many(&[f(&a, 16)], f(&c, 16), 1e-6, 0)); refused("weights that do not divide the vectors", small.rmsnorm(f(&a, 16), f(&b, 5), f(&c, 16), 1e-6)); refused("a copy over itself", small.copy(f(&a, 16), f(&a, 16))); + let blend = |candidates: &[Floats], queries: &[Floats], norms: &[Option], outs: &[Floats], batch: usize| { + small.blend_many(candidates, queries, norms, outs, 16, batch, 1e-6, 1e-6) + }; + let (q, out) = (Floats { buffer: &c, at: 0, len: 16 }, Floats { buffer: &c, at: 32, len: 16 }); + blend(&[f(&a, 16)], &[q], &[None], &[out], 1).unwrap(); + dev.synchronize().unwrap(); + refused("no candidates", blend(&[], &[q], &[None], &[out], 1)); + refused("more candidates than a launch takes", blend(&[f(&a, 16); 17], &[q], &[None], &[out], 1)); + refused("more queries than a launch takes", blend(&[f(&a, 16)], &[q; 5], &[None; 5], &[out; 5], 1)); + refused("a norm missing for a query", blend(&[f(&a, 16)], &[q], &[], &[out], 1)); + refused("a candidate shorter than the batch", blend(&[f(&a, 16)], &[q], &[None], &[out], 2)); + refused("an output over a candidate", blend(&[f(&a, 16)], &[q], &[None], &[f(&a, 16)], 1)); + refused("an output over the query", blend(&[f(&a, 16)], &[q], &[None], &[q], 1)); + refused("two queries writing one output", blend(&[f(&a, 16)], &[q, q], &[None, None], &[out, out], 1)); + refused("a norm of the wrong width", blend(&[f(&a, 16)], &[q], &[Some(f(&b, 8))], &[out], 1)); refused("a cap of zero", small.softcap(f(&a, 16), 0.0)); refused("a cap that is not a number", small.softcap(f(&a, 16), f32::NAN)); } diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 2fdd02c..f3572a5 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -341,6 +341,30 @@ pub trait Ops { fn normalize(&mut self, candidates: &[&Self::V]) -> Result; /// The blend of normalized candidates that `query` asks for. fn mix(&mut self, blend: &Self::Blend, query: &[f32]) -> Result; + /// Several blends of the same candidates, one per query. Where `norms` has weights for + /// a query, its blend is then normalized with them as `rmsnorm` does. The result is + /// what `mix` and `rmsnorm` give one after the other; an implementation may do the lot + /// in one go. + fn mix_many( + &mut self, + blend: &Self::Blend, + queries: &[&[f32]], + norms: &[Option<&[f32]>], + eps: f32, + ) -> Result, ModelError> { + if queries.len() != norms.len() { + return Err(ModelError::Capacity(format!("{} queries with {} norms", queries.len(), norms.len()))); + } + let mut out = Vec::with_capacity(queries.len()); + for (query, norm) in queries.iter().zip(norms) { + let mixed = self.mix(blend, query)?; + out.push(match norm { + Some(weights) => self.rmsnorm(&mixed, weights, eps)?, + None => mixed, + }); + } + Ok(out) + } /// Merges a message from the previous pass into a sublayer input through a gate. fn merge( &mut self, @@ -1003,11 +1027,9 @@ impl<'w, O: Ops> Inkling<'w, O> { let messages = match (&message_source, cfg.is_looped(step.layer) && step.pass > 0) { (Some(source), true) => { let at = (step.layer - cfg.loop_start) * 4 * h; - let mut four = Vec::with_capacity(4); - for port in 0..4 { - four.push(ops.mix(source, &self.message_queries[at + port * h..at + (port + 1) * h])?); - } - Some(four) + let queries: Vec<&[f32]> = + (0..4).map(|port| &self.message_queries[at + port * h..at + (port + 1) * h]).collect(); + Some(ops.mix_many(source, &queries, &[None; 4], cfg.eps)?) } _ => None, }; @@ -1053,9 +1075,8 @@ impl<'w, O: Ops> Inkling<'w, O> { candidates.push(last); } let blend = ops.normalize(&candidates)?; - let blended = ops.mix(&blend, &self.final_query)?; - let normed = ops.rmsnorm(&blended, &self.final_norm, cfg.eps)?; - ops.scores(cfg, self.unembed, &normed) + let normed = ops.mix_many(&blend, &[&self.final_query], &[Some(&self.final_norm)], cfg.eps)?; + ops.scores(cfg, self.unembed, &normed[0]) } /// How many tokens of a prompt `generate_greedy` feeds at once (1 unless set). With @@ -1506,32 +1527,42 @@ fn apply_layer( // 1. The attention inputs: the first layer reads the running sum; every other layer // blends the finished blocks and the running sum, once (local) or once each for // queries, keys and values (global). - let inputs: [O::V; 3] = if layer.attn_queries.is_empty() { - [x.clone(), x.clone(), x.clone()] + // 2. From the second pass on, the previous pass's messages are merged in. Then each + // input is normalized. Without messages a blend goes straight to its normalization, + // which the operations may do in one go. + let ports = [Port::Query, Port::Key, Port::Value]; + let has_messages = layer.gates.is_some() && messages.is_some(); + let merge_then_norm = |ops: &mut O, index: usize, input: O::V| -> Result { + let input = merged(ops, ports[index], input)?; + ops.rmsnorm(&input, &layer.input_norms[index], cfg.eps) + }; + let normed: Vec = if layer.attn_queries.is_empty() { + let mut three = Vec::with_capacity(3); + for index in 0..3 { + three.push(merge_then_norm(ops, index, x.clone())?); + } + three } else { let mut candidates: Vec<&O::V> = blocks.iter().collect(); candidates.push(x); let blend = ops.normalize(&candidates)?; - if layer.local { - let one = ops.mix(&blend, &layer.attn_queries)?; - [one.clone(), one.clone(), one] + let queries: Vec<&[f32]> = if layer.local { + vec![&layer.attn_queries[..]] } else { - [ - ops.mix(&blend, &layer.attn_queries[..h])?, - ops.mix(&blend, &layer.attn_queries[h..2 * h])?, - ops.mix(&blend, &layer.attn_queries[2 * h..])?, - ] + vec![&layer.attn_queries[..h], &layer.attn_queries[h..2 * h], &layer.attn_queries[2 * h..]] + }; + // A local layer's three inputs are one blend (and its three norms are one set of + // weights); a global layer has a blend and a norm for each. + let norms: Vec> = + (0..queries.len()).map(|i| (!has_messages).then_some(&layer.input_norms[i][..])).collect(); + let mixed = ops.mix_many(&blend, &queries, &norms, cfg.eps)?; + let mut three = Vec::with_capacity(3); + for index in 0..3 { + let input = mixed[if layer.local { 0 } else { index }].clone(); + three.push(if has_messages { merge_then_norm(ops, index, input)? } else { input }); } + three }; - // 2. From the second pass on, merge in the previous pass's messages, then normalize. - let [q, k, v] = inputs; - let mut normed = Vec::with_capacity(3); - for ((input, port), weights) in - [q, k, v].into_iter().zip([Port::Query, Port::Key, Port::Value]).zip(&layer.input_norms) - { - let input = merged(ops, port, input)?; - normed.push(ops.rmsnorm(&input, weights, cfg.eps)?); - } // 3. Attention, then a short convolution over its recent outputs. let attended = ops.attention(cfg, layer, pass, [&normed[0], &normed[1], &normed[2]], pos)?; @@ -1550,9 +1581,14 @@ fn apply_layer( let mut candidates: Vec<&O::V> = blocks.iter().collect(); candidates.push(&sum); let blend = ops.normalize(&candidates)?; - let blended = ops.mix(&blend, &layer.expert_query)?; - let blended = merged(ops, Port::Expert, blended)?; - let expert_in = ops.rmsnorm(&blended, &layer.expert_norm, cfg.eps)?; + let expert_in = if has_messages { + let blended = ops.mix(&blend, &layer.expert_query)?; + let blended = merged(ops, Port::Expert, blended)?; + ops.rmsnorm(&blended, &layer.expert_norm, cfg.eps)? + } else { + let mut one = ops.mix_many(&blend, &[&layer.expert_query], &[Some(&layer.expert_norm)], cfg.eps)?; + one.pop().ok_or_else(|| ModelError::Device("a blend returned nothing".into()))? + }; let expert_out = ops.experts(cfg, layer, &expert_in)?; let y = ops.expert_conv(layer, pass, &expert_out)?; From 9f86750da4291b82abbc781beb081242d692deb7 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:53:24 -0800 Subject: [PATCH 2/5] test: planted bugs for the combined blend; one regenerated --- .../140-blend-norm-with-messages.patch | 15 +++++++++++++ .../mutants/141-blend-many-norm-skipped.patch | 16 ++++++++++++++ .../142-global-inputs-share-a-blend.patch | 15 +++++++++++++ .../143-fused-blend-not-normalized.patch | 16 ++++++++++++++ .../mutants/144-fused-blend-first-query.patch | 16 ++++++++++++++ .../145-fused-blend-first-position.patch | 16 ++++++++++++++ .../146-fused-blend-norm-of-unit.patch | 16 ++++++++++++++ .../mutants/147-ops-blend-norm-dropped.patch | 17 ++++++++++++++ tools/mutants/41-inkling-value-message.patch | 22 +++++++++---------- 9 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 tools/mutants/140-blend-norm-with-messages.patch create mode 100644 tools/mutants/141-blend-many-norm-skipped.patch create mode 100644 tools/mutants/142-global-inputs-share-a-blend.patch create mode 100644 tools/mutants/143-fused-blend-not-normalized.patch create mode 100644 tools/mutants/144-fused-blend-first-query.patch create mode 100644 tools/mutants/145-fused-blend-first-position.patch create mode 100644 tools/mutants/146-fused-blend-norm-of-unit.patch create mode 100644 tools/mutants/147-ops-blend-norm-dropped.patch diff --git a/tools/mutants/140-blend-norm-with-messages.patch b/tools/mutants/140-blend-norm-with-messages.patch new file mode 100644 index 0000000..1aa60cb --- /dev/null +++ b/tools/mutants/140-blend-norm-with-messages.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test tiny_inkling_golden +# Bug: a blend is normalized before its message is merged in, and again after. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index f3572a5..053b38d 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1554,7 +1554,7 @@ fn apply_layer( + // A local layer's three inputs are one blend (and its three norms are one set of + // weights); a global layer has a blend and a norm for each. + let norms: Vec> = +- (0..queries.len()).map(|i| (!has_messages).then_some(&layer.input_norms[i][..])).collect(); ++ (0..queries.len()).map(|i| Some(&layer.input_norms[i][..])).collect(); + let mixed = ops.mix_many(&blend, &queries, &norms, cfg.eps)?; + let mut three = Vec::with_capacity(3); + for index in 0..3 { diff --git a/tools/mutants/141-blend-many-norm-skipped.patch b/tools/mutants/141-blend-many-norm-skipped.patch new file mode 100644 index 0000000..da0f0f7 --- /dev/null +++ b/tools/mutants/141-blend-many-norm-skipped.patch @@ -0,0 +1,16 @@ +# test: cargo test -p dluth-model --test tiny_inkling_golden +# Bug: blends asked for with a normalization come back without it. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index f3572a5..cc2ccb4 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -359,8 +359,7 @@ pub trait Ops { + for (query, norm) in queries.iter().zip(norms) { + let mixed = self.mix(blend, query)?; + out.push(match norm { +- Some(weights) => self.rmsnorm(&mixed, weights, eps)?, +- None => mixed, ++ _ => mixed, + }); + } + Ok(out) diff --git a/tools/mutants/142-global-inputs-share-a-blend.patch b/tools/mutants/142-global-inputs-share-a-blend.patch new file mode 100644 index 0000000..88b95fc --- /dev/null +++ b/tools/mutants/142-global-inputs-share-a-blend.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test tiny_inkling_golden +# Bug: a global layer's key and value inputs are the query's blend. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index f3572a5..f0a491d 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1558,7 +1558,7 @@ fn apply_layer( + let mixed = ops.mix_many(&blend, &queries, &norms, cfg.eps)?; + let mut three = Vec::with_capacity(3); + for index in 0..3 { +- let input = mixed[if layer.local { 0 } else { index }].clone(); ++ let input = mixed[0].clone(); + three.push(if has_messages { merge_then_norm(ops, index, input)? } else { input }); + } + three diff --git a/tools/mutants/143-fused-blend-not-normalized.patch b/tools/mutants/143-fused-blend-not-normalized.patch new file mode 100644 index 0000000..4617206 --- /dev/null +++ b/tools/mutants/143-fused-blend-not-normalized.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: the fused blend takes the candidates as they are, not normalized. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index d58de41..26c1c4f 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -207,7 +207,7 @@ extern "C" __global__ void blend_many( + s += squares[j][t]; + d += dots[j][t]; + } +- float inverse = 1.0f / sqrtf(s / (float)width + blend_eps); ++ float inverse = 1.0f; + squares[j][0] = inverse; + dots[j][0] = d * inverse * scale; + best = fmaxf(best, dots[j][0]); diff --git a/tools/mutants/144-fused-blend-first-query.patch b/tools/mutants/144-fused-blend-first-query.patch new file mode 100644 index 0000000..a634769 --- /dev/null +++ b/tools/mutants/144-fused-blend-first-query.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: every query of a fused blend is given the first query's blend. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index d58de41..96badcd 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -178,7 +178,7 @@ extern "C" __global__ void blend_many( + const float* all_queries[BLEND_QUERIES] = {q0, q1, q2, q3}; + const float* all_norms[BLEND_QUERIES] = {w0, w1, w2, w3}; + float* all_outs[BLEND_QUERIES] = {o0, o1, o2, o3}; +- const float* query = all_queries[which]; ++ const float* query = all_queries[0]; + const float* norm = all_norms[which]; + float* out = all_outs[which] + (size_t)b * width; + size_t at = (size_t)b * width; diff --git a/tools/mutants/145-fused-blend-first-position.patch b/tools/mutants/145-fused-blend-first-position.patch new file mode 100644 index 0000000..6e851de --- /dev/null +++ b/tools/mutants/145-fused-blend-first-position.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: every position of a fused blend reads the first position's candidates. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index d58de41..a70d94b 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -181,7 +181,7 @@ extern "C" __global__ void blend_many( + const float* query = all_queries[which]; + const float* norm = all_norms[which]; + float* out = all_outs[which] + (size_t)b * width; +- size_t at = (size_t)b * width; ++ size_t at = 0; + + float mine_squares[BLEND_MAX]; + float mine_dots[BLEND_MAX]; diff --git a/tools/mutants/146-fused-blend-norm-of-unit.patch b/tools/mutants/146-fused-blend-norm-of-unit.patch new file mode 100644 index 0000000..3ee26a5 --- /dev/null +++ b/tools/mutants/146-fused-blend-norm-of-unit.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: the normalization after a fused blend leaves out the blend's own size. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index d58de41..1a32ec2 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -235,7 +235,7 @@ extern "C" __global__ void blend_many( + if (threadIdx.x == 0) { + float s = 0.0f; + for (unsigned int t = 0; t < blockDim.x; ++t) s += squares[0][t]; +- coefficient[0] = 1.0f / sqrtf(s / (float)width + norm_eps); ++ coefficient[0] = 1.0f; + } + __syncthreads(); + float factor = coefficient[0]; diff --git a/tools/mutants/147-ops-blend-norm-dropped.patch b/tools/mutants/147-ops-blend-norm-dropped.patch new file mode 100644 index 0000000..f310e3f --- /dev/null +++ b/tools/mutants/147-ops-blend-norm-dropped.patch @@ -0,0 +1,17 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_matches +# needs: gpu +# Bug: the device asks for its blends without their normalization. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index afb9405..43679d1 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -806,8 +806,7 @@ impl<'m> Ops for CudaOps<'m> { + for (query, norm) in some_queries.iter().zip(some_norms) { + query_buffers.push(self.param(query)?); + norm_buffers.push(match norm { +- Some(weights) => Some(self.param(weights)?), +- None => None, ++ _ => None, + }); + } + let mine: Vec = diff --git a/tools/mutants/41-inkling-value-message.patch b/tools/mutants/41-inkling-value-message.patch index 22578a9..daad23f 100644 --- a/tools/mutants/41-inkling-value-message.patch +++ b/tools/mutants/41-inkling-value-message.patch @@ -1,17 +1,15 @@ # test: cargo test -p dluth-model --test tiny_inkling_golden -# test-weights: cargo test --release -p dluth-model --test inkling_golden -# weights-env: DLUTH_INKLING2_MINI # Bug: the message for the value input is dropped. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 306a8fc..1ab29ae 100644 +index f3572a5..2f18bbb 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1083,7 +1083,7 @@ fn apply_layer( - for ((input, port), weights) in - [q, k, v].into_iter().zip([Port::Query, Port::Key, Port::Value]).zip(&layer.input_norms) - { -- let input = merged(ops, port, input)?; -+ let input = if matches!(port, Port::Value) { input } else { merged(ops, port, input)? }; - normed.push(ops.rmsnorm(&input, weights, cfg.eps)?); - } - +@@ -1533,7 +1533,7 @@ fn apply_layer( + let ports = [Port::Query, Port::Key, Port::Value]; + let has_messages = layer.gates.is_some() && messages.is_some(); + let merge_then_norm = |ops: &mut O, index: usize, input: O::V| -> Result { +- let input = merged(ops, ports[index], input)?; ++ let input = if index == 2 { input } else { merged(ops, ports[index], input)? }; + ops.rmsnorm(&input, &layer.input_norms[index], cfg.eps) + }; + let normed: Vec = if layer.attn_queries.is_empty() { From 110042dc4801a1973ad891afb372c8852169f04f Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:09:27 -0800 Subject: [PATCH 3/5] perf(cuda): sums within warps in the blend, a kernel for short wide matrices, attention's value sum shared by 16 threads; the unused blend kernel removed; review fixes --- crates/dluth-cuda/kernels/attention.cu | 40 ++++++---- crates/dluth-cuda/kernels/matmat_bf16.cu | 35 +++++++++ crates/dluth-cuda/kernels/small_ops.cu | 76 ++++++------------- crates/dluth-cuda/src/attention.rs | 13 +++- crates/dluth-cuda/src/matmat.rs | 29 ++++++- crates/dluth-cuda/src/small.rs | 46 +---------- .../dluth-cuda/tests/inkling_golden_cuda.rs | 59 ++++++++++++++ crates/dluth-cuda/tests/matmat_bf16.rs | 19 ++++- crates/dluth-cuda/tests/small.rs | 58 +++----------- crates/dluth-model/src/inkling/model.rs | 9 ++- .../106-batch-blend-of-first-position.patch | 16 ---- tools/mutants/85-blend-scores-unscaled.patch | 16 ---- 12 files changed, 220 insertions(+), 196 deletions(-) delete mode 100644 tools/mutants/106-batch-blend-of-first-position.patch delete mode 100644 tools/mutants/85-blend-scores-unscaled.patch diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu index ac774e9..e920501 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu @@ -233,26 +233,36 @@ extern "C" __global__ void attn_softmax(float* weights, unsigned int heads, unsi for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) w[i] /= sum; } -// The weighted sum of the values: out[b][h][e] = sum over the tokens query b sees, oldest -// first, of the token's weight times its value. The sink has no value. -// CPU reference: the summing loop of sinkattn::attend. +// The weighted sum of the values: out[b][h][e] = sum over the tokens query b sees of the +// token's weight times its value. The sink has no value. `segs` threads share one output +// element, each taking every segs-th token, and their sums are combined with warp shuffles +// (segs is a power of two up to 32, the block size a multiple of 32): one thread walking +// every token a query sees took as long as the tokens are many. +// CPU reference: the summing loop of sinkattn::attend, which adds oldest first. extern "C" __global__ void attn_values(const float* weights, const float* values, float* out, unsigned int heads, unsigned int kv_heads, unsigned int dim, unsigned long long pos, unsigned long long window, unsigned long long cap, unsigned long long stride, - unsigned int batch) { - unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; - unsigned long long run = index / dim; - unsigned int e = (unsigned int)(index % dim); - if (run >= (unsigned long long)batch * heads) return; - unsigned int h = (unsigned int)(run % heads); - unsigned long long at = pos + run / heads; - unsigned long long seen = tokens_seen(at, window); - const float* w = weights + run * stride; - unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; + unsigned int batch, unsigned int segs) { + unsigned long long thread = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long element = thread / segs; + unsigned int seg = (unsigned int)(thread % segs); + unsigned long long run = element / dim; + unsigned int e = (unsigned int)(element % dim); + bool live = run < (unsigned long long)batch * heads; float total = 0.0f; - for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; - out[index] = total; + if (live) { + unsigned int h = (unsigned int)(run % heads); + unsigned long long at = pos + run / heads; + unsigned long long seen = tokens_seen(at, window); + const float* w = weights + run * stride; + unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; + for (unsigned long long d = seg; d < seen; d += segs) + total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; + } + // Every thread of the warp takes part in the shuffles, including those past the last element. + for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset); + if (live && seg == 0) out[element] = total; } // x[i] *= sigmoid(gate[i]). CPU reference: cpu::sigmoid. diff --git a/crates/dluth-cuda/kernels/matmat_bf16.cu b/crates/dluth-cuda/kernels/matmat_bf16.cu index 6a237b0..81c0a39 100644 --- a/crates/dluth-cuda/kernels/matmat_bf16.cu +++ b/crates/dluth-cuda/kernels/matmat_bf16.cu @@ -73,3 +73,38 @@ MATMAT_BF16(1) MATMAT_BF16(2) MATMAT_BF16(3) MATMAT_BF16(4) MATMAT_BF16(5) MATMAT_BF16(6) MATMAT_BF16(7) MATMAT_BF16(8) MATMAT_BF16(9) MATMAT_BF16(10) MATMAT_BF16(11) MATMAT_BF16(12) MATMAT_BF16(13) MATMAT_BF16(14) MATMAT_BF16(15) MATMAT_BF16(16) + +// The same product for a matrix of few, long rows (a 64 by 4608 gate, a 128 by 2304 +// router). With at most 32 threads to a row, as above, each thread walks hundreds of +// columns one load after another, and the kernel's time is that walk, not the bytes. Here +// a whole block of 256 threads shares one row for one vector: thread t takes every 256th +// group of eight columns, the sums are added within each warp by shuffles, and one thread +// adds the eight warps'. +// Needs what the fast path above needs: cols a multiple of 8, the pointers 16-byte aligned. +extern "C" __global__ void matmat_bf16_short(const unsigned short* w, const float* x, float* y, + unsigned int rows, unsigned int cols, unsigned int batch) { + __shared__ float part[8]; + unsigned int b = blockIdx.x / rows; + unsigned int row = blockIdx.x % rows; + if (b >= batch) return; + const unsigned short* wr = w + (size_t)row * cols; + const float* xv = x + (size_t)b * cols; + float acc = 0.0f; + for (unsigned int c = threadIdx.x * 8; c < cols; c += blockDim.x * 8) { + uint4 bits = *reinterpret_cast(wr + c); + const float4* xb = reinterpret_cast(xv + c); + float4 lo = xb[0], hi = xb[1]; + acc += __uint_as_float(bits.x << 16) * lo.x + __uint_as_float(bits.x & 0xffff0000u) * lo.y + + __uint_as_float(bits.y << 16) * lo.z + __uint_as_float(bits.y & 0xffff0000u) * lo.w + + __uint_as_float(bits.z << 16) * hi.x + __uint_as_float(bits.z & 0xffff0000u) * hi.y + + __uint_as_float(bits.w << 16) * hi.z + __uint_as_float(bits.w & 0xffff0000u) * hi.w; + } + for (int offset = 16; offset > 0; offset >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, offset); + if (threadIdx.x % 32 == 0) part[threadIdx.x / 32] = acc; + __syncthreads(); + if (threadIdx.x == 0) { + float total = 0.0f; + for (unsigned int i = 0; i < blockDim.x / 32; ++i) total += part[i]; + y[(size_t)b * rows + row] = total; + } +} diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu index d58de41..6f6753d 100644 --- a/crates/dluth-cuda/kernels/small_ops.cu +++ b/crates/dluth-cuda/kernels/small_ops.cu @@ -64,51 +64,8 @@ extern "C" __global__ void softcap_inplace(float* x, unsigned int n, float cap) if (i < n) x[i] = cap * tanhf(x[i] / cap); } -// A whole blend across depth in one launch, one block of threads per position of a batch: -// score_j = (query . candidate_j) * scale; weights = softmax(scores); -// out[b] = sum over j of weights_j * candidate_j -// Position b's `count` candidates of `width` floats are one after another in `candidates`, -// after those of the positions before it. CPU reference: depthmix::mix_normalized, once per -// position. +// Most candidates a blend takes in one launch (see blend_many). #define BLEND_MAX 16 -extern "C" __global__ void blend_mix(const float* query, const float* candidates, float* out, - unsigned int count, unsigned int width, float scale, - unsigned int batch) { - __shared__ float part[BLEND_MAX][256]; - __shared__ float weight[BLEND_MAX]; - if (blockIdx.x >= batch) return; - const float* mine = candidates + (size_t)blockIdx.x * count * width; - float* o = out + (size_t)blockIdx.x * width; - float dot[BLEND_MAX]; - for (unsigned int j = 0; j < count; ++j) dot[j] = 0.0f; - for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) { - float q = query[i]; - for (unsigned int j = 0; j < count; ++j) dot[j] += q * mine[(size_t)j * width + i]; - } - for (unsigned int j = 0; j < count; ++j) part[j][threadIdx.x] = dot[j]; - __syncthreads(); - if (threadIdx.x == 0) { - float best = -INFINITY; - for (unsigned int j = 0; j < count; ++j) { - float s = 0.0f; - for (unsigned int t = 0; t < blockDim.x; ++t) s += part[j][t]; - weight[j] = s * scale; - best = fmaxf(best, weight[j]); - } - float sum = 0.0f; - for (unsigned int j = 0; j < count; ++j) { - weight[j] = expf(weight[j] - best); - sum += weight[j]; - } - for (unsigned int j = 0; j < count; ++j) weight[j] /= sum; - } - __syncthreads(); - for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) { - float total = 0.0f; - for (unsigned int j = 0; j < count; ++j) total += weight[j] * mine[(size_t)j * width + i]; - o[i] = total; - } -} // Up to eight candidates, each wherever it lives and each a batch of vectors of `width`, // normalized into one buffer in one launch: @@ -158,7 +115,18 @@ extern "C" __global__ void vec_copy(const float* x, float* out, unsigned int n) // CPU reference: depthmix::normalize, depthmix::mix_normalized and cpu::rmsnorm, one after // the other. Here a candidate's dot product with the query is taken before the candidate // is scaled, and the sums are added in a different order. +// The sum of `v` over the 32 threads of a warp, in every one of them. Every thread of the +// warp must call it. +__device__ __forceinline__ float warp_sum(float v) { + for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_xor_sync(0xffffffffu, v, offset); + return v; +} + +// Sums are first taken within each warp of 32 threads, by shuffles, and one thread then +// adds the few warps' sums: a block's single thread adding every thread's part one after +// the other took most of this kernel's time. #define BLEND_QUERIES 4 +#define BLEND_WARPS 8 extern "C" __global__ void blend_many( const float* c0, const float* c1, const float* c2, const float* c3, const float* c4, const float* c5, const float* c6, const float* c7, const float* c8, const float* c9, const float* c10, const float* c11, @@ -168,9 +136,10 @@ extern "C" __global__ void blend_many( float* o0, float* o1, float* o2, float* o3, unsigned int count, unsigned int width, float scale, float blend_eps, float norm_eps, unsigned int batch, unsigned int queries) { - __shared__ float squares[BLEND_MAX][256]; - __shared__ float dots[BLEND_MAX][256]; + __shared__ float squares[BLEND_MAX][BLEND_WARPS]; + __shared__ float dots[BLEND_MAX][BLEND_WARPS]; __shared__ float coefficient[BLEND_MAX]; + unsigned int warp = threadIdx.x / 32, lane = threadIdx.x % 32, warps = blockDim.x / 32; unsigned int b = blockIdx.x / queries; unsigned int which = blockIdx.x % queries; if (b >= batch) return; @@ -195,15 +164,19 @@ extern "C" __global__ void blend_many( } } for (unsigned int j = 0; j < count; ++j) { - squares[j][threadIdx.x] = mine_squares[j]; - dots[j][threadIdx.x] = mine_dots[j]; + float s = warp_sum(mine_squares[j]); + float d = warp_sum(mine_dots[j]); + if (lane == 0) { + squares[j][warp] = s; + dots[j][warp] = d; + } } __syncthreads(); if (threadIdx.x == 0) { float best = -INFINITY; for (unsigned int j = 0; j < count; ++j) { float s = 0.0f, d = 0.0f; - for (unsigned int t = 0; t < blockDim.x; ++t) { + for (unsigned int t = 0; t < warps; ++t) { s += squares[j][t]; d += dots[j][t]; } @@ -229,12 +202,13 @@ extern "C" __global__ void blend_many( mixed_squares += total * total; } if (norm == nullptr) return; + mixed_squares = warp_sum(mixed_squares); __syncthreads(); - squares[0][threadIdx.x] = mixed_squares; + if (lane == 0) squares[0][warp] = mixed_squares; __syncthreads(); if (threadIdx.x == 0) { float s = 0.0f; - for (unsigned int t = 0; t < blockDim.x; ++t) s += squares[0][t]; + for (unsigned int t = 0; t < warps; ++t) s += squares[0][t]; coefficient[0] = 1.0f / sqrtf(s / (float)width + norm_eps); } __syncthreads(); diff --git a/crates/dluth-cuda/src/attention.rs b/crates/dluth-cuda/src/attention.rs index 482a1a4..73b6dd3 100644 --- a/crates/dluth-cuda/src/attention.rs +++ b/crates/dluth-cuda/src/attention.rs @@ -35,6 +35,9 @@ fn real(p: &mut f32) -> *mut c_void { /// Most consecutive tokens one launch takes. pub const MAX_BATCH: usize = 16; +/// Threads that share one element of attention's output, each summing every 16th token. +const VALUE_SEGS: u32 = 16; + /// The shape of a layer's attention: query heads, key-value heads, and the size of a head. #[derive(Clone, Copy, Debug)] pub struct Heads { @@ -527,11 +530,14 @@ impl<'m> Attention<'m> { // table and the sinks, and writes into each (query, head) run of `stride` floats at // most seen + 1 entries, where seen + 1 is at most `stride`. attn_softmax rewrites // those entries in place, one block of 256 threads per run. attn_values reads them - // and the values' rows and writes runs * dim floats to `out`. Every extent was + // and the values' rows and writes runs * dim floats to `out`, VALUE_SEGS threads + // to an element (a power of two up to 32, in blocks of a multiple of 32, as its + // shuffles need). Every extent was // checked above, and nothing written overlaps anything read. unsafe { self.scores.launch((blocks((runs * stride) as u64, 256)?, 1, 1), (256, 1, 1), &mut args)? }; let mut args = [ptr(&mut pw), num(&mut h), big(&mut p), big(&mut win), big(&mut st), num(&mut b)]; unsafe { self.softmax.launch((runs as u32, 1, 1), (256, 1, 1), &mut args)? }; + let mut segs = VALUE_SEGS; let mut args = [ ptr(&mut pw), ptr(&mut pv), @@ -544,8 +550,11 @@ impl<'m> Attention<'m> { big(&mut cap), big(&mut st), num(&mut b), + num(&mut segs), ]; - unsafe { self.values.launch((blocks((runs * dim) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + unsafe { + self.values.launch((blocks((runs * dim) as u64 * VALUE_SEGS as u64, 256)?, 1, 1), (256, 1, 1), &mut args) + } } /// How many floats of scratch `attend` needs per head for a batch of `batch` queries diff --git a/crates/dluth-cuda/src/matmat.rs b/crates/dluth-cuda/src/matmat.rs index b06548d..7e68c44 100644 --- a/crates/dluth-cuda/src/matmat.rs +++ b/crates/dluth-cuda/src/matmat.rs @@ -25,6 +25,11 @@ pub struct Bf16Matrix<'b> { pub cols: usize, } +/// A matrix of at most this many rows, each of at least `SHORT_COLS` columns, is given a +/// block of threads per row. +const SHORT_ROWS: usize = 256; +const SHORT_COLS: usize = 1024; + fn pw_of(w: &Bf16Matrix) -> u64 { w.buffer.handle + w.offset as u64 } @@ -34,12 +39,14 @@ pub struct Matmat<'m> { dev: &'m CudaDevice, /// `bf16[b - 1]` multiplies a batch of `b`. bf16: Vec>, + /// For a matrix of few, long rows. + short: Kernel<'m>, } impl<'m> Matmat<'m> { pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { let bf16 = (1..=MAX_BATCH).map(|b| module.kernel(&format!("matmat_bf16_b{b}"))).collect::>()?; - Ok(Matmat { dev, bf16 }) + Ok(Matmat { dev, bf16, short: module.kernel("matmat_bf16_short")? }) } /// Starts `y[b][r] = sum_c w[r][c] * x[b][c]` for `batch` vectors and returns without @@ -79,6 +86,26 @@ impl<'m> Matmat<'m> { let mut wide = u32::from(w.cols.is_multiple_of(8) && aligned(pw_of(&w)) && aligned(x.handle) && aligned(y.handle)); let (mut rows, mut cols, mut s) = (w.rows as u32, w.cols as u32, segs); + // Few, long rows: a block of threads per row and vector reads them sooner than a + // few threads walking each row would. + if wide == 1 && w.rows <= SHORT_ROWS && w.cols >= SHORT_COLS { + let mut b = batch as u32; + let mut args = [ + &mut pw as *mut u64 as *mut c_void, + &mut px as *mut u64 as *mut c_void, + &mut py as *mut u64 as *mut c_void, + &mut rows as *mut u32 as *mut c_void, + &mut cols as *mut u32 as *mut c_void, + &mut b as *mut u32 as *mut c_void, + ]; + // SAFETY: the arguments match matmat_bf16_short(const unsigned short*, const + // float*, float*, unsigned, unsigned, unsigned). One block of 256 threads (8 + // whole warps, the size of the kernel's shared array) per row and vector reads + // that row's cols weights and that vector's cols floats with 16-byte loads, and + // writes one float: the extents checked above, and `wide` says the loads are + // aligned and a row is a whole number of them. + return unsafe { self.short.launch(((w.rows * batch) as u32, 1, 1), (256, 1, 1), &mut args) }; + } let mut args = [ &mut pw as *mut u64 as *mut c_void, &mut px as *mut u64 as *mut c_void, diff --git a/crates/dluth-cuda/src/small.rs b/crates/dluth-cuda/src/small.rs index 7c838a3..2504d09 100644 --- a/crates/dluth-cuda/src/small.rs +++ b/crates/dluth-cuda/src/small.rs @@ -25,7 +25,7 @@ fn grid(n: usize) -> (u32, u32, u32) { ((n as u32).div_ceil(256), 1, 1) } -/// Most candidates one `blend_mix` takes. +/// Most candidates one `blend_many` takes. pub const BLEND_MAX: usize = 16; /// Most vectors one `normalize_many` takes. pub const MANY: usize = 8; @@ -40,7 +40,6 @@ pub struct Small<'m> { blend_scores: Kernel<'m>, gate_merge: Kernel<'m>, softcap: Kernel<'m>, - blend_mix: Kernel<'m>, normalize_many: Kernel<'m>, copy: Kernel<'m>, blend_many: Kernel<'m>, @@ -55,7 +54,6 @@ impl<'m> Small<'m> { blend_scores: module.kernel("blend_scores")?, gate_merge: module.kernel("gate_merge")?, softcap: module.kernel("softcap_inplace")?, - blend_mix: module.kernel("blend_mix")?, normalize_many: module.kernel("normalize_many")?, copy: module.kernel("vec_copy")?, blend_many: module.kernel("blend_many")?, @@ -152,44 +150,6 @@ impl<'m> Small<'m> { unsafe { self.blend_scores.launch((count as u32, 1, 1), (256, 1, 1), &mut args) } } - /// A whole blend in one launch, for each position of a batch: - /// `out = sum_j softmax_j((query . candidate_j) / sqrt(width)) * candidate_j` over `count` - /// candidates of `width` floats. `candidates` holds each position's candidates one after - /// another, position after position; the batch is `out.len / width`. - pub fn blend_mix( - &self, - query: Floats, - candidates: Floats, - out: Floats, - count: usize, - width: usize, - ) -> Result<(), CudaError> { - let what = "blend_mix"; - if count == 0 || count > BLEND_MAX || width == 0 || width > 1 << 24 || !out.len.is_multiple_of(width) { - return refuse(what, format!("{count} candidates of {width}; at most {BLEND_MAX} candidates")); - } - let batch = out.len / width; - if batch == 0 || batch > 1 << 16 { - return refuse(what, format!("a batch of {batch}")); - } - query.check(self.dev, what, width)?; - candidates.check(self.dev, what, batch * count * width)?; - out.check(self.dev, what, batch * width)?; - if out.overlaps(&query) || out.overlaps(&candidates) { - return refuse(what, "the output overlaps an input".into()); - } - let (mut pq, mut pc, mut po) = (query.address(), candidates.address(), out.address()); - let (mut c, mut w, mut scale, mut b) = (count as u32, width as u32, 1.0 / (width as f32).sqrt(), batch as u32); - let mut args = - [ptr(&mut pq), ptr(&mut pc), ptr(&mut po), num(&mut c), num(&mut w), real(&mut scale), num(&mut b)]; - // SAFETY: the arguments match blend_mix(const float*, const float*, float*, unsigned, - // unsigned, float, unsigned). One block of 256 threads per position, the size of the - // kernel's shared rows, with at most BLEND_MAX candidates, the number of those rows; - // it reads `width` floats of the query and batch * count * width of the candidates - // and writes batch * width to `out`. All checked. - unsafe { self.blend_mix.launch((batch as u32, 1, 1), (256, 1, 1), &mut args) } - } - /// Up to `MANY` candidates, each a batch of `batch` vectors, normalized into `out` so /// that each position's candidates are one after another: /// `out[b][j] = x_j[b] / sqrt(mean(x_j[b]^2) + eps)`. @@ -331,8 +291,8 @@ impl<'m> Small<'m> { ]); // SAFETY: the arguments match blend_many(16 candidate pointers, 4 query pointers, // 4 norm pointers, 4 output pointers, unsigned, unsigned, float, float, float, - // unsigned, unsigned), 35 in all. One block of 256 threads (the size of the - // kernel's shared rows) per (position, query) reads batch * width floats of each of + // unsigned, unsigned), 35 in all. One block of 256 threads (8 whole warps, the + // size of the kernel's shared rows) per (position, query) reads batch * width floats of each of // the first `count` candidates (at most BLEND_MAX, the number of shared rows), // `width` floats of its query and of its norm unless that is null, and writes // batch * width floats to its output. All were checked; no output overlaps diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 88f5d2f..2f70ccd 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -372,6 +372,65 @@ mod on_the_device { assert_eq!(got, want); } + /// A blend of more candidates than one launch takes goes step by step. No model has + /// that many, so the path is driven directly: 17 and 5 candidates, each a batch of + /// three positions, blended for two queries (one with a normalization after it), read + /// back through the output table, against the CPU operations on the same values. + #[test] + fn a_blend_of_more_candidates_than_a_launch_takes_matches_the_cpu() { + use dluth_core::bf16_to_f32; + use dluth_model::inkling::{CpuOps, CpuProducts, Ops}; + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let mut gpu = CudaOps::new(&dev, &module).unwrap(); + let mut cpu = CpuOps::new(Box::new(CpuProducts)); + let table = weights.bytes("model.llm.embed.weight").unwrap(); + let unembed = weights.bytes("model.llm.unembed.weight").unwrap(); + let floats = |name: &str| -> Vec { + weights + .bytes(name) + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|c| bf16_to_f32(u16::from_le_bytes(*c))) + .collect() + }; + let embed_norm = floats("model.llm.embed_norm.weight"); + let after = floats("model.llm.norm.weight"); + let h = cfg.hidden; + let queries: [Vec; 2] = [ + (0..h).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.3).collect(), + (0..h).map(|i| ((i * 5 % 11) as f32 - 5.0) * 0.4).collect(), + ]; + for count in [17usize, 5] { + // Each candidate is three positions' embeddings of other tokens. + let tokens = + |j: usize| -> [u32; 3] { [(j * 3 % 250) as u32, (j * 7 % 250 + 1) as u32, (j * 11 % 250 + 2) as u32] }; + let on_gpu: Vec<_> = (0..count).map(|j| gpu.embed(&cfg, table, &embed_norm, &tokens(j)).unwrap()).collect(); + let on_cpu: Vec<_> = (0..count).map(|j| cpu.embed(&cfg, table, &embed_norm, &tokens(j)).unwrap()).collect(); + let gpu_blend = gpu.normalize(&on_gpu.iter().collect::>()).unwrap(); + let cpu_blend = cpu.normalize(&on_cpu.iter().collect::>()).unwrap(); + let asked: [&[f32]; 2] = [&queries[0], &queries[1]]; + let norms = [Some(&after[..]), None]; + let got = gpu.mix_many(&gpu_blend, &asked, &norms, cfg.eps).unwrap(); + let want = cpu.mix_many(&cpu_blend, &asked, &norms, cfg.eps).unwrap(); + for q in 0..2 { + let (g, w) = + (gpu.scores(&cfg, unembed, &got[q]).unwrap(), cpu.scores(&cfg, unembed, &want[q]).unwrap()); + assert_eq!(g.len(), 3 * cfg.vocab_out); + // Scores are sums of 32 products of values of size about 1. + let worst = g.iter().zip(&w).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 2e-3, "{count} candidates, query {q}: scores differ by {worst}"); + // The two queries, and the three positions, give different scores. + assert!(w[..cfg.vocab_out] != w[cfg.vocab_out..2 * cfg.vocab_out]); + } + } + } + /// More positions than a launch takes are refused before anything is computed, and the /// model goes on as if it had not been asked. #[test] diff --git a/crates/dluth-cuda/tests/matmat_bf16.rs b/crates/dluth-cuda/tests/matmat_bf16.rs index 5d2f078..86d471d 100644 --- a/crates/dluth-cuda/tests/matmat_bf16.rs +++ b/crates/dluth-cuda/tests/matmat_bf16.rs @@ -88,7 +88,24 @@ fn matches_the_cpu_reference_for_every_shape_and_batch() { // of anything, a width that is a multiple of 8 but not of 8 times the thread count (so // the threads of a row take unequal turns), and the shapes of the real model's projections. for (rows, cols) in - [(1, 1), (1, 2304), (2304, 1), (7, 5), (333, 1001), (5, 2312), (3072, 2304), (1024, 2304), (2304, 3072)] + // The last five are few, long rows, which have a kernel of their own: the real gate, + // router and tap shapes, and the two sides of where that kernel takes over. + [ + (1, 1), + (1, 2304), + (2304, 1), + (7, 5), + (333, 1001), + (5, 2312), + (3072, 2304), + (1024, 2304), + (2304, 3072), + (64, 4608), + (128, 2304), + (32, 2304), + (256, 1024), + (257, 1024), + ] { for batch in [1, 2, 8, MAX_BATCH] { seed += 1; diff --git a/crates/dluth-cuda/tests/small.rs b/crates/dluth-cuda/tests/small.rs index 9d838c3..9394d15 100644 --- a/crates/dluth-cuda/tests/small.rs +++ b/crates/dluth-cuda/tests/small.rs @@ -124,49 +124,6 @@ fn blend_scores_match_the_cpu_and_give_the_same_blend() { } } -#[test] -fn a_whole_blend_in_one_launch_matches_the_cpu() { - let dev = CudaDevice::open(0).expect("GPU"); - let module = Module::load_embedded(&dev).unwrap(); - let small = Small::new(&dev, &module).unwrap(); - let mut rng = Lcg(6); - // One candidate (the blend is that candidate), a few, the most a launch takes; widths - // below and above the number of threads. - for (count, width, batch) in - [(1, 5, 1), (2, 100, 3), (6, 2304, 1), (9, 2304, 16), (dluth_cuda::small::BLEND_MAX, 700, 2)] - { - // Each position has its own candidates; the query is shared. - let (query, candidates) = (rng.vec(width, 0.6), rng.vec(batch * count * width, 1.7)); - let (dq, dc, dout) = (upload(&dev, &query), upload(&dev, &candidates), dev.alloc(batch * width * 4).unwrap()); - small - .blend_mix( - Floats::first(&dq, width), - Floats::first(&dc, batch * count * width), - Floats::first(&dout, batch * width), - count, - width, - ) - .unwrap(); - let got = download(&dev, &dout, batch * width); - // The scores are sums of `width` products added in another order, which moves the - // weights by a few roundings times the size of a score; the result is a sum of - // `count` terms of size below 2. - let bound = 64.0 * (width as f32).sqrt() * f32::EPSILON; - for (b, mine) in candidates.chunks_exact(count * width).enumerate() { - let mut want = vec![0.0f32; width]; - depthmix::mix_normalized(&query, mine, width, &mut want); - for i in 0..width { - let g = got[b * width + i]; - assert!( - (g - want[i]).abs() <= bound, - "{count} of {width}, position {b}, element {i}: {g} vs {}", - want[i] - ); - } - } - } -} - /// The whole blend in one launch, from candidates that were not normalized beforehand: /// against the CPU's three steps (normalize the candidates, blend, normalize the blend). #[test] @@ -227,9 +184,10 @@ fn a_blend_from_raw_candidates_for_several_queries_matches_the_cpu() { } None => mixed, }; - // As for the blend alone: scores are sums of `width` products added in - // another order, which moves the weights by a few roundings times the size - // of a score. The terms are of size below 2, times a norm weight below 2. + // Scores are sums of `width` products added in another order, which moves + // the weights by a few roundings times the size of a score. Whatever the + // candidates' sizes, a blend is of normalized candidates, so its elements + // are of size about 1, times a norm weight below 2. let bound = 256.0 * (width as f32).sqrt() * f32::EPSILON; for i in 0..width { let g = got[b * width + i]; @@ -362,9 +320,6 @@ fn requests_that_would_leave_the_buffers_are_refused() { "a gate written over its input", small.gate_merge(f(&a, 16), f(&b, 16), f(&c, 16), Floats { buffer: &c, at: 16, len: 16 }, f(&b, 16)), ); - refused("a blend of more candidates than a launch takes", small.blend_mix(f(&a, 2), f(&c, 34), f(&b, 2), 17, 2)); - refused("a blend written over its candidates", small.blend_mix(f(&a, 16), f(&c, 64), f(&c, 16), 4, 16)); - refused("a blend of candidates the buffer does not hold", small.blend_mix(f(&a, 16), f(&c, 80), f(&b, 16), 5, 16)); let nine = [f(&a, 4); 9]; refused("more vectors than a launch takes", small.normalize_many(&nine, f(&c, 36), 1e-6, 1)); refused("no vectors", small.normalize_many(&[], f(&c, 16), 1e-6, 1)); @@ -389,6 +344,11 @@ fn requests_that_would_leave_the_buffers_are_refused() { refused("an output over the query", blend(&[f(&a, 16)], &[q], &[None], &[q], 1)); refused("two queries writing one output", blend(&[f(&a, 16)], &[q, q], &[None, None], &[out, out], 1)); refused("a norm of the wrong width", blend(&[f(&a, 16)], &[q], &[Some(f(&b, 8))], &[out], 1)); + refused("no positions", blend(&[f(&a, 16)], &[q], &[None], &[out], 0)); + let eps = |blend_eps, norm_eps| small.blend_many(&[f(&a, 16)], &[q], &[None], &[out], 16, 1, blend_eps, norm_eps); + refused("a negative eps", eps(-1e-6, 1e-6)); + refused("an eps that is not a number", eps(1e-6, f32::NAN)); + refused("no width", small.blend_many(&[f(&a, 0)], &[f(&b, 0)], &[None], &[f(&c, 0)], 0, 1, 1e-6, 1e-6)); refused("a cap of zero", small.softcap(f(&a, 16), 0.0)); refused("a cap that is not a number", small.softcap(f(&a, 16), f32::NAN)); } diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index f3572a5..c2a194e 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -1551,8 +1551,13 @@ fn apply_layer( } else { vec![&layer.attn_queries[..h], &layer.attn_queries[h..2 * h], &layer.attn_queries[2 * h..]] }; - // A local layer's three inputs are one blend (and its three norms are one set of - // weights); a global layer has a blend and a norm for each. + // A global layer has a blend and a norm for each of its three inputs. A local layer + // has one blend, and one norm: its weights file holds a single input norm, which + // the loader puts in all three places. + debug_assert!( + !layer.local + || (layer.input_norms[0] == layer.input_norms[1] && layer.input_norms[1] == layer.input_norms[2]) + ); let norms: Vec> = (0..queries.len()).map(|i| (!has_messages).then_some(&layer.input_norms[i][..])).collect(); let mixed = ops.mix_many(&blend, &queries, &norms, cfg.eps)?; diff --git a/tools/mutants/106-batch-blend-of-first-position.patch b/tools/mutants/106-batch-blend-of-first-position.patch deleted file mode 100644 index aded3ab..0000000 --- a/tools/mutants/106-batch-blend-of-first-position.patch +++ /dev/null @@ -1,16 +0,0 @@ -# test: cargo test --release -p dluth-cuda --test small a_whole_blend -# needs: gpu -# Bug: every position of a batch is given the blend of the first position's candidates. -diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu -index 0d40107..2ccb159 100644 ---- a/crates/dluth-cuda/kernels/small_ops.cu -+++ b/crates/dluth-cuda/kernels/small_ops.cu -@@ -77,7 +77,7 @@ extern "C" __global__ void blend_mix(const float* query, const float* candidates - __shared__ float part[BLEND_MAX][256]; - __shared__ float weight[BLEND_MAX]; - if (blockIdx.x >= batch) return; -- const float* mine = candidates + (size_t)blockIdx.x * count * width; -+ const float* mine = candidates; - float* o = out + (size_t)blockIdx.x * width; - float dot[BLEND_MAX]; - for (unsigned int j = 0; j < count; ++j) dot[j] = 0.0f; diff --git a/tools/mutants/85-blend-scores-unscaled.patch b/tools/mutants/85-blend-scores-unscaled.patch deleted file mode 100644 index f15b72a..0000000 --- a/tools/mutants/85-blend-scores-unscaled.patch +++ /dev/null @@ -1,16 +0,0 @@ -# test: cargo test --release -p dluth-cuda --test small a_whole_blend -# needs: gpu -# Bug: the fused blend leaves out the scale of its scores. -diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu -index 25e169f..ccc0b5d 100644 ---- a/crates/dluth-cuda/kernels/small_ops.cu -+++ b/crates/dluth-cuda/kernels/small_ops.cu -@@ -84,7 +84,7 @@ extern "C" __global__ void blend_mix(const float* query, const float* candidates - for (unsigned int j = 0; j < count; ++j) { - float s = 0.0f; - for (unsigned int t = 0; t < blockDim.x; ++t) s += part[j][t]; -- weight[j] = s * scale; -+ weight[j] = s; - best = fmaxf(best, weight[j]); - } - float sum = 0.0f; From c75ba0f5f235cc52efda8d74500605d92db8d055 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:09:56 -0800 Subject: [PATCH 4/5] test: planted bugs for the new kernels; four regenerated --- .../140-blend-norm-with-messages.patch | 8 ++++---- .../146-fused-blend-norm-of-unit.patch | 6 +++--- .../148-blend-in-steps-one-position.patch | 16 +++++++++++++++ .../149-blend-warp-sums-of-one-warp.patch | 16 +++++++++++++++ .../mutants/150-short-matrix-first-warp.patch | 16 +++++++++++++++ .../151-short-matrix-first-vector.patch | 16 +++++++++++++++ .../152-values-first-segment-only.patch | 15 ++++++++++++++ tools/mutants/82-attn-weights-reversed.patch | 20 +++++++++---------- .../85-fused-blend-scores-unscaled.patch | 16 +++++++++++++++ tools/mutants/88-softcap-cap-ignored.patch | 4 ++-- 10 files changed, 114 insertions(+), 19 deletions(-) create mode 100644 tools/mutants/148-blend-in-steps-one-position.patch create mode 100644 tools/mutants/149-blend-warp-sums-of-one-warp.patch create mode 100644 tools/mutants/150-short-matrix-first-warp.patch create mode 100644 tools/mutants/151-short-matrix-first-vector.patch create mode 100644 tools/mutants/152-values-first-segment-only.patch create mode 100644 tools/mutants/85-fused-blend-scores-unscaled.patch diff --git a/tools/mutants/140-blend-norm-with-messages.patch b/tools/mutants/140-blend-norm-with-messages.patch index 1aa60cb..f70d7b6 100644 --- a/tools/mutants/140-blend-norm-with-messages.patch +++ b/tools/mutants/140-blend-norm-with-messages.patch @@ -1,12 +1,12 @@ # test: cargo test -p dluth-model --test tiny_inkling_golden # Bug: a blend is normalized before its message is merged in, and again after. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index f3572a5..053b38d 100644 +index c2a194e..8d20624 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1554,7 +1554,7 @@ fn apply_layer( - // A local layer's three inputs are one blend (and its three norms are one set of - // weights); a global layer has a blend and a norm for each. +@@ -1559,7 +1559,7 @@ fn apply_layer( + || (layer.input_norms[0] == layer.input_norms[1] && layer.input_norms[1] == layer.input_norms[2]) + ); let norms: Vec> = - (0..queries.len()).map(|i| (!has_messages).then_some(&layer.input_norms[i][..])).collect(); + (0..queries.len()).map(|i| Some(&layer.input_norms[i][..])).collect(); diff --git a/tools/mutants/146-fused-blend-norm-of-unit.patch b/tools/mutants/146-fused-blend-norm-of-unit.patch index 3ee26a5..940244d 100644 --- a/tools/mutants/146-fused-blend-norm-of-unit.patch +++ b/tools/mutants/146-fused-blend-norm-of-unit.patch @@ -2,13 +2,13 @@ # needs: gpu # Bug: the normalization after a fused blend leaves out the blend's own size. diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu -index d58de41..1a32ec2 100644 +index 6f6753d..fd71cc8 100644 --- a/crates/dluth-cuda/kernels/small_ops.cu +++ b/crates/dluth-cuda/kernels/small_ops.cu -@@ -235,7 +235,7 @@ extern "C" __global__ void blend_many( +@@ -209,7 +209,7 @@ extern "C" __global__ void blend_many( if (threadIdx.x == 0) { float s = 0.0f; - for (unsigned int t = 0; t < blockDim.x; ++t) s += squares[0][t]; + for (unsigned int t = 0; t < warps; ++t) s += squares[0][t]; - coefficient[0] = 1.0f / sqrtf(s / (float)width + norm_eps); + coefficient[0] = 1.0f; } diff --git a/tools/mutants/148-blend-in-steps-one-position.patch b/tools/mutants/148-blend-in-steps-one-position.patch new file mode 100644 index 0000000..8bb416c --- /dev/null +++ b/tools/mutants/148-blend-in-steps-one-position.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::a_blend_of_more +# needs: gpu +# Bug: the step-by-step blend normalizes every position's candidates into the first position's place. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index afb9405..3ed006c 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -630,7 +630,7 @@ impl CudaOps<'_> { + let data = self.vecs(batch, count * width)?; + for b in 0..batch { + for (j, candidate) in blend.candidates.iter().enumerate() { +- let out = data.part((b * count + j) * width, width); ++ let out = data.part(j * width, width); + self.rmsnorm_plain(candidate.part(b * width, width), out, BLEND_EPS)?; + } + } diff --git a/tools/mutants/149-blend-warp-sums-of-one-warp.patch b/tools/mutants/149-blend-warp-sums-of-one-warp.patch new file mode 100644 index 0000000..af2e41a --- /dev/null +++ b/tools/mutants/149-blend-warp-sums-of-one-warp.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: the fused blend adds up the sums of its first warp only. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 6f6753d..295c480 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -176,7 +176,7 @@ extern "C" __global__ void blend_many( + float best = -INFINITY; + for (unsigned int j = 0; j < count; ++j) { + float s = 0.0f, d = 0.0f; +- for (unsigned int t = 0; t < warps; ++t) { ++ for (unsigned int t = 0; t < 1; ++t) { + s += squares[j][t]; + d += dots[j][t]; + } diff --git a/tools/mutants/150-short-matrix-first-warp.patch b/tools/mutants/150-short-matrix-first-warp.patch new file mode 100644 index 0000000..654f01b --- /dev/null +++ b/tools/mutants/150-short-matrix-first-warp.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test matmat_bf16 +# needs: gpu +# Bug: the kernel for short wide matrices adds up the sums of its first warp only. +diff --git a/crates/dluth-cuda/kernels/matmat_bf16.cu b/crates/dluth-cuda/kernels/matmat_bf16.cu +index 81c0a39..cdd40b4 100644 +--- a/crates/dluth-cuda/kernels/matmat_bf16.cu ++++ b/crates/dluth-cuda/kernels/matmat_bf16.cu +@@ -104,7 +104,7 @@ extern "C" __global__ void matmat_bf16_short(const unsigned short* w, const floa + __syncthreads(); + if (threadIdx.x == 0) { + float total = 0.0f; +- for (unsigned int i = 0; i < blockDim.x / 32; ++i) total += part[i]; ++ total = part[0]; + y[(size_t)b * rows + row] = total; + } + } diff --git a/tools/mutants/151-short-matrix-first-vector.patch b/tools/mutants/151-short-matrix-first-vector.patch new file mode 100644 index 0000000..cb84f04 --- /dev/null +++ b/tools/mutants/151-short-matrix-first-vector.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test matmat_bf16 +# needs: gpu +# Bug: the kernel for short wide matrices multiplies every row with the first vector of the batch. +diff --git a/crates/dluth-cuda/kernels/matmat_bf16.cu b/crates/dluth-cuda/kernels/matmat_bf16.cu +index 81c0a39..f0a0ef1 100644 +--- a/crates/dluth-cuda/kernels/matmat_bf16.cu ++++ b/crates/dluth-cuda/kernels/matmat_bf16.cu +@@ -88,7 +88,7 @@ extern "C" __global__ void matmat_bf16_short(const unsigned short* w, const floa + unsigned int row = blockIdx.x % rows; + if (b >= batch) return; + const unsigned short* wr = w + (size_t)row * cols; +- const float* xv = x + (size_t)b * cols; ++ const float* xv = x; + float acc = 0.0f; + for (unsigned int c = threadIdx.x * 8; c < cols; c += blockDim.x * 8) { + uint4 bits = *reinterpret_cast(wr + c); diff --git a/tools/mutants/152-values-first-segment-only.patch b/tools/mutants/152-values-first-segment-only.patch new file mode 100644 index 0000000..5e793ac --- /dev/null +++ b/tools/mutants/152-values-first-segment-only.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: attention's value sum keeps the tokens of one of the threads that share an element and drops the others'. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index e920501..20b253e 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -261,7 +261,6 @@ extern "C" __global__ void attn_values(const float* weights, const float* values + total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; + } + // Every thread of the warp takes part in the shuffles, including those past the last element. +- for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset); + if (live && seg == 0) out[element] = total; + } + diff --git a/tools/mutants/82-attn-weights-reversed.patch b/tools/mutants/82-attn-weights-reversed.patch index 4cb61fb..2047761 100644 --- a/tools/mutants/82-attn-weights-reversed.patch +++ b/tools/mutants/82-attn-weights-reversed.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: values are weighted with the weights of the tokens at the mirrored distance. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 10196bd..f2fe7d3 100644 +index e920501..f9bafe1 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu -@@ -247,7 +247,7 @@ extern "C" __global__ void attn_values(const float* weights, const float* values - const float* w = weights + run * stride; - unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; - float total = 0.0f; -- for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; -+ for (unsigned long long d = seen; d-- > 0;) total += w[seen - 1 - d] * values[((at - d) % cap) * kv_heads * dim + column]; - out[index] = total; - } - +@@ -258,7 +258,7 @@ extern "C" __global__ void attn_values(const float* weights, const float* values + const float* w = weights + run * stride; + unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; + for (unsigned long long d = seg; d < seen; d += segs) +- total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; ++ total += w[seen - 1 - d] * values[((at - d) % cap) * kv_heads * dim + column]; + } + // Every thread of the warp takes part in the shuffles, including those past the last element. + for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset); diff --git a/tools/mutants/85-fused-blend-scores-unscaled.patch b/tools/mutants/85-fused-blend-scores-unscaled.patch new file mode 100644 index 0000000..00e481b --- /dev/null +++ b/tools/mutants/85-fused-blend-scores-unscaled.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_blend_from_raw +# needs: gpu +# Bug: the fused blend's scores are not divided by the root of the width. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 6f6753d..5f769a8 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -182,7 +182,7 @@ extern "C" __global__ void blend_many( + } + float inverse = 1.0f / sqrtf(s / (float)width + blend_eps); + squares[j][0] = inverse; +- dots[j][0] = d * inverse * scale; ++ dots[j][0] = d * inverse; + best = fmaxf(best, dots[j][0]); + } + float sum = 0.0f; diff --git a/tools/mutants/88-softcap-cap-ignored.patch b/tools/mutants/88-softcap-cap-ignored.patch index 29bebb5..870add6 100644 --- a/tools/mutants/88-softcap-cap-ignored.patch +++ b/tools/mutants/88-softcap-cap-ignored.patch @@ -2,7 +2,7 @@ # needs: gpu # Bug: the soft cap on the device forgets the cap. diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu -index 0d40107..b0749fb 100644 +index 6f6753d..ed8eb38 100644 --- a/crates/dluth-cuda/kernels/small_ops.cu +++ b/crates/dluth-cuda/kernels/small_ops.cu @@ -61,7 +61,7 @@ extern "C" __global__ void gate_merge(const float* x, const float* message, cons @@ -13,4 +13,4 @@ index 0d40107..b0749fb 100644 + if (i < n) x[i] = tanhf(x[i]); } - // A whole blend across depth in one launch, one block of threads per position of a batch: + // Most candidates a blend takes in one launch (see blend_many). From ddaf147109b9a13782c6e52b0f71c7e0302e39f8 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:33:43 -0800 Subject: [PATCH 5/5] fix(cuda): the thread-sharing constant is checked at compile time; a test asserts what its comment says; review nits --- crates/dluth-cuda/src/attention.rs | 2 ++ crates/dluth-cuda/tests/inkling_golden_cuda.rs | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/dluth-cuda/src/attention.rs b/crates/dluth-cuda/src/attention.rs index 73b6dd3..aa698d0 100644 --- a/crates/dluth-cuda/src/attention.rs +++ b/crates/dluth-cuda/src/attention.rs @@ -37,6 +37,8 @@ pub const MAX_BATCH: usize = 16; /// Threads that share one element of attention's output, each summing every 16th token. const VALUE_SEGS: u32 = 16; +// The kernel combines them with warp shuffles, which need a power of two up to 32. +const _: () = assert!(VALUE_SEGS.is_power_of_two() && VALUE_SEGS <= 32); /// The shape of a layer's attention: query heads, key-value heads, and the size of a head. #[derive(Clone, Copy, Debug)] diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 2f70ccd..dd44fde 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -425,9 +425,11 @@ mod on_the_device { // Scores are sums of 32 products of values of size about 1. let worst = g.iter().zip(&w).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); assert!(worst < 2e-3, "{count} candidates, query {q}: scores differ by {worst}"); - // The two queries, and the three positions, give different scores. + // The three positions give different scores. assert!(w[..cfg.vocab_out] != w[cfg.vocab_out..2 * cfg.vocab_out]); } + // And so do the two queries. + assert!(cpu.scores(&cfg, unembed, &want[0]).unwrap() != cpu.scores(&cfg, unembed, &want[1]).unwrap()); } }