diff --git a/crates/dluth-cuda/Cargo.toml b/crates/dluth-cuda/Cargo.toml index 73feeb5..1836d40 100644 --- a/crates/dluth-cuda/Cargo.toml +++ b/crates/dluth-cuda/Cargo.toml @@ -16,10 +16,11 @@ workspace = true 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" } +# The CPU reference every GPU kernel is compared with in tests; the device model also uses +# its expert choice and the few scalar formulas that stay on the host. +dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" } [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" diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 190da1c..33c2400 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -1,15 +1,22 @@ //! 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] +//! cargo run --release -p dluth-cuda --example generate -- "" [max new tokens] [products] +//! +//! By default every value of the forward pass stays on the device. With `timed` as the +//! last word the device is waited for after every operation and the time per kind of +//! operation is printed (which makes the run itself slower). With `products` as the +//! last word only the matrix products run there and the rest on the CPU, as an earlier step +//! of the port did, with that step's own breakdown of a token's time. //! //! 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::ops::{CudaOps, TimedOps}; use dluth_cuda::{CudaDevice, Module}; use dluth_model::inkling::prompt::{single_turn, Effort}; -use dluth_model::inkling::{load_config, InklingCpu}; +use dluth_model::inkling::{load_config, Inkling, InklingCpu}; use dluth_model::tokenizer::Tokenizer; use dluth_model::weights::Weights; use std::path::PathBuf; @@ -29,6 +36,80 @@ fn main() { let dev = CudaDevice::open(0).expect("a CUDA device"); let module = Module::load_embedded(&dev).expect("the embedded kernels"); + let mode = args.next(); + if mode.as_deref() == Some("timed") { + let ops = TimedOps::new(CudaOps::new(&dev, &module).expect("the kernels")); + let spent = ops.spent(); + let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).expect("the model"); + let mut fed = 0usize; + let generated = model + .generate_greedy_with(&ids, max_new, eos, |_| { + // Start counting once the prompt is in and the weights are on the device. + if fed == 0 { + spent.borrow_mut().clear(); + } + fed += 1; + }) + .expect("generation"); + let decoded = generated.len().saturating_sub(1).max(1) as f64; + let mut rows = spent.borrow().clone(); + rows.sort_by_key(|row| std::cmp::Reverse(row.1)); + let total: f64 = rows.iter().map(|r| r.1.as_secs_f64()).sum(); + println!( + "per generated token, waiting for the device after every operation: {:.1} ms", + total * 1000.0 / decoded + ); + for (name, time, count) in rows { + println!( + " {name:<26} {:6.2} ms ({:.0} times)", + time.as_secs_f64() * 1000.0 / decoded, + count as f64 / decoded + ); + } + return; + } + if mode.as_deref() != Some("products") { + let ops = CudaOps::new(&dev, &module).expect("the kernels"); + let stats = ops.stats(); + let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).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(); + println!( + "prompt: {} tokens in {:.1} s (weights are copied to the device as they are first used)", + ids.len(), + (first - started).as_secs_f64() + ); + if decoded > 0 { + let total = *stats.borrow(); + println!( + "generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", + decoded as f64 / seconds + ); + println!( + "per generated token: {:.1} ms; {:.0} waits for the device, {:.0} copies in, {:.0} copies out", + seconds * 1000.0 / decoded as f64, + (total.waits - at_first.waits) as f64 / decoded as f64, + (total.copies_in - at_first.copies_in) as f64 / decoded as f64, + (total.copies_out - at_first.copies_out) as f64 / decoded as f64 + ); + } + return; + } + let products = CudaProducts::new(&dev, &module).expect("the product kernels"); let stats = products.stats(); let mut model = diff --git a/crates/dluth-cuda/examples/matmat_alloc.rs b/crates/dluth-cuda/examples/matmat_alloc.rs new file mode 100644 index 0000000..4355cec --- /dev/null +++ b/crates/dluth-cuda/examples/matmat_alloc.rs @@ -0,0 +1,92 @@ +//! Does it matter how a matrix got onto the device? Times the BF16 product on 48 matrices of +//! 3,072 by 2,304 laid out four ways. Run on an idle machine: +//! +//! cargo run --release -p dluth-cuda --example matmat_alloc +//! +//! GB of weights per second, median of five runs, one vector per product. + +use dluth_core::{Backend, Buffer}; +use dluth_cuda::matmat::{Bf16Matrix, Matmat}; +use dluth_cuda::probe::Probe; +use dluth_cuda::{CudaDevice, Module}; +use std::time::Instant; + +fn median_of_five(mut run: impl FnMut() -> f64) -> f64 { + let mut v: Vec = (0..5).map(|_| run()).collect(); + v.sort_by(f64::total_cmp); + v[2] +} + +fn main() { + let dev = CudaDevice::open(0).expect("a CUDA device"); + let module = Module::load_embedded(&dev).expect("the embedded kernels"); + let mm = Matmat::new(&dev, &module).expect("the matrix kernels"); + let probe = Probe::new(&dev, &module).expect("the probe kernels"); + let (count, rows, cols) = (48usize, 3072usize, 2304usize); + let one = rows * cols * 2; + let x = dev.alloc(cols * 4).expect("device memory"); + dev.upload(&x, &vec![0u8; cols * 4]).expect("upload"); + let y = dev.alloc(rows * 4).expect("device memory"); + let host: Vec = (0..one).map(|i| (i * 31 + 7) as u8).collect(); + + let time = |name: &str, matrices: &dyn Fn(usize) -> (Buffer, usize), wait_each: bool| { + let rate = median_of_five(|| { + dev.synchronize().expect("synchronize"); + let started = Instant::now(); + for i in 0..count { + let (buffer, offset) = matrices(i); + mm.bf16(Bf16Matrix { buffer: &buffer, offset, rows, cols }, &x, 1, &y, 16).expect("launch"); + if wait_each { + dev.synchronize().expect("synchronize"); + } + } + dev.synchronize().expect("synchronize"); + (count * one) as f64 / 1e9 / started.elapsed().as_secs_f64() + }); + println!(" {name:<64} {rate:7.1}"); + }; + + println!("48 matrices of {rows} by {cols} ({:.1} MB each), GB/s", one as f64 / 1e6); + let big = dev.alloc(count * one).expect("device memory"); + probe.fill(&big, (count * one / 4) as u64).expect("fill"); + time("one buffer, filled by a kernel", &|i| (big, i * one), false); + time("one buffer, filled by a kernel, waiting after each product", &|i| (big, i * one), true); + + let big_copied = dev.alloc(count * one).expect("device memory"); + let all: Vec = host.iter().cycle().take(count * one).copied().collect(); + dev.upload(&big_copied, &all).expect("upload"); + time("one buffer, copied from the host", &|i| (big_copied, i * one), false); + + let separate: Vec = (0..count) + .map(|_| { + let b = dev.alloc(one).expect("device memory"); + dev.upload(&b, &host).expect("upload"); + b + }) + .collect(); + time("a buffer per matrix, copied from the host", &|i| (separate[i], 0), false); + time("a buffer per matrix, copied from the host, waiting after each", &|i| (separate[i], 0), true); + + // The model's rhythm: light kernels between the products. Only the products are timed. + println!("the same products with light work in between, microseconds per product (median of five passes over 48)"); + for (light, pause_us) in [(0usize, 0u64), (20, 0), (200, 0), (0, 50), (0, 200), (0, 1000)] { + let micros = median_of_five(|| { + let mut total = 0.0; + for i in 0..count { + for _ in 0..light { + probe.launch_empty().expect("launch"); + } + dev.synchronize().expect("synchronize"); + if pause_us > 0 { + std::thread::sleep(std::time::Duration::from_micros(pause_us)); + } + let started = Instant::now(); + mm.bf16(Bf16Matrix { buffer: &big, offset: i * one, rows, cols }, &x, 1, &y, 16).expect("launch"); + dev.synchronize().expect("synchronize"); + total += started.elapsed().as_secs_f64(); + } + total * 1e6 / count as f64 + }); + println!(" {light:>4} empty kernels, then {pause_us:>5} us idle, before each product: {micros:7.1}"); + } +} diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu new file mode 100644 index 0000000..f60645f --- /dev/null +++ b/crates/dluth-cuda/kernels/attention.cu @@ -0,0 +1,194 @@ +// The attention sublayer's operations other than its matrix products, for one token. +// Each mirrors one function of the CPU reference in dluth-kernels and adds a row's +// products in the same order, so the two differ only where the device rounds a multiply +// and an add together. +// +// Keys and values of earlier tokens live on the device in a history of `cap` rows. The +// token at position p is in row p % cap. A layer that sees everything has cap at least +// the longest sequence; a layer with a window has cap equal to the window, so a row is +// overwritten exactly when its token leaves the window. + +// Each head's vector: multiplied element by element by `scale` (if not null), shortened +// to length `clip` if it is longer, then multiplied by `late`. One block of threads per +// head, a thread per few elements: a single thread walking a head of 128 took 25 +// microseconds, more than the matrix product that made the head. +// CPU reference: the scale loop, cpu::l2_clip_inplace and the late factor in the model's +// attention step. The squares are added in a different order. +extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigned int heads, + unsigned int dim, float clip, float late) { + __shared__ float part[256]; + unsigned int h = blockIdx.x; + if (h >= heads) return; + float* v = x + (size_t)h * dim; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { + float t = scale ? v[i] * scale[(size_t)h * dim + i] : v[i]; + v[i] = t; + squares += t * t; + } + part[threadIdx.x] = squares; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; + part[0] = fminf(clip / (sqrtf(squares) + 1e-6f), 1.0f); + } + __syncthreads(); + float factor = part[0]; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { + float t = v[i]; + if (factor < 1.0f) t *= factor; + v[i] = t * late; + } +} + +// Each head's vector divided by sqrt(mean of its squares + eps). One block of threads per +// head. CPU reference: cpu::rmsnorm_plain, once per head, with the squares added in a +// different order. +extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsigned int heads, + unsigned int dim, float eps) { + __shared__ float part[256]; + unsigned int h = blockIdx.x; + if (h >= heads) return; + const float* v = x + (size_t)h * dim; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) squares += v[i] * v[i]; + part[threadIdx.x] = squares; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; + part[0] = 1.0f / sqrtf(squares / (float)dim + eps); + } + __syncthreads(); + float scale = part[0]; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) out[(size_t)h * dim + i] = v[i] * scale; +} + +// The token `lag` steps before position `pos`, channel c, from a ring of the last n - 1 +// tokens; zero before the start of the sequence. +__device__ __forceinline__ float earlier_token(const float* ring, unsigned int channels, unsigned int n, + unsigned long long pos, unsigned int lag, unsigned int c) { + return pos >= lag ? ring[((pos - lag) % (n - 1)) * channels + c] : 0.0f; +} + +// Short convolution with fixed taps: taps[c * n + j] weighs the token n - 1 - j steps back. +// out[c] = (sum of taps times tokens + current[c]) * norm +// Then the current token takes its place in the ring. CPU reference: sconv::fixed. +extern "C" __global__ void sconv_fixed(const float* current, float* ring, const float* taps, float* out, + unsigned int channels, unsigned int n, unsigned long long pos, + float norm) { + unsigned int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + float x = current[c]; + const float* w = taps + (size_t)c * n; + float sum = w[n - 1] * x; + for (unsigned int j = 0; j + 1 < n; ++j) sum += w[j] * earlier_token(ring, channels, n, pos, n - 1 - j, c); + out[c] = (sum + x) * norm; + if (n > 1) ring[(pos % (n - 1)) * channels + c] = x; +} + +// Short convolution whose taps are a fixed part per channel plus a part computed for this +// token and shared by the channels of a head: fixed_taps[lag * channels + c] and +// token_taps[head * n + lag], lag 0 being the current token. CPU reference: sconv::dynamic. +extern "C" __global__ void sconv_dynamic(const float* current, float* ring, const float* fixed_taps, + const float* token_taps, float* out, unsigned int channels, + unsigned int n, unsigned int heads, unsigned long long pos, + float norm) { + unsigned int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + float x = current[c]; + const float* head_taps = token_taps + (size_t)(c / (channels / heads)) * n; + float sum = (fixed_taps[c] + head_taps[0]) * x; + for (unsigned int lag = 1; lag < n; ++lag) + sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) * earlier_token(ring, channels, n, pos, lag, c); + out[c] = (sum + x) * norm; + if (n > 1) ring[(pos % (n - 1)) * channels + c] = x; +} + +// Attention scores of one query token. For query head h and the token d steps back +// (d < seen): the dot product of the head's query and that token's key times `scale`, +// plus the relative-position term, sum over k of rel[h][k] * table[k][d], which is zero +// from distance `reach` on. weights[h * (seen + 1) + d] receives it; the last entry of a +// head, at d = seen, receives the head's sink score. +// CPU reference: the scoring loop of sinkattn::attend, with sinkattn::distance_profile. +extern "C" __global__ void attn_scores(const float* q, const float* keys, const float* rel, + const float* table, const float* sinks, float* weights, + unsigned int heads, unsigned int kv_heads, unsigned int dim, + unsigned int rel_dim, unsigned int reach, float scale, + unsigned long long pos, unsigned long long seen, + unsigned long long cap) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long h = index / (seen + 1); + unsigned long long d = index % (seen + 1); + if (h >= heads) return; + if (d == seen) { + weights[index] = sinks[h]; + return; + } + const float* key = keys + ((pos - d) % cap) * kv_heads * dim + (h / (heads / kv_heads)) * dim; + const float* query = q + h * dim; + float dot = 0.0f; + for (unsigned int i = 0; i < dim; ++i) dot += query[i] * key[i]; + float bias = 0.0f; + if (d < reach) + for (unsigned int k = 0; k < rel_dim; ++k) bias += rel[h * rel_dim + k] * table[(size_t)k * reach + d]; + weights[index] = dot * scale + bias; +} + +// Softmax over each head's `count` scores, in place: one block of threads per head. +// CPU reference: cpu::softmax_inplace. The sum is added in a different order. +extern "C" __global__ void attn_softmax(float* weights, unsigned int heads, unsigned long long count) { + __shared__ float part[1024]; + unsigned int h = blockIdx.x; + if (h >= heads) return; + float* w = weights + (unsigned long long)h * count; + float best = -INFINITY; + for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) best = fmaxf(best, w[i]); + part[threadIdx.x] = best; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) best = fmaxf(best, part[t]); + part[0] = best; + } + __syncthreads(); + best = part[0]; + __syncthreads(); + float sum = 0.0f; + for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) { + float e = expf(w[i] - best); + w[i] = e; + sum += e; + } + part[threadIdx.x] = sum; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) sum += part[t]; + part[0] = sum; + } + __syncthreads(); + sum = part[0]; + for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) w[i] /= sum; +} + +// The weighted sum of the values: out[h][e] = sum over the seen tokens, oldest first, of +// the token's weight times its value. The sink has no value. +// CPU reference: the summing loop of sinkattn::attend. +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 seen, + unsigned long long cap) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long h = index / dim; + unsigned int e = (unsigned int)(index % dim); + if (h >= heads) return; + const float* w = weights + h * (seen + 1); + unsigned long long at = (h / (heads / kv_heads)) * dim + e; + float total = 0.0f; + for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((pos - d) % cap) * kv_heads * dim + at]; + out[index] = total; +} + +// x[i] *= sigmoid(gate[i]). CPU reference: cpu::sigmoid. +extern "C" __global__ void sigmoid_mul(float* x, const float* gate, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] *= 1.0f / (1.0f + expf(-gate[i])); +} diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu new file mode 100644 index 0000000..25e169f --- /dev/null +++ b/crates/dluth-cuda/kernels/small_ops.cu @@ -0,0 +1,127 @@ +// Small operations on whole vectors. None reads many bytes; they exist so that a token's +// values can stay on the device from one matrix product to the next. + +// out[i] = a[i] + b[i]. +extern "C" __global__ void vec_add(const float* a, const float* b, float* out, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = a[i] + b[i]; +} + +// Root-mean-square normalization with learned weights, one block of threads: +// out[i] = x[i] / sqrt(mean(x^2) + eps) * w[i] +// CPU reference: cpu::rmsnorm. The squares are added in a different order. +extern "C" __global__ void rmsnorm_weighted(const float* x, const float* w, float* out, unsigned int n, + float eps) { + __shared__ float part[1024]; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) squares += x[i] * x[i]; + part[threadIdx.x] = squares; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; + part[0] = squares; + } + __syncthreads(); + float scale = 1.0f / sqrtf(part[0] / (float)n + eps); + for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) out[i] = x[i] * scale * w[i]; +} + +// Scores for a blend across depth: for each of `count` candidates of `width` floats, one +// after another in `candidates`, scores[j] = (query . candidate_j) * scale. One block of +// threads per candidate. CPU reference: the scoring in depthmix::mix_normalized. +extern "C" __global__ void blend_scores(const float* query, const float* candidates, float* scores, + unsigned int count, unsigned int width, float scale) { + __shared__ float part[1024]; + unsigned int j = blockIdx.x; + if (j >= count) return; + const float* c = candidates + (size_t)j * width; + float dot = 0.0f; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) dot += query[i] * c[i]; + part[threadIdx.x] = dot; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) dot += part[t]; + scores[j] = dot * scale; + } +} + +// The gate that merges a message from the previous pass into a sublayer input: +// out[i] = (1 - tanh(forget[i])) * x[i] + tanh(gain[i]) * message[i] +// CPU reference: the last step of the model's merge. +extern "C" __global__ void gate_merge(const float* x, const float* message, const float* forget, + const float* gain, float* out, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = (1.0f - tanhf(forget[i])) * x[i] + tanhf(gain[i]) * message[i]; +} + +// x[i] = cap * tanh(x[i] / cap), in place. CPU reference: cpu::softcap. +extern "C" __global__ void softcap_inplace(float* x, unsigned int n, float cap) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = cap * tanhf(x[i] / cap); +} + +// A whole blend across depth in one launch, by one block of threads: +// score_j = (query . candidate_j) * scale; weights = softmax(scores); +// out = sum over j of weights_j * candidate_j +// for `count` candidates of `width` floats, one after another in `candidates`. +// One launch here replaces three (scores, softmax, weighted sum); a token makes about two +// hundred blends. CPU reference: depthmix::mix_normalized. +#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) { + __shared__ float part[BLEND_MAX][256]; + __shared__ float weight[BLEND_MAX]; + 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 * candidates[(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] * candidates[(size_t)j * width + i]; + out[i] = total; + } +} + +// Up to eight vectors, each wherever it lives, normalized into one buffer in one launch: +// out[j][i] = x_j[i] / sqrt(mean(x_j^2) + eps) +// One block of threads per vector. CPU reference: cpu::rmsnorm_plain, once per vector. +extern "C" __global__ void normalize_many(const float* x0, const float* x1, const float* x2, const float* x3, + const float* x4, const float* x5, const float* x6, const float* x7, + float* out, unsigned int count, unsigned int width, float eps) { + __shared__ float part[1024]; + unsigned int j = blockIdx.x; + if (j >= count) return; + const float* all[8] = {x0, x1, x2, x3, x4, x5, x6, x7}; + const float* x = all[j]; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) squares += x[i] * x[i]; + part[threadIdx.x] = squares; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; + part[0] = squares; + } + __syncthreads(); + float scale = 1.0f / sqrtf(part[0] / (float)width + eps); + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) out[(size_t)j * width + i] = x[i] * scale; +} diff --git a/crates/dluth-cuda/src/attention.rs b/crates/dluth-cuda/src/attention.rs new file mode 100644 index 0000000..d452484 --- /dev/null +++ b/crates/dluth-cuda/src/attention.rs @@ -0,0 +1,397 @@ +//! The attention sublayer's operations other than its matrix products, on the device. +//! +//! Every function starts its kernel and returns without waiting. Each checks that +//! everything the kernel will read or write lies inside the buffers it was given. + +use crate::device::CudaDevice; +use crate::error::CudaError; +use crate::floats::Floats; +use crate::module::{Kernel, Module}; +use std::ffi::c_void; + +fn refuse(what: &str, why: String) -> Result { + Err(CudaError::Refused(format!("{what}: {why}"))) +} + +fn blocks(threads: u64, per_block: u32) -> Result { + u32::try_from(threads.div_ceil(per_block as u64)) + .map_err(|_| CudaError::Refused(format!("a grid of {threads} threads is too large"))) +} + +fn ptr(p: &mut u64) -> *mut c_void { + p as *mut u64 as *mut c_void +} +fn num(p: &mut u32) -> *mut c_void { + p as *mut u32 as *mut c_void +} +fn big(p: &mut u64) -> *mut c_void { + p as *mut u64 as *mut c_void +} +fn real(p: &mut f32) -> *mut c_void { + p as *mut f32 as *mut c_void +} + +/// 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 { + pub heads: usize, + pub kv_heads: usize, + pub dim: usize, +} + +/// The keys and values of the tokens a layer pass can still see: two buffers of `cap` rows +/// of `kv_heads * dim` floats. The token at position p is in row `p % cap`. +#[derive(Clone, Copy, Debug)] +pub struct History<'b> { + pub keys: Floats<'b>, + pub values: Floats<'b>, + pub cap: usize, +} + +/// The relative-position term: one vector of `rel_dim` per query head, and a table of +/// `rel_dim` rows of `reach` columns, one column per distance. +#[derive(Clone, Copy, Debug)] +pub struct Relative<'b> { + pub rel: Floats<'b>, + pub table: Floats<'b>, + pub rel_dim: usize, + pub reach: usize, +} + +/// The attention kernels of a loaded module. +pub struct Attention<'m> { + dev: &'m CudaDevice, + scale_clip: Kernel<'m>, + rmsnorm_plain: Kernel<'m>, + sconv_fixed: Kernel<'m>, + sconv_dynamic: Kernel<'m>, + scores: Kernel<'m>, + softmax: Kernel<'m>, + values: Kernel<'m>, + sigmoid_mul: Kernel<'m>, +} + +impl<'m> Attention<'m> { + pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { + Ok(Attention { + dev, + scale_clip: module.kernel("head_scale_clip")?, + rmsnorm_plain: module.kernel("head_rmsnorm_plain")?, + sconv_fixed: module.kernel("sconv_fixed")?, + sconv_dynamic: module.kernel("sconv_dynamic")?, + scores: module.kernel("attn_scores")?, + softmax: module.kernel("attn_softmax")?, + values: module.kernel("attn_values")?, + sigmoid_mul: module.kernel("sigmoid_mul")?, + }) + } + + /// In place, for each of `heads` vectors of `dim` in `x`: multiply by `scale` element by + /// element (if given), shorten to length `clip` if longer, multiply by `late`. + pub fn head_scale_clip( + &self, + x: Floats, + scale: Option, + heads: usize, + dim: usize, + clip: f32, + late: f32, + ) -> Result<(), CudaError> { + let what = "head_scale_clip"; + if heads == 0 || dim == 0 || heads > 1 << 20 || dim > 1 << 20 { + return refuse(what, format!("{heads} heads of {dim}")); + } + // A value that is not a number is not finite, so it is refused here too. + if clip <= 0.0 || !clip.is_finite() || !late.is_finite() { + return refuse(what, format!("a clip of {clip} and a factor of {late}")); + } + x.check(self.dev, what, heads * dim)?; + if let Some(s) = &scale { + s.check(self.dev, what, heads * dim)?; + if s.overlaps(&x) { + return refuse(what, "the scale overlaps the vectors".into()); + } + } + let (mut px, mut ps) = (x.address(), scale.map_or(0, |s| s.address())); + let (mut h, mut d, mut c, mut l) = (heads as u32, dim as u32, clip, late); + let mut args = [ptr(&mut px), ptr(&mut ps), num(&mut h), num(&mut d), real(&mut c), real(&mut l)]; + // SAFETY: the arguments match head_scale_clip(float*, const float*, unsigned, + // unsigned, float, float). The kernel reads and writes heads * dim floats of `x` + // and reads as many of `scale` unless it is null; both were checked. + // One block per head, of 128 threads: within the kernel's shared array of 256. + unsafe { self.scale_clip.launch((heads as u32, 1, 1), (128, 1, 1), &mut args) } + } + + /// For each of `heads` vectors of `dim` in `x`: `out = x / sqrt(mean(x^2) + eps)`. + pub fn head_rmsnorm_plain( + &self, + x: Floats, + out: Floats, + heads: usize, + dim: usize, + eps: f32, + ) -> Result<(), CudaError> { + let what = "head_rmsnorm_plain"; + if heads == 0 || dim == 0 || heads > 1 << 20 || dim > 1 << 20 || eps < 0.0 || !eps.is_finite() { + return refuse(what, format!("{heads} heads of {dim}, eps {eps}")); + } + x.check(self.dev, what, heads * dim)?; + out.check(self.dev, what, heads * dim)?; + if x.overlaps(&out) { + return refuse(what, "the output overlaps the input".into()); + } + let (mut px, mut po, mut h, mut d, mut e) = (x.address(), out.address(), heads as u32, dim as u32, eps); + let mut args = [ptr(&mut px), ptr(&mut po), num(&mut h), num(&mut d), real(&mut e)]; + // SAFETY: the arguments match head_rmsnorm_plain(const float*, float*, unsigned, + // unsigned, float); it reads heads * dim floats of `x` and writes as many to `out`. + // One block per head, of 128 threads: within the kernel's shared array of 256. + unsafe { self.rmsnorm_plain.launch((heads as u32, 1, 1), (128, 1, 1), &mut args) } + } + + /// The short convolution of the token at `pos` with fixed taps (`channels * n` of them), + /// written to `out`; the token then takes its place in `ring`, which holds the last + /// `n - 1` tokens of `channels` floats. Tokens must be given in order of position. + pub fn sconv_fixed( + &self, + current: Floats, + ring: Floats, + taps: Floats, + out: Floats, + n: usize, + pos: usize, + ) -> Result<(), CudaError> { + let what = "sconv_fixed"; + let channels = current.len; + self.conv_checks(what, current, ring, out, n)?; + taps.check(self.dev, what, channels * n)?; + let (mut pc, mut pr, mut pt, mut po) = (current.address(), ring.address(), taps.address(), out.address()); + let (mut c, mut taps_n, mut p, mut norm) = + (channels as u32, n as u32, pos as u64, 1.0 / ((n + 1) as f32).sqrt()); + let mut args = [ + ptr(&mut pc), + ptr(&mut pr), + ptr(&mut pt), + ptr(&mut po), + num(&mut c), + num(&mut taps_n), + big(&mut p), + real(&mut norm), + ]; + // SAFETY: the arguments match sconv_fixed(const float*, float*, const float*, float*, + // unsigned, unsigned, unsigned long long, float). It reads `channels` floats of + // `current`, channels * n of `taps`, reads and writes (n - 1) * channels of `ring` + // and writes `channels` to `out`; all checked, and `out` overlaps none of them. + unsafe { self.sconv_fixed.launch((blocks(channels as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } + + /// The short convolution whose taps are `fixed_taps` (`n * channels`) plus `token_taps` + /// (`heads * n`, computed for this token and shared by the channels of a head). + #[allow(clippy::too_many_arguments)] + pub fn sconv_dynamic( + &self, + current: Floats, + ring: Floats, + fixed_taps: Floats, + token_taps: Floats, + out: Floats, + n: usize, + heads: usize, + pos: usize, + ) -> Result<(), CudaError> { + let what = "sconv_dynamic"; + let channels = current.len; + self.conv_checks(what, current, ring, out, n)?; + if heads == 0 || !channels.is_multiple_of(heads) { + return refuse(what, format!("{channels} channels in {heads} heads")); + } + fixed_taps.check(self.dev, what, channels * n)?; + token_taps.check(self.dev, what, heads * n)?; + if token_taps.overlaps(&out) || token_taps.overlaps(&ring) { + return refuse(what, "the token taps overlap something written".into()); + } + let (mut pc, mut pr, mut pf, mut pt, mut po) = + (current.address(), ring.address(), fixed_taps.address(), token_taps.address(), out.address()); + let (mut c, mut taps_n, mut h, mut p) = (channels as u32, n as u32, heads as u32, pos as u64); + let mut norm = 1.0 / ((2 * n + 1) as f32).sqrt(); + let mut args = [ + ptr(&mut pc), + ptr(&mut pr), + ptr(&mut pf), + ptr(&mut pt), + ptr(&mut po), + num(&mut c), + num(&mut taps_n), + num(&mut h), + big(&mut p), + real(&mut norm), + ]; + // SAFETY: the arguments match sconv_dynamic(const float*, float*, const float*, + // const float*, float*, unsigned, unsigned, unsigned, unsigned long long, float). + // Extents as for sconv_fixed, plus heads * n floats of `token_taps`; all checked. + unsafe { self.sconv_dynamic.launch((blocks(channels as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } + + fn conv_checks(&self, what: &str, current: Floats, ring: Floats, out: Floats, n: usize) -> Result<(), CudaError> { + let channels = current.len; + if n == 0 || n > 64 || channels == 0 || channels > 1 << 24 { + return refuse(what, format!("{n} taps for {channels} channels")); + } + current.check(self.dev, what, channels)?; + out.check(self.dev, what, channels)?; + if n > 1 { + ring.check(self.dev, what, (n - 1) * channels)?; + if ring.overlaps(¤t) || ring.overlaps(&out) { + return refuse(what, "the ring overlaps the token or the output".into()); + } + } + if out.overlaps(¤t) { + return refuse(what, "the output overlaps the token".into()); + } + Ok(()) + } + + /// Attention for the query token at position `pos`, whose own key and value are already + /// in the history: `out[h] = sum over the seen tokens of weight * value`, the weights + /// being a softmax over the seen tokens' scores and the head's sink score. + /// + /// `seen` is how many tokens, the newest included, the query may look at: at most + /// `pos + 1` and at most `history.cap`. `weights` is scratch of `heads * (seen + 1)`. + #[allow(clippy::too_many_arguments)] + pub fn attend( + &self, + shape: Heads, + q: Floats, + history: History, + relative: Relative, + sinks: Floats, + weights: Floats, + out: Floats, + pos: usize, + seen: usize, + ) -> Result<(), CudaError> { + let what = "attend"; + let Heads { heads, kv_heads, dim } = shape; + let Relative { rel, table, rel_dim, reach } = relative; + if heads == 0 + || kv_heads == 0 + || dim == 0 + || !heads.is_multiple_of(kv_heads) + || heads > 1 << 16 + || dim > 1 << 16 + { + return refuse(what, format!("{heads} heads over {kv_heads} key-value heads of {dim}")); + } + if rel_dim == 0 || reach == 0 || rel_dim > 1 << 16 || reach > u32::MAX as usize { + return refuse(what, format!("a relative-position table of {rel_dim} by {reach}")); + } + if seen == 0 || seen > history.cap || seen - 1 > pos { + return refuse(what, format!("{seen} tokens seen at position {pos} with a history of {}", history.cap)); + } + let width = kv_heads * dim; + q.check(self.dev, what, heads * dim)?; + out.check(self.dev, what, heads * dim)?; + history.keys.check(self.dev, what, history.cap * width)?; + history.values.check(self.dev, what, history.cap * width)?; + rel.check(self.dev, what, heads * rel_dim)?; + table.check(self.dev, what, rel_dim * reach)?; + sinks.check(self.dev, what, heads)?; + weights.check(self.dev, what, heads * (seen + 1))?; + for read in [&q, &history.keys, &history.values, &rel, &table, &sinks] { + if weights.overlaps(read) || out.overlaps(read) { + return refuse(what, "the scratch or the output overlaps an input".into()); + } + } + if weights.overlaps(&out) { + return refuse(what, "the scratch overlaps the output".into()); + } + + let (mut pq, mut pk, mut pv, mut pr, mut pt, mut ps, mut pw, mut po) = ( + q.address(), + history.keys.address(), + history.values.address(), + rel.address(), + table.address(), + sinks.address(), + weights.address(), + out.address(), + ); + let (mut h, mut kv, mut d, mut rd, mut rc) = + (heads as u32, kv_heads as u32, dim as u32, rel_dim as u32, reach as u32); + let (mut p, mut n, mut cap, mut count) = (pos as u64, seen as u64, history.cap as u64, seen as u64 + 1); + let mut scale = 1.0 / (dim as f32).sqrt(); + + let mut args = [ + ptr(&mut pq), + ptr(&mut pk), + ptr(&mut pr), + ptr(&mut pt), + ptr(&mut ps), + ptr(&mut pw), + num(&mut h), + num(&mut kv), + num(&mut d), + num(&mut rd), + num(&mut rc), + real(&mut scale), + big(&mut p), + big(&mut n), + big(&mut cap), + ]; + // SAFETY (the three launches): each argument list matches its kernel's parameters in + // order and type. attn_scores reads the query, `seen` rows of the keys (rows + // (pos - d) % cap for d < seen, all below cap), the relative vectors, columns below + // `reach` of the table and the sinks, and writes heads * (seen + 1) weights. + // attn_softmax rewrites those weights in place, one block of at most 1024 threads + // per head. attn_values reads them and `seen` rows of the values and writes + // heads * dim floats to `out`. Every extent was checked above, and nothing written + // overlaps anything read. + unsafe { self.scores.launch((blocks(heads as u64 * count, 256)?, 1, 1), (256, 1, 1), &mut args)? }; + let mut args = [ptr(&mut pw), num(&mut h), big(&mut count)]; + unsafe { self.softmax.launch((heads as u32, 1, 1), (256, 1, 1), &mut args)? }; + let mut args = [ + ptr(&mut pw), + ptr(&mut pv), + ptr(&mut po), + num(&mut h), + num(&mut kv), + num(&mut d), + big(&mut p), + big(&mut n), + big(&mut cap), + ]; + unsafe { self.values.launch((blocks((heads * dim) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } + + /// Softmax in place over each of `heads` runs of `count` scores in `weights`. + pub fn softmax(&self, weights: Floats, heads: usize, count: usize) -> Result<(), CudaError> { + let what = "attn_softmax"; + if heads == 0 || count == 0 || heads > 1 << 16 { + return refuse(what, format!("{heads} runs of {count}")); + } + weights.check(self.dev, what, heads * count)?; + let (mut pw, mut h, mut n) = (weights.address(), heads as u32, count as u64); + let mut args = [ptr(&mut pw), num(&mut h), big(&mut n)]; + // SAFETY: the arguments match attn_softmax(float*, unsigned, unsigned long long); + // one block of 256 threads per run reads and writes that run's `count` floats. + unsafe { self.softmax.launch((heads as u32, 1, 1), (256, 1, 1), &mut args) } + } + + /// In place: `x[i] *= sigmoid(gate[i])`. + pub fn sigmoid_mul(&self, x: Floats, gate: Floats) -> Result<(), CudaError> { + let what = "sigmoid_mul"; + let n = x.len; + if n > u32::MAX as usize { + return refuse(what, format!("{n} values")); + } + x.check(self.dev, what, n)?; + gate.check(self.dev, what, n)?; + if x.overlaps(&gate) { + return refuse(what, "the gate overlaps the values".into()); + } + let (mut px, mut pg, mut count) = (x.address(), gate.address(), n as u32); + let mut args = [ptr(&mut px), ptr(&mut pg), num(&mut count)]; + // SAFETY: the arguments match sigmoid_mul(float*, const float*, unsigned); it reads + // and writes n floats of `x` and reads n of `gate`. + unsafe { self.sigmoid_mul.launch((blocks(n as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } +} diff --git a/crates/dluth-cuda/src/device.rs b/crates/dluth-cuda/src/device.rs index 64892e4..d46e84d 100644 --- a/crates/dluth-cuda/src/device.rs +++ b/crates/dluth-cuda/src/device.rs @@ -63,6 +63,11 @@ impl CudaDevice { self.capability } + /// How many buffers this device has handed out and not been given back. + pub fn live_buffers(&self) -> usize { + self.live.borrow().len() + } + /// Refuses to go on if kernels built for `built_for` would run on a different architecture. /// A cubin holds machine code for exactly one, so this is checked before any kernel loads. pub fn preflight(&self, built_for: (u32, u32)) -> Result<(), CudaError> { diff --git a/crates/dluth-cuda/src/floats.rs b/crates/dluth-cuda/src/floats.rs new file mode 100644 index 0000000..f2af4e8 --- /dev/null +++ b/crates/dluth-cuda/src/floats.rs @@ -0,0 +1,42 @@ +//! A run of floats inside a device buffer. + +use crate::device::CudaDevice; +use crate::error::CudaError; +use dluth_core::Buffer; + +/// `len` floats starting `at` floats into `buffer`. +#[derive(Clone, Copy, Debug)] +pub struct Floats<'b> { + pub buffer: &'b Buffer, + pub at: usize, + pub len: usize, +} + +impl<'b> Floats<'b> { + /// The first `len` floats of `buffer`. + pub fn first(buffer: &'b Buffer, len: usize) -> Self { + Floats { buffer, at: 0, len } + } + + /// The device address of the first float. + pub(crate) fn address(&self) -> u64 { + self.buffer.handle + self.at as u64 * 4 + } + + /// Refuses a run that is empty, not `len` floats long, or not inside its buffer. + pub(crate) fn check(&self, dev: &CudaDevice, what: &str, len: usize) -> Result<(), CudaError> { + let have = dev.size_of(self.buffer).map_err(|e| CudaError::Refused(e.to_string()))?; + if self.len != len || len == 0 || self.at > have / 4 || len > have / 4 - self.at { + return Err(CudaError::Refused(format!( + "{what}: {} floats at float {} of a buffer of {have} bytes, where {len} are needed", + self.len, self.at + ))); + } + Ok(()) + } + + /// Whether two runs share any float. + pub(crate) fn overlaps(&self, other: &Floats) -> bool { + self.buffer.handle == other.buffer.handle && self.at < other.at + other.len && other.at < self.at + self.len + } +} diff --git a/crates/dluth-cuda/src/lib.rs b/crates/dluth-cuda/src/lib.rs index efb6054..1052b45 100644 --- a/crates/dluth-cuda/src/lib.rs +++ b/crates/dluth-cuda/src/lib.rs @@ -7,15 +7,19 @@ //! //! The declarations for the driver API are generated at build time from NVIDIA's `cuda.h`. +pub mod attention; pub mod blockmat; mod device; mod error; pub mod expert_ops; +pub mod floats; mod image; pub mod inkling; pub mod matmat; mod module; +pub mod ops; pub mod probe; +pub mod small; /// Generated declarations for the CUDA driver API. Not part of the public interface. #[allow(non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code, clippy::all)] diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs new file mode 100644 index 0000000..2478759 --- /dev/null +++ b/crates/dluth-cuda/src/ops.rs @@ -0,0 +1,850 @@ +//! The Inkling model's operations with every value on the device. +//! +//! `CudaOps` implements the model crate's `Ops` trait. The forward pass stays the one +//! written and checked on the CPU; here each of its operations is a few kernel launches on +//! vectors that never leave the device. A token waits for the device for three reasons: +//! once to copy its embedding in, once per layer pass to read back the 128 router scores +//! from which the experts are chosen on the host, and once to read back the scores of the +//! vocabulary. That is two waits plus one per layer pass, 50 for the released model. +//! +//! Order matters for safety. Kernels are started without waiting and run in the order they +//! were started. A buffer may be handed to a later kernel as its output while an earlier +//! kernel still has to read it, because the earlier one runs first. What must not happen +//! is the host writing into a buffer that a kernel not yet run will read. Every copy from +//! the host therefore comes right after a wait for the device, or goes to a buffer that no +//! kernel has been given yet. A copy itself blocks until it is done (the driver's host +//! copies are synchronous), so the host bytes it reads may be reused as soon as it returns. + +use crate::attention::{Attention, Heads, History, Relative}; +use crate::blockmat::{BlockFormat, BlockMat, BlockMatrices, Job, JOB_BYTES}; +use crate::device::CudaDevice; +use crate::error::CudaError; +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 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}; +use dluth_model::ModelError; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +/// 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()) +} + +/// Device buffers that are free to be used again, by size. +#[derive(Default)] +struct Pool { + free: HashMap>, +} + +struct Slot { + buffer: Buffer, + len: usize, + pool: Rc>, +} + +impl Drop for Slot { + fn drop(&mut self) { + // Back to the pool, not to the device: a kernel that has not run yet may still read + // it, and whoever takes it next can only be a kernel started later or a copy made + // after a wait. + self.pool.borrow_mut().free.entry(self.buffer.bytes).or_default().push(self.buffer); + } +} + +/// A vector of floats on the device. Cloning it shares the same floats; they are never +/// changed once the operation that made them has been started. +#[derive(Clone)] +pub struct DeviceVec(Rc); + +impl DeviceVec { + pub fn len(&self) -> usize { + self.0.len + } + + pub fn is_empty(&self) -> bool { + self.0.len == 0 + } + + fn all(&self) -> Floats<'_> { + Floats::first(&self.0.buffer, self.0.len) + } + + fn part(&self, at: usize, len: usize) -> Floats<'_> { + // The buffer may be larger than the vector; a run must stay inside the vector. + assert!(at + len <= self.0.len, "a run of {len} at {at} in a device vector of {}", self.0.len); + Floats { buffer: &self.0.buffer, at, len } + } +} + +/// Candidates normalized for blending: `count` vectors of `width`, one after another. +pub struct DeviceBlend { + data: DeviceVec, + count: usize, + width: usize, +} + +/// What one application of a layer remembers between tokens, on the device. +pub struct DevicePass { + keys: Buffer, + values: Buffer, + /// Rows in `keys` and `values`. The token at position p is in row `p % cap`. + cap: usize, + /// How many tokens, the newest included, a query may look at; none for a layer that + /// sees everything. + window: Option, + k_ring: Buffer, + v_ring: Buffer, + attn_ring: Buffer, + expert_ring: Buffer, + /// The position of the token being computed, set by the attention step, which comes + /// first in a layer; the two convolutions after it read it. + pos: usize, + /// The longest sequence this pass has room for. + max_seq: usize, + /// Where the buffers go when the pass is dropped: a list the operations that made the + /// pass free on the device when they are dropped in turn. + returned: Rc>>, +} + +impl Drop for DevicePass { + fn drop(&mut self) { + // Not freed here: a kernel that has not run yet may still read them. The operations + // free them, after everything they started has finished. + let buffers = [self.keys, self.values, self.k_ring, self.v_ring, self.attn_ring, self.expert_ring]; + self.returned.borrow_mut().extend(buffers); + } +} + +/// How often the device was waited for, and how many kernels were started. +#[derive(Clone, Copy, Debug, Default)] +pub struct OpsStats { + pub waits: usize, + pub copies_in: usize, + pub copies_out: usize, +} + +/// The operations of an Inkling forward pass on a CUDA device. +pub struct CudaOps<'m> { + dev: &'m CudaDevice, + matmat: Matmat<'m>, + blockmat: BlockMat<'m>, + expert_ops: ExpertOps<'m>, + attention: Attention<'m>, + small: Small<'m>, + /// Weight matrices already on the device, by where their bytes start in the weight + /// file's mapping. + weights: HashMap, + /// Small float parameters (norm weights, queries, taps, tables) already on the device, + /// by where their floats start in the model's memory. + params: HashMap, + weight_bytes: usize, + /// A run of ones, for normalizing a whole vector without learned weights. + ones: Option, + pool: Rc>, + /// Buffers of dropped passes, and others no longer needed, to be freed on the device + /// when these operations are dropped. + returned: Rc>>, + /// The chosen experts' weights and the two job lists of the expert step. + route: Option, + jobs: [Option; 2], + staging: Vec, + stats: Rc>, +} + +impl<'m> CudaOps<'m> { + pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { + Ok(CudaOps { + dev, + matmat: Matmat::new(dev, module)?, + blockmat: BlockMat::new(dev, module)?, + expert_ops: ExpertOps::new(dev, module)?, + attention: Attention::new(dev, module)?, + small: Small::new(dev, module)?, + weights: HashMap::new(), + params: HashMap::new(), + weight_bytes: 0, + ones: None, + pool: Rc::default(), + returned: Rc::default(), + route: None, + jobs: [None, None], + staging: Vec::new(), + stats: Rc::default(), + }) + } + + /// A handle on the running totals, readable after the operations have gone into 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 + } + + /// A vector of `len` floats, contents unspecified, from the pool or freshly made. + fn vec(&self, len: usize) -> Result { + if len == 0 { + return Err(ModelError::Device("an empty device vector".into())); + } + // Sizes are rounded up to a power of two, so that the pool has a few dozen sizes at + // most. (Attention's scratch grows by a few floats with every position; exact sizes + // would leave one buffer per position behind.) + let bytes = (len * 4).next_power_of_two().max(256); + let reused = self.pool.borrow_mut().free.get_mut(&bytes).and_then(Vec::pop); + let buffer = match reused { + Some(buffer) => buffer, + None => self.dev.alloc(bytes).map_err(failed)?, + }; + Ok(DeviceVec(Rc::new(Slot { buffer, len, pool: self.pool.clone() }))) + } + + fn wait(&self) -> Result<(), ModelError> { + self.stats.borrow_mut().waits += 1; + self.dev.synchronize().map_err(failed) + } + + /// Copies floats from the host into `buffer`. The caller has just waited for the + /// device, or `buffer` has never been given to a kernel. + fn copy_in(&mut self, buffer: &Buffer, values: &[f32]) -> Result<(), ModelError> { + self.staging.clear(); + self.staging.extend(values.iter().flat_map(|v| v.to_le_bytes())); + self.stats.borrow_mut().copies_in += 1; + self.dev.upload(buffer, &self.staging).map_err(failed) + } + + /// A vector on the device holding `values`. Waits for the device first. + fn send(&mut self, values: &[f32]) -> Result { + let v = self.vec(values.len())?; + self.wait()?; + self.copy_in(&v.0.buffer, values)?; + Ok(v) + } + + /// Waits for the device and copies a vector's floats to the host. + fn fetch(&mut self, v: &DeviceVec) -> Result, ModelError> { + self.wait()?; + self.staging.clear(); + self.staging.resize(v.len() * 4, 0); + self.stats.borrow_mut().copies_out += 1; + self.dev.download(&v.0.buffer, &mut self.staging).map_err(failed)?; + Ok(self.staging.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()) + } + + /// The device copy of a weight matrix, 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 weight(&mut self, bytes: &[u8]) -> Result { + let key = bytes.as_ptr() as usize; + if let Some(&buffer) = self.weights.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); + } + // A fresh buffer that no kernel has been given: safe to fill without waiting. + let buffer = self.dev.alloc(bytes.len()).map_err(failed)?; + self.dev.upload(&buffer, bytes).map_err(failed)?; + self.weights.insert(key, buffer); + self.weight_bytes += bytes.len(); + Ok(buffer) + } + + /// Several weight matrices with the same number of columns, one after another in one + /// device buffer, made on first use and recognised by where the first one starts. One + /// product with the stacked matrix gives all their products at once. + fn stacked(&mut self, parts: &[&[u8]], each: usize) -> Result { + if parts.is_empty() || parts.iter().any(|p| p.len() != each) { + return Err(ModelError::Device(format!( + "{} stacked matrices of {:?} bytes, where each should have {each}", + parts.len(), + parts.iter().map(|p| p.len()).collect::>() + ))); + } + let key = parts[0].as_ptr() as usize; + let bytes: usize = parts.iter().map(|p| p.len()).sum(); + if let Some(&buffer) = self.weights.get(&key) { + if buffer.bytes != bytes { + return Err(ModelError::Device(format!( + "stacked weights of {bytes} bytes were first used with {} bytes", + buffer.bytes + ))); + } + return Ok(buffer); + } + let joined: Vec = parts.iter().flat_map(|p| p.iter().copied()).collect(); + // A fresh buffer that no kernel has been given: safe to fill without waiting. + let buffer = self.dev.alloc(bytes).map_err(failed)?; + self.dev.upload(&buffer, &joined).map_err(failed)?; + self.weights.insert(key, buffer); + self.weight_bytes += bytes; + Ok(buffer) + } + + /// The device copy of a small float parameter of the model, made on first use. + fn param(&mut self, values: &[f32]) -> Result { + let key = values.as_ptr() as usize; + if let Some(&buffer) = self.params.get(&key) { + if buffer.bytes != values.len() * 4 { + return Err(ModelError::Device(format!( + "a parameter of {} floats was first used with {} bytes", + values.len(), + buffer.bytes + ))); + } + return Ok(buffer); + } + let buffer = self.dev.alloc(values.len() * 4).map_err(failed)?; + self.copy_in(&buffer, values)?; + self.params.insert(key, buffer); + Ok(buffer) + } + + /// `out = x / sqrt(mean(x^2) + eps)` for a whole vector, by one block of 256 threads. + fn rmsnorm_plain(&mut self, x: Floats, out: Floats, eps: f32) -> Result<(), ModelError> { + let n = x.len; + let ones = match self.ones { + Some(b) if b.bytes >= n * 4 => b, + _ => { + // A fresh buffer that no kernel has been given. The old one, if any, stays + // allocated: a kernel not yet run may still read it. + let b = self.dev.alloc((n * 4).next_power_of_two()).map_err(failed)?; + self.copy_in(&b, &vec![1.0f32; b.bytes / 4])?; + if let Some(old) = self.ones.replace(b) { + self.returned.borrow_mut().push(old); + } + b + } + }; + self.small.rmsnorm(x, Floats::first(&ones, n), out, eps).map_err(failed) + } + + /// `w` (BF16, `rows` by `cols`) times `x`. + fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &DeviceVec) -> Result { + if w.len() != rows * cols * 2 || x.len() != cols { + return Err(ModelError::Device(format!( + "a BF16 product of {rows} by {cols} with {} weight bytes and {} inputs", + w.len(), + x.len() + ))); + } + let weights = self.weight(w)?; + let y = self.vec(rows)?; + self.matmat + .bf16(Bf16Matrix { buffer: &weights, offset: 0, rows, cols }, &x.0.buffer, 1, &y.0.buffer, SEGS) + .map_err(failed)?; + Ok(y) + } + + /// A buffer kept for the host's small lists, replaced by a larger one when needed. + /// The caller has just waited for the device. + fn list(slot: &mut Option, dev: &CudaDevice, bytes: usize) -> Result { + match *slot { + Some(b) if b.bytes >= bytes => Ok(b), + old => { + if let Some(b) = old { + dev.free(b).map_err(failed)?; + } + let b = dev.alloc(bytes.next_power_of_two().max(1024)).map_err(failed)?; + *slot = Some(b); + Ok(b) + } + } + } + + /// The chosen experts for `input`: both matrix products of each, the activation between + /// them, and the weighted sum. The caller has just waited for the device (to read the + /// router's scores), which is what makes the copies of the job lists safe. + fn expert_layer( + &mut self, + cfg: &InklingConfig, + layer: &Layer, + chosen: &[(usize, f32)], + input: &DeviceVec, + ) -> Result { + let (first, second) = (&layer.first, &layer.second); + let ((pairs2, h), (h_out, inner)) = (first.shape(), second.shape()); + let n = chosen.len(); + if n == 0 || input.len() != h || h != h_out || pairs2 != 2 * inner { + return Err(ModelError::Device(format!( + "{n} experts of {pairs2} by {h} then {h_out} by {inner}, with {} inputs", + input.len() + ))); + } + let stored = |ops: &mut Self, m: &ExpertMatrices| -> Result<(Buffer, Buffer, BlockFormat), ModelError> { + let format = match m.format() { + ExpertFormat::Nvfp4 => BlockFormat::Nvfp4, + ExpertFormat::Mxfp8 => BlockFormat::Mxfp8, + }; + Ok((ops.weight(m.values())?, ops.weight(m.scales())?, format)) + }; + let (values1, scales1, format1) = stored(self, first)?; + let (values2, scales2, format2) = stored(self, second)?; + let dev = self.dev; + let route = Self::list(&mut self.route, dev, n * 4)?; + let weights: Vec = chosen.iter().map(|&(_, w)| w).collect(); + self.copy_in(&route, &weights)?; + let [jobs1, jobs2] = &mut self.jobs; + let (jobs1, jobs2) = (Self::list(jobs1, dev, n * JOB_BYTES)?, Self::list(jobs2, dev, n * JOB_BYTES)?); + + let (both, act, outs, y) = (self.vec(n * pairs2)?, self.vec(n * inner)?, self.vec(n * h)?, self.vec(h)?); + 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 m1 = BlockMatrices { format: format1, values: &values1, scales: &scales1, rows: pairs2, cols: h }; + let m2 = BlockMatrices { format: format2, values: &values2, scales: &scales2, rows: h, cols: inner }; + // Each expert's first matrix reads the same input; its second reads its own activation. + self.blockmat.run(m1, &jobs(first, &|_| 0), &input.0.buffer, &both.0.buffer, &jobs1, SEGS).map_err(failed)?; + self.expert_ops + .capped_gate_pairs(&both.0.buffer, &act.0.buffer, n * inner, cfg.gate_cap, cfg.up_cap) + .map_err(failed)?; + self.blockmat + .run(m2, &jobs(second, &|j| j * inner), &act.0.buffer, &outs.0.buffer, &jobs2, SEGS) + .map_err(failed)?; + self.expert_ops.weighted_sum(&outs.0.buffer, &route, &y.0.buffer, n, h).map_err(failed)?; + Ok(y) + } + + /// One of a layer's short convolutions over a sublayer's recent outputs. + fn conv(&mut self, taps: &[f32], ring: &Buffer, pos: usize, x: &DeviceVec) -> Result { + let channels = x.len(); + if taps.is_empty() || !taps.len().is_multiple_of(channels) { + return Err(ModelError::Device(format!("{} convolution taps for {channels} channels", taps.len()))); + } + let n = taps.len() / channels; + let taps = self.param(taps)?; + let out = self.vec(channels)?; + self.attention + .sconv_fixed( + x.all(), + Floats::first(ring, (n - 1) * channels), + Floats::first(&taps, n * channels), + out.all(), + n, + pos, + ) + .map_err(failed)?; + Ok(out) + } + + /// A token's keys or values before the per-head step: project, then convolve over the + /// last few tokens, into `out`. + #[allow(clippy::too_many_arguments)] + fn project_kv( + &mut self, + cfg: &InklingConfig, + matrix: &[u8], + conv: &KvConv, + ring: &Buffer, + pos: usize, + input: &DeviceVec, + out: Floats, + ) -> Result<(), ModelError> { + let width = cfg.kv_heads * cfg.head_dim; + let n = cfg.conv_taps; + let projected = self.bf16(matrix, width, cfg.hidden, input)?; + let ring = Floats::first(ring, (n - 1) * width); + match conv { + KvConv::Fixed { taps } => { + let taps = self.param(taps)?; + self.attention.sconv_fixed(projected.all(), ring, Floats::first(&taps, n * width), out, n, pos) + } + KvConv::Dynamic { fixed_taps, token_proj } => { + let token_taps = self.bf16(token_proj, cfg.kv_heads * n, cfg.hidden, input)?; + let fixed = self.param(fixed_taps)?; + self.attention.sconv_dynamic( + projected.all(), + ring, + Floats::first(&fixed, n * width), + token_taps.all(), + out, + n, + cfg.kv_heads, + pos, + ) + } + } + .map_err(failed) + } +} + +impl<'m> Ops for CudaOps<'m> { + type V = DeviceVec; + type Blend = DeviceBlend; + type Pass = DevicePass; + + fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { + let (h, width, recent) = (cfg.hidden, cfg.kv_heads * cfg.head_dim, cfg.conv_taps - 1); + let window = local.then_some(cfg.window); + // A layer with a window never needs more rows than the window. + let cap = window.map_or(max_seq, |w| w.min(max_seq)); + let alloc = |floats: usize| self.dev.alloc(floats.max(1) * 4).map_err(failed); + Ok(DevicePass { + keys: alloc(cap * width)?, + values: alloc(cap * width)?, + cap, + window, + k_ring: alloc(recent * width)?, + v_ring: alloc(recent * width)?, + attn_ring: alloc(recent * h)?, + expert_ring: alloc(recent * h)?, + pos: 0, + max_seq, + returned: self.returned.clone(), + }) + } + + fn reset_pass(&mut self, pass: &mut DevicePass) -> Result<(), ModelError> { + // Nothing on the device needs clearing: the kernels are told the position, and never + // read a token from before the start of the sequence. + pass.pos = 0; + Ok(()) + } + + fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result { + // One row of the table, normalized on the host: 2,304 floats, once per token. + let h = cfg.hidden; + let row = &table[token as usize * h * 2..(token as usize + 1) * h * 2]; + let raw: Vec = row.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect(); + let mut x = vec![0.0f32; h]; + cpu::rmsnorm(&raw, norm, cfg.eps, &mut x); + self.send(&x) + } + + fn normalize(&mut self, candidates: &[&DeviceVec]) -> Result { + let count = candidates.len(); + let width = candidates.first().map_or(0, |c| c.len()); + if count == 0 || candidates.iter().any(|c| c.len() != width) { + return Err(ModelError::Device(format!("a blend of {count} candidates of unequal or no width"))); + } + let data = self.vec(count * width)?; + if count <= MANY { + let runs: Vec = candidates.iter().map(|c| c.all()).collect(); + self.small.normalize_many(&runs, data.all(), BLEND_EPS).map_err(failed)?; + } else { + for (j, candidate) in candidates.iter().enumerate() { + self.rmsnorm_plain(candidate.all(), data.part(j * width, width), BLEND_EPS)?; + } + } + Ok(DeviceBlend { data, count, width }) + } + + fn mix(&mut self, blend: &DeviceBlend, query: &[f32]) -> Result { + let (count, width) = (blend.count, blend.width); + let query = self.param(query)?; + let out = self.vec(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 scores = self.vec(count)?; + self.small + .blend_scores(Floats::first(&query, width), blend.data.all(), scores.all(), count, width) + .map_err(failed)?; + self.attention.softmax(scores.all(), 1, count).map_err(failed)?; + self.expert_ops + .weighted_sum(&blend.data.0.buffer, &scores.0.buffer, &out.0.buffer, count, width) + .map_err(failed)?; + Ok(out) + } + + fn merge( + &mut self, + cfg: &InklingConfig, + gate: &Gate, + x: &DeviceVec, + message: &DeviceVec, + ) -> Result { + let h = cfg.hidden; + let both = self.vec(2 * h)?; + self.small.normalize_many(&[x.all(), message.all()], both.all(), cfg.eps).map_err(failed)?; + let inner = self.bf16(gate.down, cfg.gate_rank, 2 * h, &both)?; + // Forget and gain are two matrices over the same small vector: stacked on the + // device, they are one product. + let stacked = self.stacked(&[gate.forget, gate.gain], h * cfg.gate_rank * 2)?; + let both_gates = self.vec(2 * h)?; + self.matmat + .bf16( + Bf16Matrix { buffer: &stacked, offset: 0, rows: 2 * h, cols: cfg.gate_rank }, + &inner.0.buffer, + 1, + &both_gates.0.buffer, + SEGS, + ) + .map_err(failed)?; + let out = self.vec(h)?; + self.small + .gate_merge(x.all(), message.all(), both_gates.part(0, h), both_gates.part(h, h), out.all()) + .map_err(failed)?; + Ok(out) + } + + fn rmsnorm(&mut self, x: &DeviceVec, weights: &[f32], eps: f32) -> Result { + let n = x.len(); + let weights = self.param(weights)?; + let out = self.vec(n)?; + self.small.rmsnorm(x.all(), Floats::first(&weights, n), out.all(), eps).map_err(failed)?; + Ok(out) + } + + fn attention( + &mut self, + cfg: &InklingConfig, + layer: &Layer, + pass: &mut DevicePass, + inputs: [&DeviceVec; 3], + pos: usize, + ) -> Result { + let (h, d, heads, kv_heads) = (cfg.hidden, cfg.head_dim, cfg.heads, cfg.kv_heads); + let (q_width, width) = (heads * d, kv_heads * d); + let [q_in, k_in, v_in] = inputs; + // Before anything is written: a position beyond what the pass has room for would + // overwrite a row that is still visible. + if pos >= pass.max_seq { + return Err(ModelError::Capacity(format!( + "position {pos} is outside the history of {} positions", + pass.max_seq + ))); + } + pass.pos = pos; + // Global layers sharpen queries and relative-position vectors late in long contexts. + let late = if layer.local { 1.0 } else { cpu::log_scale(pos, cfg.log_floor, cfg.log_alpha) }; + + // Queries: learned scale per element, length limit per head. + let q = self.bf16(layer.wq, q_width, h, q_in)?; + let q_scale = self.param(&layer.q_scale)?; + self.attention + .head_scale_clip(q.all(), Some(Floats::first(&q_scale, q_width)), heads, d, cfg.qk_clip, late) + .map_err(failed)?; + + // Keys: length limit per head. Values: normalized per head. Both go straight into + // this token's row of the history. + let row = (pos % pass.cap) * width; + let key_row = Floats { buffer: &pass.keys, at: row, len: width }; + self.project_kv(cfg, layer.wk, &layer.k_conv, &pass.k_ring, pos, k_in, key_row)?; + self.attention.head_scale_clip(key_row, None, kv_heads, d, cfg.qk_clip, 1.0).map_err(failed)?; + let unnormed = self.vec(width)?; + self.project_kv(cfg, layer.wv, &layer.v_conv, &pass.v_ring, pos, v_in, unnormed.all())?; + let value_row = Floats { buffer: &pass.values, at: row, len: width }; + self.attention.head_rmsnorm_plain(unnormed.all(), value_row, kv_heads, d, cfg.eps).map_err(failed)?; + + // Relative position: each head turns a small vector into a preference per distance. + let rel = self.bf16(layer.wr, heads * cfg.rel_dim, h, q_in)?; + let rel_scale = self.param(&layer.rel_scale)?; + self.attention + .head_scale_clip( + rel.all(), + Some(Floats::first(&rel_scale, heads * cfg.rel_dim)), + heads, + cfg.rel_dim, + cfg.rel_clip, + late, + ) + .map_err(failed)?; + let table = self.param(&layer.rel_table)?; + let sinks = self.bf16(layer.sink, heads, h, q_in)?; + + let seen = pass.window.map_or(pos + 1, |w| (pos + 1).min(w)); + let (weights, attended) = (self.vec(heads * (seen + 1))?, self.vec(q_width)?); + self.attention + .attend( + Heads { heads, kv_heads, dim: d }, + q.all(), + History { + keys: Floats::first(&pass.keys, pass.cap * width), + values: Floats::first(&pass.values, pass.cap * width), + cap: pass.cap, + }, + Relative { + rel: rel.all(), + table: Floats::first(&table, cfg.rel_dim * layer.reach), + rel_dim: cfg.rel_dim, + reach: layer.reach, + }, + sinks.all(), + weights.all(), + attended.all(), + pos, + seen, + ) + .map_err(failed)?; + + // The output is gated element by element, by a function of the query input. + let gate = self.bf16(layer.out_gate, q_width, h, q_in)?; + self.attention.sigmoid_mul(attended.all(), gate.all()).map_err(failed)?; + self.bf16(layer.wo, h, q_width, &attended) + } + + fn attn_conv(&mut self, layer: &Layer, pass: &mut DevicePass, x: &DeviceVec) -> Result { + self.conv(&layer.attn_taps, &pass.attn_ring, pass.pos, x) + } + + fn expert_conv(&mut self, layer: &Layer, pass: &mut DevicePass, x: &DeviceVec) -> Result { + self.conv(&layer.expert_taps, &pass.expert_ring, pass.pos, x) + } + + fn add(&mut self, a: &DeviceVec, b: &DeviceVec) -> Result { + let out = self.vec(a.len())?; + self.small.add(a.all(), b.all(), out.all()).map_err(failed)?; + Ok(out) + } + + fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &DeviceVec) -> Result { + // The router's 128 scores come back to the host, where the experts are chosen. + let scores = self.bf16(layer.router, cfg.experts, cfg.hidden, x)?; + let scores = self.fetch(&scores)?; + let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); + self.expert_layer(cfg, layer, &chosen, x) + } + + fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &DeviceVec) -> Result, ModelError> { + let h = cfg.hidden; + // The output table is padded; only its first rows are tokens. + let logits = self.bf16(&unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, x)?; + self.small.softcap(logits.all(), cfg.logit_cap).map_err(failed)?; + self.fetch(&logits) + } +} + +impl Drop for CudaOps<'_> { + fn drop(&mut self) { + // What this object owns goes back to the device, after everything it started has + // finished; a failure leaves it to the context's end. That includes the buffers of + // passes already dropped. Vectors and passes still alive elsewhere keep theirs. + let _ = self.dev.synchronize(); + let lists = [self.route, self.jobs[0], self.jobs[1], self.ones]; + let mut pooled: Vec = self.pool.borrow_mut().free.drain().flat_map(|(_, v)| v).collect(); + pooled.append(&mut self.returned.borrow_mut()); + for buffer in + self.weights.values().chain(self.params.values()).copied().chain(lists.into_iter().flatten()).chain(pooled) + { + let _ = self.dev.free(buffer); + } + } +} + +/// Per operation: its name, the time spent in it, and how often it ran. +pub type Spent = Rc>>; + +/// `CudaOps` with a stopwatch: after every operation it waits for the device and adds the +/// time to that operation's total. The waiting makes a token slower, so this is for finding +/// out where the time goes, not for use. +pub struct TimedOps<'m> { + inner: CudaOps<'m>, + spent: Spent, +} + +impl<'m> TimedOps<'m> { + pub fn new(inner: CudaOps<'m>) -> Self { + TimedOps { inner, spent: Rc::default() } + } + + /// A handle on the totals: operation, time, how often. + pub fn spent(&self) -> Spent { + self.spent.clone() + } + + fn timed( + &mut self, + name: &'static str, + op: impl FnOnce(&mut CudaOps<'m>) -> Result, + ) -> Result { + let started = std::time::Instant::now(); + let out = op(&mut self.inner)?; + self.inner.wait()?; + let elapsed = started.elapsed(); + let mut spent = self.spent.borrow_mut(); + match spent.iter_mut().find(|(n, _, _)| *n == name) { + Some(entry) => { + entry.1 += elapsed; + entry.2 += 1; + } + None => spent.push((name, elapsed, 1)), + } + Ok(out) + } +} + +impl<'m> Ops for TimedOps<'m> { + type V = DeviceVec; + type Blend = DeviceBlend; + type Pass = DevicePass; + + fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { + self.inner.new_pass(cfg, local, max_seq) + } + fn reset_pass(&mut self, pass: &mut DevicePass) -> Result<(), ModelError> { + self.inner.reset_pass(pass) + } + fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result { + self.timed("embedding", |o| o.embed(cfg, table, norm, token)) + } + fn normalize(&mut self, candidates: &[&DeviceVec]) -> Result { + self.timed("blend: normalize", |o| o.normalize(candidates)) + } + fn mix(&mut self, blend: &DeviceBlend, query: &[f32]) -> Result { + self.timed("blend: mix", |o| o.mix(blend, query)) + } + fn merge( + &mut self, + cfg: &InklingConfig, + gate: &Gate, + x: &DeviceVec, + message: &DeviceVec, + ) -> Result { + self.timed("merge of messages", |o| o.merge(cfg, gate, x, message)) + } + fn rmsnorm(&mut self, x: &DeviceVec, weights: &[f32], eps: f32) -> Result { + self.timed("normalization", |o| o.rmsnorm(x, weights, eps)) + } + fn attention( + &mut self, + cfg: &InklingConfig, + layer: &Layer, + pass: &mut DevicePass, + inputs: [&DeviceVec; 3], + pos: usize, + ) -> Result { + self.timed("attention", |o| o.attention(cfg, layer, pass, inputs, pos)) + } + fn attn_conv(&mut self, layer: &Layer, pass: &mut DevicePass, x: &DeviceVec) -> Result { + self.timed("convolutions", |o| o.attn_conv(layer, pass, x)) + } + fn expert_conv(&mut self, layer: &Layer, pass: &mut DevicePass, x: &DeviceVec) -> Result { + self.timed("convolutions", |o| o.expert_conv(layer, pass, x)) + } + fn add(&mut self, a: &DeviceVec, b: &DeviceVec) -> Result { + self.timed("additions", |o| o.add(a, b)) + } + fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &DeviceVec) -> Result { + self.timed("experts", |o| o.experts(cfg, layer, x)) + } + fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &DeviceVec) -> Result, ModelError> { + self.timed("scores of the vocabulary", |o| o.scores(cfg, unembed, x)) + } +} diff --git a/crates/dluth-cuda/src/small.rs b/crates/dluth-cuda/src/small.rs new file mode 100644 index 0000000..d3c5c64 --- /dev/null +++ b/crates/dluth-cuda/src/small.rs @@ -0,0 +1,240 @@ +//! Small operations on whole vectors, on the device. Each starts its kernel and returns +//! without waiting, after checking that everything the kernel touches is inside its buffers. + +use crate::device::CudaDevice; +use crate::error::CudaError; +use crate::floats::Floats; +use crate::module::{Kernel, Module}; +use std::ffi::c_void; + +fn refuse(what: &str, why: String) -> Result { + Err(CudaError::Refused(format!("{what}: {why}"))) +} + +fn ptr(p: &mut u64) -> *mut c_void { + p as *mut u64 as *mut c_void +} +fn num(p: &mut u32) -> *mut c_void { + p as *mut u32 as *mut c_void +} +fn real(p: &mut f32) -> *mut c_void { + p as *mut f32 as *mut c_void +} + +fn grid(n: usize) -> (u32, u32, u32) { + ((n as u32).div_ceil(256), 1, 1) +} + +/// Most candidates one `blend_mix` takes. +pub const BLEND_MAX: usize = 16; +/// Most vectors one `normalize_many` takes. +pub const MANY: usize = 8; + +/// The small-operation kernels of a loaded module. +pub struct Small<'m> { + dev: &'m CudaDevice, + add: Kernel<'m>, + rmsnorm: Kernel<'m>, + blend_scores: Kernel<'m>, + gate_merge: Kernel<'m>, + softcap: Kernel<'m>, + blend_mix: Kernel<'m>, + normalize_many: Kernel<'m>, +} + +impl<'m> Small<'m> { + pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result { + Ok(Small { + dev, + add: module.kernel("vec_add")?, + rmsnorm: module.kernel("rmsnorm_weighted")?, + 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")?, + }) + } + + /// Checks `n` and that every run is `n` floats inside its buffer, and that `out` + /// overlaps none of `reads`. + fn runs(&self, what: &str, n: usize, reads: &[Floats], out: &Floats) -> Result<(), CudaError> { + if n == 0 || n > u32::MAX as usize / 2 { + return refuse(what, format!("{n} values")); + } + out.check(self.dev, what, n)?; + for read in reads { + read.check(self.dev, what, n)?; + if read.overlaps(out) { + return refuse(what, "the output overlaps an input".into()); + } + } + Ok(()) + } + + /// `out = a + b`. + pub fn add(&self, a: Floats, b: Floats, out: Floats) -> Result<(), CudaError> { + let n = out.len; + self.runs("vec_add", n, &[a, b], &out)?; + let (mut pa, mut pb, mut po, mut count) = (a.address(), b.address(), out.address(), n as u32); + let mut args = [ptr(&mut pa), ptr(&mut pb), ptr(&mut po), num(&mut count)]; + // SAFETY: the arguments match vec_add(const float*, const float*, float*, unsigned); + // it reads n floats of each input and writes n to `out`, all checked. + unsafe { self.add.launch(grid(n), (256, 1, 1), &mut args) } + } + + /// `out[i] = x[i] / sqrt(mean(x^2) + eps) * weights[i]`. + pub fn rmsnorm(&self, x: Floats, weights: Floats, out: Floats, eps: f32) -> Result<(), CudaError> { + let what = "rmsnorm_weighted"; + let n = out.len; + self.runs(what, n, &[x, weights], &out)?; + if eps < 0.0 || !eps.is_finite() { + return refuse(what, format!("eps {eps}")); + } + let (mut px, mut pw, mut po, mut count, mut e) = (x.address(), weights.address(), out.address(), n as u32, eps); + let mut args = [ptr(&mut px), ptr(&mut pw), ptr(&mut po), num(&mut count), real(&mut e)]; + // SAFETY: the arguments match rmsnorm_weighted(const float*, const float*, float*, + // unsigned, float). One block of 256 threads (within the kernel's shared array) + // reads n floats of `x` and `weights` and writes n to `out`, all checked. + unsafe { self.rmsnorm.launch((1, 1, 1), (256, 1, 1), &mut args) } + } + + /// `scores[j] = (query . candidate_j) / sqrt(width)` for `count` candidates of `width` + /// floats, one after another in `candidates`. + pub fn blend_scores( + &self, + query: Floats, + candidates: Floats, + scores: Floats, + count: usize, + width: usize, + ) -> Result<(), CudaError> { + let what = "blend_scores"; + if count == 0 || width == 0 || count > 1 << 16 || width > 1 << 24 { + return refuse(what, format!("{count} candidates of {width}")); + } + query.check(self.dev, what, width)?; + candidates.check(self.dev, what, count * width)?; + scores.check(self.dev, what, count)?; + if scores.overlaps(&query) || scores.overlaps(&candidates) { + return refuse(what, "the scores overlap an input".into()); + } + let (mut pq, mut pc, mut ps) = (query.address(), candidates.address(), scores.address()); + let (mut c, mut w, mut scale) = (count as u32, width as u32, 1.0 / (width as f32).sqrt()); + let mut args = [ptr(&mut pq), ptr(&mut pc), ptr(&mut ps), num(&mut c), num(&mut w), real(&mut scale)]; + // SAFETY: the arguments match blend_scores(const float*, const float*, float*, + // unsigned, unsigned, float). One block of 256 threads per candidate reads `width` + // floats of the query and of its candidate and writes one score; all checked. + unsafe { self.blend_scores.launch((count as u32, 1, 1), (256, 1, 1), &mut args) } + } + + /// A whole blend in one launch: `out = sum_j softmax_j((query . candidate_j) / sqrt(width)) + /// * candidate_j` over `count` candidates of `width` floats in `candidates`. + 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 { + return refuse(what, format!("{count} candidates of {width}; at most {BLEND_MAX} candidates")); + } + query.check(self.dev, what, width)?; + candidates.check(self.dev, what, count * width)?; + out.check(self.dev, what, 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) = (count as u32, width as u32, 1.0 / (width as f32).sqrt()); + let mut args = [ptr(&mut pq), ptr(&mut pc), ptr(&mut po), num(&mut c), num(&mut w), real(&mut scale)]; + // SAFETY: the arguments match blend_mix(const float*, const float*, float*, unsigned, + // unsigned, float). One block of 256 threads, 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 count * width of the candidates and writes `width` to + // `out`. All checked. + unsafe { self.blend_mix.launch((1, 1, 1), (256, 1, 1), &mut args) } + } + + /// Up to `MANY` vectors of `out.len / vectors.len()` floats each, normalized one after + /// another into `out`: `out[j] = x_j / sqrt(mean(x_j^2) + eps)`. + pub fn normalize_many(&self, vectors: &[Floats], out: Floats, eps: f32) -> Result<(), CudaError> { + let what = "normalize_many"; + let count = vectors.len(); + if count == 0 || count > MANY || !out.len.is_multiple_of(count) || eps < 0.0 || !eps.is_finite() { + return refuse(what, format!("{count} vectors into {} floats, eps {eps}; at most {MANY} vectors", out.len)); + } + let width = out.len / count; + if width == 0 || width > 1 << 24 { + return refuse(what, format!("vectors of {width}")); + } + out.check(self.dev, what, count * width)?; + let mut pointers = [0u64; MANY]; + for (slot, v) in pointers.iter_mut().zip(vectors) { + v.check(self.dev, what, width)?; + if v.overlaps(&out) { + return refuse(what, "the output overlaps an input".into()); + } + *slot = v.address(); + } + let (mut po, mut c, mut w, mut e) = (out.address(), count as u32, width as u32, eps); + let [a, b, cc, d, f, g, h, i] = &mut pointers; + let mut args = [ + ptr(a), + ptr(b), + ptr(cc), + ptr(d), + ptr(f), + ptr(g), + ptr(h), + ptr(i), + ptr(&mut po), + num(&mut c), + num(&mut w), + real(&mut e), + ]; + // SAFETY: the arguments match normalize_many(const float* x8, float*, unsigned, + // unsigned, float). One block of 256 threads per vector reads `width` floats of the + // first `count` pointers (the others are never touched) and writes count * width + // floats to `out`. All checked. + unsafe { self.normalize_many.launch((count 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, + x: Floats, + message: Floats, + forget: Floats, + gain: Floats, + out: Floats, + ) -> Result<(), CudaError> { + let n = out.len; + self.runs("gate_merge", n, &[x, message, forget, gain], &out)?; + let (mut px, mut pm, mut pf, mut pg, mut po) = + (x.address(), message.address(), forget.address(), gain.address(), out.address()); + let mut count = n as u32; + let mut args = [ptr(&mut px), ptr(&mut pm), ptr(&mut pf), ptr(&mut pg), ptr(&mut po), num(&mut count)]; + // SAFETY: the arguments match gate_merge(const float* x4, float*, unsigned); it + // reads n floats of each input and writes n to `out`, all checked. + unsafe { self.gate_merge.launch(grid(n), (256, 1, 1), &mut args) } + } + + /// In place: `x[i] = cap * tanh(x[i] / cap)`. + pub fn softcap(&self, x: Floats, cap: f32) -> Result<(), CudaError> { + let what = "softcap_inplace"; + let n = x.len; + if n > u32::MAX as usize / 2 || cap <= 0.0 || !cap.is_finite() { + return refuse(what, format!("{n} values with a cap of {cap}")); + } + x.check(self.dev, what, n)?; + let (mut px, mut count, mut c) = (x.address(), n as u32, cap); + let mut args = [ptr(&mut px), num(&mut count), real(&mut c)]; + // SAFETY: the arguments match softcap_inplace(float*, unsigned, float); it reads and + // writes n floats of `x`, checked. + unsafe { self.softcap.launch(grid(n), (256, 1, 1), &mut args) } + } +} diff --git a/crates/dluth-cuda/tests/attention.rs b/crates/dluth-cuda/tests/attention.rs new file mode 100644 index 0000000..1df93e2 --- /dev/null +++ b/crates/dluth-cuda/tests/attention.rs @@ -0,0 +1,403 @@ +//! The attention sublayer's operations on the GPU against the CPU reference functions. +//! GPU tests; they need an NVIDIA GPU of the architecture the kernels were built for. + +use dluth_core::{Backend, Buffer}; +use dluth_cuda::attention::{Attention, Heads, History, Relative}; +use dluth_cuda::floats::Floats; +use dluth_cuda::{CudaDevice, CudaError, Module}; +use dluth_kernels::{cpu, sconv, sinkattn}; + +struct Lcg(u64); +impl Lcg { + fn next(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((self.0 >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 + } + fn vec(&mut self, n: usize, size: f32) -> Vec { + (0..n).map(|_| self.next() * size).collect() + } +} + +fn put(dev: &CudaDevice, buf: &Buffer, values: &[f32]) { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + dev.upload(buf, &bytes).unwrap(); +} + +fn upload(dev: &CudaDevice, values: &[f32]) -> Buffer { + let buf = dev.alloc(values.len().max(1) * 4).unwrap(); + put(dev, &buf, values); + 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() +} + +/// Every element within `ulps` roundings of the reference, relative to `size` (the sum of +/// the sizes of the terms that made it, or the value itself for a product of factors). +fn close(what: &str, got: &[f32], want: &[f32], size: impl Fn(usize) -> f32, ulps: f32) { + assert_eq!(got.len(), want.len(), "{what}"); + for i in 0..got.len() { + let bound = ulps * f32::EPSILON * size(i).max(f32::MIN_POSITIVE); + assert!((got[i] - want[i]).abs() <= bound, "{what}: element {i}: {} vs {} (bound {bound})", got[i], want[i]); + } +} + +fn kernels(dev: &CudaDevice) -> (Module<'_>,) { + (Module::load_embedded(dev).unwrap(),) +} + +#[test] +fn scaling_clipping_and_the_late_factor_match_the_cpu() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let mut rng = Lcg(1); + // Real head shapes (24 heads of 128; 24 of 16) and an odd one. Vectors of very different + // lengths, so that some are over the clip and some under; one all zeros. + for (heads, dim, clip) in [(24, 128, 22.63f32), (24, 16, 8.0), (5, 3, 1.0)] { + let mut x: Vec = Vec::new(); + for h in 0..heads { + let size = [0.0, 0.01, 1.0, 5.0, 40.0][h % 5]; + x.extend(rng.vec(dim, size)); + } + let scale = rng.vec(heads * dim, 1.5); + for (with_scale, late) in [(true, 1.0718f32), (false, 1.0)] { + let (dx, ds) = (upload(&dev, &x), upload(&dev, &scale)); + let s = with_scale.then(|| Floats::first(&ds, heads * dim)); + at.head_scale_clip(Floats::first(&dx, heads * dim), s, heads, dim, clip, late).unwrap(); + let got = download(&dev, &dx, heads * dim); + let mut want = x.clone(); + if with_scale { + want.iter_mut().zip(&scale).for_each(|(v, s)| *v *= s); + } + for head in want.chunks_exact_mut(dim) { + cpu::l2_clip_inplace(head, clip); + head.iter_mut().for_each(|v| *v *= late); + } + // A product of up to four factors, one of them from a sum of squares that the + // device may round differently in its last bits. + close("head_scale_clip", &got, &want, |i| want[i].abs(), 8.0); + let lengths: Vec = + want.chunks_exact(dim).map(|h| h.iter().map(|v| v * v).sum::().sqrt()).collect(); + assert!(lengths.iter().any(|l| (l / late - clip).abs() < 1e-3 * clip), "no head was clipped: {lengths:?}"); + assert!(lengths.iter().any(|l| *l > 0.0 && l / late < 0.5 * clip), "no head was left alone"); + dev.free(dx).unwrap(); + dev.free(ds).unwrap(); + } + } +} + +#[test] +fn value_normalization_matches_the_cpu() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let mut rng = Lcg(2); + for (heads, dim) in [(8, 128), (3, 5), (1, 1)] { + let mut x = rng.vec(heads * dim, 3.0); + x[..dim].fill(0.0); // a head of zeros: only eps keeps it finite + let (dx, dout) = (upload(&dev, &x), dev.alloc(heads * dim * 4).unwrap()); + at.head_rmsnorm_plain(Floats::first(&dx, heads * dim), Floats::first(&dout, heads * dim), heads, dim, 1e-6) + .unwrap(); + let got = download(&dev, &dout, heads * dim); + let mut want = vec![0.0f32; heads * dim]; + for (o, head) in want.chunks_exact_mut(dim).zip(x.chunks_exact(dim)) { + cpu::rmsnorm_plain(head, 1e-6, o); + } + close("head_rmsnorm_plain", &got, &want, |i| want[i].abs(), 8.0); + assert!(got[..dim].iter().all(|v| *v == 0.0)); + } +} + +/// Slides the CPU reference's memory of recent tokens forward by one, oldest first. +fn remember(recent: &mut [f32], current: &[f32]) { + let n = current.len(); + if recent.len() >= n { + recent.copy_within(n.., 0); + let at = recent.len() - n; + recent[at..].copy_from_slice(current); + } +} + +#[test] +fn both_short_convolutions_match_the_cpu_token_after_token() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let mut rng = Lcg(3); + // One tap (no memory at all), two, and the model's four; channels not a multiple of anything. + for (channels, n, heads) in [(36, 4, 4), (10, 2, 5), (7, 1, 7), (1024, 4, 8)] { + let fixed_taps = rng.vec(channels * n, 0.7); + let (d_taps, d_cur, d_out) = + (upload(&dev, &fixed_taps), dev.alloc(channels * 4).unwrap(), dev.alloc(channels * 4).unwrap()); + let d_token_taps = dev.alloc(heads * n * 4).unwrap(); + // Two rings, one per kernel, never zeroed: a ring's old contents must not leak into + // the first tokens of a sequence. + let junk = vec![99.0f32; (n - 1).max(1) * channels]; + let (ring_fixed, ring_dynamic) = (upload(&dev, &junk), upload(&dev, &junk)); + let ring = |b| Floats::first(b, (n - 1) * channels); + let (mut recent_fixed, mut recent_dynamic) = + (vec![0.0f32; (n - 1) * channels], vec![0.0f32; (n - 1) * channels]); + for pos in 0..11 { + let current = rng.vec(channels, 2.0); + let token_taps = rng.vec(heads * n, 0.5); + put(&dev, &d_cur, ¤t); + put(&dev, &d_token_taps, &token_taps); + let cur = Floats::first(&d_cur, channels); + + at.sconv_fixed( + cur, + ring(&ring_fixed), + Floats::first(&d_taps, channels * n), + Floats::first(&d_out, channels), + n, + pos, + ) + .unwrap(); + let got = download(&dev, &d_out, channels); + let mut want = vec![0.0f32; channels]; + sconv::fixed(&recent_fixed, ¤t, &fixed_taps, &mut want); + // n + 1 terms added in the reference's order; the device may fuse each multiply + // into its add. The terms are of size about 1. + close(&format!("sconv_fixed, {n} taps, token {pos}"), &got, &want, |_| 8.0, 4.0); + remember(&mut recent_fixed, ¤t); + + at.sconv_dynamic( + cur, + ring(&ring_dynamic), + Floats::first(&d_taps, channels * n), + Floats::first(&d_token_taps, heads * n), + Floats::first(&d_out, channels), + n, + heads, + pos, + ) + .unwrap(); + let got = download(&dev, &d_out, channels); + sconv::dynamic(&recent_dynamic, ¤t, &fixed_taps, &token_taps, heads, &mut want); + close(&format!("sconv_dynamic, {n} taps, token {pos}"), &got, &want, |_| 8.0, 4.0); + remember(&mut recent_dynamic, ¤t); + } + } +} + +/// Runs `tokens` tokens through attention with a history of `cap` rows on the device and +/// compares every output with `sinkattn::attend` over the tokens a window of `window` shows. +fn attend_case( + dev: &CudaDevice, + at: &Attention, + shape: Heads, + relative: (usize, usize), + cap: usize, + window: usize, + tokens: usize, +) { + let (rel_dim, reach) = relative; + let Heads { heads, kv_heads, dim } = shape; + let width = kv_heads * dim; + let mut rng = Lcg((heads * 131 + cap * 7 + reach) as u64); + let table = rng.vec(rel_dim * reach, 0.8); + let d_table = upload(dev, &table); + let (d_keys, d_values) = (upload(dev, &vec![7.0f32; cap * width]), upload(dev, &vec![7.0f32; cap * width])); + let (d_q, d_rel, d_sinks) = + (dev.alloc(heads * dim * 4).unwrap(), dev.alloc(heads * rel_dim * 4).unwrap(), dev.alloc(heads * 4).unwrap()); + let (d_weights, d_out) = (dev.alloc(heads * (cap + 1) * 4).unwrap(), dev.alloc(heads * dim * 4).unwrap()); + let (mut host_keys, mut host_values) = (vec![7.0f32; cap * width], vec![7.0f32; cap * width]); + let (mut all_keys, mut all_values): (Vec, Vec) = (Vec::new(), Vec::new()); + for pos in 0..tokens { + let (key, value) = (rng.vec(width, 1.0), rng.vec(width, 2.0)); + let (q, rel, sinks) = (rng.vec(heads * dim, 1.5), rng.vec(heads * rel_dim, 1.0), rng.vec(heads, 3.0)); + // The token's key and value go into row pos % cap, as the model does it. + let row = (pos % cap) * width; + host_keys[row..row + width].copy_from_slice(&key); + host_values[row..row + width].copy_from_slice(&value); + put(dev, &d_keys, &host_keys); + put(dev, &d_values, &host_values); + put(dev, &d_q, &q); + put(dev, &d_rel, &rel); + put(dev, &d_sinks, &sinks); + all_keys.extend_from_slice(&key); + all_values.extend_from_slice(&value); + let seen = (pos + 1).min(window); + + at.attend( + shape, + Floats::first(&d_q, heads * dim), + History { keys: Floats::first(&d_keys, cap * width), values: Floats::first(&d_values, cap * width), cap }, + Relative { + rel: Floats::first(&d_rel, heads * rel_dim), + table: Floats::first(&d_table, rel_dim * reach), + rel_dim, + reach, + }, + Floats::first(&d_sinks, heads), + Floats::first(&d_weights, heads * (seen + 1)), + Floats::first(&d_out, heads * dim), + pos, + seen, + ) + .unwrap(); + let got = download(dev, &d_out, heads * dim); + + // The reference: the seen tokens oldest first, and each head's bias by distance. + let first = pos + 1 - seen; + let (keys, values) = (&all_keys[first * width..], &all_values[first * width..]); + let near = seen.min(reach); + let mut bias = vec![0.0f32; heads * seen]; + let mut profile = vec![0.0f32; near]; + for (head, row) in rel.chunks_exact(rel_dim).zip(bias.chunks_exact_mut(seen)) { + sinkattn::distance_profile(head, &table, reach, &mut profile); + for (distance, &p) in profile.iter().enumerate() { + row[seen - 1 - distance] = p; + } + } + let mut want = vec![0.0f32; heads * dim]; + sinkattn::attend( + sinkattn::Query { + q: &q, + keys, + values, + bias: &bias, + sinks: &sinks, + heads, + kv_heads, + head_dim: dim, + positions: seen, + }, + &mut want, + ); + // Weights sum to at most 1 and values are below 2 in size. The softmax's sum is + // added in a different order on the device, which moves every weight by a few + // roundings of 1; the scores feeding it are sums of `dim` products of size about 1. + let bound = 64.0 * (dim as f32) * f32::EPSILON; + for i in 0..want.len() { + assert!( + (got[i] - want[i]).abs() <= bound, + "{heads} heads, cap {cap}, window {window}, reach {reach}, token {pos}: element {i}: {} vs {}", + got[i], + want[i] + ); + } + } +} + +#[test] +fn attention_matches_the_cpu_with_and_without_a_window() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let shape = Heads { heads: 6, kv_heads: 2, dim: 8 }; + // A layer that sees everything: the history is as long as the sequence. Reach shorter + // than the sequence, so far tokens get no relative-position term; and longer. + attend_case(&dev, &at, shape, (4, 5), 32, usize::MAX, 20); + attend_case(&dev, &at, shape, (4, 40), 20, usize::MAX, 20); + // A layer with a window of 7: the history wraps around, three times over. + attend_case(&dev, &at, shape, (4, 7), 7, 7, 23); + // One head, one position of history: every token sees only itself. + attend_case(&dev, &at, Heads { heads: 1, kv_heads: 1, dim: 4 }, (2, 3), 1, 1, 4); + // The real shape of a head, at a few hundred tokens. + attend_case(&dev, &at, Heads { heads: 24, kv_heads: 8, dim: 128 }, (16, 1024), 300, usize::MAX, 300); +} + +#[test] +fn the_output_gate_matches_the_cpu() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let mut rng = Lcg(5); + let n = 3073; + let (x, gate) = (rng.vec(n, 4.0), rng.vec(n, 30.0)); + let (dx, dg) = (upload(&dev, &x), upload(&dev, &gate)); + at.sigmoid_mul(Floats::first(&dx, n), Floats::first(&dg, n)).unwrap(); + let got = download(&dev, &dx, n); + let want: Vec = x.iter().zip(&gate).map(|(x, g)| x * cpu::sigmoid(*g)).collect(); + close("sigmoid_mul", &got, &want, |i| want[i].abs(), 8.0); +} + +#[test] +fn requests_that_would_leave_the_buffers_are_refused() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let a = dev.alloc(64 * 4).unwrap(); + let b = dev.alloc(64 * 4).unwrap(); + let c = dev.alloc(1024 * 4).unwrap(); + let f = Floats::first; + let refused = |what: &str, r: Result<(), CudaError>| { + assert!(matches!(r, Err(CudaError::Refused(_))), "{what} was not refused") + }; + + refused("more heads than the buffer holds", at.head_scale_clip(f(&a, 80), None, 10, 8, 1.0, 1.0)); + refused( + "a run that starts past its buffer", + at.head_scale_clip(Floats { buffer: &a, at: 60, len: 8 }, None, 1, 8, 1.0, 1.0), + ); + refused("a clip of zero", at.head_scale_clip(f(&a, 64), None, 8, 8, 0.0, 1.0)); + refused("a clip that is not a number", at.head_scale_clip(f(&a, 64), None, 8, 8, f32::NAN, 1.0)); + refused("a scale that is the vectors", at.head_scale_clip(f(&a, 64), Some(f(&a, 64)), 8, 8, 1.0, 1.0)); + refused("normalizing in place", at.head_rmsnorm_plain(f(&a, 64), f(&a, 64), 8, 8, 1e-6)); + refused("a negative eps", at.head_rmsnorm_plain(f(&a, 64), f(&b, 64), 8, 8, -1.0)); + + refused("a ring too short for the taps", at.sconv_fixed(f(&a, 16), f(&b, 32), f(&c, 64), f(&c, 16), 4, 0)); + refused( + "taps too few", + at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 48), Floats { buffer: &c, at: 100, len: 16 }, 4, 0), + ); + refused("the output over the token", at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 64), f(&a, 16), 4, 0)); + refused("no taps", at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 64), Floats { buffer: &c, at: 100, len: 16 }, 0, 0)); + refused( + "heads that do not divide the channels", + at.sconv_dynamic( + f(&a, 16), + f(&b, 48), + f(&c, 64), + Floats { buffer: &c, at: 64, len: 12 }, + Floats { buffer: &c, at: 100, len: 16 }, + 4, + 3, + 0, + ), + ); + + let shape = Heads { heads: 4, kv_heads: 2, dim: 4 }; + let history = |cap| History { keys: f(&a, cap * 8), values: f(&b, cap * 8), cap }; + let relative = Relative { + rel: Floats { buffer: &c, at: 0, len: 8 }, + table: Floats { buffer: &c, at: 8, len: 6 }, + rel_dim: 2, + reach: 3, + }; + let (q, sinks, out) = ( + Floats { buffer: &c, at: 16, len: 16 }, + Floats { buffer: &c, at: 32, len: 4 }, + Floats { buffer: &c, at: 40, len: 16 }, + ); + let weights = |seen: usize| Floats { buffer: &c, at: 64, len: 4 * (seen + 1) }; + at.attend(shape, q, history(8), relative, sinks, weights(3), out, 2, 3).unwrap(); + dev.synchronize().unwrap(); + refused( + "more tokens seen than have been fed", + at.attend(shape, q, history(8), relative, sinks, weights(4), out, 2, 4), + ); + refused( + "more tokens seen than the history holds", + at.attend(shape, q, history(8), relative, sinks, weights(9), out, 20, 9), + ); + refused("no token seen", at.attend(shape, q, history(8), relative, sinks, weights(0), out, 2, 0)); + refused( + "a history larger than its buffers", + at.attend(shape, q, history(9), relative, sinks, weights(3), out, 2, 3), + ); + refused("scratch of the wrong size", at.attend(shape, q, history(8), relative, sinks, weights(2), out, 2, 3)); + refused("the output over the query", at.attend(shape, q, history(8), relative, sinks, weights(3), q, 2, 3)); + refused( + "heads that the key-value heads do not divide", + at.attend(Heads { heads: 3, kv_heads: 2, dim: 4 }, q, history(8), relative, sinks, weights(3), out, 2, 3), + ); + refused("a gate that is the values", at.sigmoid_mul(f(&a, 64), f(&a, 64))); + refused("a gate shorter than the values", at.sigmoid_mul(f(&a, 64), f(&b, 60))); +} diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 8d477cf..f65de89 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -100,3 +100,115 @@ fn the_real_model_matches_the_reference_with_products_on_the_gpu() { assert_eq!(report.tokens_checked, 32, "{}", case["prompt"]); } } + +/// The same three checks with every value on the device (`CudaOps`), not only the products. +mod on_the_device { + use super::*; + use dluth_cuda::ops::CudaOps; + use dluth_model::inkling::Inkling; + + #[test] + fn the_tiny_model_matches_the_reference() { + 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(); + 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 ops = CudaOps::new(&dev, &module).unwrap(); + let mut model = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); + let report = common::check_case(&mut |token, pos| model.forward_token(token, pos).unwrap(), case, tol); + eprintln!("device, {}: {report:?}", case["prompt"]); + assert_eq!(report.tie_at, None, "{}", case["prompt"]); + assert_eq!(report.tokens_checked, 24, "{}", case["prompt"]); + } + } + + /// Unrecorded text, twice over, so that a second sequence on the same model (position 0 + /// again) is covered: nothing of the first may leak into it. + #[test] + fn the_tiny_model_stays_close_to_the_cpu_model_across_two_sequences() { + 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 ops = CudaOps::new(&dev, &module).unwrap(); + let mut gpu = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); + let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let mut worst = 0.0f32; + for (sequence, length) in [(0usize, 40usize), (1, 25)] { + for pos in 0..length { + let token = ((pos * 37 + 11 + sequence * 101) % 256) as u32; + let (a, b) = (gpu.forward_token(token, pos).unwrap(), cpu.forward_token(token, pos).unwrap()); + 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, + "sequence {sequence} 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, "sequence {sequence} position {pos}"); + } + } + eprintln!("device: largest log-probability difference from the CPU model: {worst} (bar {tol})"); + } + + /// Every device buffer the model and its operations took is given back when they go: + /// weights, parameters, pooled vectors, and each layer pass's histories and rings. + #[test] + fn a_dropped_model_gives_every_device_buffer_back() { + 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 before = dev.live_buffers(); + { + let ops = CudaOps::new(&dev, &module).unwrap(); + let mut model = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); + for pos in 0..20 { + model.forward_token((pos * 7 % 250) as u32, pos).unwrap(); + } + assert!(dev.live_buffers() > before + 100, "the model should be holding buffers while it lives"); + } + assert_eq!(dev.live_buffers(), before); + } + + #[test] + fn the_real_model_matches_the_reference() { + 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 ops = CudaOps::new(&dev, &module).unwrap(); + let mut model = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 256, ops).unwrap(); + let started = std::time::Instant::now(); + let report = common::check_case(&mut |token, pos| model.forward_token(token, pos).unwrap(), case, tol); + eprintln!("device, 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"]); + } + } +} diff --git a/crates/dluth-cuda/tests/small.rs b/crates/dluth-cuda/tests/small.rs new file mode 100644 index 0000000..b2dddc3 --- /dev/null +++ b/crates/dluth-cuda/tests/small.rs @@ -0,0 +1,255 @@ +//! The small vector operations on the GPU against the CPU reference functions. +//! GPU tests; they need an NVIDIA GPU of the architecture the kernels were built for. + +use dluth_core::{Backend, Buffer}; +use dluth_cuda::floats::Floats; +use dluth_cuda::small::Small; +use dluth_cuda::{CudaDevice, CudaError, Module}; +use dluth_kernels::{cpu, depthmix}; + +struct Lcg(u64); +impl Lcg { + fn vec(&mut self, n: usize, size: f32) -> Vec { + (0..n) + .map(|_| { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (((self.0 >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0) * size + }) + .collect() + } +} + +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 add_is_exact() { + 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(1); + let n = 2305; + let (a, b) = (rng.vec(n, 10.0), rng.vec(n, 0.001)); + let (da, db, dout) = (upload(&dev, &a), upload(&dev, &b), dev.alloc(n * 4).unwrap()); + small.add(Floats::first(&da, n), Floats::first(&db, n), Floats::first(&dout, n)).unwrap(); + let got = download(&dev, &dout, n); + // One addition per element: no room for a difference. + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + assert_eq!(got, want); +} + +#[test] +fn weighted_normalization_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(2); + for n in [1, 7, 256, 2304] { + let (x, w) = (rng.vec(n, 5.0), rng.vec(n, 2.0)); + let (dx, dw, dout) = (upload(&dev, &x), upload(&dev, &w), dev.alloc(n * 4).unwrap()); + small.rmsnorm(Floats::first(&dx, n), Floats::first(&dw, n), Floats::first(&dout, n), 1e-6).unwrap(); + let got = download(&dev, &dout, n); + let mut want = vec![0.0f32; n]; + cpu::rmsnorm(&x, &w, 1e-6, &mut want); + // The squares are added in another order, which moves the scale by a few roundings. + for i in 0..n { + assert!( + (got[i] - want[i]).abs() <= 16.0 * f32::EPSILON * want[i].abs(), + "n {n}, element {i}: {} vs {}", + got[i], + want[i] + ); + } + } +} + +#[test] +fn blend_scores_match_the_cpu_and_give_the_same_blend() { + 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(3); + for (count, width) in [(1, 5), (3, 32), (9, 2304)] { + // Normalized candidates, as a blend is given them: sizes of about 1. + let (query, candidates) = (rng.vec(width, 0.5), rng.vec(count * width, 1.7)); + let (dq, dc, ds) = (upload(&dev, &query), upload(&dev, &candidates), dev.alloc(count * 4).unwrap()); + small + .blend_scores( + Floats::first(&dq, width), + Floats::first(&dc, count * width), + Floats::first(&ds, count), + count, + width, + ) + .unwrap(); + let got = download(&dev, &ds, count); + let scale = 1.0 / (width as f32).sqrt(); + for j in 0..count { + let c = &candidates[j * width..(j + 1) * width]; + let want = query.iter().zip(c).map(|(a, b)| a * b).sum::() * scale; + let size: f32 = query.iter().zip(c).map(|(a, b)| (a * b).abs()).sum::() * scale; + // `width` products added in a different order: the random-walk bar of the + // matrix kernels' tests. + let bound = 16.0 * ((width + 1) as f32).sqrt() * (f32::EPSILON / 2.0) * size; + assert!((got[j] - want).abs() <= bound, "{count} of {width}, candidate {j}: {} vs {want}", got[j]); + } + // The CPU's whole blend for comparison of meaning: scores, softmax, weighted sum. + let mut blended = vec![0.0f32; width]; + depthmix::mix_normalized(&query, &candidates, width, &mut blended); + let mut weights = got.clone(); + cpu::softmax_inplace(&mut weights); + for (i, want) in blended.iter().enumerate() { + let mine: f32 = (0..count).map(|j| weights[j] * candidates[j * width + i]).sum(); + assert!((mine - want).abs() <= 1e-4, "blend element {i}: {mine} vs {want}"); + } + } +} + +#[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) in [(1, 5), (2, 100), (6, 2304), (dluth_cuda::small::BLEND_MAX, 700)] { + let (query, candidates) = (rng.vec(width, 0.6), rng.vec(count * width, 1.7)); + let (dq, dc, dout) = (upload(&dev, &query), upload(&dev, &candidates), dev.alloc(width * 4).unwrap()); + small + .blend_mix( + Floats::first(&dq, width), + Floats::first(&dc, count * width), + Floats::first(&dout, width), + count, + width, + ) + .unwrap(); + let got = download(&dev, &dout, width); + let mut want = vec![0.0f32; width]; + depthmix::mix_normalized(&query, &candidates, width, &mut want); + // 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 i in 0..width { + assert!((got[i] - want[i]).abs() <= bound, "{count} of {width}, element {i}: {} vs {}", got[i], want[i]); + } + } +} + +#[test] +fn several_vectors_normalized_in_one_launch_match_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(7); + for (count, width) in [(1, 3), (2, 2304), (dluth_cuda::small::MANY, 513)] { + // Each vector in its own buffer, of very different sizes; one of them all zeros. + let vectors: Vec> = (0..count).map(|j| rng.vec(width, [0.0, 0.01, 3.0, 400.0][j % 4])).collect(); + let buffers: Vec = vectors.iter().map(|v| upload(&dev, v)).collect(); + let runs: Vec = buffers.iter().map(|b| Floats::first(b, width)).collect(); + let dout = dev.alloc(count * width * 4).unwrap(); + small.normalize_many(&runs, Floats::first(&dout, count * width), 1e-6).unwrap(); + let got = download(&dev, &dout, count * width); + for (j, v) in vectors.iter().enumerate() { + let mut want = vec![0.0f32; width]; + cpu::rmsnorm_plain(v, 1e-6, &mut want); + for i in 0..width { + let g = got[j * width + i]; + assert!( + (g - want[i]).abs() <= 16.0 * f32::EPSILON * want[i].abs(), + "{count} of {width}, vector {j} element {i}: {g} vs {}", + want[i] + ); + } + } + } +} + +#[test] +fn the_merging_gate_and_the_soft_cap_match_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(4); + let n = 2307; + let (x, m, f, g) = (rng.vec(n, 3.0), rng.vec(n, 3.0), rng.vec(n, 4.0), rng.vec(n, 4.0)); + let (dx, dm, df, dg, dout) = + (upload(&dev, &x), upload(&dev, &m), upload(&dev, &f), upload(&dev, &g), dev.alloc(n * 4).unwrap()); + let run = |b| Floats::first(b, n); + small.gate_merge(run(&dx), run(&dm), run(&df), run(&dg), run(&dout)).unwrap(); + let got = download(&dev, &dout, n); + for i in 0..n { + let want = (1.0 - f[i].tanh()) * x[i] + g[i].tanh() * m[i]; + // Two products of a tanh, each possibly rounded differently in its last bits. + let size = ((1.0 - f[i].tanh()) * x[i]).abs() + (g[i].tanh() * m[i]).abs(); + assert!( + (got[i] - want).abs() <= 8.0 * f32::EPSILON * size.max(f32::MIN_POSITIVE), + "gate element {i}: {} vs {want}", + got[i] + ); + } + + let scores = rng.vec(n, 90.0); + let ds = upload(&dev, &scores); + small.softcap(run(&ds), 30.0).unwrap(); + let got = download(&dev, &ds, n); + for i in 0..n { + let want = cpu::softcap(scores[i], 30.0); + assert!( + (got[i] - want).abs() <= 8.0 * f32::EPSILON * want.abs().max(f32::MIN_POSITIVE), + "cap element {i}: {} vs {want}", + got[i] + ); + } + assert!(got.iter().all(|v| v.abs() <= 30.0) && got.iter().any(|v| v.abs() > 29.0)); +} + +#[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 small = Small::new(&dev, &module).unwrap(); + let (a, b, c) = (dev.alloc(16 * 4).unwrap(), dev.alloc(16 * 4).unwrap(), dev.alloc(64 * 4).unwrap()); + let f = Floats::first; + let refused = |what: &str, r: Result<(), CudaError>| { + assert!(matches!(r, Err(CudaError::Refused(_))), "{what} was not refused") + }; + refused("an input shorter than the output", small.add(f(&a, 16), f(&b, 12), f(&c, 16))); + refused("more values than a buffer holds", small.add(f(&a, 17), f(&b, 17), f(&c, 17))); + refused("adding in place", small.add(f(&a, 16), f(&b, 16), f(&a, 16))); + refused("nothing to add", small.add(f(&a, 0), f(&b, 0), f(&c, 0))); + refused("a negative eps", small.rmsnorm(f(&a, 16), f(&b, 16), f(&c, 16), -1.0)); + refused("normalizing in place", small.rmsnorm(f(&a, 16), f(&b, 16), f(&a, 16), 1e-6)); + refused("more candidates than the buffer holds", small.blend_scores(f(&a, 16), f(&c, 80), f(&b, 5), 5, 16)); + refused( + "scores inside the candidates", + small.blend_scores(f(&a, 16), f(&c, 64), Floats { buffer: &c, at: 4, len: 4 }, 4, 16), + ); + 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)); + refused("no vectors", small.normalize_many(&[], f(&c, 16), 1e-6)); + refused("an output the vectors do not divide", small.normalize_many(&[f(&a, 5), f(&b, 5)], f(&c, 11), 1e-6)); + refused("a vector normalized over itself", small.normalize_many(&[f(&c, 16)], f(&c, 16), 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/mod.rs b/crates/dluth-model/src/inkling/mod.rs index f68cef6..531caab 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -7,5 +7,5 @@ pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; pub use model::{ CpuBlend, CpuOps, CpuProducts, ExpertLayer, ExpertMatrices, Gate, Inkling, InklingCpu, KvConv, Layer, Ops, - PassState, Products, + PassState, Products, BLEND_EPS, }; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 816fdef..07445e5 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -18,7 +18,7 @@ use dluth_core::bf16_to_f32; use dluth_kernels::{blockfloat, cpu, depthmix, router, sconv, sinkattn}; /// The normalization inside every blend across depth uses this fixed epsilon. -const BLEND_EPS: f32 = 1e-6; +pub const BLEND_EPS: f32 = 1e-6; fn bf16_values(w: &Weights, name: &str) -> Result, ModelError> { Ok(w.bytes(name)?.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect()) diff --git a/docs/learning/21-every-value-on-the-device.md b/docs/learning/21-every-value-on-the-device.md new file mode 100644 index 0000000..0eebe4f --- /dev/null +++ b/docs/learning/21-every-value-on-the-device.md @@ -0,0 +1,99 @@ +# 21. Every value on the device + +Note 20 moved the model's matrix products to the GPU and left the rest on the CPU, at the price of copying a +vector to the device and back for every product. This note is about the next step: nothing leaves the device +between a token going in and its scores coming out. + +## The forward pass, written against operations + +The forward pass no longer calls CPU functions on `Vec` values. Since the step before this one it +calls a set of operations on values of a type it does not know: + +| Operation | What it does | +|---|---| +| `embed` | a token's row of the table, normalized | +| `normalize`, `mix` | the blend across depth: normalize the candidates, then blend them for a query | +| `merge` | merge a message from the previous pass through its gate | +| `rmsnorm` | normalization with learned weights | +| `attention` | queries, keys and values for the token, its place in the history, attention, output | +| `attn_conv`, `expert_conv` | the short convolutions over a sublayer's recent outputs | +| `add` | add two vectors | +| `experts` | choose experts, run them, sum their outputs | +| `scores` | the score of every token of the vocabulary | + +That is the trait `Ops`. `CpuOps` implements it with the functions that were there before, so the CPU +model's results are the same to the last digit, and it stays the reference. `CudaOps` implements it with +kernels, on vectors that live on the device. What stays written once is the part that is easiest to get +wrong and hardest to test in pieces: which layers run how often, what a block is, where a pass starts +again, which blend feeds which sublayer, where messages come from. + +Each device operation is tested against the CPU function it replaces, on inputs chosen to reach its +corners: heads over and under the clip, the first tokens of a sequence, a history that wraps around its +window, distances beyond the reach of the relative-position table. Then the whole model is checked against +the reference recordings, exactly as on the CPU. + +## Where a history lives + +Keys and values of earlier tokens are kept in two device buffers per layer pass. The token at position p +is in row p modulo the number of rows. A layer that sees everything has a row per position. A layer with a +window has exactly as many rows as its window, so a token's row is overwritten at the moment the token +leaves the window, and nothing ever has to be moved. The short convolutions keep their last three tokens +the same way. Kernels are told the position and how many tokens are visible, and never read a row from +before the start of the sequence, so starting a new sequence needs no clearing. + +## Kernels run in the order they are started + +Starting a kernel does not wait for it. That makes one rule necessary. A buffer that an unfinished kernel +will still read may be given to a *later kernel* as its output, because the earlier kernel runs first. It +must not be written by the *host*, which does not wait in line. So the host copies into a buffer only +right after waiting for the device, or into a buffer no kernel has been given yet. A token waits 50 times: +once to copy its embedding in, once per layer pass to read back the 128 router scores from which the +experts are chosen on the host, and once for the vocabulary's scores. + +## What it bought, and what it showed + +On a GB10, the real model, generating 90 tokens: + +| Step | Tokens per second | Per token | +|---|---|---| +| Products on the GPU, the rest on the CPU (note 20) | 19.7 | 50.7 ms | +| Every value on the device, first version | 11.4 | 87.4 ms | +| A whole vector normalized by many threads instead of one | 22.4 | 44.6 ms | +| A blend, its candidates' normalization and a message's merge in fewer launches | 23.9 | 41.8 ms | +| A block of threads per head for scaling, clipping and value normalization | 24.4 | 40.9 ms | + +The first version was *slower* than the step before it. The reason is the lesson of this note. Note 17 +measured that starting a kernel costs 2 microseconds and concluded that many small kernels would be cheap. +That was the cost of a kernel that does nothing. A token starts about 3,000 kernels, they run one after +another, and a small kernel that does real work takes 5 to 10 microseconds: a single thread walking a +vector, or a block of threads with one serial step in the middle. The first version normalized each +2,304-wide vector with one thread, about 1,300 times a token, and that alone was 43 milliseconds. + +`TimedOps` wraps the operations with a stopwatch (it waits for the device after each one, which costs +about 4 ms a token by itself): + +| Operation | Per token | +|---|---| +| Attention | 18.3 ms | +| Experts | 11.1 ms | +| Blends (normalize and mix) | 4.3 ms | +| Scores of the vocabulary | 3.8 ms | +| Merges of messages | 3.4 ms | +| Normalizations | 2.2 ms | +| Convolutions and additions | 1.2 ms | + +The scores of the vocabulary are one product over 0.92 GB, and 3.8 ms is what the memory allows: the large +reads are as fast as they can be. Reading all of a token's weights needs about 22 ms. The other 20 ms is +small kernels, and that is where the next work is: fewer and faster ones, and then several positions per +sweep, which spreads this cost over the tokens of a sweep. + +## How we know it is right + +With every value on the device the tiny model matches its reference at all 72 recorded tokens, and stays +within the same bar of the CPU model over two sequences fed one after the other to the same model. The real +Inkling 2 Mini matches its 32-bit reference recording at all 96 tokens, to 0.00006 in log-probability +against a bar of 0.00015. The model gives back every device buffer it took when it is dropped, which a test counts. Seventeen +planted bugs in the device code each fail a test: among them a sink +with no say, a missing relative-position term, weights applied at the mirrored distance, a convolution +reading its memory from before the start of a sequence, forget and gain swapped in the merging gate, keys +stored without their length limit, and every value written to the first row of the history. diff --git a/tools/mutants/75-head-late-factor-dropped.patch b/tools/mutants/75-head-late-factor-dropped.patch new file mode 100644 index 0000000..1f2a148 --- /dev/null +++ b/tools/mutants/75-head-late-factor-dropped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention scaling_clipping +# needs: gpu +# Bug: the late factor is not applied to a head after clipping. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index f60645f..08ee239 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -37,7 +37,7 @@ extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigne + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { + float t = v[i]; + if (factor < 1.0f) t *= factor; +- v[i] = t * late; ++ v[i] = t; + } + } + diff --git a/tools/mutants/76-head-always-rescaled.patch b/tools/mutants/76-head-always-rescaled.patch new file mode 100644 index 0000000..ff56407 --- /dev/null +++ b/tools/mutants/76-head-always-rescaled.patch @@ -0,0 +1,23 @@ +# test: cargo test --release -p dluth-cuda --test attention scaling_clipping +# needs: gpu +# Bug: every head is rescaled to the clip length, short ones too. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index f60645f..fb39fb2 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -30,13 +30,13 @@ extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigne + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; +- part[0] = fminf(clip / (sqrtf(squares) + 1e-6f), 1.0f); ++ part[0] = clip / (sqrtf(squares) + 1e-6f); + } + __syncthreads(); + float factor = part[0]; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { + float t = v[i]; +- if (factor < 1.0f) t *= factor; ++ t *= factor; + v[i] = t * late; + } + } diff --git a/tools/mutants/77-head-norm-sum-not-mean.patch b/tools/mutants/77-head-norm-sum-not-mean.patch new file mode 100644 index 0000000..02ffb0f --- /dev/null +++ b/tools/mutants/77-head-norm-sum-not-mean.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention value_normalization +# needs: gpu +# Bug: values are divided by the root of the sum of squares, not of their mean. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index f60645f..303b559 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -56,7 +56,7 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; +- part[0] = 1.0f / sqrtf(squares / (float)dim + eps); ++ part[0] = 1.0f / sqrtf(squares + eps); + } + __syncthreads(); + float scale = part[0]; diff --git a/tools/mutants/78-conv-ring-before-start.patch b/tools/mutants/78-conv-ring-before-start.patch new file mode 100644 index 0000000..8a11d45 --- /dev/null +++ b/tools/mutants/78-conv-ring-before-start.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention both_short_convolutions +# needs: gpu +# Bug: a convolution reads its ring for tokens before the start of the sequence. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 801f951..9132ec7 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -48,7 +48,7 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign + // tokens; zero before the start of the sequence. + __device__ __forceinline__ float earlier_token(const float* ring, unsigned int channels, unsigned int n, + unsigned long long pos, unsigned int lag, unsigned int c) { +- return pos >= lag ? ring[((pos - lag) % (n - 1)) * channels + c] : 0.0f; ++ return ring[((pos + (unsigned long long)(n - 1) * lag - lag) % (n - 1)) * channels + c]; + } + + // Short convolution with fixed taps: taps[c * n + j] weighs the token n - 1 - j steps back. diff --git a/tools/mutants/79-conv-token-taps-ignored.patch b/tools/mutants/79-conv-token-taps-ignored.patch new file mode 100644 index 0000000..4ec7c99 --- /dev/null +++ b/tools/mutants/79-conv-token-taps-ignored.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention both_short_convolutions +# needs: gpu +# Bug: the dynamic convolution leaves out the taps computed for the token at earlier tokens. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 801f951..289d30a 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -80,7 +80,7 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons + const float* head_taps = token_taps + (size_t)(c / (channels / heads)) * n; + float sum = (fixed_taps[c] + head_taps[0]) * x; + for (unsigned int lag = 1; lag < n; ++lag) +- sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) * earlier_token(ring, channels, n, pos, lag, c); ++ sum += fixed_taps[(size_t)lag * channels + c] * earlier_token(ring, channels, n, pos, lag, c); + out[c] = (sum + x) * norm; + if (n > 1) ring[(pos % (n - 1)) * channels + c] = x; + } diff --git a/tools/mutants/80-attn-sink-silenced.patch b/tools/mutants/80-attn-sink-silenced.patch new file mode 100644 index 0000000..5950fe7 --- /dev/null +++ b/tools/mutants/80-attn-sink-silenced.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: the sink is given no say in attention on the device. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 801f951..1e29628 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -102,7 +102,7 @@ extern "C" __global__ void attn_scores(const float* q, const float* keys, const + unsigned long long d = index % (seen + 1); + if (h >= heads) return; + if (d == seen) { +- weights[index] = sinks[h]; ++ weights[index] = -1e30f; + return; + } + const float* key = keys + ((pos - d) % cap) * kv_heads * dim + (h / (heads / kv_heads)) * dim; diff --git a/tools/mutants/81-attn-bias-dropped.patch b/tools/mutants/81-attn-bias-dropped.patch new file mode 100644 index 0000000..c7c94d2 --- /dev/null +++ b/tools/mutants/81-attn-bias-dropped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: the relative-position term is left out of the attention scores. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 801f951..726276c 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -112,7 +112,7 @@ extern "C" __global__ void attn_scores(const float* q, const float* keys, const + float bias = 0.0f; + if (d < reach) + for (unsigned int k = 0; k < rel_dim; ++k) bias += rel[h * rel_dim + k] * table[(size_t)k * reach + d]; +- weights[index] = dot * scale + bias; ++ weights[index] = dot * scale; + } + + // Softmax over each head's `count` scores, in place: one block of threads per head. diff --git a/tools/mutants/82-attn-weights-reversed.patch b/tools/mutants/82-attn-weights-reversed.patch new file mode 100644 index 0000000..87ee7f2 --- /dev/null +++ b/tools/mutants/82-attn-weights-reversed.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# 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 801f951..24dbce2 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -164,7 +164,7 @@ extern "C" __global__ void attn_values(const float* weights, const float* values + const float* w = weights + h * (seen + 1); + unsigned long long at = (h / (heads / kv_heads)) * dim + e; + float total = 0.0f; +- for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((pos - d) % cap) * kv_heads * dim + at]; ++ for (unsigned long long d = seen; d-- > 0;) total += w[seen - 1 - d] * values[((pos - d) % cap) * kv_heads * dim + at]; + out[index] = total; + } + diff --git a/tools/mutants/83-gate-not-sigmoid.patch b/tools/mutants/83-gate-not-sigmoid.patch new file mode 100644 index 0000000..50c72ef --- /dev/null +++ b/tools/mutants/83-gate-not-sigmoid.patch @@ -0,0 +1,14 @@ +# test: cargo test --release -p dluth-cuda --test attention the_output_gate +# needs: gpu +# Bug: the attention output is multiplied by the raw gate, not its sigmoid. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 801f951..886bff4 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -171,5 +171,5 @@ extern "C" __global__ void attn_values(const float* weights, const float* values + // x[i] *= sigmoid(gate[i]). CPU reference: cpu::sigmoid. + extern "C" __global__ void sigmoid_mul(float* x, const float* gate, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; +- if (i < n) x[i] *= 1.0f / (1.0f + expf(-gate[i])); ++ if (i < n) x[i] *= gate[i]; + } diff --git a/tools/mutants/84-merge-gates-swapped.patch b/tools/mutants/84-merge-gates-swapped.patch new file mode 100644 index 0000000..71494a8 --- /dev/null +++ b/tools/mutants/84-merge-gates-swapped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small the_merging_gate +# needs: gpu +# Bug: the merging gate uses forget where gain belongs and gain where forget belongs. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 25e169f..28a3c8e 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -51,7 +51,7 @@ extern "C" __global__ void blend_scores(const float* query, const float* candida + extern "C" __global__ void gate_merge(const float* x, const float* message, const float* forget, + const float* gain, float* out, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; +- if (i < n) out[i] = (1.0f - tanhf(forget[i])) * x[i] + tanhf(gain[i]) * message[i]; ++ if (i < n) out[i] = (1.0f - tanhf(gain[i])) * x[i] + tanhf(forget[i]) * message[i]; + } + + // x[i] = cap * tanh(x[i] / cap), in place. CPU reference: cpu::softcap. diff --git a/tools/mutants/85-blend-scores-unscaled.patch b/tools/mutants/85-blend-scores-unscaled.patch new file mode 100644 index 0000000..f15b72a --- /dev/null +++ b/tools/mutants/85-blend-scores-unscaled.patch @@ -0,0 +1,16 @@ +# 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; diff --git a/tools/mutants/86-normalize-first-vector.patch b/tools/mutants/86-normalize-first-vector.patch new file mode 100644 index 0000000..3b1a7c4 --- /dev/null +++ b/tools/mutants/86-normalize-first-vector.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small several_vectors +# needs: gpu +# Bug: every vector of a normalize_many launch is read from the first pointer. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 25e169f..14abe9f 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -112,7 +112,7 @@ extern "C" __global__ void normalize_many(const float* x0, const float* x1, cons + unsigned int j = blockIdx.x; + if (j >= count) return; + const float* all[8] = {x0, x1, x2, x3, x4, x5, x6, x7}; +- const float* x = all[j]; ++ const float* x = all[0]; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) squares += x[i] * x[i]; + part[threadIdx.x] = squares; diff --git a/tools/mutants/87-norm-weights-dropped.patch b/tools/mutants/87-norm-weights-dropped.patch new file mode 100644 index 0000000..ff8962f --- /dev/null +++ b/tools/mutants/87-norm-weights-dropped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small weighted_normalization +# needs: gpu +# Bug: the weighted normalization leaves out the weights. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 25e169f..48cf2e1 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -23,7 +23,7 @@ extern "C" __global__ void rmsnorm_weighted(const float* x, const float* w, floa + } + __syncthreads(); + float scale = 1.0f / sqrtf(part[0] / (float)n + eps); +- for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) out[i] = x[i] * scale * w[i]; ++ for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) out[i] = x[i] * scale; + } + + // Scores for a blend across depth: for each of `count` candidates of `width` floats, one diff --git a/tools/mutants/88-softcap-cap-ignored.patch b/tools/mutants/88-softcap-cap-ignored.patch new file mode 100644 index 0000000..a3533f8 --- /dev/null +++ b/tools/mutants/88-softcap-cap-ignored.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small the_merging_gate +# 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 25e169f..162a088 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -57,7 +57,7 @@ extern "C" __global__ void gate_merge(const float* x, const float* message, cons + // x[i] = cap * tanh(x[i] / cap), in place. CPU reference: cpu::softcap. + extern "C" __global__ void softcap_inplace(float* x, unsigned int n, float cap) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; +- if (i < n) x[i] = cap * tanhf(x[i] / cap); ++ if (i < n) x[i] = tanhf(x[i]); + } + + // A whole blend across depth in one launch, by one block of threads: diff --git a/tools/mutants/89-ops-late-factor-off.patch b/tools/mutants/89-ops-late-factor-off.patch new file mode 100644 index 0000000..c00aea8 --- /dev/null +++ b/tools/mutants/89-ops-late-factor-off.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_matches +# needs: gpu +# Bug: the device model never sharpens queries late in a long context. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index 2f4b07e..2de5e35 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -597,7 +597,7 @@ impl<'m> Ops for CudaOps<'m> { + } + pass.pos = pos; + // Global layers sharpen queries and relative-position vectors late in long contexts. +- let late = if layer.local { 1.0 } else { cpu::log_scale(pos, cfg.log_floor, cfg.log_alpha) }; ++ let late = if layer.local { 1.0 } else { 1.0 + 0.0 * cpu::log_scale(pos, cfg.log_floor, cfg.log_alpha) }; + + // Queries: learned scale per element, length limit per head. + let q = self.bf16(layer.wq, q_width, h, q_in)?; diff --git a/tools/mutants/90-ops-keys-not-clipped.patch b/tools/mutants/90-ops-keys-not-clipped.patch new file mode 100644 index 0000000..2244110 --- /dev/null +++ b/tools/mutants/90-ops-keys-not-clipped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_matches +# needs: gpu +# Bug: the device model stores keys without their length limit. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index 2f4b07e..ff556cb 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -611,7 +611,7 @@ impl<'m> Ops for CudaOps<'m> { + let row = (pos % pass.cap) * width; + let key_row = Floats { buffer: &pass.keys, at: row, len: width }; + self.project_kv(cfg, layer.wk, &layer.k_conv, &pass.k_ring, pos, k_in, key_row)?; +- self.attention.head_scale_clip(key_row, None, kv_heads, d, cfg.qk_clip, 1.0).map_err(failed)?; ++ self.attention.head_scale_clip(key_row, None, kv_heads, d, f32::MAX, 1.0).map_err(failed)?; + let unnormed = self.vec(width)?; + self.project_kv(cfg, layer.wv, &layer.v_conv, &pass.v_ring, pos, v_in, unnormed.all())?; + let value_row = Floats { buffer: &pass.values, at: row, len: width }; diff --git a/tools/mutants/91-ops-value-row-of-first-token.patch b/tools/mutants/91-ops-value-row-of-first-token.patch new file mode 100644 index 0000000..05da2d7 --- /dev/null +++ b/tools/mutants/91-ops-value-row-of-first-token.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_matches +# needs: gpu +# Bug: the device model writes every value to the first row of the history. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index 2f4b07e..541bcda 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -614,7 +614,7 @@ impl<'m> Ops for CudaOps<'m> { + self.attention.head_scale_clip(key_row, None, kv_heads, d, cfg.qk_clip, 1.0).map_err(failed)?; + let unnormed = self.vec(width)?; + self.project_kv(cfg, layer.wv, &layer.v_conv, &pass.v_ring, pos, v_in, unnormed.all())?; +- let value_row = Floats { buffer: &pass.values, at: row, len: width }; ++ let value_row = Floats { buffer: &pass.values, at: 0, len: width }; + self.attention.head_rmsnorm_plain(unnormed.all(), value_row, kv_heads, d, cfg.eps).map_err(failed)?; + + // Relative position: each head turns a small vector into a preference per distance.