okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8ac8ce32e
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/kernels/cuda/exl3.cu - the EXL3 device kernels (the format: include/strata/kernels/exl3.hpp). 4// 5// The codebooks and the trellis window arithmetic follow exllamav3 (MIT, turboderp - exllamav3_ext/quant/ 6// codebook.cuh, exl3_dq.cuh, hadamard_inner.cuh), and so does decoding a tile straight into tensor-core fragments 7// (its small-m GEMV and GEMM); the kernels around them are shaped for this engine's decode: 8// 9// * a block owns 128 outputs (8 tiles - exactly one output rotation block) over a slice of at most 4096 inputs; 10// warp w takes tile column w through every 16-row slice, decoding 8 weights per lane (one fragment: 2 columns x 11// 4 rows) - on sm_80 and later straight into one mma.m16n8k16 a tile with up to 8 activations as its columns, 12// F32 accumulation; before sm_80 (and on HIP) F32 FMAs on the CUDA cores; 13// * the input rotation runs per block, 128 inputs at a time (F32 or q8_1 in, FP16 in shared memory), so the 14// engine's activation buffers are used as they are; the next 128 inputs' tile words load while these decode; 15// * a matrix with more than 4096 inputs, or too few output blocks to fill the device, splits its inputs over 16// blocks: the partial sums go to a per-stream scratch and the LAST block of an output block adds them up in 17// split order (deterministic) and runs the output rotation. 18// 19// NVIDIA GPUs before sm_80 (V100, T4, RTX 20) decode with v1.1.8's kernels instead (exl3_legacy.cu, use_legacy 20// below): this file's CUDA-core fallback was slower there (a V100 with EXL3-3.05bpw: decode 4.9 -> 4.4 tok/s). The 21// prompt path below is this file's on every GPU. 22#include "strata/dsv41/exl3.hpp" 23 24#include <cuda_fp16.h> 25#include <cuda_runtime.h> 26 27#include <algorithm> 28#include <atomic> 29#include <cstdio> 30#include <cstdlib> 31#include <cstring> 32#include <map> 33#include <mutex> 34#include <utility> 35 36#if !defined(STRATA_USE_HIP) 37namespace strata::dsv41k::exl3::legacy { // exl3_legacy.cu: v1.1.8's decode kernels 38int launch_errors(); 39bool prepare(cudaStream_t s); 40bool several_ok(); 41bool mv(const MvJob* jobs, int n, cudaStream_t s); 42void moe_gate_up(const MoeArgs& a, const float* x, float* h, cudaStream_t s); 43void moe_down(const MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s); 44bool win_experts(const WinArgs& a, cudaStream_t s); 45} // namespace strata::dsv41k::exl3::legacy 46#define EXL3_LEGACY(call) \ 47 if (use_legacy()) return legacy::call 48#else 49#define EXL3_LEGACY(call) (void) 0 50#endif 51 52namespace strata::dsv41k::exl3 { 53namespace { 54 55constexpr int kThreads = 256, kWarps = 8; 56constexpr int kCols = 128; // outputs per block: 8 tiles, one rotation block 57constexpr int kMaxKR = 4096; // inputs per block at most (mv's split) 58// a routed expert's widths at most (moe_* / win_*: a block streams its inputs through block_gemv's two 128-value chunk 59// buffers, so the shared memory does not grow with them; DeepSeek-V4.1's n_embd is 5120) 60constexpr int kMaxMoeK = 8192; 61constexpr float kHad = 0.088388347648f; // 1 / sqrt(128) 62 63struct Q81 { // the engine's q8_1 block (ggml block_q8_1): d, sum, 32 int8 64 __half2 ds; 65 int8_t qs[32]; 66}; 67 68std::atomic<int> g_launch_errors{0}; 69thread_local const int* g_skip = nullptr; // set_skip: the calling thread's flag (nullptr: none) 70void launch_check(const char* what) { 71 const cudaError_t e = cudaGetLastError(); 72 if (e != cudaSuccess) { 73 std::fprintf(stderr, "exl3 %s: %s\n", what, cudaGetErrorString(e)); 74 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 75 } 76} 77 78// ---------------------------------------------------------------- the codebooks 79__device__ __forceinline__ uint32_t bytesum_plus(uint32_t x, uint32_t acc) { 80#if defined(STRATA_USE_HIP) 81 return acc + (x & 0xffu) + ((x >> 8) & 0xffu) + ((x >> 16) & 0xffu) + (x >> 24); 82#else 83 return __dp4a(x, 0x01010101u, acc); 84#endif 85} 86 87// two states -> two values, FP16 arithmetic as exllamav3's decode_3inst_2 (the tensor-core kernels take the half2) 88template <int cb> 89__device__ __forceinline__ __half2 decode2h(uint32_t s0, uint32_t s1) { 90 if constexpr (cb == 2) { 91 const uint32_t a = bytesum_plus(s0 * 0x83DCD12Du, 0x6400u); 92 const uint32_t b = bytesum_plus(s1 * 0x83DCD12Du, 0x6400u); 93 const __half2 h = __halves2half2(__ushort_as_half((unsigned short) a), __ushort_as_half((unsigned short) b)); 94 return __hfma2(h, __half2half2(__ushort_as_half(0x1eee)), __half2half2(__ushort_as_half(0xc931))); 95 } else { 96 uint32_t x0 = cb == 1 ? s0 * 0xCBAC1FEDu : s0 * 89226354u + 64248484u; 97 uint32_t x1 = cb == 1 ? s1 * 0xCBAC1FEDu : s1 * 89226354u + 64248484u; 98 x0 = (x0 & 0x8fff8fffu) ^ 0x3b603b60u; 99 x1 = (x1 & 0x8fff8fffu) ^ 0x3b603b60u; 100 const __half2 lo = __halves2half2(__ushort_as_half((unsigned short) (x0 & 0xffffu)), 101 __ushort_as_half((unsigned short) (x1 & 0xffffu))); 102 const __half2 hi = __halves2half2(__ushort_as_half((unsigned short) (x0 >> 16)), 103 __ushort_as_half((unsigned short) (x1 >> 16))); 104 return __hadd2(lo, hi); 105 } 106} 107template <int cb> 108__device__ __forceinline__ float2 decode2(uint32_t s0, uint32_t s1) { 109 return __half22float2(decode2h<cb>(s0, s1)); 110} 111 112__device__ __forceinline__ uint32_t h2u(__half2 h) { return *reinterpret_cast<uint32_t*>(&h); } 113__device__ __forceinline__ __half2 u2h(uint32_t u) { return *reinterpret_cast<__half2*>(&u); } 114 115// (hi : lo) >> s, the low 32 bits 116__device__ __forceinline__ uint32_t fsh(uint32_t lo, uint32_t hi, int s) { 117 return (uint32_t) ((((uint64_t) hi << 32) | (uint64_t) lo) >> s); 118} 119 120// Step p's state is the 16-bit window ending at bit (p + 1) K of the tile's MSB-first bit stream (w: its 8 K words), 121// wrapping around the tile. A lane decodes its 8 consecutive steps lane * 8 .. + 7 together, the windows of a group 122// of steps cut from one or two words with funnel shifts - exllamav3's grouping per K (exl3_dq.cuh: dq8_aligned_*bits, 123// dq8, dq4, dq2x2), which the steps' fixed offsets keep within two words. f[i]: steps 2i, 2i + 1 as FP16 values. 124// Step lane * 8 + j sits at tile row (lane & 3) * 2 + (j & 1) + 8 (j >> 1 & 1), column (lane >> 2) + 8 (j >> 2). 125template <int cb> 126__device__ __forceinline__ void decode_states(const uint32_t (&s)[8], uint32_t (&f)[4]) { 127#pragma unroll 128 for (int i = 0; i < 4; ++i) f[i] = h2u(decode2h<cb>(s[2 * i] & 0xffffu, s[2 * i + 1] & 0xffffu)); 129} 130// K = 4: the lane's steps end in its own word b (word lane), the first three reach into a (word lane - 1) 131__device__ __forceinline__ void states4(uint32_t a, uint32_t b, uint32_t (&s)[8]) { 132 const uint32_t x = fsh(b, a, 20); 133 s[0] = x >> 8; 134 s[1] = x >> 4; 135 s[2] = x; 136 s[3] = b >> 16; 137 s[4] = b >> 12; 138 s[5] = b >> 8; 139 s[6] = b >> 4; 140 s[7] = b; 141} 142// step p .. p + G - 1's windows (G = 4 or 2) from the two words that hold them 143template <int K, int G> 144__device__ __forceinline__ void states_group(const uint32_t* w, int p, uint32_t* s) { 145 constexpr int NW = 8 * K; 146 const int b0 = (p + 257) * K - 16, b2 = b0 + (G - 1) * K + 16; 147 const int i0 = b0 >> 5, i2 = (b2 - 1) >> 5, s2 = ((i2 + 1) << 5) - b2; 148 const uint32_t a = w[i0 % NW], b = w[i2 % NW]; 149#pragma unroll 150 for (int j = 0; j < G; ++j) s[G - 1 - j] = fsh(b, a, s2 + j * K); 151} 152template <int K, int cb> 153__device__ __forceinline__ void frag8(const uint32_t* w, int lane, uint32_t (&f)[4]) { 154 const int p = lane * 8; 155 uint32_t s[8]; 156 if constexpr (K == 4) { 157 states4(w[(lane + 31) & 31], w[lane], s); 158 } else if constexpr (K == 1 || K == 2) { 159 // the 8 windows overlap in one 32-bit window: steps p + j end 8 - 1 - j K bits apart 160 constexpr int NW = 8 * K, per = 32 / (8 * K); // lanes per word 161 const int i1 = lane / per, i0 = (i1 + NW - 1) % NW; 162 const uint32_t b = fsh(w[i1], w[i0], (per - 1 - lane % per) * 8 * K); 163#pragma unroll 164 for (int j = 0; j < 8; ++j) s[j] = b >> ((7 - j) * K); 165 } else if constexpr (K == 3) { 166 // all 8 windows within two words: two funnel shifts, the rest by shifting 167 constexpr int NW = 24; 168 const int b1 = (p + 257) * 3, b0 = b1 - 16, b2 = b1 + 21; 169 const int i0 = b0 >> 5, i2 = (b2 - 1) >> 5, s2 = ((i2 + 1) << 5) - b2; 170 const uint32_t a = w[i0 % NW], b = w[i2 % NW]; 171 const uint32_t hi = fsh(b, a, s2), lo = fsh(b, a, s2 + 12); 172#pragma unroll 173 for (int j = 0; j < 4; ++j) { 174 s[7 - j] = hi >> (3 * j); 175 s[3 - j] = lo >> (3 * j); 176 } 177 } else if constexpr (K == 7) { 178#pragma unroll 179 for (int g = 0; g < 4; ++g) states_group<K, 2>(w, p + 2 * g, s + 2 * g); 180 } else { // 5, 6, 8 181 states_group<K, 4>(w, p, s); 182 states_group<K, 4>(w, p + 4, s + 4); 183 } 184 decode_states<cb>(s, f); 185} 186 187// the lane's 8 steps as F32: v[j] = step lane * 8 + j 188template <int K, int cb> 189__device__ __forceinline__ void decode8(const uint32_t* w, int lane, float* v) { 190 uint32_t f[4]; 191 frag8<K, cb>(w, lane, f); 192#pragma unroll 193 for (int i = 0; i < 4; ++i) { 194 const float2 d = __half22float2(u2h(f[i])); 195 v[2 * i] = d.x; 196 v[2 * i + 1] = d.y; 197 } 198} 199 200// ---------------------------------------------------------------- the rotation 201// the 128-point transform of the 128 values a warp holds 4 per lane (value lane * 4 + i), over sqrt(128) 202__device__ __forceinline__ void had128(float* v, int lane) { 203 const float s0 = v[0] + v[1], d0 = v[0] - v[1], s1 = v[2] + v[3], d1 = v[2] - v[3]; 204 v[0] = s0 + s1; 205 v[1] = d0 + d1; 206 v[2] = s0 - s1; 207 v[3] = d0 - d1; 208#pragma unroll 209 for (int m = 1; m < 32; m <<= 1) { 210#pragma unroll 211 for (int i = 0; i < 4; ++i) { 212 const float o = __shfl_xor_sync(0xffffffffu, v[i], m); 213 v[i] = (lane & m) ? o - v[i] : v[i] + o; 214 } 215 } 216#pragma unroll 217 for (int i = 0; i < 4; ++i) v[i] *= kHad; 218} 219 220__device__ __forceinline__ float h2f(uint16_t b) { return __half2float(__ushort_as_half(b)); } 221 222// the activation a warp rotates into its block's FP16 chunks: F32 (f) or the engine's q8_1 blocks (q) 223struct Xin { 224 const float* f = nullptr; 225 const Q81* q = nullptr; 226}; 227 228// the 128-input chunk of x from k0 on: the lane's 4 values and their suh ... 229__device__ __forceinline__ void chunk_load(const Xin& x, const uint16_t* __restrict__ suh, int k0, int lane, 230 float (&v)[4], float (&s)[4]) { 231 const int base = k0 + lane * 4; 232 if (x.f != nullptr) { 233#pragma unroll 234 for (int i = 0; i < 4; ++i) v[i] = x.f[base + i]; 235 } else { 236 const Q81* b = x.q + base / 32; 237 const float d = __low2float(b->ds); 238#pragma unroll 239 for (int i = 0; i < 4; ++i) v[i] = d * (float) b->qs[base % 32 + i]; 240 } 241#pragma unroll 242 for (int i = 0; i < 4; ++i) s[i] = h2f(suh[base + i]); 243} 244// ... and H(x * suh) of the chunk, FP16, into dst[0..127] 245__device__ __forceinline__ void chunk_store(float (&v)[4], const float (&s)[4], int lane, __half* dst) { 246#pragma unroll 247 for (int i = 0; i < 4; ++i) v[i] *= s[i]; 248 had128(v, lane); 249 __half2* d = reinterpret_cast<__half2*>(dst + lane * 4); 250 d[0] = __floats2half2_rn(v[0], v[1]); 251 d[1] = __floats2half2_rn(v[2], v[3]); 252} 253 254// ---------------------------------------------------------------- the block GEMV 255// A block owns 128 outputs - 8 tiles, warp w the tile column tc0 + w through all of the block's inputs [k0, k1) - for 256// nc <= kTok activations at once. Per 128-input chunk, warp c (< nc) scales activation c's chunk by suh and rotates 257// it into FP16 (xb, two buffers), then each warp decodes its tile of each of the chunk's 8 slices and multiplies it 258// with every activation: on sm_80 and later as one mma.m16n8k16 a tile (the decoded tile is the A operand - a lane's 8 259// steps are its A fragment - and the activations are the B operand's columns, as exllamav3's small-m GEMV and its 260// tensor-core GEMM decode tiles straight into fragments), F32 accumulation; elsewhere on the CUDA cores, in F32. An 261// activation's sums do not depend on the other columns, so a window's token gets the token path's bits. The next 262// chunk's tile words are loaded while this one is decoded. out[c * 128 + i]: activation c's sum for output i. Ends 263// with a __syncthreads (out complete). 264constexpr int kTok = 8; // activations a block takes at once (the MMA's n) 265 266#if !defined(STRATA_USE_HIP) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 267#define EXL3_TC 1 268#endif 269 270#if !defined(EXL3_TC) 271// a lane's 4 weights of one column times the activation's 4 inputs, added to a (the CUDA-core product) 272__device__ __forceinline__ float dot4_acc(float a, const float* v, float x0, float x1, float x2, float x3) { 273 return __fadd_rn(a, __fmaf_rn(v[3], x3, __fmaf_rn(v[2], x2, __fmaf_rn(v[1], x1, __fmul_rn(v[0], x0))))); 274} 275#else 276__device__ __forceinline__ void mma_f32(float (&c)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, 277 uint32_t b0, uint32_t b1) { 278 asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " 279 "{%0,%1,%2,%3};\n" 280 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) 281 : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); 282} 283#endif 284 285// a tile's words, and a lane's share of them (word lane + 32 r) 286template <int K> 287struct Words { 288 static constexpr int W = 8 * K, R = (W + 31) / 32; 289}; 290 291// the warp's tile of each of a chunk's 8 slices (slice s at tile0 + s sstride) 292template <int K> 293__device__ __forceinline__ void load_tiles(const uint32_t* __restrict__ tile0, size_t sstride, int lane, 294 uint32_t (&w)[8][Words<K>::R]) { 295 constexpr int W = Words<K>::W, R = Words<K>::R; 296#pragma unroll 297 for (int s = 0; s < 8; ++s) 298#pragma unroll 299 for (int r = 0; r < R; ++r) { 300 const int i = lane + 32 * r; 301 w[s][r] = (W % 32 == 0 || i < W) ? __ldg(tile0 + (size_t) s * sstride + i) : 0u; 302 } 303} 304 305// one slice's fragment from the lane's words: K = 4 straight from the registers (the lane's steps end in its own word, 306// the first three reach into the previous lane's), other K through the warp's stage (8 K words) 307template <int K, int cb> 308__device__ __forceinline__ void slice_frags(const uint32_t (&w)[Words<K>::R], uint32_t* st, int lane, uint32_t (&f)[4]) { 309 if constexpr (K == 4) { 310 uint32_t s[8]; 311 states4(__shfl_sync(0xffffffffu, w[0], (lane + 31) & 31), w[0], s); 312 decode_states<cb>(s, f); 313 } else { 314 constexpr int W = Words<K>::W, R = Words<K>::R; 315 __syncwarp(); 316#pragma unroll 317 for (int r = 0; r < R; ++r) 318 if (W % 32 == 0 || lane + 32 * r < W) st[lane + 32 * r] = w[r]; 319 __syncwarp(); 320 frag8<K, cb>(st, lane, f); 321 } 322} 323 324// the blocks an SM keeps of the block_gemv kernels (their registers), as measured on an RTX 3090 and an RTX 5060 Ti: 325// the routed experts four at K <= 4 (a token's 8 experts, 256 blocks, are one wave on 82 SMs), two at wider codes; 326// mv two, three at K > 4 on sm_80 .. sm_90 (sm_120 spills at the 80 registers that takes). Before sm_80 (the CUDA 327// cores' product, more registers) two; HIP reads the second bound differently and keeps its default. 328#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 329template <int K> 330constexpr int kMinBlocksX = K <= 4 ? 4 : 2; 331#else 332template <int K> 333constexpr int kMinBlocksX = 2; 334#endif 335#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && __CUDA_ARCH__ < 1000 336template <int K> 337constexpr int kMinBlocksMv = K <= 4 ? 2 : 3; 338#else 339template <int K> 340constexpr int kMinBlocksMv = 2; 341#endif 342#if defined(STRATA_USE_HIP) 343#define EXL3_BOUNDS(n) __launch_bounds__(kThreads) 344#else 345#define EXL3_BOUNDS(n) __launch_bounds__(kThreads, n) 346#endif 347 348// the shared memory of a block_gemv block 349template <int K> 350struct BlockSmem { 351 __half xb[2 * kTok * kCols]; // two chunk buffers, kTok activations each 352 uint32_t stage[kWarps * 8 * K]; // a tile per warp (K != 4) 353 float out[kTok * kCols]; 354}; 355 356template <int K, int cb> 357__device__ void block_gemv(const uint32_t* __restrict__ tr, int ld, int tc0, int k0, int k1, const Xin& x, 358 const uint16_t* __restrict__ suh, int nc, BlockSmem<K>& sm) { 359 constexpr int W = Words<K>::W, R = Words<K>::R; 360 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, g = lane >> 2, t = lane & 3; 361 const size_t sstride = (size_t) ld * W; 362 const uint32_t* tile = tr + ((size_t) (k0 / 16) * ld + tc0 + warp) * W; 363 uint32_t* st = sm.stage + warp * W; 364 const bool rot = warp < nc; 365 const int nq = (k1 - k0) / kCols; 366 uint32_t wc[8][R], wn[8][R]; 367 float xv[4], xs4[4]; 368 load_tiles<K>(tile, sstride, lane, wc); 369 if (rot) chunk_load(x, suh, k0, lane, xv, xs4); 370#if defined(EXL3_TC) 371 float c[4] = {0.0f, 0.0f, 0.0f, 0.0f}; 372#else 373 float acc[kTok][2]; 374#pragma unroll 375 for (int cc = 0; cc < kTok; ++cc) acc[cc][0] = acc[cc][1] = 0.0f; 376#endif 377 for (int q = 0; q < nq; ++q) { 378 __half* xq = sm.xb + (q & 1) * (kTok * kCols); 379 if (rot) chunk_store(xv, xs4, lane, xq + warp * kCols); 380 __syncthreads(); 381 if (q + 1 < nq) { 382 load_tiles<K>(tile + (size_t) (q + 1) * 8 * sstride, sstride, lane, wn); 383 if (rot) chunk_load(x, suh, k0 + (q + 1) * kCols, lane, xv, xs4); 384 } 385#pragma unroll 386 for (int s = 0; s < 8; ++s) { 387 uint32_t f[4]; 388 slice_frags<K, cb>(wc[s], st, lane, f); 389#if defined(EXL3_TC) 390 uint32_t b0 = 0u, b1 = 0u; 391 if (g < nc) { 392 const __half* xr = xq + g * kCols + s * 16 + 2 * t; 393 b0 = *reinterpret_cast<const uint32_t*>(xr); 394 b1 = *reinterpret_cast<const uint32_t*>(xr + 8); 395 } 396 // A: rows (outputs) g / g + 8, columns (inputs) 2t.. / 2t + 8..: steps 0,1 / 4,5 / 2,3 / 6,7 397 mma_f32(c, f[0], f[2], f[1], f[3], b0, b1); 398#else 399 float v[8]; 400#pragma unroll 401 for (int i = 0; i < 4; ++i) { 402 const float2 d = __half22float2(u2h(f[i])); 403 v[2 * i] = d.x; 404 v[2 * i + 1] = d.y; 405 } 406#pragma unroll 407 for (int cc = 0; cc < kTok; ++cc) 408 if (cc < nc) { 409 const __half* xr = xq + cc * kCols + s * 16 + 2 * t; 410 const float x0 = __half2float(xr[0]), x1 = __half2float(xr[1]); 411 const float x2 = __half2float(xr[8]), x3 = __half2float(xr[9]); 412 acc[cc][0] = dot4_acc(acc[cc][0], v, x0, x1, x2, x3); 413 acc[cc][1] = dot4_acc(acc[cc][1], v + 4, x0, x1, x2, x3); 414 } 415#endif 416 } 417#pragma unroll 418 for (int s = 0; s < 8; ++s) 419#pragma unroll 420 for (int r = 0; r < R; ++r) wc[s][r] = wn[s][r]; 421 } 422 const int o = warp * 16 + g; 423#if defined(EXL3_TC) 424 // c: the tile's outputs g (c[0], c[1]) and g + 8 (c[2], c[3]) for activations 2t (c[0], c[2]) and 2t + 1 425 if (2 * t < nc) { 426 sm.out[(2 * t) * kCols + o] = c[0]; 427 sm.out[(2 * t) * kCols + o + 8] = c[2]; 428 } 429 if (2 * t + 1 < nc) { 430 sm.out[(2 * t + 1) * kCols + o] = c[1]; 431 sm.out[(2 * t + 1) * kCols + o + 8] = c[3]; 432 } 433#else 434 // the 4 lanes of one g hold parts of the same two outputs 435#pragma unroll 436 for (int cc = 0; cc < kTok; ++cc) 437 if (cc < nc) { 438#pragma unroll 439 for (int h = 0; h < 2; ++h) { 440 acc[cc][h] += __shfl_xor_sync(0xffffffffu, acc[cc][h], 1); 441 acc[cc][h] += __shfl_xor_sync(0xffffffffu, acc[cc][h], 2); 442 } 443 if (t == 0) { 444 sm.out[cc * kCols + o] = acc[cc][0]; 445 sm.out[cc * kCols + o + 8] = acc[cc][1]; 446 } 447 } 448#endif 449 __syncthreads(); 450} 451 452// one warp: y[c] = alpha * (H(red) * svh)[c] + bias[c] for the block's 128 outputs 453__device__ __forceinline__ void epilogue(const float* red, const uint16_t* svh, float alpha, const float* bias, 454 float* y) { 455 const int lane = threadIdx.x & 31; 456 float v[4]; 457#pragma unroll 458 for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i]; 459 had128(v, lane); 460#pragma unroll 461 for (int i = 0; i < 4; ++i) { 462 const int c = lane * 4 + i; 463 y[c] = __fmaf_rn(__fmul_rn(alpha, v[i]), h2f(svh[c]), bias != nullptr ? bias[c] : 0.0f); 464 } 465} 466 467// ---------------------------------------------------------------- mv 468struct KJob { 469 const uint32_t* tr; 470 const uint16_t* suh; 471 const uint16_t* svh; 472 const float* xf; 473 const Q81* xq; 474 float* y; 475 const float* bias; 476 float* part; // nc x S x n partial sums (S > 1) 477 unsigned* cnt; // n / 128 counters, zero between launches 478 float alpha; 479 int k, n, ld, S, kr; 480 int nc; // the activations (1..kTok), xf / xq / y advanced by these per activation 481 size_t xf_cs, xq_cs, y_cs; // (floats, bytes, floats) 482}; 483struct KBatch { 484 KJob j[kMaxMvJobs]; 485 int blk_end[kMaxMvJobs]; 486 int n; 487 const int* skip; // set_skip's flag: non-zero = a pipelined window's token past a wrong draft (nullptr: none) 488}; 489 490// a launch's blocks: its jobs' (output block, input split) pairs, each for all of the job's nc activations at once 491// (block_gemv). S > 1: the partial sums go to the scratch and the last block of an output block adds them up in split 492// order (deterministic) and runs the epilogue 493template <int K, int cb> 494__global__ void EXL3_BOUNDS(kMinBlocksMv<K>) mv_kernel(const KBatch b) { 495 __shared__ __align__(16) BlockSmem<K> sm; 496 __shared__ int last; 497 int ji = 0; 498 while ((int) blockIdx.x >= b.blk_end[ji]) ++ji; 499 const KJob& J = b.j[ji]; 500 const int local = (int) blockIdx.x - (ji > 0 ? b.blk_end[ji - 1] : 0); 501 const int g = local / J.S, sp = local % J.S; 502 const int k0 = sp * J.kr, k1 = min(J.k, k0 + J.kr); 503 const int warp = threadIdx.x >> 5; 504 // a skipped token (set_skip): no work. The flag changes only between launches (skip_gate, on the same stream), so 505 // every block of the launch returns and no split counter moves 506 if (b.skip != nullptr && *b.skip) return; 507 Xin x; 508 if (warp < J.nc) { 509 if (J.xf != nullptr) x.f = J.xf + warp * J.xf_cs; 510 else x.q = (const Q81*) ((const uint8_t*) J.xq + warp * J.xq_cs); 511 } 512 block_gemv<K, cb>(J.tr, J.ld, g * 8, k0, k1, x, J.suh, J.nc, sm); 513 const float* bias = J.bias != nullptr ? J.bias + g * kCols : nullptr; 514 if (J.S == 1) { 515 if (warp < J.nc) 516 epilogue(sm.out + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols); 517 return; 518 } 519 if (threadIdx.x < kCols) 520 for (int c = 0; c < J.nc; ++c) 521 J.part[((size_t) c * J.S + sp) * J.n + g * kCols + threadIdx.x] = sm.out[c * kCols + threadIdx.x]; 522 __threadfence(); 523 __syncthreads(); 524 if (threadIdx.x == 0) last = atomicAdd(&J.cnt[g], 1u) == (unsigned) (J.S - 1); 525 __syncthreads(); 526 if (!last) return; 527 __threadfence(); 528 if (threadIdx.x < kCols) 529 for (int c = 0; c < J.nc; ++c) { 530 float s = 0.0f; 531 for (int i = 0; i < J.S; ++i) 532 s += *(volatile const float*) &J.part[((size_t) c * J.S + i) * J.n + g * kCols + threadIdx.x]; 533 sm.out[c * kCols + threadIdx.x] = s; 534 } 535 __syncthreads(); 536 if (warp < J.nc) 537 epilogue(sm.out + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols); 538 if (threadIdx.x == 0) J.cnt[g] = 0u; 539} 540 541// ---------------------------------------------------------------- the routed experts 542struct KMoe { 543 const unsigned long long* plan_ptr; 544 const float* plan_w; 545 const float* cpu_part; 546 const int* cpu_flag; 547 const float* x; 548 float* h; // [k][n_ff]: the gate's values, then the swiglu 549 float* u; // [k][n_ff]: the up's values 550 const float* sh_out; 551 float* out; 552 float* part; // [k][n_embd] 553 unsigned* cnt; // n_embd / 128 554 unsigned* cnt_gu; // k x n_ff / 128: the gate / up pairs 555 size_t suh[3], svh[3], tr[3]; 556 int k, n_embd, n_ff; 557 float limit; 558 const int* skip; // set_skip's flag (nullptr: none) 559}; 560 561// the pieces the token's experts (moe_*_kernel) and a window's grouped experts (win_*_kernel) share, so each window 562// token gets the token path's bits: one warp's output block of 128 (H, then svh) ... 563__device__ __forceinline__ void block_out(const float* red, const uint16_t* svh, float* dst) { 564 const int lane = threadIdx.x & 31; 565 float v[4]; 566#pragma unroll 567 for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i]; 568 had128(v, lane); 569#pragma unroll 570 for (int i = 0; i < 4; ++i) dst[lane * 4 + i] = __fmul_rn(v[i], h2f(svh[lane * 4 + i])); 571} 572// ... the clamped swiglu ... 573__device__ __forceinline__ float swiglu(float gv, float uv, float limit) { 574 if (limit > 0.0f) { 575 gv = fminf(gv, limit); 576 uv = fminf(fmaxf(uv, -limit), limit); 577 } 578 return __fmul_rn(__fdiv_rn(gv, __fadd_rn(1.0f, expf(-gv))), uv); 579} 580// ... the second block of a (gate, up) pair to finish (its counter back at zero for the next launch) ... 581__device__ __forceinline__ bool pair_last(unsigned* cnt, int& last) { 582 __threadfence(); 583 __syncthreads(); 584 if (threadIdx.x == 0) last = atomicAdd(cnt, 1u) == 1u; 585 __syncthreads(); 586 if (!last) return false; 587 __threadfence(); 588 if (threadIdx.x == 0) *cnt = 0u; 589 return true; 590} 591// ... and one output's sum: the experts' rows in plan order (p[i]: expert i's, 0 for one not on the device), the CPU 592// lane's part when flagged (cpu_part: null when not), the shared expert's row (sh: 0 without one) 593__device__ __forceinline__ float combine(const float* plan_w, const float* p, int k, const float* cpu_part, float sh) { 594 float m = 0.0f; 595 for (int i = 0; i < k; ++i) m = __fmaf_rn(plan_w[i], p[i], m); 596 if (cpu_part != nullptr) m = __fadd_rn(m, *cpu_part); 597 return __fadd_rn(m, sh); 598} 599 600// grid (n_ff / 128, k, 2): expert blockIdx.y's gate (z 0, into h) or up (z 1, into u) for 128 h values; the pair's 601// second block to finish turns them into the clamped swiglu, in h 602template <int K, int cb> 603__global__ void EXL3_BOUNDS(kMinBlocksX<K>) moe_gate_up_kernel(const KMoe a) { 604 __shared__ __align__(16) BlockSmem<K> sm; 605 __shared__ int last; 606 const int ei = blockIdx.y, g = blockIdx.x, r = blockIdx.z; 607 const unsigned long long ptr = a.plan_ptr[ei]; 608 if (ptr == 0ull) return; 609 if (a.skip != nullptr && *a.skip) return; // a skipped token (set_skip, as mv_kernel) 610 const uint8_t* blob = (const uint8_t*) ptr; 611 const int warp = threadIdx.x >> 5; 612 Xin x; 613 x.f = a.x; 614 block_gemv<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd, x, 615 (const uint16_t*) (blob + a.suh[r]), 1, sm); 616 const size_t row = (size_t) ei * a.n_ff + g * kCols; 617 if (warp == 0) block_out(sm.out, (const uint16_t*) (blob + a.svh[r]) + g * kCols, (r == 0 ? a.h : a.u) + row); 618 if (!pair_last(a.cnt_gu + ei * (a.n_ff / kCols) + g, last)) return; 619 if (threadIdx.x < kCols) 620 a.h[row + threadIdx.x] = swiglu(*(volatile const float*) &a.h[row + threadIdx.x], 621 *(volatile const float*) &a.u[row + threadIdx.x], a.limit); 622} 623 624// grid (n_embd / 128, k): expert blockIdx.y's down rows for 128 outputs; the last block of each output block adds 625// the experts up in plan order (as the engine's moe_down), then the CPU lane's part and the shared expert 626template <int K, int cb> 627__global__ void EXL3_BOUNDS(kMinBlocksX<K>) moe_down_kernel(const KMoe a) { 628 __shared__ __align__(16) BlockSmem<K> sm; 629 __shared__ int last; 630 const int ei = blockIdx.y, g = blockIdx.x; 631 const unsigned long long ptr = a.plan_ptr[ei]; 632 const int warp = threadIdx.x >> 5; 633 float* part = a.part + (size_t) ei * a.n_embd + g * kCols; 634 if (a.skip != nullptr && *a.skip) return; // a skipped token (set_skip, as mv_kernel) 635 if (ptr != 0ull) { 636 const uint8_t* blob = (const uint8_t*) ptr; 637 Xin x; 638 x.f = a.h + (size_t) ei * a.n_ff; 639 block_gemv<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff, x, 640 (const uint16_t*) (blob + a.suh[2]), 1, sm); 641 if (warp == 0) block_out(sm.out, (const uint16_t*) (blob + a.svh[2]) + g * kCols, part); 642 } else if (threadIdx.x < kCols) { 643 part[threadIdx.x] = 0.0f; 644 } 645 __threadfence(); 646 __syncthreads(); 647 if (threadIdx.x == 0) last = atomicAdd(&a.cnt[g], 1u) == (unsigned) (a.k - 1); 648 __syncthreads(); 649 if (!last) return; 650 __threadfence(); 651 if (threadIdx.x < kCols) { 652 const int r = g * kCols + threadIdx.x; 653 float p[8]; 654 for (int i = 0; i < a.k; ++i) p[i] = *(volatile const float*) &a.part[(size_t) i * a.n_embd + r]; 655 a.out[r] = combine(a.plan_w, p, a.k, a.cpu_flag != nullptr && *a.cpu_flag ? a.cpu_part + r : nullptr, 656 a.sh_out != nullptr ? a.sh_out[r] : 0.0f); 657 } 658 if (threadIdx.x == 0) a.cnt[g] = 0u; 659} 660 661// ---------------------------------------------------------------- a verify window's routed experts 662// gf::moe_win_experts' grouping (group g: one expert, its blob at grp_ptr[g]; its entries e = t * 8 + i at 663// grp_ent[grp_start[g] ..)), each group's weights read and decoded once for up to kTok of its tokens at a time (as 664// exllamav3's fused MoE runs a run of slots that picked one expert as the rows of one MMA tile), with the token 665// path's arithmetic per entry: every token's output is moe_gate_up + moe_down's for it alone, bit for bit 666struct KWin { 667 const unsigned long long* grp_ptr; 668 const int *grp_start, *grp_ent, *n_groups; 669 const unsigned long long* plan_ptr; 670 const float* plan_w; 671 const float* cpu_part; 672 size_t cpu_stride; 673 const int* cpu_flag; 674 const float* x; 675 size_t x_stride; 676 float* h; // [T * 8][n_ff]: the gate's values, then the swiglu 677 float* u; // [T * 8][n_ff]: the up's values 678 float* part; // [T * 8][n_embd] 679 const float* sh_out; // [T][n_embd] 680 float* out; 681 size_t out_stride; 682 unsigned* cnt_gu; // groups x n_ff / 128: the gate / up pairs 683 size_t suh[3], svh[3], tr[3]; 684 int k, n_embd, n_ff; 685 float limit; 686}; 687 688// grid (n_ff / 128, groups at most, 2): group blockIdx.y's gate (z 0, into h) or up (z 1, into u) for 128 h values of 689// each of its entries, kTok entries a pass; the pair's second block to finish turns them into the clamped swiglu 690template <int K, int cb> 691__global__ void EXL3_BOUNDS(kMinBlocksX<K>) win_gu_kernel(const KWin a) { 692 __shared__ __align__(16) BlockSmem<K> sm; 693 __shared__ int last; 694 const int grp = blockIdx.y, g = blockIdx.x, r = blockIdx.z; 695 if (grp >= *a.n_groups) return; 696 const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp]; 697 const int warp = threadIdx.x >> 5; 698 const int m0 = a.grp_start[grp], m1 = a.grp_start[grp + 1]; 699 float* dst = r == 0 ? a.h : a.u; 700 for (int mm = m0; mm < m1; mm += kTok) { 701 const int nc = min(kTok, m1 - mm); 702 Xin x; 703 if (warp < nc) x.f = a.x + (size_t) (a.grp_ent[mm + warp] >> 3) * a.x_stride; 704 block_gemv<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd, x, 705 (const uint16_t*) (blob + a.suh[r]), nc, sm); 706 if (warp < nc) 707 block_out(sm.out + warp * kCols, (const uint16_t*) (blob + a.svh[r]) + g * kCols, 708 dst + (size_t) a.grp_ent[mm + warp] * a.n_ff + g * kCols); 709 __syncthreads(); 710 } 711 if (!pair_last(a.cnt_gu + grp * (a.n_ff / kCols) + g, last)) return; 712 if (threadIdx.x < kCols) 713 for (int m = m0; m < m1; ++m) { 714 const size_t row = (size_t) a.grp_ent[m] * a.n_ff + g * kCols + threadIdx.x; 715 a.h[row] = swiglu(*(volatile const float*) &a.h[row], *(volatile const float*) &a.u[row], a.limit); 716 } 717} 718 719// grid (n_embd / 128, groups at most): group blockIdx.y's down rows for 128 outputs of each entry into its part rows 720template <int K, int cb> 721__global__ void EXL3_BOUNDS(kMinBlocksX<K>) win_down_kernel(const KWin a) { 722 __shared__ __align__(16) BlockSmem<K> sm; 723 const int grp = blockIdx.y, g = blockIdx.x; 724 if (grp >= *a.n_groups) return; 725 const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp]; 726 const int warp = threadIdx.x >> 5; 727 const int m0 = a.grp_start[grp], m1 = a.grp_start[grp + 1]; 728 for (int mm = m0; mm < m1; mm += kTok) { 729 const int nc = min(kTok, m1 - mm); 730 Xin x; 731 if (warp < nc) x.f = a.h + (size_t) a.grp_ent[mm + warp] * a.n_ff; 732 block_gemv<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff, x, 733 (const uint16_t*) (blob + a.suh[2]), nc, sm); 734 if (warp < nc) 735 block_out(sm.out + warp * kCols, (const uint16_t*) (blob + a.svh[2]) + g * kCols, 736 a.part + (size_t) a.grp_ent[mm + warp] * a.n_embd + g * kCols); 737 __syncthreads(); 738 } 739} 740 741// grid (n_embd / 128, T): each token's outputs, moe_down_kernel's combine (an entry off the device adds 0) 742__global__ void __launch_bounds__(kCols) win_combine_kernel(const KWin a) { 743 const int t = blockIdx.y, r = blockIdx.x * kCols + threadIdx.x; 744 float p[8]; 745 for (int i = 0; i < a.k; ++i) { 746 const int e = t * 8 + i; 747 p[i] = a.plan_ptr[e] != 0ull ? a.part[(size_t) e * a.n_embd + r] : 0.0f; 748 } 749 a.out[(size_t) t * a.out_stride + r] = 750 combine(a.plan_w + t * 8, p, a.k, 751 a.cpu_flag != nullptr && a.cpu_flag[t] ? a.cpu_part + (size_t) t * a.cpu_stride + r : nullptr, 752 a.sh_out != nullptr ? a.sh_out[(size_t) t * a.n_embd + r] : 0.0f); 753} 754 755__global__ void win_wait_kernel(const unsigned* p, unsigned v) { 756 if (threadIdx.x != 0) return; 757 while (*(volatile const unsigned*) p != v) { 758#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 759 __nanosleep(200); 760#endif 761 } 762 __threadfence_system(); 763} 764 765// ---------------------------------------------------------------- reconstruction 766// grid (n / 128, k / 128): the 128 x 128 block of W = diag(suh) H W' H diag(svh), written transposed (dst[c][r]) 767template <int K, int cb> 768__global__ void __launch_bounds__(kThreads) recon_rows_kernel(const uint32_t* __restrict__ tr, int ld, 769 const uint16_t* __restrict__ suh, 770 const uint16_t* __restrict__ svh, int k, uint16_t* dst, 771 bool bf16) { 772 constexpr int W = 8 * K; 773 constexpr int P = kCols + 2; // padded row (halves) 774 __shared__ __half tile[kCols * P]; 775 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; 776 const int nb = blockIdx.x, kb = blockIdx.y; 777 // decode: warp w takes the 16-row slices w (8 tiles each) 778 for (int ks = warp; ks < 8; ks += kWarps) { 779 const uint32_t* src = tr + ((size_t) (kb * 8 + ks) * ld + nb * 8) * W; 780 for (int t = 0; t < 8; ++t) { 781 float v[8]; 782 decode8<K, cb>(src + t * W, lane, v); 783#pragma unroll 784 for (int j = 0; j < 8; ++j) { 785 const int r = ks * 16 + (lane & 3) * 2 + (j & 1) + 8 * ((j >> 1) & 1); 786 const int c = t * 16 + (lane >> 2) + 8 * (j >> 2); 787 tile[r * P + c] = __float2half_rn(v[j]); 788 } 789 } 790 } 791 __syncthreads(); 792 // H along the outputs (each row of 128 is one block) 793 for (int r = warp; r < kCols; r += kWarps) { 794 float v[4]; 795#pragma unroll 796 for (int i = 0; i < 4; ++i) v[i] = __half2float(tile[r * P + lane * 4 + i]); 797 had128(v, lane); 798#pragma unroll 799 for (int i = 0; i < 4; ++i) tile[r * P + lane * 4 + i] = __float2half_rn(v[i]); 800 } 801 __syncthreads(); 802 // H along the inputs, the scales, the transposed store 803 for (int c = warp; c < kCols; c += kWarps) { 804 float v[4]; 805#pragma unroll 806 for (int i = 0; i < 4; ++i) v[i] = __half2float(tile[(lane * 4 + i) * P + c]); 807 had128(v, lane); 808 const float sv = h2f(svh[nb * kCols + c]); 809 uint16_t* d = dst + (size_t) (nb * kCols + c) * k + kb * kCols + lane * 4; 810#pragma unroll 811 for (int i = 0; i < 4; ++i) { 812 const float w = v[i] * sv * h2f(suh[kb * kCols + lane * 4 + i]); 813 if (bf16) { 814 const uint32_t u = __float_as_uint(w); 815 d[i] = (uint16_t) ((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); // round to nearest even 816 } else { 817 d[i] = __half_as_ushort(__float2half_rn(w)); 818 } 819 } 820 } 821} 822 823// grid (n / 128, k / 16): W' row-major, one tile per warp 824template <int K, int cb> 825__global__ void __launch_bounds__(kThreads) recon_inner_kernel(const uint32_t* __restrict__ tr, int ld, int n, 826 uint16_t* dst) { 827 constexpr int W = 8 * K; 828 const int lane = threadIdx.x & 31, t = threadIdx.x >> 5; 829 const int tc = blockIdx.x * 8 + t, ks = blockIdx.y; 830 float v[8]; 831 decode8<K, cb>(tr + ((size_t) ks * ld + tc) * W, lane, v); 832#pragma unroll 833 for (int j = 0; j < 8; ++j) { 834 const int r = ks * 16 + (lane & 3) * 2 + (j & 1) + 8 * ((j >> 1) & 1); 835 const int c = tc * 16 + (lane >> 2) + 8 * (j >> 2); 836 dst[(size_t) r * n + c] = __half_as_ushort(__float2half_rn(v[j])); 837 } 838} 839 840// grid (n / 128, k / 128): W' of the 128 x 128 block, transposed (dst[c][r]) - the decoded values alone. Each warp 841// decodes its slice's 8 tiles into the block's tile (half2 pairs of rows, conflict-free), then writes 256-byte rows. 842template <int K, int cb> 843__global__ void __launch_bounds__(kThreads) inner_rows_kernel(const uint32_t* __restrict__ tr, int ld, int k, 844 uint16_t* __restrict__ dst) { 845 constexpr int W = 8 * K; 846 constexpr int P = kCols + 8; // a column's 128 rows, padded (halves; 16-byte rows) 847 __shared__ __align__(16) __half tile[kCols * P]; // tile[c * P + r] 848 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, g = lane >> 2, t = lane & 3; 849 const int nb = blockIdx.x, kb = blockIdx.y; 850 for (int ks = warp; ks < 8; ks += kWarps) { 851 const uint32_t* src = tr + ((size_t) (kb * 8 + ks) * ld + nb * 8) * W; 852 const int r = ks * 16 + 2 * t; 853#pragma unroll 854 for (int tc = 0; tc < 8; ++tc) { 855 uint32_t f[4]; 856 frag8<K, cb>(src + tc * W, lane, f); 857 const int c = tc * 16 + g; 858 *reinterpret_cast<uint32_t*>(&tile[c * P + r]) = f[0]; 859 *reinterpret_cast<uint32_t*>(&tile[c * P + r + 8]) = f[1]; 860 *reinterpret_cast<uint32_t*>(&tile[(c + 8) * P + r]) = f[2]; 861 *reinterpret_cast<uint32_t*>(&tile[(c + 8) * P + r + 8]) = f[3]; 862 } 863 } 864 __syncthreads(); 865 for (int c = warp; c < kCols; c += kWarps) 866 *reinterpret_cast<uint2*>(dst + (size_t) (nb * kCols + c) * k + kb * kCols + lane * 4) = 867 *reinterpret_cast<const uint2*>(&tile[c * P + lane * 4]); 868} 869 870// one warp per 128 values of a row: the rotated FP16 input of an EXL3 matrix (rows_rot_f16) ... 871__global__ void __launch_bounds__(kThreads) rows_rot_f16_kernel(const float* __restrict__ x, int ldx, 872 const int* __restrict__ idx, int nrows, int ncols, 873 const uint16_t* __restrict__ suh, uint16_t* out) { 874 const int lane = threadIdx.x & 31, nb = ncols / kCols; 875 const int w = blockIdx.x * kWarps + (threadIdx.x >> 5); 876 if (w >= nrows * nb) return; 877 const int r = w / nb, b = w % nb; 878 Xin xin; 879 xin.f = x + (size_t) (idx != nullptr ? idx[r] : r) * ldx; 880 float v[4], sc[4]; 881 chunk_load(xin, suh, b * kCols, lane, v, sc); 882 chunk_store(v, sc, lane, reinterpret_cast<__half*>(out) + (size_t) r * ncols + b * kCols); 883} 884// ... and its output rotation in place (block_out's arithmetic) 885__global__ void __launch_bounds__(kThreads) rows_rot_out_kernel(float* y, int ldy, int nrows, int ncols, 886 const uint16_t* __restrict__ svh) { 887 const int lane = threadIdx.x & 31, nb = ncols / kCols; 888 const int w = blockIdx.x * kWarps + (threadIdx.x >> 5); 889 if (w >= nrows * nb) return; 890 const int r = w / nb, b = w % nb; 891 float* p = y + (size_t) r * ldy + b * kCols; 892 float v[4]; 893#pragma unroll 894 for (int i = 0; i < 4; ++i) v[i] = p[lane * 4 + i]; 895 had128(v, lane); 896#pragma unroll 897 for (int i = 0; i < 4; ++i) p[lane * 4 + i] = __fmul_rn(v[i], h2f(svh[b * kCols + lane * 4 + i])); 898} 899 900__global__ void rows_f16_kernel(const float* __restrict__ x, int ldx, const int* __restrict__ idx, int ncols, 901 uint16_t* __restrict__ out) { 902 const int r = blockIdx.y; 903 const float* src = x + (size_t) (idx != nullptr ? idx[r] : r) * ldx; 904 uint16_t* dst = out + (size_t) r * ncols; 905 for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < ncols; c += gridDim.x * blockDim.x) 906 dst[c] = __half_as_ushort(__float2half_rn(src[c])); 907} 908 909// ---------------------------------------------------------------- the prompt path's tensor-core GEMMs (sm_80+) 910// A block: BM rows x 128 outputs (one output rotation block). Per 128 inputs the block's rows are scaled by suh, 911// rotated and stored FP16 in shared memory (the A operands); per 16-row slice each warp decodes its 16 x 16 tile 912// straight into mma.m16n8k16's B fragments - a lane's 8 steps ARE the fragment order (steps 0,1 / 2,3 rows 2t+{0,1} / 913// 2t+8+{0,1} of column g, steps 4..7 the same of column g + 8) - and multiplies every m-tile of the block with them. 914// The output rotation and svh run on the F32 tile in shared memory. 915#if !defined(STRATA_USE_HIP) 916namespace tc { 917 918constexpr int BM = 32, MT = BM / 16, AP = 136; // rows a block, its m-tiles, the A rows' pitch (halves) 919 920__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, uint32_t b0, uint32_t b1) { 921#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 922 asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " 923 "{%0,%1,%2,%3};\n" 924 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) 925 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); 926#endif 927} 928// the lane's 4 B registers of tile t (words staged in st): b[0..1] columns 0..7, b[2..3] columns 8..15 929template <int K, int cb> 930__device__ __forceinline__ void tile_frags(const uint32_t* st, int lane, uint32_t* b) { 931 uint32_t f[4]; 932 frag8<K, cb>(st, lane, f); 933#pragma unroll 934 for (int i = 0; i < 4; ++i) b[i] = f[i]; 935} 936 937// A[r][j] = FP16(H(x_r * suh)[j]), j < 128, for the block's rows (zero past nrows). x_r: F32 row idx[r] of xf (ldx) 938// when xf is given, else FP16 row r of xh (ldx). Every warp, BM / 8 rows each. 939__device__ __forceinline__ void load_a(const float* __restrict__ xf, const int* __restrict__ idx, 940 const __half* __restrict__ xh, int ldx, int r0, int nrows, int k0, 941 const uint16_t* __restrict__ suh, __half* A) { 942 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; 943 for (int rr = warp; rr < BM; rr += kWarps) { 944 float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; 945 const int r = r0 + rr; 946 if (rr < nrows) { 947 const int c = k0 + lane * 4; 948 if (xf != nullptr) { 949 const float* src = xf + (size_t) idx[r] * ldx + c; 950#pragma unroll 951 for (int i = 0; i < 4; ++i) v[i] = src[i]; 952 } else { 953 const __half* src = xh + (size_t) r * ldx + c; 954#pragma unroll 955 for (int i = 0; i < 4; ++i) v[i] = __half2float(src[i]); 956 } 957#pragma unroll 958 for (int i = 0; i < 4; ++i) v[i] *= h2f(suh[c + i]); 959 had128(v, lane); 960 } 961#pragma unroll 962 for (int i = 0; i < 4; ++i) A[rr * AP + lane * 4 + i] = __float2half_rn(v[i]); 963 } 964} 965 966// the m-tile's A registers for the 16-column slice s of A 967__device__ __forceinline__ void a_frags(const __half* A, int mt, int s, int lane, uint32_t* a) { 968 const int g = lane >> 2, t = lane & 3; 969 const __half* p = A + (mt * 16 + g) * AP + s * 16 + 2 * t; 970 a[0] = *reinterpret_cast<const uint32_t*>(p); 971 a[1] = *reinterpret_cast<const uint32_t*>(p + 8 * AP); 972 a[2] = *reinterpret_cast<const uint32_t*>(p + 8); 973 a[3] = *reinterpret_cast<const uint32_t*>(p + 8 * AP + 8); 974} 975 976// acc (this warp's 16 columns of the block's BM rows) -> T[BM][128] F32 977__device__ __forceinline__ void store_acc(const float (&acc)[MT][2][4], float* T) { 978 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, g = lane >> 2, t = lane & 3; 979#pragma unroll 980 for (int mt = 0; mt < MT; ++mt) 981#pragma unroll 982 for (int ns = 0; ns < 2; ++ns) { 983 const int c = warp * 16 + ns * 8 + 2 * t, r = mt * 16 + g; 984 T[r * 128 + c] = acc[mt][ns][0]; 985 T[r * 128 + c + 1] = acc[mt][ns][1]; 986 T[(r + 8) * 128 + c] = acc[mt][ns][2]; 987 T[(r + 8) * 128 + c + 1] = acc[mt][ns][3]; 988 } 989} 990 991struct GArgs { 992 const uint8_t* wbase; // expert e's blob at wbase + e * stride (dense: 0, the offsets are pointers) 993 size_t stride; 994 size_t tr[3], suh[3], svh[3]; 995 int ld[3]; // tiles per 16-row slice of each matrix 996 const int* bounds; // device: expert e's rows [bounds[e], bounds[e + 1]) (null: one matrix, rows [0, m)) 997 int row0, m; // local row of a sorted row: bounds[e] - row0 + r 998 int k, n; // of the matrix (gate/up: n_embd, n_ff) 999 const float* xf; // F32 input rows by index (idx[local row]) ... 1000 const int* idx; 1001 const __half* xh; // ... or FP16 rows by local row 1002 int ldx; 1003 float* y; // F32 output rows (ldy), y = beta y + out ... 1004 int ldy; 1005 float beta; 1006 __half* h; // ... or (gate/up) the swiglu as FP16 rows (ldh) 1007 int ldh; 1008 float limit; 1009}; 1010 1011// one matrix: y = beta y + H(H(x * suh) W') * svh. grid (row blocks, n / 128, experts) 1012template <int K, int cb> 1013__global__ void __launch_bounds__(kThreads) gemm_kernel(const GArgs a) { 1014 constexpr int W = 8 * K; 1015 __shared__ __align__(16) unsigned char sm[BM * 128 * 4]; // A (BM x AP halves), then the F32 tile 1016 __shared__ uint32_t stage[kWarps][64]; 1017 __half* A = reinterpret_cast<__half*>(sm); 1018 float* T = reinterpret_cast<float*>(sm); 1019 const int e = blockIdx.z, rb = blockIdx.x, g = blockIdx.y; 1020 const int e0 = a.bounds != nullptr ? a.bounds[e] - a.row0 : 0; 1021 const int ne = a.bounds != nullptr ? a.bounds[e + 1] - a.bounds[e] : a.m; 1022 const int r0 = e0 + rb * BM, nrows = min(BM, ne - rb * BM); 1023 if (nrows <= 0) return; 1024 const uint8_t* blob = a.wbase + (size_t) e * a.stride; 1025 const uint32_t* tr = (const uint32_t*) (blob + a.tr[0]); 1026 const uint16_t* suh = (const uint16_t*) (blob + a.suh[0]); 1027 const uint16_t* svh = (const uint16_t*) (blob + a.svh[0]); 1028 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; 1029 float acc[MT][2][4] = {}; 1030 for (int k0 = 0; k0 < a.k; k0 += 128) { 1031 __syncthreads(); 1032 load_a(a.xf, a.idx, a.xh, a.ldx, r0, nrows, k0, suh, A); 1033 __syncthreads(); 1034#pragma unroll 1 1035 for (int s = 0; s < 8; ++s) { 1036 const int ks = k0 / 16 + s; 1037 const uint32_t* src = tr + ((size_t) ks * a.ld[0] + g * 8 + warp) * W; 1038 __syncwarp(); 1039 for (int i = lane; i < W; i += 32) stage[warp][i] = src[i]; 1040 __syncwarp(); 1041 uint32_t b[4]; 1042 tile_frags<K, cb>(stage[warp], lane, b); 1043#pragma unroll 1044 for (int mt = 0; mt < MT; ++mt) { 1045 uint32_t af[4]; 1046 a_frags(A, mt, s, lane, af); 1047 mma16816(acc[mt][0], af, b[0], b[1]); 1048 mma16816(acc[mt][1], af, b[2], b[3]); 1049 } 1050 } 1051 } 1052 __syncthreads(); 1053 store_acc(acc, T); 1054 __syncthreads(); 1055 for (int rr = warp; rr < nrows; rr += kWarps) { 1056 float v[4]; 1057#pragma unroll 1058 for (int i = 0; i < 4; ++i) v[i] = T[rr * 128 + lane * 4 + i]; 1059 had128(v, lane); 1060 float* yr = a.y + (size_t) (r0 + rr) * a.ldy + g * 128 + lane * 4; 1061#pragma unroll 1062 for (int i = 0; i < 4; ++i) { 1063 const float o = v[i] * h2f(svh[g * 128 + lane * 4 + i]); 1064 yr[i] = a.beta != 0.0f ? a.beta * yr[i] + o : o; 1065 } 1066 } 1067} 1068 1069// gate and up (matrices 0 and 1) over the same rows, the clamped swiglu, FP16 h. grid (row blocks, n / 128, experts) 1070template <int K, int cb> 1071__global__ void __launch_bounds__(kThreads) gate_up_kernel(const GArgs a) { 1072 constexpr int W = 8 * K; 1073 __shared__ __align__(16) unsigned char sm[2 * BM * 128 * 4]; // A_g, A_u, then the two F32 tiles 1074 __shared__ uint32_t stage[kWarps][64]; 1075 __half* A[2] = {reinterpret_cast<__half*>(sm), reinterpret_cast<__half*>(sm) + BM * AP}; 1076 float* T[2] = {reinterpret_cast<float*>(sm), reinterpret_cast<float*>(sm) + BM * 128}; 1077 const int e = blockIdx.z, rb = blockIdx.x, g = blockIdx.y; 1078 const int e0 = a.bounds[e] - a.row0, ne = a.bounds[e + 1] - a.bounds[e]; 1079 const int r0 = e0 + rb * BM, nrows = min(BM, ne - rb * BM); 1080 if (nrows <= 0) return; 1081 const uint8_t* blob = a.wbase + (size_t) e * a.stride; 1082 const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; 1083 float acc[2][MT][2][4] = {}; 1084 for (int k0 = 0; k0 < a.k; k0 += 128) { 1085 __syncthreads(); 1086 for (int m = 0; m < 2; ++m) 1087 load_a(a.xf, a.idx, a.xh, a.ldx, r0, nrows, k0, (const uint16_t*) (blob + a.suh[m]), A[m]); 1088 __syncthreads(); 1089#pragma unroll 1 1090 for (int s = 0; s < 8; ++s) { 1091 const int ks = k0 / 16 + s; 1092#pragma unroll 1093 for (int m = 0; m < 2; ++m) { 1094 const uint32_t* src = (const uint32_t*) (blob + a.tr[m]) + ((size_t) ks * a.ld[m] + g * 8 + warp) * W; 1095 __syncwarp(); 1096 for (int i = lane; i < W; i += 32) stage[warp][i] = src[i]; 1097 __syncwarp(); 1098 uint32_t b[4]; 1099 tile_frags<K, cb>(stage[warp], lane, b); 1100#pragma unroll 1101 for (int mt = 0; mt < MT; ++mt) { 1102 uint32_t af[4]; 1103 a_frags(A[m], mt, s, lane, af); 1104 mma16816(acc[m][mt][0], af, b[0], b[1]); 1105 mma16816(acc[m][mt][1], af, b[2], b[3]); 1106 } 1107 } 1108 } 1109 } 1110 __syncthreads(); 1111 store_acc(acc[0], T[0]); 1112 store_acc(acc[1], T[1]); 1113 __syncthreads(); 1114 const uint16_t* svg = (const uint16_t*) (a.wbase + (size_t) e * a.stride + a.svh[0]) + g * 128; 1115 const uint16_t* svu = (const uint16_t*) (a.wbase + (size_t) e * a.stride + a.svh[1]) + g * 128; 1116 for (int rr = warp; rr < nrows; rr += kWarps) { 1117 float vg[4], vu[4]; 1118#pragma unroll 1119 for (int i = 0; i < 4; ++i) { 1120 vg[i] = T[0][rr * 128 + lane * 4 + i]; 1121 vu[i] = T[1][rr * 128 + lane * 4 + i]; 1122 } 1123 had128(vg, lane); 1124 had128(vu, lane); 1125 __half* hr = a.h + (size_t) (r0 + rr) * a.ldh + g * 128 + lane * 4; 1126#pragma unroll 1127 for (int i = 0; i < 4; ++i) { 1128 float gv = vg[i] * h2f(svg[lane * 4 + i]), uv = vu[i] * h2f(svu[lane * 4 + i]); 1129 if (a.limit > 0.0f) { 1130 gv = fminf(gv, a.limit); 1131 uv = fminf(fmaxf(uv, -a.limit), a.limit); 1132 } 1133 hr[i] = __float2half_rn((gv / (1.0f + expf(-gv))) * uv); 1134 } 1135 } 1136} 1137 1138} // namespace tc 1139#endif 1140 1141// ---------------------------------------------------------------- dispatch 1142// F(K, cb) for K 1..8 and the three codebooks 1143template <template <int, int> class F, typename... A> 1144bool dispatch(int K, int cb, A&&... args) { 1145#define EXL3_CASE(KK) \ 1146 case KK: \ 1147 if (cb == 2) F<KK, 2>::run(std::forward<A>(args)...); \ 1148 else if (cb == 1) F<KK, 1>::run(std::forward<A>(args)...); \ 1149 else F<KK, 0>::run(std::forward<A>(args)...); \ 1150 return true; 1151 switch (K) { 1152 EXL3_CASE(1) EXL3_CASE(2) EXL3_CASE(3) EXL3_CASE(4) EXL3_CASE(5) EXL3_CASE(6) EXL3_CASE(7) EXL3_CASE(8) 1153 default: return false; 1154 } 1155#undef EXL3_CASE 1156} 1157 1158template <int K, int cb> struct RunMv { 1159 static void run(const KBatch& b, int blocks, cudaStream_t s) { mv_kernel<K, cb><<<blocks, kThreads, 0, s>>>(b); } 1160}; 1161template <int K, int cb> struct RunWin { 1162 static void run(const KWin& a, int groups, cudaStream_t s) { 1163 win_gu_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) groups, 2u), kThreads, 0, s>>>(a); 1164 } 1165}; 1166template <int K, int cb> struct RunWinDown { 1167 static void run(const KWin& a, int groups, cudaStream_t s) { 1168 win_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) groups), kThreads, 0, s>>>(a); 1169 } 1170}; 1171template <int K, int cb> struct RunGU { 1172 static void run(const KMoe& a, cudaStream_t s) { 1173 moe_gate_up_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) a.k, 2u), kThreads, 0, s>>>(a); 1174 } 1175}; 1176template <int K, int cb> struct RunDown { 1177 static void run(const KMoe& a, cudaStream_t s) { 1178 moe_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.k), kThreads, 0, s>>>(a); 1179 } 1180}; 1181template <int K, int cb> struct RunRows { 1182 static void run(const Mat& m, uint16_t* dst, bool bf16, cudaStream_t s) { 1183 recon_rows_kernel<K, cb><<<dim3((unsigned) (m.n / kCols), (unsigned) (m.k / kCols)), kThreads, 0, s>>>( 1184 m.trellis, m.ld > 0 ? m.ld : m.n / 16, m.suh, m.svh, m.k, dst, bf16); 1185 } 1186}; 1187#if !defined(STRATA_USE_HIP) 1188template <int K, int cb> struct RunGemm { 1189 static void run(const tc::GArgs& a, dim3 grid, cudaStream_t s) { tc::gemm_kernel<K, cb><<<grid, kThreads, 0, s>>>(a); } 1190}; 1191template <int K, int cb> struct RunGateUp { 1192 static void run(const tc::GArgs& a, dim3 grid, cudaStream_t s) { 1193 tc::gate_up_kernel<K, cb><<<grid, kThreads, 0, s>>>(a); 1194 } 1195}; 1196#endif 1197template <int K, int cb> struct RunInnerRows { 1198 static void run(const Mat& m, uint16_t* dst, cudaStream_t s) { 1199 inner_rows_kernel<K, cb><<<dim3((unsigned) (m.n / kCols), (unsigned) (m.k / kCols)), kThreads, 0, s>>>( 1200 m.trellis, m.ld > 0 ? m.ld : m.n / 16, m.k, dst); 1201 } 1202}; 1203template <int K, int cb> struct RunInner { 1204 static void run(const Mat& m, uint16_t* dst, cudaStream_t s) { 1205 recon_inner_kernel<K, cb><<<dim3((unsigned) (m.n / kCols), (unsigned) (m.k / 16)), kThreads, 0, s>>>( 1206 m.trellis, m.ld > 0 ? m.ld : m.n / 16, m.n, dst); 1207 } 1208}; 1209 1210// ---------------------------------------------------------------- per-stream scratch 1211constexpr size_t kPartFloats = (size_t) 2 << 20; // split partials: 8 MB 1212constexpr size_t kCounters = 16384; 1213constexpr size_t kCntGU = 8192; // the counters from here on: the experts' gate / up pairs 1214constexpr size_t kHFloats = (size_t) 8 * 8192; // the experts' h 1215constexpr size_t kUFloats = (size_t) 128 * 4096; // the experts' up values: a window's 16 tokens x 8, n_ff <= 4096 1216struct Scratch { 1217 float* part = nullptr; 1218 unsigned* cnt = nullptr; 1219 float* h = nullptr; 1220 float* u = nullptr; 1221}; 1222std::mutex g_mu; 1223std::map<std::pair<int, cudaStream_t>, Scratch> g_scratch; 1224 1225Scratch* scratch(cudaStream_t s) { 1226 int dev = 0; 1227 cudaGetDevice(&dev); 1228 // (the last stream this thread used: an engine thread per device launches without the lock) 1229 thread_local int t_dev = -1; 1230 thread_local cudaStream_t t_s = nullptr; 1231 thread_local Scratch* t_sc = nullptr; 1232 if (t_sc != nullptr && t_dev == dev && t_s == s) return t_sc; 1233 std::lock_guard<std::mutex> lk(g_mu); 1234 auto it = g_scratch.find({dev, s}); 1235 if (it != g_scratch.end()) { 1236 t_dev = dev, t_s = s, t_sc = &it->second; 1237 return &it->second; 1238 } 1239 cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone; 1240 if (cudaStreamIsCapturing(s, &cs) == cudaSuccess && cs != cudaStreamCaptureStatusNone) { 1241 std::fprintf(stderr, "exl3: scratch for a stream first seen inside a graph capture (call exl3::prepare)\n"); 1242 return nullptr; 1243 } 1244 Scratch sc; 1245 if (cudaMalloc(&sc.part, kPartFloats * sizeof(float)) != cudaSuccess || 1246 cudaMalloc(&sc.cnt, kCounters * sizeof(unsigned)) != cudaSuccess || 1247 cudaMalloc(&sc.h, kHFloats * sizeof(float)) != cudaSuccess || 1248 cudaMalloc(&sc.u, kUFloats * sizeof(float)) != cudaSuccess || 1249 cudaMemsetAsync(sc.cnt, 0, kCounters * sizeof(unsigned), s) != cudaSuccess) { 1250 std::fprintf(stderr, "exl3: scratch did not allocate\n"); 1251 return nullptr; 1252 } 1253 cudaStreamSynchronize(s); 1254 return &(g_scratch[{dev, s}] = sc); 1255} 1256 1257int sm_count() { 1258 int dev = 0, sms = 0; 1259 cudaGetDevice(&dev); 1260 cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); 1261 return std::max(1, sms); 1262} 1263 1264// Whether the current device decodes with v1.1.8's kernels (exl3_legacy.cu): NVIDIA before sm_80, where this file's 1265// tiles run on the CUDA cores and were slower; STRATA_GLM_EXL3_DECODE=legacy | new picks one on any GPU (A/B). The 1266// token path and the verify windows take the same family on a device, so a window stays bit for bit its token path. 1267// Asked once per device. 1268bool use_legacy() { 1269#if defined(STRATA_USE_HIP) 1270 return false; 1271#else 1272 static std::atomic<int> cache[64]; // 0 not asked, 1 v1.1.8's kernels, 2 this file's 1273 int dev = 0; 1274 cudaGetDevice(&dev); 1275 if (dev < 0 || dev >= 64) return false; 1276 int c = cache[dev].load(std::memory_order_acquire); 1277 if (c == 0) { 1278 int major = 0; 1279 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 1280 const char* v = std::getenv("STRATA_GLM_EXL3_DECODE"); 1281 c = v != nullptr && std::strcmp(v, "legacy") == 0 ? 1 : v != nullptr && std::strcmp(v, "new") == 0 ? 2 1282 : major < 8 ? 1 1283 : 2; 1284 if (c == 1) std::fprintf(stderr, "exl3: CUDA%d decodes with v1.1.8's kernels\n", dev); 1285 cache[dev].store(c, std::memory_order_release); 1286 } 1287 return c == 1; 1288#endif 1289} 1290 1291// the blocks of mv_kernel<K> an SM of the current device keeps at once (its registers and shared memory), asked once 1292// per device and K 1293template <int K, int cb> struct OccMv { 1294 static void run(int& n) { 1295 if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&n, mv_kernel<K, cb>, kThreads, 0) != cudaSuccess) { 1296 cudaGetLastError(); 1297 n = 2; 1298 } 1299 } 1300}; 1301int mv_occ(int K) { 1302 static std::atomic<int> cache[64][9]; // 0: not asked 1303 int dev = 0; 1304 cudaGetDevice(&dev); 1305 if (dev < 0 || dev >= 64 || K < 1 || K > 8) return 2; 1306 int n = cache[dev][K].load(std::memory_order_acquire); 1307 if (n == 0) { 1308 n = 2; 1309 dispatch<OccMv>(K, 2, n); 1310 n = std::max(1, n); 1311 cache[dev][K].store(n, std::memory_order_release); 1312 } 1313 return n; 1314} 1315 1316// mv's input split for m: S blocks of kr inputs per output block, at most kMaxKR inputs a block (the same for every 1317// activation count, so a job of several sums each activation as a job of one). About two blocks per SM; where an SM 1318// keeps three or more (`occ`: the RTX 3090's at K > 4) four a SM, down to 128 inputs a block - its decode sets the pace 1319// there, and the more, shorter blocks balance it over the SMs (RTX 3090, K6 / K5, us: a KDA layer's 8192 x 4096 1320// output 47.6 -> 45.5, the dense layers' 4096 x 12288 gate 58.9 -> 52.5 and 12288 x 4096 down 59.3 -> 52.2, the 1321// shared expert's 4096 x 2048 17.4 -> 16.5); with two a SM, a launch that would spill a short second wave (more blocks 1322// than the SMs keep, less than one and a half times) takes twice the splits (RTX 5060 Ti, K5: that gate 99.4 -> 84.8 1323// us, that down 100.6 -> 84.9) 1324// call_groups: the output blocks the call's jobs of this code count together against the target, not the job's own - 1325// where an SM keeps three or more, all of them (RTX 3090, K6, a KDA layer's q, k and v, three 4096 x 8192 jobs: 1536 1326// blocks 119.6 us, 384 blocks 105.9); at two a SM only jobs of the same shape (RTX 5060 Ti: those q, k and v 191 -> 1327// 185 us, a shared expert's gate and up 35.9 -> 35.0; the MLA layer's q_a and kv_a together would lose 8%). Never the 1328// activations: a window's token gets the token path's split 1329void mv_split(const Mat& m, int sms, int occ, int& S, int& kr, int call_groups = 0) { 1330 const bool many = occ >= 3; 1331 const int groups = std::max(m.n / kCols, call_groups); 1332 const int kr_min = many ? 128 : 256, target = (many ? 4 : 2) * sms, P = occ * sms; 1333 S = (m.k + kMaxKR - 1) / kMaxKR; 1334 while (groups * S < target && m.k / (S * 2) >= kr_min) S *= 2; 1335 if (!many && groups * S > P && 2 * groups * S < 3 * P && m.k / (S * 2) >= kr_min) S *= 2; 1336 kr = ((m.k + S - 1) / S + 127) / 128 * 128; 1337 S = (m.k + kr - 1) / kr; 1338} 1339 1340} // namespace 1341 1342Mat view(const Mat& m, int c0, int nc) { 1343 Mat v = m; 1344 v.ld = m.ld > 0 ? m.ld : m.n / 16; 1345 v.trellis = m.trellis + (size_t) (c0 / 16) * 8 * m.K; 1346 v.svh = m.svh + c0; 1347 v.n = nc; 1348 return v; 1349} 1350 1351bool supported(const Mat& m) { 1352 return m.trellis != nullptr && m.suh != nullptr && m.svh != nullptr && m.k > 0 && m.n > 0 && m.k % 128 == 0 && 1353 m.n % 128 == 0 && m.K >= 1 && m.K <= 8 && m.cb >= 0 && m.cb <= 2; 1354} 1355 1356void set_skip(const int* flag) { g_skip = flag; } 1357 1358int mv_splits(const Mat& m) { 1359 if (!supported(m)) return 0; 1360 int S = 1, kr = 0; 1361 mv_split(m, sm_count(), mv_occ(m.K), S, kr); 1362 return S; 1363} 1364 1365int mv_cols(const Mat& m) { 1366 if (!supported(m)) return 0; 1367#if !defined(STRATA_USE_HIP) 1368 if (use_legacy()) return 4; // (v1.1.8's kernels: the runs of four their callers have always used) 1369#endif 1370 const int S = mv_splits(m); 1371 if (S <= 0) return 0; 1372 if (S == 1) return kTok; 1373 return (int) std::max<size_t>(1, std::min<size_t>(kTok, kPartFloats / ((size_t) S * m.n))); 1374} 1375 1376int launch_errors() { 1377#if !defined(STRATA_USE_HIP) 1378 return g_launch_errors.load(std::memory_order_relaxed) + legacy::launch_errors(); 1379#else 1380 return g_launch_errors.load(std::memory_order_relaxed); 1381#endif 1382} 1383 1384bool prepare(cudaStream_t s) { 1385 EXL3_LEGACY(prepare(s)); 1386 return scratch(s) != nullptr; 1387} 1388 1389bool several_ok() { 1390 EXL3_LEGACY(several_ok()); 1391 return true; 1392} 1393 1394bool mv(const MvJob* jobs, int n, cudaStream_t s) { 1395 EXL3_LEGACY(mv(jobs, n, s)); 1396 if (n <= 0 || n > kMaxMvJobs) return false; 1397 Scratch* sc = scratch(s); 1398 if (sc == nullptr) return false; 1399 const int sms = sm_count(); 1400 // the launch units: a job's activations in runs of up to kTok (one pass over its weights each) 1401 struct Unit { 1402 int j, c0, nc; 1403 }; 1404 Unit units[kMaxMvJobs * kMaxMvCols]; 1405 int nu = 0; 1406 const int run = kTok; 1407 for (int j = 0; j < n; ++j) { 1408 const Mat& m = *jobs[j].m; 1409 if (!supported(m) || jobs[j].y == nullptr || (jobs[j].xf == nullptr && jobs[j].xq == nullptr) || 1410 jobs[j].ncol < 1 || jobs[j].ncol > kMaxMvCols) { 1411 std::fprintf(stderr, "exl3 mv: job %d unsupported (k %d n %d K %d cb %d, %d activations)\n", j, m.k, m.n, 1412 m.K, m.cb, jobs[j].ncol); 1413 return false; 1414 } 1415 for (int c0 = 0; c0 < jobs[j].ncol; c0 += run) units[nu++] = {j, c0, std::min(run, jobs[j].ncol - c0)}; 1416 } 1417 // each job's call_groups (mv_split): the output blocks of the call's jobs of its code - of its shape too where an SM 1418 // keeps fewer than three 1419 int cg[kMaxMvJobs] = {}; 1420 for (int j = 0; j < n; ++j) { 1421 const Mat& a = *jobs[j].m; 1422 const bool many = mv_occ(a.K) >= 3; 1423 for (int q = 0; q < n; ++q) { 1424 const Mat& b = *jobs[q].m; 1425 if (b.K == a.K && b.cb == a.cb && (many || (b.k == a.k && b.n == a.n))) cg[j] += b.n / kCols; 1426 } 1427 } 1428 bool done[sizeof(units) / sizeof(units[0])] = {}; 1429 for (int i = 0; i < nu; ++i) { 1430 if (done[i]) continue; 1431 const Mat& m0 = *jobs[units[i].j].m; 1432 // a launch: the units of one (K, codebook), as many as KBatch and the split scratch take (the next launch on 1433 // the stream may use the scratch again: this one's last blocks are done with it by then) 1434 KBatch b{}; 1435 int blocks = 0, nb = 0; 1436 size_t part_at = 0, cnt_at = 0; 1437 for (int u = i; u < nu && nb < kMaxMvJobs; ++u) { 1438 const MvJob& job = jobs[units[u].j]; 1439 const Mat& m = *job.m; 1440 if (done[u] || m.K != m0.K || m.cb != m0.cb) continue; 1441 const int c0 = units[u].c0, nc = units[u].nc, groups = m.n / kCols; 1442 int S = 1, kr = 0; 1443 mv_split(m, sms, mv_occ(m.K), S, kr, cg[units[u].j]); 1444 const size_t need = S > 1 ? (size_t) S * m.n * nc : 0; 1445 if (S > 1 && (part_at + need > kPartFloats || cnt_at + (size_t) groups > kCounters)) { 1446 if (nb > 0) continue; // the next launch 1447 std::fprintf(stderr, "exl3 mv: scratch too small for k %d n %d (%d activations)\n", m.k, m.n, nc); 1448 return false; 1449 } 1450 done[u] = true; 1451 KJob& J = b.j[nb]; 1452 J.tr = m.trellis; 1453 J.suh = m.suh; 1454 J.svh = m.svh; 1455 J.xf = job.xf != nullptr ? job.xf + c0 * job.xf_cs : nullptr; 1456 J.xq = job.xq != nullptr ? (const Q81*) ((const uint8_t*) job.xq + c0 * job.xq_cs) : nullptr; 1457 J.y = job.y + c0 * job.y_cs; 1458 J.bias = job.bias; 1459 J.alpha = job.alpha; 1460 J.k = m.k; 1461 J.n = m.n; 1462 J.ld = m.ld > 0 ? m.ld : m.n / 16; 1463 J.S = S; 1464 J.kr = kr; 1465 J.part = sc->part + part_at; 1466 J.cnt = sc->cnt + cnt_at; 1467 J.nc = nc; 1468 J.xf_cs = job.xf_cs; 1469 J.xq_cs = job.xq_cs; 1470 J.y_cs = job.y_cs; 1471 part_at += need; 1472 if (S > 1) cnt_at += (size_t) groups; 1473 blocks += groups * S; 1474 b.blk_end[nb++] = blocks; 1475 } 1476 b.n = nb; 1477 b.skip = g_skip; 1478 if (!dispatch<RunMv>(m0.K, m0.cb, b, blocks, s)) return false; 1479 } 1480 launch_check("mv"); 1481 return true; 1482} 1483 1484static bool moe_args(const MoeArgs& a, KMoe& m, cudaStream_t s) { 1485 Scratch* sc = scratch(s); 1486 if (sc == nullptr) return false; 1487 if (a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxMoeK || 1488 a.n_ff > kMaxMoeK || (size_t) a.k * a.n_ff > kHFloats || (size_t) a.k * a.n_embd > kPartFloats || 1489 (size_t) (a.n_embd / kCols) > kCntGU || kCntGU + (size_t) a.k * (a.n_ff / kCols) > kCounters) { 1490 std::fprintf(stderr, "exl3 moe: geometry not covered (k %d n_embd %d n_ff %d)\n", a.k, a.n_embd, a.n_ff); 1491 return false; 1492 } 1493 m = KMoe{}; 1494 m.plan_ptr = a.plan_ptr; 1495 m.plan_w = a.plan_w; 1496 m.cpu_part = a.cpu_part; 1497 m.cpu_flag = a.cpu_flag; 1498 m.h = sc->h; 1499 m.u = sc->u; 1500 m.part = sc->part; 1501 m.cnt = sc->cnt; 1502 m.cnt_gu = sc->cnt + kCntGU; 1503 for (int r = 0; r < 3; ++r) { 1504 m.suh[r] = a.lay.suh[r]; 1505 m.svh[r] = a.lay.svh[r]; 1506 m.tr[r] = a.lay.trellis[r]; 1507 } 1508 m.k = a.k; 1509 m.n_embd = a.n_embd; 1510 m.n_ff = a.n_ff; 1511 m.limit = a.limit; 1512 m.skip = g_skip; 1513 return true; 1514} 1515 1516void moe_gate_up(const MoeArgs& a, const float* x, float* h, cudaStream_t s) { 1517 EXL3_LEGACY(moe_gate_up(a, x, h, s)); 1518 KMoe m; 1519 if (!moe_args(a, m, s)) return; 1520 if (a.lay.K[0] != a.lay.K[1]) { 1521 std::fprintf(stderr, "exl3 moe_gate_up: gate K %d != up K %d\n", a.lay.K[0], a.lay.K[1]); 1522 return; 1523 } 1524 m.x = x; 1525 if (h != nullptr) m.h = h; 1526 if (!dispatch<RunGU>(a.lay.K[0], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_gate_up: K %d\n", a.lay.K[0]); 1527 launch_check("moe_gate_up"); 1528} 1529 1530void moe_down(const MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s) { 1531 EXL3_LEGACY(moe_down(a, h, sh_out, out, s)); 1532 KMoe m; 1533 if (!moe_args(a, m, s)) return; 1534 if (h != nullptr) m.h = const_cast<float*>(h); 1535 m.sh_out = sh_out; 1536 m.out = out; 1537 if (!dispatch<RunDown>(a.lay.K[2], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_down: K %d\n", a.lay.K[2]); 1538 launch_check("moe_down"); 1539} 1540 1541bool win_experts(const WinArgs& a, cudaStream_t s) { 1542 EXL3_LEGACY(win_experts(a, s)); 1543 if (a.T < 1 || a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxMoeK || 1544 a.n_ff > kMaxMoeK || a.lay.K[0] != a.lay.K[1] || a.h == nullptr || a.part == nullptr || a.out == nullptr) { 1545 std::fprintf(stderr, "exl3 win_experts: not covered (T %d k %d n_embd %d n_ff %d, gate K %d up K %d)\n", a.T, 1546 a.k, a.n_embd, a.n_ff, a.lay.K[0], a.lay.K[1]); 1547 return false; 1548 } 1549 Scratch* sc = scratch(s); 1550 if (sc == nullptr) return false; 1551 const int groups = a.T * a.k; // at most (the blocks past the real count return at once) 1552 if ((size_t) a.T * 8 * a.n_ff > kUFloats || kCntGU + (size_t) groups * (a.n_ff / kCols) > kCounters) { 1553 std::fprintf(stderr, "exl3 win_experts: %d tokens are more than the scratch takes\n", a.T); 1554 return false; 1555 } 1556 KWin w{}; 1557 w.grp_ptr = a.grp_ptr; 1558 w.grp_start = a.grp_start; 1559 w.grp_ent = a.grp_ent; 1560 w.n_groups = a.n_groups; 1561 w.plan_ptr = a.plan_ptr; 1562 w.plan_w = a.plan_w; 1563 w.cpu_part = a.cpu_part; 1564 w.cpu_stride = a.cpu_stride != 0 ? a.cpu_stride : (size_t) a.n_embd; 1565 w.cpu_flag = a.cpu_flag; 1566 w.x = a.x; 1567 w.x_stride = a.x_stride; 1568 w.h = a.h; 1569 w.u = sc->u; 1570 w.cnt_gu = sc->cnt + kCntGU; 1571 w.part = a.part; 1572 w.sh_out = a.sh_out; 1573 w.out = a.out; 1574 w.out_stride = a.out_stride; 1575 for (int r = 0; r < 3; ++r) { 1576 w.suh[r] = a.lay.suh[r]; 1577 w.svh[r] = a.lay.svh[r]; 1578 w.tr[r] = a.lay.trellis[r]; 1579 } 1580 w.k = a.k; 1581 w.n_embd = a.n_embd; 1582 w.n_ff = a.n_ff; 1583 w.limit = a.limit; 1584 if (!dispatch<RunWin>(a.lay.K[0], a.lay.cb, w, groups, s) || 1585 !dispatch<RunWinDown>(a.lay.K[2], a.lay.cb, w, groups, s)) 1586 return false; 1587 if (a.wait_ptr != nullptr) win_wait_kernel<<<1, 32, 0, s>>>(a.wait_ptr, a.wait_val); 1588 win_combine_kernel<<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.T), kCols, 0, s>>>(w); 1589 launch_check("win_experts"); 1590 return true; 1591} 1592 1593bool mma_supported() { 1594#if defined(STRATA_USE_HIP) 1595 return false; 1596#else 1597 int dev = 0, major = 0; 1598 cudaGetDevice(&dev); 1599 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 1600 return major >= 8; 1601#endif 1602} 1603 1604void set_gate_up(const SetArgs& sa, const float* x, int ldx, const int* row_idx, uint16_t* h16, int ldh, 1605 cudaStream_t s) { 1606#if !defined(STRATA_USE_HIP) 1607 if (sa.lay.K[0] != sa.lay.K[1]) { 1608 std::fprintf(stderr, "exl3 set_gate_up: gate K %d != up K %d\n", sa.lay.K[0], sa.lay.K[1]); 1609 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 1610 return; 1611 } 1612 if (sa.n_exp <= 0 || sa.max_rows <= 0) return; 1613 tc::GArgs a{}; 1614 a.wbase = sa.wbase; 1615 a.stride = sa.stride; 1616 for (int r = 0; r < 2; ++r) { 1617 a.tr[r] = sa.lay.trellis[r]; 1618 a.suh[r] = sa.lay.suh[r]; 1619 a.svh[r] = sa.lay.svh[r]; 1620 a.ld[r] = sa.n_ff / 16; 1621 } 1622 a.bounds = sa.bounds; 1623 a.row0 = sa.row0; 1624 a.k = sa.n_embd; 1625 a.n = sa.n_ff; 1626 a.xf = x; 1627 a.idx = row_idx; 1628 a.ldx = ldx; 1629 a.h = (__half*) h16; 1630 a.ldh = ldh; 1631 a.limit = sa.limit; 1632 const dim3 grid((unsigned) ((sa.max_rows + tc::BM - 1) / tc::BM), (unsigned) (sa.n_ff / kCols), (unsigned) sa.n_exp); 1633 if (!dispatch<RunGateUp>(sa.lay.K[0], sa.lay.cb, a, grid, s)) std::fprintf(stderr, "exl3 set_gate_up: K\n"); 1634 launch_check("set_gate_up"); 1635#else 1636 (void) sa; (void) x; (void) ldx; (void) row_idx; (void) h16; (void) ldh; (void) s; 1637#endif 1638} 1639 1640void set_down(const SetArgs& sa, const uint16_t* h16, int ldh, float* y, int ldy, cudaStream_t s) { 1641#if !defined(STRATA_USE_HIP) 1642 if (sa.n_exp <= 0 || sa.max_rows <= 0) return; 1643 tc::GArgs a{}; 1644 a.wbase = sa.wbase; 1645 a.stride = sa.stride; 1646 a.tr[0] = sa.lay.trellis[2]; 1647 a.suh[0] = sa.lay.suh[2]; 1648 a.svh[0] = sa.lay.svh[2]; 1649 a.ld[0] = sa.n_embd / 16; 1650 a.bounds = sa.bounds; 1651 a.row0 = sa.row0; 1652 a.k = sa.n_ff; 1653 a.n = sa.n_embd; 1654 a.xh = (const __half*) h16; 1655 a.ldx = ldh; 1656 a.y = y; 1657 a.ldy = ldy; 1658 const dim3 grid((unsigned) ((sa.max_rows + tc::BM - 1) / tc::BM), (unsigned) (sa.n_embd / kCols), (unsigned) sa.n_exp); 1659 if (!dispatch<RunGemm>(sa.lay.K[2], sa.lay.cb, a, grid, s)) std::fprintf(stderr, "exl3 set_down: K\n"); 1660 launch_check("set_down"); 1661#else 1662 (void) sa; (void) h16; (void) ldh; (void) y; (void) ldy; (void) s; 1663#endif 1664} 1665 1666void gemm_rows(const Mat& m, const uint16_t* x16, int ldx, int rows, float* y, int ldy, float beta, cudaStream_t s) { 1667#if !defined(STRATA_USE_HIP) 1668 if (rows <= 0) return; 1669 tc::GArgs a{}; 1670 a.wbase = nullptr; 1671 a.tr[0] = (size_t) m.trellis; 1672 a.suh[0] = (size_t) m.suh; 1673 a.svh[0] = (size_t) m.svh; 1674 a.ld[0] = m.ld > 0 ? m.ld : m.n / 16; 1675 a.m = rows; 1676 a.k = m.k; 1677 a.n = m.n; 1678 a.xh = (const __half*) x16; 1679 a.ldx = ldx; 1680 a.y = y; 1681 a.ldy = ldy; 1682 a.beta = beta; 1683 const dim3 grid((unsigned) ((rows + tc::BM - 1) / tc::BM), (unsigned) (m.n / kCols), 1); 1684 if (!supported(m) || !dispatch<RunGemm>(m.K, m.cb, a, grid, s)) { 1685 std::fprintf(stderr, "exl3 gemm_rows: unsupported matrix\n"); 1686 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 1687 return; 1688 } 1689 launch_check("gemm_rows"); 1690#else 1691 (void) m; (void) x16; (void) ldx; (void) rows; (void) y; (void) ldy; (void) beta; (void) s; 1692#endif 1693} 1694 1695void reconstruct_rows(const Mat& m, uint16_t* dst, bool bf16, cudaStream_t s) { 1696 if (!supported(m) || !dispatch<RunRows>(m.K, m.cb, m, dst, bf16, s)) { 1697 std::fprintf(stderr, "exl3 reconstruct_rows: unsupported matrix\n"); 1698 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 1699 return; 1700 } 1701 launch_check("reconstruct_rows"); 1702} 1703 1704void reconstruct_inner_rows(const Mat& m, uint16_t* dst, cudaStream_t s) { 1705 if (!supported(m) || !dispatch<RunInnerRows>(m.K, m.cb, m, dst, s)) { 1706 std::fprintf(stderr, "exl3 reconstruct_inner_rows: unsupported matrix\n"); 1707 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 1708 return; 1709 } 1710 launch_check("reconstruct_inner_rows"); 1711} 1712 1713void rows_rot_f16(const float* x, int ldx, const int* idx, int nrows, int ncols, const uint16_t* suh, uint16_t* out, 1714 cudaStream_t s) { 1715 if (nrows <= 0) return; 1716 const long long warps = (long long) nrows * (ncols / kCols); 1717 rows_rot_f16_kernel<<<(unsigned) ((warps + kWarps - 1) / kWarps), kThreads, 0, s>>>(x, ldx, idx, nrows, ncols, suh, 1718 out); 1719 launch_check("rows_rot_f16"); 1720} 1721 1722void rows_rot_out(float* y, int ldy, int nrows, int ncols, const uint16_t* svh, cudaStream_t s) { 1723 if (nrows <= 0) return; 1724 const long long warps = (long long) nrows * (ncols / kCols); 1725 rows_rot_out_kernel<<<(unsigned) ((warps + kWarps - 1) / kWarps), kThreads, 0, s>>>(y, ldy, nrows, ncols, svh); 1726 launch_check("rows_rot_out"); 1727} 1728 1729void rows_f16(const float* x, int ldx, const int* idx, int nrows, int ncols, uint16_t* out, cudaStream_t s) { 1730 if (nrows <= 0) return; 1731 rows_f16_kernel<<<dim3((unsigned) std::min(8, (ncols + 255) / 256), (unsigned) nrows), 256, 0, s>>>(x, ldx, idx, 1732 ncols, out); 1733 launch_check("rows_f16"); 1734} 1735 1736void reconstruct_inner(const Mat& m, uint16_t* dst, cudaStream_t s) { 1737 if (!supported(m) || !dispatch<RunInner>(m.K, m.cb, m, dst, s)) { 1738 std::fprintf(stderr, "exl3 reconstruct_inner: unsupported matrix\n"); 1739 g_launch_errors.fetch_add(1, std::memory_order_relaxed); 1740 return; 1741 } 1742 launch_check("reconstruct_inner"); 1743} 1744 1745} // namespace strata::dsv41k::exl3