okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a0b666cff
main
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3// src/ds4/ds4_kernels.cu - DeepSeek-V4.1's device kernels (see ds4_kernels.cuh). No fast math here: the rotary 4// angles, the softmaxes and the roundings follow the reference's F32 arithmetic. A window's token is blockIdx.y. 5#include "ds4_kernels.cuh" 6#include "ds4_numerics.cuh" 7#include "ds4_q6k.cuh" 8#include "ds4_attn_split.cuh" 9 10#include <cuda_fp16.h> 11 12#include <algorithm> 13#include <atomic> 14#include <cfloat> 15#include <cstdlib> 16#include <map> 17#include <mutex> 18#include <cstdio> 19 20namespace strata::ds4 { 21namespace { 22 23constexpr int kThreads = 256; 24 25__device__ __forceinline__ float bf16f(uint16_t b) { return __uint_as_float((uint32_t) b << 16); } 26 27__device__ __forceinline__ uint16_t f2bf16(float f) { // round to nearest even (the values here are exact anyway) 28 uint32_t u = __float_as_uint(f); 29 if ((u & 0x7f800000u) == 0x7f800000u) return (uint16_t) (u >> 16); 30 u += 0x7fffu + ((u >> 16) & 1u); 31 return (uint16_t) (u >> 16); 32} 33 34__device__ __forceinline__ float warp_sum(float v) { 35 for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); 36 return v; 37} 38__device__ __forceinline__ float warp_max(float v) { 39 for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); 40 return v; 41} 42 43// block-wide sum for blockDim.x <= 1024 (a multiple of 32); every thread gets the result 44__device__ float block_sum(float v) { 45 __shared__ float red[32]; 46 __shared__ float total; 47 const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; 48 v = warp_sum(v); 49 if (lane == 0) red[w] = v; 50 __syncthreads(); 51 if (w == 0) { 52 float t = lane < (int) (blockDim.x >> 5) ? red[lane] : 0.0f; 53 t = warp_sum(t); 54 if (lane == 0) total = t; 55 } 56 __syncthreads(); 57 const float r = total; 58 __syncthreads(); 59 return r; 60} 61 62// 2^ceil(log2(x)) for a positive normal x (the reference's fast_round_scale) 63__device__ __forceinline__ float pow2_ceil(float x) { 64 const uint32_t b = __float_as_uint(x); 65 const int e = (int) ((b >> 23) & 0xffu) - 127 + ((b & 0x7fffffu) != 0u ? 1 : 0); 66 return __uint_as_float((uint32_t) (e + 127) << 23); 67} 68 69// a load of memory another device or the host writes, never from a stale cache line (CUDA's __ldcv; HIP: volatile 70// 32-bit loads) 71template <class T> 72__device__ __forceinline__ T ld_fresh(const T* p) { 73#if defined(STRATA_USE_HIP) 74 T v; 75 const volatile uint32_t* s = (const volatile uint32_t*) p; 76 uint32_t* d = (uint32_t*) &v; 77#pragma unroll 78 for (int i = 0; i < (int) (sizeof(T) / 4); ++i) d[i] = s[i]; 79 return v; 80#else 81 return __ldcv(p); 82#endif 83} 84 85__device__ __forceinline__ float fp8_rt(float v) { return e4m3_round(v); } // E4M3, nearest even (input clamped) 86 87__device__ __forceinline__ float e2m1_rt(float v) { // E2M1 magnitudes 0 .5 1 1.5 2 3 4 6, nearest, ties to even 88 const float a = fabsf(v); 89 float r; 90 if (a <= 0.25f) r = 0.0f; 91 else if (a < 0.75f) r = 0.5f; 92 else if (a <= 1.25f) r = 1.0f; 93 else if (a < 1.75f) r = 1.5f; 94 else if (a <= 2.5f) r = 2.0f; 95 else if (a < 3.5f) r = 3.0f; 96 else if (a <= 5.0f) r = 4.0f; 97 else r = 6.0f; 98 return copysignf(r, v); 99} 100 101// ---------------------------------------------------------------- the caches' packed rows (kv_row_bytes) 102// the E2M1 code of a value e2m1_rt returned (bit 3 the sign, -0 kept; magnitudes 0 .5 1 1.5 2 3 4 6 as 0 .. 7) 103__device__ __forceinline__ uint32_t e2m1_code(float q) { 104 const float a = fabsf(q); 105 const uint32_t m = a <= 1.5f ? (uint32_t) (a * 2.0f) : a <= 2.0f ? 4u : a <= 3.0f ? 5u : a <= 4.0f ? 6u : 7u; 106 return m | ((__float_as_uint(q) >> 31) << 3); 107} 108// the E4M3 code of v / 2^k for a v whose quotient is an E4M3 value (|v / 2^k| <= 448, at most 4 significant bits, a 109// multiple of 2^-9; v 0 or a normal F32): integer arithmetic, exact, -0 kept 110__device__ __forceinline__ uint32_t e4m3_code(float v, int k = 0) { 111 const uint32_t b = __float_as_uint(v), sg = (b >> 24) & 0x80u, a = b & 0x7fffffffu; 112 if (a == 0u) return sg; 113 const int e = (int) (a >> 23) - 127 - k; // the quotient's binade 114 if (e >= -6) return sg | ((uint32_t) (e + 7) << 3) | ((a >> 20) & 7u); 115 return sg | (((a & 0x7fffffu) | 0x800000u) >> (14 - e)); // a subnormal: m 2^-9 116} 117// an E2M1 code's value times 2^-14, by the conversion of an FP16 (the code's sign, exponent and mantissa bit are an 118// FP16's at bits 15 and 11..9: exact, subnormals too) - the readers' decode: (value 2^-14) (scale 2^14) is value * scale 119// exactly, both products exact 120__device__ __forceinline__ float e2m1_val14(uint32_t c) { 121 return __half2float(__ushort_as_half((unsigned short) (((c & 8u) << 12) | ((c & 7u) << 9)))); 122} 123// a UE8M0 scale byte's value (the byte the F32 exponent: 2^(b - 127); 0 -> 0, an unwritten row's) 124__device__ __forceinline__ float ue8m0_val(uint32_t b) { return __uint_as_float(b << 23); } 125 126// ---------------------------------------------------------------- embed 127__global__ void embed_kernel(const uint16_t* __restrict__ rows, float* __restrict__ h, int dim, int hc) { 128 const int e = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 129 if (e >= dim) return; 130 const float v = bf16f(rows[(size_t) t * dim + e]); 131 for (int s = 0; s < hc; ++s) h[((size_t) t * hc + s) * dim + e] = v; 132} 133 134// ---------------------------------------------------------------- finish 135constexpr int kFinMax = 32; // values a thread holds: len <= 32 * 256 136 137// kPack: the rounded rows packed to f.pdst (f.quant's cache format) instead of written to x or f.dst 138template <bool kPack> 139__global__ void __launch_bounds__(kThreads) finish_kernel(float* x, int len, long long stride, Finish f) { 140 float* v = x + (long long) blockIdx.x * stride; 141 float r[kFinMax]; 142 const int nj = (len + kThreads - 1) / kThreads; 143 float ss = 0.0f; 144#pragma unroll 145 for (int j = 0; j < kFinMax; ++j) { 146 if (j >= nj) break; 147 const int e = threadIdx.x + j * kThreads; 148 r[j] = e < len ? v[e] : 0.0f; 149 ss += r[j] * r[j]; 150 } 151 if (f.w != nullptr) { 152 const float tot = block_sum(ss); 153 const float inv = rsqrtf(tot / (float) len + f.eps); 154#pragma unroll 155 for (int j = 0; j < kFinMax; ++j) { 156 if (j >= nj) break; 157 const int e = threadIdx.x + j * kThreads; 158 if (e < len) r[j] = r[j] * inv * f.w[e]; 159 } 160 } 161 // Capture after norm and before RoPE. This is the stable source for SCR relocation. 162 if (f.master != nullptr && f.rd > 0) { 163 float* m = f.master + (long long) blockIdx.x * f.master_stride; 164#pragma unroll 165 for (int j = 0; j < kFinMax; ++j) { 166 if (j >= nj) break; 167 const int e = threadIdx.x + j * kThreads; 168 if (e >= len) continue; 169 if (e >= len - f.rd) m[e - (len - f.rd)] = r[j]; 170 } 171 if (threadIdx.x == 0 && f.master_valid != nullptr) f.master_valid[blockIdx.x] = 1; 172 } 173 if (f.rd > 0) { 174 const int r0 = len - f.rd; 175 const int pos = f.pos + (int) (blockIdx.x / f.vpp) * f.pos_step; 176#pragma unroll 177 for (int j = 0; j < kFinMax; ++j) { 178 if (j >= nj) break; 179 const int e = threadIdx.x + j * kThreads; 180 const float other = __shfl_xor_sync(0xffffffffu, r[j], 1); 181 if (e >= r0 && e < len) { 182 const int i = (e - r0) >> 1; 183 const float ang = (float) pos * f.freqs[i]; 184 const float c = cosf(ang); 185 const float sn = f.inverse ? -sinf(ang) : sinf(ang); 186 if (((e - r0) & 1) == 0) r[j] = r[j] * c - other * sn; // re = a c - b s 187 else r[j] = other * sn + r[j] * c; // im = a s + b c 188 } 189 } 190 } 191 if (f.quant != 0 && !kPack) { 192 const int g = f.quant == 2 ? 16 : 32; 193#pragma unroll 194 for (int j = 0; j < kFinMax; ++j) { 195 if (j >= nj) break; 196 const int e = threadIdx.x + j * kThreads; 197 float a = e < len ? fabsf(r[j]) : 0.0f; 198 for (int o = g / 2; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); 199 if (e >= len) continue; 200 if (f.quant == 1) { 201 const float s = pow2_ceil(fmaxf(a, 1e-4f) * (1.0f / 448.0f)); 202 r[j] = fp8_rt(fminf(fmaxf(r[j] / s, -448.0f), 448.0f)) * s; 203 } else if (f.quant == 2) { 204 const float s = fp8_rt(fmaxf(a, 6.0f * 0.001953125f) / 6.0f); 205 r[j] = e2m1_rt(fminf(fmaxf(r[j] / s, -6.0f), 6.0f)) * s; 206 } else { 207 const float s = pow2_ceil(fmaxf(a, 6.0f * 1.1754943508222875e-38f) * (1.0f / 6.0f)); 208 r[j] = e2m1_rt(fminf(fmaxf(r[j] / s, -6.0f), 6.0f)) * s; 209 } 210 } 211 } 212 if (kPack) { // the same roundings, written as their codes and each group's scale (the readers' q * s: r exactly) 213 const int g = f.quant == 2 ? 16 : 32; 214 uint8_t* pr = f.pdst + (long long) blockIdx.x * f.pdst_stride; 215#pragma unroll 216 for (int j = 0; j < kFinMax; ++j) { 217 if (j >= nj) break; 218 const int e = threadIdx.x + j * kThreads; 219 float a = e < len ? fabsf(r[j]) : 0.0f; 220 for (int o = g / 2; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); 221 float q = 0.0f, s = 1.0f; 222 if (e < len) { 223 if (f.quant == 1) { 224 s = pow2_ceil(fmaxf(a, 1e-4f) * (1.0f / 448.0f)); 225 q = fp8_rt(fminf(fmaxf(r[j] / s, -448.0f), 448.0f)); 226 } else if (f.quant == 2) { 227 s = fp8_rt(fmaxf(a, 6.0f * 0.001953125f) / 6.0f); 228 q = e2m1_rt(fminf(fmaxf(r[j] / s, -6.0f), 6.0f)); 229 } else { 230 s = pow2_ceil(fmaxf(a, 6.0f * 1.1754943508222875e-38f) * (1.0f / 6.0f)); 231 q = e2m1_rt(fminf(fmaxf(r[j] / s, -6.0f), 6.0f)); 232 } 233 r[j] = q * s; 234 } 235 if (f.quant == 1) { 236 if (e < len) pr[e] = (uint8_t) e4m3_code(q); 237 } else { 238 const uint32_t c = e2m1_code(q); 239 const uint32_t hi = __shfl_down_sync(0xffffffffu, c, 1); // (value e + 1: the next lane's) 240 if (e < len && (e & 1) == 0) pr[e >> 1] = (uint8_t) (c | (hi << 4)); 241 } 242 if (e < len && e % g == 0) 243 pr[(f.quant == 1 ? len : len / 2) + e / g] = 244 (uint8_t) (f.quant == 2 ? e4m3_code(s) : __float_as_uint(s) >> 23); 245 } 246 } 247 uint16_t* d = f.dst != nullptr ? f.dst + (long long) blockIdx.x * f.dst_stride : nullptr; 248#pragma unroll 249 for (int j = 0; j < kFinMax; ++j) { 250 if (j >= nj) break; 251 const int e = threadIdx.x + j * kThreads; 252 if (e >= len) continue; 253 if (d != nullptr) d[e] = f2bf16(r[j]); 254 else if (!kPack) v[e] = r[j]; 255 } 256} 257 258__global__ void scr_merge_kernel(const uint8_t* packed, const uint8_t* tail, uint8_t* dst, 259 int len, int rd, int fmt) { 260 const size_t rb = kv_row_bytes(fmt, len), tb = kv_row_bytes(fmt, rd); 261 const int group = fmt == kKvFp4 ? 16 : 32; 262 for (size_t e = threadIdx.x; e < rb; e += blockDim.x) { 263 uint8_t v = packed[(size_t) blockIdx.x * rb + e]; 264 if (e >= (size_t) (len - rd) / 2 && e < (size_t) len / 2) 265 v = tail[(size_t) blockIdx.x * tb + e - (len - rd) / 2]; 266 else if (e >= (size_t) len / 2 + (len - rd) / group && e < (size_t) len / 2 + len / group) 267 v = tail[(size_t) blockIdx.x * tb + rd / 2 + e - len / 2 - (len - rd) / group]; 268 dst[(size_t) blockIdx.x * rb + e] = v; 269 } 270} 271 272// ---------------------------------------------------------------- hyper-connections 273__global__ void __launch_bounds__(kThreads) hc_mix_kernel(const float* __restrict__ h, const float* __restrict__ fn, 274 int hcdim, float eps, float* __restrict__ mixes) { 275 const int m = blockIdx.x, t = blockIdx.y; 276 const float* w = fn + (size_t) m * hcdim; 277 const float* x = h + (size_t) t * hcdim; 278 float acc = 0.0f, ss = 0.0f; 279 for (int k = threadIdx.x * 4; k < hcdim; k += kThreads * 4) { 280 const float4 hv = *(const float4*) (x + k); 281 const float4 wv = *(const float4*) (w + k); 282 acc += hv.x * wv.x + hv.y * wv.y + hv.z * wv.z + hv.w * wv.w; 283 ss += hv.x * hv.x + hv.y * hv.y + hv.z * hv.z + hv.w * hv.w; 284 } 285 acc = block_sum(acc); 286 ss = block_sum(ss); 287 if (threadIdx.x == 0) mixes[(size_t) t * 32 + m] = acc * rsqrtf(ss / (float) hcdim + eps); 288} 289 290// a warp a token: lane j * hc + k holds comb[j][k] (hc <= 4: lanes 0..15; wider streams fall back to lane 0 alone). The body is 291// a device function (hc_mix_kernel's last block runs it too); mx is the token's 32 mixes 292__device__ __forceinline__ void hc_split_body(const float* mx, int t, int lane, const float* __restrict__ scale, 293 const float* __restrict__ base, int hc, int iters, float eps, float* pre, 294 float* post, float* comb) { 295 pre += (size_t) t * 8; 296 post += (size_t) t * 8; 297 comb += (size_t) t * 64; 298 if (lane < hc) { 299 pre[lane] = 1.0f / (1.0f + expf(-(mx[lane] * scale[0] + base[lane]))) + eps; 300 post[lane] = 2.0f / (1.0f + expf(-(mx[hc + lane] * scale[1] + base[hc + lane]))); 301 } 302 if (hc == 4) { 303 // rows are the 4-lane groups (j = lane / 4), columns the lanes 4 apart (k = lane % 4) 304 const bool on = lane < 16; 305 float c = on ? mx[8 + lane] * scale[2] + base[8 + lane] : -FLT_MAX; 306 auto row_sum = [&](float v) { 307 v += __shfl_xor_sync(0xffffffffu, v, 1); 308 return v + __shfl_xor_sync(0xffffffffu, v, 2); 309 }; 310 auto col_sum = [&](float v) { 311 v += __shfl_xor_sync(0xffffffffu, v, 4); 312 return v + __shfl_xor_sync(0xffffffffu, v, 8); 313 }; 314 float m = fmaxf(c, __shfl_xor_sync(0xffffffffu, c, 1)); 315 m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, 2)); 316 c = on ? expf(c - m) : 0.0f; 317 c = c / row_sum(c) + eps; // softmax over each row, + eps 318 c = on ? c : 0.0f; 319 c = c / (col_sum(c) + eps); // each destination column over its sources 320 for (int it = 1; it < iters; ++it) { 321 c = c / (row_sum(c) + eps); 322 c = c / (col_sum(c) + eps); 323 } 324 if (on) comb[lane] = c; 325 return; 326 } 327 if (lane != 0) return; 328 float c[8][8]; 329 for (int j = 0; j < hc; ++j) { 330 float m = -FLT_MAX; 331 for (int k = 0; k < hc; ++k) { 332 c[j][k] = mx[2 * hc + j * hc + k] * scale[2] + base[2 * hc + j * hc + k]; 333 m = fmaxf(m, c[j][k]); 334 } 335 float s = 0.0f; 336 for (int k = 0; k < hc; ++k) { 337 c[j][k] = expf(c[j][k] - m); 338 s += c[j][k]; 339 } 340 for (int k = 0; k < hc; ++k) c[j][k] = c[j][k] / s + eps; 341 } 342 for (int k = 0; k < hc; ++k) { 343 float s = 0.0f; 344 for (int j = 0; j < hc; ++j) s += c[j][k]; 345 for (int j = 0; j < hc; ++j) c[j][k] /= s + eps; 346 } 347 for (int it = 1; it < iters; ++it) { 348 for (int j = 0; j < hc; ++j) { 349 float s = 0.0f; 350 for (int k = 0; k < hc; ++k) s += c[j][k]; 351 for (int k = 0; k < hc; ++k) c[j][k] /= s + eps; 352 } 353 for (int k = 0; k < hc; ++k) { 354 float s = 0.0f; 355 for (int j = 0; j < hc; ++j) s += c[j][k]; 356 for (int j = 0; j < hc; ++j) c[j][k] /= s + eps; 357 } 358 } 359 for (int j = 0; j < hc; ++j) 360 for (int k = 0; k < hc; ++k) comb[j * hc + k] = c[j][k]; 361} 362__global__ void hc_split_kernel(const float* __restrict__ mixes, const float* __restrict__ scale, 363 const float* __restrict__ base, int hc, int iters, float eps, float* pre, float* post, 364 float* comb) { 365 const int t = blockIdx.x; 366 hc_split_body(mixes + (size_t) t * 32, t, threadIdx.x, scale, base, hc, iters, eps, pre, post, comb); 367} 368 369// hc_mix_kernel with hc_split_kernel behind it: the block that finishes the token's last mix (an atomic count, reset by it) runs 370// the split on warp 0 - the same arithmetic as the two launches, one launch less and no round trip through the launch gap 371__global__ void __launch_bounds__(kThreads) hc_mix_split_kernel(const float* __restrict__ h, const float* __restrict__ fn, 372 int hcdim, float eps, float* mixes, unsigned* cnt, 373 const float* __restrict__ scale, 374 const float* __restrict__ base, int hc, int iters, 375 float hc_eps, float* pre, float* post, float* comb) { 376 const int m = blockIdx.x, t = blockIdx.y; 377 const float* w = fn + (size_t) m * hcdim; 378 const float* x = h + (size_t) t * hcdim; 379 float acc = 0.0f, ss = 0.0f; 380 for (int k = threadIdx.x * 4; k < hcdim; k += kThreads * 4) { 381 const float4 hv = *(const float4*) (x + k); 382 const float4 wv = *(const float4*) (w + k); 383 acc += hv.x * wv.x + hv.y * wv.y + hv.z * wv.z + hv.w * wv.w; 384 ss += hv.x * hv.x + hv.y * hv.y + hv.z * hv.z + hv.w * hv.w; 385 } 386 acc = block_sum(acc); 387 ss = block_sum(ss); 388 __shared__ unsigned last; 389 __shared__ float smx[32]; 390 if (threadIdx.x == 0) { 391 mixes[(size_t) t * 32 + m] = acc * rsqrtf(ss / (float) hcdim + eps); 392 __threadfence(); 393 last = atomicAdd(cnt + t, 1u) == gridDim.x - 1 ? 1u : 0u; 394 } 395 __syncthreads(); 396 if (!last) return; 397 __threadfence(); 398 if (threadIdx.x < 32) { 399 const int n = gridDim.x; // the mixes of the token (n_mix <= 32); read past the L1 400 smx[threadIdx.x] = threadIdx.x < n ? *(const volatile float*) (mixes + (size_t) t * 32 + threadIdx.x) : 0.0f; 401 __syncwarp(); 402 hc_split_body(smx, t, threadIdx.x, scale, base, hc, iters, hc_eps, pre, post, comb); 403 } 404 if (threadIdx.x == 0) cnt[t] = 0u; 405} 406 407__global__ void __launch_bounds__(1024) hc_pre_norm_kernel(const float* __restrict__ h, const float* __restrict__ mix, 408 const float* __restrict__ w, int dim, int hc, float eps, 409 float* __restrict__ x) { 410 const int t = blockIdx.x; 411 h += (size_t) t * hc * dim; 412 mix += (size_t) t * 8; 413 x += (size_t) t * dim; 414 float r[8]; 415 float ss = 0.0f; 416 int n = 0; 417 for (int e = threadIdx.x; e < dim; e += blockDim.x, ++n) { 418 float a = 0.0f; 419 for (int s = 0; s < hc; ++s) a += mix[s] * h[(size_t) s * dim + e]; 420 r[n] = a; 421 ss += a * a; 422 } 423 const float inv = rsqrtf(block_sum(ss) / (float) dim + eps); 424 n = 0; 425 for (int e = threadIdx.x; e < dim; e += blockDim.x, ++n) x[e] = w != nullptr ? r[n] * inv * w[e] : r[n]; 426} 427 428__global__ void hc_post_kernel(const float* __restrict__ y, const float* __restrict__ res, 429 const float* __restrict__ post, const float* __restrict__ comb, int dim, int hc, 430 float* __restrict__ out) { 431 const int i = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 432 if (i >= dim * hc) return; 433 const int k = i / dim, e = i - k * dim; 434 const float* r = res + (size_t) t * hc * dim; 435 float a = post[(size_t) t * 8 + k] * y[(size_t) t * dim + e]; 436 for (int j = 0; j < hc; ++j) a += comb[(size_t) t * 64 + j * hc + k] * r[(size_t) j * dim + e]; 437 out[(size_t) t * hc * dim + i] = a; 438} 439 440// ---------------------------------------------------------------- gemv over F16 weights, a warp a row 441__global__ void __launch_bounds__(kThreads) gemv_f16_kernel(const uint16_t* __restrict__ W, const float* __restrict__ x, 442 int n, int k, float alpha, float* __restrict__ y) { 443 const int row = blockIdx.x * (kThreads / 32) + (threadIdx.x >> 5); 444 const int lane = threadIdx.x & 31, t = blockIdx.y; 445 if (row >= n) return; 446 const uint16_t* w = W + (size_t) row * k; 447 const float* xv = x + (size_t) t * k; 448 float acc = 0.0f; 449 for (int c = lane * 8; c < k; c += 32 * 8) { 450 const uint4 q = *(const uint4*) (w + c); 451 const __half2* hp = (const __half2*) &q; 452#pragma unroll 453 for (int i = 0; i < 4; ++i) { 454 const float2 f = __half22float2(hp[i]); 455 acc += f.x * xv[c + 2 * i] + f.y * xv[c + 2 * i + 1]; 456 } 457 } 458 acc = warp_sum(acc); 459 if (lane == 0) y[(size_t) t * n + row] = alpha * acc; 460} 461// ... for T activations (rows ldx apart, 16-byte aligned; outputs ldy apart), kRowsT of them a block (grid y): each 462// weight row read once for the block's activations, theirs in float4s - each activation's sum gemv_f16_kernel's (the 463// same products in the same order), so its bits too. (A block for all of them, 16 at most, was slower than a launch 464// a token: its accumulators and guards kept the loop from unrolling - 66 against 29 us at 5 tokens on an RTX 5060 Ti, 465// this 9) 466constexpr int kRowsT = 2; 467__global__ void __launch_bounds__(kThreads) gemv_f16_rows_kernel(const uint16_t* __restrict__ W, 468 const float* __restrict__ x, size_t ldx, int n, int k, 469 int T, float alpha, float* __restrict__ y, size_t ldy) { 470 const int row = blockIdx.x * (kThreads / 32) + (threadIdx.x >> 5); 471 const int lane = threadIdx.x & 31; 472 const int t0 = blockIdx.y * kRowsT, nt = min(kRowsT, T - t0); 473 if (row >= n) return; 474 const uint16_t* w = W + (size_t) row * k; 475 float acc[kRowsT]; 476#pragma unroll 477 for (int t = 0; t < kRowsT; ++t) acc[t] = 0.0f; 478 for (int c = lane * 8; c < k; c += 32 * 8) { 479 const uint4 q = *(const uint4*) (w + c); 480 const __half2* hp = (const __half2*) &q; 481 float xv[kRowsT][8]; 482#pragma unroll 483 for (int t = 0; t < kRowsT; ++t) 484 if (t < nt) { 485 const float* xp = x + (size_t) (t0 + t) * ldx + c; 486 const float4 a = *(const float4*) xp, b = *(const float4*) (xp + 4); 487 xv[t][0] = a.x, xv[t][1] = a.y, xv[t][2] = a.z, xv[t][3] = a.w; 488 xv[t][4] = b.x, xv[t][5] = b.y, xv[t][6] = b.z, xv[t][7] = b.w; 489 } 490#pragma unroll 491 for (int i = 0; i < 4; ++i) { 492 const float2 f = __half22float2(hp[i]); 493#pragma unroll 494 for (int t = 0; t < kRowsT; ++t) 495 if (t < nt) acc[t] += f.x * xv[t][2 * i] + f.y * xv[t][2 * i + 1]; 496 } 497 } 498#pragma unroll 499 for (int t = 0; t < kRowsT; ++t) 500 if (t < nt) { 501 const float a = warp_sum(acc[t]); 502 if (lane == 0) y[(size_t) (t0 + t) * ldy + row] = alpha * a; 503 } 504} 505 506// ---------------------------------------------------------------- gemv over F32 weights, a warp a row (the router) 507__global__ void __launch_bounds__(kThreads) gemv_f32_kernel(const float* __restrict__ W, const float* __restrict__ x, 508 int n, int k, float* __restrict__ y, int ldy) { 509 const int row = blockIdx.x * (kThreads / 32) + (threadIdx.x >> 5); 510 const int lane = threadIdx.x & 31, t = blockIdx.y; 511 if (row >= n) return; 512 const float4* w = (const float4*) (W + (size_t) row * k); 513 const float4* xv = (const float4*) (x + (size_t) t * k); 514 float acc = 0.0f; 515 for (int c = lane; c < k / 4; c += 32) { 516 const float4 a = w[c], b = xv[c]; 517 acc = fmaf(a.x, b.x, acc); 518 acc = fmaf(a.y, b.y, acc); 519 acc = fmaf(a.z, b.z, acc); 520 acc = fmaf(a.w, b.w, acc); 521 } 522 acc = warp_sum(acc); 523 if (lane == 0) y[(size_t) t * ldy + row] = acc; 524} 525 526// ---------------------------------------------------------------- the router 527// Cache-Prior (ds4-recipe 06 §4, MoCCE arXiv:2412.00099): in decode, a bonus of lambda x the row's score range on the 528// selection score of every expert resident in VRAM and of the exact top-keep (never displaced); the mixing weights stay 529// the unbiased scores'. lambda 0 (the default, DS4_CP_LAMBDA unset) is exact routing. 530__device__ float g_cp_lambda = 0.0f; 531__device__ int g_cp_keep = 3; 532__device__ float g_cp_plambda = 0.0f; // the same bias in prefill (DS4_CP_PREFILL; route() given the residency table) 533__device__ int g_cp_pkeep = 3; // its exact top-keep (DS4_CP_PREFILL_KEEP, else DS4_CP_KEEP) 534 535__global__ void __launch_bounds__(512) route_kernel(const float* __restrict__ logits, const float* __restrict__ bias, 536 int n, int k, float route_scale, int* idx, float* w, 537 const float* __restrict__ bias_vl, const VlBits vl, 538 const unsigned long long* __restrict__ vram, 539 const unsigned char* __restrict__ res) { 540 __shared__ float sc[1024], bs[1024]; 541 __shared__ float bv[32]; 542 __shared__ int bi[32]; 543 __shared__ int pick[16]; 544 const int t = blockIdx.x; 545 logits += (size_t) t * 1024; 546 if (bias_vl != nullptr && ((vl.w[t >> 5] >> (t & 31)) & 1u)) bias = bias_vl; 547 for (int i = threadIdx.x; i < n; i += blockDim.x) { 548 const float l = logits[i]; 549 const float sp = l > 20.0f ? l : log1pf(expf(l)); 550 sc[i] = sqrtf(sp); 551 bs[i] = sc[i] + bias[i]; 552 } 553 __syncthreads(); 554 if (vram != nullptr && g_cp_plambda > 0.0f) { // (res: the RAM store's experts too, DS4_CP_STORE) 555 __shared__ float cp_add; 556 __shared__ int cp_keep[8], cp_n; 557 if (threadIdx.x == 0) { 558 float lo = FLT_MAX, hi = -FLT_MAX; 559 for (int i = 0; i < n; ++i) lo = fminf(lo, bs[i]), hi = fmaxf(hi, bs[i]); 560 cp_n = min(max(g_cp_pkeep, 0), 8); 561 for (int q = 0; q < cp_n; ++q) { // the exact top-keep, ties to the lower index as the selection below 562 float b = -FLT_MAX; 563 int ix = 0x7fffffff; 564 for (int i = 0; i < n; ++i) { 565 bool taken = false; 566 for (int z = 0; z < q; ++z) taken |= cp_keep[z] == i; 567 if (!taken && (bs[i] > b || (bs[i] == b && i < ix))) b = bs[i], ix = i; 568 } 569 cp_keep[q] = ix; 570 } 571 cp_add = g_cp_plambda * (hi - lo); 572 } 573 __syncthreads(); 574 for (int i = threadIdx.x; i < n; i += blockDim.x) { 575 bool favoured = vram[i] != 0ull || (res != nullptr && res[i] != 0); 576 for (int z = 0; z < cp_n; ++z) favoured |= cp_keep[z] == i; 577 if (favoured) bs[i] += cp_add; 578 } 579 __syncthreads(); 580 } 581 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; 582 for (int r = 0; r < k; ++r) { 583 float best = -FLT_MAX; 584 int bix = 0x7fffffff; 585 for (int i = threadIdx.x; i < n; i += blockDim.x) 586 if (bs[i] > best || (bs[i] == best && i < bix)) best = bs[i], bix = i; 587 for (int o = 16; o > 0; o >>= 1) { 588 const float ov = __shfl_xor_sync(0xffffffffu, best, o); 589 const int oi = __shfl_xor_sync(0xffffffffu, bix, o); 590 if (ov > best || (ov == best && oi < bix)) best = ov, bix = oi; 591 } 592 if (lane == 0) bv[wp] = best, bi[wp] = bix; 593 __syncthreads(); 594 if (threadIdx.x == 0) { 595 float b = -FLT_MAX; 596 int ix = 0x7fffffff; 597 for (int q = 0; q < (int) (blockDim.x >> 5); ++q) 598 if (bv[q] > b || (bv[q] == b && bi[q] < ix)) b = bv[q], ix = bi[q]; 599 pick[r] = ix; 600 bs[ix] = -FLT_MAX; 601 } 602 __syncthreads(); 603 } 604 if (threadIdx.x == 0) { 605 float s = 0.0f; 606 for (int r = 0; r < k; ++r) s += sc[pick[r]]; 607 for (int r = 0; r < k; ++r) { 608 idx[(size_t) t * kPicks + r] = pick[r]; 609 w[(size_t) t * kPicks + r] = sc[pick[r]] / (s + 1e-20f) * route_scale; 610 } 611 } 612} 613 614__global__ void swiglu_kernel(const float* __restrict__ g, const float* __restrict__ u, int n, float lim, 615 float* __restrict__ h) { 616 const int i = blockIdx.x * blockDim.x + threadIdx.x; 617 if (i >= n) return; 618 float gv = g[i], uv = u[i]; 619 if (lim > 0.0f) { 620 gv = fminf(gv, lim); 621 uv = fminf(fmaxf(uv, -lim), lim); 622 } 623 h[i] = gv / (1.0f + expf(-gv)) * uv; 624} 625 626// ---------------------------------------------------------------- the compressor (ratio > 1), a window in order 627__global__ void __launch_bounds__(512) compress_kernel(const float* __restrict__ kv, const float* __restrict__ score, 628 float* kv_state, float* score_state, int ratio, int p0, int T, 629 int d, const float* __restrict__ w, float eps, 630 float* __restrict__ latent) { 631 int g = 0; 632 for (int t = 0; t < T; ++t) { 633 const int slot = (p0 + t) % ratio; 634 const bool pool = (p0 + t + 1) % ratio == 0; 635 for (int e = threadIdx.x; e < d; e += blockDim.x) { 636 kv_state[(size_t) slot * d + e] = kv[(size_t) t * d + e]; 637 score_state[(size_t) slot * d + e] = score[(size_t) t * d + e]; 638 } 639 __syncthreads(); 640 if (!pool) continue; 641 // (kv * softmax(score, over the slots)).sum: each slot's probability first, then the sum, as torch does 642 float val[2] = {0.0f, 0.0f}; // d <= 2 * blockDim 643 float ss = 0.0f; 644 int n = 0; 645 for (int e = threadIdx.x; e < d; e += blockDim.x, ++n) { 646 float m = -FLT_MAX; 647 for (int s = 0; s < ratio; ++s) m = fmaxf(m, score_state[(size_t) s * d + e]); 648 float den = 0.0f; 649 for (int s = 0; s < ratio; ++s) den += expf(score_state[(size_t) s * d + e] - m); 650 float acc = 0.0f; 651 for (int s = 0; s < ratio; ++s) 652 acc += kv_state[(size_t) s * d + e] * (expf(score_state[(size_t) s * d + e] - m) / den); 653 val[n] = acc; 654 ss += acc * acc; 655 } 656 const float inv = rsqrtf(block_sum(ss) / (float) d + eps); 657 n = 0; 658 for (int e = threadIdx.x; e < d; e += blockDim.x, ++n) latent[(size_t) g * d + e] = val[n] * inv * w[e]; 659 ++g; 660 __syncthreads(); 661 } 662} 663 664// ---------------------------------------------------------------- per-query sizes 665__device__ __forceinline__ void rows_at(const Rows& r, int t, int& n, int& k) { 666 if (r.gen == 0) { 667 n = r.n[t]; 668 k = r.k[t]; 669 return; 670 } 671 const int nn = (int) ((r.p0 + t + 1) / r.R); 672 const int cb = min(r.ccap, (nn + r.blk - 1) / r.blk); 673 switch (r.gen) { 674 case 1: n = nn, k = min(r.kcap, nn); break; 675 case 2: n = nn, k = cb; break; 676 case 3: n = cb * r.blk, k = min(r.kcap, nn); break; 677 default: n = (nn + r.blk - 1) / r.blk, k = r.kcap; break; 678 } 679} 680 681// ---------------------------------------------------------------- the indexer 682// a thread a position: its key row (KF: kKvFp4p packed, or BF16) against every head's query (shared memory), relu, 683// weighted sum 684template <int HD, int KF> 685__global__ void __launch_bounds__(kThreads) index_score_kernel(const float* __restrict__ q, const float* __restrict__ w, 686 const uint8_t* __restrict__ kc, int heads, int n, 687 const int* __restrict__ cand, int cand_stride, int blk, 688 Rows lim, float* __restrict__ out, 689 long long out_stride) { 690 extern __shared__ float qs[]; // heads * HD, then heads weights 691 const int t = blockIdx.y; 692 for (int i = threadIdx.x; i < heads * HD; i += blockDim.x) qs[i] = q[(size_t) t * heads * HD + i]; 693 for (int i = threadIdx.x; i < heads; i += blockDim.x) qs[heads * HD + i] = w[(size_t) t * 64 + i]; 694 __syncthreads(); 695 const int i = blockIdx.x * blockDim.x + threadIdx.x; 696 if (i >= n) return; 697 float* o = out + (long long) t * out_stride; 698 int ln, lk; 699 rows_at(lim, t, ln, lk); 700 int p = i; 701 if (cand != nullptr) { 702 if (i >= lk * blk) { 703 o[i] = -INFINITY; 704 return; 705 } 706 p = cand[(size_t) t * cand_stride + i / blk] * blk + i % blk; 707 } 708 if (p >= ln) { 709 o[i] = -INFINITY; 710 return; 711 } 712 const uint8_t* kr = kc + (size_t) p * kv_row_bytes(KF, HD); 713 float acc[32]; 714#pragma unroll 715 for (int h = 0; h < 32; ++h) acc[h] = 0.0f; 716#pragma unroll 2 717 for (int c = 0; c < HD; c += 8) { 718 float kv[8]; 719 if (KF == kKvFp4p) { // 8 codes in 4 bytes, the group's power-of-two scale: the values the finish rounded to 720 const uint32_t cw = *(const uint32_t*) (kr + c / 2); 721 const float ks = ue8m0_val(kr[HD / 2 + c / 32]); 722#pragma unroll 723 for (int x = 0; x < 8; ++x) kv[x] = e2m1_val14(cw >> (4 * x)) * 16384.0f * ks; // (any 2^k: exact) 724 } else { 725 const uint4 raw = *(const uint4*) (kr + c * 2); 726 const uint16_t* b = (const uint16_t*) &raw; 727#pragma unroll 728 for (int x = 0; x < 8; ++x) kv[x] = bf16f(b[x]); 729 } 730#pragma unroll 731 for (int h = 0; h < 32; ++h) { 732 if (h >= heads) break; 733 const float* qh = qs + h * HD + c; 734#pragma unroll 735 for (int x = 0; x < 8; ++x) acc[h] += qh[x] * kv[x]; 736 } 737 } 738 float s = 0.0f; 739#pragma unroll 740 for (int h = 0; h < 32; ++h) { 741 if (h >= heads) break; 742 s += fmaxf(acc[h], 0.0f) * qs[heads * HD + h]; 743 } 744 o[i] = s; 745} 746 747__device__ __forceinline__ uint32_t ord_key(float f) { 748 const uint32_t b = __float_as_uint(f); 749 return (b & 0x80000000u) ? ~b : (b | 0x80000000u); 750} 751 752// a block a row: the k-th largest key by four 8-bit radix passes, then everything above it and enough of its ties 753__global__ void __launch_bounds__(1024) topk_kernel(const float* __restrict__ vals, long long stride, Rows r, 754 const int* __restrict__ cand, int cand_stride, int blk, 755 int* __restrict__ out, int out_stride) { 756 __shared__ unsigned hist[256]; 757 __shared__ uint32_t prefix_s, mask_s; 758 __shared__ int remaining_s; 759 __shared__ int cnt_gt, cnt_eq; 760 const int t = blockIdx.x; 761 int n, k; 762 rows_at(r, t, n, k); 763 vals += (long long) t * stride; 764 out += (size_t) t * out_stride; 765 const int* cd = cand != nullptr ? cand + (size_t) t * cand_stride : nullptr; 766 if (n <= 0) return; 767 if (k >= n) { 768 for (int i = threadIdx.x; i < n; i += blockDim.x) out[i] = cd != nullptr ? cd[i / blk] * blk + i % blk : i; 769 return; 770 } 771 if (threadIdx.x == 0) { 772 prefix_s = 0u; 773 mask_s = 0u; 774 remaining_s = k; 775 cnt_gt = 0; 776 cnt_eq = 0; 777 } 778 __syncthreads(); 779 for (int shift = 24; shift >= 0; shift -= 8) { 780 for (int i = threadIdx.x; i < 256; i += blockDim.x) hist[i] = 0u; 781 __syncthreads(); 782 const uint32_t prefix = prefix_s, mask = mask_s; 783 for (int i = threadIdx.x; i < n; i += blockDim.x) { 784 const uint32_t u = ord_key(vals[i]); 785 if ((u & mask) == prefix) atomicAdd(&hist[(u >> shift) & 0xffu], 1u); 786 } 787 __syncthreads(); 788 if (threadIdx.x == 0) { 789 const int rem = remaining_s; 790 int cum = 0; 791 for (int d = 255; d >= 0; --d) { 792 const int h = (int) hist[d]; 793 if (cum + h >= rem) { 794 prefix_s = prefix | ((uint32_t) d << shift); 795 mask_s = mask | (0xffu << shift); 796 remaining_s = rem - cum; 797 break; 798 } 799 cum += h; 800 } 801 } 802 __syncthreads(); 803 } 804 const uint32_t thr = prefix_s; 805 const int remaining = remaining_s; 806 const int n_gt = k - remaining; 807 // the picks in index order (a scan a pass of 1024 values), so the attention sums them in the same order every run 808 // and the ties kept are the lowest positions 809 __shared__ int wgt[32], weq[32]; 810 const int lane = threadIdx.x & 31, wid = threadIdx.x >> 5, nw = blockDim.x >> 5; 811 const unsigned below = (1u << lane) - 1u; 812 for (int i0 = 0; i0 < n; i0 += blockDim.x) { 813 const int i = i0 + threadIdx.x; 814 const uint32_t u = i < n ? ord_key(vals[i]) : 0u; 815 const bool gt = i < n && u > thr, eq = i < n && u == thr; 816 const unsigned bg = __ballot_sync(0xffffffffu, gt), be = __ballot_sync(0xffffffffu, eq); 817 if (lane == 0) { 818 wgt[wid] = __popc(bg); 819 weq[wid] = __popc(be); 820 } 821 __syncthreads(); 822 if (wid == 0) { 823 const int g0 = lane < nw ? wgt[lane] : 0, e0 = lane < nw ? weq[lane] : 0; 824 int gs = g0, es = e0; 825 for (int o = 1; o < 32; o <<= 1) { 826 const int a = __shfl_up_sync(0xffffffffu, gs, o), b = __shfl_up_sync(0xffffffffu, es, o); 827 if (lane >= o) { 828 gs += a; 829 es += b; 830 } 831 } 832 if (lane < nw) { 833 wgt[lane] = cnt_gt + gs - g0; 834 weq[lane] = cnt_eq + es - e0; 835 } 836 __syncwarp(); 837 if (lane == 31) { 838 cnt_gt += gs; 839 cnt_eq += es; 840 } 841 } 842 __syncthreads(); 843 int slot = -1; 844 if (gt) slot = wgt[wid] + __popc(bg & below); 845 else if (eq) { 846 const int e = weq[wid] + __popc(be & below); 847 if (e < remaining) slot = n_gt + e; 848 } 849 if (slot >= 0) out[slot] = cd != nullptr ? cd[i / blk] * blk + i % blk : i; 850 __syncthreads(); 851 } 852} 853 854__global__ void block_max_kernel(const float* __restrict__ score, long long stride, Rows r, int blk, 855 float* __restrict__ bm, long long bm_stride) { 856 const int b = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 857 int n, k_; 858 rows_at(r, t, n, k_); 859 const int nb = (n + blk - 1) / blk; 860 if (b >= nb) return; 861 float m = -INFINITY; 862 for (int j = 0; j < blk; ++j) { 863 const int p = b * blk + j; 864 if (p < n) m = fmaxf(m, score[(long long) t * stride + p]); 865 } 866 if (b == (n - 1) / blk) m = INFINITY; // the newest position's block is pinned in 867 bm[(long long) t * bm_stride + b] = m; 868} 869 870// ---------------------------------------------------------------- sparse attention, a block a (head, query) 871constexpr int kAttTile = 64; 872 873// kContig: query t's selected rows are ckv's rows t * sel_stride .. (the scratch of rows decoded once a query) - read 874// without sel, a warp's rows of a tile loaded kPre at a time before their dots (0: as the BF16 kernel); the 875// arithmetic the same 876template <bool kContig, int kPre = 0> 877__global__ void __launch_bounds__(kThreads) sparse_attn_kernel(const float* __restrict__ q, 878 const uint16_t* __restrict__ win, 879 const uint16_t* __restrict__ ckv, 880 const int* __restrict__ sel, int sel_stride, 881 AttnRows ar, const float* __restrict__ sink, int heads, 882 int d, float scale, float* __restrict__ out) { 883 // d == 512: a thread owns 2 output values, a lane 16 of a row's dot 884 const int h = blockIdx.x, t = blockIdx.y; 885 int n_win, n_sel, w0; 886 if (ar.gen) { 887 const long long ta = ar.t0 + t, pa = ar.p0 + ta; 888 long long first = max((long long) ar.win - ar.p0, ta + 1); // the window buffer row of max(0, pa - win + 1) 889 if (ar.floor >= 0) first = max(first, (long long) ar.win + ar.floor - ar.p0); // (an SCR junction's replay) 890 w0 = (int) first; 891 n_win = (int) (ar.win + ta - first + 1); 892 n_sel = ar.R > 0 ? (int) min((long long) ar.kcap, (pa + 1) / ar.R) : 0; 893 } else { 894 n_win = ar.nwin[t], n_sel = ar.nsel[t], w0 = ar.win0[t]; 895 } 896 const uint16_t* wbase = win + (size_t) w0 * d; 897 const int* sl = sel + (size_t) t * sel_stride; 898 __shared__ float qs[512]; 899 __shared__ float sc[kAttTile]; 900 __shared__ const uint16_t* rows[kAttTile]; 901 __shared__ float m_run_s, tile_scale_s, den_s; 902 for (int i = threadIdx.x; i < d; i += blockDim.x) qs[i] = q[((size_t) t * heads + h) * d + i]; 903 if (threadIdx.x == 0) { 904 m_run_s = -1e30f; 905 den_s = 0.0f; 906 } 907 __syncthreads(); 908 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; 909 float o0 = 0.0f, o1 = 0.0f; 910 const int total = n_win + n_sel; 911 for (int t0 = 0; t0 < total; t0 += kAttTile) { 912 const int nt = min(kAttTile, total - t0); 913 if (threadIdx.x < nt) { 914 const int j = t0 + threadIdx.x; 915 rows[threadIdx.x] = j < n_win ? wbase + (size_t) j * d 916 : ckv + (kContig ? (size_t) t * sel_stride + (j - n_win) : (size_t) sl[j - n_win]) * d; 917 } 918 __syncthreads(); 919 if (kContig && kPre > 0) { // the warp's rows of the tile (wp, wp + 8, ..), kPre loads at a time, then dots 920#pragma unroll 921 for (int k0 = 0; k0 < kAttTile / 8; k0 += (kPre > 0 ? kPre : 1)) { 922 uint4 ra[kPre > 0 ? kPre : 1], rb[kPre > 0 ? kPre : 1]; 923#pragma unroll 924 for (int k = 0; k < kPre; ++k) { 925 const int jj = wp + 8 * (k0 + k); 926 if (jj < nt) { 927 ra[k] = *(const uint4*) (rows[jj] + lane * 16); 928 rb[k] = *(const uint4*) (rows[jj] + lane * 16 + 8); 929 } 930 } 931#pragma unroll 932 for (int k = 0; k < kPre; ++k) { 933 const int jj = wp + 8 * (k0 + k); 934 if (jj < nt) { 935 const uint16_t* pa = (const uint16_t*) &ra[k]; 936 const uint16_t* pb = (const uint16_t*) &rb[k]; 937 float s = 0.0f; 938#pragma unroll 939 for (int x = 0; x < 8; ++x) s += qs[lane * 16 + x] * bf16f(pa[x]); 940#pragma unroll 941 for (int x = 0; x < 8; ++x) s += qs[lane * 16 + 8 + x] * bf16f(pb[x]); 942 s = warp_sum(s); 943 if (lane == 0) sc[jj] = s * scale; 944 } 945 } 946 } 947 } else 948 for (int jj = wp; jj < nt; jj += kThreads / 32) { 949 const uint16_t* rr = rows[jj]; 950 const uint4 a = *(const uint4*) (rr + lane * 16); 951 const uint4 b = *(const uint4*) (rr + lane * 16 + 8); 952 const uint16_t* pa = (const uint16_t*) &a; 953 const uint16_t* pb = (const uint16_t*) &b; 954 float s = 0.0f; 955#pragma unroll 956 for (int x = 0; x < 8; ++x) s += qs[lane * 16 + x] * bf16f(pa[x]); 957#pragma unroll 958 for (int x = 0; x < 8; ++x) s += qs[lane * 16 + 8 + x] * bf16f(pb[x]); 959 s = warp_sum(s); 960 if (lane == 0) sc[jj] = s * scale; 961 } 962 __syncthreads(); 963 if (wp == 0) { 964 float m = -INFINITY; 965 for (int j = lane; j < nt; j += 32) m = fmaxf(m, sc[j]); 966 m = warp_max(m); 967 const float m_old = m_run_s; 968 const float m_new = fmaxf(m_old, m); 969 float s = 0.0f; 970 for (int j = lane; j < nt; j += 32) { 971 const float p = expf(sc[j] - m_new); 972 sc[j] = p; 973 s += p; 974 } 975 s = warp_sum(s); 976 __syncwarp(); 977 if (lane == 0) { 978 tile_scale_s = expf(m_old - m_new); 979 den_s = den_s * tile_scale_s + s; 980 m_run_s = m_new; 981 } 982 } 983 __syncthreads(); 984 const float cs = tile_scale_s; 985 o0 *= cs; 986 o1 *= cs; 987 const int c = threadIdx.x * 2; 988 if (kContig && kPre > 0) { // (eight rows' loads at once) 989#pragma unroll 8 990 for (int j = 0; j < nt; ++j) { 991 const uint32_t pr = *(const uint32_t*) (rows[j] + c); 992 o0 += sc[j] * bf16f((uint16_t) (pr & 0xffffu)); 993 o1 += sc[j] * bf16f((uint16_t) (pr >> 16)); 994 } 995 } else 996 for (int j = 0; j < nt; ++j) { 997 const uint32_t pr = *(const uint32_t*) (rows[j] + c); 998 o0 += sc[j] * bf16f((uint16_t) (pr & 0xffffu)); 999 o1 += sc[j] * bf16f((uint16_t) (pr >> 16)); 1000 } 1001 __syncthreads(); 1002 } 1003 const float den = den_s + expf(sink[h] - m_run_s); 1004 const int c = threadIdx.x * 2; 1005 float* ov = out + ((size_t) t * heads + h) * d; 1006 ov[c] = o0 / den; 1007 ov[c + 1] = o1 / den; 1008} 1009 1010// ---------------------------------------------------------------- sparse attention over the packed compressed rows 1011// G heads of one query a block (8 / G warps a head): each pass stages 16 of a tile's rows in shared memory as BF16 1012// (the window's rows as they are; the packed rows decoded - exact in BF16), once for all G heads, through one 16-byte 1013// load a thread. Each head's arithmetic is sparse_attn_kernel's, operation for operation: its tiles of 64 rows, its 1014// dots by a warp's lanes (16 values each, in order) and the same butterfly, its softmax by one warp the same way, each 1015// output value's weighted sum by the same thread in row order - the same bits for any G. 1016constexpr int kStage = 16; // rows a pass stages (a thread: 32 values of one) 1017 1018// values part * 32 .. + 32 of a packed compressed row (kKvFp4, 512 values) as BF16 into dst[0 .. 4) (exact: the 1019// values are E2M1 times an E4M3 scale) 1020__device__ __forceinline__ void unpack32(const uint8_t* rr, int part, uint4* dst) { 1021 const uint4 cw = *(const uint4*) (rr + part * 16); // 32 codes, two scale groups 1022 const float k0 = e4m3_value(rr[256 + part * 2]) * 16384.0f, k1 = e4m3_value(rr[256 + part * 2 + 1]) * 16384.0f; 1023 const uint32_t wv[4] = {cw.x, cw.y, cw.z, cw.w}; 1024 uint32_t o[16]; 1025#pragma unroll 1026 for (int i = 0; i < 16; ++i) { // values 2i, 2i + 1 (the low and the high nibble of byte i) 1027 const uint32_t b = wv[i >> 2] >> (8 * (i & 3)); 1028 const float ks = i < 8 ? k0 : k1; 1029 const float lo = e2m1_val14(b) * ks, hi = e2m1_val14(b >> 4) * ks; // (exact: their BF16 bits) 1030 o[i] = (__float_as_uint(lo) >> 16) | (__float_as_uint(hi) & 0xffff0000u); 1031 } 1032 dst[0] = make_uint4(o[0], o[1], o[2], o[3]); 1033 dst[1] = make_uint4(o[4], o[5], o[6], o[7]); 1034 dst[2] = make_uint4(o[8], o[9], o[10], o[11]); 1035 dst[3] = make_uint4(o[12], o[13], o[14], o[15]); 1036} 1037 1038// a few queries' attention (a decode step, a short window): the rows each query selects decoded once to BF16 rows - 1039// out[t * cap + i] = ckv[sel[t][i]] for i < the query's n_sel - for the BF16 kernel reading them in place (once a 1040// query, not once a head) 1041__global__ void __launch_bounds__(kThreads) unpack_sel_kernel(const uint8_t* __restrict__ ckv, 1042 const int* __restrict__ sel, int sel_stride, AttnRows ar, 1043 int cap, uint16_t* __restrict__ out) { 1044 const int t = blockIdx.y, i = blockIdx.x * kStage + (int) (threadIdx.x >> 4), part = threadIdx.x & 15; 1045 int n_sel; 1046 if (ar.gen) { 1047 const long long pa = ar.p0 + ar.t0 + t; 1048 n_sel = ar.R > 0 ? (int) min((long long) ar.kcap, (pa + 1) / ar.R) : 0; 1049 } else { 1050 n_sel = ar.nsel[t]; 1051 } 1052 if (i >= n_sel) return; 1053 const size_t r = (size_t) t * cap + i; 1054 unpack32(ckv + (size_t) sel[(size_t) t * sel_stride + i] * kv_row_bytes(kKvFp4, 512), part, (uint4*) (out + r * 512 + part * 32)); 1055} 1056 1057template <int G> 1058__global__ void __launch_bounds__(kThreads) sparse_attn_packed_kernel(const float* __restrict__ q, 1059 const uint16_t* __restrict__ win, 1060 const uint8_t* __restrict__ ckv, 1061 const int* __restrict__ sel, int sel_stride, 1062 AttnRows ar, const float* __restrict__ sink, 1063 int heads, float scale, float* __restrict__ out) { 1064 constexpr int d = 512, W = 8 / G; // (kThreads / 32 warps) 1065 const int hb = blockIdx.x * G, t = blockIdx.y; 1066 int n_win, n_sel, w0; 1067 if (ar.gen) { 1068 const long long ta = ar.t0 + t, pa = ar.p0 + ta; 1069 long long first = max((long long) ar.win - ar.p0, ta + 1); 1070 if (ar.floor >= 0) first = max(first, (long long) ar.win + ar.floor - ar.p0); // (an SCR junction's replay) 1071 w0 = (int) first; 1072 n_win = (int) (ar.win + ta - first + 1); 1073 n_sel = ar.R > 0 ? (int) min((long long) ar.kcap, (pa + 1) / ar.R) : 0; 1074 } else { 1075 n_win = ar.nwin[t], n_sel = ar.nsel[t], w0 = ar.win0[t]; 1076 } 1077 const uint16_t* wbase = win + (size_t) w0 * d; 1078 const int* sl = sel + (size_t) t * sel_stride; 1079 const size_t crow = kv_row_bytes(kKvFp4, d); 1080 __shared__ __align__(16) uint16_t tile[kStage * d]; 1081 __shared__ float sc[G][kAttTile]; 1082 __shared__ const uint8_t* rows[kAttTile]; 1083 __shared__ float m_run_s[G], tile_scale_s[G], den_s[G]; 1084 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5, gw = wp / W, wr = wp % W; 1085 float qr[16]; // this lane's 16 values of its warp's head 1086#pragma unroll 1087 for (int x = 0; x < 16; ++x) qr[x] = q[((size_t) t * heads + hb + gw) * d + lane * 16 + x]; 1088 if (threadIdx.x < G) { 1089 m_run_s[threadIdx.x] = -1e30f; 1090 den_s[threadIdx.x] = 0.0f; 1091 } 1092 float o0[G], o1[G]; 1093#pragma unroll 1094 for (int g = 0; g < G; ++g) o0[g] = o1[g] = 0.0f; 1095 const int c = threadIdx.x * 2; 1096 const int sr = threadIdx.x >> 4, part = threadIdx.x & 15; // the staging: a thread's row and 32 values 1097 // rows [s0, s0 + n) of the tile at t0 into tile[] as BF16 1098 auto stage = [&](int t0, int s0, int n) { 1099 if (sr >= n) return; 1100 const int j = s0 + sr; 1101 uint4* dst = (uint4*) (tile + sr * d + part * 32); 1102 if (t0 + j < n_win) { // a window row: BF16 already 1103 const uint4* src = (const uint4*) (rows[j] + part * 64); 1104 dst[0] = src[0]; 1105 dst[1] = src[1]; 1106 dst[2] = src[2]; 1107 dst[3] = src[3]; 1108 return; 1109 } 1110 unpack32(rows[j], part, dst); 1111 }; 1112 const int total = n_win + n_sel; 1113 for (int t0 = 0; t0 < total; t0 += kAttTile) { 1114 const int nt = min(kAttTile, total - t0); 1115 if (threadIdx.x < nt) { 1116 const int j = t0 + threadIdx.x; 1117 rows[threadIdx.x] = j < n_win ? (const uint8_t*) (wbase + (size_t) j * d) : ckv + (size_t) sl[j - n_win] * crow; 1118 } 1119 __syncthreads(); 1120 for (int s0 = 0; s0 < nt; s0 += kStage) { // the dots 1121 const int n = min(kStage, nt - s0); 1122 stage(t0, s0, n); 1123 __syncthreads(); 1124#if !defined(STRATA_USE_HIP) // (HIP leaves a loop with shuffles and a remainder rolled anyway) 1125#pragma unroll 2 1126#endif 1127 for (int r = wr; r < n; r += W) { // (two rows' chains at once) 1128 const uint16_t* vr = tile + r * d + lane * 16; 1129 const uint4 a = *(const uint4*) vr; 1130 const uint4 b = *(const uint4*) (vr + 8); 1131 const uint16_t* pa = (const uint16_t*) &a; 1132 const uint16_t* pb = (const uint16_t*) &b; 1133 float s = 0.0f; 1134#pragma unroll 1135 for (int x = 0; x < 8; ++x) s += qr[x] * bf16f(pa[x]); 1136#pragma unroll 1137 for (int x = 0; x < 8; ++x) s += qr[8 + x] * bf16f(pb[x]); 1138 s = warp_sum(s); 1139 if (lane == 0) sc[gw][s0 + r] = s * scale; 1140 } 1141 __syncthreads(); 1142 } 1143 if (wp < G) { // head wp's softmax over the tile 1144 float* scg = sc[wp]; 1145 float m = -INFINITY; 1146 for (int j = lane; j < nt; j += 32) m = fmaxf(m, scg[j]); 1147 m = warp_max(m); 1148 const float m_old = m_run_s[wp]; 1149 const float m_new = fmaxf(m_old, m); 1150 float s = 0.0f; 1151 for (int j = lane; j < nt; j += 32) { 1152 const float p = expf(scg[j] - m_new); 1153 scg[j] = p; 1154 s += p; 1155 } 1156 s = warp_sum(s); 1157 __syncwarp(); 1158 if (lane == 0) { 1159 tile_scale_s[wp] = expf(m_old - m_new); 1160 den_s[wp] = den_s[wp] * tile_scale_s[wp] + s; 1161 m_run_s[wp] = m_new; 1162 } 1163 } 1164 __syncthreads(); 1165#pragma unroll 1166 for (int g = 0; g < G; ++g) { 1167 const float cs = tile_scale_s[g]; 1168 o0[g] *= cs; 1169 o1[g] *= cs; 1170 } 1171 for (int s0 = 0; s0 < nt; s0 += kStage) { // the weighted sums 1172 const int n = min(kStage, nt - s0); 1173 stage(t0, s0, n); 1174 __syncthreads(); 1175 for (int r = 0; r < n; ++r) { 1176 const uint32_t pr = *(const uint32_t*) (tile + r * d + c); 1177 const float v0 = bf16f((uint16_t) (pr & 0xffffu)), v1 = bf16f((uint16_t) (pr >> 16)); 1178#pragma unroll 1179 for (int g = 0; g < G; ++g) { 1180 o0[g] += sc[g][s0 + r] * v0; 1181 o1[g] += sc[g][s0 + r] * v1; 1182 } 1183 } 1184 __syncthreads(); 1185 } 1186 } 1187#pragma unroll 1188 for (int g = 0; g < G; ++g) { 1189 const float den = den_s[g] + expf(sink[hb + g] - m_run_s[g]); 1190 float* ov = out + ((size_t) t * heads + hb + g) * d; 1191 ov[c] = o0[g] / den; 1192 ov[c + 1] = o1[g] / den; 1193 } 1194} 1195 1196// the ring's rows are kKvFp8: E4M3 codes, a UE8M0 scale per 32 (decoded: exactly the BF16 values they were made from) 1197__global__ void ring_to_ext_kernel(const uint8_t* __restrict__ ring, uint16_t* __restrict__ ext, long long p0, int n, 1198 int d) { 1199 const int r = blockIdx.x; 1200 const long long p = p0 - n + r; 1201 const uint8_t* row = ring + (size_t) (p >= 0 ? p % n : 0) * kv_row_bytes(kKvFp8, d); 1202 for (int e = threadIdx.x; e < d; e += blockDim.x) 1203 ext[(size_t) r * d + e] = p >= 0 ? f2bf16(e4m3_value(row[e]) * ue8m0_val(row[d + e / 32])) : (uint16_t) 0; 1204} 1205 1206// a window row's BF16 values (FP8 roundings: each an E4M3 value times its group's power of two) as E4M3 codes at the 1207// smallest power-of-two scale 2^k their group fits under (max |v| <= 448 * 2^k = 1.75 * 2^(8 + k)): never above the 1208// rounding's own scale, so each v / 2^k is that E4M3 value times a power of two >= 1, at most 448 - an E4M3 value again 1209__global__ void __launch_bounds__(kThreads) ext_to_ring_kernel(const uint16_t* __restrict__ ext, 1210 uint8_t* __restrict__ ring, long long p0, int n, int T, 1211 int d, uint8_t* __restrict__ backup) { 1212 const int t = blockIdx.x; 1213 if (T - t > n) return; // overwritten by a later row of the window anyway 1214 const size_t rb = kv_row_bytes(kKvFp8, d); 1215 uint8_t* row = ring + (size_t) ((p0 + t) % n) * rb; 1216 if (backup != nullptr) { 1217 for (size_t i = threadIdx.x; i < rb; i += blockDim.x) backup[(size_t) t * rb + i] = row[i]; 1218 __syncthreads(); 1219 } 1220 const uint16_t* src = ext + (size_t) (n + t) * d; 1221 for (int e0 = 0; e0 < d; e0 += blockDim.x) { // (d a multiple of 32: a warp's 32 values one group) 1222 const int e = e0 + (int) threadIdx.x; 1223 const float v = e < d ? bf16f(src[e]) : 0.0f; 1224 uint32_t a = __float_as_uint(v) & 0x7fffffffu; // (the magnitudes' order as bits) 1225 for (int o = 16; o > 0; o >>= 1) a = max(a, (uint32_t) __shfl_xor_sync(0xffffffffu, a, o)); 1226 const int k = a == 0u ? 0 : (int) (a >> 23) - 135 + ((a & 0x7fffffu) > 0x600000u ? 1 : 0); 1227 if (e >= d) continue; 1228 row[e] = (uint8_t) e4m3_code(v, k); 1229 if ((e & 31) == 0) row[d + e / 32] = (uint8_t) (k + 127); 1230 } 1231} 1232 1233__global__ void ring_restore_kernel(uint8_t* __restrict__ ring, const uint8_t* __restrict__ backup, long long p0, int n, 1234 int keep, size_t rb) { 1235 const int t = keep + blockIdx.x; 1236 uint8_t* row = ring + (size_t) ((p0 + t) % n) * rb; 1237 for (size_t i = threadIdx.x; i < rb; i += blockDim.x) row[i] = backup[(size_t) t * rb + i]; 1238} 1239__global__ void ring_restore_batch_kernel(const RingBatch b, long long p0, int n, int keep, size_t rb) { 1240 const int t = keep + blockIdx.x, li = blockIdx.y; 1241 uint8_t* row = b.ring[li] + (size_t) ((p0 + t) % n) * rb; 1242 const uint8_t* src = b.bak[li] + (size_t) t * rb; 1243 for (size_t i = threadIdx.x; i < rb; i += blockDim.x) row[i] = src[i]; 1244} 1245 1246__global__ void hc_mean_kernel(const float* __restrict__ h, int hc, int dim, float* __restrict__ out, 1247 long long out_stride) { 1248 const int e = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 1249 if (e >= dim) return; 1250 float a = 0.0f; 1251 for (int s = 0; s < hc; ++s) a += h[((size_t) t * hc + s) * dim + e]; 1252 out[(long long) t * out_stride + e] = a / (float) hc; 1253} 1254 1255__global__ void iota_rows_kernel(int* out, int n, int stride) { 1256 const int t = blockIdx.x; 1257 for (int i = threadIdx.x; i < n; i += blockDim.x) out[(size_t) t * stride + i] = i; 1258} 1259 1260// a warp a vocabulary row: E[*tok] (shared memory) . H[v] 1261__global__ void __launch_bounds__(kThreads) markov_kernel(float* __restrict__ logits, const uint16_t* __restrict__ E, 1262 const uint16_t* __restrict__ H, const int* __restrict__ tok, 1263 int V, int R) { 1264 extern __shared__ float er[]; 1265 const uint16_t* erow = E + (size_t) (*tok) * R; 1266 for (int i = threadIdx.x; i < R; i += blockDim.x) er[i] = bf16f(erow[i]); 1267 __syncthreads(); 1268 const int lane = threadIdx.x & 31; 1269 const int v = blockIdx.x * (kThreads / 32) + (threadIdx.x >> 5); 1270 if (v >= V) return; 1271 const uint16_t* hr = H + (size_t) v * R; 1272 float a = 0.0f; 1273 for (int c = lane * 8; c < R; c += 32 * 8) { 1274 const uint4 q = *(const uint4*) (hr + c); 1275 const __half2* hp = (const __half2*) &q; 1276#pragma unroll 1277 for (int i = 0; i < 4; ++i) { 1278 const float2 f = __half22float2(hp[i]); 1279 a += f.x * er[c + 2 * i] + f.y * er[c + 2 * i + 1]; 1280 } 1281 } 1282 a = warp_sum(a); 1283 if (lane == 0) logits[v] += a; 1284} 1285 1286// ---------------------------------------------------------------- the markov bias over a head group (markov_share) 1287// a member's rows [v0, v0 + vn) of the bias (markov_kernel's sums, the prev token's E row already on the device, BF16) 1288__global__ void __launch_bounds__(kThreads) markov_share_kernel(float* __restrict__ logits, 1289 const uint16_t* __restrict__ H, 1290 const uint16_t* __restrict__ erow, int vn, int R) { 1291 extern __shared__ float er[]; 1292 for (int i = threadIdx.x; i < R; i += blockDim.x) er[i] = bf16f(erow[i]); 1293 __syncthreads(); 1294 const int lane = threadIdx.x & 31; 1295 const int v = blockIdx.x * (kThreads / 32) + (threadIdx.x >> 5); 1296 if (v >= vn) return; 1297 const uint16_t* hr = H + (size_t) v * R; 1298 float a = 0.0f; 1299 for (int c = lane * 8; c < R; c += 32 * 8) { 1300 const uint4 q = *(const uint4*) (hr + c); 1301 const __half2* hp = (const __half2*) &q; 1302#pragma unroll 1303 for (int i = 0; i < 4; ++i) { 1304 const float2 f = __half22float2(hp[i]); 1305 a += f.x * er[c + 2 * i] + f.y * er[c + 2 * i + 1]; 1306 } 1307 } 1308 a = warp_sum(a); 1309 if (lane == 0) logits[v] += a; 1310} 1311// the share's argmax (the greedy sampler's rule: the larger value, on a tie the lower index) -> slot {value, v0 + i, 1312// seq}, the seq last 1313__global__ void __launch_bounds__(1024) argmax_share_kernel(const float* __restrict__ row, int vn, int v0, 1314 unsigned* slot, unsigned seq) { 1315 __shared__ float sv[32]; 1316 __shared__ int si[32]; 1317 float bv = __int_as_float(0xff800000); 1318 int bi = 0x7fffffff; 1319 for (int i = threadIdx.x; i < vn; i += blockDim.x) { 1320 const float x = row[i]; 1321 if (x > bv) bv = x, bi = i; // (ascending: the lowest index of a tie stays) 1322 } 1323 for (int o = 16; o > 0; o >>= 1) { 1324 const float ov = __shfl_xor_sync(0xffffffffu, bv, o); 1325 const int oi = __shfl_xor_sync(0xffffffffu, bi, o); 1326 if (ov > bv || (ov == bv && oi < bi)) bv = ov, bi = oi; 1327 } 1328 if ((threadIdx.x & 31) == 0) sv[threadIdx.x >> 5] = bv, si[threadIdx.x >> 5] = bi; 1329 __syncthreads(); 1330 if (threadIdx.x == 0) { 1331 for (int w = 1; w < (int) (blockDim.x >> 5); ++w) 1332 if (sv[w] > bv || (sv[w] == bv && si[w] < bi)) bv = sv[w], bi = si[w]; 1333 slot[0] = __float_as_uint(bv); 1334 slot[1] = (unsigned) (v0 + (bi == 0x7fffffff ? 0 : bi)); 1335 __threadfence_system(); 1336 *(volatile unsigned*) (slot + 2) = seq; 1337 } 1338} 1339// every member's share argmax of this step (slots nm apart) -> the global one into *tok, and its E row (host-mapped 1340// BF16 [V][R]) into erow for the next step's bias 1341__global__ void markov_pick_kernel(const unsigned* slots, int nm, unsigned seq, int* tok, const uint16_t* E, 1342 uint16_t* erow, int R) { 1343 __shared__ int pick; 1344 if ((int) threadIdx.x < nm) 1345 while ((int) (*(volatile const unsigned*) (slots + (size_t) threadIdx.x * 4 + 2) - seq) < 0) { 1346#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 1347 __nanosleep(32); 1348#endif 1349 } 1350 __syncthreads(); 1351 if (threadIdx.x == 0) { 1352 float bv = __int_as_float(0xff800000); 1353 int bi = 0x7fffffff; 1354 for (int m = 0; m < nm; ++m) { // (members in vocabulary order: a tie keeps the lower index) 1355 const float v = __uint_as_float(*(volatile const unsigned*) (slots + (size_t) m * 4)); 1356 const int i = (int) *(volatile const unsigned*) (slots + (size_t) m * 4 + 1); 1357 if (v > bv || (v == bv && i < bi)) bv = v, bi = i; 1358 } 1359 pick = bi; 1360 *tok = bi; 1361 } 1362 __syncthreads(); 1363#if defined(STRATA_USE_HIP) // (E is fixed once loaded: a plain load is as fresh) 1364 for (int i = threadIdx.x; i < R; i += blockDim.x) erow[i] = E[(size_t) pick * R + i]; 1365#else 1366 for (int i = threadIdx.x; i < R; i += blockDim.x) erow[i] = __ldcv(E + (size_t) pick * R + i); 1367#endif 1368} 1369 1370__global__ void __launch_bounds__(1024) confidence_kernel(const float* __restrict__ x, const uint16_t* __restrict__ E, 1371 const int* __restrict__ tok, const float* __restrict__ w, 1372 int dim, int R, float* __restrict__ out) { 1373 const int t = blockIdx.x; 1374 const float* xt = x + (size_t) t * dim; 1375 const uint16_t* er = E + (size_t) tok[t] * R; 1376 float a = 0.0f; 1377 for (int i = threadIdx.x; i < dim + R; i += blockDim.x) a += w[i] * (i < dim ? xt[i] : bf16f(er[i - dim])); 1378 a = block_sum(a); 1379 if (threadIdx.x == 0) out[t] = 1.0f / (1.0f + expf(-a)); 1380} 1381 1382// ---------------------------------------------------------------- engram 1383// ggml's IQ4_NL: a block of 32 values is 18 bytes, an fp16 d then 16 packed nibble bytes; the low nibble of qs[j] is 1384// value j and its high nibble value j + 16, each an index into this codebook (ggml-common.h's kvalues_iq4nl, 1385// dequantize_row_iq4_nl). A row is hd / 32 of these blocks, the d of every one inside it - no separate scales. 1386__device__ __constant__ int8_t kIq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1387 1, 13, 25, 38, 53, 69, 89, 113}; 1388__device__ __forceinline__ float iq4nl_value(const uint8_t* b, int e) { 1389 const uint8_t q = b[2 + (e & 15)]; 1390 const int v = (e & 16) ? (q >> 4) : (q & 15); 1391 return __half2float(__ushort_as_half(*(const uint16_t*) b)) * (float) kIq4nl[v]; 1392} 1393 1394__global__ void engram_dequant_kernel(const uint8_t* __restrict__ rows, const uint8_t* __restrict__ scales, int hd, 1395 float* __restrict__ out, int fmt) { 1396 const int r = blockIdx.x; 1397 if (fmt == 1) { // (ggml Q6_K superblocks at the row's start) 1398 for (int e = threadIdx.x; e < hd; e += blockDim.x) 1399 out[(size_t) r * hd + e] = q6k_value(rows + (size_t) r * hd + (size_t) (e / 256) * kQ6kBytes, e % 256); 1400 return; 1401 } 1402 if (fmt == 2) { // (ggml IQ4_NL blocks at the row's start, their scales inside) 1403 for (int e = threadIdx.x; e < hd; e += blockDim.x) 1404 out[(size_t) r * hd + e] = iq4nl_value(rows + (size_t) r * hd + (size_t) (e / 32) * 18, e % 32); 1405 return; 1406 } 1407 for (int e = threadIdx.x; e < hd; e += blockDim.x) { 1408 const float hv = e4m3_value(rows[(size_t) r * hd + e]); 1409 const uint8_t sb = scales[(size_t) r * (hd / 32) + e / 32]; 1410 const float s = sb == 0xffu ? __int_as_float(0x7fc00000) : (sb == 0 ? 5.877471754111438e-39f 1411 : __uint_as_float((uint32_t) sb << 23)); 1412 out[(size_t) r * hd + e] = hv * s; 1413 } 1414} 1415 1416__global__ void __launch_bounds__(1024) engram_gate_kernel(float* __restrict__ h, const float* __restrict__ kv, 1417 const float* __restrict__ w, int hc, int dim, float eps) { 1418 const int k = blockIdx.x, t = blockIdx.y; 1419 float* hk = h + ((size_t) t * hc + k) * dim; 1420 const float* kvt = kv + (size_t) t * (hc + 1) * dim; 1421 const float* key = kvt + (size_t) k * dim; 1422 const float* val = kvt + (size_t) hc * dim; 1423 const float* wk = w + (size_t) k * dim; 1424 float sh = 0.0f, sk = 0.0f, sd = 0.0f; 1425 for (int e = threadIdx.x; e < dim; e += blockDim.x) { 1426 const float hv = hk[e], kv_ = key[e]; 1427 sh += hv * hv; 1428 sk += kv_ * kv_; 1429 sd += hv * wk[e] * kv_; 1430 } 1431 sh = block_sum(sh); 1432 sk = block_sum(sk); 1433 sd = block_sum(sd); 1434 const float rstd = rsqrtf(sh / (float) dim + eps) * rsqrtf(sk / (float) dim + eps); 1435 const float dot = sd * rstd * rsqrtf((float) dim); 1436 const float sq = copysignf(sqrtf(fmaxf(fabsf(dot), 1e-6f)), dot); 1437 const float gate = 1.0f / (1.0f + expf(-sq)); 1438 for (int e = threadIdx.x; e < dim; e += blockDim.x) hk[e] = hk[e] + gate * val[e]; 1439} 1440 1441__global__ void gather_kernel(const float* __restrict__ x, Gather g, int cols, float* __restrict__ out) { 1442 const int r = blockIdx.y; 1443 const int c = blockIdx.x * blockDim.x + threadIdx.x; 1444 if (c < cols) out[(size_t) r * cols + c] = x[(size_t) g.src[r] * cols + c]; 1445} 1446 1447__global__ void combine_kernel(const float* __restrict__ ed, const float* __restrict__ cpu, 1448 const float* __restrict__ sh, Combine cm, int dim, float* __restrict__ out) { 1449 const int e = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 1450 if (e >= dim) return; 1451 float a = 0.0f; 1452 for (int j = 0; j < cm.n[t]; ++j) a += cm.w[t][j] * ed[(size_t) cm.row[t][j] * dim + e]; 1453 if (cpu != nullptr && cm.cpu[t]) a += cpu[(size_t) t * dim + e]; 1454 if (sh != nullptr) a += sh[(size_t) t * dim + e]; 1455 out[(size_t) t * dim + e] = a; 1456} 1457 1458__global__ void __launch_bounds__(512) route_publish_kernel(const float* __restrict__ logits, 1459 const float* __restrict__ bias, int n, int k, 1460 float route_scale, const unsigned long long* __restrict__ vram, 1461 const float* __restrict__ x, int dim, int* idx, float* w, 1462 unsigned long long* plan_ptr, Req* req, 1463 const float* __restrict__ bias_vl, unsigned vl, const unsigned char* __restrict__ res) { 1464 __shared__ float sc[1024], bs[1024]; 1465 __shared__ float bv[32]; 1466 __shared__ int bi[32]; 1467 __shared__ int pick[16]; 1468 __shared__ int on_cpu; 1469 const int t = blockIdx.x; 1470 logits += (size_t) t * 1024; 1471 if (bias_vl != nullptr && ((vl >> t) & 1u)) bias = bias_vl; 1472 for (int i = threadIdx.x; i < n; i += blockDim.x) { 1473 const float l = logits[i]; 1474 const float sp = l > 20.0f ? l : log1pf(expf(l)); 1475 sc[i] = sqrtf(sp); 1476 bs[i] = sc[i] + bias[i]; 1477 } 1478 __syncthreads(); 1479 if (g_cp_lambda > 0.0f) { 1480 __shared__ float cp_add; 1481 __shared__ int cp_keep[8], cp_n; 1482 if (threadIdx.x == 0) { 1483 float lo = FLT_MAX, hi = -FLT_MAX; 1484 for (int i = 0; i < n; ++i) lo = fminf(lo, bs[i]), hi = fmaxf(hi, bs[i]); 1485 cp_n = min(max(g_cp_keep, 0), 8); 1486 for (int q = 0; q < cp_n; ++q) { // the exact top-keep, ties to the lower index as the selection below 1487 float b = -FLT_MAX; 1488 int ix = 0x7fffffff; 1489 for (int i = 0; i < n; ++i) { 1490 bool taken = false; 1491 for (int z = 0; z < q; ++z) taken |= cp_keep[z] == i; 1492 if (!taken && (bs[i] > b || (bs[i] == b && i < ix))) b = bs[i], ix = i; 1493 } 1494 cp_keep[q] = ix; 1495 } 1496 cp_add = g_cp_lambda * (hi - lo); 1497 } 1498 __syncthreads(); 1499 for (int i = threadIdx.x; i < n; i += blockDim.x) { 1500 bool favoured = vram[i] != 0ull || (res != nullptr && res[i] != 0); 1501 for (int z = 0; z < cp_n; ++z) favoured |= cp_keep[z] == i; 1502 if (favoured) bs[i] += cp_add; 1503 } 1504 __syncthreads(); 1505 } 1506 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; 1507 for (int r = 0; r < k; ++r) { 1508 float best = -FLT_MAX; 1509 int bix = 0x7fffffff; 1510 for (int i = threadIdx.x; i < n; i += blockDim.x) 1511 if (bs[i] > best || (bs[i] == best && i < bix)) best = bs[i], bix = i; 1512 for (int o = 16; o > 0; o >>= 1) { 1513 const float ov = __shfl_xor_sync(0xffffffffu, best, o); 1514 const int oi = __shfl_xor_sync(0xffffffffu, bix, o); 1515 if (ov > best || (ov == best && oi < bix)) best = ov, bix = oi; 1516 } 1517 if (lane == 0) bv[wp] = best, bi[wp] = bix; 1518 __syncthreads(); 1519 if (threadIdx.x == 0) { 1520 float b = -FLT_MAX; 1521 int ix = 0x7fffffff; 1522 for (int q = 0; q < (int) (blockDim.x >> 5); ++q) 1523 if (bv[q] > b || (bv[q] == b && bi[q] < ix)) b = bv[q], ix = bi[q]; 1524 pick[r] = ix; 1525 bs[ix] = -FLT_MAX; 1526 } 1527 __syncthreads(); 1528 } 1529 if (threadIdx.x == 0) { 1530 float s = 0.0f; 1531 for (int r = 0; r < k; ++r) s += sc[pick[r]]; 1532 int cpu = 0; 1533 for (int r = 0; r < k; ++r) { 1534 const float wv = sc[pick[r]] / (s + 1e-20f) * route_scale; 1535 idx[(size_t) t * kPicks + r] = pick[r]; 1536 w[(size_t) t * kPicks + r] = wv; 1537 plan_ptr[(size_t) t * kPicks + r] = vram[pick[r]]; 1538 cpu |= vram[pick[r]] == 0ull; 1539 if (req != nullptr) { 1540 req->ids[t][r] = pick[r]; 1541 req->w[t][r] = wv; 1542 } 1543 } 1544 on_cpu = cpu; 1545 } 1546 // the token's FFN input to the host only where the CPU lane reads it (a pick of its on the CPU lane): each row 1547 // 20 KB over PCIe, where most windows have none 1548 __syncthreads(); 1549 if (req != nullptr && on_cpu) 1550 for (int i = threadIdx.x; i < dim; i += blockDim.x) req->x[t][i] = x[(size_t) t * dim + i]; 1551} 1552 1553// a later layer's m likely picks (route_kernel's choice from its logits) into req->ahead[t][off ..) 1554__global__ void __launch_bounds__(512) route_ahead_kernel(const float* __restrict__ logits, 1555 const float* __restrict__ bias, int n, int m, Req* req, 1556 int off) { 1557 __shared__ float bs[1024]; 1558 __shared__ float bv[32]; 1559 __shared__ int bi[32]; 1560 const int t = blockIdx.x; 1561 logits += (size_t) t * 1024; 1562 for (int i = threadIdx.x; i < n; i += blockDim.x) { 1563 const float l = logits[i]; 1564 const float sp = l > 20.0f ? l : log1pf(expf(l)); 1565 bs[i] = sqrtf(sp) + bias[i]; 1566 } 1567 __syncthreads(); 1568 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; 1569 for (int r = 0; r < m; ++r) { 1570 float best = -FLT_MAX; 1571 int bix = 0x7fffffff; 1572 for (int i = threadIdx.x; i < n; i += blockDim.x) 1573 if (bs[i] > best || (bs[i] == best && i < bix)) best = bs[i], bix = i; 1574 for (int o = 16; o > 0; o >>= 1) { 1575 const float ov = __shfl_xor_sync(0xffffffffu, best, o); 1576 const int oi = __shfl_xor_sync(0xffffffffu, bix, o); 1577 if (ov > best || (ov == best && oi < bix)) best = ov, bix = oi; 1578 } 1579 if (lane == 0) bv[wp] = best, bi[wp] = bix; 1580 __syncthreads(); 1581 if (threadIdx.x == 0) { 1582 float b = -FLT_MAX; 1583 int ix = 0x7fffffff; 1584 for (int q = 0; q < (int) (blockDim.x >> 5); ++q) 1585 if (bv[q] > b || (bv[q] == b && bi[q] < ix)) b = bv[q], ix = bi[q]; 1586 req->ahead[t][off + r] = ix < n ? ix : -1; 1587 if (ix < n) bs[ix] = -FLT_MAX; 1588 } 1589 __syncthreads(); 1590 } 1591} 1592 1593__global__ void publish_kernel(Req* req, int T, unsigned seq, int na0, int na1) { 1594 __threadfence_system(); 1595 req->na[0] = na0; 1596 req->na[1] = na1; 1597 req->T = T; 1598 __threadfence_system(); 1599 *(volatile unsigned*) &req->seq = seq; 1600} 1601 1602__global__ void wait_seq_kernel(const unsigned* seq_ptr, unsigned seq) { 1603 if (threadIdx.x != 0) return; 1604 while (*(volatile const unsigned*) seq_ptr != seq) { 1605#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 1606 __nanosleep(200); 1607#endif 1608 } 1609 __threadfence_system(); 1610} 1611 1612__global__ void init_pre_kernel(float* pre, int T) { 1613 const int i = blockIdx.x * blockDim.x + threadIdx.x; 1614 if (i < T * 8) pre[i] = (i % 8) == 0 ? 1.0f : 0.0f; 1615} 1616 1617 1618// the hand-offs through host-mapped memory: a grid-stride copy of the segments (16 bytes a thread), then (put, flag 1619// given) the last block to finish sets the flag after a system fence; a get first waits for the flag 1620__device__ __forceinline__ void xfer_copy(const Xfer& x, bool from_host) { 1621 size_t total = 0; 1622 for (int i = 0; i < x.n; ++i) total += x.bytes[i] / 16; 1623 for (size_t q = (size_t) blockIdx.x * blockDim.x + threadIdx.x; q < total; q += (size_t) gridDim.x * blockDim.x) { 1624 size_t r = q; 1625 int i = 0; 1626 while (r >= x.bytes[i] / 16) r -= x.bytes[i++] / 16; 1627 const uint4* src = (const uint4*) x.src[i] + r; 1628 ((uint4*) x.dst[i])[r] = from_host ? ld_fresh(src) : *src; 1629 } 1630} 1631 1632__global__ void __launch_bounds__(kThreads) xfer_put_kernel(const Xfer x, unsigned* flag, unsigned seq, unsigned* cnt) { 1633 xfer_copy(x, false); 1634 if (flag == nullptr) return; 1635 __threadfence_system(); 1636 __syncthreads(); 1637 if (threadIdx.x == 0 && atomicAdd(cnt, 1u) == gridDim.x - 1) { 1638 *cnt = 0u; 1639 __threadfence_system(); 1640 *(volatile unsigned*) flag = seq; 1641 } 1642} 1643 1644__device__ __forceinline__ void wait_at_least(const unsigned* flag, unsigned seq) { 1645 while ((int) (*(volatile const unsigned*) flag - seq) < 0) { 1646#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 1647 __nanosleep(100); 1648#endif 1649 } 1650} 1651 1652__global__ void __launch_bounds__(kThreads) xfer_get_kernel(const Xfer x, const unsigned* flag, unsigned seq) { 1653 if (threadIdx.x == 0) wait_at_least(flag, seq); 1654 __syncthreads(); 1655 xfer_copy(x, true); 1656} 1657 1658__global__ void wait_flags_kernel(const unsigned* flags, int n, int stride, unsigned seq) { 1659 if (threadIdx.x != 0) return; 1660 for (int i = 0; i < n; ++i) wait_at_least(flags + (size_t) i * stride, seq); 1661 __threadfence_system(); 1662} 1663__global__ void set_flag_kernel(unsigned* flag, unsigned v) { 1664 __threadfence_system(); 1665 *(volatile unsigned*) flag = v; 1666} 1667 1668// three members or more: a reduce-scatter and an all-gather in one launch, a block a contiguous range of the row cut 1669// in nm chunks. The block puts its range of this member's partial out and flags it; once every member's flag of the 1670// range is up it sums chunk mi of the range in member order (ar_sum_kernel's sums, bit for bit), puts that out and 1671// flags it; once every member's sum flag is up it reads the other chunks' sums. Each member reads about two rows over 1672// PCIe whatever nm is, where every member reading every other row grows with nm 1673__global__ void __launch_bounds__(kThreads) ar_rs_kernel(float* x, int n4, float* rows, float* sums, size_t stride, 1674 unsigned* bflags, int nm, int mi, int slot, int slots, 1675 unsigned seq) { 1676 float4* x4 = (float4*) x; 1677 const int per = (n4 + (int) gridDim.x - 1) / (int) gridDim.x; 1678 const int lo = blockIdx.x * per, hi = min(n4, lo + per), cs = (hi - lo + nm - 1) / nm; 1679 auto rflag = [&](int m) { return bflags + (((size_t) m * slots + slot) * kArBlocks + blockIdx.x) * 8; }; 1680 auto sflag = [&](int m) { 1681 return bflags + ((((size_t) nm + m) * slots + slot) * kArBlocks + blockIdx.x) * 8; 1682 }; 1683 auto row = [&](int m) { return (float4*) (rows + ((size_t) m * slots + slot) * stride); }; 1684 float4* sum = (float4*) (sums + (size_t) slot * stride); 1685 if (lo < hi) { 1686 float4* mine = row(mi); 1687 for (int q = lo + threadIdx.x; q < hi; q += blockDim.x) mine[q] = x4[q]; 1688 } 1689 __threadfence_system(); 1690 __syncthreads(); 1691 if (threadIdx.x == 0) *(volatile unsigned*) rflag(mi) = seq; 1692 if ((int) threadIdx.x < nm && (int) threadIdx.x != mi) wait_at_least(rflag(threadIdx.x), seq); 1693 __syncthreads(); 1694 const int c0 = min(hi, lo + mi * cs), c1 = min(hi, c0 + cs); 1695 for (int q = c0 + threadIdx.x; q < c1; q += blockDim.x) { 1696 float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 1697 for (int m = 0; m < nm; ++m) { 1698 const float4 p = m == mi ? x4[q] : ld_fresh(row(m) + q); 1699 if (m == 0) v = p; 1700 else { 1701 v.x = __fadd_rn(v.x, p.x); 1702 v.y = __fadd_rn(v.y, p.y); 1703 v.z = __fadd_rn(v.z, p.z); 1704 v.w = __fadd_rn(v.w, p.w); 1705 } 1706 } 1707 sum[q] = v; 1708 x4[q] = v; 1709 } 1710 __threadfence_system(); 1711 __syncthreads(); 1712 if (threadIdx.x == 0) *(volatile unsigned*) sflag(mi) = seq; 1713 if ((int) threadIdx.x < nm && (int) threadIdx.x != mi) wait_at_least(sflag(threadIdx.x), seq); 1714 __syncthreads(); 1715 for (int q = lo + threadIdx.x; q < hi; q += blockDim.x) 1716 if (q < c0 || q >= c1) x4[q] = ld_fresh(sum + q); 1717} 1718 1719// ar_rs_kernel with the rows and the sums in FP16 (DS4_AR_F16): half the bytes over PCIe. Every member's partial is 1720// rounded to FP16 (the owner's too), summed in F32 in member order, the sum rounded to FP16 - and every member, the 1721// owner too, takes that rounded sum, so the members' copies of the stream stay the same 1722__device__ __forceinline__ uint2 to_h4(float4 v) { 1723 const __half2 a = __floats2half2_rn(v.x, v.y), b = __floats2half2_rn(v.z, v.w); 1724 return make_uint2(*(const unsigned*) &a, *(const unsigned*) &b); 1725} 1726__device__ __forceinline__ float4 from_h4(uint2 u) { 1727 const float2 a = __half22float2(*(const __half2*) &u.x), b = __half22float2(*(const __half2*) &u.y); 1728 return make_float4(a.x, a.y, b.x, b.y); 1729} 1730__device__ __forceinline__ float4 sat4(float4 v) { // (FP16's range: a partial past it saturates instead of inf) 1731 const float m = 65504.0f; 1732 return make_float4(fminf(fmaxf(v.x, -m), m), fminf(fmaxf(v.y, -m), m), fminf(fmaxf(v.z, -m), m), fminf(fmaxf(v.w, -m), m)); 1733} 1734__global__ void __launch_bounds__(kThreads) ar_rs16_kernel(float* x, int n4, float* rows, float* sums, size_t stride, 1735 unsigned* bflags, int nm, int mi, int slot, int slots, 1736 unsigned seq) { 1737 float4* x4 = (float4*) x; 1738 const int per = (n4 + (int) gridDim.x - 1) / (int) gridDim.x; 1739 const int lo = blockIdx.x * per, hi = min(n4, lo + per), cs = (hi - lo + nm - 1) / nm; 1740 auto rflag = [&](int m) { return bflags + (((size_t) m * slots + slot) * kArBlocks + blockIdx.x) * 8; }; 1741 auto sflag = [&](int m) { 1742 return bflags + ((((size_t) nm + m) * slots + slot) * kArBlocks + blockIdx.x) * 8; 1743 }; 1744 auto row = [&](int m) { return (uint2*) (rows + ((size_t) m * slots + slot) * stride); }; // (FP16: half a row) 1745 uint2* sum = (uint2*) (sums + (size_t) slot * stride); 1746 if (lo < hi) { 1747 uint2* mine = row(mi); 1748 for (int q = lo + threadIdx.x; q < hi; q += blockDim.x) mine[q] = to_h4(sat4(x4[q])); 1749 } 1750 __threadfence_system(); 1751 __syncthreads(); 1752 if (threadIdx.x == 0) *(volatile unsigned*) rflag(mi) = seq; 1753 if ((int) threadIdx.x < nm && (int) threadIdx.x != mi) wait_at_least(rflag(threadIdx.x), seq); 1754 __syncthreads(); 1755 const int c0 = min(hi, lo + mi * cs), c1 = min(hi, c0 + cs); 1756 for (int q = c0 + threadIdx.x; q < c1; q += blockDim.x) { 1757 float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 1758 for (int m = 0; m < nm; ++m) { 1759 const uint2 u = m == mi ? to_h4(sat4(x4[q])) : ld_fresh(row(m) + q); 1760 const float4 p = from_h4(u); 1761 if (m == 0) v = p; 1762 else { 1763 v.x = __fadd_rn(v.x, p.x); 1764 v.y = __fadd_rn(v.y, p.y); 1765 v.z = __fadd_rn(v.z, p.z); 1766 v.w = __fadd_rn(v.w, p.w); 1767 } 1768 } 1769 const uint2 s16 = to_h4(sat4(v)); 1770 sum[q] = s16; 1771 x4[q] = from_h4(s16); 1772 } 1773 __threadfence_system(); 1774 __syncthreads(); 1775 if (threadIdx.x == 0) *(volatile unsigned*) sflag(mi) = seq; 1776 if ((int) threadIdx.x < nm && (int) threadIdx.x != mi) wait_at_least(sflag(threadIdx.x), seq); 1777 __syncthreads(); 1778 for (int q = lo + threadIdx.x; q < hi; q += blockDim.x) 1779 if (q < c0 || q >= c1) x4[q] = from_h4(ld_fresh(sum + q)); 1780} 1781 1782// x[i] = the members' partials summed in member order (this member's from x, the others' from their host rows) 1783__global__ void __launch_bounds__(kThreads) ar_sum_kernel(float* x, int n4, const float* peers, size_t stride, 1784 const unsigned* flags, int nm, int mi, int slot, int slots, 1785 unsigned seq) { 1786 if (threadIdx.x == 0) 1787 for (int m = 0; m < nm; ++m) 1788 if (m != mi) wait_at_least(flags + ((size_t) m * slots + slot) * 32, seq); 1789 __syncthreads(); 1790 for (int q = blockIdx.x * blockDim.x + threadIdx.x; q < n4; q += gridDim.x * blockDim.x) { 1791 float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 1792 for (int m = 0; m < nm; ++m) { 1793 const float4 p = m == mi ? ((const float4*) x)[q] 1794 : ld_fresh((const float4*) (peers + ((size_t) m * slots + slot) * stride) + q); 1795 if (m == 0) v = p; 1796 else { 1797 v.x = __fadd_rn(v.x, p.x); 1798 v.y = __fadd_rn(v.y, p.y); 1799 v.z = __fadd_rn(v.z, p.z); 1800 v.w = __fadd_rn(v.w, p.w); 1801 } 1802 } 1803 ((float4*) x)[q] = v; 1804 } 1805} 1806 1807 1808// a thread a (token, value): every stream's value read before any is written 1809__global__ void hc_post_inplace_kernel(const float* __restrict__ y, float* h, const float* __restrict__ post, 1810 const float* __restrict__ comb, int dim, int hc) { 1811 const int e = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 1812 if (e >= dim) return; 1813 float* r = h + (size_t) t * hc * dim; 1814 float rv[8]; 1815 for (int j = 0; j < hc; ++j) rv[j] = r[(size_t) j * dim + e]; 1816 const float yv = y[(size_t) t * dim + e]; 1817 for (int k = 0; k < hc; ++k) { 1818 float a = post[(size_t) t * 8 + k] * yv; 1819 for (int j = 0; j < hc; ++j) a += comb[(size_t) t * 64 + j * hc + k] * rv[j]; 1820 r[(size_t) k * dim + e] = a; 1821 } 1822} 1823 1824__global__ void __launch_bounds__(kThreads) hc_mix_scale_kernel(const float* __restrict__ h, int hcdim, int n_mix, 1825 float eps, float* mixes) { 1826 const int t = blockIdx.x; 1827 const float* x = h + (size_t) t * hcdim; 1828 float ss = 0.0f; 1829 for (int k = threadIdx.x * 4; k < hcdim; k += kThreads * 4) { 1830 const float4 hv = *(const float4*) (x + k); 1831 ss += hv.x * hv.x + hv.y * hv.y + hv.z * hv.z + hv.w * hv.w; 1832 } 1833 ss = block_sum(ss); 1834 const float inv = rsqrtf(ss / (float) hcdim + eps); 1835 if (threadIdx.x < n_mix) mixes[(size_t) t * 32 + threadIdx.x] *= inv; 1836} 1837 1838__global__ void engram_dequant_tok_kernel(const uint8_t* __restrict__ src, size_t per, int cols, int hd, 1839 float* __restrict__ out, int fmt) { 1840 const int r = blockIdx.x, t = r / cols, c = r - t * cols; 1841 const uint8_t* rows = src + (size_t) t * per + (size_t) c * hd; 1842 const uint8_t* scales = src + (size_t) t * per + (size_t) cols * hd + (size_t) c * (hd / 32); 1843 if (fmt == 1) { // (ggml Q6_K superblocks at the row's start) 1844 for (int e = threadIdx.x; e < hd; e += blockDim.x) 1845 out[(size_t) r * hd + e] = q6k_value(rows + (size_t) (e / 256) * kQ6kBytes, e % 256); 1846 return; 1847 } 1848 if (fmt == 2) { // (ggml IQ4_NL blocks at the row's start, their scales inside) 1849 for (int e = threadIdx.x; e < hd; e += blockDim.x) 1850 out[(size_t) r * hd + e] = iq4nl_value(rows + (size_t) (e / 32) * 18, e % 32); 1851 return; 1852 } 1853 for (int e = threadIdx.x; e < hd; e += blockDim.x) { 1854 const float hv = e4m3_value(rows[e]); 1855 const uint8_t sb = scales[e / 32]; 1856 const float s = sb == 0xffu ? __int_as_float(0x7fc00000) : (sb == 0 ? 5.877471754111438e-39f 1857 : __uint_as_float((uint32_t) sb << 23)); 1858 out[(size_t) r * hd + e] = hv * s; 1859 } 1860} 1861 1862// a block a virtual slot: its picks counted (sort pass 1), or (fill) placed in token order by a block-wide scan 1863template <bool FILL> 1864__global__ void __launch_bounds__(kThreads) moe_sort_kernel(const int* __restrict__ idx, int T, int k, 1865 const int* __restrict__ vs, int* bounds, int* row_tok, 1866 int* pos) { 1867 const int slot = blockIdx.x; 1868 __shared__ int warp_n[kThreads / 32]; 1869 __shared__ int base_s; 1870 if (threadIdx.x == 0) base_s = FILL ? bounds[slot] : 0; 1871 __syncthreads(); 1872 const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; 1873 const int n = T * k; 1874 for (int q0 = 0; q0 < n; q0 += kThreads) { 1875 const int q = q0 + threadIdx.x; 1876 const int t = q / k, i = q - t * k; 1877 const bool hit = q < n && vs[idx[(size_t) t * kPicks + i]] == slot; 1878 const unsigned m = __ballot_sync(0xffffffffu, hit); 1879 if (lane == 0) warp_n[wp] = __popc(m); 1880 __syncthreads(); 1881 int before = 0, total = 0; 1882 for (int w = 0; w < kThreads / 32; ++w) { 1883 if (w < wp) before += warp_n[w]; 1884 total += warp_n[w]; 1885 } 1886 if (FILL && hit) { 1887 const int r = base_s + before + __popc(m & ((1u << lane) - 1u)); 1888 row_tok[r] = t; 1889 pos[(size_t) t * kPicks + i] = r; 1890 } 1891 __syncthreads(); 1892 if (threadIdx.x == 0) base_s += total; 1893 __syncthreads(); 1894 } 1895 if (!FILL && threadIdx.x == 0) bounds[slot + 1] = base_s; // (the counts; the scan makes them bounds) 1896} 1897 1898__global__ void bounds_scan_kernel(int* bounds, int n_vs) { // one thread: bounds[0] = 0, bounds[s + 1] += bounds[s] 1899 if (threadIdx.x != 0) return; 1900 bounds[0] = 0; 1901 for (int s = 0; s < n_vs; ++s) bounds[s + 1] += bounds[s]; 1902} 1903 1904__global__ void moe_combine_kernel(float* acc, const float* __restrict__ y, const int* __restrict__ pos, 1905 const float* __restrict__ w, int k, int r0, int r1, int dim) { 1906 const int e = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; 1907 if (e >= dim) return; 1908 float a = acc[(size_t) t * dim + e]; 1909 bool any = false; 1910 for (int i = 0; i < k; ++i) { 1911 const int r = pos[(size_t) t * kPicks + i]; 1912 if (r < r0 || r >= r1) continue; 1913 a = __fmaf_rn(w[(size_t) t * kPicks + i], y[(size_t) (r - r0) * dim + e], a); 1914 any = true; 1915 } 1916 if (any) acc[(size_t) t * dim + e] = a; 1917} 1918 1919int cdiv(int a, int b) { return (a + b - 1) / b; } 1920 1921} // namespace 1922 1923namespace { 1924 1925// ---- the split-KV attention's scratch: a device allocation a (device, stream), made on first use and kept 1926constexpr int kSplitG = 4, kSplitR = 40, kSplitCap = 24, kSplitMaxT = 5; 1927bool split_enabled() { 1928 static const bool on = [] { 1929 const char* e = std::getenv("DS4_ATTN_SPLIT"); 1930 return e != nullptr && std::atoi(e) != 0; // opt-in: no gain measured on 4x R9700 (21.8 vs 21.9 tok/s) 1931 }(); 1932 return on; 1933} 1934attnsplit::AttnSplitScratch split_scratch(cudaStream_t s, int heads) { 1935 static std::mutex mu; 1936 static std::map<std::pair<int, cudaStream_t>, attnsplit::AttnSplitScratch> m; 1937 int dev = 0; 1938 cudaGetDevice(&dev); 1939 std::lock_guard<std::mutex> lk(mu); 1940 auto it = m.find({dev, s}); 1941 if (it != m.end()) return it->second; 1942 attnsplit::AttnSplitScratch sc; 1943 sc.nsplit = kSplitCap; 1944 sc.max_t = kSplitMaxT; 1945 const size_t np = (size_t) kSplitMaxT * heads * kSplitCap; 1946 if (cudaMalloc((void**) &sc.part, np * 512 * sizeof(float)) != cudaSuccess || 1947 cudaMalloc((void**) &sc.ml, np * 2 * sizeof(float)) != cudaSuccess) { 1948 cudaGetLastError(); 1949 if (sc.part != nullptr) cudaFree(sc.part); 1950 sc = attnsplit::AttnSplitScratch{}; 1951 } 1952 m[{dev, s}] = sc; 1953 return sc; 1954} 1955} // namespace 1956 1957void route_publish(const float* logits, const float* bias, int n, int k, int T, float route_scale, 1958 const unsigned long long* vram, const float* x, int dim, int* idx, float* w, 1959 unsigned long long* plan_ptr, Req* req, unsigned seq, cudaStream_t s, const float* bias_vl, 1960 unsigned vl, int na0, int na1, const unsigned char* res) { 1961 static bool cp_set[64] = {}; 1962 int cp_dev = 0; 1963 if (cudaGetDevice(&cp_dev) == cudaSuccess && cp_dev >= 0 && cp_dev < 64 && !cp_set[cp_dev]) { 1964 const char* el = std::getenv("DS4_CP_LAMBDA"); 1965 const char* ek = std::getenv("DS4_CP_KEEP"); 1966 const float lam = el != nullptr ? (float) std::atof(el) : 0.0f; 1967 const int keep = ek != nullptr ? std::atoi(ek) : 3; 1968 cudaMemcpyToSymbolAsync(g_cp_lambda, &lam, sizeof lam, 0, cudaMemcpyHostToDevice, s); 1969 cudaMemcpyToSymbolAsync(g_cp_keep, &keep, sizeof keep, 0, cudaMemcpyHostToDevice, s); 1970 cudaStreamSynchronize(s); 1971 if (lam > 0.0f) std::fprintf(stderr, "ds4: Cache-Prior routing in decode: lambda %.3f, exact top-%d kept\n", lam, keep); 1972 cp_set[cp_dev] = true; 1973 } 1974 route_publish_kernel<<<T, 512, 0, s>>>(logits, bias, n, k, route_scale, vram, x, dim, idx, w, plan_ptr, req, 1975 vl != 0 ? bias_vl : nullptr, vl, res); 1976 if (req != nullptr) publish_kernel<<<1, 1, 0, s>>>(req, T, seq, na0, na1); 1977} 1978void route_ahead(const float* logits, const float* bias, int n, int m, int T, Req* req, int off, cudaStream_t s) { 1979 if (req != nullptr && m > 0 && T > 0 && n <= 1024 && off + m <= kAhead) 1980 route_ahead_kernel<<<T, 512, 0, s>>>(logits, bias, n, m, req, off); 1981} 1982void wait_seq(const unsigned* seq_ptr, unsigned seq, cudaStream_t s) { wait_seq_kernel<<<1, 32, 0, s>>>(seq_ptr, seq); } 1983 1984// the RAM store's experts for the device (a decode token, window of one): a pick the VRAM table left at 0 whose expert the store holds 1985// (zc_tab[expert] = the slot's device address over PCIe, 0: not) is copied to staging slot i with wide coalesced loads (the PCIe 1986// rate; the expert kernels' own small loads over PCIe ran at a tenth of it), then the plan points at the copy 1987__global__ void zc_copy_kernel(const unsigned long long* __restrict__ plan, const int* __restrict__ idx, 1988 const unsigned long long* __restrict__ zc_tab, uint8_t* __restrict__ stage, size_t stride, size_t bytes) { 1989 const int i = blockIdx.y; 1990 if (plan[i] != 0) return; 1991 const unsigned long long p = zc_tab[idx[i]]; 1992 if (p == 0) return; 1993 const uint4* src = (const uint4*) p; 1994 uint4* dst = (uint4*) (stage + (size_t) i * stride); 1995 const size_t n = bytes / 16; 1996 for (size_t o = (size_t) blockIdx.x * blockDim.x + threadIdx.x; o < n; o += (size_t) gridDim.x * blockDim.x) dst[o] = src[o]; 1997} 1998__global__ void zc_fix_kernel(unsigned long long* __restrict__ plan, const int* __restrict__ idx, const unsigned long long* __restrict__ zc_tab, 1999 int k, uint8_t* __restrict__ stage, size_t stride) { 2000 const int i = threadIdx.x; 2001 if (i >= k || plan[i] != 0) return; 2002 if (zc_tab[idx[i]] != 0) plan[i] = (unsigned long long) (stage + (size_t) i * stride); 2003} 2004void zc_stage(unsigned long long* plan, const int* idx, const unsigned long long* zc_tab, int k, uint8_t* stage, size_t stride, size_t bytes, 2005 cudaStream_t s) { 2006 zc_copy_kernel<<<dim3(64, k), 256, 0, s>>>(plan, idx, zc_tab, stage, stride, bytes); 2007 zc_fix_kernel<<<1, 32, 0, s>>>(plan, idx, zc_tab, k, stage, stride); 2008} 2009 2010void init_pre(float* pre, int T, cudaStream_t s) { init_pre_kernel<<<cdiv(T * 8, 128), 128, 0, s>>>(pre, T); } 2011 2012void embed(const uint16_t* rows, int T, float* h, int dim, int hc, cudaStream_t s) { 2013 embed_kernel<<<dim3(cdiv(dim, kThreads), T), kThreads, 0, s>>>(rows, h, dim, hc); 2014} 2015 2016void scr_repack(const uint8_t* packed, float* master, uint8_t* tail_scratch, uint8_t* dst, 2017 int n, int len, int rd, int fmt, int pos, int step, const float* freqs, cudaStream_t s) { 2018 Finish f; 2019 f.rd = rd; 2020 f.pos = pos; 2021 f.pos_step = step; 2022 f.freqs = freqs; 2023 f.quant = fmt; 2024 f.pdst = tail_scratch; 2025 f.pdst_stride = (long long) kv_row_bytes(fmt, rd); 2026 // Complete quantization groups: stripping the untouched prefix changes neither the rotations nor the reductions. 2027 finish(master, n, rd, rd, f, s); 2028 scr_merge_kernel<<<n, kThreads, 0, s>>>(packed, tail_scratch, dst, len, rd, fmt); 2029} 2030 2031void finish(float* x, int n_vec, int len, long long stride, const Finish& f, cudaStream_t s) { 2032 if (len > kFinMax * kThreads) { 2033 std::fprintf(stderr, "ds4 finish: a vector of %d values is more than %d\n", len, kFinMax * kThreads); 2034 return; 2035 } 2036 if (n_vec <= 0) return; 2037 if (f.pdst != nullptr) { 2038 if (f.quant < kKvFp8 || f.quant > kKvFp4p || len % 32 != 0) { 2039 std::fprintf(stderr, "ds4 finish: packed rows of quant %d, %d values not covered\n", f.quant, len); 2040 return; 2041 } 2042 finish_kernel<true><<<n_vec, kThreads, 0, s>>>(x, len, stride, f); 2043 } else 2044 finish_kernel<false><<<n_vec, kThreads, 0, s>>>(x, len, stride, f); 2045} 2046 2047void hc_mix(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes, cudaStream_t s) { 2048 hc_mix_kernel<<<dim3(n_mix, T), kThreads, 0, s>>>(h, fn, hcdim, eps, mixes); 2049} 2050void hc_mix_split(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes, unsigned* cnt, 2051 const float* scale, const float* base, int hc, int iters, float hc_eps, float* pre, float* post, 2052 float* comb, cudaStream_t s) { 2053 hc_mix_split_kernel<<<dim3(n_mix, T), kThreads, 0, s>>>(h, fn, hcdim, eps, mixes, cnt, scale, base, hc, iters, hc_eps, pre, 2054 post, comb); 2055} 2056void hc_split(const float* mixes, const float* scale, const float* base, int hc, int iters, float hc_eps, int T, 2057 float* pre, float* post, float* comb, cudaStream_t s) { 2058 hc_split_kernel<<<T, 32, 0, s>>>(mixes, scale, base, hc, iters, hc_eps, pre, post, comb); 2059} 2060void hc_pre_norm(const float* h, const float* mix, const float* w, int dim, int hc, int T, float eps, float* x, 2061 cudaStream_t s) { 2062 hc_pre_norm_kernel<<<T, 1024, 0, s>>>(h, mix, w, dim, hc, eps, x); 2063} 2064void hc_post(const float* y, const float* res, const float* post, const float* comb, int dim, int hc, int T, 2065 float* out, cudaStream_t s) { 2066 hc_post_kernel<<<dim3(cdiv(dim * hc, kThreads), T), kThreads, 0, s>>>(y, res, post, comb, dim, hc, out); 2067} 2068 2069void hc_post_inplace(const float* y, float* h, const float* post, const float* comb, int dim, int hc, int T, 2070 cudaStream_t s) { 2071 hc_post_inplace_kernel<<<dim3(cdiv(dim, kThreads), T), kThreads, 0, s>>>(y, h, post, comb, dim, hc); 2072} 2073void hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float* mixes, cudaStream_t s) { 2074 hc_mix_scale_kernel<<<T, kThreads, 0, s>>>(h, hcdim, n_mix, eps, mixes); 2075} 2076void engram_dequant_tok(const uint8_t* src, size_t per, int cols, int T, int hd, float* out, cudaStream_t s, int fmt) { 2077 if (T > 0) engram_dequant_tok_kernel<<<T * cols, kThreads, 0, s>>>(src, per, cols, hd, out, fmt); 2078} 2079void moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos, 2080 cudaStream_t s) { 2081 moe_sort_kernel<false><<<n_vs, kThreads, 0, s>>>(idx, T, k, vs, bounds, row_tok, pos); 2082 bounds_scan_kernel<<<1, 32, 0, s>>>(bounds, n_vs); 2083 moe_sort_kernel<true><<<n_vs, kThreads, 0, s>>>(idx, T, k, vs, bounds, row_tok, pos); 2084} 2085void moe_combine(float* acc, const float* y, const int* pos, const float* w, int T, int k, int r0, int r1, int dim, 2086 cudaStream_t s) { 2087 if (r1 > r0 && T > 0) moe_combine_kernel<<<dim3(cdiv(dim, kThreads), T), kThreads, 0, s>>>(acc, y, pos, w, k, r0, r1, dim); 2088} 2089 2090void gemv_f16(const uint16_t* W, const float* x, int n, int k, int T, float alpha, float* y, cudaStream_t s) { 2091 gemv_f16_kernel<<<dim3(cdiv(n, kThreads / 32), T), kThreads, 0, s>>>(W, x, n, k, alpha, y); 2092} 2093void gemv_f16_rows(const uint16_t* W, const float* x, size_t ldx, int n, int k, int T, float alpha, float* y, size_t ldy, 2094 cudaStream_t s) { 2095 if (T > 0) 2096 gemv_f16_rows_kernel<<<dim3(cdiv(n, kThreads / 32), cdiv(T, kRowsT)), kThreads, 0, s>>>(W, x, ldx, n, k, T, alpha, 2097 y, ldy); 2098} 2099 2100void gemv_f32(const float* W, const float* x, int n, int k, int T, float* y, int ldy, cudaStream_t s) { 2101 if (T > 0) gemv_f32_kernel<<<dim3(cdiv(n, kThreads / 32), T), kThreads, 0, s>>>(W, x, n, k, y, ldy); 2102} 2103 2104void route(const float* logits, const float* bias, int n, int k, int T, float route_scale, int* idx, float* w, 2105 cudaStream_t s, const float* bias_vl, const VlBits* vl, const unsigned long long* vram, const unsigned char* res) { 2106 static const VlBits none = {}; 2107 if (vram != nullptr) { // the prefill bias's lambda, once per device (DS4_CP_PREFILL; 0: exact routing) 2108 static bool set[64] = {}; 2109 int dev = 0; 2110 if (cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64 && !set[dev]) { 2111 const char* e = std::getenv("DS4_CP_PREFILL"); 2112 const char* ek = std::getenv("DS4_CP_PREFILL_KEEP"); 2113 if (ek == nullptr) ek = std::getenv("DS4_CP_KEEP"); 2114 const float lam = e != nullptr ? (float) std::atof(e) : 0.0f; 2115 const int keep = ek != nullptr ? std::atoi(ek) : 3; 2116 cudaMemcpyToSymbolAsync(g_cp_plambda, &lam, sizeof lam, 0, cudaMemcpyHostToDevice, s); 2117 cudaMemcpyToSymbolAsync(g_cp_pkeep, &keep, sizeof keep, 0, cudaMemcpyHostToDevice, s); 2118 cudaStreamSynchronize(s); 2119 if (lam > 0.0f) std::fprintf(stderr, "ds4: Cache-Prior routing in prefill: lambda %.3f, exact top-%d kept\n", lam, keep); 2120 set[dev] = true; 2121 } 2122 } 2123 route_kernel<<<T, 512, 0, s>>>(logits, bias, n, k, route_scale, idx, w, vl != nullptr ? bias_vl : nullptr, 2124 vl != nullptr ? *vl : none, vram, res); 2125} 2126 2127// ---------------------------------------------------------------- the lookahead adapter (DS4_AHEAD_ADAPTER) 2128// out[t][i] += sum_j (x[t] . U[:, j]) V[j][i]: a low-rank correction of the next layer's gate on this layer's FFN input 2129__global__ void lowrank_xu_kernel(const float* __restrict__ x, int D, const float* __restrict__ U, int r, float* tmp) { 2130 const int t = blockIdx.x, j = blockIdx.y; 2131 float acc = 0.0f; 2132 for (int e = threadIdx.x; e < D; e += blockDim.x) acc += x[(size_t) t * D + e] * U[(size_t) e * r + j]; 2133 __shared__ float red[256]; 2134 red[threadIdx.x] = acc; 2135 __syncthreads(); 2136 for (int w = blockDim.x / 2; w > 0; w >>= 1) { 2137 if ((int) threadIdx.x < w) red[threadIdx.x] += red[threadIdx.x + w]; 2138 __syncthreads(); 2139 } 2140 if (threadIdx.x == 0) tmp[(size_t) t * r + j] = red[0]; 2141} 2142__global__ void lowrank_v_kernel(const float* __restrict__ tmp, const float* __restrict__ V, int r, int n, float* out, int ld) { 2143 const int t = blockIdx.x; 2144 for (int i = threadIdx.x; i < n; i += blockDim.x) { 2145 float acc = 0.0f; 2146 for (int j = 0; j < r; ++j) acc += tmp[(size_t) t * r + j] * V[(size_t) j * n + i]; 2147 out[(size_t) t * ld + i] += acc; 2148 } 2149} 2150void lowrank_add(const float* x, int D, int T, const float* U, const float* V, int r, int n, float* out, int ld, float* tmp, 2151 cudaStream_t s) { 2152 if (T <= 0 || r <= 0) return; 2153 lowrank_xu_kernel<<<dim3(T, r), 256, 0, s>>>(x, D, U, r, tmp); 2154 lowrank_v_kernel<<<T, 512, 0, s>>>(tmp, V, r, n, out, ld); 2155} 2156 2157void swiglu(const float* g, const float* u, int n, float lim, float* h, cudaStream_t s) { 2158 if (n > 0) swiglu_kernel<<<cdiv(n, kThreads), kThreads, 0, s>>>(g, u, n, lim, h); 2159} 2160 2161void compress_win(const float* kv, const float* score, float* kv_state, float* score_state, int ratio, int p0, int T, 2162 int d, const float* w, float eps, float* latent, cudaStream_t s) { 2163 compress_kernel<<<1, 512, 0, s>>>(kv, score, kv_state, score_state, ratio, p0, T, d, w, eps, latent); 2164} 2165 2166void index_score(const float* q, const float* w, const void* k, int heads, int hd, int T, int n, const int* cand, 2167 int cand_stride, int blk, const Rows& lim, float* out, long long out_stride, cudaStream_t s, 2168 int kfmt) { 2169 if (hd != 128 || heads > 32 || (kfmt != kKvFp4p && kfmt != kKvBf16)) { 2170 std::fprintf(stderr, "ds4 index_score: %d heads of %d (keys %d) not covered\n", heads, hd, kfmt); 2171 return; 2172 } 2173 if (n <= 0) return; 2174 const size_t smem = (size_t) (heads * hd + heads) * sizeof(float); 2175 const dim3 grid(cdiv(n, kThreads), T); 2176 if (kfmt == kKvFp4p) 2177 index_score_kernel<128, kKvFp4p><<<grid, kThreads, smem, s>>>(q, w, (const uint8_t*) k, heads, n, cand, 2178 cand_stride, blk, lim, out, out_stride); 2179 else 2180 index_score_kernel<128, kKvBf16><<<grid, kThreads, smem, s>>>(q, w, (const uint8_t*) k, heads, n, cand, 2181 cand_stride, blk, lim, out, out_stride); 2182} 2183 2184void topk(const float* vals, long long stride, int T, const Rows& r, const int* cand, int cand_stride, int blk, 2185 int* out, int out_stride, cudaStream_t s) { 2186 topk_kernel<<<T, 1024, 0, s>>>(vals, stride, r, cand, cand_stride, blk, out, out_stride); 2187} 2188 2189void cand_blocks(const float* score, long long stride, int T, const Rows& r, int blk, float* bm, long long bm_stride, 2190 int* out, int out_stride, cudaStream_t s) { 2191 int nb_max = 1; 2192 Rows rb = r; 2193 if (r.gen != 0) { // (a chunk: the widest query's blocks, made on the device per query) 2194 rb.gen = 4; 2195 rb.blk = blk; 2196 nb_max = cdiv((int) ((r.p0 + T) / r.R), blk); 2197 } else 2198 for (int t = 0; t < T; ++t) { 2199 rb.n[t] = cdiv(r.n[t], blk); 2200 rb.k[t] = r.k[t]; 2201 nb_max = rb.n[t] > nb_max ? rb.n[t] : nb_max; 2202 } 2203 block_max_kernel<<<dim3(cdiv(nb_max, kThreads), T), kThreads, 0, s>>>(score, stride, r, blk, bm, bm_stride); 2204 topk(bm, bm_stride, T, rb, nullptr, 0, 1, out, out_stride, s); 2205} 2206 2207// the multiprocessors of the current device (cached a device) 2208static int sm_count() { 2209 static std::atomic<int> cached[64]; 2210 int dev = 0; 2211 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) dev = 0; 2212 int v = cached[dev].load(std::memory_order_relaxed); 2213 if (v <= 0) { 2214 if (cudaDeviceGetAttribute(&v, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess || v <= 0) v = 1; 2215 cached[dev].store(v, std::memory_order_relaxed); 2216 } 2217 return v; 2218} 2219 2220void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int* sel, int sel_stride, 2221 const AttnRows& a, const float* sink, int heads, int d, int T, float scale, float* out, cudaStream_t s, 2222 int ckv_fmt, int heads_per_block, const AttnScratch* scr) { 2223 if (d != 512 || (ckv_fmt != kKvFp4 && ckv_fmt != kKvBf16)) { 2224 std::fprintf(stderr, "ds4 sparse_attn: head dim %d (rows %d) not covered\n", d, ckv_fmt); 2225 return; 2226 } 2227 if (ckv_fmt == kKvBf16) { 2228 sparse_attn_kernel<false><<<dim3(heads, T), kThreads, 0, s>>>(q, win, (const uint16_t*) ckv, sel, sel_stride, a, 2229 sink, heads, d, scale, out); 2230 return; 2231 } 2232 // a decode step / short verify window of packed rows: the split-KV kernel (Strata's CUDA lab, ds4_attn_split.cuh; 2.9x at 2233 // one query on an A4000). The same inputs; the merge sums the chunks in another order, so the bits differ in the last 2234 // place (4e-7 against a double reference). DS4_ATTN_SPLIT=1 turns it on (off by default: no measurable decode gain on the R9700 box, the decode is bound elsewhere). 2235 if (ckv_fmt == kKvFp4 && a.gen == 0 && T >= 1 && T <= kSplitMaxT && heads % kSplitG == 0 && split_enabled()) { 2236 int total_max = 0; 2237 for (int t = 0; t < T; ++t) total_max = std::max(total_max, a.nwin[t] + a.nsel[t]); 2238 if (total_max > 0 && total_max <= kSplitCap * kSplitR) { 2239 const attnsplit::AttnSplitScratch sc = split_scratch(s, heads); 2240 if (sc.part != nullptr) { 2241 attnsplit::sparse_attn_split<kSplitG, kSplitR>(q, win, (const uint8_t*) ckv, kv_row_bytes(kKvFp4, d), sel, 2242 sel_stride, a, sink, heads, T, scale, out, sc, total_max, s); 2243 return; 2244 } 2245 } 2246 } 2247 // a few queries (a decode step, a short window): their selected rows decoded once a query into the scratch, then 2248 // the BF16 rows' kernel itself (heads_per_block -1: this way at any T) 2249 const bool few = heads_per_block == -1 || (heads_per_block == 0 && T <= kAttnScratchT); 2250 if (few && scr != nullptr && scr->rows != nullptr && T <= scr->max_t && sel_stride <= scr->cap) { 2251 unpack_sel_kernel<<<dim3(cdiv(sel_stride, kStage), T), kThreads, 0, s>>>((const uint8_t*) ckv, sel, sel_stride, a, 2252 scr->cap, scr->rows); 2253#if !defined(STRATA_USE_HIP) 2254 if (T == 1) // (V100: the loads ahead pay for the decode's kernel at one query, not at more) 2255 sparse_attn_kernel<true, 8><<<dim3(heads, T), kThreads, 0, s>>>(q, win, scr->rows, nullptr, scr->cap, a, sink, 2256 heads, d, scale, out); 2257 else 2258#endif 2259 sparse_attn_kernel<true, 0><<<dim3(heads, T), kThreads, 0, s>>>(q, win, scr->rows, nullptr, scr->cap, a, sink, 2260 heads, d, scale, out); 2261 return; 2262 } 2263 // packed rows: as many heads a block as still leaves two blocks a multiprocessor (a decoded row serves them all) 2264 int G = heads_per_block; 2265 if (G != 1 && G != 2 && G != 4 && G != 8) { 2266 G = 8; 2267 while (G > 1 && (heads % G != 0 || (heads / G) * T < 2 * sm_count())) G /= 2; 2268 } 2269 if (heads % G != 0) G = 1; 2270 const dim3 grid(heads / G, T); 2271 const uint8_t* c = (const uint8_t*) ckv; 2272 if (G == 8) sparse_attn_packed_kernel<8><<<grid, kThreads, 0, s>>>(q, win, c, sel, sel_stride, a, sink, heads, scale, out); 2273 else if (G == 4) sparse_attn_packed_kernel<4><<<grid, kThreads, 0, s>>>(q, win, c, sel, sel_stride, a, sink, heads, scale, out); 2274 else if (G == 2) sparse_attn_packed_kernel<2><<<grid, kThreads, 0, s>>>(q, win, c, sel, sel_stride, a, sink, heads, scale, out); 2275 else sparse_attn_packed_kernel<1><<<grid, kThreads, 0, s>>>(q, win, c, sel, sel_stride, a, sink, heads, scale, out); 2276} 2277 2278void ring_to_ext(const uint8_t* ring, uint16_t* ext, int64_t p0, int n, int d, cudaStream_t s) { 2279 ring_to_ext_kernel<<<n, kThreads, 0, s>>>(ring, ext, (long long) p0, n, d); 2280} 2281void ext_to_ring(const uint16_t* ext, uint8_t* ring, int64_t p0, int n, int T, int d, cudaStream_t s, uint8_t* backup) { 2282 if (d % 32 != 0) { 2283 std::fprintf(stderr, "ds4 ext_to_ring: row of %d not covered\n", d); 2284 return; 2285 } 2286 ext_to_ring_kernel<<<T, kThreads, 0, s>>>(ext, ring, (long long) p0, n, T, d, backup); 2287} 2288void ring_restore(uint8_t* ring, const uint8_t* backup, int64_t p0, int n, int keep, int T, int d, cudaStream_t s) { 2289 if (T > keep) 2290 ring_restore_kernel<<<T - keep, kThreads, 0, s>>>(ring, backup, (long long) p0, n, keep, kv_row_bytes(kKvFp8, d)); 2291} 2292void ring_restore_batch(const RingBatch& b, int64_t p0, int n, int keep, int T, int d, cudaStream_t s) { 2293 if (T > keep && b.n > 0) 2294 ring_restore_batch_kernel<<<dim3(T - keep, b.n), kThreads, 0, s>>>(b, (long long) p0, n, keep, 2295 kv_row_bytes(kKvFp8, d)); 2296} 2297void hc_mean(const float* h, int T, int hc, int dim, float* out, long long out_stride, cudaStream_t s) { 2298 hc_mean_kernel<<<dim3(cdiv(dim, kThreads), T), kThreads, 0, s>>>(h, hc, dim, out, out_stride); 2299} 2300void iota_rows(int* out, int T, int n, int stride, cudaStream_t s) { iota_rows_kernel<<<T, 64, 0, s>>>(out, n, stride); } 2301void markov_add(float* logits, const uint16_t* E, const uint16_t* H, const int* tok, int V, int R, cudaStream_t s) { 2302 markov_kernel<<<cdiv(V, kThreads / 32), kThreads, (size_t) R * sizeof(float), s>>>(logits, E, H, tok, V, R); 2303} 2304void markov_share(float* logits, const uint16_t* H, const uint16_t* erow, int vn, int R, cudaStream_t s) { 2305 markov_share_kernel<<<cdiv(vn, kThreads / 32), kThreads, (size_t) R * sizeof(float), s>>>(logits, H, erow, vn, R); 2306} 2307void argmax_share(const float* row, int vn, int v0, unsigned* slot, unsigned seq, cudaStream_t s) { 2308 argmax_share_kernel<<<1, 1024, 0, s>>>(row, vn, v0, slot, seq); 2309} 2310void markov_pick(const unsigned* slots, int nm, unsigned seq, int* tok, const uint16_t* E, uint16_t* erow, int R, 2311 cudaStream_t s) { 2312 markov_pick_kernel<<<1, 256, 0, s>>>(slots, nm, seq, tok, E, erow, R); 2313} 2314void confidence(const float* x, const uint16_t* E, const int* tok, const float* w, int T, int dim, int R, float* out, 2315 cudaStream_t s) { 2316 confidence_kernel<<<T, 1024, 0, s>>>(x, E, tok, w, dim, R, out); 2317} 2318 2319void engram_dequant(const uint8_t* rows, const uint8_t* scales, int n, int hd, float* out, cudaStream_t s, int fmt) { 2320 engram_dequant_kernel<<<n, kThreads, 0, s>>>(rows, scales, hd, out, fmt); 2321} 2322 2323void engram_gate(float* h, const float* kv, const float* w, int hc, int dim, int T, float eps, cudaStream_t s) { 2324 engram_gate_kernel<<<dim3(hc, T), 1024, 0, s>>>(h, kv, w, hc, dim, eps); 2325} 2326 2327void gather_rows(const float* x, const Gather& g, int n, int cols, float* out, cudaStream_t s) { 2328 if (n > 0) gather_kernel<<<dim3(cdiv(cols, kThreads), n), kThreads, 0, s>>>(x, g, cols, out); 2329} 2330 2331void combine(const float* ed, const float* cpu, const float* sh, const Combine& c, int T, int dim, float* out, 2332 cudaStream_t s) { 2333 combine_kernel<<<dim3(cdiv(dim, kThreads), T), kThreads, 0, s>>>(ed, cpu, sh, c, dim, out); 2334} 2335 2336void xfer_put(const Xfer& x, unsigned* flag, unsigned seq, unsigned* cnt, cudaStream_t s) { 2337 size_t total = 0; 2338 for (int i = 0; i < x.n; ++i) total += x.bytes[i] / 16; 2339 const int blocks = (int) std::max<size_t>(1, std::min<size_t>(64, (total + kThreads - 1) / kThreads)); 2340 xfer_put_kernel<<<blocks, kThreads, 0, s>>>(x, flag, seq, cnt); 2341 // (another GPU, or the host, waits for this flag: on Windows the put must not sit in the queue - #303: two RTX 3080s 2342 // hung at the first hand-off, the receiver spinning on a flag whose writer had never been submitted) 2343 win_submit(s); 2344} 2345void win_submit(cudaStream_t s) { 2346#if defined(_WIN32) 2347 static const bool on = [] { 2348 const char* v = std::getenv("DS4_WIN_SUBMIT"); 2349 return v == nullptr || std::atoi(v) != 0; 2350 }(); 2351 if (on) { 2352 (void) cudaStreamQuery(s); 2353 (void) cudaGetLastError(); 2354 } 2355#else 2356 (void) s; 2357#endif 2358} 2359void xfer_get(const Xfer& x, const unsigned* flag, unsigned seq, cudaStream_t s) { 2360 size_t total = 0; 2361 for (int i = 0; i < x.n; ++i) total += x.bytes[i] / 16; 2362 const int blocks = (int) std::max<size_t>(1, std::min<size_t>(64, (total + kThreads - 1) / kThreads)); 2363 xfer_get_kernel<<<blocks, kThreads, 0, s>>>(x, flag, seq); 2364} 2365void wait_flags(const unsigned* flags, int n, int stride, unsigned seq, cudaStream_t s) { 2366 if (n > 0) wait_flags_kernel<<<1, 32, 0, s>>>(flags, n, stride, seq); 2367} 2368void set_flag(unsigned* flag, unsigned v, cudaStream_t s) { 2369 set_flag_kernel<<<1, 1, 0, s>>>(flag, v); 2370 win_submit(s); // (the writer on another GPU waits for this acknowledgement before its next put - #384) 2371} 2372void allreduce(float* x, int n, const ArGroup& a, int mi, unsigned seq, unsigned* cnt, cudaStream_t s) { 2373 const int slot = (int) (seq % (unsigned) a.slots); 2374 if (a.nm > 2 && a.sums != nullptr && a.bflags != nullptr) { // (the reduce-scatter: ar_rs_kernel) 2375 static const bool f16 = [] { 2376 const char* e = std::getenv("DS4_AR_F16"); 2377 return e != nullptr && std::atoi(e) != 0; // opt-in: no gain measured on 4x R9700 (21.8 vs 21.9 tok/s) // (on unless DS4_AR_F16=0) 2378 }(); 2379 const int n4 = n / 4; 2380 const int blocks = std::max(1, std::min(kArBlocks, cdiv(n4, kThreads))); 2381 if (f16) 2382 ar_rs16_kernel<<<blocks, kThreads, 0, s>>>(x, n4, a.data, a.sums, a.stride, a.bflags, a.nm, mi, slot, a.slots, seq); 2383 else 2384 ar_rs_kernel<<<blocks, kThreads, 0, s>>>(x, n4, a.data, a.sums, a.stride, a.bflags, a.nm, mi, slot, a.slots, seq); 2385 return; 2386 } 2387 Xfer xp; 2388 xp.n = 1; 2389 xp.src[0] = x; 2390 xp.dst[0] = a.data + ((size_t) mi * a.slots + slot) * a.stride; 2391 xp.bytes[0] = (size_t) n * 4; 2392 xfer_put(xp, a.flags + ((size_t) mi * a.slots + slot) * 32, seq, cnt, s); 2393 const int n4 = n / 4; 2394 const int blocks = std::max(1, std::min(64, cdiv(n4, kThreads))); 2395 ar_sum_kernel<<<blocks, kThreads, 0, s>>>(x, n4, a.data, a.stride, a.flags, a.nm, mi, slot, a.slots, seq); 2396} 2397 2398} // namespace strata::ds4