Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 25 additions & 15 deletions crates/dluth-cuda/kernels/attention.cu
Original file line number Diff line number Diff line change
Expand Up @@ -233,26 +233,36 @@ extern "C" __global__ void attn_softmax(float* weights, unsigned int heads, unsi
for (unsigned long long i = threadIdx.x; i < count; i += blockDim.x) w[i] /= sum;
}

// The weighted sum of the values: out[b][h][e] = sum over the tokens query b sees, oldest
// first, of the token's weight times its value. The sink has no value.
// CPU reference: the summing loop of sinkattn::attend.
// The weighted sum of the values: out[b][h][e] = sum over the tokens query b sees of the
// token's weight times its value. The sink has no value. `segs` threads share one output
// element, each taking every segs-th token, and their sums are combined with warp shuffles
// (segs is a power of two up to 32, the block size a multiple of 32): one thread walking
// every token a query sees took as long as the tokens are many.
// CPU reference: the summing loop of sinkattn::attend, which adds oldest first.
extern "C" __global__ void attn_values(const float* weights, const float* values, float* out,
unsigned int heads, unsigned int kv_heads, unsigned int dim,
unsigned long long pos, unsigned long long window,
unsigned long long cap, unsigned long long stride,
unsigned int batch) {
unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long run = index / dim;
unsigned int e = (unsigned int)(index % dim);
if (run >= (unsigned long long)batch * heads) return;
unsigned int h = (unsigned int)(run % heads);
unsigned long long at = pos + run / heads;
unsigned long long seen = tokens_seen(at, window);
const float* w = weights + run * stride;
unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e;
unsigned int batch, unsigned int segs) {
unsigned long long thread = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long element = thread / segs;
unsigned int seg = (unsigned int)(thread % segs);
unsigned long long run = element / dim;
unsigned int e = (unsigned int)(element % dim);
bool live = run < (unsigned long long)batch * heads;
float total = 0.0f;
for (unsigned long long d = seen; d-- > 0;) total += w[d] * values[((at - d) % cap) * kv_heads * dim + column];
out[index] = total;
if (live) {
unsigned int h = (unsigned int)(run % heads);
unsigned long long at = pos + run / heads;
unsigned long long seen = tokens_seen(at, window);
const float* w = weights + run * stride;
unsigned long long column = (size_t)(h / (heads / kv_heads)) * dim + e;
for (unsigned long long d = seg; d < seen; d += segs)
total += w[d] * values[((at - d) % cap) * kv_heads * dim + column];
}
// Every thread of the warp takes part in the shuffles, including those past the last element.
for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset);
if (live && seg == 0) out[element] = total;
}

// x[i] *= sigmoid(gate[i]). CPU reference: cpu::sigmoid.
Expand Down
35 changes: 35 additions & 0 deletions crates/dluth-cuda/kernels/matmat_bf16.cu
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,38 @@ MATMAT_BF16(1) MATMAT_BF16(2) MATMAT_BF16(3) MATMAT_BF16(4)
MATMAT_BF16(5) MATMAT_BF16(6) MATMAT_BF16(7) MATMAT_BF16(8)
MATMAT_BF16(9) MATMAT_BF16(10) MATMAT_BF16(11) MATMAT_BF16(12)
MATMAT_BF16(13) MATMAT_BF16(14) MATMAT_BF16(15) MATMAT_BF16(16)

// The same product for a matrix of few, long rows (a 64 by 4608 gate, a 128 by 2304
// router). With at most 32 threads to a row, as above, each thread walks hundreds of
// columns one load after another, and the kernel's time is that walk, not the bytes. Here
// a whole block of 256 threads shares one row for one vector: thread t takes every 256th
// group of eight columns, the sums are added within each warp by shuffles, and one thread
// adds the eight warps'.
// Needs what the fast path above needs: cols a multiple of 8, the pointers 16-byte aligned.
extern "C" __global__ void matmat_bf16_short(const unsigned short* w, const float* x, float* y,
unsigned int rows, unsigned int cols, unsigned int batch) {
__shared__ float part[8];
unsigned int b = blockIdx.x / rows;
unsigned int row = blockIdx.x % rows;
if (b >= batch) return;
const unsigned short* wr = w + (size_t)row * cols;
const float* xv = x + (size_t)b * cols;
float acc = 0.0f;
for (unsigned int c = threadIdx.x * 8; c < cols; c += blockDim.x * 8) {
uint4 bits = *reinterpret_cast<const uint4*>(wr + c);
const float4* xb = reinterpret_cast<const float4*>(xv + c);
float4 lo = xb[0], hi = xb[1];
acc += __uint_as_float(bits.x << 16) * lo.x + __uint_as_float(bits.x & 0xffff0000u) * lo.y
+ __uint_as_float(bits.y << 16) * lo.z + __uint_as_float(bits.y & 0xffff0000u) * lo.w
+ __uint_as_float(bits.z << 16) * hi.x + __uint_as_float(bits.z & 0xffff0000u) * hi.y
+ __uint_as_float(bits.w << 16) * hi.z + __uint_as_float(bits.w & 0xffff0000u) * hi.w;
}
for (int offset = 16; offset > 0; offset >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, offset);
if (threadIdx.x % 32 == 0) part[threadIdx.x / 32] = acc;
__syncthreads();
if (threadIdx.x == 0) {
float total = 0.0f;
for (unsigned int i = 0; i < blockDim.x / 32; ++i) total += part[i];
y[(size_t)b * rows + row] = total;
}
}
159 changes: 115 additions & 44 deletions crates/dluth-cuda/kernels/small_ops.cu
Original file line number Diff line number Diff line change
Expand Up @@ -64,51 +64,8 @@ extern "C" __global__ void softcap_inplace(float* x, unsigned int n, float cap)
if (i < n) x[i] = cap * tanhf(x[i] / cap);
}

// A whole blend across depth in one launch, one block of threads per position of a batch:
// score_j = (query . candidate_j) * scale; weights = softmax(scores);
// out[b] = sum over j of weights_j * candidate_j
// Position b's `count` candidates of `width` floats are one after another in `candidates`,
// after those of the positions before it. CPU reference: depthmix::mix_normalized, once per
// position.
// Most candidates a blend takes in one launch (see blend_many).
#define BLEND_MAX 16
extern "C" __global__ void blend_mix(const float* query, const float* candidates, float* out,
unsigned int count, unsigned int width, float scale,
unsigned int batch) {
__shared__ float part[BLEND_MAX][256];
__shared__ float weight[BLEND_MAX];
if (blockIdx.x >= batch) return;
const float* mine = candidates + (size_t)blockIdx.x * count * width;
float* o = out + (size_t)blockIdx.x * width;
float dot[BLEND_MAX];
for (unsigned int j = 0; j < count; ++j) dot[j] = 0.0f;
for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) {
float q = query[i];
for (unsigned int j = 0; j < count; ++j) dot[j] += q * mine[(size_t)j * width + i];
}
for (unsigned int j = 0; j < count; ++j) part[j][threadIdx.x] = dot[j];
__syncthreads();
if (threadIdx.x == 0) {
float best = -INFINITY;
for (unsigned int j = 0; j < count; ++j) {
float s = 0.0f;
for (unsigned int t = 0; t < blockDim.x; ++t) s += part[j][t];
weight[j] = s * scale;
best = fmaxf(best, weight[j]);
}
float sum = 0.0f;
for (unsigned int j = 0; j < count; ++j) {
weight[j] = expf(weight[j] - best);
sum += weight[j];
}
for (unsigned int j = 0; j < count; ++j) weight[j] /= sum;
}
__syncthreads();
for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) {
float total = 0.0f;
for (unsigned int j = 0; j < count; ++j) total += weight[j] * mine[(size_t)j * width + i];
o[i] = total;
}
}

// Up to eight candidates, each wherever it lives and each a batch of vectors of `width`,
// normalized into one buffer in one launch:
Expand Down Expand Up @@ -144,3 +101,117 @@ extern "C" __global__ void vec_copy(const float* x, float* out, unsigned int n)
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = x[i];
}

// A whole blend across depth for up to four queries at once, from the candidates as they
// are (not normalized beforehand), each optionally followed by a normalization with
// learned weights. For position b of a batch and query q:
// n_j = candidate_j[b] / sqrt(mean(candidate_j[b]^2) + blend_eps)
// weights = softmax over j of (query_q . n_j) * scale
// mixed = sum over j of weights_j * n_j
// out_q[b] = mixed if norm_q is null
// = mixed / sqrt(mean(mixed^2) + norm_eps) * norm_q otherwise
// One block of threads per (position, query). Each candidate is its own buffer holding the
// batch; each query and each norm is one vector of `width`; each output holds the batch.
// CPU reference: depthmix::normalize, depthmix::mix_normalized and cpu::rmsnorm, one after
// the other. Here a candidate's dot product with the query is taken before the candidate
// is scaled, and the sums are added in a different order.
// The sum of `v` over the 32 threads of a warp, in every one of them. Every thread of the
// warp must call it.
__device__ __forceinline__ float warp_sum(float v) {
for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_xor_sync(0xffffffffu, v, offset);
return v;
}

// Sums are first taken within each warp of 32 threads, by shuffles, and one thread then
// adds the few warps' sums: a block's single thread adding every thread's part one after
// the other took most of this kernel's time.
#define BLEND_QUERIES 4
#define BLEND_WARPS 8
extern "C" __global__ void blend_many(
const float* c0, const float* c1, const float* c2, const float* c3, const float* c4, const float* c5,
const float* c6, const float* c7, const float* c8, const float* c9, const float* c10, const float* c11,
const float* c12, const float* c13, const float* c14, const float* c15,
const float* q0, const float* q1, const float* q2, const float* q3,
const float* w0, const float* w1, const float* w2, const float* w3,
float* o0, float* o1, float* o2, float* o3,
unsigned int count, unsigned int width, float scale, float blend_eps, float norm_eps,
unsigned int batch, unsigned int queries) {
__shared__ float squares[BLEND_MAX][BLEND_WARPS];
__shared__ float dots[BLEND_MAX][BLEND_WARPS];
__shared__ float coefficient[BLEND_MAX];
unsigned int warp = threadIdx.x / 32, lane = threadIdx.x % 32, warps = blockDim.x / 32;
unsigned int b = blockIdx.x / queries;
unsigned int which = blockIdx.x % queries;
if (b >= batch) return;
const float* candidates[BLEND_MAX] = {c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15};
const float* all_queries[BLEND_QUERIES] = {q0, q1, q2, q3};
const float* all_norms[BLEND_QUERIES] = {w0, w1, w2, w3};
float* all_outs[BLEND_QUERIES] = {o0, o1, o2, o3};
const float* query = all_queries[which];
const float* norm = all_norms[which];
float* out = all_outs[which] + (size_t)b * width;
size_t at = (size_t)b * width;

float mine_squares[BLEND_MAX];
float mine_dots[BLEND_MAX];
for (unsigned int j = 0; j < count; ++j) mine_squares[j] = mine_dots[j] = 0.0f;
for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) {
float q = query[i];
for (unsigned int j = 0; j < count; ++j) {
float x = candidates[j][at + i];
mine_squares[j] += x * x;
mine_dots[j] += q * x;
}
}
for (unsigned int j = 0; j < count; ++j) {
float s = warp_sum(mine_squares[j]);
float d = warp_sum(mine_dots[j]);
if (lane == 0) {
squares[j][warp] = s;
dots[j][warp] = d;
}
}
__syncthreads();
if (threadIdx.x == 0) {
float best = -INFINITY;
for (unsigned int j = 0; j < count; ++j) {
float s = 0.0f, d = 0.0f;
for (unsigned int t = 0; t < warps; ++t) {
s += squares[j][t];
d += dots[j][t];
}
float inverse = 1.0f / sqrtf(s / (float)width + blend_eps);
squares[j][0] = inverse;
dots[j][0] = d * inverse * scale;
best = fmaxf(best, dots[j][0]);
}
float sum = 0.0f;
for (unsigned int j = 0; j < count; ++j) {
coefficient[j] = expf(dots[j][0] - best);
sum += coefficient[j];
}
// The weight of a candidate times the factor that normalizes it.
for (unsigned int j = 0; j < count; ++j) coefficient[j] = coefficient[j] / sum * squares[j][0];
}
__syncthreads();
float mixed_squares = 0.0f;
for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) {
float total = 0.0f;
for (unsigned int j = 0; j < count; ++j) total += coefficient[j] * candidates[j][at + i];
out[i] = total;
mixed_squares += total * total;
}
if (norm == nullptr) return;
mixed_squares = warp_sum(mixed_squares);
__syncthreads();
if (lane == 0) squares[0][warp] = mixed_squares;
__syncthreads();
if (threadIdx.x == 0) {
float s = 0.0f;
for (unsigned int t = 0; t < warps; ++t) s += squares[0][t];
coefficient[0] = 1.0f / sqrtf(s / (float)width + norm_eps);
}
__syncthreads();
float factor = coefficient[0];
for (unsigned int i = threadIdx.x; i < width; i += blockDim.x) out[i] = out[i] * factor * norm[i];
}
15 changes: 13 additions & 2 deletions crates/dluth-cuda/src/attention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ fn real(p: &mut f32) -> *mut c_void {
/// Most consecutive tokens one launch takes.
pub const MAX_BATCH: usize = 16;

/// Threads that share one element of attention's output, each summing every 16th token.
const VALUE_SEGS: u32 = 16;
// The kernel combines them with warp shuffles, which need a power of two up to 32.
const _: () = assert!(VALUE_SEGS.is_power_of_two() && VALUE_SEGS <= 32);

/// The shape of a layer's attention: query heads, key-value heads, and the size of a head.
#[derive(Clone, Copy, Debug)]
pub struct Heads {
Expand Down Expand Up @@ -527,11 +532,14 @@ impl<'m> Attention<'m> {
// table and the sinks, and writes into each (query, head) run of `stride` floats at
// most seen + 1 entries, where seen + 1 is at most `stride`. attn_softmax rewrites
// those entries in place, one block of 256 threads per run. attn_values reads them
// and the values' rows and writes runs * dim floats to `out`. Every extent was
// and the values' rows and writes runs * dim floats to `out`, VALUE_SEGS threads
// to an element (a power of two up to 32, in blocks of a multiple of 32, as its
// shuffles need). Every extent was
// checked above, and nothing written overlaps anything read.
unsafe { self.scores.launch((blocks((runs * stride) as u64, 256)?, 1, 1), (256, 1, 1), &mut args)? };
let mut args = [ptr(&mut pw), num(&mut h), big(&mut p), big(&mut win), big(&mut st), num(&mut b)];
unsafe { self.softmax.launch((runs as u32, 1, 1), (256, 1, 1), &mut args)? };
let mut segs = VALUE_SEGS;
let mut args = [
ptr(&mut pw),
ptr(&mut pv),
Expand All @@ -544,8 +552,11 @@ impl<'m> Attention<'m> {
big(&mut cap),
big(&mut st),
num(&mut b),
num(&mut segs),
];
unsafe { self.values.launch((blocks((runs * dim) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) }
unsafe {
self.values.launch((blocks((runs * dim) as u64 * VALUE_SEGS as u64, 256)?, 1, 1), (256, 1, 1), &mut args)
}
}

/// How many floats of scratch `attend` needs per head for a batch of `batch` queries
Expand Down
29 changes: 28 additions & 1 deletion crates/dluth-cuda/src/matmat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ pub struct Bf16Matrix<'b> {
pub cols: usize,
}

/// A matrix of at most this many rows, each of at least `SHORT_COLS` columns, is given a
/// block of threads per row.
const SHORT_ROWS: usize = 256;
const SHORT_COLS: usize = 1024;

fn pw_of(w: &Bf16Matrix) -> u64 {
w.buffer.handle + w.offset as u64
}
Expand All @@ -34,12 +39,14 @@ pub struct Matmat<'m> {
dev: &'m CudaDevice,
/// `bf16[b - 1]` multiplies a batch of `b`.
bf16: Vec<Kernel<'m>>,
/// For a matrix of few, long rows.
short: Kernel<'m>,
}

impl<'m> Matmat<'m> {
pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result<Self, CudaError> {
let bf16 = (1..=MAX_BATCH).map(|b| module.kernel(&format!("matmat_bf16_b{b}"))).collect::<Result<_, _>>()?;
Ok(Matmat { dev, bf16 })
Ok(Matmat { dev, bf16, short: module.kernel("matmat_bf16_short")? })
}

/// Starts `y[b][r] = sum_c w[r][c] * x[b][c]` for `batch` vectors and returns without
Expand Down Expand Up @@ -79,6 +86,26 @@ impl<'m> Matmat<'m> {
let mut wide =
u32::from(w.cols.is_multiple_of(8) && aligned(pw_of(&w)) && aligned(x.handle) && aligned(y.handle));
let (mut rows, mut cols, mut s) = (w.rows as u32, w.cols as u32, segs);
// Few, long rows: a block of threads per row and vector reads them sooner than a
// few threads walking each row would.
if wide == 1 && w.rows <= SHORT_ROWS && w.cols >= SHORT_COLS {
let mut b = batch as u32;
let mut args = [
&mut pw as *mut u64 as *mut c_void,
&mut px as *mut u64 as *mut c_void,
&mut py as *mut u64 as *mut c_void,
&mut rows as *mut u32 as *mut c_void,
&mut cols as *mut u32 as *mut c_void,
&mut b as *mut u32 as *mut c_void,
];
// SAFETY: the arguments match matmat_bf16_short(const unsigned short*, const
// float*, float*, unsigned, unsigned, unsigned). One block of 256 threads (8
// whole warps, the size of the kernel's shared array) per row and vector reads
// that row's cols weights and that vector's cols floats with 16-byte loads, and
// writes one float: the extents checked above, and `wide` says the loads are
// aligned and a row is a whole number of them.
return unsafe { self.short.launch(((w.rows * batch) as u32, 1, 1), (256, 1, 1), &mut args) };
}
let mut args = [
&mut pw as *mut u64 as *mut c_void,
&mut px as *mut u64 as *mut c_void,
Expand Down
Loading
Loading