diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 33c2400..d056dfa 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -10,7 +10,8 @@ //! 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. +//! last, so loading the weights and reading the prompt are not in it. In the default mode +//! the text is then read again in batches of 1 to 16 positions, to show what a batch costs. use dluth_cuda::inkling::CudaProducts; use dluth_cuda::ops::{CudaOps, TimedOps}; @@ -107,6 +108,28 @@ fn main() { (total.copies_out - at_first.copies_out) as f64 / decoded as f64 ); } + // The same text again, from the start, fed in batches of consecutive positions and + // not scored: how fast the model reads text it is given. Every weight it needs is + // on the device by now. The scores after the last token are fetched to make the + // device finish. + let text: Vec = ids.iter().chain(&generated).copied().collect(); + let text = &text[..text.len() / 16 * 16]; + if !text.is_empty() { + println!("reading the same {} tokens again, without scoring them:", text.len()); + for batch in [1, 2, 4, 8, 16] { + let started = Instant::now(); + for (i, chunk) in text.chunks(batch).enumerate() { + model.feed(chunk, i * batch).expect("a batch"); + } + model.next_scores().expect("the scores"); + let seconds = started.elapsed().as_secs_f64(); + println!( + " batches of {batch:2}: {:6.1} tokens per second, {:5.1} ms per batch", + text.len() as f64 / seconds, + seconds * 1000.0 / (text.len() / batch) as f64 + ); + } + } return; } diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu index f60645f..10196bd 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu @@ -8,18 +8,29 @@ // 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. +// How many tokens, the newest included, the token at position `pos` may look at: all of +// them, or the last `window` when the layer has a window (window 0 means none). +__device__ __forceinline__ unsigned long long tokens_seen(unsigned long long pos, unsigned long long window) { + return (window != 0 && pos + 1 > window) ? window : pos + 1; +} + // 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 +// to length `clip` if it is longer, then multiplied by a factor that grows late in a long +// context: 1 + alpha * ln(max((position + 1) / floor, 1)), which is exactly 1 when alpha +// is 0. `x` holds `vectors` vectors of `dim`: for each position of a batch, `heads` of +// them; the scale repeats per position, and the first position is `pos`. One block of +// threads per vector. +// CPU reference: the scale loop, cpu::l2_clip_inplace and cpu::log_scale 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) { +extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigned int vectors, + unsigned int heads, unsigned int dim, float clip, + unsigned long long pos, float floor, float alpha) { __shared__ float part[256]; - unsigned int h = blockIdx.x; - if (h >= heads) return; - float* v = x + (size_t)h * dim; + unsigned int index = blockIdx.x; + if (index >= vectors) return; + unsigned int h = index % heads; + unsigned long long at = pos + index / heads; + float* v = x + (size_t)index * 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]; @@ -34,6 +45,7 @@ extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigne } __syncthreads(); float factor = part[0]; + float late = 1.0f + alpha * logf(fmaxf((float)(at + 1) / floor, 1.0f)); for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { float t = v[i]; if (factor < 1.0f) t *= factor; @@ -42,8 +54,8 @@ extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigne } // 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. +// head; for a batch, `heads` counts the heads of every position. 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]; @@ -63,84 +75,132 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign 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; +// The token `lag` steps before position b of a batch whose first token is at `pos`, +// channel c: from the batch itself if it is that recent, else from a ring of the last +// n - 1 tokens before the batch; zero before the start of the sequence. +__device__ __forceinline__ float earlier_token(const float* current, const float* ring, unsigned int channels, + unsigned int n, unsigned long long pos, unsigned int b, + unsigned int lag, unsigned int c) { + if (b >= lag) return current[(size_t)(b - lag) * channels + c]; + unsigned long long at = pos + b; + return at >= lag ? ring[((at - 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. +// Short convolution with fixed taps, for a batch of `batch` consecutive tokens of +// `channels` floats: taps[c * n + j] weighs the token n - 1 - j steps back. +// out[b][c] = (sum of taps times tokens + current[b][c]) * norm +// With a batch of one, the token then takes its place in the ring. With a larger batch +// the ring is only read here (another position's thread may be reading the slot a write +// would hit); `ring_store` puts the batch's last tokens in afterwards. +// CPU reference: sconv::fixed, token after token. 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]; + float norm, unsigned int batch) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned int b = (unsigned int)(index / channels); + unsigned int c = (unsigned int)(index % channels); + if (b >= batch) return; + float x = current[index]; 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; + for (unsigned int j = 0; j + 1 < n; ++j) sum += w[j] * earlier_token(current, ring, channels, n, pos, b, n - 1 - j, c); + out[index] = (sum + x) * norm; + if (batch == 1 && 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 +// Short convolution whose taps are a fixed part per channel plus a part computed for each // 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. +// token_taps[b][head * n + lag], lag 0 being the current token. The ring as in +// sconv_fixed. CPU reference: sconv::dynamic, token after token. 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 norm, unsigned int batch) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned int b = (unsigned int)(index / channels); + unsigned int c = (unsigned int)(index % channels); + if (b >= batch) return; + float x = current[index]; + const float* head_taps = token_taps + ((size_t)b * heads + 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; + sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) + * earlier_token(current, ring, channels, n, pos, b, lag, c); + out[index] = (sum + x) * norm; + if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x; +} + +// After a convolution over a batch larger than one: the batch's last n - 1 tokens (or all +// of them, if it has fewer) take their places in the ring. The token at position p goes to +// slot p % (n - 1); the tokens stored here have different slots. +extern "C" __global__ void ring_store(const float* current, float* ring, unsigned int channels, + unsigned int n, unsigned long long pos, unsigned int batch) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned int b = (unsigned int)(index / channels); + unsigned int c = (unsigned int)(index % channels); + if (b >= batch || n < 2) return; + if (batch - b > n - 1) return; + ring[((pos + b) % (n - 1)) * channels + c] = current[index]; +} + +// The keys or values of a batch go to their rows of the history: the token at position p +// is in row p % cap. The rows of a batch may wrap around the end of the history. +extern "C" __global__ void store_rows(const float* rows, float* history, unsigned int width, + unsigned long long cap, unsigned long long pos, unsigned int batch) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long b = index / width; + if (b >= batch) return; + history[((pos + b) % cap) * width + index % width] = rows[index]; } -// 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. +// Attention scores of a batch of query tokens, the first at position `pos`. The query at +// position p sees tokens_seen(p, window) tokens. For query b, 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[b][h][k] * table[k][d], which is zero +// from distance `reach` on. Each (query, head) has a run of `stride` floats in `weights`: +// entry d receives the score, entry `seen` the head's sink score, and the rest is unused. // 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 pos, unsigned long long window, + unsigned long long cap, unsigned long long stride, + unsigned int batch) { unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; - unsigned long long h = index / (seen + 1); - unsigned long long d = index % (seen + 1); - if (h >= heads) return; + unsigned long long run = index / stride; + unsigned long long d = index % stride; + if (run >= (unsigned long long)batch * heads) return; + unsigned long long b = run / heads; + unsigned int h = (unsigned int)(run % heads); + unsigned long long at = pos + b; + unsigned long long seen = tokens_seen(at, window); + if (d > seen) return; if (d == seen) { - weights[index] = sinks[h]; + weights[index] = sinks[run]; return; } - const float* key = keys + ((pos - d) % cap) * kv_heads * dim + (h / (heads / kv_heads)) * dim; - const float* query = q + h * dim; + const float* key = keys + ((at - d) % cap) * kv_heads * dim + (size_t)(h / (heads / kv_heads)) * dim; + const float* query = q + run * 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]; + for (unsigned int k = 0; k < rel_dim; ++k) bias += rel[run * 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) { +// Softmax over each (query, head) run's scores and its sink, in place: one block of +// threads per run. 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 pos, + unsigned long long window, unsigned long long stride, + unsigned int batch) { __shared__ float part[1024]; - unsigned int h = blockIdx.x; - if (h >= heads) return; - float* w = weights + (unsigned long long)h * count; + unsigned long long run = blockIdx.x; + if (run >= (unsigned long long)batch * heads) return; + unsigned long long count = tokens_seen(pos + run / heads, window) + 1; + float* w = weights + run * stride; float best = -INFINITY; for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) best = fmaxf(best, w[i]); part[threadIdx.x] = best; @@ -169,21 +229,25 @@ extern "C" __global__ void attn_softmax(float* weights, unsigned int heads, unsi for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) w[i] /= sum; } -// The weighted sum of the values: out[h][e] = sum over the seen tokens, oldest first, of -// the token's weight times its value. The sink has no value. +// The weighted sum of the values: out[b][h][e] = sum over the tokens query b sees, oldest +// first, of the token's weight times its value. The sink has no value. // CPU reference: the summing loop of sinkattn::attend. 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 pos, unsigned long long window, + unsigned long long cap, unsigned long long stride, + unsigned int batch) { unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; - unsigned long long h = index / dim; + unsigned long long run = 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; + if (run >= (unsigned long long)batch * heads) return; + unsigned int h = (unsigned int)(run % heads); + unsigned long long at = pos + run / heads; + unsigned long long seen = tokens_seen(at, window); + const float* w = weights + run * stride; + unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; 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[d] * values[((at - d) % cap) * kv_heads * dim + column]; out[index] = total; } diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu index c23c4c7..252df27 100644 --- a/crates/dluth-cuda/kernels/expert_ops.cu +++ b/crates/dluth-cuda/kernels/expert_ops.cu @@ -18,15 +18,20 @@ extern "C" __global__ void capped_gate_pairs(const float* both, float* act, unsi act[i] = gate * (1.0f / (1.0f + expf(-gu.x))) * up; } -// The weighted sum of the chosen experts' outputs: -// y[r] = sum over j of weights[j] * outs[j][r] -// `outs` is count vectors of width floats, one after another. The sum runs in the order of -// j, like the CPU reference (the loop in the model's expert step). +// The weighted sum of the chosen experts' outputs, for a batch of positions: +// y[b][r] = sum over j of weights[b][j] * outs[b][j][r] +// `outs` holds, for each position, `count` vectors of `width` floats, one after another; +// `weights` holds `count` floats per position. The sum runs in the order of j, like the +// CPU reference (the loop in the model's expert step). extern "C" __global__ void weighted_sum(const float* outs, const float* weights, float* y, - unsigned int count, unsigned int width) { - unsigned int r = blockIdx.x * blockDim.x + threadIdx.x; - if (r >= width) return; + unsigned int count, unsigned int width, unsigned int batch) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long b = index / width; + unsigned int r = (unsigned int)(index % width); + if (b >= batch) return; + const float* mine = outs + b * count * width; + const float* w = weights + b * count; float total = 0.0f; - for (unsigned int j = 0; j < count; ++j) total += weights[j] * outs[(size_t)j * width + r]; - y[r] = total; + for (unsigned int j = 0; j < count; ++j) total += w[j] * mine[(size_t)j * width + r]; + y[index] = total; } diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu index 25e169f..0d40107 100644 --- a/crates/dluth-cuda/kernels/small_ops.cu +++ b/crates/dluth-cuda/kernels/small_ops.cu @@ -7,14 +7,18 @@ extern "C" __global__ void vec_add(const float* a, const float* b, float* out, u 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. +// Root-mean-square normalization with learned weights, for a batch of vectors of n +// floats, one block of threads per vector: +// out[b][i] = x[b][i] / sqrt(mean(x[b]^2) + eps) * w[i] +// CPU reference: cpu::rmsnorm, once per vector. 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) { + float eps, unsigned int batch) { __shared__ float part[1024]; + if (blockIdx.x >= batch) return; + const float* v = x + (size_t)blockIdx.x * n; + float* o = out + (size_t)blockIdx.x * n; float squares = 0.0f; - for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) squares += x[i] * x[i]; + for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) squares += v[i] * v[i]; part[threadIdx.x] = squares; __syncthreads(); if (threadIdx.x == 0) { @@ -23,7 +27,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) o[i] = v[i] * scale * w[i]; } // Scores for a blend across depth: for each of `count` candidates of `width` floats, one @@ -60,22 +64,26 @@ extern "C" __global__ void softcap_inplace(float* x, unsigned int n, float cap) if (i < n) x[i] = cap * tanhf(x[i] / cap); } -// A whole blend across depth in one launch, by one block of threads: +// A whole blend across depth in one launch, one block of threads per position of a batch: // score_j = (query . candidate_j) * scale; weights = softmax(scores); -// out = 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. +// out[b] = sum over j of weights_j * candidate_j +// Position b's `count` candidates of `width` floats are one after another in `candidates`, +// after those of the positions before it. CPU reference: depthmix::mix_normalized, once per +// position. #define BLEND_MAX 16 extern "C" __global__ void blend_mix(const float* query, const float* candidates, float* out, - unsigned int count, unsigned int width, float scale) { + unsigned int count, unsigned int width, float scale, + unsigned int batch) { __shared__ float part[BLEND_MAX][256]; __shared__ float weight[BLEND_MAX]; + if (blockIdx.x >= batch) return; + const float* mine = candidates + (size_t)blockIdx.x * count * width; + float* o = out + (size_t)blockIdx.x * width; float dot[BLEND_MAX]; for (unsigned int j = 0; j < count; ++j) dot[j] = 0.0f; for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) { float q = query[i]; - for (unsigned int j = 0; j < count; ++j) dot[j] += q * candidates[(size_t)j * width + i]; + for (unsigned int j = 0; j < count; ++j) dot[j] += q * mine[(size_t)j * width + i]; } for (unsigned int j = 0; j < count; ++j) part[j][threadIdx.x] = dot[j]; __syncthreads(); @@ -97,22 +105,26 @@ extern "C" __global__ void blend_mix(const float* query, const float* candidates __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; + for (unsigned int j = 0; j < count; ++j) total += weight[j] * mine[(size_t)j * width + i]; + o[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. +// Up to eight candidates, each wherever it lives and each a batch of vectors of `width`, +// normalized into one buffer in one launch: +// out[b][j][i] = x_j[b][i] / sqrt(mean(x_j[b]^2) + eps) +// so that position b's candidates end up one after another. 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) { + float* out, unsigned int count, unsigned int width, float eps, + unsigned int batch) { __shared__ float part[1024]; - unsigned int j = blockIdx.x; - if (j >= count) return; + unsigned int j = blockIdx.x % count; + unsigned int b = blockIdx.x / count; + if (b >= batch) return; const float* all[8] = {x0, x1, x2, x3, x4, x5, x6, x7}; - const float* x = all[j]; + const float* x = all[j] + (size_t)b * width; float squares = 0.0f; for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) squares += x[i] * x[i]; part[threadIdx.x] = squares; @@ -123,5 +135,12 @@ extern "C" __global__ void normalize_many(const float* x0, const float* x1, cons } __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; + float* o = out + ((size_t)b * count + j) * width; + for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) o[i] = x[i] * scale; +} + +// out[i] = x[i]: one position of a batch copied out as a batch of one. +extern "C" __global__ void vec_copy(const float* x, float* out, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = x[i]; } diff --git a/crates/dluth-cuda/src/attention.rs b/crates/dluth-cuda/src/attention.rs index d452484..ef803dd 100644 --- a/crates/dluth-cuda/src/attention.rs +++ b/crates/dluth-cuda/src/attention.rs @@ -1,4 +1,5 @@ -//! The attention sublayer's operations other than its matrix products, on the device. +//! The attention sublayer's operations other than its matrix products, on the device, for +//! a batch of consecutive tokens. //! //! 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. @@ -31,6 +32,9 @@ fn real(p: &mut f32) -> *mut c_void { p as *mut f32 as *mut c_void } +/// Most consecutive tokens one launch takes. +pub const MAX_BATCH: usize = 16; + /// The shape of a layer's attention: query heads, key-value heads, and the size of a head. #[derive(Clone, Copy, Debug)] pub struct Heads { @@ -48,8 +52,8 @@ pub struct History<'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. +/// The relative-position term: one vector of `rel_dim` per query token and 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>, @@ -58,6 +62,23 @@ pub struct Relative<'b> { pub reach: usize, } +/// The factor a head is multiplied by late in a long context: +/// `1 + alpha * ln(max((position + 1) / floor, 1))`, where `pos` is the position of the +/// first token of the batch. With `alpha` 0 it is exactly 1. +#[derive(Clone, Copy, Debug)] +pub struct Late { + pub pos: usize, + pub floor: f32, + pub alpha: f32, +} + +impl Late { + /// No factor. + pub fn none() -> Self { + Late { pos: 0, floor: 1.0, alpha: 0.0 } + } +} + /// The attention kernels of a loaded module. pub struct Attention<'m> { dev: &'m CudaDevice, @@ -65,6 +86,8 @@ pub struct Attention<'m> { rmsnorm_plain: Kernel<'m>, sconv_fixed: Kernel<'m>, sconv_dynamic: Kernel<'m>, + ring_store: Kernel<'m>, + store_rows: Kernel<'m>, scores: Kernel<'m>, softmax: Kernel<'m>, values: Kernel<'m>, @@ -79,6 +102,8 @@ impl<'m> Attention<'m> { rmsnorm_plain: module.kernel("head_rmsnorm_plain")?, sconv_fixed: module.kernel("sconv_fixed")?, sconv_dynamic: module.kernel("sconv_dynamic")?, + ring_store: module.kernel("ring_store")?, + store_rows: module.kernel("store_rows")?, scores: module.kernel("attn_scores")?, softmax: module.kernel("attn_softmax")?, values: module.kernel("attn_values")?, @@ -86,8 +111,10 @@ impl<'m> Attention<'m> { }) } - /// 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`. + /// In place, for each vector of `dim` in `x`: multiply by `scale` element by element (if + /// given), shorten to length `clip` if longer, multiply by the late factor of its + /// position. `x` holds `heads` vectors for each position of a batch; `scale` holds + /// `heads` vectors and is used for every position. pub fn head_scale_clip( &self, x: Floats, @@ -95,17 +122,21 @@ impl<'m> Attention<'m> { heads: usize, dim: usize, clip: f32, - late: f32, + late: Late, ) -> 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}")); + if heads == 0 || dim == 0 || heads > 1 << 20 || dim > 1 << 20 || !x.len.is_multiple_of(heads * dim) { + return refuse(what, format!("{} floats for heads of {dim}, {heads} per position", x.len)); } + let vectors = x.len / 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}")); + if clip <= 0.0 || !clip.is_finite() || late.floor <= 0.0 || !late.floor.is_finite() || !late.alpha.is_finite() { + return refuse(what, format!("a clip of {clip} and a late factor of {late:?}")); } - x.check(self.dev, what, heads * dim)?; + if vectors == 0 || vectors > u32::MAX as usize { + return refuse(what, format!("{vectors} vectors")); + } + x.check(self.dev, what, vectors * dim)?; if let Some(s) = &scale { s.check(self.dev, what, heads * dim)?; if s.overlaps(&x) { @@ -113,16 +144,29 @@ impl<'m> Attention<'m> { } } 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)]; + let (mut v, mut h, mut d, mut c) = (vectors as u32, heads as u32, dim as u32, clip); + let (mut pos, mut floor, mut alpha) = (late.pos as u64, late.floor, late.alpha); + let mut args = [ + ptr(&mut px), + ptr(&mut ps), + num(&mut v), + num(&mut h), + num(&mut d), + real(&mut c), + big(&mut pos), + real(&mut floor), + real(&mut alpha), + ]; // 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) } + // unsigned, unsigned, float, unsigned long long, float, float). The kernel reads + // and writes vectors * dim floats of `x` and reads heads * dim of `scale` unless it + // is null; both were checked. One block per vector, of 128 threads: within the + // kernel's shared array of 256. + unsafe { self.scale_clip.launch((vectors 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)`. + /// For a batch, `heads` counts the heads of every position. pub fn head_rmsnorm_plain( &self, x: Floats, @@ -148,9 +192,14 @@ impl<'m> Attention<'m> { 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. + /// The short convolution with fixed taps (`channels * n` of them) of a batch of `batch` + /// consecutive tokens, the first at `pos`, written to `out`. `current` and `out` hold + /// the tokens one after another. `ring` holds the `n - 1` tokens before the batch. + /// + /// With a batch of one the token then takes its place in the ring. With a larger batch + /// the ring is left as it was: call `ring_store` after this. Batches must be given in + /// order of position. + #[allow(clippy::too_many_arguments)] pub fn sconv_fixed( &self, current: Floats, @@ -159,14 +208,17 @@ impl<'m> Attention<'m> { out: Floats, n: usize, pos: usize, + batch: usize, ) -> Result<(), CudaError> { let what = "sconv_fixed"; - let channels = current.len; - self.conv_checks(what, current, ring, out, n)?; + let channels = self.conv_checks(what, current, ring, out, n, batch)?; taps.check(self.dev, what, channels * n)?; + if taps.overlaps(&out) || taps.overlaps(&ring) { + return refuse(what, "the taps overlap the output or the ring".into()); + } 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 c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32); + let mut norm = 1.0 / ((n + 1) as f32).sqrt(); let mut args = [ ptr(&mut pc), ptr(&mut pr), @@ -176,16 +228,19 @@ impl<'m> Attention<'m> { num(&mut taps_n), big(&mut p), real(&mut norm), + num(&mut b), ]; // 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) } + // unsigned, unsigned, unsigned long long, float, unsigned). It reads batch * channels + // floats of `current`, channels * n of `taps` and (n - 1) * channels of `ring`, + // writes batch * channels to `out`, and writes the ring only for a batch of one; all + // checked, and `out` overlaps none of the inputs. + unsafe { self.sconv_fixed.launch((blocks((batch * 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). + /// (for each token of the batch, `heads * n`, shared by the channels of a head). The + /// ring as for `sconv_fixed`. #[allow(clippy::too_many_arguments)] pub fn sconv_dynamic( &self, @@ -197,21 +252,26 @@ impl<'m> Attention<'m> { n: usize, heads: usize, pos: usize, + batch: usize, ) -> Result<(), CudaError> { let what = "sconv_dynamic"; - let channels = current.len; - self.conv_checks(what, current, ring, out, n)?; + let channels = self.conv_checks(what, current, ring, out, n, batch)?; 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()); + token_taps.check(self.dev, what, batch * heads * n)?; + if token_taps.overlaps(&out) + || token_taps.overlaps(&ring) + || fixed_taps.overlaps(&out) + || fixed_taps.overlaps(&ring) + { + return refuse(what, "the 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 c, mut taps_n, mut h, mut p, mut b) = + (channels as u32, n as u32, heads as u32, pos as u64, batch as u32); let mut norm = 1.0 / ((2 * n + 1) as f32).sqrt(); let mut args = [ ptr(&mut pc), @@ -224,38 +284,121 @@ impl<'m> Attention<'m> { num(&mut h), big(&mut p), real(&mut norm), + num(&mut b), ]; // 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) } + // const float*, float*, unsigned, unsigned, unsigned, unsigned long long, float, + // unsigned). Extents as for sconv_fixed, plus batch * heads * n floats of + // `token_taps`; all checked. + unsafe { self.sconv_dynamic.launch((blocks((batch * 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")); + /// Checks what both convolutions share and returns the number of channels. + fn conv_checks( + &self, + what: &str, + current: Floats, + ring: Floats, + out: Floats, + n: usize, + batch: usize, + ) -> Result { + if n == 0 || n > 64 || batch == 0 || batch > MAX_BATCH || !current.len.is_multiple_of(batch) { + return refuse(what, format!("{n} taps, {} floats for a batch of {batch}", current.len)); } - current.check(self.dev, what, channels)?; - out.check(self.dev, what, channels)?; + let channels = current.len / batch; + if channels == 0 || channels > 1 << 24 { + return refuse(what, format!("{channels} channels")); + } + current.check(self.dev, what, batch * channels)?; + out.check(self.dev, what, batch * 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()); + return refuse(what, "the ring overlaps the tokens or the output".into()); } } if out.overlaps(¤t) { - return refuse(what, "the output overlaps the token".into()); + return refuse(what, "the output overlaps the tokens".into()); + } + Ok(channels) + } + + /// After a convolution over a batch larger than one: the batch's last `n - 1` tokens + /// take their places in `ring`. After a batch of one, which stored its token itself, + /// it stores the same token again. + pub fn ring_store( + &self, + current: Floats, + ring: Floats, + n: usize, + pos: usize, + batch: usize, + ) -> Result<(), CudaError> { + let what = "ring_store"; + if n == 0 || n > 64 || batch == 0 || batch > MAX_BATCH || !current.len.is_multiple_of(batch) { + return refuse(what, format!("{n} taps, {} floats for a batch of {batch}", current.len)); + } + if n == 1 { + return Ok(()); + } + let channels = current.len / batch; + if channels == 0 || channels > 1 << 24 { + return refuse(what, format!("{channels} channels")); } - Ok(()) + current.check(self.dev, what, batch * channels)?; + ring.check(self.dev, what, (n - 1) * channels)?; + if ring.overlaps(¤t) { + return refuse(what, "the ring overlaps the tokens".into()); + } + let (mut pc, mut pr) = (current.address(), ring.address()); + let (mut c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32); + let mut args = [ptr(&mut pc), ptr(&mut pr), num(&mut c), num(&mut taps_n), big(&mut p), num(&mut b)]; + // SAFETY: the arguments match ring_store(const float*, float*, unsigned, unsigned, + // unsigned long long, unsigned). It reads batch * channels floats of `current` and + // writes at most (n - 1) * channels of `ring`, each slot from one token; all checked. + unsafe { self.ring_store.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } + + /// The keys or values of a batch, `rows` (one row of `width` per token), go to their + /// rows of `history` (`cap` rows): the token at position p to row `p % cap`. + pub fn store_rows( + &self, + rows: Floats, + history: Floats, + width: usize, + cap: usize, + pos: usize, + batch: usize, + ) -> Result<(), CudaError> { + let what = "store_rows"; + // More tokens than rows would write one row twice in one launch. + if width == 0 || cap == 0 || batch == 0 || batch > MAX_BATCH || batch > cap || width > 1 << 24 { + return refuse(what, format!("{batch} rows of {width} into a history of {cap}")); + } + rows.check(self.dev, what, batch * width)?; + history.check(self.dev, what, cap * width)?; + if rows.overlaps(&history) { + return refuse(what, "the rows are inside the history".into()); + } + let (mut pr, mut ph, mut w) = (rows.address(), history.address(), width as u32); + let (mut c, mut p, mut b) = (cap as u64, pos as u64, batch as u32); + let mut args = [ptr(&mut pr), ptr(&mut ph), num(&mut w), big(&mut c), big(&mut p), num(&mut b)]; + // SAFETY: the arguments match store_rows(const float*, float*, unsigned, unsigned + // long long, unsigned long long, unsigned). It reads batch * width floats of `rows` + // and writes that many into rows below `cap` of `history`, no row twice; all checked. + unsafe { self.store_rows.launch((blocks((batch * width) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } } - /// 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. + /// Attention for a batch of `batch` query tokens, the first at position `pos`, whose + /// own keys and values are already in the history: for each query and head, `out` is + /// the sum over the tokens it sees of weight times value, the weights being a softmax + /// over those 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)`. + /// A query at position p sees all tokens up to p, or the last `window` of them. + /// Per query, `q` holds `heads * dim` floats, `relative.rel` `heads * rel_dim` and + /// `sinks` `heads`, query after query. `weights` is scratch of + /// `heads * attend_scratch(pos, window, batch)`. #[allow(clippy::too_many_arguments)] pub fn attend( &self, @@ -267,7 +410,8 @@ impl<'m> Attention<'m> { weights: Floats, out: Floats, pos: usize, - seen: usize, + window: Option, + batch: usize, ) -> Result<(), CudaError> { let what = "attend"; let Heads { heads, kv_heads, dim } = shape; @@ -284,18 +428,31 @@ impl<'m> Attention<'m> { 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)); + if batch == 0 || batch > MAX_BATCH || window == Some(0) { + return refuse(what, format!("a batch of {batch} with a window of {window:?}")); } - let width = kv_heads * dim; - q.check(self.dev, what, heads * dim)?; - out.check(self.dev, what, heads * dim)?; + // Every token the first query sees must still be in its row after the batch's own + // tokens were stored: a token's row is taken by the token `cap` positions later. + let seen_first = window.map_or(pos + 1, |w| (pos + 1).min(w)); + if seen_first + batch - 1 > history.cap { + return refuse( + what, + format!( + "position {pos} sees {seen_first} tokens and its batch has {batch}: more than a history of {}", + history.cap + ), + ); + } + let stride = Self::attend_scratch(pos, window, batch) / batch; + let (width, runs) = (kv_heads * dim, batch * heads); + q.check(self.dev, what, runs * dim)?; + out.check(self.dev, what, runs * 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)?; + rel.check(self.dev, what, runs * rel_dim)?; table.check(self.dev, what, rel_dim * reach)?; - sinks.check(self.dev, what, heads)?; - weights.check(self.dev, what, heads * (seen + 1))?; + sinks.check(self.dev, what, runs)?; + weights.check(self.dev, what, runs * stride)?; 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()); @@ -317,7 +474,9 @@ impl<'m> Attention<'m> { ); 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 p, mut win, mut cap, mut st) = + (pos as u64, window.map_or(0, |w| w as u64), history.cap as u64, stride as u64); + let mut b = batch as u32; let mut scale = 1.0 / (dim as f32).sqrt(); let mut args = [ @@ -334,20 +493,22 @@ impl<'m> Attention<'m> { num(&mut rc), real(&mut scale), big(&mut p), - big(&mut n), + big(&mut win), big(&mut cap), + big(&mut st), + num(&mut b), ]; // 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)? }; + // order and type. attn_scores reads the queries, the keys' rows of the tokens each + // query sees (rows below cap), the relative vectors, columns below `reach` of the + // table and the sinks, and writes into each (query, head) run of `stride` floats at + // most seen + 1 entries, where seen + 1 is at most `stride`. attn_softmax rewrites + // those entries in place, one block of 256 threads per run. attn_values reads them + // and the values' rows and writes runs * dim floats to `out`. Every extent was + // checked above, and nothing written overlaps anything read. + unsafe { self.scores.launch((blocks((runs * stride) as u64, 256)?, 1, 1), (256, 1, 1), &mut args)? }; + let mut args = [ptr(&mut pw), num(&mut h), big(&mut p), big(&mut win), big(&mut st), num(&mut b)]; + unsafe { self.softmax.launch((runs as u32, 1, 1), (256, 1, 1), &mut args)? }; let mut args = [ ptr(&mut pw), ptr(&mut pv), @@ -356,24 +517,38 @@ impl<'m> Attention<'m> { num(&mut kv), num(&mut d), big(&mut p), - big(&mut n), + big(&mut win), big(&mut cap), + big(&mut st), + num(&mut b), ]; - unsafe { self.values.launch((blocks((heads * dim) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + unsafe { self.values.launch((blocks((runs * dim) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } + } + + /// How many floats of scratch `attend` needs per head for a batch of `batch` queries + /// starting at `pos`: for each query, one more than the last query's view. + pub fn attend_scratch(pos: usize, window: Option, batch: usize) -> usize { + let last = pos + batch; + batch * (window.map_or(last, |w| last.min(w)) + 1) } - /// 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> { + /// Softmax in place over each of `runs` runs of `count` scores, one after another. + pub fn softmax_runs(&self, weights: Floats, runs: 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}")); + if runs == 0 || count < 2 || runs > 1 << 16 { + return refuse(what, format!("{runs} runs of {count}; a run has at least 2 scores")); } - 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) } + weights.check(self.dev, what, runs * count)?; + // In the kernel's terms: one head, a window of count - 1 tokens that every position + // has filled, and the sink as the last score of a run. + let (mut pw, mut h, mut p, mut win) = (weights.address(), 1u32, count as u64, count as u64 - 1); + let (mut st, mut b) = (count as u64, runs as u32); + let mut args = [ptr(&mut pw), num(&mut h), big(&mut p), big(&mut win), big(&mut st), num(&mut b)]; + // SAFETY: the arguments match attn_softmax(float*, unsigned, unsigned long long, + // unsigned long long, unsigned long long, unsigned). One block of 256 threads per run + // reads and writes window + 1 = count floats of its run of `count`; runs * count + // floats were checked. + unsafe { self.softmax.launch((runs as u32, 1, 1), (256, 1, 1), &mut args) } } /// In place: `x[i] *= sigmoid(gate[i])`. diff --git a/crates/dluth-cuda/src/expert_ops.rs b/crates/dluth-cuda/src/expert_ops.rs index 2ef5413..30cb61f 100644 --- a/crates/dluth-cuda/src/expert_ops.rs +++ b/crates/dluth-cuda/src/expert_ops.rs @@ -61,8 +61,8 @@ impl<'m> ExpertOps<'m> { unsafe { self.gate.launch(((pairs as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) } } - /// Starts `y[r] = sum_j weights[j] * outs[j][r]` over `count` vectors of `width` floats - /// and returns without waiting. + /// Starts, for each of `batch` positions, `y[b][r] = sum_j weights[b][j] * outs[b][j][r]` + /// over `count` vectors of `width` floats, and returns without waiting. pub fn weighted_sum( &self, outs: &Buffer, @@ -70,33 +70,36 @@ impl<'m> ExpertOps<'m> { y: &Buffer, count: usize, width: usize, + batch: usize, ) -> Result<(), CudaError> { let refuse = |why: String| Err(CudaError::Refused(format!("weighted_sum: {why}"))); let have = |b: &Buffer| self.dev.size_of(b).map_err(unknown); let (outs_have, weights_have, y_have) = (have(outs)?, have(weights)?, have(y)?); - if count == 0 || width == 0 || count > 1 << 16 || width > 1 << 24 { - return refuse(format!("{count} vectors of {width}")); + if count == 0 || width == 0 || batch == 0 || count > 1 << 16 || width > 1 << 24 || batch > 1 << 12 { + return refuse(format!("{batch} positions of {count} vectors of {width}")); } - if count * width * 4 > outs_have || count * 4 > weights_have || width * 4 > y_have { + if batch * count * width * 4 > outs_have || batch * count * 4 > weights_have || batch * width * 4 > y_have { return refuse(format!( - "{count} vectors of {width} with buffers of {outs_have}, {weights_have} and {y_have} bytes" + "{batch} positions of {count} vectors of {width} with buffers of {outs_have}, {weights_have} and {y_have} bytes" )); } if y.handle == outs.handle || y.handle == weights.handle || outs.handle == weights.handle { return refuse("one buffer used for two of the three arguments".into()); } - let (mut po, mut pw, mut py, mut c, mut w) = - (outs.handle, weights.handle, y.handle, count as u32, width as u32); + let (mut po, mut pw, mut py, mut c, mut w, mut b) = + (outs.handle, weights.handle, y.handle, count as u32, width as u32, batch as u32); let mut args = [ &mut po as *mut u64 as *mut c_void, &mut pw as *mut u64 as *mut c_void, &mut py as *mut u64 as *mut c_void, &mut c as *mut u32 as *mut c_void, &mut w as *mut u32 as *mut c_void, + &mut b as *mut u32 as *mut c_void, ]; // SAFETY: the arguments match weighted_sum(const float*, const float*, float*, - // unsigned, unsigned). The kernel reads count * width floats from `outs` and count - // from `weights`, and writes width floats to `y`; all checked above. - unsafe { self.sum.launch(((width as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) } + // unsigned, unsigned, unsigned). The kernel reads batch * count * width floats from + // `outs` and batch * count from `weights`, and writes batch * width floats to `y`; + // all checked above. + unsafe { self.sum.launch((((batch * width) as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) } } } diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs index 8108a86..3607c49 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs @@ -250,7 +250,7 @@ impl Products for CudaProducts<'_> { self.blockmat .run(second, &jobs(layer.second, &|j| j * inner), &d_act, &d_outs, &jobs_second, SEGS) .map_err(failed)?; - self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h).map_err(failed)?; + self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h, 1).map_err(failed)?; self.receive(&dy, out)?; let mut stats = self.stats.borrow_mut(); stats.expert_launches += 1; diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index dec93f7..acf8619 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -2,10 +2,13 @@ //! //! `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. +//! vectors that never leave the device. A value is a batch: one vector for each of up to +//! `MAX_BATCH` consecutive positions, one after another in one buffer, and every kernel +//! takes the whole batch in one launch. A batch waits for the device for three reasons: +//! once to copy its embeddings in, once per layer pass to read back the 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, +//! however many positions the batch holds. //! //! 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 @@ -15,8 +18,8 @@ //! 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}; +use crate::attention::{Attention, Heads, History, Late, Relative, MAX_BATCH}; +use crate::blockmat::{BlockFormat, BlockMat, BlockMatrices, Job, JOB_VECTORS}; use crate::device::CudaDevice; use crate::error::CudaError; use crate::expert_ops::ExpertOps; @@ -29,7 +32,7 @@ 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::collections::{BTreeMap, HashMap}; use std::rc::Rc; /// Threads per row for the matrix kernels: the measured best on the real shapes. @@ -48,6 +51,8 @@ struct Pool { struct Slot { buffer: Buffer, len: usize, + /// How many positions the floats belong to: `len / count` floats each. + count: usize, pool: Rc>, } @@ -60,8 +65,9 @@ impl Drop for Slot { } } -/// 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. +/// A batch of vectors on the device: one for each of a few consecutive positions, one after +/// another. 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); @@ -74,6 +80,16 @@ impl DeviceVec { self.0.len == 0 } + /// How many positions it holds. + pub fn count(&self) -> usize { + self.0.count + } + + /// Floats per position. + pub fn width(&self) -> usize { + self.0.len / self.0.count + } + fn all(&self) -> Floats<'_> { Floats::first(&self.0.buffer, self.0.len) } @@ -85,11 +101,27 @@ impl DeviceVec { } } -/// Candidates normalized for blending: `count` vectors of `width`, one after another. +/// Candidates normalized for blending: for each position of a batch, `count` vectors of +/// `width`, one after another. pub struct DeviceBlend { data: DeviceVec, count: usize, width: usize, + batch: usize, +} + +/// The results of several matrices applied to one input: see `CudaOps::products`. +struct Cut { + vecs: Vec, + /// For each matrix: which of `vecs` holds its result, where, and how many floats. + parts: Vec<(usize, usize, usize)>, +} + +impl Cut { + fn part(&self, i: usize) -> Floats<'_> { + let (v, at, len) = self.parts[i]; + self.vecs[v].part(at, len) + } } /// What one application of a layer remembers between tokens, on the device. @@ -105,8 +137,8 @@ pub struct DevicePass { 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. + /// The position of the first token of the batch 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, @@ -191,8 +223,14 @@ impl<'m> CudaOps<'m> { self.weight_bytes } - /// A vector of `len` floats, contents unspecified, from the pool or freshly made. + /// `len` floats for one position, contents unspecified. fn vec(&self, len: usize) -> Result { + self.vecs(1, len) + } + + /// `count` vectors of `width` floats, contents unspecified, from the pool or freshly made. + fn vecs(&self, count: usize, width: usize) -> Result { + let len = count * width; if len == 0 { return Err(ModelError::Device("an empty device vector".into())); } @@ -205,7 +243,7 @@ impl<'m> CudaOps<'m> { Some(buffer) => buffer, None => self.dev.alloc(bytes).map_err(failed)?, }; - Ok(DeviceVec(Rc::new(Slot { buffer, len, pool: self.pool.clone() }))) + Ok(DeviceVec(Rc::new(Slot { buffer, len, count, pool: self.pool.clone() }))) } fn wait(&self) -> Result<(), ModelError> { @@ -222,9 +260,9 @@ impl<'m> CudaOps<'m> { 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())?; + /// `count` vectors on the device holding `values`. Waits for the device first. + fn send(&mut self, values: &[f32], count: usize) -> Result { + let v = self.vecs(count, values.len() / count)?; self.wait()?; self.copy_in(&v.0.buffer, values)?; Ok(v) @@ -332,23 +370,65 @@ impl<'m> CudaOps<'m> { self.small.rmsnorm(x, Floats::first(&ones, n), out, eps).map_err(failed) } - /// `w` (BF16, `rows` by `cols`) times `x`. + /// `w` (BF16, `rows` by `cols`) times each vector of `x`. fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &DeviceVec) -> Result { - if w.len() != rows * cols * 2 || x.len() != cols { + if w.len() != rows * cols * 2 || x.width() != cols { return Err(ModelError::Device(format!( - "a BF16 product of {rows} by {cols} with {} weight bytes and {} inputs", + "a BF16 product of {rows} by {cols} with {} weight bytes and inputs of {}", w.len(), - x.len() + x.width() ))); } let weights = self.weight(w)?; - let y = self.vec(rows)?; + let y = self.vecs(x.count(), rows)?; self.matmat - .bf16(Bf16Matrix { buffer: &weights, offset: 0, rows, cols }, &x.0.buffer, 1, &y.0.buffer, SEGS) + .bf16(Bf16Matrix { buffer: &weights, offset: 0, rows, cols }, &x.0.buffer, x.count(), &y.0.buffer, SEGS) .map_err(failed)?; Ok(y) } + /// Several matrices of `cols` columns applied to the same input. They are stacked in one + /// device buffer. For one position that is one product, whose result is cut into the + /// parts. For a batch each matrix is its own product, so that each result holds the + /// positions one after another, as the kernels that read it expect. + fn products(&mut self, parts: &[(&[u8], usize)], cols: usize, x: &DeviceVec) -> Result { + if parts.iter().any(|(w, rows)| w.len() != rows * cols * 2) || x.width() != cols { + return Err(ModelError::Device(format!( + "stacked matrices of {:?} bytes for an input of {}", + parts.iter().map(|(w, _)| w.len()).collect::>(), + x.width() + ))); + } + let slices: Vec<&[u8]> = parts.iter().map(|(w, _)| *w).collect(); + let stacked = self.stacked(&slices, cols)?; + let batch = x.count(); + if batch == 1 { + let rows: usize = parts.iter().map(|(_, rows)| rows).sum(); + let all = self.vec(rows)?; + self.matmat + .bf16(Bf16Matrix { buffer: &stacked, offset: 0, rows, cols }, &x.0.buffer, 1, &all.0.buffer, SEGS) + .map_err(failed)?; + let mut at = 0; + let mut cuts = Vec::new(); + for &(_, rows) in parts { + cuts.push((0, at, rows)); + at += rows; + } + return Ok(Cut { vecs: vec![all], parts: cuts }); + } + let (mut vecs, mut cuts, mut offset) = (Vec::new(), Vec::new(), 0); + for (i, &(_, rows)) in parts.iter().enumerate() { + let y = self.vecs(batch, rows)?; + self.matmat + .bf16(Bf16Matrix { buffer: &stacked, offset, rows, cols }, &x.0.buffer, batch, &y.0.buffer, SEGS) + .map_err(failed)?; + offset += rows * cols * 2; + cuts.push((i, 0, batch * rows)); + vecs.push(y); + } + Ok(Cut { vecs, parts: cuts }) + } + /// 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 { @@ -365,9 +445,14 @@ impl<'m> CudaOps<'m> { } } - /// 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. + /// The chosen experts for each position of `input`: both matrix products of each, the + /// activation between them, and the weighted sum. `chosen` holds, position after + /// position, the same number of (expert, weight) pairs. The caller has just waited for + /// the device (to read the router's scores), which is what makes the copy of the job + /// lists safe. + /// + /// An expert chosen by several positions is one job: its matrix is read once for all of + /// them. fn expert_layer( &mut self, cfg: &InklingConfig, @@ -377,13 +462,15 @@ impl<'m> CudaOps<'m> { ) -> 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 { + let batch = input.count(); + let total = chosen.len(); + if total == 0 || !total.is_multiple_of(batch) || input.width() != 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() + "{total} experts for {batch} positions, of {pairs2} by {h} then {h_out} by {inner}, with inputs of {}", + input.width() ))); } + let n = total / batch; let stored = |ops: &mut Self, m: &ExpertMatrices| -> Result<(Buffer, Buffer, BlockFormat), ModelError> { let format = match m.format() { ExpertFormat::Nvfp4 => BlockFormat::Nvfp4, @@ -394,33 +481,41 @@ impl<'m> CudaOps<'m> { let (values1, scales1, format1) = stored(self, first)?; let (values2, scales2, format2) = stored(self, second)?; let dev = self.dev; - let (both, act, outs, y) = (self.vec(n * pairs2)?, self.vec(n * inner)?, self.vec(n * h)?, self.vec(h)?); + let (both, act) = (self.vec(total * pairs2)?, self.vec(total * inner)?); + let (outs, y) = (self.vec(total * h)?, self.vecs(batch, h)?); + // Which slots (position times n, plus the place among that position's experts) want + // each expert, experts in ascending order. + let mut wanted: BTreeMap> = BTreeMap::new(); + for (slot, &(expert, _)) in chosen.iter().enumerate() { + wanted.entry(expert).or_default().push(slot); + } 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 mut jobs = Vec::new(); + for (&expert, slots) in &wanted { + for group in slots.chunks(JOB_VECTORS) { + jobs.push(Job { + values: expert * per_values, + scales: expert * per_scales, + factor: m.factor(expert), + vectors: group.iter().map(|&slot| (vector(slot), slot)).collect(), + }); + } + } + jobs }; 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. - let list1 = - self.blockmat.encode(m1, &jobs(first, &|_| 0), &input.0.buffer, &both.0.buffer, SEGS).map_err(failed)?; - let list2 = self - .blockmat - .encode(m2, &jobs(second, &|j| j * inner), &act.0.buffer, &outs.0.buffer, SEGS) - .map_err(failed)?; + // An expert's first matrix reads the input of each position that chose it; its second + // reads the activation in the same slot. + let (jobs1, jobs2) = (jobs(first, &|slot| (slot / n) * h), jobs(second, &|slot| slot * inner)); + let count = jobs1.len(); + let list1 = self.blockmat.encode(m1, &jobs1, &input.0.buffer, &both.0.buffer, SEGS).map_err(failed)?; + let list2 = self.blockmat.encode(m2, &jobs2, &act.0.buffer, &outs.0.buffer, SEGS).map_err(failed)?; // Everything the host hands over for this step goes in one copy: the experts' // weights, padded to a whole number of 8-byte words, then the two job lists. - let weights_bytes = (n * 4).next_multiple_of(8); + let weights_bytes = (total * 4).next_multiple_of(8); self.staging.clear(); self.staging.extend(chosen.iter().flat_map(|&(_, w)| w.to_le_bytes())); self.staging.resize(weights_bytes, 0); @@ -432,40 +527,38 @@ impl<'m> CudaOps<'m> { let (at1, at2) = (route.handle + weights_bytes as u64, route.handle + (weights_bytes + list1.len()) as u64); // SAFETY (both): each list is the one `encode` returned for the same matrices and - // buffers, copied unchanged into `route`, which is not written again before the next - // wait for the device (the next copy into it follows the next layer's router fetch). - unsafe { self.blockmat.start(m1, n, &input.0.buffer, &both.0.buffer, at1, SEGS) }.map_err(failed)?; + // buffers, with `count` jobs, copied unchanged into `route`, which is not written + // again before the next wait for the device (the next copy into it follows the next + // layer's router fetch). + unsafe { self.blockmat.start(m1, count, &input.0.buffer, &both.0.buffer, at1, SEGS) }.map_err(failed)?; self.expert_ops - .capped_gate_pairs(&both.0.buffer, &act.0.buffer, n * inner, cfg.gate_cap, cfg.up_cap) + .capped_gate_pairs(&both.0.buffer, &act.0.buffer, total * inner, cfg.gate_cap, cfg.up_cap) .map_err(failed)?; - unsafe { self.blockmat.start(m2, n, &act.0.buffer, &outs.0.buffer, at2, SEGS) }.map_err(failed)?; - self.expert_ops.weighted_sum(&outs.0.buffer, &route, &y.0.buffer, n, h).map_err(failed)?; + unsafe { self.blockmat.start(m2, count, &act.0.buffer, &outs.0.buffer, at2, SEGS) }.map_err(failed)?; + self.expert_ops.weighted_sum(&outs.0.buffer, &route, &y.0.buffer, n, h, batch).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(); + let (channels, batch) = (x.width(), x.count()); 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)?; + let out = self.vecs(batch, channels)?; + let ring = Floats::first(ring, (n - 1) * channels); self.attention - .sconv_fixed( - x.all(), - Floats::first(ring, (n - 1) * channels), - Floats::first(&taps, n * channels), - out.all(), - n, - pos, - ) + .sconv_fixed(x.all(), ring, Floats::first(&taps, n * channels), out.all(), n, pos, batch) .map_err(failed)?; + if batch > 1 { + self.attention.ring_store(x.all(), ring, n, pos, batch).map_err(failed)?; + } Ok(out) } - /// A token's keys or values before the per-head step: project, then convolve over the + /// A batch'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( @@ -479,13 +572,13 @@ impl<'m> CudaOps<'m> { out: Floats, ) -> Result<(), ModelError> { let width = cfg.kv_heads * cfg.head_dim; - let n = cfg.conv_taps; + let (n, batch) = (cfg.conv_taps, input.count()); 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) + self.attention.sconv_fixed(projected.all(), ring, Floats::first(&taps, n * width), out, n, pos, batch) } KvConv::Dynamic { fixed_taps, token_proj } => { let token_taps = self.bf16(token_proj, cfg.kv_heads * n, cfg.hidden, input)?; @@ -499,10 +592,15 @@ impl<'m> CudaOps<'m> { n, cfg.kv_heads, pos, + batch, ) } } - .map_err(failed) + .map_err(failed)?; + if batch > 1 { + self.attention.ring_store(projected.all(), ring, n, pos, batch).map_err(failed)?; + } + Ok(()) } } @@ -514,8 +612,10 @@ impl<'m> Ops for CudaOps<'m> { 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)); + // A layer with a window needs the rows of the window, and more for a batch: the + // first token of a batch still sees tokens whose rows, with only `window` of them, + // the batch's later tokens would take. + let cap = window.map_or(max_seq, |w| (w + MAX_BATCH - 1).min(max_seq)); let alloc = |floats: usize| self.dev.alloc(floats.max(1) * 4).map_err(failed); Ok(DevicePass { keys: alloc(cap * width)?, @@ -539,16 +639,21 @@ impl<'m> Ops for CudaOps<'m> { Ok(()) } - fn count(&self, _x: &DeviceVec) -> usize { - // One position at a time for now: see `embed`. - 1 + fn count(&self, x: &DeviceVec) -> usize { + x.count() } fn row(&mut self, x: &DeviceVec, index: usize) -> Result { - if index != 0 { - return Err(ModelError::Capacity(format!("position {index} of a batch of 1"))); + let (count, width) = (x.count(), x.width()); + if index >= count { + return Err(ModelError::Capacity(format!("position {index} of a batch of {count}"))); + } + if count == 1 { + return Ok(x.clone()); } - Ok(x.clone()) + let out = self.vec(width)?; + self.small.copy(x.part(index * width, width), out.all()).map_err(failed)?; + Ok(out) } fn embed( @@ -558,58 +663,71 @@ impl<'m> Ops for CudaOps<'m> { norm: &[f32], tokens: &[u32], ) -> Result { - // The device operations do not take batches yet. Refused here, where a batch enters - // the forward pass, before anything is computed. - let &[token] = tokens else { + // Refused here, where a batch enters the forward pass, before anything is computed. + if tokens.is_empty() || tokens.len() > MAX_BATCH { return Err(ModelError::Capacity(format!( - "a batch of {} tokens: the device operations take one position at a time so far", + "a batch of {} tokens: the device operations take 1 to {MAX_BATCH} positions at a time", tokens.len() ))); - }; - // One row of the table, normalized on the host: 2,304 floats, once per token. + } + // One row of the table per token, normalized on the host: 2,304 floats each. 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) + let mut x = vec![0.0f32; tokens.len() * h]; + for (&token, out) in tokens.iter().zip(x.chunks_exact_mut(h)) { + 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(); + cpu::rmsnorm(&raw, norm, cfg.eps, out); + } + self.send(&x, tokens.len()) } 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 (width, batch) = candidates.first().map_or((0, 0), |c| (c.width(), c.count())); + if count == 0 || candidates.iter().any(|c| c.width() != width || c.count() != batch) { + return Err(ModelError::Device(format!("a blend of {count} candidates of unequal or no size"))); } - let data = self.vec(count * width)?; + // Each position's candidates one after another, position after position. + let data = self.vecs(batch, count * width)?; if count <= MANY { let runs: Vec = candidates.iter().map(|c| c.all()).collect(); - self.small.normalize_many(&runs, data.all(), BLEND_EPS).map_err(failed)?; + self.small.normalize_many(&runs, data.all(), BLEND_EPS, batch).map_err(failed)?; } else { - for (j, candidate) in candidates.iter().enumerate() { - self.rmsnorm_plain(candidate.all(), data.part(j * width, width), BLEND_EPS)?; + for b in 0..batch { + for (j, candidate) in candidates.iter().enumerate() { + let out = data.part((b * count + j) * width, width); + self.rmsnorm_plain(candidate.part(b * width, width), out, BLEND_EPS)?; + } } } - Ok(DeviceBlend { data, count, width }) + Ok(DeviceBlend { data, count, width, batch }) } fn mix(&mut self, blend: &DeviceBlend, query: &[f32]) -> Result { - let (count, width) = (blend.count, blend.width); + let (count, width, batch) = (blend.count, blend.width, blend.batch); let query = self.param(query)?; - let out = self.vec(width)?; + let out = self.vecs(batch, width)?; if count <= BLEND_MAX { self.small .blend_mix(Floats::first(&query, width), blend.data.all(), out.all(), count, width) .map_err(failed)?; return Ok(out); } - let 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)?; + let scores = self.vec(batch * count)?; + for b in 0..batch { + self.small + .blend_scores( + Floats::first(&query, width), + blend.data.part(b * count * width, count * width), + scores.part(b * count, count), + count, + width, + ) + .map_err(failed)?; + } + self.attention.softmax_runs(scores.all(), batch, count).map_err(failed)?; self.expert_ops - .weighted_sum(&blend.data.0.buffer, &scores.0.buffer, &out.0.buffer, count, width) + .weighted_sum(&blend.data.0.buffer, &scores.0.buffer, &out.0.buffer, count, width, batch) .map_err(failed)?; Ok(out) } @@ -621,42 +739,31 @@ impl<'m> Ops for CudaOps<'m> { 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. - if gate.forget.len() != h * cfg.gate_rank * 2 || gate.gain.len() != gate.forget.len() { + let (h, batch) = (cfg.hidden, x.count()); + if x.width() != h || message.width() != h || message.count() != batch { return Err(ModelError::Device(format!( - "gate matrices of {} and {} bytes for {h} by {}", - gate.forget.len(), - gate.gain.len(), - cfg.gate_rank + "a merge of {} by {} with {} by {}", + batch, + x.width(), + message.count(), + message.width() ))); } - let stacked = self.stacked(&[gate.forget, gate.gain], cfg.gate_rank)?; - 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)?; + // For each position: the token and its message, both normalized, as one vector. + let both = self.vecs(batch, 2 * h)?; + self.small.normalize_many(&[x.all(), message.all()], both.all(), cfg.eps, batch).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. + let gates = self.products(&[(gate.forget, h), (gate.gain, h)], cfg.gate_rank, &inner)?; + let out = self.vecs(batch, h)?; + self.small.gate_merge(x.all(), message.all(), gates.part(0), gates.part(1), out.all()).map_err(failed)?; Ok(out) } fn rmsnorm(&mut self, x: &DeviceVec, weights: &[f32], eps: f32) -> Result { - let n = x.len(); + let n = x.width(); let weights = self.param(weights)?; - let out = self.vec(n)?; + let out = self.vecs(x.count(), n)?; self.small.rmsnorm(x.all(), Floats::first(&weights, n), out.all(), eps).map_err(failed)?; Ok(out) } @@ -672,38 +779,33 @@ impl<'m> Ops for CudaOps<'m> { 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; + let batch = q_in.count(); + if k_in.count() != batch || v_in.count() != batch { + return Err(ModelError::Device(format!( + "attention inputs of {batch}, {} and {} positions", + k_in.count(), + v_in.count() + ))); + } // 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 { + if pos >= pass.max_seq || batch > pass.max_seq - pos { return Err(ModelError::Capacity(format!( - "position {pos} is outside the history of {} positions", + "positions {pos} to {} are outside the history of {} positions", + pos + batch - 1, 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) }; + let late = if layer.local { Late::none() } else { Late { pos, floor: cfg.log_floor, alpha: cfg.log_alpha } }; // Four matrices read the query input: the queries, the output gate, the - // relative-position vectors and the sinks. Stacked on the device, they are one - // product; its result is cut back into the four. + // relative-position vectors and the sinks. let rel_width = heads * cfg.rel_dim; let sizes = [(layer.wq, q_width), (layer.out_gate, q_width), (layer.wr, rel_width), (layer.sink, heads)]; - if sizes.iter().any(|(w, rows)| w.len() != rows * h * 2) || q_in.len() != h { - return Err(ModelError::Device(format!( - "attention matrices of {:?} bytes for an input of {}", - sizes.map(|(w, _)| w.len()), - q_in.len() - ))); - } - let rows = 2 * q_width + rel_width + heads; - let stacked = self.stacked(&sizes.map(|(w, _)| w), h)?; - let from_q = self.vec(rows)?; - self.matmat - .bf16(Bf16Matrix { buffer: &stacked, offset: 0, rows, cols: h }, &q_in.0.buffer, 1, &from_q.0.buffer, SEGS) - .map_err(failed)?; - let (q, gate) = (from_q.part(0, q_width), from_q.part(q_width, q_width)); - let (rel, sinks) = (from_q.part(2 * q_width, rel_width), from_q.part(2 * q_width + rel_width, heads)); + let from_q = self.products(&sizes, h, q_in)?; + let (q, gate, rel, sinks) = (from_q.part(0), from_q.part(1), from_q.part(2), from_q.part(3)); // Queries: learned scale per element, length limit per head. let q_scale = self.param(&layer.q_scale)?; @@ -711,16 +813,28 @@ impl<'m> Ops for CudaOps<'m> { .head_scale_clip(q, 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)?; + // Keys: length limit per head. Values: normalized per head. Both go into the rows of + // the history for these positions: directly when the rows are one run, by way of a + // copy when they wrap around the end of the history. + let first_row = pos % pass.cap; + let wraps = first_row + batch > pass.cap; + let keys_all = Floats::first(&pass.keys, pass.cap * width); + let values_all = Floats::first(&pass.values, pass.cap * width); + let rows_of = |buffer| Floats { buffer, at: first_row * width, len: batch * width }; + let aside = if wraps { Some((self.vecs(batch, width)?, self.vecs(batch, width)?)) } else { None }; + let (key_rows, value_rows) = match &aside { + Some((k, v)) => (k.all(), v.all()), + None => (rows_of(&pass.keys), rows_of(&pass.values)), + }; + self.project_kv(cfg, layer.wk, &layer.k_conv, &pass.k_ring, pos, k_in, key_rows)?; + self.attention.head_scale_clip(key_rows, None, kv_heads, d, cfg.qk_clip, Late::none()).map_err(failed)?; + let unnormed = self.vecs(batch, 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)?; + self.attention.head_rmsnorm_plain(unnormed.all(), value_rows, batch * kv_heads, d, cfg.eps).map_err(failed)?; + if wraps { + self.attention.store_rows(key_rows, keys_all, width, pass.cap, pos, batch).map_err(failed)?; + self.attention.store_rows(value_rows, values_all, width, pass.cap, pos, batch).map_err(failed)?; + } // Relative position: each head turns a small vector into a preference per distance. let rel_scale = self.param(&layer.rel_scale)?; @@ -729,17 +843,13 @@ impl<'m> Ops for CudaOps<'m> { .map_err(failed)?; let table = self.param(&layer.rel_table)?; - 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)?); + let scratch = heads * Attention::attend_scratch(pos, pass.window, batch); + let (weights, attended) = (self.vec(scratch)?, self.vecs(batch, q_width)?); self.attention .attend( Heads { heads, kv_heads, dim: d }, q, - History { - keys: Floats::first(&pass.keys, pass.cap * width), - values: Floats::first(&pass.values, pass.cap * width), - cap: pass.cap, - }, + History { keys: keys_all, values: values_all, cap: pass.cap }, Relative { rel, table: Floats::first(&table, cfg.rel_dim * layer.reach), @@ -750,7 +860,8 @@ impl<'m> Ops for CudaOps<'m> { weights.all(), attended.all(), pos, - seen, + pass.window, + batch, ) .map_err(failed)?; @@ -768,16 +879,27 @@ impl<'m> Ops for CudaOps<'m> { } fn add(&mut self, a: &DeviceVec, b: &DeviceVec) -> Result { - let out = self.vec(a.len())?; + if a.len() != b.len() || a.count() != b.count() { + return Err(ModelError::Device(format!("a sum of {} and {} floats", a.len(), b.len()))); + } + let out = self.vecs(a.count(), a.width())?; 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. + // The router's scores for every position come back to the host in one copy, and the + // experts are chosen there, position by position. 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); + let mut chosen = Vec::new(); + for position in scores.chunks_exact(cfg.experts) { + let mine = router::choose(position, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); + if mine.len() != cfg.experts_per_token.min(cfg.experts) { + return Err(ModelError::Device("positions of a batch chose different numbers of experts".into())); + } + chosen.extend(mine); + } self.expert_layer(cfg, layer, &chosen, x) } diff --git a/crates/dluth-cuda/src/small.rs b/crates/dluth-cuda/src/small.rs index d3c5c64..e0098de 100644 --- a/crates/dluth-cuda/src/small.rs +++ b/crates/dluth-cuda/src/small.rs @@ -40,6 +40,7 @@ pub struct Small<'m> { softcap: Kernel<'m>, blend_mix: Kernel<'m>, normalize_many: Kernel<'m>, + copy: Kernel<'m>, } impl<'m> Small<'m> { @@ -53,6 +54,7 @@ impl<'m> Small<'m> { softcap: module.kernel("softcap_inplace")?, blend_mix: module.kernel("blend_mix")?, normalize_many: module.kernel("normalize_many")?, + copy: module.kernel("vec_copy")?, }) } @@ -83,20 +85,38 @@ impl<'m> Small<'m> { unsafe { self.add.launch(grid(n), (256, 1, 1), &mut args) } } + /// `out = x` for `out.len` floats. + pub fn copy(&self, x: Floats, out: Floats) -> Result<(), CudaError> { + let n = out.len; + self.runs("vec_copy", n, &[x], &out)?; + let (mut px, mut po, mut count) = (x.address(), out.address(), n as u32); + let mut args = [ptr(&mut px), ptr(&mut po), num(&mut count)]; + // SAFETY: the arguments match vec_copy(const float*, float*, unsigned); it reads n + // floats of `x` and writes n to `out`, both checked. + unsafe { self.copy.launch(grid(n), (256, 1, 1), &mut args) } + } + + /// For each of the vectors of `weights.len` floats in `x`: /// `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 (n, total) = (weights.len, out.len); + if n == 0 || !total.is_multiple_of(n) || total / n > 1 << 16 { + return refuse(what, format!("{total} floats in vectors of {n}")); } - 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)]; + self.runs(what, total, &[x], &out)?; + weights.check(self.dev, what, n)?; + if weights.overlaps(&out) || eps < 0.0 || !eps.is_finite() { + return refuse(what, format!("eps {eps}, or the weights overlap the output")); + } + let (mut px, mut pw, mut po) = (x.address(), weights.address(), out.address()); + let (mut count, mut e, mut batch) = (n as u32, eps, (total / n) as u32); + let mut args = [ptr(&mut px), ptr(&mut pw), ptr(&mut po), num(&mut count), real(&mut e), num(&mut batch)]; // 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) } + // unsigned, float, unsigned). One block of 256 threads (within the kernel's shared + // array) per vector reads n floats of `x` and of `weights` and writes n to `out`; + // batch * n floats of `x` and `out` and n of `weights` were checked. + unsafe { self.rmsnorm.launch((batch, 1, 1), (256, 1, 1), &mut args) } } /// `scores[j] = (query . candidate_j) / sqrt(width)` for `count` candidates of `width` @@ -128,8 +148,10 @@ impl<'m> Small<'m> { unsafe { self.blend_scores.launch((count as u32, 1, 1), (256, 1, 1), &mut args) } } - /// A whole blend in one launch: `out = sum_j softmax_j((query . candidate_j) / sqrt(width)) - /// * candidate_j` over `count` candidates of `width` floats in `candidates`. + /// A whole blend in one launch, for each position of a batch: + /// `out = sum_j softmax_j((query . candidate_j) / sqrt(width)) * candidate_j` over `count` + /// candidates of `width` floats. `candidates` holds each position's candidates one after + /// another, position after position; the batch is `out.len / width`. pub fn blend_mix( &self, query: Floats, @@ -139,48 +161,64 @@ impl<'m> Small<'m> { width: usize, ) -> Result<(), CudaError> { let what = "blend_mix"; - if count == 0 || count > BLEND_MAX || width == 0 || width > 1 << 24 { + if count == 0 || count > BLEND_MAX || width == 0 || width > 1 << 24 || !out.len.is_multiple_of(width) { return refuse(what, format!("{count} candidates of {width}; at most {BLEND_MAX} candidates")); } + let batch = out.len / width; + if batch == 0 || batch > 1 << 16 { + return refuse(what, format!("a batch of {batch}")); + } query.check(self.dev, what, width)?; - candidates.check(self.dev, what, count * width)?; - out.check(self.dev, what, width)?; + candidates.check(self.dev, what, batch * count * width)?; + out.check(self.dev, what, batch * width)?; if out.overlaps(&query) || out.overlaps(&candidates) { return refuse(what, "the output overlaps an input".into()); } let (mut pq, mut pc, mut po) = (query.address(), candidates.address(), out.address()); - let (mut c, mut w, mut scale) = (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)]; + let (mut c, mut w, mut scale, mut b) = (count as u32, width as u32, 1.0 / (width as f32).sqrt(), batch as u32); + let mut args = + [ptr(&mut pq), ptr(&mut pc), ptr(&mut po), num(&mut c), num(&mut w), real(&mut scale), num(&mut b)]; // SAFETY: the arguments match blend_mix(const float*, const float*, float*, unsigned, - // unsigned, float). 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) } + // unsigned, float, unsigned). One block of 256 threads per position, the size of the + // kernel's shared rows, with at most BLEND_MAX candidates, the number of those rows; + // it reads `width` floats of the query and batch * count * width of the candidates + // and writes batch * width to `out`. All checked. + unsafe { self.blend_mix.launch((batch as u32, 1, 1), (256, 1, 1), &mut args) } } - /// Up to `MANY` 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> { + /// Up to `MANY` candidates, each a batch of `batch` vectors, normalized into `out` so + /// that each position's candidates are one after another: + /// `out[b][j] = x_j[b] / sqrt(mean(x_j[b]^2) + eps)`. + pub fn normalize_many(&self, vectors: &[Floats], out: Floats, eps: f32, batch: usize) -> 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)); + if count == 0 + || count > MANY + || batch == 0 + || batch > 1 << 12 + || !out.len.is_multiple_of(count * batch) + || eps < 0.0 + || !eps.is_finite() + { + return refuse( + what, + format!("{count} candidates of {batch} into {} floats, eps {eps}; at most {MANY}", out.len), + ); } - let width = out.len / count; + let width = out.len / (count * batch); if width == 0 || width > 1 << 24 { return refuse(what, format!("vectors of {width}")); } - out.check(self.dev, what, count * width)?; + out.check(self.dev, what, batch * count * width)?; let mut pointers = [0u64; MANY]; for (slot, v) in pointers.iter_mut().zip(vectors) { - v.check(self.dev, what, width)?; + v.check(self.dev, what, batch * 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 (mut po, mut c, mut w, mut e, mut n) = (out.address(), count as u32, width as u32, eps, batch as u32); let [a, b, cc, d, f, g, h, i] = &mut pointers; let mut args = [ ptr(a), @@ -195,12 +233,14 @@ impl<'m> Small<'m> { num(&mut c), num(&mut w), real(&mut e), + num(&mut n), ]; // 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) } + // unsigned, float, unsigned). One block of 256 threads per vector reads `width` + // floats, within batch * width of one of the first `count` pointers (the others are + // never touched), and writes them into batch * count * width floats of `out`. All + // checked. + unsafe { self.normalize_many.launch(((count * batch) as u32, 1, 1), (256, 1, 1), &mut args) } } /// `out[i] = (1 - tanh(forget[i])) * x[i] + tanh(gain[i]) * message[i]`. diff --git a/crates/dluth-cuda/tests/attention.rs b/crates/dluth-cuda/tests/attention.rs index 1df93e2..80c858f 100644 --- a/crates/dluth-cuda/tests/attention.rs +++ b/crates/dluth-cuda/tests/attention.rs @@ -2,7 +2,7 @@ //! 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::attention::{Attention, Heads, History, Late, Relative, MAX_BATCH}; use dluth_cuda::floats::Floats; use dluth_cuda::{CudaDevice, CudaError, Module}; use dluth_kernels::{cpu, sconv, sinkattn}; @@ -57,36 +57,49 @@ fn scaling_clipping_and_the_late_factor_match_the_cpu() { 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. + // lengths, so that some are over the clip and some under; one all zeros. Batches of one + // and of several positions; the several straddle the position where the late factor + // stops being 1 (a floor of 16: positions 13, 14 and 15 are before it). 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 (batch, pos) in [(1usize, 40usize), (5, 13), (MAX_BATCH, 0)] { + let mut x: Vec = Vec::new(); + for v in 0..batch * heads { + let size = [0.0, 0.01, 1.0, 5.0, 40.0][v % 5]; + x.extend(rng.vec(dim, size)); } - for head in want.chunks_exact_mut(dim) { - cpu::l2_clip_inplace(head, clip); - head.iter_mut().for_each(|v| *v *= late); + let scale = rng.vec(heads * dim, 1.5); + for (with_scale, late) in [(true, Late { pos, floor: 16.0, alpha: 0.1 }), (false, Late::none())] { + 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, batch * heads * dim), s, heads, dim, clip, late).unwrap(); + let got = download(&dev, &dx, batch * heads * dim); + let mut want = x.clone(); + let (mut clipped, mut left_alone, mut factors) = (false, false, Vec::new()); + for (b, position) in want.chunks_exact_mut(heads * dim).enumerate() { + if with_scale { + position.iter_mut().zip(&scale).for_each(|(v, s)| *v *= s); + } + let factor = cpu::log_scale(late.pos + b, late.floor, late.alpha); + factors.push(factor); + for head in position.chunks_exact_mut(dim) { + cpu::l2_clip_inplace(head, clip); + let length = head.iter().map(|v| v * v).sum::().sqrt(); + clipped |= (length - clip).abs() < 1e-3 * clip; + left_alone |= length > 0.0 && length < 0.5 * clip; + head.iter_mut().for_each(|v| *v *= factor); + } + } + // A product of up to four factors: one from a sum of squares that the device + // may round differently in its last bits, one from a logarithm computed on + // the device. + close("head_scale_clip", &got, &want, |i| want[i].abs(), 16.0); + assert!(clipped && left_alone, "the case should clip some heads and leave some alone"); + if with_scale && batch == 5 { + assert!(factors[..3].iter().all(|f| *f == 1.0) && factors[3] > 1.0 && factors[4] > factors[3]); + } + dev.free(dx).unwrap(); + dev.free(ds).unwrap(); } - // 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(); } } } @@ -129,12 +142,16 @@ fn both_short_convolutions_match_the_cpu_token_after_token() { 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. + // One tap (no memory at all), two, and the model's four; channels not a multiple of + // anything. The tokens come in batches of every kind: single tokens, batches shorter + // than the memory, as long as it, longer, and the most a launch takes. + let batches = [1usize, 1, 3, 2, 1, 5, MAX_BATCH, 1, 4, 2]; 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 most = MAX_BATCH * channels; 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(); + (upload(&dev, &fixed_taps), dev.alloc(most * 4).unwrap(), dev.alloc(most * 4).unwrap()); + let d_token_taps = dev.alloc(MAX_BATCH * 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]; @@ -142,146 +159,184 @@ fn both_short_convolutions_match_the_cpu_token_after_token() { 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); + let mut pos = 0; + for batch in batches { + let current = rng.vec(batch * channels, 2.0); + let token_taps = rng.vec(batch * 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); + let cur = Floats::first(&d_cur, batch * channels); + let out = Floats::first(&d_out, batch * channels); + at.sconv_fixed(cur, ring(&ring_fixed), Floats::first(&d_taps, channels * n), out, n, pos, batch).unwrap(); + if batch > 1 { + at.ring_store(cur, ring(&ring_fixed), n, pos, batch).unwrap(); + } + let got_fixed = download(&dev, &d_out, batch * channels); 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), + Floats::first(&d_token_taps, batch * heads * n), + out, n, heads, pos, + batch, ) .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); + if batch > 1 { + at.ring_store(cur, ring(&ring_dynamic), n, pos, batch).unwrap(); + } + let got_dynamic = download(&dev, &d_out, batch * channels); + + // The reference takes the same tokens one after another. + for b in 0..batch { + let token = ¤t[b * channels..(b + 1) * channels]; + let mut want = vec![0.0f32; channels]; + sconv::fixed(&recent_fixed, token, &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. + let what = format!("{n} taps, token {} (a batch of {batch})", pos + b); + close( + &format!("sconv_fixed, {what}"), + &got_fixed[b * channels..(b + 1) * channels], + &want, + |_| 8.0, + 4.0, + ); + remember(&mut recent_fixed, token); + let taps = &token_taps[b * heads * n..(b + 1) * heads * n]; + sconv::dynamic(&recent_dynamic, token, &fixed_taps, taps, heads, &mut want); + close( + &format!("sconv_dynamic, {what}"), + &got_dynamic[b * channels..(b + 1) * channels], + &want, + |_| 8.0, + 4.0, + ); + remember(&mut recent_dynamic, token); + } + pos += batch; } } } -/// 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. +/// Runs `tokens` tokens through attention with a history of `cap` rows (`history` is the +/// rows and the window) on the device, in +/// batches of the sizes in `batches` (taken in turn), and compares every output with +/// `sinkattn::attend` over the tokens a window of `window` shows that token. fn attend_case( dev: &CudaDevice, at: &Attention, shape: Heads, relative: (usize, usize), - cap: usize, - window: usize, + history: (usize, Option), tokens: usize, + batches: &[usize], ) { let (rel_dim, reach) = relative; + let (cap, window) = history; 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); + // Histories full of something else: a row not yet written must never be read. 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 alloc = |floats: usize| dev.alloc(MAX_BATCH * floats * 4).unwrap(); + let (d_new_keys, d_new_values) = (alloc(width), alloc(width)); + let (d_q, d_rel, d_sinks, d_out) = (alloc(heads * dim), alloc(heads * rel_dim), alloc(heads), alloc(heads * dim)); + let d_weights = alloc(heads * (cap + 1)); 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); + let (mut pos, mut turn) = (0, 0); + while pos < tokens { + let batch = batches[turn % batches.len()].min(tokens - pos); + turn += 1; + let (keys, values) = (rng.vec(batch * width, 1.0), rng.vec(batch * width, 2.0)); + let q = rng.vec(batch * heads * dim, 1.5); + let (rel, sinks) = (rng.vec(batch * heads * rel_dim, 1.0), rng.vec(batch * heads, 3.0)); + put(dev, &d_new_keys, &keys); + put(dev, &d_new_values, &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); + all_keys.extend_from_slice(&keys); + all_values.extend_from_slice(&values); + let history = + History { keys: Floats::first(&d_keys, cap * width), values: Floats::first(&d_values, cap * width), cap }; + // The batch's keys and values go to rows pos % cap onwards, as the model does it. + at.store_rows(Floats::first(&d_new_keys, batch * width), history.keys, width, cap, pos, batch).unwrap(); + at.store_rows(Floats::first(&d_new_values, batch * width), history.values, width, cap, pos, batch).unwrap(); + let scratch = heads * Attention::attend_scratch(pos, window, batch); 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 }, + Floats::first(&d_q, batch * heads * dim), + history, Relative { - rel: Floats::first(&d_rel, heads * rel_dim), + rel: Floats::first(&d_rel, batch * 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), + Floats::first(&d_sinks, batch * heads), + Floats::first(&d_weights, scratch), + Floats::first(&d_out, batch * heads * dim), pos, - seen, + window, + batch, ) .unwrap(); - let got = download(dev, &d_out, heads * dim); + let got = download(dev, &d_out, batch * 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; + for b in 0..batch { + // The reference: the tokens this one sees, oldest first, and each head's bias by + // distance. A later token of the batch is not among them. + let at_pos = pos + b; + let seen = window.map_or(at_pos + 1, |w| (at_pos + 1).min(w)); + let first = at_pos + 1 - seen; + let (keys, values) = + (&all_keys[first * width..(at_pos + 1) * width], &all_values[first * width..(at_pos + 1) * width]); + let near = seen.min(reach); + let mut bias = vec![0.0f32; heads * seen]; + let mut profile = vec![0.0f32; near]; + let my_rel = &rel[b * heads * rel_dim..(b + 1) * heads * rel_dim]; + for (head, row) in my_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] + let mut want = vec![0.0f32; heads * dim]; + sinkattn::attend( + sinkattn::Query { + q: &q[b * heads * dim..(b + 1) * heads * dim], + keys, + values, + bias: &bias, + sinks: &sinks[b * heads..(b + 1) * heads], + 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() { + let g = got[b * heads * dim + i]; + assert!( + (g - want[i]).abs() <= bound, + "{heads} heads, cap {cap}, window {window:?}, reach {reach}, token {at_pos} of a batch of {batch}: element {i}: {g} vs {}", + want[i] + ); + } } + pos += batch; } } @@ -291,16 +346,51 @@ fn attention_matches_the_cpu_with_and_without_a_window() { let (module,) = kernels(&dev); let at = Attention::new(&dev, &module).unwrap(); let shape = Heads { heads: 6, kv_heads: 2, dim: 8 }; + let mixed = [1usize, 3, 1, MAX_BATCH, 2, 5]; // 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); + // than the sequence, so far tokens get no relative-position term; and longer. One token + // at a time, and in batches. + for batches in [&[1usize][..], &mixed[..]] { + attend_case(&dev, &at, shape, (4, 5), (32, None), 20, batches); + attend_case(&dev, &at, shape, (4, 40), (20, None), 20, batches); + } + // A layer with a window of 7 and exactly 7 rows: one token at a time, the history wraps + // around three times over. + attend_case(&dev, &at, shape, (4, 7), (7, Some(7)), 23, &[1]); + // The same window in batches of up to 4 needs 3 more rows; the batches wrap around the + // end of the history, and the first token of each still sees rows the batch did not take. + attend_case(&dev, &at, shape, (4, 7), (10, Some(7)), 41, &[4, 1, 3, 4, 2]); + attend_case(&dev, &at, shape, (4, 7), (7 + MAX_BATCH - 1, Some(7)), 80, &[MAX_BATCH, 5, MAX_BATCH]); // 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); + attend_case(&dev, &at, Heads { heads: 1, kv_heads: 1, dim: 4 }, (2, 3), (1, Some(1)), 4, &[1]); // 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); + attend_case( + &dev, + &at, + Heads { heads: 24, kv_heads: 8, dim: 128 }, + (16, 1024), + (300, None), + 300, + &[MAX_BATCH, 1, 7, 8], + ); +} + +#[test] +fn softmax_over_runs_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(9); + for (runs, count) in [(1, 2), (3, 17), (5, 700)] { + let x = rng.vec(runs * count, 6.0); + let dx = upload(&dev, &x); + at.softmax_runs(Floats::first(&dx, runs * count), runs, count).unwrap(); + let got = download(&dev, &dx, runs * count); + let mut want = x.clone(); + want.chunks_exact_mut(count).for_each(cpu::softmax_inplace); + // The sum is added in another order: a few roundings of 1 on every weight. + close("softmax_runs", &got, &want, |_| 1.0, 16.0); + } } #[test] @@ -331,24 +421,28 @@ fn requests_that_would_leave_the_buffers_are_refused() { 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("more heads than the buffer holds", at.head_scale_clip(f(&a, 80), None, 10, 8, 1.0, Late::none())); 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), + at.head_scale_clip(Floats { buffer: &a, at: 60, len: 8 }, None, 1, 8, 1.0, Late::none()), ); - 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("a clip of zero", at.head_scale_clip(f(&a, 64), None, 8, 8, 0.0, Late::none())); + refused("a clip that is not a number", at.head_scale_clip(f(&a, 64), None, 8, 8, f32::NAN, Late::none())); + refused("a scale that is the vectors", at.head_scale_clip(f(&a, 64), Some(f(&a, 64)), 8, 8, 1.0, Late::none())); 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("a ring too short for the taps", at.sconv_fixed(f(&a, 16), f(&b, 32), f(&c, 64), f(&c, 16), 4, 0, 1)); 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), + at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 48), Floats { buffer: &c, at: 100, len: 16 }, 4, 0, 1), ); - 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("the output over the token", at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 64), f(&a, 16), 4, 0, 1)); + refused( + "no taps", + at.sconv_fixed(f(&a, 16), f(&b, 48), f(&c, 64), Floats { buffer: &c, at: 100, len: 16 }, 0, 0, 1), + ); + refused("taps that are the ring", at.sconv_fixed(f(&a, 16), f(&c, 48), f(&c, 64), f(&b, 16), 4, 0, 1)); refused( "heads that do not divide the channels", at.sconv_dynamic( @@ -360,6 +454,7 @@ fn requests_that_would_leave_the_buffers_are_refused() { 4, 3, 0, + 1, ), ); @@ -377,27 +472,29 @@ fn requests_that_would_leave_the_buffers_are_refused() { 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(); + at.attend(shape, q, history(8), relative, sinks, weights(3), out, 2, None, 1).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)); + let attend = |history, weights, out, pos, window, batch| { + at.attend(shape, q, history, relative, sinks, weights, out, pos, window, batch) + }; + refused("a position the history has no row for", attend(history(8), weights(9), out, 20, None, 1)); + refused("a batch the history has no rows for", attend(history(8), weights(9), out, 7, None, 2)); + refused("a window of no tokens", attend(history(8), weights(3), out, 2, Some(0), 1)); + refused("no tokens", attend(history(8), weights(3), out, 2, None, 0)); + refused("more tokens than a launch takes", attend(history(8), weights(3), out, 2, None, MAX_BATCH + 1)); + refused("a history larger than its buffers", attend(history(9), weights(3), out, 2, None, 1)); + refused("scratch too small", attend(history(8), weights(2), out, 2, None, 1)); + refused("the output over the query", attend(history(8), weights(3), q, 2, None, 1)); 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), + at.attend(Heads { heads: 3, kv_heads: 2, dim: 4 }, q, history(8), relative, sinks, weights(3), out, 2, None, 1), ); + refused("more rows stored than the history has", at.store_rows(f(&c, 72), f(&a, 64), 8, 8, 0, 9)); + refused("rows stored from inside the history", at.store_rows(f(&a, 8), f(&a, 64), 8, 8, 0, 1)); + refused("rows the buffer does not hold", at.store_rows(f(&b, 64), f(&a, 64), 8, 8, 0, 9)); + refused("a ring that is the tokens", at.ring_store(f(&a, 32), f(&a, 48), 4, 0, 2)); + refused("tokens the batch does not divide", at.ring_store(f(&a, 33), f(&b, 48), 4, 0, 2)); + refused("a softmax over a run of one", at.softmax_runs(f(&a, 4), 4, 1)); 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/expert_ops.rs b/crates/dluth-cuda/tests/expert_ops.rs index 7ef22b4..a235305 100644 --- a/crates/dluth-cuda/tests/expert_ops.rs +++ b/crates/dluth-cuda/tests/expert_ops.rs @@ -62,23 +62,39 @@ fn the_weighted_sum_matches_the_cpu_loop() { let dev = CudaDevice::open(0).expect("GPU"); let module = Module::load_embedded(&dev).unwrap(); let ops = ExpertOps::new(&dev, &module).unwrap(); - let (count, width) = (8, 2305); - let outs: Vec = (0..count * width).map(|i| ((i * 2654435761usize) % 2001) as f32 * 0.001 - 1.0).collect(); - let weights: Vec = (0..count).map(|j| 0.25 + j as f32 * 0.37).collect(); - let (d_outs, d_weights, d_y) = (upload(&dev, &outs), upload(&dev, &weights), dev.alloc(width * 4).unwrap()); - ops.weighted_sum(&d_outs, &d_weights, &d_y, count, width).unwrap(); - let got = download(&dev, &d_y, width); - for r in 0..width { - let mut want = 0.0f32; - let mut size = 0.0f32; - for j in 0..count { - want += weights[j] * outs[j * width + r]; - size += (weights[j] * outs[j * width + r]).abs(); + // Three positions, each with its own eight vectors and weights. + let (count, width, batch) = (8, 2305, 3); + let all_outs: Vec = + (0..batch * count * width).map(|i| ((i * 2654435761usize) % 2001) as f32 * 0.001 - 1.0).collect(); + let all_weights: Vec = (0..batch * count).map(|j| 0.25 + (j % 11) as f32 * 0.37).collect(); + let (d_outs, d_weights, d_y) = + (upload(&dev, &all_outs), upload(&dev, &all_weights), dev.alloc(batch * width * 4).unwrap()); + ops.weighted_sum(&d_outs, &d_weights, &d_y, count, width, batch).unwrap(); + let all_got = download(&dev, &d_y, batch * width); + for b in 0..batch { + position( + &all_got[b * width..][..width], + &all_outs[b * count * width..][..count * width], + &all_weights[b * count..][..count], + ); + } + // And the positions differ, so one position's weights cannot have served another. + assert_ne!(all_got[..width], all_got[width..2 * width]); + + fn position(got: &[f32], outs: &[f32], weights: &[f32]) { + let (count, width) = (weights.len(), got.len()); + for r in 0..width { + let mut want = 0.0f32; + let mut size = 0.0f32; + for j in 0..count { + want += weights[j] * outs[j * width + r]; + size += (weights[j] * outs[j * width + r]).abs(); + } + // The same order of additions. The device may fuse a multiply and an add into one + // rounding where the CPU rounds twice: at most one rounding of difference per term. + let bound = count as f32 * (f32::EPSILON / 2.0) * size; + assert!((got[r] - want).abs() <= bound, "row {r}: {} vs {want}", got[r]); } - // The same order of additions. The device may fuse a multiply and an add into one - // rounding where the CPU rounds twice: at most one rounding of difference per term. - let bound = count as f32 * (f32::EPSILON / 2.0) * size; - assert!((got[r] - want).abs() <= bound, "row {r}: {} vs {want}", got[r]); } } @@ -102,13 +118,15 @@ fn requests_that_would_leave_the_buffers_are_refused() { let (outs, weights, y) = (dev.alloc(3 * 6 * 4).unwrap(), dev.alloc(3 * 4).unwrap(), dev.alloc(6 * 4).unwrap()); for (what, result) in [ - ("more vectors than the input holds", ops.weighted_sum(&outs, &weights, &y, 4, 6)), - ("wider vectors than the output holds", ops.weighted_sum(&outs, &weights, &y, 2, 7)), - ("no vectors", ops.weighted_sum(&outs, &weights, &y, 0, 6)), - ("no width", ops.weighted_sum(&outs, &weights, &y, 3, 0)), - ("output over the input", ops.weighted_sum(&outs, &weights, &outs, 3, 6)), - ("output over the weights", ops.weighted_sum(&outs, &y, &y, 1, 6)), - ("the vectors as their own weights", ops.weighted_sum(&outs, &outs, &y, 3, 6)), + ("more vectors than the input holds", ops.weighted_sum(&outs, &weights, &y, 4, 6, 1)), + ("wider vectors than the output holds", ops.weighted_sum(&outs, &weights, &y, 2, 7, 1)), + ("no vectors", ops.weighted_sum(&outs, &weights, &y, 0, 6, 1)), + ("no width", ops.weighted_sum(&outs, &weights, &y, 3, 0, 1)), + ("output over the input", ops.weighted_sum(&outs, &weights, &outs, 3, 6, 1)), + ("output over the weights", ops.weighted_sum(&outs, &y, &y, 1, 6, 1)), + ("more positions than the buffers hold", ops.weighted_sum(&outs, &weights, &y, 3, 6, 2)), + ("no positions", ops.weighted_sum(&outs, &weights, &y, 3, 6, 0)), + ("the vectors as their own weights", ops.weighted_sum(&outs, &outs, &y, 3, 6, 1)), ] { assert!(matches!(result, Err(CudaError::Refused(_))), "{what} was not refused"); } diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 323d550..b118810 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -185,10 +185,98 @@ mod on_the_device { assert_eq!(dev.live_buffers(), before); } - /// Until the device operations take batches, a batch is refused before anything is - /// computed, and the model goes on as if it had not been asked. + /// The five most likely tokens' log-probabilities within `tol`, and the same most likely + /// token except at a near-tie: the bar the model is held to against the reference. + /// Returns the largest difference among those five. + fn close_scores(a: &[f32], b: &[f32], tol: f32, what: &str) -> f32 { + 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])); + let mut worst = 0.0f32; + for &i in &order[..5] { + worst = worst.max((a[i] - b[i]).abs()); + assert!((a[i] - b[i]).abs() < tol, "{what}, 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, "{what}: {top} vs {}", order[0]); + worst + } + + /// Two sequences fed in batches of every kind, each position's scores against the CPU + /// model one token at a time. The tiny model's window is 8, so batches end on it, + /// straddle it and are longer than it, and the histories of its local layers (8 + 15 + /// rows) wrap around inside batches. The second sequence starts again at position 0. #[test] - fn a_batch_is_refused_and_changes_nothing() { + fn the_tiny_model_in_batches_stays_close_to_the_cpu_model() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let golden: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("golden.json")).unwrap()).unwrap(); + let tol = 4.0 * golden["reference_self_difference"].as_f64().unwrap() as f32; + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let ops = CudaOps::new(&dev, &module).unwrap(); + let stats = ops.stats(); + let cfg = load_config(&dir).unwrap(); + let (vocab, passes) = (cfg.vocab_out, cfg.layer_passes()); + let mut gpu = Inkling::with_ops(cfg, &weights, 64, ops).unwrap(); + let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let mut worst = 0.0f32; + let splits: [&[usize]; 2] = [&[16, 1, 7, 2, 16, 5, 13, 4], &[3, 8, 1, 1, 16, 11]]; + for (sequence, split) in splits.into_iter().enumerate() { + let mut pos = 0; + for &n in split { + let tokens: Vec = (pos..pos + n).map(|p| ((p * 37 + 11 + sequence * 101) % 256) as u32).collect(); + let waits = stats.borrow().waits; + let got = gpu.forward_tokens(&tokens, pos).unwrap(); + // However many positions: one wait for the embeddings, one per layer pass + // for the router's scores, one for the scores of the vocabulary. + assert_eq!(stats.borrow().waits - waits, passes + 2, "a batch of {n}"); + assert_eq!(got.len(), n * vocab); + for (i, scores) in got.chunks_exact(vocab).enumerate() { + let want = cpu.forward_token(tokens[i], pos + i).unwrap(); + let what = format!("sequence {sequence}, position {} in a batch of {n}", pos + i); + worst = worst.max(close_scores(scores, &want, tol, &what)); + } + pos += n; + } + } + eprintln!("device in batches: largest log-probability difference from the CPU model: {worst} (bar {tol})"); + } + + /// Feeding without scoring, then asking: the scores after the last token only, the same + /// as one token at a time on the device gives. + #[test] + fn the_tiny_model_scores_the_last_position_of_a_fed_prompt() { + 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 model = + || Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, CudaOps::new(&dev, &module).unwrap()); + let (mut batched, mut single) = (model().unwrap(), model().unwrap()); + let tokens: Vec = (0..37).map(|p| ((p * 53 + 5) % 256) as u32).collect(); + let mut want = Vec::new(); + for (pos, &t) in tokens.iter().enumerate() { + want = single.forward_token(t, pos).unwrap(); + } + for (i, chunk) in tokens.chunks(16).enumerate() { + batched.feed(chunk, i * 16).unwrap(); + } + close_scores(&batched.next_scores().unwrap(), &want, tol, "after a prompt of 37 fed in batches of 16"); + // Generation with the prompt fed in batches picks the same tokens. + let alone = single.generate_greedy(&tokens[..21], 10, u32::MAX).unwrap(); + batched.set_prompt_batch(16).unwrap(); + assert_eq!(batched.generate_greedy(&tokens[..21], 10, u32::MAX).unwrap(), alone); + } + + /// More positions than a launch takes are refused before anything is computed, and the + /// model goes on as if it had not been asked. + #[test] + fn too_large_a_batch_is_refused_and_changes_nothing() { 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"); @@ -198,14 +286,54 @@ mod on_the_device { let ops = CudaOps::new(&dev, &module).unwrap(); let mut fresh = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); assert_eq!(gpu.forward_token(7, 0).unwrap(), fresh.forward_token(7, 0).unwrap()); - let e = gpu.forward_tokens(&[8, 9], 1).unwrap_err(); + let e = gpu.forward_tokens(&[9; 17], 1).unwrap_err(); assert!( - matches!(e, dluth_model::ModelError::Capacity(_)) && e.to_string().contains("one position at a time"), + matches!(e, dluth_model::ModelError::Capacity(_)) && e.to_string().contains("1 to 16 positions"), "{e}" ); assert_eq!(gpu.forward_token(8, 1).unwrap(), fresh.forward_token(8, 1).unwrap()); } + /// The real model with each recorded prompt fed in batches of 16: the scores after the + /// prompt against the same model fed one token at a time, at the bar of the recordings. + #[test] + fn the_real_model_scores_the_same_after_a_prompt_fed_in_batches() { + 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(); + let tol = 4.0 * golden["reference_self_check"]["top5"].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 model = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 256, ops).unwrap(); + for case in golden["cases"].as_array().unwrap() { + let prompt: Vec = serde_json::from_value(case["prompt_ids"].clone()).unwrap(); + let mut want = Vec::new(); + let started = std::time::Instant::now(); + for (pos, &t) in prompt.iter().enumerate() { + want = model.forward_token(t, pos).unwrap(); + } + let one_at_a_time = started.elapsed(); + let started = std::time::Instant::now(); + for (i, chunk) in prompt.chunks(16).enumerate() { + model.feed(chunk, i * 16).unwrap(); + } + let got = model.next_scores().unwrap(); + let worst = close_scores(&got, &want, tol, &format!("{}", case["prompt"])); + eprintln!( + "device, prompt of {} tokens: {:.0} ms one at a time, {:.0} ms in batches of 16; largest difference {worst}", + prompt.len(), + one_at_a_time.as_secs_f64() * 1e3, + started.elapsed().as_secs_f64() * 1e3 + ); + } + } + #[test] fn the_real_model_matches_the_reference() { let Ok(dir) = std::env::var("DLUTH_INKLING2_MINI") else { diff --git a/crates/dluth-cuda/tests/small.rs b/crates/dluth-cuda/tests/small.rs index b2dddc3..1762be7 100644 --- a/crates/dluth-cuda/tests/small.rs +++ b/crates/dluth-cuda/tests/small.rs @@ -55,18 +55,26 @@ fn weighted_normalization_matches_the_cpu() { 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); + // One vector, and batches of them sharing the weights; a vector of zeros among them. + for (n, batch) in [(1, 1), (7, 3), (256, 1), (2304, 5)] { + let (mut x, w) = (rng.vec(batch * n, 5.0), rng.vec(n, 2.0)); + if batch > 1 { + x[n..2 * n].fill(0.0); + } + let (dx, dw, dout) = (upload(&dev, &x), upload(&dev, &w), dev.alloc(batch * n * 4).unwrap()); + small + .rmsnorm(Floats::first(&dx, batch * n), Floats::first(&dw, n), Floats::first(&dout, batch * n), 1e-6) + .unwrap(); + let got = download(&dev, &dout, batch * n); + let mut want = vec![0.0f32; batch * n]; + for (o, v) in want.chunks_exact_mut(n).zip(x.chunks_exact(n)) { + cpu::rmsnorm(v, &w, 1e-6, o); + } // The squares are added in another order, which moves the scale by a few roundings. - for i in 0..n { + for i in 0..batch * n { assert!( (got[i] - want[i]).abs() <= 16.0 * f32::EPSILON * want[i].abs(), - "n {n}, element {i}: {} vs {}", + "n {n}, batch {batch}, element {i}: {} vs {}", got[i], want[i] ); @@ -124,27 +132,37 @@ fn a_whole_blend_in_one_launch_matches_the_cpu() { 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()); + for (count, width, batch) in + [(1, 5, 1), (2, 100, 3), (6, 2304, 1), (9, 2304, 16), (dluth_cuda::small::BLEND_MAX, 700, 2)] + { + // Each position has its own candidates; the query is shared. + let (query, candidates) = (rng.vec(width, 0.6), rng.vec(batch * count * width, 1.7)); + let (dq, dc, dout) = (upload(&dev, &query), upload(&dev, &candidates), dev.alloc(batch * width * 4).unwrap()); small .blend_mix( Floats::first(&dq, width), - Floats::first(&dc, count * width), - Floats::first(&dout, width), + Floats::first(&dc, batch * count * width), + Floats::first(&dout, batch * 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); + let got = download(&dev, &dout, batch * width); // The scores are sums of `width` products added in another order, which moves the // weights by a few roundings times the size of a score; the result is a sum of // `count` terms of size below 2. let bound = 64.0 * (width as f32).sqrt() * f32::EPSILON; - for i in 0..width { - assert!((got[i] - want[i]).abs() <= bound, "{count} of {width}, element {i}: {} vs {}", got[i], want[i]); + for (b, mine) in candidates.chunks_exact(count * width).enumerate() { + let mut want = vec![0.0f32; width]; + depthmix::mix_normalized(&query, mine, width, &mut want); + for i in 0..width { + let g = got[b * width + i]; + assert!( + (g - want[i]).abs() <= bound, + "{count} of {width}, position {b}, element {i}: {g} vs {}", + want[i] + ); + } } } } @@ -155,29 +173,47 @@ fn several_vectors_normalized_in_one_launch_match_the_cpu() { 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(); + for (count, width, batch) in [(1, 3, 1), (2, 2304, 1), (2, 2304, 16), (dluth_cuda::small::MANY, 513, 3)] { + // Each candidate in its own buffer, a batch of vectors of very different sizes; some + // all zeros. + let vectors: Vec> = (0..count) + .map(|j| (0..batch).flat_map(|b| rng.vec(width, [0.0, 0.01, 3.0, 400.0][(j + b) % 4])).collect()) + .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); + let runs: Vec = buffers.iter().map(|b| Floats::first(b, batch * width)).collect(); + let dout = dev.alloc(batch * count * width * 4).unwrap(); + small.normalize_many(&runs, Floats::first(&dout, batch * count * width), 1e-6, batch).unwrap(); + let got = download(&dev, &dout, batch * 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] - ); + for b in 0..batch { + let mut want = vec![0.0f32; width]; + cpu::rmsnorm_plain(&v[b * width..(b + 1) * width], 1e-6, &mut want); + for i in 0..width { + // Position b's candidates are one after another. + let g = got[(b * count + j) * width + i]; + assert!( + (g - want[i]).abs() <= 16.0 * f32::EPSILON * want[i].abs(), + "{count} of {width}, candidate {j} position {b} element {i}: {g} vs {}", + want[i] + ); + } } } } } +#[test] +fn a_copy_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(8); + let x = rng.vec(3000, 9.0); + let (dx, dout) = (upload(&dev, &x), dev.alloc(1000 * 4).unwrap()); + small.copy(Floats { buffer: &dx, at: 700, len: 1000 }, Floats::first(&dout, 1000)).unwrap(); + assert_eq!(download(&dev, &dout, 1000), x[700..1700]); +} + #[test] fn the_merging_gate_and_the_soft_cap_match_the_cpu() { let dev = CudaDevice::open(0).expect("GPU"); @@ -246,10 +282,14 @@ fn requests_that_would_leave_the_buffers_are_refused() { 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("more vectors than a launch takes", small.normalize_many(&nine, f(&c, 36), 1e-6, 1)); + refused("no vectors", small.normalize_many(&[], f(&c, 16), 1e-6, 1)); + refused("an output the vectors do not divide", small.normalize_many(&[f(&a, 5), f(&b, 5)], f(&c, 11), 1e-6, 1)); + refused("a vector normalized over itself", small.normalize_many(&[f(&c, 16)], f(&c, 16), 1e-6, 1)); + refused("a batch the vectors do not hold", small.normalize_many(&[f(&a, 16), f(&b, 16)], f(&c, 64), 1e-6, 2)); + refused("no positions", small.normalize_many(&[f(&a, 16)], f(&c, 16), 1e-6, 0)); + refused("weights that do not divide the vectors", small.rmsnorm(f(&a, 16), f(&b, 5), f(&c, 16), 1e-6)); + refused("a copy over itself", small.copy(f(&a, 16), f(&a, 16))); 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/docs/learning/22-several-positions-per-sweep.md b/docs/learning/22-several-positions-per-sweep.md new file mode 100644 index 0000000..12affd3 --- /dev/null +++ b/docs/learning/22-several-positions-per-sweep.md @@ -0,0 +1,90 @@ +# 22. Several positions per sweep of the weights + +Note 21 ended with a token that costs about 40 milliseconds, of which about 22 are the weights being read +and the rest is the cost of starting many small kernels one after another. Both costs are paid per +sweep through the model, not per position. This note is about putting several consecutive positions +through one sweep. + +## What a batch is + +A value of the forward pass used to be one vector. It is now a batch: one vector for each of a few +consecutive positions of the same sequence, in order, one after another in one device buffer. A token at a +time is a batch of one. The forward pass itself did not change: it still says which operation follows +which. The operations changed, on both sides: + +- On the CPU each operation loops over the positions. That makes a batch the same arithmetic in the same + order as feeding the tokens one by one, so the CPU model in batches is equal to itself token by token to + the last bit. That equality is the definition of a batch for everything else. +- On the device each kernel takes the whole batch in one launch. A sweep over 16 positions starts about as + many kernels as a sweep over one. + +The model can be asked for the scores of every position of a batch, or to feed a batch and score only its +last position. The second matters: the output table is the largest matrix of the model, and when a prompt +is read nobody looks at the scores after its first tokens. + +## Three places where a batch is not just a loop + +Most kernels only needed to know which position a vector belongs to. Three things needed thought, because +in them the positions of a batch depend on each other. + +**Attention's history.** A position sees itself and the tokens before it. In a batch, the keys and values +of all its positions are stored first, and then every position is scored against its own view, which ends +at itself: a later token of the same batch is in the history but not in view. A layer with a window keeps +its history in a ring of rows, and a token's row is taken by the token that comes one ring later. With +exactly as many rows as the window, the last position of a batch would take a row the first position can +still see. So a windowed history has `window + 15` rows, 15 being one less than the largest batch. When a +batch's rows run past the end of the ring they are computed aside and copied in by a kernel that wraps. + +**The short convolutions.** Each keeps the last three tokens of its input. With one position, a thread reads +that memory and then writes its own token into it. With several, one position's write would race another +position's read. So for a batch the kernel takes an earlier token from the batch itself when it is that +recent and from the memory otherwise, writes nothing, and a second small kernel stores the batch's last +three tokens afterwards. + +**The late factor.** Global layers multiply queries by a factor that grows with the position, late in a +long context. It differs per position of a batch, so the kernel computes it from the position instead of +being handed one number. + +## Experts shared within a batch + +The router's scores for every position come back to the host in one copy, and the experts are chosen +there. Positions next to each other often choose the same experts (note 19 measured 28.5 distinct experts +per layer pass for 8 positions, where 64 were chosen). An expert chosen by several positions is one job: +its matrix is read once and multiplied with each of their vectors. + +## What it costs + +Inkling 2 Mini on the GB10, reading 160 tokens of text it already knows the weights for, without scoring +them (`examples/generate.rs` prints this after generating): + +| Positions per sweep | Milliseconds per sweep | Tokens per second | +|---|---|---| +| 1 | 36.4 | 27.5 | +| 2 | 44.2 | 45.2 | +| 4 | 58.0 | 69.0 | +| 8 | 82.2 | 97.4 | +| 16 | 133.3 | 120.0 | + +Eight positions cost 2.3 times what one costs. Generation one token at a time is where it was: 24.5 tokens +per second, against 24.6 to 24.7 for the code before this step on the same prompt. + +Two uses follow. A prompt is read in batches: `set_prompt_batch(16)` and the model reads it more than four +times as fast. And a guess at the next few tokens can be checked in one sweep: feed the guessed tokens as a +batch, and each position's scores say whether the next guess was the model's own choice. A sweep of four +(the last token and three guesses) costs 58 milliseconds against 36 for one, before the scores, so guesses +pay roughly when more than 0.6 of the three are right on average. That is the next step. + +## How it was checked + +- Each batched kernel against the CPU function, position by position, on batches of every kind: one token, + several, the most a launch takes; batches that end on a window, straddle it, are longer than it, and wrap + around the end of a history. +- The tiny model on the device in batches against the CPU model one token at a time, at every position of + two sequences, at the bar the model is held to against the reference. The number of waits for the device + per batch is asserted: two plus one per layer pass, whatever the batch. +- The real model with each recorded prompt fed in batches of 16 against itself one token at a time: the + five most likely tokens after the prompt had the same log-probabilities in every case. +- Planted bugs for the ways a batch goes wrong, each caught by a test: every position given the first + position's view, late factor, expert input, expert weights or blend; a convolution that reads its memory + for tokens inside the batch; a memory left with the batch's first tokens; rows not wrapped; a windowed + history without its spare rows; all rows stored in one; the stacked matrices all read from the first. diff --git a/tools/mutants/100-batch-conv-ignores-batch.patch b/tools/mutants/100-batch-conv-ignores-batch.patch new file mode 100644 index 0000000..3ecf507 --- /dev/null +++ b/tools/mutants/100-batch-conv-ignores-batch.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-cuda --test attention both_short_convolutions +# needs: gpu +# Bug: a convolution over a batch takes every earlier token from the ring, which does not hold the batch's own tokens yet. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..dc419e3 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -81,7 +81,6 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign + __device__ __forceinline__ float earlier_token(const float* current, const float* ring, unsigned int channels, + unsigned int n, unsigned long long pos, unsigned int b, + unsigned int lag, unsigned int c) { +- if (b >= lag) return current[(size_t)(b - lag) * channels + c]; + unsigned long long at = pos + b; + return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f; + } diff --git a/tools/mutants/101-batch-ring-keeps-first-tokens.patch b/tools/mutants/101-batch-ring-keeps-first-tokens.patch new file mode 100644 index 0000000..446a3e7 --- /dev/null +++ b/tools/mutants/101-batch-ring-keeps-first-tokens.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention both_short_convolutions +# needs: gpu +# Bug: after a batch, the ring is given the batch's first tokens, not its last. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..15ef7d0 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -139,7 +139,7 @@ extern "C" __global__ void ring_store(const float* current, float* ring, unsigne + unsigned int b = (unsigned int)(index / channels); + unsigned int c = (unsigned int)(index % channels); + if (b >= batch || n < 2) return; +- if (batch - b > n - 1) return; ++ if (b >= n - 1) return; + ring[((pos + b) % (n - 1)) * channels + c] = current[index]; + } + diff --git a/tools/mutants/102-batch-rows-not-wrapped.patch b/tools/mutants/102-batch-rows-not-wrapped.patch new file mode 100644 index 0000000..466ae17 --- /dev/null +++ b/tools/mutants/102-batch-rows-not-wrapped.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_in_batches +# needs: gpu +# Bug: a batch whose rows wrap around the end of a history is written as one run. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index a3a0faf..6b836b5 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -817,7 +817,7 @@ impl<'m> Ops for CudaOps<'m> { + // the history for these positions: directly when the rows are one run, by way of a + // copy when they wrap around the end of the history. + let first_row = pos % pass.cap; +- let wraps = first_row + batch > pass.cap; ++ let wraps = first_row + batch > pass.cap + batch; + let keys_all = Floats::first(&pass.keys, pass.cap * width); + let values_all = Floats::first(&pass.values, pass.cap * width); + let rows_of = |buffer| Floats { buffer, at: first_row * width, len: batch * width }; diff --git a/tools/mutants/103-batch-history-without-spare-rows.patch b/tools/mutants/103-batch-history-without-spare-rows.patch new file mode 100644 index 0000000..e6154f4 --- /dev/null +++ b/tools/mutants/103-batch-history-without-spare-rows.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_in_batches +# needs: gpu +# Bug: a windowed history has only as many rows as the window. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index a3a0faf..f1d24cb 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -615,7 +615,7 @@ impl<'m> Ops for CudaOps<'m> { + // A layer with a window needs the rows of the window, and more for a batch: the + // first token of a batch still sees tokens whose rows, with only `window` of them, + // the batch's later tokens would take. +- let cap = window.map_or(max_seq, |w| (w + MAX_BATCH - 1).min(max_seq)); ++ 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)?, diff --git a/tools/mutants/104-batch-experts-read-first-position.patch b/tools/mutants/104-batch-experts-read-first-position.patch new file mode 100644 index 0000000..2abc36e --- /dev/null +++ b/tools/mutants/104-batch-experts-read-first-position.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_in_batches +# needs: gpu +# Bug: every position's experts read the input of the batch's first position. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index a3a0faf..1f15488 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -508,7 +508,7 @@ impl<'m> CudaOps<'m> { + let m2 = BlockMatrices { format: format2, values: &values2, scales: &scales2, rows: h, cols: inner }; + // An expert's first matrix reads the input of each position that chose it; its second + // reads the activation in the same slot. +- let (jobs1, jobs2) = (jobs(first, &|slot| (slot / n) * h), jobs(second, &|slot| slot * inner)); ++ let (jobs1, jobs2) = (jobs(first, &|_| 0), jobs(second, &|slot| slot * inner)); + let count = jobs1.len(); + let list1 = self.blockmat.encode(m1, &jobs1, &input.0.buffer, &both.0.buffer, SEGS).map_err(failed)?; + let list2 = self.blockmat.encode(m2, &jobs2, &act.0.buffer, &outs.0.buffer, SEGS).map_err(failed)?; diff --git a/tools/mutants/105-batch-sum-with-first-weights.patch b/tools/mutants/105-batch-sum-with-first-weights.patch new file mode 100644 index 0000000..780da7e --- /dev/null +++ b/tools/mutants/105-batch-sum-with-first-weights.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test expert_ops the_weighted_sum +# needs: gpu +# Bug: every position's expert outputs are weighted with the first position's weights. +diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu +index 252df27..d7fd36d 100644 +--- a/crates/dluth-cuda/kernels/expert_ops.cu ++++ b/crates/dluth-cuda/kernels/expert_ops.cu +@@ -30,7 +30,7 @@ extern "C" __global__ void weighted_sum(const float* outs, const float* weights, + unsigned int r = (unsigned int)(index % width); + if (b >= batch) return; + const float* mine = outs + b * count * width; +- const float* w = weights + b * count; ++ const float* w = weights; + float total = 0.0f; + for (unsigned int j = 0; j < count; ++j) total += w[j] * mine[(size_t)j * width + r]; + y[index] = total; diff --git a/tools/mutants/106-batch-blend-of-first-position.patch b/tools/mutants/106-batch-blend-of-first-position.patch new file mode 100644 index 0000000..aded3ab --- /dev/null +++ b/tools/mutants/106-batch-blend-of-first-position.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test small a_whole_blend +# needs: gpu +# Bug: every position of a batch is given the blend of the first position's candidates. +diff --git a/crates/dluth-cuda/kernels/small_ops.cu b/crates/dluth-cuda/kernels/small_ops.cu +index 0d40107..2ccb159 100644 +--- a/crates/dluth-cuda/kernels/small_ops.cu ++++ b/crates/dluth-cuda/kernels/small_ops.cu +@@ -77,7 +77,7 @@ extern "C" __global__ void blend_mix(const float* query, const float* candidates + __shared__ float part[BLEND_MAX][256]; + __shared__ float weight[BLEND_MAX]; + if (blockIdx.x >= batch) return; +- const float* mine = candidates + (size_t)blockIdx.x * count * width; ++ const float* mine = candidates; + float* o = out + (size_t)blockIdx.x * width; + float dot[BLEND_MAX]; + for (unsigned int j = 0; j < count; ++j) dot[j] = 0.0f; diff --git a/tools/mutants/107-batch-products-not-advanced.patch b/tools/mutants/107-batch-products-not-advanced.patch new file mode 100644 index 0000000..3cbd50e --- /dev/null +++ b/tools/mutants/107-batch-products-not-advanced.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_in_batches +# needs: gpu +# Bug: for a batch, each of the stacked matrices is read from where the first one starts. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index a3a0faf..da6fabd 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -422,7 +422,7 @@ impl<'m> CudaOps<'m> { + self.matmat + .bf16(Bf16Matrix { buffer: &stacked, offset, rows, cols }, &x.0.buffer, batch, &y.0.buffer, SEGS) + .map_err(failed)?; +- offset += rows * cols * 2; ++ offset += 0 * rows; + cuts.push((i, 0, batch * rows)); + vecs.push(y); + } diff --git a/tools/mutants/108-batch-row-is-first.patch b/tools/mutants/108-batch-row-is-first.patch new file mode 100644 index 0000000..a0faf6d --- /dev/null +++ b/tools/mutants/108-batch-row-is-first.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_scores_the_last +# needs: gpu +# Bug: asked for one position of a batch, the device gives the first. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index a3a0faf..aeb5bb2 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -652,7 +652,7 @@ impl<'m> Ops for CudaOps<'m> { + return Ok(x.clone()); + } + let out = self.vec(width)?; +- self.small.copy(x.part(index * width, width), out.all()).map_err(failed)?; ++ self.small.copy(x.part(0, width), out.all()).map_err(failed)?; + Ok(out) + } + diff --git a/tools/mutants/109-batch-rows-stored-in-one-row.patch b/tools/mutants/109-batch-rows-stored-in-one-row.patch new file mode 100644 index 0000000..523313d --- /dev/null +++ b/tools/mutants/109-batch-rows-stored-in-one-row.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: every key and value of a batch is stored in the row of the batch's first token. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..0acd16f 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -150,7 +150,7 @@ extern "C" __global__ void store_rows(const float* rows, float* history, unsigne + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long b = index / width; + if (b >= batch) return; +- history[((pos + b) % cap) * width + index % width] = rows[index]; ++ history[(pos % cap) * width + index % width] = rows[index]; + } + + // Attention scores of a batch of query tokens, the first at position `pos`. The query at diff --git a/tools/mutants/110-batch-scores-last-view.patch b/tools/mutants/110-batch-scores-last-view.patch new file mode 100644 index 0000000..f6d62c1 --- /dev/null +++ b/tools/mutants/110-batch-scores-last-view.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: every token of a batch is scored against as many tokens as the batch's last token sees. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..d809924 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -174,7 +174,7 @@ extern "C" __global__ void attn_scores(const float* q, const float* keys, const + unsigned long long b = run / heads; + unsigned int h = (unsigned int)(run % heads); + unsigned long long at = pos + b; +- unsigned long long seen = tokens_seen(at, window); ++ unsigned long long seen = tokens_seen(pos + batch - 1, window); + if (d > seen) return; + if (d == seen) { + weights[index] = sinks[run]; diff --git a/tools/mutants/70-cuda-expert-first-vector.patch b/tools/mutants/70-cuda-expert-first-vector.patch index b373521..f5d4b79 100644 --- a/tools/mutants/70-cuda-expert-first-vector.patch +++ b/tools/mutants/70-cuda-expert-first-vector.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: every expert's second matrix on the GPU reads the first expert's activation. diff --git a/crates/dluth-cuda/src/inkling.rs b/crates/dluth-cuda/src/inkling.rs -index 14f7f8f..4293c1c 100644 +index 3607c49..587bd27 100644 --- a/crates/dluth-cuda/src/inkling.rs +++ b/crates/dluth-cuda/src/inkling.rs -@@ -242,7 +242,7 @@ impl Products for CudaProducts<'_> { +@@ -248,7 +248,7 @@ impl Products for CudaProducts<'_> { self.blockmat.run(first, &jobs(layer.first, &|_| 0), &dx, &d_both, &jobs_first, SEGS).map_err(failed)?; self.ops.capped_gate_pairs(&d_both, &d_act, n * inner, layer.gate_cap, layer.up_cap).map_err(failed)?; self.blockmat - .run(second, &jobs(layer.second, &|j| j * inner), &d_act, &d_outs, &jobs_second, SEGS) + .run(second, &jobs(layer.second, &|_| 0), &d_act, &d_outs, &jobs_second, SEGS) .map_err(failed)?; - self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h).map_err(failed)?; + self.ops.weighted_sum(&d_outs, &d_route, &dy, n, h, 1).map_err(failed)?; self.receive(&dy, out)?; diff --git a/tools/mutants/72-gate-sigmoid-of-capped.patch b/tools/mutants/72-gate-sigmoid-of-capped.patch index 0d69f06..ef14ee5 100644 --- a/tools/mutants/72-gate-sigmoid-of-capped.patch +++ b/tools/mutants/72-gate-sigmoid-of-capped.patch @@ -2,7 +2,7 @@ # needs: gpu # Bug: the expert activation on the GPU takes the sigmoid of the capped gate, not the raw one. diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu -index c23c4c7..14b1f18 100644 +index 252df27..720d448 100644 --- a/crates/dluth-cuda/kernels/expert_ops.cu +++ b/crates/dluth-cuda/kernels/expert_ops.cu @@ -15,7 +15,7 @@ extern "C" __global__ void capped_gate_pairs(const float* both, float* act, unsi @@ -13,4 +13,4 @@ index c23c4c7..14b1f18 100644 + act[i] = gate * (1.0f / (1.0f + expf(-gate))) * up; } - // The weighted sum of the chosen experts' outputs: + // The weighted sum of the chosen experts' outputs, for a batch of positions: diff --git a/tools/mutants/73-weighted-sum-unweighted.patch b/tools/mutants/73-weighted-sum-unweighted.patch index 6786f5b..e8829c5 100644 --- a/tools/mutants/73-weighted-sum-unweighted.patch +++ b/tools/mutants/73-weighted-sum-unweighted.patch @@ -2,14 +2,14 @@ # needs: gpu # Bug: the experts' outputs are added without their weights. diff --git a/crates/dluth-cuda/kernels/expert_ops.cu b/crates/dluth-cuda/kernels/expert_ops.cu -index c23c4c7..ca3d48c 100644 +index 252df27..7846005 100644 --- a/crates/dluth-cuda/kernels/expert_ops.cu +++ b/crates/dluth-cuda/kernels/expert_ops.cu -@@ -27,6 +27,6 @@ extern "C" __global__ void weighted_sum(const float* outs, const float* weights, - unsigned int r = blockIdx.x * blockDim.x + threadIdx.x; - if (r >= width) return; +@@ -32,6 +32,6 @@ extern "C" __global__ void weighted_sum(const float* outs, const float* weights, + const float* mine = outs + b * count * width; + const float* w = weights + b * count; float total = 0.0f; -- for (unsigned int j = 0; j < count; ++j) total += weights[j] * outs[(size_t)j * width + r]; -+ for (unsigned int j = 0; j < count; ++j) total += outs[(size_t)j * width + r]; - y[r] = total; +- for (unsigned int j = 0; j < count; ++j) total += w[j] * mine[(size_t)j * width + r]; ++ for (unsigned int j = 0; j < count; ++j) total += mine[(size_t)j * width + r]; + y[index] = total; } diff --git a/tools/mutants/76-head-always-rescaled.patch b/tools/mutants/76-head-always-rescaled.patch index ff56407..1eb7727 100644 --- a/tools/mutants/76-head-always-rescaled.patch +++ b/tools/mutants/76-head-always-rescaled.patch @@ -2,10 +2,10 @@ # 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 +index 10196bd..ff744f8 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 +@@ -41,14 +41,14 @@ 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]; @@ -14,6 +14,7 @@ index f60645f..fb39fb2 100644 } __syncthreads(); float factor = part[0]; + float late = 1.0f + alpha * logf(fmaxf((float)(at + 1) / floor, 1.0f)); for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { float t = v[i]; - if (factor < 1.0f) t *= factor; diff --git a/tools/mutants/78-conv-ring-before-start.patch b/tools/mutants/78-conv-ring-before-start.patch index 8a11d45..dc20aac 100644 --- a/tools/mutants/78-conv-ring-before-start.patch +++ b/tools/mutants/78-conv-ring-before-start.patch @@ -2,15 +2,15 @@ # 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 +index 10196bd..203030d 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]; +@@ -83,7 +83,7 @@ __device__ __forceinline__ float earlier_token(const float* current, const float + unsigned int lag, unsigned int c) { + if (b >= lag) return current[(size_t)(b - lag) * channels + c]; + unsigned long long at = pos + b; +- return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f; ++ return ring[((at + (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. + // Short convolution with fixed taps, for a batch of `batch` consecutive tokens of diff --git a/tools/mutants/79-conv-token-taps-ignored.patch b/tools/mutants/79-conv-token-taps-ignored.patch index 4ec7c99..be41646 100644 --- a/tools/mutants/79-conv-token-taps-ignored.patch +++ b/tools/mutants/79-conv-token-taps-ignored.patch @@ -2,15 +2,15 @@ # 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 +index 10196bd..07920ae 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; +@@ -124,7 +124,7 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons + const float* head_taps = token_taps + ((size_t)b * heads + 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; - } +- sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) ++ sum += fixed_taps[(size_t)lag * channels + c] + * earlier_token(current, ring, channels, n, pos, b, lag, c); + out[index] = (sum + x) * norm; + if (batch == 1 && 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 index 5950fe7..9799e0e 100644 --- a/tools/mutants/80-attn-sink-silenced.patch +++ b/tools/mutants/80-attn-sink-silenced.patch @@ -2,15 +2,15 @@ # 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 +index 10196bd..5a88901 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; +@@ -177,7 +177,7 @@ extern "C" __global__ void attn_scores(const float* q, const float* keys, const + unsigned long long seen = tokens_seen(at, window); + if (d > seen) return; if (d == seen) { -- weights[index] = sinks[h]; +- weights[index] = sinks[run]; + weights[index] = -1e30f; return; } - const float* key = keys + ((pos - d) % cap) * kv_heads * dim + (h / (heads / kv_heads)) * dim; + const float* key = keys + ((at - d) % cap) * kv_heads * dim + (size_t)(h / (heads / kv_heads)) * dim; diff --git a/tools/mutants/81-attn-bias-dropped.patch b/tools/mutants/81-attn-bias-dropped.patch index c7c94d2..ec209f4 100644 --- a/tools/mutants/81-attn-bias-dropped.patch +++ b/tools/mutants/81-attn-bias-dropped.patch @@ -2,15 +2,15 @@ # 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 +index 10196bd..e6e2e86 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 +@@ -187,7 +187,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]; + for (unsigned int k = 0; k < rel_dim; ++k) bias += rel[run * 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. + // Softmax over each (query, head) run's scores and its sink, in place: one block of diff --git a/tools/mutants/82-attn-weights-reversed.patch b/tools/mutants/82-attn-weights-reversed.patch index 87ee7f2..4cb61fb 100644 --- a/tools/mutants/82-attn-weights-reversed.patch +++ b/tools/mutants/82-attn-weights-reversed.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: values are weighted with the weights of the tokens at the mirrored distance. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 801f951..24dbce2 100644 +index 10196bd..f2fe7d3 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; +@@ -247,7 +247,7 @@ extern "C" __global__ void attn_values(const float* weights, const float* values + const float* w = weights + run * stride; + unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e; float total = 0.0f; -- for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((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]; +- for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((at - d) % cap) * kv_heads * dim + column]; ++ for (unsigned long long d = seen; d-- > 0;) total += w[seen - 1 - d] * values[((at - d) % cap) * kv_heads * dim + column]; out[index] = total; } diff --git a/tools/mutants/86-normalize-first-vector.patch b/tools/mutants/86-normalize-first-vector.patch index 3b1a7c4..4c9af34 100644 --- a/tools/mutants/86-normalize-first-vector.patch +++ b/tools/mutants/86-normalize-first-vector.patch @@ -1,16 +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. +# Bug: every candidate 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 +index 0d40107..d91750a 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; +@@ -124,7 +124,7 @@ extern "C" __global__ void normalize_many(const float* x0, const float* x1, cons + unsigned int b = blockIdx.x / count; + if (b >= batch) return; const float* all[8] = {x0, x1, x2, x3, x4, x5, x6, x7}; -- const float* x = all[j]; -+ const float* x = all[0]; +- const float* x = all[j] + (size_t)b * width; ++ const float* x = all[0] + (size_t)b * width; 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 index ff8962f..f37a1ef 100644 --- a/tools/mutants/87-norm-weights-dropped.patch +++ b/tools/mutants/87-norm-weights-dropped.patch @@ -2,15 +2,15 @@ # 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 +index 0d40107..811b273 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 +@@ -27,7 +27,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; +- for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) o[i] = v[i] * scale * w[i]; ++ for (unsigned int i = threadIdx.x; i < n; i += blockDim.x) o[i] = v[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 index a3533f8..29bebb5 100644 --- a/tools/mutants/88-softcap-cap-ignored.patch +++ b/tools/mutants/88-softcap-cap-ignored.patch @@ -2,10 +2,10 @@ # 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 +index 0d40107..b0749fb 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 +@@ -61,7 +61,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; @@ -13,4 +13,4 @@ index 25e169f..162a088 100644 + if (i < n) x[i] = tanhf(x[i]); } - // A whole blend across depth in one launch, by one block of threads: + // A whole blend across depth in one launch, one block of threads per position of a batch: diff --git a/tools/mutants/89-ops-late-factor-off.patch b/tools/mutants/89-ops-late-factor-off.patch index 9c8fabf..823e6ef 100644 --- a/tools/mutants/89-ops-late-factor-off.patch +++ b/tools/mutants/89-ops-late-factor-off.patch @@ -2,15 +2,15 @@ # 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 79df46f..086b3ef 100644 +index a3a0faf..eed6bce 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs -@@ -656,7 +656,7 @@ impl<'m> Ops for CudaOps<'m> { +@@ -798,7 +798,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) }; +- let late = if layer.local { Late::none() } else { Late { pos, floor: cfg.log_floor, alpha: cfg.log_alpha } }; ++ let late = if layer.local { Late::none() } else { Late { pos, floor: cfg.log_floor, alpha: 0.0 } }; // Four matrices read the query input: the queries, the output gate, the - // relative-position vectors and the sinks. Stacked on the device, they are one + // relative-position vectors and the sinks. diff --git a/tools/mutants/90-ops-keys-not-clipped.patch b/tools/mutants/90-ops-keys-not-clipped.patch index 2244110..2794fc9 100644 --- a/tools/mutants/90-ops-keys-not-clipped.patch +++ b/tools/mutants/90-ops-keys-not-clipped.patch @@ -2,15 +2,15 @@ # 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 +index a3a0faf..5be2e2a 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)?; +@@ -827,7 +827,7 @@ impl<'m> Ops for CudaOps<'m> { + None => (rows_of(&pass.keys), rows_of(&pass.values)), + }; + self.project_kv(cfg, layer.wk, &layer.k_conv, &pass.k_ring, pos, k_in, key_rows)?; +- self.attention.head_scale_clip(key_rows, None, kv_heads, d, cfg.qk_clip, Late::none()).map_err(failed)?; ++ self.attention.head_scale_clip(key_rows, None, kv_heads, d, f32::MAX, Late::none()).map_err(failed)?; + let unnormed = self.vecs(batch, 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_rows, batch * kv_heads, d, cfg.eps).map_err(failed)?; diff --git a/tools/mutants/91-ops-value-row-of-first-token.patch b/tools/mutants/91-ops-value-row-of-first-token.patch index 05da2d7..4efcc08 100644 --- a/tools/mutants/91-ops-value-row-of-first-token.patch +++ b/tools/mutants/91-ops-value-row-of-first-token.patch @@ -2,15 +2,15 @@ # 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 +index a3a0faf..364e14e 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. +@@ -824,7 +824,7 @@ impl<'m> Ops for CudaOps<'m> { + let aside = if wraps { Some((self.vecs(batch, width)?, self.vecs(batch, width)?)) } else { None }; + let (key_rows, value_rows) = match &aside { + Some((k, v)) => (k.all(), v.all()), +- None => (rows_of(&pass.keys), rows_of(&pass.values)), ++ None => (rows_of(&pass.keys), Floats { buffer: &pass.values, at: 0, len: batch * width }), + }; + self.project_kv(cfg, layer.wk, &layer.k_conv, &pass.k_ring, pos, k_in, key_rows)?; + self.attention.head_scale_clip(key_rows, None, kv_heads, d, cfg.qk_clip, Late::none()).map_err(failed)?; diff --git a/tools/mutants/92-ops-gate-reads-queries.patch b/tools/mutants/92-ops-gate-reads-queries.patch index 43a769d..4c3fd64 100644 --- a/tools/mutants/92-ops-gate-reads-queries.patch +++ b/tools/mutants/92-ops-gate-reads-queries.patch @@ -1,16 +1,16 @@ # test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_tiny_model_matches # needs: gpu -# Bug: the output gate is cut from the wrong part of the stacked product: it reads the queries. +# Bug: the output gate is taken from the wrong part of the stacked product: it reads the queries. diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs -index 79df46f..9ccbb8c 100644 +index a3a0faf..2adae7e 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs -@@ -676,7 +676,7 @@ impl<'m> Ops for CudaOps<'m> { - self.matmat - .bf16(Bf16Matrix { buffer: &stacked, offset: 0, rows, cols: h }, &q_in.0.buffer, 1, &from_q.0.buffer, SEGS) - .map_err(failed)?; -- let (q, gate) = (from_q.part(0, q_width), from_q.part(q_width, q_width)); -+ let (q, gate) = (from_q.part(0, q_width), from_q.part(0, q_width)); - let (rel, sinks) = (from_q.part(2 * q_width, rel_width), from_q.part(2 * q_width + rel_width, heads)); +@@ -805,7 +805,7 @@ impl<'m> Ops for CudaOps<'m> { + let rel_width = heads * cfg.rel_dim; + let sizes = [(layer.wq, q_width), (layer.out_gate, q_width), (layer.wr, rel_width), (layer.sink, heads)]; + let from_q = self.products(&sizes, h, q_in)?; +- let (q, gate, rel, sinks) = (from_q.part(0), from_q.part(1), from_q.part(2), from_q.part(3)); ++ let (q, gate, rel, sinks) = (from_q.part(0), from_q.part(0), from_q.part(2), from_q.part(3)); // Queries: learned scale per element, length limit per head. + let q_scale = self.param(&layer.q_scale)?; diff --git a/tools/mutants/93-ops-second-list-is-first.patch b/tools/mutants/93-ops-second-list-is-first.patch index 10cf3f9..2e0307e 100644 --- a/tools/mutants/93-ops-second-list-is-first.patch +++ b/tools/mutants/93-ops-second-list-is-first.patch @@ -2,10 +2,10 @@ # needs: gpu # Bug: the experts' second matrices are started with the first matrices' job list. diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs -index 79df46f..6d3ad19 100644 +index a3a0faf..3166a5f 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs -@@ -429,7 +429,7 @@ impl<'m> CudaOps<'m> { +@@ -524,7 +524,7 @@ impl<'m> CudaOps<'m> { let route = Self::list(&mut self.route, dev, self.staging.len())?; self.stats.borrow_mut().copies_in += 1; dev.upload(&route, &self.staging).map_err(failed)?; @@ -13,4 +13,4 @@ index 79df46f..6d3ad19 100644 + let (at1, at2) = (route.handle + weights_bytes as u64, route.handle + weights_bytes as u64); // SAFETY (both): each list is the one `encode` returned for the same matrices and - // buffers, copied unchanged into `route`, which is not written again before the next + // buffers, with `count` jobs, copied unchanged into `route`, which is not written diff --git a/tools/mutants/98-batch-softmax-of-first-view.patch b/tools/mutants/98-batch-softmax-of-first-view.patch new file mode 100644 index 0000000..22d3338 --- /dev/null +++ b/tools/mutants/98-batch-softmax-of-first-view.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention attention_matches +# needs: gpu +# Bug: every token of a batch gets a softmax over as many tokens as the batch's first token sees. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..48f9f6f 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -199,7 +199,7 @@ extern "C" __global__ void attn_softmax(float* weights, unsigned int heads, unsi + __shared__ float part[1024]; + unsigned long long run = blockIdx.x; + if (run >= (unsigned long long)batch * heads) return; +- unsigned long long count = tokens_seen(pos + run / heads, window) + 1; ++ unsigned long long count = tokens_seen(pos, window) + 1; + float* w = weights + run * stride; + float best = -INFINITY; + for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) best = fmaxf(best, w[i]); diff --git a/tools/mutants/99-batch-late-factor-of-first.patch b/tools/mutants/99-batch-late-factor-of-first.patch new file mode 100644 index 0000000..83f448b --- /dev/null +++ b/tools/mutants/99-batch-late-factor-of-first.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention scaling_clipping +# needs: gpu +# Bug: every token of a batch is given the late factor of the batch's first token. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index 10196bd..088f2dc 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -45,7 +45,7 @@ extern "C" __global__ void head_scale_clip(float* x, const float* scale, unsigne + } + __syncthreads(); + float factor = part[0]; +- float late = 1.0f + alpha * logf(fmaxf((float)(at + 1) / floor, 1.0f)); ++ float late = 1.0f + alpha * logf(fmaxf((float)(pos + 1) / floor, 1.0f)); + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) { + float t = v[i]; + if (factor < 1.0f) t *= factor;