okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01529aaa8
main
1// src/kernels/cuda/gdn.cu - P2.S2: the gated delta-net's non-projection parts. 2// 3// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no 4// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end. 5#include "strata/kernels/gdn.hpp" 6 7#include <cuda_runtime.h> 8 9#include <cmath> 10#include <cstdio> 11#include <cstdlib> 12 13namespace strata::kernels { 14namespace { 15 16constexpr int JTHREADS = 32; ///< threads along j, the state's fast axis 17/// Heads staged per block. **THIS IS A LATENCY-HIDING KNOB, NOT A CAPACITY ONE, AND IT WAS SET WRONG.** 18/// 19/// The kernel is one thread per `(h, j)` COLUMN of the state, so the thread count is fixed at 20/// `S * h_v` = 128 * 48 = **6,144** no matter how the work is packed - and `MAX_H` decides only how many of 21/// those columns share a block: 22/// 23/// MAX_H = 8 grid = (S/32, h_v/8) = (4, 6) = 24 blocks x 32 threads -> 1 warp on 24 of 48 SMs 24/// MAX_H = 1 grid = (S/32, h_v/1) = (4, 48) = 192 blocks x 32 threads -> 4 warps on every SM 25/// 26/// Each thread walks `i` in 0..S-1 TWICE per head with a strided global load each step, so it is entirely 27/// latency-bound: a warp that issues one 128-byte transaction and then waits ~600 cycles needs other warps to 28/// run meanwhile, and at 24 blocks there were none. Measured 0.2800 ms per GDN block - 10 ms of a 71.5 ms 29/// token, 14%, in a kernel touching 12.6 MB that a 643 GB/s card should do in 0.020 ms. 30/// 31/// The arithmetic does not change at all: the same columns are computed by the same code, in different blocks. 32constexpr int MAX_H = 1; ///< heads staged in shared memory per block 33 34/// ggml_compute_softplus_f32: log1p(exp(x)), with the large-x branch that avoids overflow. 35__device__ __forceinline__ float softplus_f(float x) { return x > 20.0f ? x : log1pf(expf(x)); } 36__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); } 37 38/// One step of the recurrence. One thread per (h, j) column of the state. 39/// 40/// `ks`/`qs` stage `k[idx[h]]` and `q[idx[h]]` for the block's heads. Within a warp h is constant and j 41/// varies, so the staged row is read with a single broadcast - which is also why the GLOBAL loads of 42/// `q`/`k` are done once per block into shared instead of once per thread. 43__global__ void gdn_step_kernel(float* __restrict__ state, const float* __restrict__ q, 44 const float* __restrict__ k, const float* __restrict__ v, 45 const float* __restrict__ gate, const float* __restrict__ beta, 46 float* __restrict__ o, int S, int h_k, int h_v) { 47 __shared__ float ks[MAX_H][128]; 48 __shared__ float qs[MAX_H][128]; 49 __shared__ float dec_s[MAX_H]; 50 __shared__ float beta_s[MAX_H]; 51 52 const int h0 = blockIdx.y * MAX_H; 53 const int nh = min(MAX_H, h_v - h0); 54 const int j = blockIdx.x * JTHREADS + threadIdx.x; 55 56 // stage this block's q/k rows and its per-head scalars 57 for (int hi = 0; hi < nh; ++hi) { 58 const int h = h0 + hi; 59 const int src = h % h_k; // MODULO head pairing 60 for (int i = threadIdx.x; i < S; i += JTHREADS) { 61 ks[hi][i] = k[src * S + i]; 62 qs[hi][i] = q[src * S + i]; 63 } 64 if (threadIdx.x == 0) { 65 dec_s[hi] = expf(gate[h]); 66 beta_s[hi] = beta[h]; 67 } 68 } 69 __syncthreads(); 70 if (j >= S) return; 71 72 for (int hi = 0; hi < nh; ++hi) { 73 const int h = h0 + hi; 74 const float dec = dec_s[hi], b = beta_s[hi]; 75 float* col = state + (size_t) h * S + j; // (S, h_v, S) with j fastest 76 const size_t stride = (size_t) h_v * S; 77 78 // pass 1: decay the state and contract it against k. Decay BEFORE the update - PROPERTY 5. 79 float sk = 0.0f; 80 for (int i = 0; i < S; ++i) { 81 const float s = col[(size_t) i * stride] * dec; 82 col[(size_t) i * stride] = s; 83 sk += s * ks[hi][i]; 84 } 85 const float d = (v[(size_t) h * S + j] - sk) * b; 86 // pass 2: the rank-1 update, then read out against q using the UPDATED state 87 float dot = 0.0f; 88 for (int i = 0; i < S; ++i) { 89 const float s = col[(size_t) i * stride] + ks[hi][i] * d; 90 col[(size_t) i * stride] = s; 91 dot += s * qs[hi][i]; 92 } 93 o[(size_t) h * S + j] = dot; 94 } 95} 96 97/// `ggml_ssm_conv`: out[c] = sum_i inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x], and the state slides. 98/// One thread per channel; d_conv is 4, so the serial work per thread is a 4-tap dot and an unrolled shift. 99__global__ void gdn_conv_kernel(float* __restrict__ cs, const float* __restrict__ x, 100 const float* __restrict__ kW, float* __restrict__ out, int C, int dc) { 101 const int c = blockIdx.x * blockDim.x + threadIdx.x; 102 if (c >= C) return; 103 float* st = cs + (size_t) c * (dc - 1); 104 const float* w = kW + (size_t) c * dc; 105 float acc = 0.0f; 106 for (int i = 0; i < dc - 1; ++i) acc += st[i] * w[i]; // kernel[0] reads the OLDEST state row 107 acc += x[c] * w[dc - 1]; // the new input lands in the LAST tap 108 out[c] = acc; 109 for (int i = 0; i < dc - 2; ++i) st[i] = st[i + 1]; // slide: drop the oldest, append the newest 110 st[dc - 2] = x[c]; 111} 112 113/// `build_gdn_l2_norm`, one warp per row: x / sqrt(sum(x^2) + eps) over the last axis. 114/// 115/// The sum is accumulated in DOUBLE, as `ref/gdn.py` does (`l2_norm(q.astype(np.float64), eps)`), because the 116/// reference deliberately computes this one in float64 and then casts - so matching its precision is part of 117/// transcribing it. 118__global__ void gdn_l2_kernel(float* __restrict__ x, int cols, float eps) { 119 const int row = blockIdx.x; 120 float* p = x + (size_t) row * cols; 121 double acc = 0.0; 122 for (int i = threadIdx.x; i < cols; i += blockDim.x) acc += (double) p[i] * (double) p[i]; 123 // warp reduction 124 for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); 125 __shared__ double ssum; 126 if (threadIdx.x == 0) ssum = acc; 127 __syncthreads(); 128 const float inv = (float) (1.0 / sqrt(ssum + (double) eps)); 129 for (int i = threadIdx.x; i < cols; i += blockDim.x) p[i] *= inv; 130} 131 132/// y = rms_norm(o, eps) * ssm_norm * sigmoid(z), one warp per head, norm over that head's S values. 133__global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __restrict__ z, 134 const float* __restrict__ ssm_norm, float* __restrict__ y, int S, 135 float eps) { 136 const int h = blockIdx.x; 137 const float* po = o + (size_t) h * S; 138 const float* pz = z + (size_t) h * S; 139 float* py = y + (size_t) h * S; 140 double acc = 0.0; 141 for (int i = threadIdx.x; i < S; i += blockDim.x) acc += (double) po[i] * (double) po[i]; 142 for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); 143 __shared__ double ssum; 144 if (threadIdx.x == 0) ssum = acc; 145 __syncthreads(); 146 const float inv = (float) (1.0 / sqrt(ssum / (double) S + (double) eps)); 147 for (int i = threadIdx.x; i < S; i += blockDim.x) 148 py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]); 149} 150 151} // namespace 152 153void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate, 154 const float* beta, float* o, const GdnShapes& s, void* stream) { 155 if (s.S <= 0 || s.h_k <= 0 || s.h_v <= 0) return; 156 if (s.S > 128) { 157 std::fprintf(stderr, "gdn_step: S = %lld exceeds the staged 128 (`ks`/`qs` are [8][128])\n", 158 (long long) s.S); 159 std::exit(1); 160 } 161 const dim3 grid((unsigned) ((s.S + JTHREADS - 1) / JTHREADS), 162 (unsigned) ((s.h_v + MAX_H - 1) / MAX_H)); 163 gdn_step_kernel<<<grid, JTHREADS, 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, o, (int) s.S, 164 (int) s.h_k, (int) s.h_v); 165 if (stream == nullptr) { 166 const cudaError_t e = cudaDeviceSynchronize(); 167 if (e != cudaSuccess) { 168 std::fprintf(stderr, "gdn_step: %s\n", cudaGetErrorString(e)); 169 std::exit(1); 170 } 171 } 172} 173 174void gdn_conv_step(float* conv_state, const float* x, const float* kW, float* out, int64_t channels, 175 int64_t d_conv, void* stream) { 176 if (channels <= 0 || d_conv < 1) return; 177 const int blocks = (int) ((channels + 255) / 256); 178 gdn_conv_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(conv_state, x, kW, out, (int) channels, 179 (int) d_conv); 180 if (stream == nullptr) { 181 const cudaError_t e = cudaDeviceSynchronize(); 182 if (e != cudaSuccess) { 183 std::fprintf(stderr, "gdn_conv_step: %s\n", cudaGetErrorString(e)); 184 std::exit(1); 185 } 186 } 187} 188 189void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream) { 190 if (rows <= 0 || cols <= 0) return; 191 if (cols > 1024) { 192 std::fprintf(stderr, "gdn_l2_norm: cols = %lld exceeds the 1024-wide warp reduction\n", (long long) cols); 193 std::exit(1); 194 } 195 gdn_l2_kernel<<<(unsigned) rows, 32, 0, (cudaStream_t) stream>>>(x, (int) cols, eps); 196 if (stream == nullptr) { 197 const cudaError_t e = cudaDeviceSynchronize(); 198 if (e != cudaSuccess) { 199 std::fprintf(stderr, "gdn_l2_norm: %s\n", cudaGetErrorString(e)); 200 std::exit(1); 201 } 202 } 203} 204 205/// `beta = sigmoid(beta)`, in place, over the `h_v` per-head scalars. 206/// 207/// **THIS IS `build_layer_attn_linear` L889, AND LEAVING IT OUT WAS THE C1 BUG.** The reference computes 208/// `beta = ggml_sigmoid(ssm_beta @ cur)` and hands the RESULT to the delta net; `gdn_step_kernel` is documented 209/// as `d[h,j] = (v[h,j] - sk[h,j]) * beta[h]` and applies no sigmoid of its own, so the layer glue owes it one. 210/// The engine passed the raw pre-activation, which is unbounded and signed - the delta-net write strength then 211/// stops being a fraction and the whole recurrence is wrong from layer 0. 212/// 213/// **IT SURVIVED `gdn_parity` BECAUSE THAT TEST SUPPLIES ITS OWN `beta`.** The kernel was always right; only 214/// the glue between the projection and the kernel was wrong, and `ref/gdn.py` (`beta = sigmoid(wbeta @ x)`) and 215/// `ref/model.py` (`beta = G.sigmoid(proj(...))`) both get it right - so the two transcriptions agreed with 216/// each other and neither was ever compared against the C++ that actually runs. 217__global__ void gdn_beta_gate_kernel(float* __restrict__ beta, int n) { 218 const int i = blockIdx.x * blockDim.x + threadIdx.x; 219 if (i < n) beta[i] = sigmoid_f(beta[i]); 220} 221 222void gdn_beta_gate(float* beta, int64_t h_v, void* stream) { 223 if (beta == nullptr || h_v <= 0) return; 224 const int n = (int) h_v; 225 gdn_beta_gate_kernel<<<(unsigned) ((n + 127) / 128), 128, 0, (cudaStream_t) stream>>>(beta, n); 226 if (stream == nullptr) { 227 const cudaError_t e = cudaDeviceSynchronize(); 228 if (e != cudaSuccess) { 229 std::fprintf(stderr, "gdn_beta_gate: %s\n", cudaGetErrorString(e)); 230 std::exit(1); 231 } 232 } 233} 234 235void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S, 236 float eps, void* stream) { 237 if (h_v <= 0 || S <= 0) return; 238 gdn_out_norm_kernel<<<(unsigned) h_v, 32, 0, (cudaStream_t) stream>>>(o, z, ssm_norm, y, (int) S, eps); 239 if (stream == nullptr) { 240 const cudaError_t e = cudaDeviceSynchronize(); 241 if (e != cudaSuccess) { 242 std::fprintf(stderr, "gdn_out_norm: %s\n", cudaGetErrorString(e)); 243 std::exit(1); 244 } 245 } 246} 247 248} // namespace strata::kernels