okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
727890fde
main
1// src/qwen35/q36_engine.cu - strata-q36: the engine path for Qwen3.6-35B-A3B (GGUF architecture qwen35moe), 2// NEW-MODELS-PLAN.md T1. A driver of its own beside Flash-Next's (generate/verify/prefill stay untouched, so the 3// Flash-Next identity gate cannot move), built from Strata's kernels: 4// 5// * weights straight from the GGUF: dense Q8_0 / K-quant matrices in their blocks (native MMVQ), the 1-D tensors and 6// the F32 projections (ssm_alpha/beta, the router, the shared-expert gate) as f32, the routed experts repacked at 7// load into native expert blobs [gate | up | down] per (layer, expert) for `native_expert_grouped`; 8// * the plain pre-norm residual layer driver: x += mixer(rms(x) * attn_norm); x += moe(rms(x) * post_attention_norm); 9// * GDN: fused conv + L2 and the fused step with the SiLU-gated norm (per token, the state carried); 10// * attention without an indexer: dense, 16 query heads over 2 KV heads, split-K over 256-cell chunks with a 11// log-sum-exp merge, causal for a batch of queries (the prompt) and for one (decode); 12// * MoE: the native router (256 / top-8), the experts grouped per expert on the device (one weight read per expert 13// for the whole batch), the shared expert with its sigmoid gate, the native combine; 14// * the prompt read in chunks of --chunk tokens through the same driver (batched matmuls, ncols <= 8 per launch); 15// * decode one token at a time from a captured graph (positions on the device), or with --no-graph eagerly. 16// 17// Modes: --serve (serve/server.py's engine protocol: READY / GEN / T / DONE / STOP / PP), --tokens IDS [--n N] 18// [--force IDS] [--dump-full-logits F] (tools/qwen35/kl.py's reference interface), --bench-pp N / --bench-tg N. 19#include "strata/artifact/gguf_reader.hpp" 20#include "strata/core/family_layout.hpp" 21#include "strata/kernels/fused_gdn.hpp" 22#include "strata/kernels/iq_kernels.hpp" 23#include "strata/kernels/native_mmvq.hpp" 24#include "strata/kernels/native_moe.hpp" 25#include "strata/kernels/native_router.hpp" 26#include "strata/kernels/q36_prompt_route.hpp" 27#include "strata/prefill/gemm.hpp" 28#include "strata/prefill/moe_fused.hpp" 29#include "strata/prefill/fused_tile_rule.hpp" 30#include "strata/prefill/moe_fused_q36.hpp" 31#include "strata/prefill/mmq_ids_margin.hpp" 32#include "strata/prefill/moe_mmq.hpp" 33#include "strata/qwen35/context_fit.hpp" 34#include "strata/qwen35/engine.hpp" 35#include "strata/qwen35/sampling.hpp" 36#include "q36_kernels.cuh" 37#if defined(STRATA_Q36_CPU_POOL) 38#include "strata/kernels/cpu/native_expert.hpp" 39#include "strata/kernels/cpu/pool.hpp" 40#endif 41 42#include <cublas_v2.h> 43#include <cuda_fp16.h> 44#include <cuda_runtime.h> 45 46#include <algorithm> 47#include <cctype> 48#include <atomic> 49#include <chrono> 50#include <cmath> 51#include <condition_variable> 52#include <cstdint> 53#include <cstdio> 54#include <cstdlib> 55#include <cstring> 56#include <deque> 57#include <functional> 58#include <iostream> 59#include <map> 60#include <memory> 61#include <mutex> 62#include <random> 63#include <string> 64#include <thread> 65#include <tuple> 66#include <type_traits> 67#include <vector> 68 69namespace { 70 71namespace K = strata::kernels; 72namespace MMQ = strata::prefill::mmq; 73namespace PF = strata::prefill::fused; // the grouping and the int8 sizes (shape-free) 74namespace FQ = strata::prefill::fused_q36; // the fused kernels for Qwen3.6's shape (CUDA) 75 76#define CK(x) \ 77 do { \ 78 cudaError_t e_ = (x); \ 79 if (e_ != cudaSuccess) { \ 80 std::fprintf(stderr, "strata-q36: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \ 81 std::exit(1); \ 82 } \ 83 } while (0) 84 85using Clock = std::chrono::steady_clock; 86double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); } 87 88constexpr int kThreads = 256; 89constexpr int kChunkCells = 256; // attention split-K chunk 90constexpr int kConvTile = 16; // tokens per block of the prompt conv (k_conv_seq tile mode) 91 92// ------------------------------------------------------------------------------------------------ small kernels 93__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } 94__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } 95__device__ __forceinline__ float softplus(float v) { return v > 20.f ? v : log1pf(expf(v)); } 96 97__device__ float block_sum(float v, float* sh) { 98 sh[threadIdx.x] = v; 99 __syncthreads(); 100 for (int s = blockDim.x / 2; s > 0; s >>= 1) { 101 if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s]; 102 __syncthreads(); 103 } 104 const float r = sh[0]; 105 __syncthreads(); 106 return r; 107} 108__device__ float block_max(float v, float* sh) { 109 sh[threadIdx.x] = v; 110 __syncthreads(); 111 for (int s = blockDim.x / 2; s > 0; s >>= 1) { 112 if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]); 113 __syncthreads(); 114 } 115 const float r = sh[0]; 116 __syncthreads(); 117 return r; 118} 119 120/// y[r] = rms(x[r]) * w, one block per row of n. 121__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) { 122 __shared__ float sh[kThreads]; 123 const float* xr = x + (size_t) blockIdx.x * n; 124 float* yr = y + (size_t) blockIdx.x * n; 125 float s = 0.f; 126 for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; 127 s = block_sum(s, sh); 128 const float r = rsqrtf(s / (float) n + eps); 129 for (int i = threadIdx.x; i < n; i += blockDim.x) yr[i] = xr[i] * r * w[i]; 130} 131/// x[r] += y[r]; h[r] = rms(x[r]) * w (one block per row of n): the residual add and the next norm in one launch. 132/// out[r * ld_out + i] = rms(x[r * ldx + ..]) * w (one block per row of n): a norm into a slice of a wider row. 133__global__ void k_rms_ld(const float* x, int ldx, const float* w, float* out, int ld_out, int n, float eps) { 134 __shared__ float sh[kThreads]; 135 const float* xr = x + (size_t) blockIdx.x * ldx; 136 float* yr = out + (size_t) blockIdx.x * ld_out; 137 float s = 0.f; 138 for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; 139 s = block_sum(s, sh); 140 const float r = rsqrtf(s / (float) n + eps); 141 for (int i = threadIdx.x; i < n; i += blockDim.x) yr[i] = xr[i] * r * w[i]; 142} 143__global__ void k_add_rms(float* x, const float* y, const float* w, float* h, int n, float eps) { 144 __shared__ float sh[kThreads]; 145 float* xr = x + (size_t) blockIdx.x * n; 146 const float* yr = y + (size_t) blockIdx.x * n; 147 float* hr = h + (size_t) blockIdx.x * n; 148 float s = 0.f; 149 for (int i = threadIdx.x; i < n; i += blockDim.x) { 150 const float v = xr[i] + yr[i]; 151 xr[i] = v; 152 s += v * v; 153 } 154 s = block_sum(s, sh); 155 const float r = rsqrtf(s / (float) n + eps); 156 for (int i = threadIdx.x; i < n; i += blockDim.x) hr[i] = xr[i] * r * w[i]; 157} 158/// The MoE block's end for one token row (block per row): x += sum_k w_k part_k (in pick order, FMA after the first 159/// product, as native_moe_combine) + sigmoid(sgate) * shared; then, with `wn`, h = rms(x) * wn (the next layer's 160/// attention norm). Replaces combine + gate + add + rms. 161__global__ void k_moe_out(float* x, const float* parts, const int32_t* prow, const float* wts, int K_, 162 const float* shared, const float* sgate, int sg_stride, const float* wn, float* h, int n, 163 float eps) { 164 __shared__ float sh[kThreads]; 165 __shared__ const float* pk[16]; 166 const int t = blockIdx.x; 167 float* xr = x + (size_t) t * n; 168 if (threadIdx.x < K_) // pick k's row: t * K + k, or its sorted row (`prow`, the prompt's MMQ order) 169 pk[threadIdx.x] = parts + (size_t) (prow ? prow[t * K_ + threadIdx.x] : t * K_ + threadIdx.x) * n; 170 __syncthreads(); 171 const float* wr = wts + (size_t) t * K_; 172 const float gs = sigm(sgate[(size_t) t * sg_stride]); 173 float s = 0.f; 174 for (int i = threadIdx.x; i < n; i += blockDim.x) { 175 float acc = wr[0] * pk[0][i]; 176 for (int k = 1; k < K_; ++k) acc = fmaf(wr[k], pk[k][i], acc); 177 acc += gs * shared[(size_t) t * n + i]; 178 const float v = xr[i] + acc; 179 xr[i] = v; 180 s += v * v; 181 } 182 if (wn == nullptr) return; 183 s = block_sum(s, sh); 184 const float r = rsqrtf(s / (float) n + eps); 185 for (int i = threadIdx.x; i < n; i += blockDim.x) h[(size_t) t * n + i] = xr[i] * r * wn[i]; 186} 187/// GDN alpha and beta for T <= 8 rows in one launch, their epilogues applied: rows [0, HV) of the output are 188/// softplus(alpha . x + dt) * ssm_a, rows [HV, 2 HV) sigmoid(beta . x). Warp per row (grid (ceil(2 HV / 8), T)). 189__global__ void k_gdn_ab(const float* Wa, const float* Wb, const float* x, const float* dt, const float* ssm_a, 190 float* alpha, float* beta, int n_in, int HV) { 191 const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; 192 const int o = blockIdx.x * 8 + warp; 193 if (o >= 2 * HV) return; 194 const bool isb = o >= HV; 195 const int r = isb ? o - HV : o; 196 const float4* wr = (const float4*) ((isb ? Wb : Wa) + (size_t) r * n_in); 197 const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); 198 float acc = 0.f; 199 for (int i = lane; i < n_in / 4; i += 32) { 200 const float4 a = wr[i], b = xr[i]; 201 acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; 202 } 203 for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); 204 if (lane != 0) return; 205 if (isb) beta[(size_t) blockIdx.y * HV + r] = sigm(acc); 206 else alpha[(size_t) blockIdx.y * HV + r] = softplus(acc + dt[r]) * ssm_a[r]; 207} 208__global__ void k_add(float* x, const float* y, int64_t n) { 209 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 210 if (i < n) x[i] += y[i]; 211} 212__global__ void k_swiglu(const float* g, const float* u, float* h, int64_t n) { 213 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 214 if (i < n) h[i] = silu(g[i]) * u[i]; 215} 216/// y[t][o] = W[o] . x[t] for f32 W [n_out][n_in], n_in a multiple of 128: one warp per row, float4 loads, 8 rows per 217/// block (grid (ceil(n_out / 8), T)). 218__global__ void k_gemv_f32(const float* W, const float* x, float* y, int n_in, int n_out) { 219 const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; 220 const int o = blockIdx.x * 8 + warp; 221 if (o >= n_out) return; 222 const float4* wr = (const float4*) (W + (size_t) o * n_in); 223 const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); 224 float acc = 0.f; 225 for (int i = lane; i < n_in / 4; i += 32) { 226 const float4 a = wr[i], b = xr[i]; 227 acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; 228 } 229 for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); 230 if (lane == 0) y[(size_t) blockIdx.y * n_out + o] = acc; 231} 232unsigned rows8(int n) { return (unsigned) ((n + 7) / 8); } 233/// GDN gate / beta in place for T rows of HV: alpha -> softplus(alpha + dt) * ssm_a, beta -> sigmoid(beta). 234__global__ void k_gdn_gb(float* alpha, const float* dt, const float* ssm_a, float* beta, int HV, int T) { 235 const int i = blockIdx.x * blockDim.x + threadIdx.x; 236 if (i >= HV * T) return; 237 const int h = i % HV; 238 alpha[i] = softplus(alpha[i] + dt[h]) * ssm_a[h]; 239 beta[i] = sigm(beta[i]); 240} 241/// sh[t] *= sigmoid(gate[t]) (the shared expert's scalar gate), rows of n. 242__global__ void k_gate_rows(float* sh, const float* gate, int n, int T) { 243 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 244 if (i >= (int64_t) n * T) return; 245 sh[i] *= sigm(gate[i / n]); 246} 247 248/// Batch rows (several sessions decoded in one window, one token each): row t reads and writes the cache of session 249/// slot[t] at cell[t]; its rotary position is cell[t] + delta[t]. Every field null: one session, the rows are its 250/// consecutive cells *pos0 + t (the prompt, a verify window, a decode step). 251struct RowSel { 252 const int32_t* cell = nullptr; // device [T] 253 const int32_t* slot = nullptr; // device [T] 254 const int32_t* delta = nullptr; // device [T] 255 float* const* kc = nullptr; // device [n_sessions]: this layer's K / V base of each session 256 float* const* vc = nullptr; 257}; 258 259/// The attention layer's per-token preparation for T rows at positions *pos0 + t: q (from the [q | gate] pairs) and k 260/// RMS-normed per head with their weights, NEOX RoPE over the first n_rot dims, k / v into the cache, the gate kept. 261/// Rotary position of a cell: the cell itself (text) plus *rdelta (what the pictures before a text run did not use 262/// of their cells, see mrope), or, with `mtab` (a request's prompt cells, device int32 [cell][3] = t, h, w), the 263/// interleaved M-RoPE position (llama.cpp's IMROPE with sections 11 / 11 / 10: pair p takes stream p % 3). 264/// grid (H + HKV, T), block 256 (HD <= 256). 265__global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, 266 float* q, float* gate, float* kc, float* vc, int H, int HKV, int HD, int n_rot, 267 const int32_t* pos0, int ctx, float base, float eps, const int32_t* rdelta, 268 const int32_t* mtab, RowSel rs) { 269 __shared__ float sh[kThreads]; 270 __shared__ float buf[256]; 271 const int head = blockIdx.x, t = blockIdx.y; 272 const int pos = rs.cell ? rs.cell[t] : *pos0 + t; 273 const int dl = rs.delta ? rs.delta[t] : (rdelta ? *rdelta : 0); 274 if (rs.kc) { 275 kc = rs.kc[rs.slot[t]]; 276 vc = rs.vc[rs.slot[t]]; 277 } 278 const bool isq = head < H; 279 const float* src = isq ? qg + ((size_t) t * H + head) * 2 * HD : kx + ((size_t) t * HKV + head - H) * HD; 280 const int i = threadIdx.x; 281 const float v0 = i < HD ? src[i] : 0.f; 282 const float s = block_sum(v0 * v0, sh); 283 const float r = rsqrtf(s / (float) HD + eps); 284 if (i < HD) buf[i] = v0 * r * (isq ? qw[i] : kw[i]); 285 __syncthreads(); 286 if (i >= HD) return; 287 float v = buf[i]; 288 const int half = n_rot / 2; 289 if (i < n_rot) { 290 const int p = i < half ? i : i - half; 291 const int rp = mtab ? __ldg(mtab + (size_t) pos * 3 + p % 3) : pos + dl; 292 const float theta = (float) rp * powf(base, -2.0f * (float) p / (float) n_rot); 293 float sn, cs; 294 sincosf(theta, &sn, &cs); 295 v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; 296 } 297 if (isq) { 298 q[((size_t) t * H + head) * HD + i] = v; 299 gate[((size_t) t * H + head) * HD + i] = qg[((size_t) t * H + head) * 2 * HD + HD + i]; 300 } else { 301 const int kh = head - H; 302 kc[((size_t) kh * ctx + pos) * HD + i] = v; 303 vc[((size_t) kh * ctx + pos) * HD + i] = vx[((size_t) t * HKV + kh) * HD + i]; 304 } 305} 306 307/// Split-K attention, one block per (chunk of 256 cells, query row): query row qi = t * H + h (t from t0) sees the 308/// cells [0, *pos0 + t]. Writes the chunk's partial accumulator, max and sum; chunks past the query's cells write 309/// nothing (the merge stops before them). grid (n_chunk, n_rows), block 256, HD == 256. 310__global__ void k_attn_part(const float* q, const float* kc, const float* vc, const int32_t* pos0, int t0, int H, 311 int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl, RowSel rs) { 312 constexpr int HD = 256; 313 __shared__ float qs[HD], sc[kChunkCells], sh[kThreads]; 314 const int c = blockIdx.x, row = blockIdx.y; 315 const int t = t0 + row / H, h = row % H, kvh = h / (H / HKV); 316 const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; 317 if (rs.kc) { 318 kc = rs.kc[rs.slot[t]]; 319 vc = rs.vc[rs.slot[t]]; 320 } 321 const int p0 = c * kChunkCells; 322 if (p0 >= npos) return; 323 const int j = threadIdx.x; 324 qs[j] = q[((size_t) t * H + h) * HD + j]; 325 __syncthreads(); 326 const int p = p0 + j; 327 float s = -INFINITY; 328 if (p < npos) { 329 const float* kp = kc + ((size_t) kvh * ctx + p) * HD; 330 float a = 0.f; 331 for (int i = 0; i < HD; ++i) a += qs[i] * kp[i]; 332 s = a * scale; 333 } 334 const float m = block_max(s, sh); 335 const float e = p < npos ? expf(s - m) : 0.f; 336 sc[j] = e; 337 const float l = block_sum(e, sh); 338 const int n = min(kChunkCells, npos - p0); 339 float acc = 0.f; 340 const float* vp = vc + ((size_t) kvh * ctx + p0) * HD + j; 341 for (int k = 0; k < n; ++k) acc += sc[k] * vp[(size_t) k * HD]; 342 const size_t o = (size_t) row * n_chunk + c; 343 pacc[o * HD + j] = acc; 344 if (j == 0) { 345 pm[o] = m; 346 pl[o] = l; 347 } 348} 349/// The chunks merged, times sigmoid(gate): grid (n_rows), block HD. 350__global__ void k_attn_merge(const float* pacc, const float* pm, const float* pl, const float* gate, 351 const int32_t* pos0, int t0, int H, int n_chunk, float* out, RowSel rs) { 352 constexpr int HD = 256; 353 const int row = blockIdx.x, t = t0 + row / H, h = row % H, d = threadIdx.x; 354 const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; 355 const int nc = (npos + kChunkCells - 1) / kChunkCells; 356 float M = -INFINITY; 357 for (int c = 0; c < nc; ++c) M = fmaxf(M, pm[(size_t) row * n_chunk + c]); 358 float num = 0.f, den = 0.f; 359 for (int c = 0; c < nc; ++c) { 360 const size_t o = (size_t) row * n_chunk + c; 361 const float w = expf(pm[o] - M); 362 num += w * pacc[o * HD + d]; 363 den += w * pl[o]; 364 } 365 const size_t gi = ((size_t) t * H + h) * HD + d; 366 out[gi] = num / den * sigm(gate[gi]); 367} 368 369/// The routed entries (T tokens x K picks, entry e = t * K + k) grouped per expert, on the device: one group per 370/// expert used (ascending id), its blob address, its entries in entry order. One block. 371__global__ void k_group(const int32_t* ids, int n_ent, int K_, int n_expert, const uint8_t* blobs, unsigned long long blob, 372 unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups, int32_t* ent_dst, 373 int32_t* ent_tok) { 374 __shared__ int cnt[512], off[512]; 375 for (int x = threadIdx.x; x < n_expert; x += blockDim.x) cnt[x] = 0; 376 __syncthreads(); 377 for (int e = threadIdx.x; e < n_ent; e += blockDim.x) atomicAdd(&cnt[ids[e]], 1); 378 __syncthreads(); 379 if (threadIdx.x == 0) { 380 int g = 0, pos = 0; 381 for (int x = 0; x < n_expert; ++x) { 382 off[x] = pos; 383 if (cnt[x] == 0) continue; 384 grp_ptr[g] = (unsigned long long) (blobs + (size_t) x * blob); 385 grp_start[g] = pos; 386 pos += cnt[x]; 387 ++g; 388 } 389 grp_start[g] = pos; 390 *n_groups = g; 391 for (int e = 0; e < n_ent; ++e) { 392 const int p = off[ids[e]]++; 393 ent_dst[p] = e; 394 ent_tok[p] = e / K_; 395 } 396 } 397} 398/// k_group for the hybrid mode: only the entries whose expert has a VRAM slot (slot_of[x] >= 0) are grouped, each 399/// group's blob at blobs + slot * blob; the others are the CPU pool's (their rows come from k_merge_cpu). One block. 400__global__ void k_group_hy(const int32_t* ids, int n_ent, int K_, int n_expert, const int32_t* slot_of, 401 const uint8_t* blobs, unsigned long long blob, unsigned long long* grp_ptr, int32_t* grp_start, 402 int32_t* n_groups, int32_t* ent_dst, int32_t* ent_tok) { 403 __shared__ int cnt[512], off[512]; 404 for (int x = threadIdx.x; x < n_expert; x += blockDim.x) cnt[x] = 0; 405 __syncthreads(); 406 for (int e = threadIdx.x; e < n_ent; e += blockDim.x) 407 if (slot_of[ids[e]] >= 0) atomicAdd(&cnt[ids[e]], 1); 408 __syncthreads(); 409 if (threadIdx.x == 0) { 410 int g = 0, pos = 0; 411 for (int x = 0; x < n_expert; ++x) { 412 off[x] = pos; 413 if (cnt[x] == 0) continue; 414 grp_ptr[g] = (unsigned long long) (blobs + (size_t) slot_of[x] * blob); 415 grp_start[g] = pos; 416 pos += cnt[x]; 417 ++g; 418 } 419 grp_start[g] = pos; 420 *n_groups = g; 421 for (int e = 0; e < n_ent; ++e) { 422 if (slot_of[ids[e]] < 0) continue; 423 const int p = off[ids[e]]++; 424 ent_dst[p] = e; 425 ent_tok[p] = e / K_; 426 } 427 } 428} 429/// The CPU pool's expert rows into the entries' rows: parts[e] = cpu[e] where miss[e]. grid (n_ent), block 256. 430__global__ void k_merge_cpu(float* parts, const float* cpu, const int32_t* miss, int n) { 431 const int e = blockIdx.x; 432 if (!miss[e]) return; 433 for (int i = threadIdx.x; i < n; i += blockDim.x) parts[(size_t) e * n + i] = cpu[(size_t) e * n + i]; 434} 435/// The prompt attention's FP16 operands: cells [0, P) of each KV head's K / V (cache rows ctx apart) into compact 436/// [kvh][P][HD] halves. grid1(HKV * P * HD). 437__global__ void k_kv_f16(const float* kc, const float* vc, __half* k16, __half* v16, int ctx, int P, int HD, int HKV) { 438 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 439 if (i >= (int64_t) HKV * P * HD) return; 440 const int64_t per = (int64_t) P * HD; 441 const int64_t kvh = i / per, rest = i % per; 442 const size_t src = (size_t) kvh * ctx * HD + rest; 443 k16[i] = __float2half(kc[src]); 444 v16[i] = __float2half(vc[src]); 445} 446/// The prompt's causal softmax: row (h, t) of S (ld floats, P cells) -> softmax(S * scale) over the cells 447/// [0, pos0 + t], 0 past them, as FP16 probabilities (S16, the same row offsets, ld halves). grid (T, H), block 256. 448__global__ void k_attn_softmax16(const float* S, __half* S16, int ld, int T, int P, int pos0, float scale) { 449 __shared__ float sh[kThreads]; 450 const int t = blockIdx.x, h = blockIdx.y; 451 const float* row = S + ((size_t) h * T + t) * ld; 452 __half* out = S16 + ((size_t) h * T + t) * ld; 453 const int n = min(P, pos0 + t + 1); 454 float mx = -INFINITY; 455 for (int p = threadIdx.x; p < n; p += blockDim.x) mx = fmaxf(mx, row[p] * scale); 456 mx = block_max(mx, sh); 457 float sum = 0.f; 458 for (int p = threadIdx.x; p < n; p += blockDim.x) sum += expf(row[p] * scale - mx); 459 sum = block_sum(sum, sh); 460 const float inv = 1.0f / sum; 461 for (int p = threadIdx.x; p < P; p += blockDim.x) out[p] = __float2half(p < n ? expf(row[p] * scale - mx) * inv : 0.f); 462} 463/// att *= sigmoid(gate) (the attention output gate), n values. 464__global__ void k_gate_mul(float* att, const float* gate, int64_t n) { 465 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 466 if (i < n) att[i] *= sigm(gate[i]); 467} 468 469/// Picture rows over the embeddings of a chunk: x[r] = img[map[r]] for the rows with map[r] >= 0 (the rows of a picture's 470/// <|image_pad|> cells). grid (T), block 256. 471__global__ void k_put_rows(float* x, const float* img, const int32_t* map, int n) { 472 const int r = blockIdx.x; 473 const int m = map[r]; 474 if (m < 0) return; 475 for (int i = threadIdx.x; i < n; i += blockDim.x) x[(size_t) r * n + i] = img[(size_t) m * n + i]; 476} 477 478/// The prompt's routed entries sorted by expert for MMQ: bounds[x] .. bounds[x + 1] are expert x's rows; sorted row r 479/// holds entry dst[r] (= t * K + k, the row of the per-slot outputs) of token src[r]. The order inside an expert is the 480/// atomics' (no output depends on it: every row's products are its own). cnt / cur: n_expert ints of scratch. 481__global__ void k_route_count(const int32_t* ids, int n_ent, int32_t* cnt) { 482 const int e = blockIdx.x * blockDim.x + threadIdx.x; 483 if (e < n_ent) atomicAdd(&cnt[ids[e]], 1); 484} 485__global__ void k_route_scan(const int32_t* cnt, int n_expert, int32_t* bounds, int32_t* cur, int32_t* max_rows) { 486 if (threadIdx.x != 0) return; 487 int pos = 0, mx = 0; 488 for (int x = 0; x < n_expert; ++x) { 489 bounds[x] = pos; 490 cur[x] = pos; 491 pos += cnt[x]; 492 mx = max(mx, cnt[x]); 493 } 494 bounds[n_expert] = pos; 495 *max_rows = mx; 496} 497__global__ void k_route_scatter(const int32_t* ids, int n_ent, int K_, int32_t* cur, int32_t* dst, int32_t* src, 498 int32_t* inv) { 499 const int e = blockIdx.x * blockDim.x + threadIdx.x; 500 if (e >= n_ent) return; 501 const int r = atomicAdd(&cur[ids[e]], 1); 502 dst[r] = e; 503 src[r] = e / K_; 504 inv[e] = r; // entry e's sorted row: where its down product lands 505} 506 507/// The greedy pick of one logits row: out = argmax (lowest id on ties). Stage 1: `gridDim.x` blocks each write the 508/// best of their stride into (pv, pi); stage 2 (one block, n = the stage-1 block count) reads those. 509__global__ void k_argmax(const float* x, int n, int32_t* out, float* pv, int32_t* pi, bool stage2) { 510 __shared__ float bv[kThreads]; 511 __shared__ int bi[kThreads]; 512 // row blockIdx.y: its logits (stage 1, n = the vocabulary) and its kArgBlocks partials 513 x += (size_t) blockIdx.y * (stage2 ? 0 : n); 514 pv += (size_t) blockIdx.y * 128; 515 pi += (size_t) blockIdx.y * 128; 516 out += blockIdx.y; 517 float v = -INFINITY; 518 int id = 0x7fffffff; 519 if (stage2) { 520 for (int i = threadIdx.x; i < n; i += blockDim.x) 521 if (pv[i] > v || (pv[i] == v && pi[i] < id)) { v = pv[i]; id = pi[i]; } 522 } else { 523 for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) 524 if (x[i] > v) { v = x[i]; id = i; } 525 } 526 bv[threadIdx.x] = v; 527 bi[threadIdx.x] = id; 528 __syncthreads(); 529 for (int s = blockDim.x / 2; s > 0; s >>= 1) { 530 if ((int) threadIdx.x < s) { 531 const float ov = bv[threadIdx.x + s]; 532 const int oi = bi[threadIdx.x + s]; 533 if (ov > bv[threadIdx.x] || (ov == bv[threadIdx.x] && oi < bi[threadIdx.x])) { 534 bv[threadIdx.x] = ov; 535 bi[threadIdx.x] = oi; 536 } 537 } 538 __syncthreads(); 539 } 540 if (threadIdx.x == 0) { 541 if (stage2) *out = bi[0]; 542 else { pv[blockIdx.x] = bv[0]; pi[blockIdx.x] = bi[0]; } 543 } 544} 545constexpr int kArgBlocks = 128; // (the row stride of k_argmax's partials) 546 547unsigned grid1(int64_t n, int b = kThreads) { return (unsigned) ((n + b - 1) / b); } 548 549/// out[t][o] = W[o] . x[t] in FP32 for a prompt chunk's small F32 projections (the router, the GDN alpha / beta, 550/// the shared expert's gate: n_out <= 256): a (16 TM) x 64 output tile per block, K in steps of 16 through shared 551/// memory, TM x 4 outputs per thread (TM = 4 for the router, 1 for the 32-wide alpha / beta: more blocks). hipBLAS 552/// picked 8 x 8 / 16 x 16 tiles for these shapes (~10% of a prompt). K % 4 == 0. 553template <int TM> 554__global__ void __launch_bounds__(256) k_sgemm_nt(const float* __restrict__ W, const float* __restrict__ x, 555 float* __restrict__ out, int K, int n_out, int T, int ldo, int kz) { 556 constexpr int BM = 16 * TM, BN = 64, BK = 16; 557 const int kb = blockIdx.z * kz, ke = min(K, kb + kz); // split-K: this block's K range, its own partial 558 out += (size_t) blockIdx.z * T * ldo; 559 __shared__ float As[BK][BM + 4], Bs[BK][BN + 4]; 560 const int tid = threadIdx.x; 561 const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; 562 const int tm = (tid / 16) * TM, tn = (tid % 16) * 4; 563 const int lr = tid / 4, lk = (tid % 4) * 4; // this thread's loads: row lr of each tile, k lk .. lk + 3 564 float acc[TM][4] = {}; 565 for (int k0 = kb; k0 < ke; k0 += BK) { 566 if (lr < BM) { 567 float4 a = make_float4(0.f, 0.f, 0.f, 0.f); 568 if (m0 + lr < T && k0 + lk < ke) a = *reinterpret_cast<const float4*>(x + (size_t) (m0 + lr) * K + k0 + lk); 569 As[lk][lr] = a.x; As[lk + 1][lr] = a.y; As[lk + 2][lr] = a.z; As[lk + 3][lr] = a.w; 570 } 571 float4 b = make_float4(0.f, 0.f, 0.f, 0.f); 572 if (n0 + lr < n_out && k0 + lk < ke) b = *reinterpret_cast<const float4*>(W + (size_t) (n0 + lr) * K + k0 + lk); 573 Bs[lk][lr] = b.x; Bs[lk + 1][lr] = b.y; Bs[lk + 2][lr] = b.z; Bs[lk + 3][lr] = b.w; 574 __syncthreads(); 575#pragma unroll 576 for (int k = 0; k < BK; ++k) { 577 float ar[TM]; 578#pragma unroll 579 for (int i = 0; i < TM; ++i) ar[i] = As[k][tm + i]; 580 const float4 bv = *reinterpret_cast<const float4*>(&Bs[k][tn]); 581 const float br[4] = {bv.x, bv.y, bv.z, bv.w}; 582#pragma unroll 583 for (int i = 0; i < TM; ++i) 584#pragma unroll 585 for (int j = 0; j < 4; ++j) acc[i][j] = fmaf(ar[i], br[j], acc[i][j]); 586 } 587 __syncthreads(); 588 } 589#pragma unroll 590 for (int i = 0; i < TM; ++i) 591#pragma unroll 592 for (int j = 0; j < 4; ++j) 593 if (m0 + tm + i < T && n0 + tn + j < n_out) out[(size_t) (m0 + tm + i) * ldo + n0 + tn + j] = acc[i][j]; 594} 595 596/// out[i] = the sum of the split-K partials part[z][i] in order (deterministic), n values each. 597__global__ void k_sum_splits(const float* part, float* out, int64_t n, int splits) { 598 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 599 if (i >= n) return; 600 float a = 0.f; 601 for (int z = 0; z < splits; ++z) a += part[(size_t) z * n + i]; 602 out[i] = a; 603} 604 605/// x f32 -> FP16 bits (the prompt GEMMs' activations). 606__global__ void k_to_f16(const float* x, __half* y, int64_t n) { 607 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 608 if (i < n) y[i] = __float2half(x[i]); 609} 610 611/// The GDN conv for T tokens in ONE launch (the prompt): one block per 128-channel head, thread = channel, the 612/// 3-entry history carried in registers across the tokens and written back at the end; SiLU, then the L2 norm of the 613/// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. 614__global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, 615 int qk_heads, float eps, int T, bool write, 616 float* const* hist_tab = nullptr, const int32_t* slot_rows = nullptr, 617 const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { 618 __shared__ float part[4]; 619 if (hist_tab) { // batch rows, grid y = group: group g's history is session slot_rows[g]'s; its rows are 620 // grow0[g] .. + gcnt[g] - 1 (one row at row g when there are no group arrays) 621 const int g = blockIdx.y, r0 = grow0 ? grow0[g] : g; 622 hist = hist_tab[slot_rows[g]]; 623 if (gcnt) T = gcnt[g]; 624 qkv += (size_t) r0 * C; 625 h += (size_t) r0 * C; 626 } 627 const int c = blockIdx.x * 128 + threadIdx.x; 628 float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; 629 // TILE mode (a prompt chunk: grid y > 1, no batch tables): the tiles of kConvTile tokens run side by side. A tile's history 630 // is the three inputs before its first token (exactly the values the sequential loop carries); tile 0 reads the old history, 631 // and, as the only writer, stores the new one: the last three of (old history, inputs). The arithmetic per token is the same. 632 int t_first = 0, t_end = T; 633 const bool tiled = hist_tab == nullptr && gridDim.y > 1; 634 if (tiled) { 635 t_first = (int) blockIdx.y * kConvTile; 636 t_end = min(T, t_first + kConvTile); 637 if (t_first == 0 && write) { 638 const float o0 = v0, o1 = v1, o2 = v2; 639 const float old3[3] = {o0, o1, o2}; 640 for (int k = 0; k < 3; ++k) { 641 const int idx = T - 3 + k; 642 hist[c * 3 + k] = idx >= 0 ? qkv[(size_t) idx * C + c] : old3[idx + 3]; 643 } 644 } 645 if (t_first > 0) { 646 v0 = qkv[(size_t) (t_first - 3) * C + c]; 647 v1 = qkv[(size_t) (t_first - 2) * C + c]; 648 v2 = qkv[(size_t) (t_first - 1) * C + c]; 649 } 650 if (t_first >= T) return; 651 } 652 const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; 653 const bool qk = (int) blockIdx.x < qk_heads; 654 for (int t = t_first; t < t_end; ++t) { 655 const float x = qkv[(size_t) t * C + c]; 656 const float sum = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; 657 v0 = v1; 658 v1 = v2; 659 v2 = x; 660 float y = sum / (1.0f + __expf(-sum)); 661 if (qk) { 662 float sq = y * y; 663 for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); 664 if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; 665 __syncthreads(); 666 const float ss = part[0] + part[1] + part[2] + part[3]; 667 __syncthreads(); 668 y *= rsqrtf(ss + eps); 669 } 670 h[(size_t) t * C + c] = y; 671 } 672 if (!write || tiled) return; // a verify window: the history is commit()'s to move; tiles: tile 0 stored it 673 hist[c * 3] = v0; 674 hist[c * 3 + 1] = v1; 675 hist[c * 3 + 2] = v2; 676} 677 678/// The gated delta rule + SiLU-gated norm for T tokens in ONE launch (the prompt): fused_gdn_step_norm's kernel 679/// (block = one V head, 128 columns x 4 row groups, state [row][head][col]) with its 32 state rows per thread kept in 680/// registers across the tokens. h (T, C) = q | k | v, gate / beta (T, HV), z / y (T, ZV). 681__global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, 682 const float* beta, const float* z, const float* gamma, float eps, 683 float* y, int h_k, int h_v, int T, bool write, 684 float* const* state_tab = nullptr, const int32_t* slot_rows = nullptr, 685 const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { 686 constexpr int S = 128, RG = 4, RPG = 32; 687 if (state_tab) { // batch rows, grid y = group (see k_conv_seq) 688 const int g = blockIdx.y, r = grow0 ? grow0[g] : g; 689 state = state_tab[slot_rows[g]]; 690 if (gcnt) T = gcnt[g]; 691 h += (size_t) r * C; 692 gate += (size_t) r * h_v; 693 beta += (size_t) r * h_v; 694 z += (size_t) r * h_v * S; 695 if (y) y += (size_t) r * h_v * S; 696 } 697 __shared__ float sk[S], sq[S]; 698 __shared__ float red_kv[RG][S]; 699 __shared__ float red_o[RG][S]; 700 __shared__ float wsum[S * RG / 32]; 701 const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; 702 const int qh = head % h_k; 703 const int ZV = h_v * S; 704 float s[RPG]; 705 float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; 706 const size_t row_stride = (size_t) h_v * S; 707#pragma unroll 708 for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; 709 for (int t = 0; t < T; ++t) { 710 const float* ht = h + (size_t) t * C; 711 if (tid < S) { sk[tid] = ht[h_k * S + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } 712 __syncthreads(); 713 const float g = __expf(gate[(size_t) t * h_v + head]); 714 float kv = 0.0f; 715#pragma unroll 716 for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); 717 red_kv[rg][col] = kv; 718 __syncthreads(); 719 const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col]; 720 const float delta = (ht[2 * h_k * S + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; 721 float o = 0.0f; 722#pragma unroll 723 for (int r = 0; r < RPG; ++r) { 724 s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); 725 o = fmaf(s[r], sq[rg * RPG + r], o); 726 } 727 red_o[rg][col] = o; 728 __syncthreads(); 729 float oc = 0.0f, sq_part = 0.0f; 730 if (rg == 0) { 731 oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) * rsqrtf((float) S); 732 sq_part = oc * oc; 733 } 734 for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); 735 if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; 736 __syncthreads(); 737 if (rg == 0 && y != nullptr) { // (the commit runs without outputs) 738 const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; 739 const float scale = rsqrtf(ss / (float) S + eps); 740 const float zz = z[(size_t) t * ZV + head * S + col]; 741 y[(size_t) t * ZV + head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz))); 742 } 743 __syncthreads(); // sk / sq / the reductions are rewritten by the next token 744 } 745 if (!write) return; // a verify window: the state is commit()'s to write 746#pragma unroll 747 for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; 748} 749 750/// The prompt's gated delta rule with more parallelism: a state column's update needs only that column (kv, delta and 751/// the output o all reduce over the rows), so a V head splits into kGdnColGroups blocks of 128 / kGdnColGroups columns, 752/// each with 16 row groups of 8 rows (512 threads, 8 state values per thread in registers). Writes the raw outputs 753/// o (T, HV * 128); k_gdn_norm applies the SiLU-gated RMS norm. grid (HV, kGdnColGroups), block (32, 16). 754constexpr int kGdnColGroups = 4; 755__global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* h, int C, const float* gate, 756 const float* beta, float* o_raw, int h_k, int h_v, int T) { 757 constexpr int S = 128, NC = S / kGdnColGroups, RG = 16, RPG = S / RG; 758 // two barriers per token (was three): sk / sq are double-buffered, and the output sum of token t is done after token t + 1's first 759 // barrier, off the chain of the recurrence (red_o is read between that barrier and the next one, written after it) 760 __shared__ float sk[2][S], sq[2][S]; 761 __shared__ float red_kv[RG][NC]; 762 __shared__ float red_o[RG][NC]; 763 const int head = blockIdx.x, cl = threadIdx.x, rg = threadIdx.y, tid = rg * NC + cl; 764 const int col = blockIdx.y * NC + cl; 765 const int qh = head % h_k; 766 float sv[RPG]; 767 float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; 768 const size_t row_stride = (size_t) h_v * S; 769#pragma unroll 770 for (int r = 0; r < RPG; ++r) sv[r] = base[r * row_stride]; 771 // the next token's inputs are loaded while this one is computed (the loads were the head of every iteration) 772 float nsk = 0.0f, nsq = 0.0f, nvv = 0.0f, ngate = 0.0f, nbeta = 0.0f; 773 auto load = [&](int t) { 774 const float* ht = h + (size_t) t * C; 775 if (tid < S) { nsk = ht[h_k * S + qh * S + tid]; nsq = ht[qh * S + tid]; } 776 nvv = ht[2 * h_k * S + head * S + col]; 777 ngate = gate[(size_t) t * h_v + head]; 778 nbeta = beta[(size_t) t * h_v + head]; 779 }; 780 if (T > 0) load(0); 781 for (int t = 0; t < T; ++t) { 782 const int par = t & 1; 783 if (tid < S) { sk[par][tid] = nsk; sq[par][tid] = nsq; } 784 const float vcur = nvv, gcur = ngate, bcur = nbeta; 785 if (t + 1 < T) load(t + 1); 786 __syncthreads(); 787 if (t > 0 && rg == 0) { // token t - 1's output 788 float oc = 0.0f; 789#pragma unroll 790 for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; 791 o_raw[(size_t) (t - 1) * h_v * S + head * S + col] = oc * rsqrtf((float) S); 792 } 793 const float g = __expf(gcur); 794 float kv = 0.0f; 795#pragma unroll 796 for (int r = 0; r < RPG; ++r) kv = fmaf(sv[r], sk[par][rg * RPG + r], kv); 797 red_kv[rg][cl] = kv; 798 __syncthreads(); 799 float kv_col = 0.0f; 800#pragma unroll 801 for (int i = 0; i < RG; ++i) kv_col += red_kv[i][cl]; 802 const float delta = (vcur - g * kv_col) * bcur; 803 float o = 0.0f; 804#pragma unroll 805 for (int r = 0; r < RPG; ++r) { 806 sv[r] = fmaf(g, sv[r], sk[par][rg * RPG + r] * delta); 807 o = fmaf(sv[r], sq[par][rg * RPG + r], o); 808 } 809 red_o[rg][cl] = o; 810 } 811 __syncthreads(); 812 if (T > 0 && rg == 0) { // the last token's output 813 float oc = 0.0f; 814#pragma unroll 815 for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; 816 o_raw[(size_t) (T - 1) * h_v * S + head * S + col] = oc * rsqrtf((float) S); 817 } 818#pragma unroll 819 for (int r = 0; r < RPG; ++r) base[r * row_stride] = sv[r]; 820} 821/// y = rms(o) * gamma * SiLU(z) per (token, V head): grid (HV, T), block 128. 822__global__ void __launch_bounds__(128) k_gdn_norm(const float* o_raw, const float* z, const float* gamma, float eps, 823 float* y, int h_v) { 824 __shared__ float part[4]; 825 const size_t i = ((size_t) blockIdx.y * h_v + blockIdx.x) * 128 + threadIdx.x; 826 const float oc = o_raw[i]; 827 float sq = oc * oc; 828 for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); 829 if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; 830 __syncthreads(); 831 const float ss = part[0] + part[1] + part[2] + part[3]; 832 const float scale = rsqrtf(ss / 128.0f + eps); 833 const float zz = z[i]; 834 y[i] = oc * scale * gamma[threadIdx.x] * (zz / (1.0f + __expf(-zz))); 835} 836 837// ------------------------------------------------------------------------------------------------ the model 838struct Mat { 839 const uint8_t* d = nullptr; // device, GGUF blocks 840 int type = -1; 841 int n_in = 0, n_out = 0; 842}; 843 844struct Layer { 845 bool attn = false; 846 const float *attn_norm = nullptr, *post_norm = nullptr; 847 // GDN 848 Mat qkv, zg, ssm_out; 849 const float *alpha = nullptr, *beta = nullptr, *dt = nullptr, *ssm_a = nullptr, *conv = nullptr, *ssm_norm = nullptr; 850 // attention 851 Mat wq, wk, wv, wo; 852 const float *q_norm = nullptr, *k_norm = nullptr; 853 // MoE 854 const float* router = nullptr; // [n_expert][N] f32 855 float* router_ext = nullptr; // the same with the shared expert's gate row appended: [n_expert + 1][N] 856 Mat sh_gate, sh_up, sh_down; 857 const float* sh_gate_inp = nullptr; // [N] 858 K::NativeExpertLayout L; 859 uint8_t* blobs = nullptr; // n_expert blobs, `stride` bytes apart (L.bytes rounded up to whole blocks of every 860 size_t stride = 0; // part's type, so MMQ can step over them by blocks), then kMmqTail zero bytes 861 // (hybrid mode: n_slots slots, see place_experts) 862 // the GGUF's expert tensors (the mapped file stays open): place_experts builds the blobs from them 863 const uint8_t *src_g = nullptr, *src_u = nullptr, *src_d = nullptr; 864 size_t src_gsz = 0, src_dsz = 0; 865 uint8_t* hblobs = nullptr; // hybrid mode: every expert's blob in host memory, `stride` apart 866 int n_slots = 0; // hybrid mode: the experts resident in VRAM 867}; 868 869struct Model { 870 strata::core::ModelGeometry g; 871 std::shared_ptr<strata::GgufModel> file; // kept mapped: the experts are placed after the engine's buffers 872 bool hybrid = false; // not every expert fits in VRAM: slots + the CPU pool 873 // the packed Q8_0 decode copies (gguf weights, packed copy, bytes): given back when that lets every expert fit 874 std::vector<std::tuple<const uint8_t*, uint8_t*, size_t>> packed; 875 // the GGUF-native MTP block (blk.<n_layers>, loaded with --mtp): eh_proj over [enorm(e) | hnorm(h)], then an 876 // attention + MoE layer, shared_head_norm, the main head 877 bool has_mtp = false; 878 Layer mtp; 879 Mat eh_proj; 880 const float *mtp_enorm = nullptr, *mtp_hnorm = nullptr, *mtp_shnorm = nullptr; 881 int64_t top_k = 8; 882 float eps = 1e-6f, rope_base = 1e7f; 883 int n_rot = 64; 884 std::vector<Layer> layers; 885 const float* out_norm = nullptr; 886 Mat head; 887 const uint8_t* embd = nullptr; 888 int embd_type = -1; 889 size_t embd_row = 0; 890}; 891 892constexpr size_t kMmqTail = 4096; 893size_t gcd_sz(size_t a, size_t b) { return b ? gcd_sz(b, a % b) : a; } 894size_t lcm_sz(size_t a, size_t b) { return a / gcd_sz(a, b) * b; } 895size_t block_bytes(int type) { 896 int be = 0, bb = 0; 897 return strata::block_geometry((uint32_t) type, be, bb) ? (size_t) bb : 1; 898} // zeroed bytes after the last expert (MMQ reads a little past a matrix) 899 900size_t row_bytes(int type, int64_t n) { 901 int be = 0, bb = 0; 902 if (!strata::block_geometry((uint32_t) type, be, bb)) return 0; 903 return (size_t) (n / be) * (size_t) bb; 904} 905 906float bf16_to_f32(uint16_t b) { 907 const uint32_t u = (uint32_t) b << 16; 908 float f; 909 std::memcpy(&f, &u, 4); 910 return f; 911} 912 913// IEEE binary16 -> f32 by hand. __ushort_as_half is a __device__ intrinsic and 914// upload_f32 runs on the host, so a CUDA toolkit older than 12.5 refuses the 915// call; widen the bits here instead, the way bf16_to_f32 does. 916float f16_to_f32(uint16_t h) { 917 const uint32_t sign = (uint32_t) (h & 0x8000) << 16; 918 const uint32_t exponent = (h >> 10) & 0x1f; 919 const uint32_t mantissa = h & 0x3ff; 920 uint32_t u; 921 if (exponent == 0) { 922 if (mantissa == 0) { 923 u = sign; // +-0 924 } else { 925 uint32_t m = mantissa, shift = 0; // subnormal: normalize it 926 while ((m & 0x400) == 0) { 927 m <<= 1; 928 ++shift; 929 } 930 u = sign | ((uint32_t) (127 - 14 - shift) << 23) | ((m & 0x3ff) << 13); 931 } 932 } else if (exponent == 0x1f) { 933 u = sign | 0x7f800000u | (mantissa << 13); // inf / nan 934 } else { 935 u = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13); 936 } 937 float f; 938 std::memcpy(&f, &u, 4); 939 return f; 940} 941 942/// A tensor as f32 on the device (F32 as it is, BF16 / F16 widened). 943float* upload_f32(const strata::TensorInfo& t, const uint8_t* src) { 944 std::vector<float> h((size_t) t.elements()); 945 if (t.type == 0) std::memcpy(h.data(), src, h.size() * 4); 946 else if (t.type == 30) 947 for (size_t i = 0; i < h.size(); ++i) h[i] = bf16_to_f32((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); 948 else if (t.type == 1) // F16 949 for (size_t i = 0; i < h.size(); ++i) 950 h[i] = f16_to_f32((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); 951 else if (t.type == 8 && h.size() % 32 == 0) { 952 // Q8_0 (the Q8_0 file stores ssm_alpha / ssm_beta so): blocks of an fp16 scale and 32 int8, widened here 953 for (size_t b = 0; b < h.size() / 32; ++b) { 954 const uint8_t* q = src + b * 34; 955 const float d = f16_to_f32((uint16_t) (q[0] | (q[1] << 8))); 956 for (int j = 0; j < 32; ++j) h[b * 32 + j] = d * (float) (int8_t) q[2 + j]; 957 } 958 } else { 959 std::fprintf(stderr, "strata-q36: %s is %s, expected F32, BF16, F16 or Q8_0\n", t.name.c_str(), t.type_name()); 960 std::exit(1); 961 } 962 float* d = nullptr; 963 CK(cudaMalloc(&d, h.size() * 4)); 964 CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); 965 return d; 966} 967 968bool load(const std::string& path, Model& m, std::string& err, bool want_mtp) { 969 const auto t0 = Clock::now(); 970 m.file = std::make_shared<strata::GgufModel>(strata::GgufModel::open(path)); 971 const strata::GgufModel& gm = *m.file; 972 if (!strata::core::geometry_from_gguf(gm.meta(), m.g, m.top_k, err)) return false; 973 if (m.g.family != strata::ModelFamily::Qwen35Moe) { 974 err = "strata-q36 runs Qwen3.6-35B-A3B (qwen35moe) files only"; 975 return false; 976 } 977 size_t checked = 0; 978 if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) return false; 979 const auto& g = m.g; 980 if (g.head_dim != 256 || g.ssm_state_size != 128 || g.ssm_d_conv != 4 || g.n_expert > 512 || m.top_k > 15) { 981 err = "a geometry this driver's kernels do not take (head 256, state 128, conv 4, <= 512 experts, top-k <= 15)"; 982 return false; 983 } 984 const std::string p = "qwen35moe."; 985 if (const strata::MetaValue* v = gm.meta().get(p + "attention.layer_norm_rms_epsilon")) m.eps = (float) v->num(); 986 if (const strata::MetaValue* v = gm.meta().get(p + "rope.freq_base")) m.rope_base = (float) v->num(); 987 if (const strata::MetaValue* v = gm.meta().get(p + "rope.dimension_count")) m.n_rot = (int) v->u; 988 uint64_t bytes = 0; 989 auto find = [&](const std::string& name, size_t& s) -> const strata::TensorInfo* { 990 const strata::TensorInfo* t = gm.find(name, &s); 991 if (!t) { 992 std::fprintf(stderr, "strata-q36: missing %s\n", name.c_str()); 993 std::exit(1); 994 } 995 return t; 996 }; 997 auto f32 = [&](const std::string& name) -> const float* { 998 size_t s = 0; 999 const strata::TensorInfo* t = find(name, s); 1000 bytes += t->elements() * 4; 1001 return upload_f32(*t, gm.shard(s).tensor_data(*t)); 1002 }; 1003 auto mat = [&](const std::string& name) -> Mat { 1004 size_t s = 0; 1005 const strata::TensorInfo* t = find(name, s); 1006 Mat w; 1007 w.type = (int) t->type; 1008 w.n_in = (int) t->shape[0]; 1009 w.n_out = (int) t->shape[1]; 1010 if (!K::native_mmvq_supported(w.type)) { 1011 std::fprintf(stderr, "strata-q36: %s is %s, which the native MMVQ does not take\n", name.c_str(), t->type_name()); 1012 std::exit(1); 1013 } 1014 const uint64_t nb = strata::tensor_payload_bytes(*t); 1015 uint8_t* d = nullptr; 1016 CK(cudaMalloc(&d, nb)); 1017 CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); 1018 bytes += nb; 1019 w.d = d; 1020 // STRATA_Q8_PACKED (on by default here): the lossless qs / d plane copy the Q8_0 decode kernels read instead, 1021 // bitwise the same outputs 1022 if (w.type == 8 && K::native_q8_0_packed_enabled() && K::native_q8_0_packed_eligible(w.n_in, w.n_out)) { 1023 std::vector<uint8_t> packed(nb); 1024 K::native_q8_0_pack_host(gm.shard(s).tensor_data(*t), packed.data(), w.n_in, w.n_out); 1025 uint8_t* pd = nullptr; 1026 CK(cudaMalloc(&pd, nb)); 1027 CK(cudaMemcpy(pd, packed.data(), nb, cudaMemcpyHostToDevice)); 1028 K::native_q8_0_packed_register(d, pd, w.n_in, w.n_out); 1029 m.packed.emplace_back(d, pd, (size_t) nb); 1030 bytes += nb; 1031 } 1032 return w; 1033 }; 1034 auto L = [](int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; }; 1035 m.layers.resize((size_t) g.n_layers); 1036 // the MTP block whenever the file has one, with or without drafts (--mtp): the VRAM it takes is then the same 1037 // either way, so the hybrid mode's slot tables - and with them the greedy text - do not depend on --mtp 1038 (void) want_mtp; 1039 m.has_mtp = g.n_mtp_layers > 0; 1040 for (int64_t l = 0; l < g.n_layers + (m.has_mtp ? 1 : 0); ++l) { 1041 const bool is_mtp = l == g.n_layers; 1042 Layer& y = is_mtp ? m.mtp : m.layers[(size_t) l]; 1043 y.attn = is_mtp || strata::core::is_qsa_layer(g, l); 1044 y.attn_norm = f32(L(l, "attn_norm.weight")); 1045 y.post_norm = f32(L(l, "post_attention_norm.weight")); 1046 if (!y.attn) { 1047 y.qkv = mat(L(l, "attn_qkv.weight")); 1048 y.zg = mat(L(l, "attn_gate.weight")); 1049 y.ssm_out = mat(L(l, "ssm_out.weight")); 1050 y.alpha = f32(L(l, "ssm_alpha.weight")); 1051 y.beta = f32(L(l, "ssm_beta.weight")); 1052 y.dt = f32(L(l, "ssm_dt.bias")); 1053 y.ssm_a = f32(L(l, "ssm_a")); 1054 y.conv = f32(L(l, "ssm_conv1d.weight")); 1055 y.ssm_norm = f32(L(l, "ssm_norm.weight")); 1056 } else { 1057 y.wq = mat(L(l, "attn_q.weight")); 1058 y.wk = mat(L(l, "attn_k.weight")); 1059 y.wv = mat(L(l, "attn_v.weight")); 1060 y.wo = mat(L(l, "attn_output.weight")); 1061 y.q_norm = f32(L(l, "attn_q_norm.weight")); 1062 y.k_norm = f32(L(l, "attn_k_norm.weight")); 1063 } 1064 y.router = f32(L(l, "ffn_gate_inp.weight")); 1065 y.sh_gate = mat(L(l, "ffn_gate_shexp.weight")); 1066 y.sh_up = mat(L(l, "ffn_up_shexp.weight")); 1067 y.sh_down = mat(L(l, "ffn_down_shexp.weight")); 1068 y.sh_gate_inp = f32(L(l, "ffn_gate_inp_shexp.weight")); 1069 CK(cudaMalloc(&y.router_ext, (size_t) (g.n_expert + 1) * g.n_embd * 4)); 1070 CK(cudaMemcpy(y.router_ext, y.router, (size_t) g.n_expert * g.n_embd * 4, cudaMemcpyDeviceToDevice)); 1071 CK(cudaMemcpy(y.router_ext + (size_t) g.n_expert * g.n_embd, y.sh_gate_inp, (size_t) g.n_embd * 4, 1072 cudaMemcpyDeviceToDevice)); 1073 bytes += (size_t) (g.n_expert + 1) * g.n_embd * 4; 1074 // the routed experts: [gate | up | down] per expert, the native expert layout 1075 size_t sg = 0, su = 0, sd = 0; 1076 const strata::TensorInfo* tg = find(L(l, "ffn_gate_exps.weight"), sg); 1077 const strata::TensorInfo* tu = find(L(l, "ffn_up_exps.weight"), su); 1078 const strata::TensorInfo* td = find(L(l, "ffn_down_exps.weight"), sd); 1079 if (tg->type != tu->type) { 1080 err = L(l, "ffn_gate_exps / ffn_up_exps differ in type"); 1081 return false; 1082 } 1083 if (!K::native_expert_supported((int) tg->type, (int) td->type, g.n_embd, g.n_ff)) { 1084 err = L(l, "experts are ") + tg->type_name() + "/" + td->type_name() + ", which the native expert kernels " + 1085 "do not take (build with -DSTRATA_Q6K_EXPERTS=ON for Q6_K)"; 1086 return false; 1087 } 1088 y.L = K::native_expert_layout((int) tg->type, (int) td->type, g.n_embd, g.n_ff); 1089 const size_t gsz = (size_t) g.n_ff * y.L.gu_row, dsz = (size_t) g.n_embd * y.L.d_row; 1090 // a stride in whole blocks of both parts' types (MMQ steps over the experts by blocks), 16-byte aligned 1091 const size_t al = lcm_sz(lcm_sz(block_bytes(y.L.gu_type), block_bytes(y.L.d_type)), 16); 1092 y.stride = (y.L.bytes + al - 1) / al * al; 1093 y.src_g = gm.shard(sg).tensor_data(*tg); 1094 y.src_u = gm.shard(su).tensor_data(*tu); 1095 y.src_d = gm.shard(sd).tensor_data(*td); 1096 y.src_gsz = gsz; 1097 y.src_dsz = dsz; 1098 } 1099 if (m.has_mtp) { 1100 const int64_t l = g.n_layers; 1101 m.eh_proj = mat(L(l, "nextn.eh_proj.weight")); 1102 m.mtp_enorm = f32(L(l, "nextn.enorm.weight")); 1103 m.mtp_hnorm = f32(L(l, "nextn.hnorm.weight")); 1104 m.mtp_shnorm = f32(L(l, "nextn.shared_head_norm.weight")); 1105 } 1106 m.out_norm = f32("output_norm.weight"); 1107 m.head = mat("output.weight"); 1108 { 1109 size_t s = 0; 1110 const strata::TensorInfo* t = find("token_embd.weight", s); 1111 m.embd_type = (int) t->type; 1112 m.embd_row = row_bytes(m.embd_type, (int64_t) t->shape[0]); 1113 const uint64_t nb = strata::tensor_payload_bytes(*t); 1114 uint8_t* d = nullptr; 1115 CK(cudaMalloc(&d, nb)); 1116 CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); 1117 m.embd = d; 1118 bytes += nb; 1119 } 1120 std::fprintf(stderr, "strata-q36: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s (the routed " 1121 "experts are placed after the engine's buffers)\n", path.c_str(), checked, (double) bytes / (1 << 30), 1122 ms_since(t0) / 1000.0); 1123 return true; 1124} 1125 1126/// Expert e of layer L as its native blob [gate | up | down] (L.L.bytes) at dst (host memory). 1127void expert_blob(const Layer& L, int64_t e, uint8_t* dst) { 1128 std::memcpy(dst, L.src_g + (size_t) e * L.src_gsz, L.src_gsz); 1129 std::memcpy(dst + L.L.up_off, L.src_u + (size_t) e * L.src_gsz, L.src_gsz); 1130 std::memcpy(dst + L.L.down_off, L.src_d + (size_t) e * L.src_dsz, L.src_dsz); 1131} 1132 1133// ------------------------------------------------------------------------------------------------ the engine 1134float* dalloc(size_t n) { 1135 float* p = nullptr; 1136 CK(cudaMalloc(&p, n * 4)); 1137 CK(cudaMemset(p, 0, n * 4)); 1138 return p; 1139} 1140template <class T> T* dalloc_t(size_t n) { 1141 T* p = nullptr; 1142 CK(cudaMalloc(&p, n * sizeof(T))); 1143 CK(cudaMemset(p, 0, n * sizeof(T))); 1144 return p; 1145} 1146 1147/// A picture in a prompt: its first cell, its rows, and the hash the conversation cache compares it by. 1148struct ImgKey { 1149 int64_t cell = 0, n = 0; 1150 uint64_t hash = 0; 1151 bool operator==(const ImgKey& o) const { return cell == o.cell && n == o.n && hash == o.hash; } 1152}; 1153 1154struct Engine { 1155 const Model* m = nullptr; 1156 cudaStream_t st = nullptr; 1157 int ctx = 32768, tmax = 512; 1158 int64_t pos = 0; // cells holding a processed token 1159 // activations [tmax][...] 1160 float *x, *h, *y, *qkv, *hc, *z, *alpha, *beta, *gdn_y, *qg, *kx, *vx, *q, *gate, *att, *logits_r, *eparts, *moe_out, 1161 *sg, *su, *shh, *sy, *sgate, *ewts, *logits; 1162 float* hmain = nullptr; // [tmax][N] the main model's final normed hidden of each row (the MTP seeds) 1163 float* hlast = nullptr; // [N] that of the last processed position (zeros before the first): the current session's 1164 void *q8, *xq, *escr; 1165 int32_t *ids, *grp_start, *n_groups, *ent_dst, *ent_tok, *tok, *pos0, *pick; 1166 int32_t* hpin = nullptr; // pinned staging: [0] decode token, [1] position, [2..9] picks, [10] max rows, [16..] tokens 1167 unsigned long long* grp_ptr; 1168 float *pacc, *pm, *pl, *amv; 1169 int32_t* ami; 1170 int n_chunk = 0, att_rows = 0; // attention partials: att_rows query rows x n_chunk chunks 1171 std::vector<float*> conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers: the CURRENT session's (select) 1172 // verify windows (T <= kVerify): the GDN inputs of every row per layer, kept for the commit 1173 static constexpr int kVerify = 8; 1174 std::vector<float*> v_qkv, v_hc, v_alpha, v_beta; 1175 // the MTP block (when loaded) 1176 float *mtp_cat = nullptr, *hmtp = nullptr, *logits_m = nullptr; 1177 int32_t *tok_m = nullptr, *pos0_m = nullptr, *pick_m = nullptr; 1178 // graphs: [0] the decode step, [T] a verify window of T rows, mtp1 the MTP draft step 1179 // (the graphs hold the current session's state pointers as kernel arguments: one set per session) 1180 struct GSet { 1181 cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; 1182 }; 1183 std::vector<GSet> gsets; 1184 GSet& gs() { return gsets[(size_t) cur]; } 1185 strata::prefill::Gemm gemm; 1186 cublasHandle_t blas = nullptr; 1187 float* att_s = nullptr; // the prompt attention's scores / probabilities, kAttScoreFloats floats 1188 static constexpr int kSplitK = 16; 1189 float* sk_part = nullptr; // the split-K partials of the F32 projections: [kSplitK][tmax][<= 257] 1190 __half* att_p16 = nullptr; // the probabilities in FP16 (kAttScoreFloats halves) 1191 __half *k16 = nullptr, *v16 = nullptr, *q16 = nullptr; // the prompt attention's FP16 operands 1192 size_t kAttScoreFloats = (size_t) 64 << 20; // 256 MB (16 M floats when the experts' fit is close) 1193 // the prompt's experts on Strata's fused int8 kernels (moe_fused_iq_q36.cu, CUDA): per layer (fused_on), the rest on MMQ 1194 // where it has a tile, else the native grouped kernels. use_pf: every layer's prompt chunks have one of the two, so the 1195 // hybrid mode streams each layer's experts for a chunk (the strategy MMQ had alone before) 1196 std::vector<char> fused_on; // by state index (the MTP block last) 1197 // our int8 expert kernels (native_expert_i8) for the layers neither the fused kernels nor MMQ take (q36_layer_route, include/strata/kernels/q36_prompt_route.hpp): the layer's 1198 // rows are quantized once, the groups come from group_entries, the output is the grouped kernels' (eparts by entry); a chunk with few rows per expert takes the grouped kernels 1199 std::vector<char> i8_on; // by state index 1200 size_t n_i8 = 0; 1201 int i8_few = 0; // native_expert_i8_few_rows_limit() 1202 void* i8x = nullptr; // the activation image native_expert_i8 reads (native_expert_i8_quantize) 1203 bool use_pf = false; 1204 void* f_scr = nullptr; // the grouping tables (fused::group_bytes) 1205 void *f_xq = nullptr, *f_ha = nullptr; // the layer's input and H in the kernels' int8 form (fused::act_bytes) 1206 int32_t *f_slot = nullptr, *f_src = nullptr; 1207 // the prompt's MMQ experts 1208 bool use_mmq = false; 1209 std::unique_ptr<MMQ::Context> mctx; 1210 int32_t *rcnt = nullptr, *rcur = nullptr, *rbounds = nullptr, *rmax = nullptr, *ident = nullptr, *rinv = nullptr; 1211 void *mq_x = nullptr, *mq_hq = nullptr; 1212 float *mq_gu = nullptr, *mq_h = nullptr; 1213 __half* x16 = nullptr; 1214 bool use_graph = true; 1215 int mtp_d = 0; // MTP drafts per speculative step (0: none; greedy requests only) 1216 1217 // ---- sessions: the conversation states. One for a single-request engine; --batch N keeps N, each with its own 1218 // recurrent state and KV cache, so N requests run at once: their rows share one decode window (forward_rows). The 1219 // members conv / S / kc / vc / pos / hlast above are the CURRENT session's (select() swaps them). 1220 struct Sess { 1221 std::vector<float*> conv, S, kc, vc; 1222 float* hlast = nullptr; 1223 int64_t pos = 0; 1224 int32_t rdelta = 0; // rotary offset of the text after the last picture (see k_attn_prep) 1225 std::vector<int32_t> live; // the tokens whose state it holds (cell i = live[i]) 1226 std::vector<ImgKey> imgs; // the pictures among them 1227 bool active = false; // a batch slot is decoding in it 1228 uint64_t used = 0; // when it was last used (the LRU pick) 1229 }; 1230 std::vector<Sess> sess; 1231 int n_sess = 1, cur = 0; 1232 uint64_t use_clock = 0; 1233 // device tables for batch rows: per state index (layer, then the MTP block) the session pointers 1234 float **d_conv_tab = nullptr, **d_S_tab = nullptr, **d_kc_tab = nullptr, **d_vc_tab = nullptr; 1235 int32_t *d_rcell = nullptr, *d_rslot = nullptr, *d_rdelta = nullptr; // [kVerify] the rows' cell / session / rotary offset 1236 // the GDN layers run a slot's rows in sequence: per group (a slot) its session, its first row and its row count 1237 int32_t *d_gslot = nullptr, *d_grow0 = nullptr, *d_gcnt = nullptr; 1238 int rows_G = 0; // groups of the rows being run 1239 int32_t* hrow = nullptr; // pinned staging for the rows 1240 bool rows_mode = false; // layer(): the rows are sessions' (not consecutive cells) 1241 bool bmtp = false; // --batch-mtp: batch windows verify MTP proposals 1242 int64_t rows_pmax = 0; // (eager) the highest cell of the rows 1243 // pictures (--vision): the request's rows replace the embeddings of its <|image_pad|> cells; M-RoPE 1244 bool vision = false; 1245 int32_t* d_mtab = nullptr; // [ctx][3] t, h, w of the current request's prompt cells (vision) 1246 const int32_t* mtab_now = nullptr; // set for a forward over prompt cells that need it, else null 1247 int32_t* d_delta = nullptr; // device scalar: the current session's rotary offset (decode graphs read it) 1248 float* d_img = nullptr; // the request's picture rows [n][N] 1249 size_t img_cap = 0; // floats 1250 int32_t* d_map = nullptr; // [tmax] a chunk's row -> picture row (or -1) 1251 int32_t* h_map = nullptr; // pinned 1252 bool map_on = false; // this forward's embeddings take picture rows 1253 std::vector<int32_t> img_map; // the request's cell -> picture row (-1: text) 1254 int64_t img_prompt_cells = 0; // the request's prompt length: cells below it use the table 1255 1256 // ---- the hybrid mode (Model::hybrid): per state index (the layers, then the MTP block) the slot tables; a 1257 // batch of up to hybrid_t rows runs its VRAM-resident experts on the GPU and the others on the CPU pool, side by 1258 // side; a bigger prompt chunk streams each layer's experts into a staging buffer for MMQ (two, double-buffered) 1259 struct Hy { 1260 std::vector<int> slot_of, exp_in_slot; 1261 std::vector<double> score; // routing counts, halved at each rebalance 1262 int32_t* slot_of_d = nullptr; 1263#if defined(STRATA_Q36_CPU_POOL) 1264 strata::kernels::cpu::NativeFmt fmt; 1265#endif 1266 }; 1267 std::vector<Hy> hy; 1268 int hybrid_t = 32; 1269 bool main_hybrid = false; // some main layer is hybrid (else only the MTP block is: the decode graph stays) 1270 bool mtp_graph = true; // the MTP draft step may be a graph (not when its layer is hybrid) 1271 /// state index li's layer runs hybrid (its experts not all in VRAM) 1272 bool lhy(size_t li) const { 1273 if (!m->hybrid) return false; 1274 const Layer& L = li < m->layers.size() ? m->layers[li] : m->mtp; 1275 return L.n_slots < (int) m->g.n_expert; 1276 } 1277#if defined(STRATA_Q36_CPU_POOL) 1278 std::unique_ptr<strata::kernels::cpu::ExpertPool> pool; 1279 std::vector<strata::kernels::cpu::ExpertJobMulti> jobs; 1280#endif 1281 float *h_h = nullptr, *cpu_out = nullptr, *ecpu = nullptr; 1282 int32_t *h_ids = nullptr, *h_miss = nullptr, *d_miss = nullptr, *h_cnt = nullptr; 1283 uint8_t* acts = nullptr; // per token: its quantized activation (kNativeActBytes) 1284 cudaEvent_t ev_route = nullptr; 1285 uint8_t* stage[2] = {}; 1286 cudaStream_t cst = nullptr; 1287 cudaEvent_t ev_copy[2] = {}, ev_used[2] = {}; 1288 std::vector<int> stream_seq; // the state indices a streamed forward visits, in order 1289 int stream_pos = 0; 1290 long long hy_cpu = 0, hy_gpu = 0, hy_swaps = 0; // entries computed on the CPU / GPU, slot replacements 1291 double hy_cpu_ms = 0; 1292 // decode / verify rows: their routing is counted once the rows are kept (commit), so a verify window's rejected 1293 // drafts never move the slots; the slots follow the counts at every kRebalanceEvery-th position exactly (a 1294 // window never steps over one), so plain and speculative decoding see the same slot tables at every position 1295 static constexpr int kRebalanceEvery = 32; 1296 bool rows_deferred = false; // set while a decode step or a verify window runs 1297 std::vector<std::vector<int32_t>> row_ids; // [main layer][row * top_k + k] of the last such call 1298 void count_rows(int n) { 1299 const int Kp = (int) m->top_k; 1300 for (size_t li = 0; li < row_ids.size() && li < hy.size(); ++li) 1301 if (!row_ids[li].empty()) 1302 for (int e = 0; e < n * Kp; ++e) hy[li].score[(size_t) row_ids[li][(size_t) e]] += 1.0; 1303 } 1304 void after_rows(int n) { // a decode step / verify window kept n rows: count them, rebalance at the boundary 1305 if (!m->hybrid) return; 1306 count_rows(n); 1307 if (pos % kRebalanceEvery == 0) { 1308 CK(cudaStreamSynchronize(st)); 1309 rebalance(8); 1310 } 1311 } 1312 1313 void alloc_session(Sess& ss) const { 1314 const auto& g = m->g; 1315 const size_t C = (size_t) g.ssm_conv_channels; 1316 for (const Layer& L : m->layers) { 1317 if (L.attn) { 1318 ss.conv.push_back(nullptr); 1319 ss.S.push_back(nullptr); 1320 ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); 1321 ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); 1322 } else { 1323 ss.conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); 1324 ss.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); 1325 ss.kc.push_back(nullptr); 1326 ss.vc.push_back(nullptr); 1327 } 1328 } 1329 if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) 1330 ss.conv.push_back(nullptr); 1331 ss.S.push_back(nullptr); 1332 ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); 1333 ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); 1334 } 1335 ss.hlast = dalloc((size_t) g.n_embd); 1336 } 1337 1338 /// The current session: `i`'s state, cache and position become the engine's (conv / S / kc / vc / pos / hlast). 1339 void select(int i) { 1340 if (i == cur) return; 1341 sess[(size_t) cur].pos = pos; 1342 cur = i; 1343 load_cur(); 1344 } 1345 void load_cur() { 1346 Sess& ss = sess[(size_t) cur]; 1347 conv = ss.conv; S = ss.S; kc = ss.kc; vc = ss.vc; 1348 hlast = ss.hlast; 1349 pos = ss.pos; 1350 ss.used = ++use_clock; 1351 set_delta(ss.rdelta); 1352 } 1353 /// The rotary offset the decode graphs read (a device scalar), for the current session. 1354 void set_delta(int32_t d) { 1355 sess[(size_t) cur].rdelta = d; 1356 if (!d_delta) return; 1357 hpin[60] = d; 1358 CK(cudaMemcpyAsync(d_delta, hpin + 60, 4, cudaMemcpyHostToDevice, st)); 1359 CK(cudaStreamSynchronize(st)); // (the pinned word is reused) 1360 } 1361 1362 void init(const Model& model, int ctx_, int tmax_, int n_sessions = 1, bool vision_ = false) { 1363 m = &model; 1364 ctx = ctx_; 1365 n_sess = std::max(1, std::min(n_sessions, kVerify)); 1366 vision = vision_; 1367 tmax = std::max(tmax_, kVerify); 1368 const auto& g = m->g; 1369 const size_t T = (size_t) tmax, N = (size_t) g.n_embd, Kp = (size_t) m->top_k, FF = (size_t) g.n_ff; 1370 const size_t C = (size_t) g.ssm_conv_channels; 1371 CK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking)); 1372 x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); 1373 qkv = dalloc(T * C); hc = dalloc(T * C); z = dalloc(T * g.ssm_value_dim); 1374 alpha = dalloc(T * g.ssm_v_heads); beta = dalloc(T * g.ssm_v_heads); gdn_y = dalloc(T * g.ssm_value_dim); 1375 qg = dalloc(T * 2 * g.n_head * g.head_dim); kx = dalloc(T * g.n_head_kv * g.head_dim); 1376 vx = dalloc(T * g.n_head_kv * g.head_dim); q = dalloc(T * g.n_head * g.head_dim); 1377 gate = dalloc(T * g.n_head * g.head_dim); att = dalloc(T * g.n_head * g.head_dim); 1378 logits_r = dalloc(T * (g.n_expert + 1)); 1379 eparts = dalloc(T * Kp * N); moe_out = dalloc(T * N); 1380 sg = dalloc(T * g.n_ff_shexp); su = dalloc(T * g.n_ff_shexp); shh = dalloc(T * g.n_ff_shexp); sy = dalloc(T * N); 1381 sgate = dalloc(T); ewts = dalloc(T * Kp); logits = dalloc((size_t) kVerify * g.n_vocab); 1382 const int max_in = (int) std::max<int64_t>({2 * g.n_embd, g.ssm_value_dim, g.n_head * g.head_dim, g.n_ff_shexp}); 1383 CK(cudaMalloc(&q8, K::native_q8_1_bytes(max_in, 1) * T)); 1384 CK(cudaMalloc(&xq, K::native_q8_1_bytes((int) N, 1) * T)); 1385 x16 = dalloc_t<__half>(T * (size_t) max_in); 1386 if (cublasCreate(&blas) != CUBLAS_STATUS_SUCCESS || cublasSetStream(blas, st) != CUBLAS_STATUS_SUCCESS) { 1387 std::fprintf(stderr, "strata-q36: cuBLAS handle failed\n"); 1388 std::exit(1); 1389 } 1390 att_s = dalloc(kAttScoreFloats); 1391 sk_part = dalloc((size_t) kSplitK * T * (g.n_expert + 1)); 1392 att_p16 = dalloc_t<__half>(kAttScoreFloats); 1393 k16 = dalloc_t<__half>((size_t) g.n_head_kv * ctx * g.head_dim); 1394 v16 = dalloc_t<__half>((size_t) g.n_head_kv * ctx * g.head_dim); 1395 q16 = dalloc_t<__half>(T * g.n_head * g.head_dim); 1396 const bool mmq_avail = MMQ::built() && std::getenv("STRATA_Q36_NO_MMQ") == nullptr; 1397 auto mmq_ok = [&](const Layer& L) { 1398 return MMQ::supported(L.L.gu_type) && MMQ::supported(L.L.d_type) && MMQ::fits(L.L.gu_type, 2 * g.n_ff) && 1399 MMQ::fits(L.L.d_type, g.n_embd); 1400 }; 1401 const size_t n_state = m->layers.size() + (m->has_mtp ? 1 : 0); 1402 fused_on.assign(n_state, 0); 1403 // (HIP: gfx12 only, STRATA_PF_FUSED=1, which this engine sets itself in a build without MMQ: fused_tile::q36_takes_gfx12) 1404 // Strata's fused kernels where they cover the layer's pair on this card: the default on the cards the Flash-Next engine's rule takes (sm_86-class and sm_120 cards 1405 // with 80+ SMs, the staged launches on 40-79 SMs: fused_tile::q36_takes, the rule of takes_by_default), STRATA_PF_FUSED=1 on every card that covers the pair, 1406 // STRATA_PF_FUSED=0 keeps every layer on MMQ; HIP builds, cards under 40 SMs and compute capability below 8 are as before (MMQ) 1407 if (g.n_embd == FQ::kQ36Embd && g.n_ff == FQ::kQ36FF) 1408 for (size_t i = 0; i < n_state; ++i) { 1409 const Layer& L = layer_at((int) i); 1410 fused_on[i] = FQ::native_layer_ext(L.L.gu_type, L.L.d_type) ? 1 : 0; 1411 } 1412 // the route of each layer (q36_layer_route): fused > our int8 kernels (STRATA_EXPERT_I8=1) > MMQ > our int8 kernels > the grouped kernels. A build without MMQ reads an unset 1413 // STRATA_EXPERT_I8 as 1 (the standalone engine does not link prefill.cpp's start-up list, so it tells the kernel library itself). 1414 const bool mmq_free = !MMQ::built(); 1415 if (mmq_free) K::native_expert_i8_set_mmq_free(); 1416 const int i8_raw = K::i8_switch_parse(std::getenv("STRATA_EXPERT_I8")); 1417 i8_on.assign(n_state, 0); 1418 i8_few = K::native_expert_i8_few_rows_limit(); 1419 use_pf = true; 1420 bool any_mmq = false; 1421 size_t n_fused = 0, n_grouped = 0; 1422 for (size_t i = 0; i < n_state; ++i) { 1423 const Layer& Li = layer_at((int) i); 1424 const bool mmq_takes = !fused_on[i] && mmq_avail && mmq_ok(Li); 1425 const K::Q36Route r = K::q36_layer_route(fused_on[i] != 0, i8_raw, mmq_free, mmq_takes, !fused_on[i] && K::native_expert_i8_supported(Li.L)); 1426 const bool mq = r == K::Q36Route::Mmq; 1427 i8_on[i] = r == K::Q36Route::Int8 ? 1 : 0; 1428 if (r == K::Q36Route::Grouped) ++n_grouped; 1429 any_mmq = any_mmq || mq; 1430 n_fused += fused_on[i] ? 1 : 0; 1431 n_i8 += i8_on[i]; 1432 } 1433 use_pf = K::q36_prompt_path_ok((int) n_state, (int) n_grouped); 1434 if (!use_pf) { // a layer has no route faster than the grouped kernels: every prompt chunk on the native grouped kernels, as before 1435 std::fill(fused_on.begin(), fused_on.end(), 0); 1436 std::fill(i8_on.begin(), i8_on.end(), 0); 1437 n_fused = 0; 1438 n_i8 = 0; 1439 any_mmq = false; 1440 } 1441 use_mmq = use_pf && any_mmq; 1442 if (n_i8 > 0) CK(cudaMalloc(&i8x, K::native_q8_1_bytes((int) N, 1) * T)); 1443 if (use_pf) { 1444 const int64_t ne = (int64_t) T * Kp; 1445 rcnt = dalloc_t<int32_t>((size_t) g.n_expert); 1446 rcur = dalloc_t<int32_t>((size_t) g.n_expert); 1447 rbounds = dalloc_t<int32_t>((size_t) g.n_expert + 1); 1448 rmax = dalloc_t<int32_t>(1); 1449 rinv = dalloc_t<int32_t>((size_t) ne); 1450 if (n_fused > 0) { 1451 CK(cudaMalloc(&f_scr, PF::group_bytes(ne, (int) g.n_expert))); 1452 CK(cudaMalloc(&f_xq, PF::act_bytes((int64_t) T, g.n_embd))); 1453 CK(cudaMalloc(&f_ha, PF::act_bytes(ne, g.n_ff))); 1454 f_slot = dalloc_t<int32_t>((size_t) ne); 1455 f_src = dalloc_t<int32_t>((size_t) ne); 1456 } 1457 } 1458 if (use_mmq) { 1459 const int64_t ne = (int64_t) T * Kp; 1460 mctx = std::make_unique<MMQ::Context>(); 1461 // The row table (ids) is read past its end by llama.cpp's MMQ: mul_mat_q copies ids_dst[col_low + jt*J + j] for a whole J-column tile before it 1462 // compares the tile with the expert's rows, and its stream-k fixup does the same for every tile up to roundup(max_rows, J) from an expert's first row, 1463 // which can be the table's last (mmq.cuh; J goes to 128). mmq_ids_table_rows adds roundup(max_rows, 128) + 128 entries, max_rows <= T (an expert takes at 1464 // most one row per token): the margin the Flash-Next prompt path already uses (prefill.cpp mmq_ids_rows, PR #5108). An exact table of ne ints (64 KB at the 1465 // default chunk) was read past its end: compute-sanitizer on the same size in the Qwen3.6 one-layer test (z440-20261111-2224-d478), 311 invalid reads of size 4 1466 // in mul_mat_q<Q8_0, 96>, 29 to 57+ bytes after a 65,536-byte allocation. The identity is written over the whole table, as there. 1467 const int64_t ids_rows = (int64_t) MMQ::mmq_ids_table_rows((uint64_t) ne, (uint64_t) T); 1468 if (ids_rows <= 0) { std::fprintf(stderr, "strata-q36: the MMQ row table does not fit\n"); std::exit(1); } 1469 ident = dalloc_t<int32_t>((size_t) ids_rows); 1470 CK(cudaDeviceSynchronize()); // ident's cudaMemset (legacy stream) before the iota on the non-blocking stream 1471 MMQ::iota(ident, ids_rows, st); 1472 CK(cudaMalloc(&mq_x, MMQ::q8_bytes(ne, g.n_embd))); 1473 CK(cudaMalloc(&mq_hq, MMQ::q8_bytes(ne, g.n_ff))); 1474 mq_gu = dalloc((size_t) ne * 2 * FF); 1475 mq_h = dalloc((size_t) ne * FF); 1476 } 1477 if (n_i8 > 0) 1478 std::fprintf(stderr, "strata-q36: prompt experts: %zu of %zu layers on the fused int8 kernels, %zu on our int8 kernels, %zu on MMQ (int8)\n", n_fused, n_state, n_i8, 1479 n_state - n_fused - n_i8); 1480 else if (n_fused == n_state) 1481 std::fprintf(stderr, "strata-q36: prompt experts on the fused int8 kernels\n"); 1482 else if (n_fused > 0) 1483 std::fprintf(stderr, "strata-q36: prompt experts on the fused int8 kernels (%zu of %zu layers), the rest on MMQ (int8)\n", 1484 n_fused, n_state); 1485 else 1486 std::fprintf(stderr, "strata-q36: prompt experts on %s\n", use_mmq ? "MMQ (int8)" : "the native grouped kernels"); 1487 { 1488 std::string gerr; 1489 int64_t big = 0; 1490 auto take = [&](const Layer& L) { 1491 for (const Mat* w : {&L.qkv, &L.zg, &L.ssm_out, &L.wq, &L.wk, &L.wv, &L.wo, &L.sh_gate, &L.sh_up, &L.sh_down}) 1492 big = std::max<int64_t>(big, (int64_t) w->n_in * w->n_out); 1493 }; 1494 for (const Layer& L : m->layers) take(L); 1495 if (m->has_mtp) { 1496 take(m->mtp); 1497 big = std::max<int64_t>(big, (int64_t) m->eh_proj.n_in * m->eh_proj.n_out); 1498 } 1499 if (!gemm.init(st, big, gerr)) { 1500 std::fprintf(stderr, "strata-q36: prompt GEMM: %s\n", gerr.c_str()); 1501 std::exit(1); 1502 } 1503 } 1504 CK(cudaMalloc(&escr, K::native_expert_scratch_bytes((int64_t) (T * Kp), (int64_t) FF))); 1505 ids = dalloc_t<int32_t>(T * Kp); 1506 grp_ptr = dalloc_t<unsigned long long>(std::min<size_t>(T * Kp, (size_t) g.n_expert) + 1); 1507 grp_start = dalloc_t<int32_t>(std::min<size_t>(T * Kp, (size_t) g.n_expert) + 1); 1508 n_groups = dalloc_t<int32_t>(1); 1509 ent_dst = dalloc_t<int32_t>(T * Kp); 1510 ent_tok = dalloc_t<int32_t>(T * Kp); 1511 tok = dalloc_t<int32_t>(T); 1512 pos0 = dalloc_t<int32_t>(1); 1513 pick = dalloc_t<int32_t>(kVerify); 1514 amv = dalloc((size_t) kArgBlocks * kVerify); 1515 ami = dalloc_t<int32_t>((size_t) kArgBlocks * kVerify); 1516 CK(cudaHostAlloc((void**) &hpin, 64 * sizeof(int32_t), cudaHostAllocDefault)); 1517 n_chunk = (ctx + kChunkCells - 1) / kChunkCells; 1518 att_rows = (int) (g.n_head * std::min<int64_t>((int64_t) T, 64)); // 64 query tokens per attention batch 1519 pacc = dalloc((size_t) att_rows * n_chunk * g.head_dim); 1520 pm = dalloc((size_t) att_rows * n_chunk); 1521 pl = dalloc((size_t) att_rows * n_chunk); 1522 for (const Layer& L : m->layers) { // the verify windows' GDN inputs (one set, whichever session runs) 1523 if (L.attn) { 1524 for (auto* v : {&v_qkv, &v_hc, &v_alpha, &v_beta}) v->push_back(nullptr); 1525 } else { 1526 v_qkv.push_back(dalloc((size_t) kVerify * C)); 1527 v_hc.push_back(dalloc((size_t) kVerify * C)); 1528 v_alpha.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); 1529 v_beta.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); 1530 } 1531 } 1532 if (m->has_mtp) { 1533 mtp_cat = dalloc(T * 2 * N); 1534 hmtp = dalloc(T * N); 1535 logits_m = dalloc((size_t) g.n_vocab); 1536 tok_m = dalloc_t<int32_t>(T); 1537 pos0_m = dalloc_t<int32_t>(1); 1538 pick_m = dalloc_t<int32_t>(1); 1539 } 1540 sess.resize((size_t) n_sess); 1541 gsets.resize((size_t) n_sess); 1542 { // the sessions' caches: said before they fail (a slot's K / V at the context, fp32, for the attention layers and 1543 // the MTP block, and its recurrent state) 1544 size_t n_attn = m->has_mtp ? 1 : 0, n_gdn = 0; 1545 for (const Layer& L : m->layers) (L.attn ? n_attn : n_gdn) += 1; 1546 const size_t per = (size_t) (g.n_head_kv * g.head_dim * 2 * 4) * (size_t) ctx * n_attn + 1547 (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4 * n_gdn; 1548 size_t fr0 = 0, tot0 = 0; 1549 CK(cudaMemGetInfo(&fr0, &tot0)); 1550 if (n_sess > 1) 1551 std::fprintf(stderr, "strata-q36: %d sessions (--batch): %.2f GiB of VRAM each at a context of %d (%.2f GiB in " 1552 "all), %.2f GiB free before them\n", n_sess, (double) per / (1 << 30), ctx, 1553 (double) per * n_sess / (1 << 30), (double) fr0 / (1 << 30)); 1554 if (n_sess > 1 && per * (size_t) n_sess + ((size_t) 1 << 30) > fr0) { 1555 std::fprintf(stderr, "strata-q36: not enough VRAM for %d slots at a context of %d (%.2f GiB each, %.2f GiB " 1556 "free): use fewer slots (\"parallel\" / --batch) or a shorter --max-context\n", n_sess, ctx, 1557 (double) per / (1 << 30), (double) fr0 / (1 << 30)); 1558 std::exit(1); 1559 } 1560 if (n_sess == 1) { // #5715: one session whose context cannot fit, said in words before the allocation fails 1561 const size_t shared_tok = (size_t) g.n_head_kv * g.head_dim * 2 * 2; // the fp16 K / V copy (k16 / v16 above) 1562 const size_t kv_tok = (size_t) (g.n_head_kv * g.head_dim * 2 * 4) * n_attn; 1563 const size_t ne = (size_t) g.n_expert; 1564 size_t total_main = 0, max_layer = 0, packed = 0; 1565 for (const Layer& L : m->layers) { 1566 total_main += L.stride * ne + kMmqTail; 1567 max_layer = std::max(max_layer, L.stride * ne); 1568 } 1569 if (m->has_mtp) max_layer = std::max(max_layer, m->mtp.stride * ne); 1570 for (const auto& pk : m->packed) packed += std::get<2>(pk); 1571 const strata::qwen35::OneSessionFit f = strata::qwen35::one_session_fit( 1572 {(size_t) ctx, kv_tok, shared_tok, per - kv_tok * (size_t) ctx, fr0, total_main, packed, 1573 kAttScoreFloats > ((size_t) 16 << 20) ? (kAttScoreFloats - ((size_t) 16 << 20)) * 6 : 0, 1574 strata::qwen35::one_session_staging_counted(use_mmq, n_i8 > 0, use_pf, MMQ::built()) 1575 ? 2 * (max_layer + kMmqTail) : 0, T * Kp * N * 4 + T * Kp * 4}); 1576 if (f.refuse) { // the old ending: the bare cudaMalloc line in alloc_session, or the hybrid buffers' text in place_experts 1577 std::fprintf(stderr, "strata-q36: %s\n", strata::qwen35::one_session_fit_line(ctx, f).c_str()); 1578 std::exit(1); 1579 } 1580 } 1581 } 1582 for (Sess& ss : sess) alloc_session(ss); 1583 if (n_sess > 1) { // the batch rows' tables: per state index the session pointers, on the device 1584 const size_t ns = sess[0].conv.size(); 1585 std::vector<float*> hc(ns * (size_t) n_sess), hs(hc), hk(hc), hv(hc); 1586 for (size_t li = 0; li < ns; ++li) 1587 for (int s_ = 0; s_ < n_sess; ++s_) { 1588 hc[li * n_sess + s_] = sess[(size_t) s_].conv[li]; 1589 hs[li * n_sess + s_] = sess[(size_t) s_].S[li]; 1590 hk[li * n_sess + s_] = sess[(size_t) s_].kc[li]; 1591 hv[li * n_sess + s_] = sess[(size_t) s_].vc[li]; 1592 } 1593 const std::pair<float***, std::vector<float*>*> tabs[4] = {{&d_conv_tab, &hc}, {&d_S_tab, &hs}, 1594 {&d_kc_tab, &hk}, {&d_vc_tab, &hv}}; 1595 for (const auto& tb : tabs) { 1596 CK(cudaMalloc((void**) tb.first, tb.second->size() * sizeof(float*))); 1597 CK(cudaMemcpy((void*) *tb.first, tb.second->data(), tb.second->size() * sizeof(float*), 1598 cudaMemcpyHostToDevice)); 1599 } 1600 d_rcell = dalloc_t<int32_t>(kVerify); 1601 d_rslot = dalloc_t<int32_t>(kVerify); 1602 d_rdelta = dalloc_t<int32_t>(kVerify); 1603 d_gslot = dalloc_t<int32_t>(kVerify); 1604 d_grow0 = dalloc_t<int32_t>(kVerify); 1605 d_gcnt = dalloc_t<int32_t>(kVerify); 1606 CK(cudaHostAlloc((void**) &hrow, 128 * sizeof(int32_t), cudaHostAllocDefault)); 1607 } 1608 if (vision) { 1609 d_mtab = dalloc_t<int32_t>((size_t) ctx * 3); 1610 d_map = dalloc_t<int32_t>(T); 1611 CK(cudaHostAlloc((void**) &h_map, T * sizeof(int32_t), cudaHostAllocDefault)); 1612 } 1613 d_delta = dalloc_t<int32_t>(1); 1614 cur = 0; 1615 load_cur(); 1616 CK(cudaDeviceSynchronize()); // every legacy-stream cudaMemset of the buffers above is done 1617 size_t fr = 0, tot = 0; 1618 CK(cudaMemGetInfo(&fr, &tot)); 1619 std::fprintf(stderr, "strata-q36: context %d cells, prompt chunk %d%s, %.2f GiB of VRAM free\n", ctx, tmax, 1620 m->has_mtp ? ", MTP block loaded" : "", (double) fr / (1 << 30)); 1621 } 1622 1623 /// The recurrent state and the cache to a fresh sequence. 1624 void reset() { 1625 const auto& g = m->g; 1626 for (size_t l = 0; l < conv.size(); ++l) { 1627 if (conv[l]) CK(cudaMemsetAsync(conv[l], 0, (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * 4, st)); 1628 if (S[l]) CK(cudaMemsetAsync(S[l], 0, (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, st)); 1629 } 1630 CK(cudaMemsetAsync(hlast, 0, (size_t) g.n_embd * 4, st)); 1631 CK(cudaStreamSynchronize(st)); 1632 pos = 0; 1633 sess[(size_t) cur].pos = 0; 1634 set_delta(0); 1635 } 1636 1637 /// y [T][n_out] = W x [T][n_in] on the native MMVQ, 8 columns per launch. 1638 void mm(const Mat& w, const float* xin, float* out, int T) { 1639 prep(xin, w.n_in, T, q8); 1640 apply(w, q8, out, T); 1641 } 1642 /// y [T][n_out] = W [n_out][n_in] (f32) x [T][n_in]: a decode batch on the warp-per-row kernel, a prompt chunk on 1643 /// cuBLAS's FP32 GEMM (the router and the GDN alpha / beta stay in FP32, as llama.cpp keeps them). 1644 void f32mm(const float* W, const float* xin, float* out, int n_in, int n_out, int T) { 1645 if (T <= kGemmT) { 1646 k_gemv_f32<<<dim3(rows8(n_out), T), kThreads, 0, st>>>(W, xin, out, n_in, n_out); 1647 return; 1648 } 1649 static const bool blas_f32 = std::getenv("STRATA_Q36_BLAS_F32") != nullptr; // the hipBLAS / cuBLAS SGEMM (A/B) 1650 if (!blas_f32 && n_in % 4 == 0) { 1651 // K split so that about 128 blocks run (the partials summed in a fixed order: deterministic); TM = 4 rows per 1652 // thread for the 256-wide router, 1 for the narrow ones (alpha / beta 32, the gate 1) 1653 const int tm = n_out > 64 ? 4 : 1; 1654 const int gx = (n_out + 63) / 64, gy = (T + 16 * tm - 1) / (16 * tm); 1655 const int want = std::max(1, std::min(kSplitK, 128 / std::max(1, gx * gy))); 1656 const int kz = (n_in / want + 15) / 16 * 16; 1657 const int splits = (n_in + kz - 1) / kz; 1658 float* dst = splits > 1 ? sk_part : out; 1659 if (tm == 4) k_sgemm_nt<4><<<dim3(gx, gy, splits), 256, 0, st>>>(W, xin, dst, n_in, n_out, T, n_out, kz); 1660 else k_sgemm_nt<1><<<dim3(gx, gy, splits), 256, 0, st>>>(W, xin, dst, n_in, n_out, T, n_out, kz); 1661 if (splits > 1) 1662 k_sum_splits<<<grid1((int64_t) T * n_out), kThreads, 0, st>>>(sk_part, out, (int64_t) T * n_out, splits); 1663 return; 1664 } 1665 const float one = 1.0f, zero = 0.0f; 1666 if (cublasSgemm(blas, CUBLAS_OP_T, CUBLAS_OP_N, n_out, T, n_in, &one, W, n_in, xin, n_in, &zero, out, n_out) != 1667 CUBLAS_STATUS_SUCCESS) { 1668 std::fprintf(stderr, "strata-q36: cublasSgemm failed\n"); 1669 std::exit(1); 1670 } 1671 } 1672 1673 /// A batch above kGemmT tokens (a prompt chunk) runs its projections as GEMMs (prefill::Gemm::native: the GGUF 1674 /// blocks dequantized to FP16, the activations FP16); a decode batch on the native MMVQ (q8_1 activations). 1675 static constexpr int kGemmT = 8; 1676 void prep(const float* xin, int n, int T, void* q) { 1677 if (T > kGemmT) k_to_f16<<<grid1((int64_t) n * T), kThreads, 0, st>>>(xin, x16, (int64_t) n * T); 1678 else quant(xin, n, T, q); 1679 } 1680 void apply(const Mat& w, const void* q, float* out, int T) { 1681 if (T > kGemmT) gemm.native((const uint16_t*) x16, w.type, w.d, out, T, w.n_out, w.n_in); 1682 else mmq(w, q, out, T); 1683 } 1684 /// x [T][n] -> its q8_1 image (T contiguous columns: one vector of T * n), for every matrix that reads x. 1685 void quant(const float* xin, int n, int T, void* q) { K::native_quantize_q8_1(xin, q, n * T, 1, st); } 1686 // ---- decode kernels of this engine (q36_kernels.cuh), each the old kernel's bits (STRATA_Q36_VERIFY=1 compares) 1687 bool fast_k = std::getenv("STRATA_Q36_OLD_KERNELS") == nullptr; 1688 bool verify_k = std::getenv("STRATA_Q36_VERIFY") != nullptr; 1689 float* vbuf = nullptr; // verify scratch 1690 long long v_calls = 0, v_bad = 0; 1691 std::map<std::string, long long> v_by; // mismatches per check 1692 void verify_cmp(const char* what, const float* a, const float* b, size_t n, const std::string& tag = "") { 1693 CK(cudaStreamSynchronize(st)); 1694 std::vector<float> ha(n), hb(n); 1695 CK(cudaMemcpy(ha.data(), a, n * 4, cudaMemcpyDeviceToHost)); 1696 CK(cudaMemcpy(hb.data(), b, n * 4, cudaMemcpyDeviceToHost)); 1697 ++v_calls; 1698 if (std::memcmp(ha.data(), hb.data(), n * 4) != 0) { 1699 ++v_bad; 1700 size_t i = 0; 1701 while (i < n && std::memcmp(&ha[i], &hb[i], 4) == 0) ++i; 1702 if (++v_by[what] <= 3) 1703 std::fprintf(stderr, "strata-q36 VERIFY MISMATCH %s%s: first at %zu of %zu: new %g old %g (bits %08x %08x)\n", what, 1704 tag.c_str(), i, n, (double) ha[i], (double) hb[i], *(unsigned*) &ha[i], *(unsigned*) &hb[i]); 1705 } 1706 } 1707 /// A Q8_0 matrix that is not on the packed decode kernel (the shared expert, attention k / v: fewer than 2048 1708 /// rows) for T <= 8 columns: one warp per row (q36k::k_q8_rows) in place of the 4-warp block of 1709 /// native_small_mmvq_kernel; the same bits. 1710 bool q8_small(const Mat& w, const void* q, float* out, int T) { 1711 if (!fast_k || w.type != 8 || T < 1 || T > 8 || w.n_in % 32 != 0) return false; 1712 if (K::native_q8_0_packed_eligible(w.n_in, w.n_out) && K::native_q8_0_packed_enabled()) return false; 1713 const int nb = w.n_in / 32; 1714 if (nb > 64) return false; 1715 const void* wp = w.d; 1716 const half* dpl = nullptr; 1717 const int NJ = nb <= 32 ? 1 : 2; 1718#define Q36_Q8(NCV) \ 1719 case NCV: \ 1720 if (NJ == 1) q36k::launch_q8_rows<NCV, 1, false>(wp, dpl, q, out, nb, w.n_out, st); \ 1721 else q36k::launch_q8_rows<NCV, 2, false>(wp, dpl, q, out, nb, w.n_out, st); \ 1722 break; 1723 switch (T) { Q36_Q8(1) Q36_Q8(2) Q36_Q8(3) Q36_Q8(4) Q36_Q8(5) Q36_Q8(6) Q36_Q8(7) Q36_Q8(8) } 1724#undef Q36_Q8 1725 if (verify_k) { 1726 if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4)); 1727 const size_t qb = K::native_q8_1_bytes(w.n_in, 1); 1728 for (int c0 = 0; c0 < T; c0 += 8) { 1729 const int nc = std::min(8, T - c0); 1730 K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, vbuf + (size_t) c0 * w.n_out, w.n_in, w.n_out, 1731 nc, st); 1732 } 1733 verify_cmp("q8_small", out, vbuf, (size_t) T * w.n_out, 1734 " n_in " + std::to_string(w.n_in) + " n_out " + std::to_string(w.n_out) + " T " + std::to_string(T)); 1735 } 1736 return true; 1737 } 1738 // ---- the q8_1 images produced by the norm kernels themselves (fast_k, T <= kGemmT): xq_ready = the layer's input h is 1739 // already quantized in xq (k_moe_out_small of the layer before), xq_post = the MoE input h is (k_add_rms_q) 1740 bool xq_ready = false, xq_post = false; 1741 void* vq = nullptr; 1742 void verify_q8(const char* what, const float* hsrc, int T, const std::string& tag) { 1743 const int N = (int) m->g.n_embd; 1744 const size_t qb = K::native_q8_1_bytes(N, 1); 1745 if (!vq) CK(cudaMalloc(&vq, qb * 8)); 1746 K::native_quantize_q8_1(hsrc, vq, N * T, 1, st); 1747 const long long before = v_bad; 1748 verify_cmp(what, (const float*) xq, (const float*) vq, qb * (size_t) T / 4, tag); 1749 if (v_bad != before && std::getenv("STRATA_Q36_VDEBUG") && v_by[what] <= 2) { // a mismatching block, on the host 1750 std::vector<uint8_t> a(qb * (size_t) T), b(qb * (size_t) T); 1751 std::vector<float> hv((size_t) N * T); 1752 CK(cudaMemcpy(a.data(), xq, a.size(), cudaMemcpyDeviceToHost)); 1753 CK(cudaMemcpy(b.data(), vq, b.size(), cudaMemcpyDeviceToHost)); 1754 CK(cudaMemcpy(hv.data(), hsrc, hv.size() * 4, cudaMemcpyDeviceToHost)); 1755 for (size_t o = 0; o < a.size(); o += 36) 1756 if (std::memcmp(&a[o], &b[o], 36) != 0) { 1757 const size_t blk = o / 36; 1758 float v[32], t[32]; 1759 for (int l = 0; l < 32; ++l) v[l] = t[l] = hv[blk * 32 + (size_t) l]; 1760 for (int off = 16; off > 0; off >>= 1) { // the xor butterfly, lane by lane 1761 float u[32]; 1762 for (int l = 0; l < 32; ++l) u[l] = t[l] + t[l ^ off]; 1763 std::memcpy(t, u, sizeof(u)); 1764 } 1765 unsigned ds_a, ds_b; 1766 const __half t0h = __float2half(t[0]); // host side: __half_as_ushort is __device__ only 1767 unsigned short t0bits; 1768 std::memcpy(&t0bits, &t0h, sizeof(t0bits)); 1769 std::memcpy(&ds_a, &a[o], 4); 1770 std::memcpy(&ds_b, &b[o], 4); 1771 std::fprintf(stderr, "VDEBUG block %zu: ds new %08x old %08x, qs bytes %s, cpu butterfly sum %.9g (half %04x)\n", 1772 blk, ds_a, ds_b, std::memcmp(&a[o + 4], &b[o + 4], 32) == 0 ? "equal" : "DIFFER", (double) t[0], 1773 (unsigned) t0bits); 1774 break; 1775 } 1776 } 1777 } 1778 void prep_in(int T) { 1779 if (xq_ready && T <= kGemmT) { 1780 xq_ready = false; 1781 return; 1782 } 1783 xq_ready = false; 1784 prep(h, (int) m->g.n_embd, T, xq); 1785 } 1786 void add_rms_post(const Layer& L, int T) { 1787 const int N = (int) m->g.n_embd; 1788 xq_post = false; 1789 if (fast_k && T <= kGemmT) { 1790 if (verify_k) { 1791 if (!vx_) { 1792 CK(cudaMalloc((void**) &vx_, (size_t) 8 * 2048 * 4)); 1793 CK(cudaMalloc((void**) &vh_, (size_t) 8 * 2048 * 4)); 1794 } 1795 CK(cudaMemcpyAsync(vx_, x, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, st)); 1796 k_add_rms<<<T, kThreads, 0, st>>>(vx_, y, L.post_norm, vh_, N, m->eps); 1797 } 1798 q36k::k_add_rms_q<<<T, 256, 0, st>>>(x, y, L.post_norm, h, (q36k::QB*) xq, N, m->eps); 1799 xq_post = true; 1800 if (verify_k) { 1801 verify_cmp("add_rms x", x, vx_, (size_t) T * N, " T " + std::to_string(T)); 1802 verify_cmp("add_rms h", h, vh_, (size_t) T * N, " T " + std::to_string(T)); 1803 verify_q8("add_rms q8", h, T, " T " + std::to_string(T)); 1804 } 1805 return; 1806 } 1807 k_add_rms<<<T, kThreads, 0, st>>>(x, y, L.post_norm, h, N, m->eps); 1808 } 1809 /// The shared expert's gate + up + SwiGLU + q8_1 image (into q8) for T <= 4 rows in one launch (q36k::k_sh_gu), else false. 1810 bool shared_gu(const Layer& L, int T) { 1811 const int FS = (int) m->g.n_ff_shexp; 1812 const Mat &a = L.sh_gate, &b = L.sh_up; 1813 if (!fast_k || T < 1 || T > 4 || a.type != 8 || b.type != 8 || a.n_in != b.n_in || a.n_out != FS || b.n_out != FS || 1814 a.n_in % 32 != 0 || a.n_in / 32 > 64 || a.n_in / 32 <= 32 || FS % 32 != 0 || 1815 (K::native_q8_0_packed_eligible(a.n_in, a.n_out) && K::native_q8_0_packed_enabled())) 1816 return false; 1817 const int nb = a.n_in / 32; 1818 const dim3 grid((unsigned) (FS / 32)); 1819 const bool pkd = false; 1820 const uint8_t* wa = a.d; 1821 const uint8_t* wb = b.d; 1822 const half* da = nullptr; 1823 const half* db = nullptr; 1824#define Q36_SH(NCV) \ 1825 case NCV: \ 1826 if (pkd) \ 1827 q36k::k_sh_gu<NCV, 2, true><<<grid, 1024, 0, st>>>(wa, da, wb, db, (const q36k::QB*) xq, \ 1828 (q36k::QB*) q8, nb, FS); \ 1829 else \ 1830 q36k::k_sh_gu<NCV, 2, false><<<grid, 1024, 0, st>>>(wa, nullptr, wb, nullptr, (const q36k::QB*) xq, \ 1831 (q36k::QB*) q8, nb, FS); \ 1832 break; 1833 switch (T) { Q36_SH(1) Q36_SH(2) Q36_SH(3) Q36_SH(4) } 1834#undef Q36_SH 1835 if (verify_k) { 1836 if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4)); 1837 if (!vq) CK(cudaMalloc(&vq, K::native_q8_1_bytes(m->g.n_embd, 1) * 8)); 1838 float* vg = vbuf; 1839 float* vu = vbuf + (size_t) 8 * FS; 1840 mmq_ref(a, xq, vg, T); 1841 mmq_ref(b, xq, vu, T); 1842 K::native_swiglu_quantize_q8_1(vg, vu, vq, FS, T, st); 1843 verify_cmp("shared_gu q8", (const float*) q8, (const float*) vq, K::native_q8_1_bytes(FS, 1) * (size_t) T / 4, 1844 " T " + std::to_string(T)); 1845 } 1846 return true; 1847 } 1848 /// The old products (native MMVQ), for the checks. 1849 void mmq_ref(const Mat& w, const void* q, float* out, int T) { 1850 const size_t qb = K::native_q8_1_bytes(w.n_in, 1); 1851 for (int c0 = 0; c0 < T; c0 += 8) { 1852 const int nc = std::min(8, T - c0); 1853 K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, out + (size_t) c0 * w.n_out, w.n_in, w.n_out, nc, st); 1854 } 1855 } 1856 void group_old(const Layer& L, const int32_t* slot_of, int T, unsigned long long* o_ptr, int32_t* o_start, int32_t* o_ng, 1857 int32_t* o_dst, int32_t* o_tok, const uint8_t* wb = nullptr) { 1858 const int Kp = (int) m->top_k, n_ent = T * Kp; 1859 const uint8_t* bl = wb ? wb : L.blobs; 1860 if (slot_of) 1861 k_group_hy<<<1, kThreads, 0, st>>>(ids, n_ent, Kp, (int) m->g.n_expert, slot_of, bl, L.stride, o_ptr, o_start, 1862 o_ng, o_dst, o_tok); 1863 else 1864 k_group<<<1, kThreads, 0, st>>>(ids, n_ent, Kp, (int) m->g.n_expert, bl, L.stride, o_ptr, o_start, o_ng, o_dst, 1865 o_tok); 1866 } 1867 /// VERIFY: the old grouping of the current `ids` into scratch, compared with grp_ptr / grp_start / n_groups / ent_dst / ent_tok. 1868 void group_verify(const Layer& L, const int32_t* slot_of, int T) { 1869 if (!vgrp) CK(cudaMalloc((void**) &vgrp, 2048)); 1870 unsigned long long* o_ptr = (unsigned long long*) vgrp; 1871 int32_t* o_start = (int32_t*) (o_ptr + 65); 1872 int32_t* o_ng = o_start + 66; 1873 int32_t* o_dst = o_ng + 2; 1874 int32_t* o_tok = o_dst + 64; 1875 group_old(L, slot_of, T, o_ptr, o_start, o_ng, o_dst, o_tok); 1876 CK(cudaStreamSynchronize(st)); 1877 int nn = 0, no = 0; 1878 CK(cudaMemcpy(&nn, n_groups, 4, cudaMemcpyDeviceToHost)); 1879 CK(cudaMemcpy(&no, o_ng, 4, cudaMemcpyDeviceToHost)); 1880 ++v_calls; 1881 bool bad = nn != no; 1882 if (!bad) { 1883 std::vector<unsigned long long> a((size_t) nn + 1), b((size_t) nn + 1); 1884 std::vector<int32_t> sa((size_t) nn + 1), sb((size_t) nn + 1), da(64), db(64), ta(64), tb(64); 1885 CK(cudaMemcpy(a.data(), grp_ptr, (size_t) nn * 8, cudaMemcpyDeviceToHost)); 1886 CK(cudaMemcpy(b.data(), o_ptr, (size_t) nn * 8, cudaMemcpyDeviceToHost)); 1887 CK(cudaMemcpy(sa.data(), grp_start, ((size_t) nn + 1) * 4, cudaMemcpyDeviceToHost)); 1888 CK(cudaMemcpy(sb.data(), o_start, ((size_t) nn + 1) * 4, cudaMemcpyDeviceToHost)); 1889 const int tot = sa[(size_t) nn]; 1890 CK(cudaMemcpy(da.data(), ent_dst, (size_t) tot * 4, cudaMemcpyDeviceToHost)); 1891 CK(cudaMemcpy(db.data(), o_dst, (size_t) tot * 4, cudaMemcpyDeviceToHost)); 1892 CK(cudaMemcpy(ta.data(), ent_tok, (size_t) tot * 4, cudaMemcpyDeviceToHost)); 1893 CK(cudaMemcpy(tb.data(), o_tok, (size_t) tot * 4, cudaMemcpyDeviceToHost)); 1894 bad = std::memcmp(a.data(), b.data(), (size_t) nn * 8) != 0 || 1895 std::memcmp(sa.data(), sb.data(), ((size_t) nn + 1) * 4) != 0 || 1896 std::memcmp(da.data(), db.data(), (size_t) tot * 4) != 0 || 1897 std::memcmp(ta.data(), tb.data(), (size_t) tot * 4) != 0; 1898 } 1899 if (bad) { 1900 ++v_bad; 1901 if (v_bad <= 20) std::fprintf(stderr, "strata-q36 VERIFY MISMATCH group (T %d, groups %d vs %d)\n", T, nn, no); 1902 } 1903 } 1904 bool grouped_by_route = false; // route_group already filled the group arrays of this layer 1905 /// The router's top-k and the grouping of the picks in one launch (T <= 8, 256 experts, 8 picks); the logits are in logits_r. 1906 /// `slot_of`: the hybrid mode's slot table (null: every expert resident). Returns false when the old kernels must run. 1907 bool route_group(const Layer& L, const int32_t* slot_of, int T, int ld) { 1908 const int Kp = (int) m->top_k; 1909 grouped_by_route = false; 1910 if (!fast_k || T > 8 || m->g.n_expert != 256 || Kp != 8) return false; 1911 if (slot_of) 1912 q36k::k_route_group<true><<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, ld, slot_of, L.blobs, L.stride, grp_ptr, 1913 grp_start, n_groups, ent_dst, ent_tok); 1914 else 1915 q36k::k_route_group<false><<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, ld, nullptr, L.blobs, L.stride, grp_ptr, 1916 grp_start, n_groups, ent_dst, ent_tok); 1917 grouped_by_route = true; 1918 if (verify_k) { 1919 // the old top-k into scratch, the ids / weights compared, then the old grouping of the new ids 1920 if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4)); 1921 int32_t* vid = (int32_t*) (vbuf + 8 * 8192); 1922 float* vw = vbuf + 8 * 8192 + 64; 1923 K::native_router_topk(logits_r, vid, vw, 256, Kp, T, st); 1924 verify_cmp("route ids", (const float*) ids, (const float*) vid, (size_t) T * Kp, " T " + std::to_string(T)); 1925 verify_cmp("route weights", ewts, vw, (size_t) T * Kp, " T " + std::to_string(T)); 1926 group_verify(L, slot_of, T); 1927 } 1928 return true; 1929 } 1930 /// The routed entries of T rows grouped per expert (k_group; with slot_of the hybrid mode's k_group_hy). 1931 void group_entries(const Layer& L, const int32_t* slot_of, int T, const uint8_t* wb = nullptr) { 1932 if (grouped_by_route) { // route_group did it 1933 grouped_by_route = false; 1934 return; 1935 } 1936 const int Kp = (int) m->top_k, n_ent = T * Kp; 1937 if (fast_k && n_ent <= 64) { 1938 if (slot_of) 1939 q36k::k_group_small<true><<<1, 64, 0, st>>>(ids, n_ent, Kp, slot_of, wb ? wb : L.blobs, L.stride, grp_ptr, grp_start, 1940 n_groups, ent_dst, ent_tok); 1941 else 1942 q36k::k_group_small<false><<<1, 64, 0, st>>>(ids, n_ent, Kp, nullptr, wb ? wb : L.blobs, L.stride, grp_ptr, grp_start, 1943 n_groups, ent_dst, ent_tok); 1944 if (verify_k) group_verify(L, slot_of, T); 1945 return; 1946 } 1947 group_old(L, slot_of, T, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, wb); 1948 } 1949 void* vgrp = nullptr; 1950 float *vx_ = nullptr, *vh_ = nullptr; 1951 /// The MoE block's end (k_moe_out) for T rows. 1952 void moe_end(int T, const int32_t* prow, const float* shared, const float* sgate, const float* wn, float* hout, int sgs = 1) { 1953 const int N = (int) m->g.n_embd, Kp = (int) m->top_k; 1954 const bool small = fast_k && T <= 8 && N <= 2048 && N % 256 == 0 && Kp <= 15; 1955 if (small && verify_k) { 1956 if (!vx_) { 1957 CK(cudaMalloc((void**) &vx_, (size_t) 8 * 2048 * 4)); 1958 CK(cudaMalloc((void**) &vh_, (size_t) 8 * 2048 * 4)); 1959 } 1960 CK(cudaMemcpyAsync(vx_, x, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, st)); 1961 k_moe_out<<<T, kThreads, 0, st>>>(vx_, eparts, prow, ewts, Kp, shared, sgate, sgs, wn, vh_, N, m->eps); 1962 } 1963 if (small) { 1964 const bool mkq = wn != nullptr && hout == h; // the next layer's input, quantized here 1965 q36k::k_moe_out_small<<<T, 1024, 0, st>>>(x, eparts, prow, ewts, Kp, shared, sgate, sgs, wn, hout, N, m->eps, 1966 mkq ? (q36k::QB*) xq : nullptr); 1967 xq_ready = mkq; 1968 if (verify_k) { 1969 if (mkq) verify_q8("moe_out q8", hout, T, " T " + std::to_string(T)); 1970 verify_cmp("moe_out x", x, vx_, (size_t) T * N, " T " + std::to_string(T)); 1971 if (wn) verify_cmp("moe_out h", hout, vh_, (size_t) T * N, " T " + std::to_string(T)); 1972 } 1973 return; 1974 } 1975 xq_ready = false; 1976 k_moe_out<<<T, kThreads, 0, st>>>(x, eparts, prow, ewts, Kp, shared, sgate, sgs, wn, hout, N, m->eps); 1977 } 1978 /// y [T][n_out] = W x from x's q8_1 image, 8 columns per launch. 1979 void mmq(const Mat& w, const void* q, float* out, int T) { 1980 if (q8_small(w, q, out, T)) return; 1981 const size_t qb = K::native_q8_1_bytes(w.n_in, 1); 1982 for (int c0 = 0; c0 < T; c0 += 8) { 1983 const int nc = std::min(8, T - c0); 1984 K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, out + (size_t) c0 * w.n_out, w.n_in, 1985 w.n_out, nc, st); 1986 } 1987 } 1988 1989 /// One layer for T rows: x (the residual) += mixer(h); then MoE; x += moe; `hout` = rms(x) * wn (the next norm). 1990 /// `li` indexes the layer's state; positions *dpos .. + T - 1 (device), p0 the same on the host (eager grids); 1991 /// `verify`: a verify window - the GDN state is read, not written (commit() writes it for the kept rows). 1992 void layer(const Layer& L, size_t li, int T, int64_t p0, const int32_t* dpos, bool graph_mode, bool verify, 1993 const float* wn, float* hout) { 1994 const auto& g = m->g; 1995 const int N = (int) g.n_embd, Kp = (int) m->top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp; 1996 const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, D = (int) g.ssm_state_size; 1997 const int C = (int) g.ssm_conv_channels; 1998 const int H = (int) g.n_head, HKV = (int) g.n_head_kv, HD = (int) g.head_dim; 1999 if (!L.attn) { 2000 float* qkv_b = verify ? v_qkv[li] : qkv; 2001 float* hc_b = verify ? v_hc[li] : hc; 2002 float* al_b = verify ? v_alpha[li] : alpha; 2003 float* be_b = verify ? v_beta[li] : beta; 2004 prep_in(T); 2005 apply(L.qkv, xq, qkv_b, T); 2006 apply(L.zg, xq, z, T); 2007 if (T <= kGemmT) { 2008 k_gdn_ab<<<dim3(rows8(2 * HV), T), kThreads, 0, st>>>(L.alpha, L.beta, h, L.dt, L.ssm_a, al_b, be_b, N, 2009 HV); 2010 } else { 2011 f32mm(L.alpha, h, al_b, N, HV, T); 2012 f32mm(L.beta, h, be_b, N, HV, T); 2013 k_gdn_gb<<<grid1((int64_t) HV * T), kThreads, 0, st>>>(al_b, L.dt, L.ssm_a, be_b, HV, T); 2014 } 2015 if (rows_mode) { // batch rows: a slot's rows (one, or a verify window's two) in sequence on its own state 2016 k_conv_seq<<<dim3(C / 128, rows_G), 128, 0, st>>>(nullptr, qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, 1, 2017 !verify, d_conv_tab + li * n_sess, d_gslot, d_grow0, d_gcnt); 2018 k_gdn_seq<<<dim3(HV, rows_G), dim3(128, 4), 0, st>>>(nullptr, hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, 2019 gdn_y, HK, HV, 1, !verify, d_S_tab + li * n_sess, 2020 d_gslot, d_grow0, d_gcnt); 2021 } else { 2022 // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a 2023 // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's 2024 // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs 2025 // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a 2026 // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) 2027 // a prompt chunk: tiles of kConvTile tokens side by side (tile mode); else one block per head walks the tokens 2028 const int tiles = (fast_k && T > kGemmT && !verify) ? (T + kConvTile - 1) / kConvTile : 1; 2029 k_conv_seq<<<dim3(C / 128, tiles), 128, 0, st>>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); 2030 if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm 2031 k_gdn_seq_cols<<<dim3(HV, kGdnColGroups), dim3(128 / kGdnColGroups, 16), 0, st>>>(S[li], hc_b, C, al_b, 2032 be_b, gdn_y, HK, HV, T); 2033 k_gdn_norm<<<dim3(HV, T), 128, 0, st>>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); 2034 } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows 2035 k_gdn_seq<<<HV, dim3(128, 4), 0, st>>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, 2036 T, !verify); 2037 } 2038 } 2039 mm(L.ssm_out, gdn_y, y, T); 2040 } else { 2041 prep_in(T); 2042 apply(L.wq, xq, qg, T); 2043 apply(L.wk, xq, kx, T); 2044 apply(L.wv, xq, vx, T); 2045 RowSel rs; 2046 if (rows_mode) { 2047 rs.cell = d_rcell; 2048 rs.slot = d_rslot; 2049 rs.delta = d_rdelta; 2050 rs.kc = d_kc_tab + li * n_sess; 2051 rs.vc = d_vc_tab + li * n_sess; 2052 } 2053 k_attn_prep<<<dim3(H + HKV, T), kThreads, 0, st>>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, rows_mode ? nullptr : kc[li], 2054 rows_mode ? nullptr : vc[li], H, HKV, HD, m->n_rot, dpos, ctx, 2055 m->rope_base, m->eps, d_delta, mtab_now, rs); 2056 if (T > kGemmT) { 2057 // a prompt chunk: scores = Q K^T and out = P V as FP16 GEMMs (FP32 accumulation, FP32 scores) per KV 2058 // head (its query heads one strided batch over the shared K / V), the causal softmax in between writing 2059 // FP16 probabilities; the queries in slices whose scores fit 2060 const int P = (int) p0 + T; 2061 const int ldp = (P + 7) / 8 * 8; 2062 const int tq = (int) std::max<int64_t>(1, std::min<int64_t>(T, (int64_t) (kAttScoreFloats / ((size_t) H * ldp)))); 2063 const int G = H / HKV; 2064 const float one = 1.0f, zero = 0.0f; 2065 k_kv_f16<<<grid1((int64_t) HKV * P * HD), kThreads, 0, st>>>(kc[li], vc[li], k16, v16, ctx, P, HD, HKV); 2066 k_to_f16<<<grid1((int64_t) T * H * HD), kThreads, 0, st>>>(q, q16, (int64_t) T * H * HD); 2067 for (int t0 = 0; t0 < T; t0 += tq) { 2068 const int nt = std::min(tq, T - t0); 2069 for (int kvh = 0; kvh < HKV; ++kvh) { 2070 const __half* Kh = k16 + (size_t) kvh * P * HD; 2071 const __half* Qh = q16 + ((size_t) t0 * H + kvh * G) * HD; 2072 float* Sh = att_s + (size_t) kvh * G * nt * ldp; 2073 if (cublasGemmStridedBatchedEx(blas, CUBLAS_OP_T, CUBLAS_OP_N, P, nt, HD, &one, Kh, CUDA_R_16F, HD, 2074 0, Qh, CUDA_R_16F, H * HD, HD, &zero, Sh, CUDA_R_32F, ldp, 2075 (long long) nt * ldp, G, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != 2076 CUBLAS_STATUS_SUCCESS) { 2077 std::fprintf(stderr, "strata-q36: attention scores GEMM failed\n"); 2078 std::exit(1); 2079 } 2080 } 2081 k_attn_softmax16<<<dim3(nt, H), kThreads, 0, st>>>(att_s, att_p16, ldp, nt, P, (int) p0 + t0, 2082 1.0f / sqrtf((float) HD)); 2083 for (int kvh = 0; kvh < HKV; ++kvh) { 2084 const __half* Vh = v16 + (size_t) kvh * P * HD; 2085 const __half* Sh = att_p16 + (size_t) kvh * G * nt * ldp; 2086 float* Oh = att + ((size_t) t0 * H + kvh * G) * HD; 2087 if (cublasGemmStridedBatchedEx(blas, CUBLAS_OP_N, CUBLAS_OP_N, HD, nt, P, &one, Vh, CUDA_R_16F, HD, 2088 0, Sh, CUDA_R_16F, ldp, (long long) nt * ldp, &zero, Oh, CUDA_R_32F, 2089 H * HD, HD, G, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != 2090 CUBLAS_STATUS_SUCCESS) { 2091 std::fprintf(stderr, "strata-q36: attention values GEMM failed\n"); 2092 std::exit(1); 2093 } 2094 } 2095 } 2096 k_gate_mul<<<grid1((int64_t) T * H * HD), kThreads, 0, st>>>(att, gate, (int64_t) T * H * HD); 2097 } else { 2098 // split-K over 256-cell chunks; the chunk grid covers every cell a row can see (graph mode: the whole 2099 // context, past-the-end chunks return at once) 2100 const int rows_per = att_rows / H; 2101 for (int t0 = 0; t0 < T; t0 += rows_per) { 2102 const int nt = std::min(rows_per, T - t0); 2103 const int nc = graph_mode ? n_chunk 2104 : (int) std::min<int64_t>(n_chunk, (p0 + t0 + nt + kChunkCells - 1) / kChunkCells); 2105 k_attn_part<<<dim3(nc, nt * H), kChunkCells, 0, st>>>(q, rows_mode ? nullptr : kc[li], 2106 rows_mode ? nullptr : vc[li], dpos, t0, H, HKV, ctx, 2107 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl, rs); 2108 k_attn_merge<<<nt * H, HD, 0, st>>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att, rs); 2109 } 2110 } 2111 mm(L.wo, att, y, T); 2112 } 2113 add_rms_post(L, T); 2114 // routed experts (one token: the router and the shared expert's gate in one product, the gate its last row) 2115 const bool one = T == 1; 2116 // a decode batch of up to 8 rows takes the router and the shared expert's gate in one product too (rows of 257) when the fused 2117 // router follows; the prompt chunks and the checks keep the separate products 2118 const bool ext = one || (fast_k && std::getenv("STRATA_Q36_NO_EXT") == nullptr && !verify_k && T <= kGemmT && g.n_expert == 256 && Kp == 8); 2119 if (ext) f32mm(L.router_ext, h, logits_r, N, (int) g.n_expert + 1, T); 2120 else f32mm(L.router, h, logits_r, N, (int) g.n_expert, T); 2121 // the hybrid rows path: a batch of up to hybrid_t rows; when only the MTP block is hybrid, its every batch 2122 // (its prompt pass too: no staging buffers then) 2123 const bool hy_rows = lhy(li) && (T <= hybrid_t || !main_hybrid); 2124 const bool mmq_rows = !hy_rows && T > kGemmT && use_pf; 2125 if (!(!mmq_rows && route_group(L, hy_rows ? hy[li].slot_of_d : nullptr, T, ext ? (int) g.n_expert + 1 : (int) g.n_expert))) 2126 K::native_router_topk(logits_r, ids, ewts, (int) g.n_expert, Kp, T, st); 2127 const int64_t n_ent = (int64_t) T * Kp; 2128 const int32_t* prow = nullptr; 2129 if (hy_rows) { 2130 moe_hybrid_gpu(L, li, T); 2131 } else if (T > kGemmT && use_pf) { 2132 // a prompt chunk: each expert's weights read once for all its rows, on Strata's fused int8 kernels where they 2133 // cover the layer (fused_on), else on llama.cpp's MMQ. In the hybrid mode the layer's experts come streamed 2134 // (stream_take); the routing counts feed the slots' scores there 2135 const int ne = (int) g.n_expert; 2136 const bool fz = fused_on[li] != 0; 2137 const bool i8l = i8_on[li] != 0; // our int8 kernels (no sorted-row tables: they collect their own groups) 2138 const bool mql = !fz && !i8l; // MMQ 2139 int64_t maxr = 0; 2140 if (mql || lhy(li)) { 2141 CK(cudaMemsetAsync(rcnt, 0, (size_t) ne * 4, st)); 2142 k_route_count<<<grid1(n_ent), kThreads, 0, st>>>(ids, (int) n_ent, rcnt); 2143 } 2144 if (mql) { 2145 // MMQ: the entries sorted by expert on the device, gate+up as one [2 FF] product per expert, SwiGLU, down 2146 // into rows the combine reads through entry -> sorted row 2147 k_route_scan<<<1, 32, 0, st>>>(rcnt, ne, rbounds, rcur, rmax); 2148 k_route_scatter<<<grid1(n_ent), kThreads, 0, st>>>(ids, (int) n_ent, Kp, rcur, ent_dst, ent_tok, rinv); 2149 CK(cudaMemcpyAsync(hpin + 10, rmax, 4, cudaMemcpyDeviceToHost, st)); 2150 } 2151 if (lhy(li)) CK(cudaMemcpyAsync(h_cnt + li * g.n_expert, rcnt, (size_t) ne * 4, cudaMemcpyDeviceToHost, st)); 2152 if (mql || lhy(li)) { 2153 CK(cudaStreamSynchronize(st)); 2154 if (lhy(li)) 2155 for (int x = 0; x < ne; ++x) hy[li].score[(size_t) x] += h_cnt[li * g.n_expert + x]; 2156 maxr = hpin[10]; 2157 } 2158 const uint8_t* wbase = lhy(li) ? stream_take((int) li) : L.blobs; 2159 if (fz) { 2160 // the layer's input to int8 once per token, the rows of each expert grouped on the device (no host wait), 2161 // then per batch of experts gate/up + SwiGLU + H to int8 + down into the entries' rows (f_slot) 2162 FQ::quantize_act_native(h, T, N, f_xq, st); 2163 PF::group(ids, n_ent, Kp, ne, f_scr, f_slot, f_src, st); 2164 const FQ::NativeGeom ng{L.L.gu_type, L.L.d_type, L.L.gu_row, L.L.d_row, L.L.up_off, L.L.down_off}; 2165 for (int e = 0; e < ne; e += FQ::kQ36MaxBatch) { 2166 FQ::Batch b; 2167 b.e0 = e; 2168 b.e1 = std::min(ne, e + FQ::kQ36MaxBatch); 2169 for (int x = b.e0; x < b.e1; ++x) b.blob[x - b.e0] = wbase + (size_t) x * L.stride; 2170 FQ::experts_native_ext(b, ng, ne, n_ent, f_scr, f_xq, f_src, f_ha, eparts, st); 2171 } 2172 prow = f_slot; 2173 } else if (i8l) { 2174 // our int8 expert kernels: the layer's rows quantized once, the groups per expert (blobs from wbase: the streamed ring in the hybrid mode), gate/up + SwiGLU + H to int8 and 2175 // the down rows into eparts by entry (prow stays null, as the grouped kernels). A chunk whose experts average few rows takes the grouped kernels (the few-rows route). 2176 group_entries(L, nullptr, T, wbase); 2177 if (K::q36_i8_chunk_takes(n_ent, ne, i8_few)) { 2178 K::native_expert_i8_quantize(h, T, N, i8x, st); 2179 K::native_expert_i8(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, std::min<int64_t>(n_ent, g.n_expert), n_ent, i8x, escr, eparts, st); 2180 } else { 2181 quant(h, N, T, xq); 2182 K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, std::min<int64_t>(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); 2183 } 2184 } else { 2185 MMQ::quantize(h, ent_tok, mq_x, L.L.gu_type, N, N, n_ent, st); 2186 MMQ::Product gu; 2187 gu.w = wbase; gu.type = L.L.gu_type; gu.w_rows = 2 * FF; gu.w_cols = N; gu.expert_bytes = L.stride; 2188 gu.n = ne; gu.xq = mq_x; gu.bounds = rbounds; gu.ids = ident; gu.total_rows = n_ent; gu.max_rows = maxr; 2189 gu.dst = mq_gu; gu.ld_dst = 2 * FF; 2190 mctx->run(gu, st); 2191 MMQ::swiglu(mq_gu, mq_h, n_ent, FF, false, st); 2192 MMQ::quantize(mq_h, nullptr, mq_hq, L.L.d_type, FF, FF, n_ent, st); 2193 MMQ::Product dn; 2194 dn.w = wbase + L.L.down_off; dn.type = L.L.d_type; dn.w_rows = N; dn.w_cols = FF; 2195 dn.expert_bytes = L.stride; dn.n = ne; dn.xq = mq_hq; dn.bounds = rbounds; dn.ids = ident; 2196 dn.total_rows = n_ent; dn.max_rows = maxr; dn.dst = eparts; dn.ld_dst = N; 2197 mctx->run(dn, st); 2198 prow = rinv; 2199 } 2200 if (lhy(li)) stream_done(); 2201 } else { 2202 group_entries(L, nullptr, T); 2203 if (!xq_post) quant(h, N, T, xq); // the experts' and the shared expert's input 2204 K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, 2205 std::min<int64_t>(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); 2206 } 2207 // the shared expert, scaled by sigmoid(w . h) 2208 if (T > kGemmT) k_to_f16<<<grid1((int64_t) N * T), kThreads, 0, st>>>(h, x16, (int64_t) N * T); 2209 if (T <= kGemmT) { 2210 if (!shared_gu(L, T)) { 2211 apply(L.sh_gate, xq, sg, T); 2212 apply(L.sh_up, xq, su, T); 2213 K::native_swiglu_quantize_q8_1(sg, su, q8, FS, T, st); // SwiGLU and its q8_1 image in one launch 2214 } 2215 mmq(L.sh_down, q8, sy, T); 2216 } else { 2217 apply(L.sh_gate, xq, sg, T); 2218 apply(L.sh_up, xq, su, T); 2219 k_swiglu<<<grid1((int64_t) T * FS), kThreads, 0, st>>>(sg, su, shh, (int64_t) T * FS); 2220 mm(L.sh_down, shh, sy, T); 2221 } 2222 if (!ext) f32mm(L.sh_gate_inp, h, sgate, N, 1, T); 2223 if (hy_rows) moe_hybrid_cpu(li, T); // the CPU pool's experts (while the GPU runs the rest), merged 2224 // the combine, the shared expert's gate, the residual add and the next norm in one launch 2225 moe_end(T, prow, sy, ext ? logits_r + g.n_expert : sgate, wn, hout, ext ? (int) g.n_expert + 1 : 1); 2226 } 2227 2228 /// The main model over T rows (device `tok`, positions p0 .. p0 + T - 1, also at *pos0): hmain gets every row's 2229 /// final normed hidden; `heads` rows from the end get logits (rows [T - heads, T): logits row r - (T - heads)) and 2230 /// their greedy picks (`pick`). `verify`: a verify window (the GDN state left for commit()). 2231 void forward(int T, int64_t p0, int heads, bool graph_mode, bool verify) { 2232 const auto& g = m->g; 2233 const int N = (int) g.n_embd; 2234 if (main_hybrid && T > hybrid_t && use_pf) { 2235 std::vector<int> seq; 2236 for (size_t l = 0; l < m->layers.size(); ++l) 2237 if (lhy(l)) seq.push_back((int) l); 2238 stream_begin(seq); 2239 } 2240 K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok, T, N, x, st); 2241 if (map_on) k_put_rows<<<T, kThreads, 0, st>>>(x, d_img, d_map, N); // a picture's cells take its rows 2242 k_rms<<<T, kThreads, 0, st>>>(x, m->layers[0].attn_norm, h, N, m->eps); // later layers: from k_moe_out 2243 for (size_t l = 0; l < m->layers.size(); ++l) { 2244 const bool last = l + 1 == m->layers.size(); 2245 layer(m->layers[l], l, T, p0, pos0, graph_mode, verify, last ? m->out_norm : m->layers[l + 1].attn_norm, 2246 last ? hmain : h); 2247 } 2248 if (heads > 0) head_rows(hmain + (size_t) (T - heads) * N, heads, logits, pick); 2249 } 2250 /// logits [n][V] = W_out hn rows, and each row's greedy pick. 2251 void head_rows(const float* hn, int n, float* lg, int32_t* pk) { 2252 const auto& g = m->g; 2253 mm(m->head, hn, lg, n); 2254 k_argmax<<<dim3(kArgBlocks, n), kThreads, 0, st>>>(lg, (int) g.n_vocab, pk, amv, ami, false); 2255 k_argmax<<<dim3(1, n), kThreads, 0, st>>>(lg, kArgBlocks, pk, amv, ami, true); 2256 } 2257 2258 /// The draft head: the MTP block's pick over the first `draft_n` rows of the output matrix only (the lowest token ids are 2259 /// the most frequent ones). A draft only proposes: the verify window decides, so a token outside the subset is a 2260 /// rejected draft and nothing else - the answer is the plain greedy answer whatever draft_n is. 0 = the whole vocabulary. 2261 int draft_n = 0; 2262 void head_draft(const float* hn) { 2263 const auto& g = m->g; 2264 const int N = (int) g.n_embd; 2265 const Mat& hd = m->head; 2266 if (!fast_k || draft_n <= 0 || draft_n >= g.n_vocab || draft_n % 8 != 0 || hd.type != 8 || hd.n_in != N || N / 32 != 64) { 2267 head_rows(hn, 1, logits_m, pick_m); 2268 return; 2269 } 2270 quant(hn, N, 1, q8); 2271 const uint8_t* pk = nullptr; 2272 for (const auto& p : m->packed) 2273 if (std::get<0>(p) == hd.d) pk = std::get<1>(p); 2274 if (pk) { 2275 const half* dpl = reinterpret_cast<const half*>(pk + (size_t) hd.n_in * hd.n_out); 2276 q36k::launch_q8_rows<1, 2, true>(pk, dpl, q8, logits_m, 64, draft_n, st); 2277 } else { 2278 q36k::launch_q8_rows<1, 2, false>(hd.d, nullptr, q8, logits_m, 64, draft_n, st); 2279 } 2280 k_argmax<<<dim3(kArgBlocks, 1), kThreads, 0, st>>>(logits_m, draft_n, pick_m, amv, ami, false); 2281 k_argmax<<<dim3(1, 1), kThreads, 0, st>>>(logits_m, kArgBlocks, pick_m, amv, ami, true); 2282 } 2283 2284 /// The MTP block over T rows: row t reads token tok_m[t] at position p0 + t (also at *pos0_m) and the seed hidden 2285 /// seeds[t] (the main model's normed hidden of the position before, or the block's own for a chained draft); 2286 /// hmtp gets each row's normed output. `draft`: logits of the last row and its pick (`pick_m`). 2287 void forward_mtp(int T, int64_t p0, const float* seeds, bool draft, bool graph_mode) { 2288 const auto& g = m->g; 2289 const int N = (int) g.n_embd; 2290 if (main_hybrid && lhy(m->layers.size()) && T > hybrid_t && use_pf) stream_begin({(int) m->layers.size()}); 2291 K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); 2292 if (map_on) k_put_rows<<<T, kThreads, 0, st>>>(y, d_img, d_map, N); 2293 k_rms_ld<<<T, kThreads, 0, st>>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] 2294 k_rms_ld<<<T, kThreads, 0, st>>>(seeds, N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] 2295 mm(m->eh_proj, mtp_cat, x, T); 2296 k_rms<<<T, kThreads, 0, st>>>(x, m->mtp.attn_norm, h, N, m->eps); 2297 layer(m->mtp, m->layers.size(), T, p0, pos0_m, graph_mode, false, m->mtp_shnorm, hmtp); 2298 if (draft) head_draft(hmtp + (size_t) (T - 1) * N); 2299 } 2300 2301 /// After a verify window of T rows: the GDN state takes the first n_keep rows (conv history and recurrence run 2302 /// again over the rows' kept inputs). 2303 void commit(int n_keep) { 2304 const auto& g = m->g; 2305 const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, C = (int) g.ssm_conv_channels; 2306 for (size_t l = 0; l < m->layers.size(); ++l) { 2307 const Layer& L = m->layers[l]; 2308 if (L.attn) continue; 2309 k_conv_seq<<<C / 128, 128, 0, st>>>(conv[l], v_qkv[l], L.conv, hc, C, 2 * HK, m->eps, n_keep, true); 2310 k_gdn_seq<<<HV, dim3(128, 4), 0, st>>>(S[l], v_hc[l], C, v_alpha[l], v_beta[l], z, L.ssm_norm, m->eps, 2311 nullptr, HK, HV, n_keep, true); 2312 } 2313 } 2314 2315 // ---- the hybrid mode 2316 const Layer& layer_at(int li) const { return li < (int) m->layers.size() ? m->layers[(size_t) li] : m->mtp; } 2317 2318 /// A streamed forward over the state indices `seq`: the first two layers' experts start copying now. 2319 void stream_begin(const std::vector<int>& seq) { 2320 stream_seq = seq; 2321 stream_pos = 0; 2322 for (int i = 0; i < 2 && i < (int) seq.size(); ++i) stream_kick(i); 2323 } 2324 void stream_kick(int i) { // the i-th layer of the sequence into staging buffer i % 2, after its last reader 2325 const int b = i % 2; 2326 const Layer& L = layer_at(stream_seq[(size_t) i]); 2327 CK(cudaStreamWaitEvent(cst, ev_used[b], 0)); 2328 // the experts with a VRAM slot come from it (device to device, at VRAM speed), only the others over PCIe; runs 2329 // of consecutive experts from the same source in one copy each. STRATA_Q36_STREAM_ALL=1: the whole layer from 2330 // host memory (the first version: PCIe-bound) 2331 static const bool all = std::getenv("STRATA_Q36_STREAM_ALL") != nullptr; 2332 const int ne = (int) m->g.n_expert; 2333 const Hy& H = hy[(size_t) stream_seq[(size_t) i]]; 2334 // fewer than half the experts resident (a 12 GB card): the one whole-layer copy is faster than many small ones 2335 // (RTX 3060, UD-Q4_K_XL at 37 of 256: pp2048 1970 whole vs 1540 in runs) 2336 if (all || 2 * L.n_slots < ne) { 2337 CK(cudaMemcpyAsync(stage[b], L.hblobs, L.stride * (size_t) ne, cudaMemcpyHostToDevice, cst)); 2338 } else { 2339 for (int x = 0; x < ne;) { 2340 const bool dev = H.slot_of[(size_t) x] >= 0; 2341 int y = x + 1; 2342 if (dev) // consecutive slots holding consecutive experts 2343 while (y < ne && H.slot_of[(size_t) y] == H.slot_of[(size_t) y - 1] + 1) ++y; 2344 else 2345 while (y < ne && H.slot_of[(size_t) y] < 0) ++y; 2346 const size_t n = (size_t) (y - x) * L.stride; 2347 if (dev) 2348 CK(cudaMemcpyAsync(stage[b] + (size_t) x * L.stride, L.blobs + (size_t) H.slot_of[(size_t) x] * L.stride, 2349 n, cudaMemcpyDeviceToDevice, cst)); 2350 else 2351 CK(cudaMemcpyAsync(stage[b] + (size_t) x * L.stride, L.hblobs + (size_t) x * L.stride, n, 2352 cudaMemcpyHostToDevice, cst)); 2353 x = y; 2354 } 2355 } 2356 CK(cudaEventRecord(ev_copy[b], cst)); 2357 } 2358 const uint8_t* stream_take(int li) { 2359 if (stream_pos >= (int) stream_seq.size() || stream_seq[(size_t) stream_pos] != li) { 2360 std::fprintf(stderr, "strata-q36: the expert stream is out of step (layer %d)\n", li); 2361 std::exit(1); 2362 } 2363 const int b = stream_pos % 2; 2364 CK(cudaStreamWaitEvent(st, ev_copy[b], 0)); 2365 return stage[b]; 2366 } 2367 void stream_done() { 2368 const int b = stream_pos % 2; 2369 CK(cudaEventRecord(ev_used[b], st)); 2370 if (stream_pos + 2 < (int) stream_seq.size()) stream_kick(stream_pos + 2); 2371 ++stream_pos; 2372 } 2373 2374 /// The GPU half of a hybrid MoE: the routing to the host, the resident experts' entries grouped and run. 2375 void moe_hybrid_gpu(const Layer& L, size_t li, int T) { 2376 const auto& g = m->g; 2377 const int N = (int) g.n_embd, Kp = (int) m->top_k; 2378 const int64_t n_ent = (int64_t) T * Kp; 2379 CK(cudaMemcpyAsync(h_ids, ids, (size_t) n_ent * 4, cudaMemcpyDeviceToHost, st)); 2380 CK(cudaMemcpyAsync(h_h, h, (size_t) T * N * 4, cudaMemcpyDeviceToHost, st)); 2381 CK(cudaEventRecord(ev_route, st)); 2382 group_entries(L, hy[li].slot_of_d, T); 2383 if (!xq_post) quant(h, N, T, xq); // the experts' and the shared expert's input 2384 K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, 2385 std::min<int64_t>(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); 2386 } 2387 /// The CPU half: the entries without a slot on the pool (ggml-cpu's arithmetic for the layer's formats), their 2388 /// rows uploaded and merged into the entries' rows. 2389 void moe_hybrid_cpu(size_t li, int T) { 2390#if defined(STRATA_Q36_CPU_POOL) 2391 namespace C = strata::kernels::cpu; 2392 const auto& g = m->g; 2393 const int N = (int) g.n_embd, Kp = (int) m->top_k; 2394 const int n_ent = T * Kp; 2395 Hy& H = hy[li]; 2396 const Layer& L = layer_at((int) li); 2397 while (cudaEventQuery(ev_route) == cudaErrorNotReady) { 2398 } 2399 const auto t0 = Clock::now(); 2400 // the missed entries per expert (up to MAXT tokens per job) 2401 jobs.clear(); 2402 std::vector<char> quantized((size_t) T, 0); 2403 int n_miss = 0; 2404 std::map<int, size_t> open; // expert -> its job with room 2405 const bool defer = rows_deferred && li < m->layers.size(); 2406 if (defer) { 2407 if (row_ids.size() < m->layers.size()) row_ids.resize(m->layers.size()); 2408 row_ids[li].assign(h_ids, h_ids + n_ent); 2409 } 2410 for (int e = 0; e < n_ent; ++e) { 2411 const int x = h_ids[e]; 2412 if (!defer) H.score[(size_t) x] += 1.0; 2413 h_miss[e] = H.slot_of[(size_t) x] < 0; 2414 if (!h_miss[e]) continue; 2415 ++n_miss; 2416 const int t = e / Kp; 2417 if (!quantized[(size_t) t]) { 2418 C::native_quant_act(H.fmt, h_h + (size_t) t * N, acts + (size_t) t * C::kNativeActBytes); 2419 quantized[(size_t) t] = 1; 2420 } 2421 auto it = open.find(x); 2422 if (it == open.end() || jobs[it->second].nt == C::MAXT) { 2423 C::ExpertJobMulti j; 2424 j.blob = L.hblobs + (size_t) x * L.stride; 2425 jobs.push_back(j); 2426 it = open.insert_or_assign(x, jobs.size() - 1).first; 2427 } 2428 C::ExpertJobMulti& j = jobs[it->second]; 2429 j.nact[j.nt] = acts + (size_t) t * C::kNativeActBytes; 2430 j.out[j.nt] = cpu_out + (size_t) e * N; 2431 ++j.nt; 2432 } 2433 hy_cpu += n_miss; 2434 hy_gpu += n_ent - n_miss; 2435 if (n_miss == 0) return; 2436 pool->run_split_multi_native(H.fmt, jobs.data(), (int) jobs.size()); 2437 hy_cpu_ms += ms_since(t0); 2438 CK(cudaMemcpyAsync(ecpu, cpu_out, (size_t) n_ent * N * 4, cudaMemcpyHostToDevice, st)); 2439 CK(cudaMemcpyAsync(d_miss, h_miss, (size_t) n_ent * 4, cudaMemcpyHostToDevice, st)); 2440 k_merge_cpu<<<n_ent, kThreads, 0, st>>>(eparts, ecpu, d_miss, N); 2441#else 2442 (void) li; 2443 (void) T; 2444#endif 2445 } 2446 2447 /// The slots to the experts the routing used most (the counts halved each time): at most max_swaps replacements 2448 /// over all layers, between forwards (the copies are on the engine's stream). 2449 void rebalance(int max_swaps) { 2450 static const bool off = std::getenv("STRATA_Q36_FIXED_SLOTS") != nullptr; // the slots as placed (tests) 2451 if (!m->hybrid || off || warming) return; 2452 const int64_t ne = m->g.n_expert; 2453 int left = max_swaps; 2454 for (size_t li = 0; li < hy.size() && left > 0; ++li) { 2455 Hy& H = hy[li]; 2456 const Layer& L = layer_at((int) li); 2457 const int S = L.n_slots; 2458 if (S <= 0 || S >= ne) continue; 2459 std::vector<int> order((size_t) ne); 2460 for (int x = 0; x < ne; ++x) order[(size_t) x] = x; 2461 std::sort(order.begin(), order.end(), [&](int a, int b) { return H.score[(size_t) a] > H.score[(size_t) b]; }); 2462 // residents outside the top S, lowest score first: the slots to give away 2463 std::vector<int> victims; 2464 for (int s = 0; s < S; ++s) victims.push_back(s); 2465 std::sort(victims.begin(), victims.end(), [&](int a, int b) { 2466 return H.score[(size_t) H.exp_in_slot[(size_t) a]] < H.score[(size_t) H.exp_in_slot[(size_t) b]]; 2467 }); 2468 size_t vi = 0; 2469 bool changed = false; 2470 for (int i = 0; i < S && left > 0; ++i) { 2471 const int x = order[(size_t) i]; 2472 if (H.slot_of[(size_t) x] >= 0) continue; 2473 while (vi < victims.size()) { 2474 const int s = victims[vi]; 2475 const int y = H.exp_in_slot[(size_t) s]; 2476 if (H.score[(size_t) y] >= H.score[(size_t) x]) { vi = victims.size(); break; } 2477 // y must not be in the top S itself 2478 ++vi; 2479 H.slot_of[(size_t) y] = -1; 2480 H.slot_of[(size_t) x] = s; 2481 H.exp_in_slot[(size_t) s] = x; 2482 CK(cudaMemcpyAsync(L.blobs + (size_t) s * L.stride, L.hblobs + (size_t) x * L.stride, L.L.bytes, 2483 cudaMemcpyHostToDevice, st)); 2484 --left; 2485 ++hy_swaps; 2486 changed = true; 2487 break; 2488 } 2489 if (vi >= victims.size()) break; 2490 } 2491 if (changed) 2492 CK(cudaMemcpyAsync(H.slot_of_d, H.slot_of.data(), (size_t) ne * 4, cudaMemcpyHostToDevice, st)); 2493 for (double& v : H.score) v *= 0.5; 2494 } 2495 CK(cudaStreamSynchronize(st)); // slot_of's host copy is pageable: the upload is done before it changes 2496 } 2497 2498 void shrink_att(size_t floats) { 2499 CK(cudaDeviceSynchronize()); 2500 CK(cudaFree(att_s)); 2501 CK(cudaFree(att_p16)); 2502 kAttScoreFloats = floats; 2503 att_s = dalloc(kAttScoreFloats); 2504 att_p16 = dalloc_t<__half>(kAttScoreFloats); 2505 CK(cudaDeviceSynchronize()); 2506 } 2507 void reset_graphs() { 2508 for (GSet& gset : gsets) { 2509 for (cudaGraphExec_t* g : {&gset.g1, &gset.gm1}) 2510 if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } 2511 for (auto& g : gset.gv) 2512 if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } 2513 } 2514 for (auto& kv : row_graphs) 2515 if (kv.second) CK(cudaGraphExecDestroy(kv.second)); 2516 row_graphs.clear(); 2517 } 2518 2519 template <class F> void graph_run(cudaGraphExec_t& gx, F body) { 2520 if (!use_graph) { body(); return; } 2521 if (!gx) { 2522 cudaGraph_t graph = nullptr; 2523 CK(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal)); 2524 body(); 2525 CK(cudaStreamEndCapture(st, &graph)); 2526 CK(cudaGraphInstantiate(&gx, graph, 0)); 2527 CK(cudaGraphDestroy(graph)); 2528 } 2529 CK(cudaGraphLaunch(gx, st)); 2530 } 2531 2532 // ---- pictures (--vision). A request with pictures hands the engine its rows (the encoder's, in prompt order), the 2533 // cell -> row map of its <|image_pad|> cells and the M-RoPE table of its prompt cells; the cells below the prompt 2534 // length take their rotary positions from the table, the text after it continues at cell + delta (what the pictures 2535 // did not use of their cells: llama.cpp's mtmd advances the text position by max(nx, ny) per picture). 2536 bool img_active = false; 2537 void set_images(const std::vector<float>& rows, const std::vector<int32_t>& cell_row, const std::vector<int32_t>& mrope, 2538 int64_t n_prompt, int32_t delta) { 2539 const size_t need = rows.size(); 2540 if (need > img_cap) { 2541 CK(cudaDeviceSynchronize()); 2542 if (d_img) CK(cudaFree(d_img)); 2543 CK(cudaMalloc((void**) &d_img, need * 4)); 2544 img_cap = need; 2545 } 2546 CK(cudaMemcpy(d_img, rows.data(), need * 4, cudaMemcpyHostToDevice)); 2547 CK(cudaMemcpy(d_mtab, mrope.data(), mrope.size() * 4, cudaMemcpyHostToDevice)); 2548 img_map = cell_row; 2549 img_prompt_cells = n_prompt; 2550 img_active = true; 2551 set_delta(delta); 2552 } 2553 void clear_images() { 2554 img_map.clear(); 2555 img_active = false; 2556 img_prompt_cells = 0; 2557 mtab_now = nullptr; 2558 map_on = false; 2559 set_delta(0); 2560 } 2561 /// A forward over the cells [c0, c0 + T): the picture rows of its cells, and the table when it is a prompt's. 2562 void chunk_pictures(int64_t c0, int T) { 2563 mtab_now = nullptr; 2564 map_on = false; 2565 if (!img_active) return; 2566 if (c0 < img_prompt_cells) mtab_now = d_mtab; 2567 bool any = false; 2568 for (int j = 0; j < T; ++j) { 2569 const int64_t c = c0 + j; 2570 const int32_t v = c < (int64_t) img_map.size() ? img_map[(size_t) c] : -1; 2571 h_map[j] = v; 2572 any = any || v >= 0; 2573 } 2574 if (any) { 2575 CK(cudaMemcpyAsync(d_map, h_map, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2576 map_on = true; 2577 } 2578 } 2579 2580 /// The tokens at the current position: a prompt in chunks (eager), one token from the decode graph. The last 2581 /// token's logits stay in `logits` (its greedy pick in `pick`), hlast its normed hidden. With the MTP block the 2582 /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). on_chunk(done) runs 2583 /// after every chunk; false ends the read there (a cancelled request): the tokens processed are returned. 2584 template <class F> int64_t process(const int32_t* toks, int64_t n, F on_chunk_) { 2585 const int N = (int) m->g.n_embd; 2586 auto on_chunk = [&](int64_t done) -> bool { // a callback returning void never cancels 2587 if constexpr (std::is_void_v<decltype(on_chunk_(done))>) { 2588 on_chunk_(done); 2589 return true; 2590 } else { 2591 return on_chunk_(done); 2592 } 2593 }; 2594 if (n == 1) { 2595 CK(cudaStreamSynchronize(st)); // the pinned staging is free again 2596 hpin[0] = toks[0]; 2597 hpin[1] = (int32_t) pos; 2598 CK(cudaMemcpyAsync(tok, hpin, 4, cudaMemcpyHostToDevice, st)); 2599 CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2600 chunk_pictures(pos, 1); 2601 rows_deferred = true; 2602 // a prompt cell of a picture request (its rotary position is in the table, its row a picture's) runs eagerly 2603 if (mtab_now || map_on) forward(1, pos, 1, false, false); 2604 else graph_run(gs().g1, [&] { forward(1, pos, 1, use_graph, false); }); 2605 mtab_now = nullptr; 2606 map_on = false; 2607 rows_deferred = false; 2608 CK(cudaMemcpyAsync(hlast, hmain, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2609 pos += 1; 2610 after_rows(1); 2611 on_chunk(1); 2612 return 1; 2613 } 2614 for (int64_t i = 0; i < n; i += tmax) { 2615 const int T = (int) std::min<int64_t>(tmax, n - i); 2616 CK(cudaStreamSynchronize(st)); 2617 hpin[1] = (int32_t) pos; 2618 CK(cudaMemcpyAsync(tok, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2619 CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2620 chunk_pictures(pos, T); 2621 forward(T, pos, i + T == n ? 1 : 0, false, false); 2622 if (m->has_mtp && mtp_d > 0) { 2623 // seeds: h_{q-1} for each row q: hlast, then this chunk's rows 0 .. T - 2 (in `y`, free here) 2624 CK(cudaMemcpyAsync(mtp_seed(), hlast, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2625 if (T > 1) 2626 CK(cudaMemcpyAsync(mtp_seed() + N, hmain, (size_t) (T - 1) * N * 4, cudaMemcpyDeviceToDevice, st)); 2627 CK(cudaMemcpyAsync(tok_m, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2628 CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2629 forward_mtp(T, pos, mtp_seed(), false, false); 2630 } 2631 CK(cudaMemcpyAsync(hlast, hmain + (size_t) (T - 1) * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2632 pos += T; 2633 CK(cudaStreamSynchronize(st)); 2634 mtab_now = nullptr; 2635 map_on = false; 2636 if (!on_chunk(i + T)) { 2637 if (m->hybrid) rebalance(hybrid_swaps_after_prompt); 2638 return i + T; 2639 } 2640 } 2641 if (m->hybrid) rebalance(hybrid_swaps_after_prompt); 2642 return n; 2643 } 2644 2645 // ---- batch rows: one decode window for the next token of several sessions 2646 struct Row { int slot; int32_t tok; }; 2647 long long win_count = 0; 2648 std::map<int, cudaGraphExec_t> row_graphs; // by (rows, groups, kind): graphs of the batch windows 2649 /// A slot's rows of one window: `n` consecutive cells from the session's position (1: the next token; 2: also an MTP 2650 /// proposal the window verifies). 2651 struct Group { int slot; int n; int32_t tok[2]; }; 2652 int32_t rows_pick[kVerify] = {}; 2653 int rows_G_last = 0; // groups of the window run last (commit_rows takes their keep counts) 2654 2655 void run_graph_key(int key, const std::function<void()>& body) { 2656 if (!use_graph) { body(); return; } 2657 graph_run(row_graphs[key], body); 2658 } 2659 2660 /// One window over the groups' rows. `verify`: a verify window - the GDN state is read, not written (commit_rows writes 2661 /// it for the kept rows) and the sessions' positions stay. The greedy picks end up in rows_pick (one per row), every 2662 /// row's logits in `logits`. Without verify the sessions' positions advance by their rows. 2663 void run_rows(const Group* gr, int G, bool verify) { 2664 sess[(size_t) cur].pos = pos; 2665 CK(cudaStreamSynchronize(st)); // the pinned staging is free again 2666 int64_t pmax = 0; 2667 int T = 0; 2668 for (int g = 0; g < G; ++g) { 2669 const Sess& ss = sess[(size_t) gr[g].slot]; 2670 hrow[40 + g] = gr[g].slot; 2671 hrow[48 + g] = T; 2672 hrow[56 + g] = gr[g].n; 2673 for (int j = 0; j < gr[g].n; ++j) { 2674 hrow[T] = gr[g].tok[j]; 2675 hrow[8 + T] = (int32_t) (ss.pos + j); 2676 hrow[16 + T] = gr[g].slot; 2677 hrow[24 + T] = ss.rdelta; 2678 ++T; 2679 } 2680 pmax = std::max<int64_t>(pmax, ss.pos + gr[g].n - 1); 2681 } 2682 CK(cudaMemcpyAsync(tok, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2683 CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2684 CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2685 CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2686 CK(cudaMemcpyAsync(d_gslot, hrow + 40, (size_t) G * 4, cudaMemcpyHostToDevice, st)); 2687 CK(cudaMemcpyAsync(d_grow0, hrow + 48, (size_t) G * 4, cudaMemcpyHostToDevice, st)); 2688 CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); 2689 mtab_now = nullptr; 2690 map_on = false; 2691 rows_mode = true; 2692 rows_G = G; 2693 rows_deferred = true; 2694 run_graph_key((verify ? 1000 : 0) + G * 10 + (T - G), [&] { forward(T, pmax, T, use_graph, verify); }); 2695 rows_deferred = false; 2696 rows_mode = false; 2697 CK(cudaMemcpyAsync(hrow + 32, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); 2698 CK(cudaStreamSynchronize(st)); 2699 for (int r = 0; r < T; ++r) rows_pick[r] = hrow[32 + r]; 2700 if (!verify) 2701 for (int g = 0; g < G; ++g) sess[(size_t) gr[g].slot].pos += gr[g].n; 2702 pos = sess[(size_t) cur].pos; 2703 rows_G_last = G; 2704 if (m->hybrid) { 2705 count_rows(T); 2706 if (++win_count % kRebalanceEvery == 0) rebalance(8); 2707 } 2708 } 2709 /// One window for the next token of each of the rows' sessions (no proposals): the greedy picks in rows_pick. 2710 void step_rows(const Row* rows, int nb) { 2711 Group gr[kVerify]; 2712 for (int r = 0; r < nb; ++r) gr[r] = {rows[r].slot, 1, {rows[r].tok, 0}}; 2713 run_rows(gr, nb, false); 2714 } 2715 /// After run_rows(.., verify = true): the GDN state of group g takes its first keep[g] rows (the conv history and the 2716 /// recurrence run again over the rows' kept inputs, as commit() does) and the session advances by keep[g]. 2717 void commit_rows(const Group* gr, const int* keep, int G) { 2718 const auto& g = m->g; 2719 const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, C = (int) g.ssm_conv_channels; 2720 sess[(size_t) cur].pos = pos; 2721 for (int i = 0; i < G; ++i) hrow[56 + i] = keep[i]; // (hrow's slot / first-row words are the window's, unchanged) 2722 CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); 2723 rows_mode = true; 2724 rows_G = G; 2725 run_graph_key(2000 + G, [&] { 2726 for (size_t l = 0; l < m->layers.size(); ++l) { 2727 const Layer& L = m->layers[l]; 2728 if (L.attn) continue; 2729 k_conv_seq<<<dim3(C / 128, G), 128, 0, st>>>(nullptr, v_qkv[l], L.conv, hc, C, 2 * HK, m->eps, 1, true, 2730 d_conv_tab + l * n_sess, d_gslot, d_grow0, d_gcnt); 2731 k_gdn_seq<<<dim3(HV, G), dim3(128, 4), 0, st>>>(nullptr, v_hc[l], C, v_alpha[l], v_beta[l], z, L.ssm_norm, 2732 m->eps, nullptr, HK, HV, 1, true, d_S_tab + l * n_sess, 2733 d_gslot, d_grow0, d_gcnt); 2734 } 2735 }); 2736 rows_mode = false; 2737 CK(cudaStreamSynchronize(st)); 2738 for (int i = 0; i < G; ++i) sess[(size_t) gr[i].slot].pos += keep[i]; 2739 pos = sess[(size_t) cur].pos; 2740 } 2741 2742 /// The MTP block over rows of several sessions: row r reads token tok at cell `cell` of session `slot` and the seed 2743 /// hidden at `seed` (device, n_embd floats); its draft - the block's greedy pick after that row - ends up in 2744 /// mtp_pick[r], and the block's K / V cells are written. 2745 struct MtpRow { int slot; int32_t tok; int64_t cell; const float* seed; }; 2746 int32_t mtp_pick[kVerify] = {}; 2747 float* logits_mr = nullptr; 2748 int32_t* pick_mr = nullptr; 2749 void mtp_rows(const MtpRow* rows, int T) { 2750 const auto& g = m->g; 2751 const int N = (int) g.n_embd; 2752 if (!logits_mr) { 2753 logits_mr = dalloc((size_t) kVerify * g.n_vocab); 2754 pick_mr = dalloc_t<int32_t>(kVerify); 2755 } 2756 sess[(size_t) cur].pos = pos; 2757 CK(cudaStreamSynchronize(st)); 2758 int64_t pmax = 0; 2759 for (int r = 0; r < T; ++r) { 2760 hrow[r] = rows[r].tok; 2761 hrow[8 + r] = (int32_t) rows[r].cell; 2762 hrow[16 + r] = rows[r].slot; 2763 hrow[24 + r] = sess[(size_t) rows[r].slot].rdelta; 2764 pmax = std::max<int64_t>(pmax, rows[r].cell); 2765 CK(cudaMemcpyAsync(mtp_seed() + (size_t) r * N, rows[r].seed, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2766 } 2767 CK(cudaMemcpyAsync(tok_m, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2768 CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2769 CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2770 CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2771 mtab_now = nullptr; 2772 map_on = false; 2773 rows_mode = true; 2774 rows_G = T; 2775 rows_deferred = true; 2776 run_graph_key(3000 + T, [&] { 2777 K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); 2778 k_rms_ld<<<T, kThreads, 0, st>>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] 2779 k_rms_ld<<<T, kThreads, 0, st>>>(mtp_seed(), N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] 2780 mm(m->eh_proj, mtp_cat, x, T); 2781 k_rms<<<T, kThreads, 0, st>>>(x, m->mtp.attn_norm, h, N, m->eps); 2782 layer(m->mtp, m->layers.size(), T, pmax, pos0_m, use_graph, false, m->mtp_shnorm, hmtp); 2783 mm(m->head, hmtp, logits_mr, T); 2784 k_argmax<<<dim3(kArgBlocks, T), kThreads, 0, st>>>(logits_mr, (int) g.n_vocab, pick_mr, amv, ami, false); 2785 k_argmax<<<dim3(1, T), kThreads, 0, st>>>(logits_mr, kArgBlocks, pick_mr, amv, ami, true); 2786 }); 2787 rows_deferred = false; 2788 rows_mode = false; 2789 CK(cudaMemcpyAsync(hrow + 32, pick_mr, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); 2790 CK(cudaStreamSynchronize(st)); 2791 for (int r = 0; r < T; ++r) mtp_pick[r] = hrow[32 + r]; 2792 } 2793 /// Row r's logits of the last step_rows, on the host. 2794 void host_logits_row(int r, std::vector<float>& out) { 2795 out.resize((size_t) m->g.n_vocab); 2796 CK(cudaMemcpyAsync(out.data(), logits + (size_t) r * m->g.n_vocab, out.size() * 4, cudaMemcpyDeviceToHost, st)); 2797 CK(cudaStreamSynchronize(st)); 2798 } 2799 2800 /// Session dst takes session src's state: the recurrent state, the cache's first src.pos cells, the position, the 2801 /// pictures' offset (for a conversation read in one session that continues in another). 2802 void copy_session(int src, int dst) { 2803 if (src == dst) return; 2804 sess[(size_t) cur].pos = pos; 2805 const auto& g = m->g; 2806 const Sess& a = sess[(size_t) src]; 2807 Sess& b = sess[(size_t) dst]; 2808 const size_t C = (size_t) g.ssm_conv_channels; 2809 const size_t row = (size_t) ctx * g.head_dim * 4; 2810 for (size_t l = 0; l < a.conv.size(); ++l) { 2811 if (a.conv[l]) { 2812 CK(cudaMemcpyAsync(b.conv[l], a.conv[l], C * (g.ssm_d_conv - 1) * 4, cudaMemcpyDeviceToDevice, st)); 2813 CK(cudaMemcpyAsync(b.S[l], a.S[l], (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, 2814 cudaMemcpyDeviceToDevice, st)); 2815 } 2816 if (a.kc[l] && a.pos > 0) { 2817 CK(cudaMemcpy2DAsync(b.kc[l], row, a.kc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, 2818 cudaMemcpyDeviceToDevice, st)); 2819 CK(cudaMemcpy2DAsync(b.vc[l], row, a.vc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, 2820 cudaMemcpyDeviceToDevice, st)); 2821 } 2822 } 2823 CK(cudaMemcpyAsync(b.hlast, a.hlast, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, st)); 2824 CK(cudaStreamSynchronize(st)); 2825 b.pos = a.pos; 2826 b.rdelta = a.rdelta; 2827 b.live = a.live; 2828 b.imgs = a.imgs; 2829 if (dst == cur) load_cur(); 2830 } 2831 int hybrid_swaps_after_prompt = 2048; 2832 /// the MTP seed rows of a prompt chunk: a buffer the block's own forward does not use (`moe_out`, [tmax][N]) 2833 float* mtp_seed() { return moe_out; } 2834 2835 /// One speculative step with D MTP drafts (greedy): `x` is the next token (decided, not processed); `fix` the 2836 /// tokens of the rows the block must redo first (the drafts the last window accepted, seeded by hmain rows 2837 /// 0 .. fix.size() - 1 of that window). Drafts d1 .. dD, then the window [x, d1 .. dD] through the main model; 2838 /// returns the accepted count a and writes the picks of rows 0 .. a (row a's pick is the token after them). 2839 /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft), so that a request 2840 /// stopped mid-answer leaves the state at the tokens it has shown: a conversation that continues from them (the server's 2841 /// hand-over of a stopped request to a batch slot) reuses it instead of reading them again. 2842 int spec_step(int x_tok, const std::vector<int32_t>& fix, int D, std::vector<int32_t>& drafts, int32_t* picks, 2843 const std::atomic<bool>* cancel = nullptr) { 2844 const int N = (int) m->g.n_embd; 2845 if (main_hybrid) D = std::min<int>(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1); 2846 const int T0 = (int) fix.size() + 1; // the redo rows and the row of x 2847 CK(cudaStreamSynchronize(st)); 2848 // rows of the first MTP call: (hmain row i, fix[i]) at positions pos - fix.size() + i, then (hlast, x) at pos 2849 for (int i = 0; i < (int) fix.size(); ++i) hpin[16 + i] = fix[(size_t) i]; 2850 hpin[16 + fix.size()] = x_tok; 2851 hpin[1] = (int32_t) (pos - (int64_t) fix.size()); 2852 CK(cudaMemcpyAsync(tok_m, hpin + 16, (size_t) T0 * 4, cudaMemcpyHostToDevice, st)); 2853 CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2854 // seeds: hmain rows 0 .. fix - 1 are the h of the positions before the fixed rows; hlast is that before x 2855 float* seeds = mtp_seed(); 2856 if (!fix.empty()) 2857 CK(cudaMemcpyAsync(seeds, hmain, fix.size() * (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2858 CK(cudaMemcpyAsync(seeds + fix.size() * (size_t) N, hlast, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2859 forward_mtp(T0, pos - (int64_t) fix.size(), seeds, D > 0, false); 2860 drafts.assign((size_t) D, 0); 2861 if (D > 0) { 2862 CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); 2863 CK(cudaStreamSynchronize(st)); 2864 drafts[0] = hpin[2]; 2865 } 2866 int last_row = T0 - 1; // the row of the previous MTP call whose output seeds the next draft 2867 for (int d = 1; d < D; ++d) { // chained: (the block's own output, the last draft) at the next position 2868 hpin[0] = drafts[(size_t) d - 1]; 2869 hpin[1] = (int32_t) (pos + d); 2870 CK(cudaMemcpyAsync(tok_m, hpin, 4, cudaMemcpyHostToDevice, st)); 2871 CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2872 CK(cudaMemcpyAsync(seeds, hmtp + (size_t) last_row * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2873 last_row = 0; 2874 if (mtp_graph) graph_run(gs().gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); 2875 else forward_mtp(1, pos + d, seeds, true, false); 2876 CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); 2877 CK(cudaStreamSynchronize(st)); 2878 drafts[(size_t) d] = hpin[2]; 2879 } 2880 // the verify window 2881 const int T = D + 1; 2882 hpin[16] = x_tok; 2883 for (int d = 0; d < D; ++d) hpin[17 + d] = drafts[(size_t) d]; 2884 hpin[1] = (int32_t) pos; 2885 CK(cudaMemcpyAsync(tok, hpin + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); 2886 CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); 2887 rows_deferred = true; 2888 graph_run(gs().gv[T], [&] { forward(T, pos, T, use_graph, true); }); 2889 rows_deferred = false; 2890 CK(cudaMemcpyAsync(hpin + 2, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); 2891 CK(cudaStreamSynchronize(st)); 2892 int a = 0; 2893 while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a; 2894 if (cancel != nullptr && cancel->load()) a = 0; 2895 for (int i = 0; i <= a; ++i) picks[i] = hpin[2 + i]; 2896 commit(a + 1); 2897 CK(cudaMemcpyAsync(hlast, hmain + (size_t) a * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); 2898 pos += a + 1; 2899 after_rows(a + 1); 2900 return a; 2901 } 2902 2903 /// The first prompt after load ran at about half speed (pp4096 rep 0: ~1770 tok/s against ~3290): the GPU's code 2904 /// objects, the BLAS handles' kernels and the decode graph are made on first use. A throw-away prompt of one 2905 /// chunk, a decode step and (with drafts) a speculative step at load do that before the first request; then the 2906 /// state, the cache position and the hybrid counters are as after load. 2907 bool warming = false; 2908 void warmup() { 2909 const auto t0 = Clock::now(); 2910 warming = true; 2911 const int32_t filler = 198; // a newline: any token works 2912 // #4708: the prompt chunk may equal or exceed the context (--context 2048 with a 2048-token chunk): warm only cells that 2913 // exist, and start the small-prompt, decode and speculative probes in a fresh sequence instead of appending past the cache. 2914 std::vector<int32_t> toks((size_t) std::max(1, std::min(tmax, ctx)), filler); 2915 process(toks.data(), (int64_t) toks.size(), [](int64_t) {}); 2916 reset(); 2917 if (tmax > kGemmT + 1 && ctx > kGemmT + 1) process(toks.data(), kGemmT + 1, [](int64_t) {}); // the smallest GEMM chunk too 2918 process(&filler, 1, [](int64_t) {}); 2919 if (mtp_d > 0) { 2920 std::vector<int32_t> fix, drafts; 2921 int32_t picks[16]; 2922 spec_step(filler, fix, mtp_d, drafts, picks); 2923 } 2924 CK(cudaStreamSynchronize(st)); 2925 warming = false; 2926 for (Hy& H : hy) std::fill(H.score.begin(), H.score.end(), 0.0); 2927 hy_cpu = hy_gpu = hy_swaps = 0; 2928 hy_cpu_ms = 0; 2929 reset(); 2930 std::fprintf(stderr, "strata-q36: warmed up in %.1f s (one prompt chunk, a decode step%s)\n", 2931 ms_since(t0) / 1000.0, mtp_d > 0 ? ", a speculative step" : ""); 2932 } 2933 2934 int greedy() { 2935 CK(cudaMemcpyAsync(hpin + 2, pick, 4, cudaMemcpyDeviceToHost, st)); 2936 CK(cudaStreamSynchronize(st)); 2937 return hpin[2]; 2938 } 2939 void host_logits(std::vector<float>& out) { 2940 out.resize((size_t) m->g.n_vocab); 2941 CK(cudaMemcpyAsync(out.data(), logits, out.size() * 4, cudaMemcpyDeviceToHost, st)); 2942 CK(cudaStreamSynchronize(st)); 2943 } 2944}; 2945 2946// ------------------------------------------------------------------------------------------------ expert placement 2947/// The routed experts after the engine's buffers: all in VRAM when they fit in `vram_gib` (< 0: the free VRAM less a 2948/// reserve), else the hybrid mode - every expert in host memory, the same number of VRAM slots per layer, a decode 2949/// batch's other experts on the CPU pool and a prompt chunk's streamed through two staging buffers. 2950bool place_experts(Model& m, Engine& E, double vram_gib, int threads, int hybrid_t, int slots, std::string& err) { 2951 const auto t0 = Clock::now(); 2952 const auto& g = m.g; 2953 const int64_t ne = g.n_expert; 2954 std::vector<Layer*> all; 2955 for (Layer& L : m.layers) all.push_back(&L); 2956 if (m.has_mtp) all.push_back(&m.mtp); 2957 size_t total = 0, per_slot = 0, max_layer = 0; 2958 for (Layer* L : all) { 2959 total += L->stride * (size_t) ne + kMmqTail; 2960 per_slot += L->stride; 2961 max_layer = std::max(max_layer, L->stride * (size_t) ne); 2962 } 2963 size_t fr = 0, tot = 0; 2964 CK(cudaMemGetInfo(&fr, &tot)); 2965 const size_t reserve = (size_t) 768 << 20; 2966 const size_t budget = vram_gib >= 0 ? (size_t) (vram_gib * (double) (1ull << 30)) 2967 : (fr > reserve ? fr - reserve : 0); 2968 // every expert fits once the packed Q8_0 decode copies are given back (a file a few GiB larger than the card's 2969 // room, UD-Q6_K_XL on 32 GB): drop them - the decode reads the GGUF layout then, bitwise the same outputs, a little 2970 // slower - rather than run the hybrid mode with its CPU share and streamed prompt layers. STRATA_Q36_KEEP_PACKED=1 2971 // keeps them (and the hybrid mode). 2972 size_t packed_bytes = 0; 2973 for (const auto& pk : m.packed) packed_bytes += std::get<2>(pk); 2974 size_t main_need = 0; // the main layers' experts (the MTP block's can go to the CPU, see below) 2975 for (Layer& L : m.layers) main_need += L.stride * (size_t) ne + kMmqTail; 2976 const size_t slack = ((size_t) 512 << 20) + (E.kAttScoreFloats - ((size_t) 16 << 20)) * 6; // reserve + scores 2977 const bool mtp_cpu_ok = m.has_mtp && std::getenv("STRATA_Q36_NO_MTP_CPU") == nullptr; 2978 if (slots <= 0 && vram_gib < 0 && total > budget && packed_bytes > 0 && 2979 (total <= budget + packed_bytes || (mtp_cpu_ok && main_need <= budget + packed_bytes + slack)) && 2980 std::getenv("STRATA_Q36_KEEP_PACKED") == nullptr) { 2981 CK(cudaDeviceSynchronize()); 2982 for (const auto& pk : m.packed) { 2983 K::native_q8_0_packed_unregister(std::get<0>(pk)); 2984 CK(cudaFree(std::get<1>(pk))); 2985 } 2986 m.packed.clear(); 2987 E.reset_graphs(); 2988 CK(cudaMemGetInfo(&fr, &tot)); 2989 std::fprintf(stderr, "strata-q36: the packed Q8_0 decode copies (%.2f GiB) given back so that every routed " 2990 "expert fits in VRAM (STRATA_Q36_KEEP_PACKED=1 keeps them and runs the hybrid mode)\n", 2991 (double) packed_bytes / (1 << 30)); 2992 } 2993 size_t budget2 = vram_gib >= 0 ? budget : (fr > reserve ? fr - reserve : 0); 2994 // the MAIN layers' experts fit, the MTP block's not all (UD-Q6_K_XL on 32 GB): the main layers all in VRAM - the 2995 // text is the all-in-VRAM text, the decode graph stays - and the MTP block's experts on slots + the CPU pool (its 2996 // drafts only). When that needs it: the attention scores buffer at 64 MB instead of 256 MB (more, smaller 2997 // slices in a long prompt) and the reserve at 256 MiB instead of 768 (said in the log; --expert-vram sets the 2998 // budget instead). STRATA_Q36_NO_MTP_CPU=1: the plain hybrid mode for every layer. 2999 size_t total_main = 0; 3000 for (Layer& L : m.layers) total_main += L.stride * (size_t) ne + kMmqTail; 3001 bool mtp_only = false; 3002 if (slots <= 0 && vram_gib < 0 && m.has_mtp && total > budget2 && std::getenv("STRATA_Q36_NO_MTP_CPU") == nullptr) { 3003 const size_t att_save = (E.kAttScoreFloats - ((size_t) 16 << 20)) * 6; // att_s (4 B) + att_p16 (2 B) 3004 const size_t small_reserve = (size_t) 256 << 20; 3005 const size_t room = fr + att_save > small_reserve ? fr + att_save - small_reserve : 0; 3006 if (total_main + ((size_t) 64 << 20) <= budget2) { 3007 mtp_only = true; 3008 } else if (total_main + ((size_t) 64 << 20) <= room) { 3009 E.shrink_att((size_t) 16 << 20); 3010 CK(cudaMemGetInfo(&fr, &tot)); 3011 budget2 = fr > small_reserve ? fr - small_reserve : 0; 3012 mtp_only = total_main + ((size_t) 64 << 20) <= budget2; 3013 std::fprintf(stderr, "strata-q36: the experts nearly fit: the attention scores buffer at 64 MB and the VRAM " 3014 "reserve at 256 MiB (instead of 768) so that every main layer's experts fit; a driver or " 3015 "another program needing more VRAM later can make it fail - --expert-vram GiB sets the experts' " 3016 "budget instead\n"); 3017 } 3018 } 3019 if (slots <= 0 && total <= budget2 && total + ((size_t) 256 << 20) <= fr) { 3020 std::vector<uint8_t> blob; 3021 for (Layer* L : all) { 3022 CK(cudaMalloc(&L->blobs, L->stride * (size_t) ne + kMmqTail)); 3023 CK(cudaMemset(L->blobs, 0, L->stride * (size_t) ne + kMmqTail)); 3024 blob.assign(L->L.bytes, 0); 3025 for (int64_t e = 0; e < ne; ++e) { 3026 expert_blob(*L, e, blob.data()); 3027 CK(cudaMemcpy(L->blobs + (size_t) e * L->stride, blob.data(), L->L.bytes, cudaMemcpyHostToDevice)); 3028 } 3029 L->n_slots = (int) ne; 3030 } 3031 std::fprintf(stderr, "strata-q36: every routed expert in VRAM (%.2f GiB) in %.1f s\n", (double) total / (1 << 30), 3032 ms_since(t0) / 1000.0); 3033 return true; 3034 } 3035#if !defined(STRATA_Q36_CPU_POOL) 3036 (void) threads; 3037 (void) hybrid_t; 3038 err = "the routed experts (" + std::to_string(total >> 20) + " MiB) do not fit in VRAM, and this build has no CPU " 3039 "expert pool (STRATA_NATIVE_EXPERTS=OFF)"; 3040 return false; 3041#else 3042 namespace C = strata::kernels::cpu; 3043 m.hybrid = true; 3044 E.main_hybrid = !mtp_only; 3045 if (E.main_hybrid) E.use_graph = false; // the host takes part in every layer 3046 E.mtp_graph = false; // the MTP block's layer is hybrid either way 3047 E.hybrid_t = std::max(1, std::min(hybrid_t, E.use_mmq ? E.tmax : E.tmax)); 3048 if (!E.use_pf) E.hybrid_t = E.tmax; // no streamed prompt path: every batch on slots + the pool 3049 const size_t staging = E.use_pf && E.main_hybrid ? 2 * (max_layer + kMmqTail) : 0; 3050 size_t slot_bytes = budget2 > staging ? budget2 - staging : 0; 3051 if (slot_bytes + staging + ((size_t) 256 << 20) > fr) slot_bytes = fr > staging + ((size_t) 512 << 20) ? fr - staging - ((size_t) 512 << 20) : 0; 3052 // --expert-slots: that many per layer (tests: the same split with and without the MTP block) 3053 int S = slots > 0 ? (int) std::min<int64_t>(ne, slots) : (int) std::min<size_t>((size_t) ne, slot_bytes / per_slot); 3054 if (mtp_only) { // the main layers all, the MTP block what is left 3055 const size_t left = budget2 > total_main ? budget2 - total_main : 0; 3056 S = (int) std::min<size_t>((size_t) ne, left / m.mtp.stride); 3057 } 3058 { // what the hybrid mode allocates next (the staging pair, the CPU part's outputs, the slots) against the VRAM the 3059 // sessions and the context left: said with the numbers instead of a cudaMalloc failure (8 slots on a 12 GB card) 3060 const size_t Tn = (size_t) E.tmax, Nn = (size_t) g.n_embd, Kn = (size_t) m.top_k; 3061 size_t need = staging + Tn * Kn * Nn * 4 + Tn * Kn * 4; 3062 for (Layer* L : all) { 3063 if (mtp_only && L != &m.mtp) need += L->stride * (size_t) ne + kMmqTail; 3064 else need += (S > 0 ? (size_t) S * L->stride + kMmqTail : 0); 3065 } 3066 if (need > fr) { 3067 err = "not enough VRAM left for the hybrid experts' buffers and slots (" + std::to_string((need >> 20)) + 3068 " MiB needed, " + std::to_string(fr >> 20) + " MiB free after the weights, the context and the sessions): use " 3069 "fewer slots (\"parallel\" / --batch), a shorter --max-context" + 3070 (slots > 0 ? ", or fewer --expert-slots" : ""); 3071 return false; 3072 } 3073 } 3074 // host memory: every expert, pinned where the driver allows it (the prompt's stream and the slot copies) 3075 size_t host = 0; 3076 for (Layer* L : all) 3077 if (!mtp_only || L == &m.mtp) host += L->stride * (size_t) ne + kMmqTail; 3078 uint8_t* arena = nullptr; 3079 bool pinned = cudaHostAlloc((void**) &arena, host, cudaHostAllocDefault) == cudaSuccess; 3080 if (!pinned) { 3081 (void) cudaGetLastError(); 3082 arena = (uint8_t*) std::malloc(host); 3083 if (!arena) { 3084 err = "no host memory for the experts (" + std::to_string(host >> 20) + " MiB)"; 3085 return false; 3086 } 3087 } 3088 size_t off = 0; 3089 E.hy.resize(all.size()); 3090 for (size_t li = 0; li < all.size(); ++li) { 3091 Layer& L = *all[li]; 3092 if (mtp_only && &L != &m.mtp) { // a main layer: every expert in VRAM, as in the all-in-VRAM placement 3093 CK(cudaMalloc(&L.blobs, L.stride * (size_t) ne + kMmqTail)); 3094 CK(cudaMemset(L.blobs, 0, L.stride * (size_t) ne + kMmqTail)); 3095 std::vector<uint8_t> blob(L.L.bytes, 0); 3096 for (int64_t e = 0; e < ne; ++e) { 3097 expert_blob(L, e, blob.data()); 3098 CK(cudaMemcpy(L.blobs + (size_t) e * L.stride, blob.data(), L.L.bytes, cudaMemcpyHostToDevice)); 3099 } 3100 L.n_slots = (int) ne; 3101 continue; 3102 } 3103 L.hblobs = arena + off; 3104 off += L.stride * (size_t) ne + kMmqTail; 3105 std::memset(L.hblobs, 0, L.stride * (size_t) ne + kMmqTail); 3106 for (int64_t e = 0; e < ne; ++e) expert_blob(L, e, L.hblobs + (size_t) e * L.stride); 3107 L.n_slots = S; 3108 if (S > 0) { 3109 CK(cudaMalloc(&L.blobs, L.stride * (size_t) S + kMmqTail)); 3110 CK(cudaMemset(L.blobs, 0, L.stride * (size_t) S + kMmqTail)); 3111 CK(cudaMemcpy(L.blobs, L.hblobs, L.stride * (size_t) S, cudaMemcpyHostToDevice)); 3112 } 3113 Engine::Hy& H = E.hy[li]; 3114 H.slot_of.assign((size_t) ne, -1); 3115 H.exp_in_slot.assign((size_t) S, 0); 3116 for (int s = 0; s < S; ++s) { 3117 H.slot_of[(size_t) s] = s; 3118 H.exp_in_slot[(size_t) s] = s; 3119 } 3120 H.score.assign((size_t) ne, 0.0); 3121 CK(cudaMalloc(&H.slot_of_d, (size_t) ne * 4)); 3122 CK(cudaMemcpy(H.slot_of_d, H.slot_of.data(), (size_t) ne * 4, cudaMemcpyHostToDevice)); 3123 if (!C::native_fmt(L.L.gu_type, L.L.d_type, g.n_embd, g.n_ff, H.fmt, err)) return false; 3124 if (H.fmt.up_off != L.L.up_off || H.fmt.down_off != L.L.down_off || H.fmt.bytes != L.L.bytes) { 3125 err = "the CPU and GPU expert layouts differ"; 3126 return false; 3127 } 3128 } 3129 const size_t T = (size_t) E.tmax, N = (size_t) g.n_embd, Kp = (size_t) m.top_k; 3130 CK(cudaHostAlloc((void**) &E.h_h, T * N * 4, cudaHostAllocDefault)); 3131 CK(cudaHostAlloc((void**) &E.cpu_out, T * Kp * N * 4, cudaHostAllocDefault)); 3132 CK(cudaHostAlloc((void**) &E.h_ids, T * Kp * 4, cudaHostAllocDefault)); 3133 CK(cudaHostAlloc((void**) &E.h_miss, T * Kp * 4, cudaHostAllocDefault)); 3134 CK(cudaHostAlloc((void**) &E.h_cnt, all.size() * (size_t) ne * 4, cudaHostAllocDefault)); 3135 CK(cudaMalloc(&E.ecpu, T * Kp * N * 4)); 3136 CK(cudaMalloc(&E.d_miss, T * Kp * 4)); 3137 E.acts = (uint8_t*) std::malloc(T * C::kNativeActBytes + 64); 3138 CK(cudaEventCreateWithFlags(&E.ev_route, cudaEventDisableTiming)); 3139 if (staging) { 3140 CK(cudaStreamCreateWithFlags(&E.cst, cudaStreamNonBlocking)); 3141 for (int b = 0; b < 2; ++b) { 3142 CK(cudaMalloc(&E.stage[b], max_layer + kMmqTail)); 3143 CK(cudaMemset(E.stage[b], 0, max_layer + kMmqTail)); 3144 CK(cudaEventCreateWithFlags(&E.ev_copy[b], cudaEventDisableTiming)); 3145 CK(cudaEventCreateWithFlags(&E.ev_used[b], cudaEventDisableTiming)); 3146 CK(cudaEventRecord(E.ev_used[b], E.st)); 3147 } 3148 } 3149 E.pool = std::make_unique<C::ExpertPool>(threads); 3150 CK(cudaDeviceSynchronize()); 3151 if (mtp_only) 3152 std::fprintf(stderr, "strata-q36: every main layer's routed experts in VRAM (%.2f GiB); the MTP block's: %d of " 3153 "%lld in VRAM, the rest on the CPU pool (its drafts only)\n", (double) total_main / (1 << 30), S, 3154 (long long) ne); 3155 else 3156 std::fprintf(stderr, "strata-q36: hybrid experts: %d of %lld per layer in VRAM (%.2f GiB), all %.2f GiB in %s host " 3157 "memory, the rest of a batch of <= %d rows on %d CPU threads, bigger prompt chunks streamed (%.2f GiB " 3158 "staging); %.1f s\n", S, (long long) ne, (double) S * per_slot / (1 << 30), (double) host / (1 << 30), 3159 pinned ? "pinned" : "pageable", E.hybrid_t, E.pool->workers() + (E.pool->host_works() ? 1 : 0), 3160 (double) staging / (1 << 30), ms_since(t0) / 1000.0); 3161 return true; 3162#endif 3163} 3164 3165// ------------------------------------------------------------------------------------------------ sampling 3166using strata::qwen35::Sampling; 3167 3168int sample(std::vector<float>& lg, const Sampling& s, const std::vector<int32_t>& hist, std::mt19937_64& rng) { 3169 strata::qwen35::apply_penalties(lg, s, hist); 3170 if (s.temperature <= 0.f) return (int) (std::max_element(lg.begin(), lg.end()) - lg.begin()); 3171 const int kk = std::max(1, std::min(s.top_k > 0 ? s.top_k : 64, (int) lg.size())); 3172 std::vector<int> idx(lg.size()); 3173 for (size_t i = 0; i < idx.size(); ++i) idx[i] = (int) i; 3174 std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int a, int b) { return lg[a] > lg[b]; }); 3175 idx.resize((size_t) kk); 3176 std::vector<double> p(idx.size()); 3177 const double mx = lg[(size_t) idx[0]]; 3178 double sum = 0; 3179 for (size_t i = 0; i < idx.size(); ++i) sum += (p[i] = std::exp((lg[(size_t) idx[i]] - mx) / s.temperature)); 3180 size_t keep = idx.size(); 3181 double cum = 0; 3182 for (size_t i = 0; i < idx.size(); ++i) { 3183 if (p[i] / sum < s.min_p * (p[0] / sum)) { keep = i; break; } 3184 cum += p[i] / sum; 3185 if (cum >= s.top_p) { keep = i + 1; break; } 3186 } 3187 keep = std::max<size_t>(1, keep); 3188 double tot = 0; 3189 for (size_t i = 0; i < keep; ++i) tot += p[i]; 3190 std::uniform_real_distribution<double> u(0.0, tot); 3191 double r = u(rng); 3192 for (size_t i = 0; i < keep; ++i) { 3193 if ((r -= p[i]) <= 0) return idx[i]; 3194 } 3195 return idx[keep - 1]; 3196} 3197 3198std::vector<int32_t> parse_ids(const char* s) { 3199 std::vector<int32_t> v; 3200 while (*s) { 3201 while (*s == ',' || *s == ' ') ++s; 3202 if (!*s) break; 3203 char* e = nullptr; 3204 const long x = std::strtol(s, &e, 10); 3205 if (e == s) break; 3206 v.push_back((int32_t) x); 3207 s = e; 3208 } 3209 return v; 3210} 3211 3212bool is_eos(int t) { return t == 248044 || t == 248046; } 3213 3214// ------------------------------------------------------------------------------------------------ pictures 3215constexpr int32_t kImagePad = 248056; // <|image_pad|> 3216 3217uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { 3218 const uint8_t* b = (const uint8_t*) p; 3219 for (size_t i = 0; i < n; ++i) h = (h ^ b[i]) * 1099511628211ull; 3220 return h; 3221} 3222 3223/// A request's pictures: the encoder's rows in prompt order, each picture's cell run, and the positions. 3224struct ImgReq { 3225 std::vector<float> rows; 3226 std::vector<ImgKey> imgs; 3227 std::vector<int32_t> cell_row; // per prompt cell: its row in `rows`, or -1 (text) 3228 std::vector<int32_t> mrope; // [cell][3] t, h, w of every prompt cell (llama.cpp's mtmd positions) 3229 int32_t delta = 0; // the text after the prompt: rotary position = cell + delta 3230}; 3231 3232/// Reads a strata-vision file (one or more records: int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats, in prompt 3233/// order) and lays the pictures over the prompt's <|image_pad|> runs. Positions as mtmd's: text counts up by one; a 3234/// picture's cells take (t, h, w) = (p, p + row, p + column) and the text after it continues at p + max(nx, ny). "" or 3235/// the error. `keys`: the server's key for each picture (img_keys=), else the embeddings' hash. 3236std::string build_images(const std::string& path, const std::vector<int32_t>& ids, int64_t n_embd, 3237 const std::vector<uint64_t>& keys, ImgReq& r) { 3238 struct Img { int64_t n, nx, ny; size_t off; }; 3239 std::vector<Img> imgs; 3240 std::FILE* f = std::fopen(path.c_str(), "rb"); 3241 if (!f) return "cannot open " + path; 3242 std::string ve; 3243 while (ve.empty()) { 3244 int32_t hdr[5]; 3245 const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); 3246 if (got == 0) break; 3247 if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || (int64_t) hdr[2] * hdr[3] != hdr[1] || 3248 hdr[4] != (int32_t) n_embd) { 3249 ve = "bad embeddings file (expected strata-vision records of width " + std::to_string((long long) n_embd) + ")"; 3250 break; 3251 } 3252 const size_t off = r.rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; 3253 r.rows.resize(off + cnt); 3254 if (std::fread(r.rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } 3255 imgs.push_back({hdr[1], hdr[2], hdr[3], off}); 3256 } 3257 std::fclose(f); 3258 if (!ve.empty()) return ve; 3259 const int64_t n = (int64_t) ids.size(); 3260 r.cell_row.assign((size_t) n, -1); 3261 r.mrope.assign((size_t) n * 3, 0); 3262 auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { 3263 r.mrope[(size_t) c * 3] = (int32_t) t; 3264 r.mrope[(size_t) c * 3 + 1] = (int32_t) h; 3265 r.mrope[(size_t) c * 3 + 2] = (int32_t) w; 3266 }; 3267 int64_t p = 0, i = 0; 3268 size_t k = 0; 3269 while (i < n) { 3270 if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } 3271 if (k >= imgs.size()) return "the prompt has more images than the embeddings file"; 3272 const Img& im = imgs[k++]; 3273 uint64_t h; 3274 { // what the conversation cache compares: a picture is its grid and its key (or its embeddings) 3275 const int64_t grid[3] = {im.n, im.nx, im.ny}; 3276 h = fnv1a(grid, sizeof grid); 3277 if (keys.size() == imgs.size()) h = fnv1a(&keys[k - 1], sizeof(uint64_t), h); 3278 else h = fnv1a(r.rows.data() + im.off, (size_t) im.n * (size_t) n_embd * sizeof(float), h); 3279 } 3280 r.imgs.push_back({i, im.n, h}); 3281 for (int64_t j = 0; j < im.n; ++j) 3282 if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) 3283 return "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + 3284 " rows but fewer <|image_pad|> tokens"; 3285 for (int64_t j = 0; j < im.n; ++j) { 3286 const int64_t y = j / im.nx, x = j % im.nx; 3287 put(i + j, p, p + y, p + x); 3288 r.cell_row[(size_t) (i + j)] = (int32_t) ((im.off / (size_t) n_embd) + (size_t) j); 3289 } 3290 i += im.n; 3291 p += std::max(im.nx, im.ny); 3292 } 3293 if (k != imgs.size()) return "the embeddings file has more images than the prompt"; 3294 if (n > 0 && ids[(size_t) (n - 1)] == kImagePad) return "the prompt cannot end in an image"; 3295 r.delta = (int32_t) (p - n); 3296 return ""; 3297} 3298 3299// ------------------------------------------------------------------------------------------------ serve 3300/// A batch slot: a session decoding (its next token is `x`, not yet in the state). 3301struct Slot { 3302 bool active = false, stop = false; 3303 int32_t x = 0; 3304 int64_t produced = 0, max_new = 0; 3305 Sampling smp; 3306 std::mt19937_64 rng; 3307 std::vector<int32_t> hist; 3308 Clock::time_point t0; 3309 int32_t draft = 0; // --batch-mtp: the MTP block's proposal for the token after `x` 3310 bool draft_ready = false; 3311 long long offered = 0, accepted = 0; 3312}; 3313 3314/// The engine protocol (serve/server.py). One request at a time on the control lines: GEN / GENI (alone: speculative 3315/// steps with the MTP block), or with --batch N BGEN / BGENI <slot> (the request's prompt is read into that slot's 3316/// session - the decode windows of the other slots go on between its chunks - then its tokens come as BT lines, one 3317/// window for every slot decoding, until BDONE). BSTOP <slot> ends a slot at its next window; STOP the request on the 3318/// control lines. 3319struct Serve { 3320 Engine& E; 3321 std::mutex mu; 3322 std::condition_variable cv; 3323 std::deque<std::string> lines; 3324 bool eof = false; 3325 std::atomic<bool> stop{false}; 3326 std::vector<Slot> slots; 3327 int n_active = 0; 3328 std::vector<float> lg; 3329 // decode windows of the other slots between two chunks of a prompt read: STRATA_Q36_READ_WINDOWS (default 1; a chunk 3330 // takes ~0.15 s at 512 tokens, a window ~0.012 s: more windows give the decoding slots more of the time a read takes) 3331 int read_windows = 1; 3332 3333 explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) { 3334 if (const char* v = std::getenv("STRATA_Q36_READ_WINDOWS")) read_windows = std::max(0, std::min(64, std::atoi(v))); 3335 } 3336 3337 /// BSTOP / BYIELD lines among the queued ones: applied now (a window is a moment away at most). 3338 void poll_control() { 3339 std::lock_guard<std::mutex> lk(mu); 3340 for (auto it = lines.begin(); it != lines.end();) { 3341 if (it->rfind("BSTOP ", 0) == 0) { 3342 const int b = std::atoi(it->c_str() + 6); 3343 if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; 3344 it = lines.erase(it); 3345 } else if (it->rfind("BYIELD", 0) == 0) { // (a read here does not give way: the server then goes on) 3346 it = lines.erase(it); 3347 } else { 3348 ++it; 3349 } 3350 } 3351 } 3352 3353 /// One decode window with MTP proposals (--batch-mtp): every active slot's next token, and for up to kVerify - S of the 3354 /// slots (the greedy ones, in turn) also the proposal its MTP block made: the window verifies both at once. A slot whose 3355 /// proposal the main model confirms moves two tokens in the window. The proposals for the next window come right after 3356 /// it, from the hidden states the window just produced (the first one of a slot from the state its prompt left). 3357 int mtp_turn = 0; 3358 void window_mtp() { 3359 poll_control(); 3360 const int N = (int) E.m->g.n_embd; 3361 std::vector<int> act; 3362 for (int b = 0; b < E.n_sess; ++b) 3363 if (slots[(size_t) b].active) act.push_back(b); 3364 const int S = (int) act.size(); 3365 if (S == 0) return; 3366 // who verifies a proposal this window: the greedy slots in turn, as many as fit beside one row per slot 3367 const int room = Engine::kVerify - S; 3368 std::vector<char> cand((size_t) S, 0); 3369 int nc = 0; 3370 for (int k = 0; k < S && nc < room; ++k) { 3371 const int i = (mtp_turn + k) % S; 3372 if (!slots[(size_t) act[(size_t) i]].smp.needs_logits()) { cand[(size_t) i] = 1; ++nc; } 3373 } 3374 ++mtp_turn; 3375 // a candidate without a proposal gets its first one from the state its last row left 3376 std::vector<Engine::MtpRow> first; 3377 std::vector<int> first_of; 3378 for (int i = 0; i < S; ++i) { 3379 Slot& sl = slots[(size_t) act[(size_t) i]]; 3380 if (cand[(size_t) i] && !sl.draft_ready) { 3381 Engine::Sess& ss = E.sess[(size_t) act[(size_t) i]]; 3382 first.push_back({act[(size_t) i], sl.x, ss.pos, ss.hlast}); 3383 first_of.push_back(i); 3384 } 3385 } 3386 if (!first.empty()) { 3387 E.mtp_rows(first.data(), (int) first.size()); 3388 for (size_t k = 0; k < first.size(); ++k) { 3389 Slot& sl = slots[(size_t) act[(size_t) first_of[k]]]; 3390 sl.draft = E.mtp_pick[k]; 3391 sl.draft_ready = true; 3392 } 3393 } 3394 std::vector<Engine::Group> gr((size_t) S); 3395 std::vector<int> row0((size_t) S); 3396 int T = 0; 3397 for (int i = 0; i < S; ++i) { 3398 const Slot& sl = slots[(size_t) act[(size_t) i]]; 3399 gr[(size_t) i] = {act[(size_t) i], cand[(size_t) i] ? 2 : 1, {sl.x, sl.draft}}; 3400 row0[(size_t) i] = T; 3401 T += gr[(size_t) i].n; 3402 } 3403 E.run_rows(gr.data(), S, true); 3404 // the picks: emit, decide how many rows each slot keeps 3405 std::vector<int> keep((size_t) S, 1); 3406 std::vector<int32_t> last((size_t) S, 0); 3407 std::vector<char> alive((size_t) S, 0); 3408 for (int i = 0; i < S; ++i) { 3409 const int b = act[(size_t) i]; 3410 Slot& sl = slots[(size_t) b]; 3411 Engine::Sess& ss = E.sess[(size_t) b]; 3412 const int n = gr[(size_t) i].n, r0 = row0[(size_t) i]; 3413 int y0 = E.rows_pick[r0]; 3414 if (sl.smp.needs_logits()) { 3415 E.host_logits_row(r0, lg); 3416 y0 = sample(lg, sl.smp, sl.hist, sl.rng); 3417 } 3418 bool two = n == 2 && y0 == sl.draft && !is_eos(y0) && !sl.stop && sl.produced + 2 <= sl.max_new && 3419 ss.pos + 3 <= E.ctx; // (ss.pos: the position of the slot's next token: the window did not move it) 3420 if (n == 2) { ++sl.offered; if (two) ++sl.accepted; } 3421 const int rows_kept = two ? 2 : 1; 3422 keep[(size_t) i] = rows_kept; 3423 const int32_t fed[2] = {sl.x, sl.draft}; 3424 bool done = false; 3425 int y = y0; 3426 for (int j = 0; j < rows_kept; ++j) { 3427 if (j == 1) y = E.rows_pick[r0 + 1]; 3428 ss.live.push_back(fed[j]); 3429 std::printf("BT %d %d\n", b, y); 3430 ++sl.produced; 3431 sl.hist.push_back(y); 3432 const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" 3433 : ss.pos + j + 2 > E.ctx ? "length" : nullptr; 3434 if (fin) { 3435 std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); 3436 if (sl.offered > 0) 3437 std::fprintf(stderr, "strata batch: slot %d: %lld of %lld MTP proposals accepted\n", b, sl.accepted, 3438 sl.offered); 3439 sl.active = false; 3440 ss.active = false; 3441 --n_active; 3442 done = true; 3443 break; 3444 } 3445 } 3446 last[(size_t) i] = y; 3447 alive[(size_t) i] = !done; 3448 if (!done) sl.x = y; 3449 } 3450 E.commit_rows(gr.data(), keep.data(), S); 3451 // the hidden state after each slot's last kept row (the seed of a later first proposal), and the next proposals 3452 std::vector<Engine::MtpRow> nx; 3453 std::vector<int> nx_of, nx_last; 3454 for (int i = 0; i < S; ++i) { 3455 const int b = act[(size_t) i]; 3456 Engine::Sess& ss = E.sess[(size_t) b]; 3457 const int r0 = row0[(size_t) i]; 3458 CK(cudaMemcpyAsync(ss.hlast, E.hmain + (size_t) (r0 + keep[(size_t) i] - 1) * N, (size_t) N * 4, 3459 cudaMemcpyDeviceToDevice, E.st)); 3460 Slot& sl = slots[(size_t) b]; 3461 sl.draft_ready = false; 3462 if (!alive[(size_t) i] || !cand[(size_t) i]) continue; 3463 const int64_t p_new = ss.pos; // commit_rows moved it: the cell of the token the next window feeds 3464 if (keep[(size_t) i] == 2) { 3465 nx.push_back({b, sl.draft, p_new - 1, E.hmain + (size_t) r0 * N}); 3466 nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) (r0 + 1) * N}); 3467 nx_last.push_back((int) nx.size() - 1); 3468 } else { 3469 nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) r0 * N}); 3470 nx_last.push_back((int) nx.size() - 1); 3471 } 3472 nx_of.push_back(i); 3473 } 3474 std::fflush(stdout); 3475 if (!nx.empty()) { 3476 // (more rows than the window holds: the proposals come in two calls) 3477 for (size_t at = 0, k = 0; at < nx.size();) { 3478 size_t take = std::min<size_t>(nx.size() - at, Engine::kVerify); 3479 while (take > 0 && at + take < nx.size() && nx[at + take].slot == nx[at + take - 1].slot) --take; // a slot's rows together 3480 E.mtp_rows(nx.data() + at, (int) take); 3481 for (; k < nx_last.size() && (size_t) nx_last[k] < at + take; ++k) { 3482 Slot& sl = slots[(size_t) act[(size_t) nx_of[k]]]; 3483 sl.draft = E.mtp_pick[(size_t) nx_last[k] - at]; 3484 sl.draft_ready = true; 3485 } 3486 at += take; 3487 } 3488 } 3489 } 3490 3491 /// One decode window over every active slot: one token each. 3492 void window() { 3493 poll_control(); 3494 if (E.bmtp && E.mtp_d > 0) { // proposals need a row to spare and a slot that decodes greedily 3495 int act = 0, greedy = 0; 3496 for (const Slot& sl : slots) 3497 if (sl.active) { ++act; greedy += !sl.smp.needs_logits(); } 3498 if (greedy > 0 && Engine::kVerify - act > 0) { window_mtp(); return; } 3499 } 3500 window_plain(); 3501 } 3502 3503 /// One token of every active slot, no proposals. 3504 void window_plain() { 3505 std::vector<Engine::Row> rows; 3506 for (int b = 0; b < E.n_sess; ++b) 3507 if (slots[(size_t) b].active) rows.push_back({b, slots[(size_t) b].x}); 3508 if (rows.empty()) return; 3509 E.step_rows(rows.data(), (int) rows.size()); 3510 const size_t Nb = (size_t) E.m->g.n_embd * 4; 3511 for (size_t r = 0; r < rows.size(); ++r) { 3512 const int b = rows[r].slot; 3513 Slot& sl = slots[(size_t) b]; 3514 Engine::Sess& ss = E.sess[(size_t) b]; 3515 if (E.bmtp) // (the hidden state a later first proposal starts from) 3516 CK(cudaMemcpyAsync(ss.hlast, E.hmain + r * (size_t) E.m->g.n_embd, Nb, cudaMemcpyDeviceToDevice, E.st)); 3517 sl.draft_ready = false; 3518 ss.live.push_back(sl.x); 3519 int y; 3520 if (sl.smp.needs_logits()) { 3521 E.host_logits_row((int) r, lg); 3522 y = sample(lg, sl.smp, sl.hist, sl.rng); 3523 } else { 3524 y = E.rows_pick[r]; 3525 } 3526 std::printf("BT %d %d\n", b, y); 3527 ++sl.produced; 3528 sl.hist.push_back(y); 3529 const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" 3530 : ss.pos + 1 > E.ctx ? "length" : nullptr; 3531 if (fin) { 3532 std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); 3533 sl.active = false; 3534 ss.active = false; 3535 --n_active; 3536 } else { 3537 sl.x = y; 3538 } 3539 } 3540 std::fflush(stdout); 3541 } 3542 3543 /// The length of session ss's held tokens when they are a proper start of `ids` with the same pictures, else 0. 3544 size_t match_len(const Engine::Sess& ss, const std::vector<int32_t>& ids, const std::vector<ImgKey>& imgs) const { 3545 const size_t L = ss.live.size(); 3546 if (L == 0 || L >= ids.size() || !std::equal(ss.live.begin(), ss.live.end(), ids.begin())) return 0; 3547 std::vector<ImgKey> in_live; 3548 for (const ImgKey& k : imgs) { 3549 if (k.cell + k.n <= (int64_t) L) in_live.push_back(k); 3550 else if (k.cell < (int64_t) L) return 0; // the held tokens end inside a picture 3551 } 3552 return in_live == ss.imgs ? L : 0; 3553 } 3554 3555 /// The session a request alone takes: the one holding the longest start of its prompt, else an empty one, else the 3556 /// least recently used (never a decoding slot). 3557 int pick_session(const std::vector<int32_t>& ids, const std::vector<ImgKey>& imgs) const { 3558 int best = -1, free_empty = -1, lru = -1; 3559 size_t bl = 0; 3560 for (int i = 0; i < E.n_sess; ++i) { 3561 const Engine::Sess& ss = E.sess[(size_t) i]; 3562 if (ss.active) continue; 3563 const size_t l = match_len(ss, ids, imgs); 3564 if (l > bl) { bl = l; best = i; } 3565 if (ss.live.empty() && free_empty < 0) free_empty = i; 3566 if (lru < 0 || ss.used < E.sess[(size_t) lru].used) lru = i; 3567 } 3568 return best >= 0 ? best : free_empty >= 0 ? free_empty : lru; 3569 } 3570 3571 void request(const std::string& line) { 3572 const bool adm = line[0] == 'B'; 3573 const bool geni = line.rfind(adm ? "BGENI " : "GENI ", 0) == 0; 3574 if (!adm && !geni && line.rfind("GEN ", 0) != 0) { 3575 std::printf("ERR expected: GEN <max_new> [key=value ...] <id,id,...> or GENI <max_new> [keys] <file> <id,id,...>\n"); 3576 std::fflush(stdout); 3577 return; 3578 } 3579 char* p = const_cast<char*>(line.c_str()) + (adm ? (geni ? 6 : 5) : (geni ? 5 : 4)); 3580 int slot = -1; 3581 if (adm) { 3582 char* e1 = nullptr; 3583 const long b = std::strtol(p, &e1, 10); 3584 p = e1; 3585 slot = (int) b; 3586 if (e1 == line.c_str() || b < 0 || b >= (long) slots.size() || slots[(size_t) b].active || E.n_sess < 2) { 3587 std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", E.n_sess < 2 ? 0 : E.n_sess); 3588 std::fflush(stdout); 3589 return; 3590 } 3591 } 3592 const long long max_new = std::strtoll(p, &p, 10); 3593 Sampling smp; 3594 std::vector<uint64_t> img_keys; 3595 for (;;) { 3596 while (*p == ' ') ++p; 3597 const char* st0 = p; 3598 while (*p && *p != ' ') ++p; 3599 const std::string tk(st0, (size_t) (p - st0)); 3600 const size_t eq = tk.find('='); 3601 if (tk.empty() || eq == std::string::npos) { p = const_cast<char*>(st0); break; } 3602 const std::string key = tk.substr(0, eq); 3603 const char* v = tk.c_str() + eq + 1; 3604 if (key == "temperature") smp.temperature = std::strtof(v, nullptr); 3605 else if (key == "top_p") smp.top_p = std::strtof(v, nullptr); 3606 else if (key == "top_k") smp.top_k = std::atoi(v); 3607 else if (key == "min_p") smp.min_p = std::strtof(v, nullptr); 3608 else if (key == "penalty_last_n") smp.last_n = std::atoi(v); 3609 else if (key == "penalty_repeat") smp.repeat = std::strtof(v, nullptr); 3610 else if (key == "penalty_freq") smp.freq = std::strtof(v, nullptr); 3611 else if (key == "penalty_present") smp.present = std::strtof(v, nullptr); 3612 else if (key == "seed") smp.seed = std::strtoull(v, nullptr, 10); 3613 else if (key == "img_keys") { 3614 const char* q = v; 3615 img_keys.clear(); 3616 while (*q) { 3617 char* qe = nullptr; 3618 const unsigned long long x = std::strtoull(q, &qe, 16); 3619 if (qe == q) { img_keys.clear(); break; } 3620 img_keys.push_back((uint64_t) x); 3621 q = *qe == ',' ? qe + 1 : qe; 3622 if (*qe != ',' && *qe != '\0') { img_keys.clear(); break; } 3623 } 3624 } 3625 } 3626 std::string emb; 3627 if (geni) { 3628 while (*p == ' ') ++p; 3629 const char* e = p; 3630 while (*e && *e != ' ') ++e; 3631 emb.assign(p, (size_t) (e - p)); 3632 p = const_cast<char*>(e); 3633 } 3634 const std::vector<int32_t> ids = parse_ids(p); 3635 if (max_new < 1 || ids.empty() || (geni && emb.empty())) { 3636 std::printf("ERR bad request: max_new or the ids\n"); 3637 std::fflush(stdout); 3638 return; 3639 } 3640 if (geni && !E.vision) { 3641 std::printf("ERR this engine was started without --vision\n"); 3642 std::fflush(stdout); 3643 return; 3644 } 3645 if ((int64_t) ids.size() + max_new > E.ctx) { 3646 std::printf("ERR prompt (%zu tokens) + max_new (%lld) exceeds the context (%d)\n", ids.size(), max_new, E.ctx); 3647 std::fflush(stdout); 3648 return; 3649 } 3650 bool bad = false; 3651 for (int32_t t : ids) bad |= t < 0 || t >= (int32_t) E.m->g.n_vocab; 3652 if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); return; } 3653 ImgReq ir; 3654 if (geni) { 3655 const std::string ve = build_images(emb, ids, E.m->g.n_embd, img_keys, ir); 3656 if (!ve.empty()) { std::printf("ERR %s\n", ve.c_str()); std::fflush(stdout); return; } 3657 } 3658 stop.store(false); 3659 // ---- the session: the held state continues when the request extends it (the recurrent state cannot step back) 3660 const int s = adm ? slot : pick_session(ids, ir.imgs); 3661 Engine::Sess& ss = E.sess[(size_t) s]; 3662 size_t reuse = match_len(ss, ids, ir.imgs); 3663 if (adm) { // another session holding more of this prompt (the conversation was read alone): copy its state 3664 int src = -1; 3665 size_t best = reuse; 3666 for (int i = 0; i < E.n_sess; ++i) { 3667 if (i == s || E.sess[(size_t) i].active) continue; 3668 const size_t l = match_len(E.sess[(size_t) i], ids, ir.imgs); 3669 if (l > best) { best = l; src = i; } 3670 } 3671 if (src >= 0) { 3672 E.copy_session(src, s); 3673 reuse = best; 3674 } 3675 } 3676 E.select(s); 3677 if (reuse == 0) { 3678 E.reset(); 3679 ss.live.clear(); 3680 ss.imgs.clear(); 3681 } 3682 if (geni) E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) ids.size(), ir.delta); 3683 else E.clear_images(); 3684 const auto t0 = Clock::now(); 3685 const int64_t fresh = (int64_t) (ids.size() - reuse); 3686 bool cancelled = false; 3687 const int64_t got = E.process(ids.data() + reuse, fresh, [&](int64_t done) -> bool { 3688 std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0), 3689 (double) done / std::max(1e-9, ms_since(t0) / 1000.0)); 3690 std::fflush(stdout); 3691 if (n_active > 0 && done < fresh) { 3692 poll_control(); 3693 // the slots decoding go on between a read's chunks (the last chunk's 3694 for (int w = 0; w < read_windows && n_active > 0; ++w) window(); // logits must stay for the first token) 3695 } else { 3696 poll_control(); 3697 } 3698 if (stop.load() && done < fresh) { cancelled = true; return false; } 3699 return true; 3700 }); 3701 ss.live.insert(ss.live.end(), ids.begin() + (long) reuse, ids.begin() + (long) reuse + (long) got); 3702 ss.imgs.clear(); 3703 bool cut = false; 3704 for (const ImgKey& k : ir.imgs) { 3705 if (k.cell + k.n <= (int64_t) ss.live.size()) ss.imgs.push_back(k); 3706 else if (k.cell < (int64_t) ss.live.size()) cut = true; 3707 } 3708 if (cancelled && cut) { // stopped inside a picture: the state cannot be continued, the next read starts over 3709 ss.live.clear(); 3710 ss.imgs.clear(); 3711 } 3712 E.sess[(size_t) E.cur].pos = E.pos; 3713 const double prompt_ms = ms_since(t0); 3714 if (cancelled) { 3715 std::printf("DONE 0 %zu %.1f 0.0 cancel 0 0 %zu 0 0 0 0 0.0 %lld 0\n", ids.size(), prompt_ms, reuse, (long long) got); 3716 if (adm) std::printf("BADM %d 0\n", slot); 3717 std::fflush(stdout); 3718 return; 3719 } 3720 std::mt19937_64 rng(smp.seed); 3721 // #4590: the penalties count the reply's tokens (and the fed-back last prompt token), not the prompt; STRATA_PENALTY_PROMPT=1 3722 // restores the old window. `ids` is the request's full prompt whether or not the session was resumed. 3723 static const bool pen_prompt = strata::kernels::penalty_counts_prompt(std::getenv("STRATA_PENALTY_PROMPT")); 3724 std::vector<int32_t> hist = strata::qwen35::penalty_history_start(ids, pen_prompt); 3725 const auto d0 = Clock::now(); 3726 long long produced = 0, offered = 0, accepted = 0; 3727 const char* finish = "length"; 3728 // greedy requests alone with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy 3729 // text); sampled ones, and requests beside others, one token at a time 3730 const bool spec = E.mtp_d > 0 && !smp.needs_logits() && !adm; 3731 std::vector<int32_t> fix, drafts; 3732 int32_t picks[16]; 3733 int nx = smp.needs_logits() ? -1 : E.greedy(); 3734 if (adm) { 3735 if (smp.needs_logits()) { 3736 E.host_logits(lg); 3737 nx = sample(lg, smp, hist, rng); 3738 } 3739 std::printf("T %d\n", nx); 3740 ++produced; 3741 hist.push_back(nx); 3742 const char* fin = is_eos(nx) ? "stop" : stop.load() ? "cancel" : max_new <= 1 ? "length" 3743 : E.pos + 1 > E.ctx ? "length" : nullptr; 3744 const bool cont = fin == nullptr; 3745 std::printf("DONE %lld %zu %.1f %.1f %s 0 0 %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, 3746 ms_since(d0), cont ? "length" : fin, reuse, (long long) fresh); 3747 if (cont) { 3748 Slot& sl = slots[(size_t) slot]; 3749 sl = Slot{}; 3750 sl.active = true; 3751 sl.x = nx; 3752 sl.produced = 1; 3753 sl.max_new = max_new; 3754 sl.smp = smp; 3755 sl.rng = rng; 3756 sl.hist = hist; 3757 sl.t0 = Clock::now(); 3758 ss.active = true; 3759 ++n_active; 3760 } 3761 std::printf("BADM %d %d\n", slot, cont ? 1 : 0); 3762 std::fflush(stdout); 3763 std::fprintf(stderr, "strata batch: slot %d takes a prompt of %zu tokens = %zu reused + %lld read in %.0f ms (%.1f " 3764 "tok/s)%s\n", slot, ids.size(), reuse, (long long) fresh, prompt_ms, 3765 prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, cont ? "" : ", done at once"); 3766 return; 3767 } 3768 for (;;) { 3769 if (smp.needs_logits()) { 3770 E.host_logits(lg); 3771 nx = sample(lg, smp, hist, rng); 3772 } 3773 auto emit = [&](int t) { // false: the answer ends here 3774 std::printf("T %d\n", t); 3775 std::fflush(stdout); 3776 ++produced; 3777 hist.push_back(t); 3778 if (is_eos(t)) { finish = "stop"; return false; } 3779 if (produced >= max_new) return false; 3780 if (stop.load()) { finish = "cancel"; return false; } 3781 return true; 3782 }; 3783 if (!emit(nx)) break; 3784 if (n_active > 0) window(); 3785 if (spec && n_active == 0 && E.pos + E.mtp_d + 1 <= E.ctx) { 3786 const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks, &stop); 3787 offered += E.mtp_d; 3788 accepted += a; 3789 // the state now holds x and every accepted draft, whether or not the answer ends inside them (an end of 3790 // answer, max_new): the held tokens say so, so a later request that continues this conversation matches them 3791 // (a prompt that has the same tokens next reuses the state, any other reads from the start) and never reads 3792 // a token twice 3793 ss.live.push_back(nx); 3794 for (int i = 0; i < a; ++i) ss.live.push_back(drafts[(size_t) i]); 3795 fix.assign(drafts.begin(), drafts.begin() + a); 3796 bool ended = false; 3797 for (int i = 0; i < a && !ended; ++i) 3798 if (!emit(drafts[(size_t) i])) ended = true; 3799 if (ended) break; 3800 nx = picks[a]; 3801 continue; 3802 } 3803 if (E.pos + 1 > E.ctx) break; 3804 const int32_t one = nx; 3805 E.process(&one, 1, [](int64_t) {}); 3806 ss.live.push_back(nx); 3807 fix.clear(); 3808 if (!smp.needs_logits()) nx = E.greedy(); 3809 } 3810 E.sess[(size_t) E.cur].pos = E.pos; 3811 const double decode_ms = ms_since(d0); 3812 std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, 3813 decode_ms, finish, accepted, offered, reuse, (long long) fresh); 3814 std::fflush(stdout); 3815 std::fprintf(stderr, "strata serve: session %d: prompt %zu tokens = %zu reused + %lld read in %.0f ms (%.1f tok/s), " 3816 "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld (%s)\n", s, ids.size(), reuse, 3817 (long long) fresh, prompt_ms, prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, produced, 3818 decode_ms, decode_ms > 0 ? 1000.0 * (double) produced / decode_ms : 0.0, accepted, offered, finish); 3819 } 3820 3821 int run() { 3822 if (E.n_sess > 1) std::printf("INFO batch_slots=%d slot_cache=1\n", E.n_sess); 3823 std::printf("READY %d stop\n", E.ctx); 3824 std::fflush(stdout); 3825 std::thread reader([&] { 3826 std::string l; 3827 while (std::getline(std::cin, l)) { 3828 if (!l.empty() && l.back() == '\r') l.pop_back(); 3829 if (l == "STOP") { stop.store(true); continue; } 3830 std::lock_guard<std::mutex> lk(mu); 3831 lines.push_back(l); 3832 cv.notify_one(); 3833 } 3834 std::lock_guard<std::mutex> lk(mu); 3835 eof = true; 3836 cv.notify_one(); 3837 }); 3838 reader.detach(); 3839 for (;;) { 3840 std::string line; 3841 bool have = false; 3842 { 3843 std::unique_lock<std::mutex> lk(mu); 3844 if (n_active == 0) cv.wait(lk, [&] { return eof || !lines.empty(); }); 3845 if (!lines.empty()) { 3846 line = lines.front(); 3847 lines.pop_front(); 3848 have = true; 3849 } else if (n_active == 0) { 3850 return 0; 3851 } 3852 } 3853 if (!have) { window(); continue; } 3854 if (line.empty()) continue; 3855 if (line.rfind("BSTOP ", 0) == 0) { 3856 const int b = std::atoi(line.c_str() + 6); 3857 if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; 3858 } else if (line.rfind("BYIELD", 0) == 0) { 3859 // (a read that has ended) 3860 } else if (line.rfind("GEN", 0) == 0 || line.rfind("BGEN", 0) == 0) { 3861 request(line); 3862 } else { 3863 std::printf("ERR expected: GEN <max_new> [key=value ...] <id,id,...>\n"); 3864 std::fflush(stdout); 3865 } 3866 if (n_active > 0) window(); 3867 } 3868 } 3869}; 3870 3871int serve(Engine& E) { 3872 Serve sv(E); 3873 return sv.run(); 3874} 3875 3876} // namespace 3877 3878int strata::qwen35::run(int argc, char** argv) { 3879 std::string model, tokens, force, dump_full, emb_file; 3880 int ctx = 32768, chunk = 0, n_gen = 64, bench_pp = 0, bench_tg = 0, mtp_d = 0, cpu_threads = 0, hybrid_rows = 128; 3881 double expert_vram = -1.0; 3882 bool warm = true; 3883 int expert_slots = 0, batch = 0, draft_vocab = -1; 3884 bool serve_mode = false, graph = true, vision = false, batch_mtp = false; 3885 for (int i = 1; i < argc; ++i) { 3886 const std::string a = argv[i]; 3887 auto next = [&]() -> std::string { 3888 if (i + 1 >= argc) { std::fprintf(stderr, "strata-q36: %s needs a value\n", a.c_str()); std::exit(2); } 3889 return argv[++i]; 3890 }; 3891 // strata's names where they mean the same thing (the family switch passes strata's command line on) 3892 if (a == "--model" || a == "--native") model = next(); 3893 else if (a == "--max-new") n_gen = std::atoi(next().c_str()); 3894 else if (a == "--no-token-graph") graph = false; 3895 else if (a == "--pool-workers") cpu_threads = std::atoi(next().c_str()); 3896 else if (a == "--gpu") (void) next(); // applied by strata before the switch (CUDA/HIP_VISIBLE_DEVICES) 3897 else if (a == "--greedy") {} // --tokens decodes greedily here anyway 3898 else if (a == "--serve") serve_mode = true; 3899 else if (a == "--max-context" || a == "--ctx") ctx = std::atoi(next().c_str()); 3900 else if (a == "--chunk" || a == "--prefill") { const std::string v = next(); chunk = v == "auto" ? 0 : std::atoi(v.c_str()); } 3901 else if (a == "--tokens") tokens = next(); 3902 else if (a == "--n") n_gen = std::atoi(next().c_str()); 3903 else if (a == "--force") force = next(); 3904 else if (a == "--emb") emb_file = next(); // --tokens with pictures: a strata-vision file (the ids carry <|image_pad|> runs) 3905 else if (a == "--dump-full-logits") dump_full = next(); 3906 else if (a == "--bench-pp") bench_pp = std::atoi(next().c_str()); 3907 else if (a == "--bench-tg") bench_tg = std::atoi(next().c_str()); 3908 else if (a == "--no-graph") graph = false; 3909 else if (a == "--no-warmup") warm = false; 3910 else if (a == "--mtp") { 3911 // a number of drafts; Flash-Next's "--mtp <draft layer dir>" means nothing for this family 3912 const std::string v = next(); 3913 if (!v.empty() && std::isdigit((unsigned char) v[0])) mtp_d = std::atoi(v.c_str()); 3914 else std::fprintf(stderr, "strata-q36: ignoring --mtp %s (this family's MTP is the GGUF's own block: --mtp N " 3915 "drafts)\n", v.c_str()); 3916 } 3917 else if (a == "--draft-vocab") draft_vocab = std::atoi(next().c_str()); // the MTP drafts pick among the first N token ids 3918 else if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision's 3919 else if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding together 3920 else if (a == "--batch-mtp") batch_mtp = true; // ... each verifying an MTP proposal 3921 else if (a == "--expert-vram") expert_vram = std::atof(next().c_str()); // GiB for the routed experts 3922 else if (a == "--cpu-threads") cpu_threads = std::atoi(next().c_str()); 3923 else if (a == "--expert-slots") expert_slots = std::atoi(next().c_str()); 3924 else if (a == "--hybrid-rows") hybrid_rows = std::atoi(next().c_str()); 3925 else if (serve_mode && a.rfind("--", 0) == 0) { 3926 // serve passes the config's args plus a few of its own: one this engine does not have is said and skipped 3927 // (with its value), not fatal 3928 const bool val = i + 1 < argc && std::string(argv[i + 1]).rfind("--", 0) != 0; 3929 std::fprintf(stderr, "strata-q36: ignoring %s%s%s (not an option of this engine)\n", a.c_str(), 3930 val ? " " : "", val ? argv[i + 1] : ""); 3931 if (val) ++i; 3932 } else { 3933 std::fprintf(stderr, 3934 "usage: strata-q36 --model GGUF [--max-context 32768] [--chunk 512] [--no-graph]\n" 3935 " (--serve | --tokens IDS [--n 64] [--force IDS] [--dump-full-logits F] | --bench-pp N " 3936 "--bench-tg N)\n"); 3937 return 2; 3938 } 3939 } 3940 if (model.empty()) { std::fprintf(stderr, "strata-q36: --model is required\n"); return 2; } 3941#if !defined(_WIN32) 3942 setenv("CUDA_MODULE_LOADING", "EAGER", 0); // every kernel loaded with the context, not in the first prompt 3943 setenv("STRATA_Q8_PACKED", "1", 0); // the packed Q8_0 decode copy unless STRATA_Q8_PACKED is set otherwise 3944 setenv("STRATA_MMQ_KQ", "1", 0); // the K-quant MMQ prompt kernels (every expert of this family is a K-quant) 3945#else 3946 if (std::getenv("STRATA_MMQ_KQ") == nullptr) _putenv_s("STRATA_MMQ_KQ", "1"); 3947 if (std::getenv("STRATA_Q8_PACKED") == nullptr) _putenv_s("STRATA_Q8_PACKED", "1"); // as on Linux (it was missing here) 3948 if (std::getenv("CUDA_MODULE_LOADING") == nullptr) _putenv_s("CUDA_MODULE_LOADING", "EAGER"); 3949#endif 3950 // Strata's fused prompt kernels for this family's formats (moe_fused_iq_q36.cu): the K-quant, Q6_K and Q8_0 gate/up 3951 // instances are opt-in for Flash-Next's packs; this engine sets them up by default (=0 keeps a format on MMQ) 3952 for (const char* v : {"STRATA_PF_FUSED_KQ", "STRATA_PF_FUSED_Q6K", "STRATA_PF_FUSED_Q8GU"}) { 3953#if !defined(_WIN32) 3954 setenv(v, "1", 0); 3955#else 3956 if (std::getenv(v) == nullptr) _putenv_s(v, "1"); 3957#endif 3958 } 3959 // (HIP: gfx12 cards take the fused kernels through the same value: fused_tile::q36_takes_gfx12; other cards keep their route) 3960 // A build without llama.cpp's MMQ (MMQ::built() false: strata_pf_own with mmq_absent.cpp) has no MMQ tile for any layer, so a layer takes the fused kernels or the 3961 // whole prompt takes the grouped kernels. `strata` already sets STRATA_PF_FUSED=1 before main in such a build (prefill.cpp, g_own_only_defaults), which makes every 3962 // sm_80+ card whose kernels cover a layer's pair take them (fused_tile::q36_takes); this standalone engine does not link that code, so it does the same here: the same 3963 // behaviour on both entry points. A value you set is kept (=0 keeps every layer on the grouped kernels). A build with MMQ is unchanged. 3964 { 3965 const int pf_now = strata::prefill::fused_tile::pf_env(std::getenv("STRATA_PF_FUSED")); 3966 if (pf_now < 0 && strata::prefill::fused_tile::q36_start_env(MMQ::built(), pf_now) == 1) { 3967#if !defined(_WIN32) 3968 setenv("STRATA_PF_FUSED", "1", 1); 3969#else 3970 _putenv_s("STRATA_PF_FUSED", "1"); 3971#endif 3972 } 3973 } 3974 if (mtp_d < 0 || mtp_d > 7) { std::fprintf(stderr, "strata-q36: --mtp takes 0 .. 7 drafts\n"); return 2; } 3975 if (chunk < 0 || chunk > 4096 || ctx < 256) { std::fprintf(stderr, "strata-q36: bad --chunk / --max-context\n"); return 2; } 3976 Model m; 3977 std::string err; 3978 try { 3979 if (!load(model, m, err, mtp_d > 0)) { std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); return 1; } 3980 } catch (const std::exception& e) { 3981 std::fprintf(stderr, "strata-q36: %s\n", e.what()); 3982 return 1; 3983 } 3984 Engine E; 3985 E.use_graph = graph; 3986 if (chunk == 0) { 3987 // auto: the largest chunk (4096 .. 1024) that fits beside every expert in VRAM; 2048 when they will not all fit (a prompt chunk streams every layer's 3988 // experts over PCIe once, so a bigger chunk pays that once for more tokens) 3989 size_t fr = 0, tot = 0, experts = 0; 3990 CK(cudaMemGetInfo(&fr, &tot)); 3991 for (const Layer& L : m.layers) experts += L.stride * (size_t) m.g.n_expert; 3992 const size_t fr_raw = fr; // before the packed Q8_0 copies count as given back 3993 // (the MTP block's experts can go to the CPU, the packed Q8_0 copies can be given back: see place_experts) 3994 size_t packed = 0; 3995 for (const auto& pk : m.packed) packed += std::get<2>(pk); 3996 fr += packed; 3997 // the engine's buffers at 512 (~1.1 GiB on gfx1201 at 8K, less the scores buffer's shrink) + the small reserve 3998 const double want = (double) experts + 1.1 * (1ull << 30); 3999 const bool fits = expert_slots <= 0 && (expert_vram < 0 ? want <= (double) fr 4000 : (double) experts <= expert_vram * (double) (1ull << 30)); 4001 chunk = fits ? 512 : 2048; 4002 const double GiB = (double) (1ull << 30); 4003 if (fits && expert_vram < 0) { 4004 // a bigger prompt chunk feeds the MMQ expert kernels more rows per expert (R9700, UD-Q4_K_XL, pp4096: 512 3390, 1024 4005 // 4495, 2048 5353, 4096 5750 tok/s): the largest that fits beside the experts. Its buffers grow by about 0.5 MiB per 4006 // token (measured 0.47: 1.66 GiB more at 4096 than at 512), the sessions' K / V caches by 50 KB per cell and session. 4007 // With several slots a long prompt would hold the other slots' windows for a whole chunk: 1024 at most there. 4008 // (measured on a 32 GB R9700 at 8192 cells, 512 chunk: 1.77 GiB of buffers + K / V; the free room after init must still hold 4009 // every expert and the 0.77 GiB reserve, or place_experts gives the packed decode copies back - slower decode - or goes hybrid) 4010 const int ns = std::max(1, batch); 4011 const double kv_one = 45056.0, kv_shared = 5120.0; // per cell: a session's K / V, and the fp16 copies the prompt attention keeps 4012 const double sess_extra = std::max(0.0, (double) ctx * (kv_one * ns + kv_shared) - 8192.0 * (kv_one + kv_shared)); 4013 const int cap = ns > 1 ? 1024 : 4096; 4014 for (int c : {4096, 2048, 1024}) 4015 if (c <= cap && (double) experts + 2.75 * GiB + (double) (c - 512) * 0.5 * 1048576.0 + sess_extra <= (double) fr_raw) { // (no give-back of the packed decode copies for a bigger chunk) 4016 chunk = c; 4017 break; 4018 } 4019 } else if (!fits) { 4020 // the hybrid mode: 2048 (a chunk streams every layer's experts over PCIe once); a small card, where the chunk's buffers 4021 // would take the slots' room, falls back to less 4022 const double fr_gib = (double) fr / GiB; 4023 chunk = fr_gib >= 7.5 ? 2048 : fr_gib >= 5.5 ? 1024 : 512; 4024 } 4025 if (const char* cv = std::getenv("STRATA_Q36_CHUNK")) chunk = std::max(256, std::min(4096, std::atoi(cv))); // force a chunk (512: the old default) 4026 if (std::getenv("STRATA_Q36_PLACE_DEBUG")) 4027 std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (raw %.2f, with %.2f packed), main experts %.2f GiB, chunk %d\n", 4028 fr / 1073741824.0, fr_raw / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0, chunk); 4029 } 4030 E.init(m, ctx, chunk, batch, vision); 4031 if (!place_experts(m, E, expert_vram, cpu_threads, hybrid_rows, expert_slots, err)) { 4032 std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); 4033 return 1; 4034 } 4035 struct Report { 4036 Engine& E; 4037 ~Report() { 4038 if (E.verify_k) std::fprintf(stderr, "strata-q36 VERIFY: %lld comparisons, %lld mismatches\n", E.v_calls, E.v_bad); 4039 if (E.verify_k) 4040 for (const auto& kv : E.v_by) 4041 std::fprintf(stderr, "strata-q36 VERIFY %s: %lld mismatches\n", kv.first.c_str(), kv.second); 4042 if (!E.m->hybrid) return; 4043 const long long n = E.hy_cpu + E.hy_gpu; 4044 std::fprintf(stderr, "strata-q36: hybrid experts: %lld of %lld batch entries on the GPU (%.1f%%), %lld on the " 4045 "CPU pool in %.0f ms, %lld slot replacements\n", E.hy_gpu, n, n ? 100.0 * E.hy_gpu / n : 0.0, 4046 E.hy_cpu, E.hy_cpu_ms, E.hy_swaps); 4047 } 4048 } report{E}; 4049 E.reset(); 4050 E.mtp_d = m.has_mtp ? mtp_d : 0; 4051 if (draft_vocab < 0 && std::getenv("STRATA_Q36_DRAFT_VOCAB") != nullptr) draft_vocab = std::atoi(std::getenv("STRATA_Q36_DRAFT_VOCAB")); 4052 E.draft_n = std::max(0, draft_vocab); 4053 E.bmtp = (batch_mtp || (std::getenv("STRATA_BATCH_MTP") != nullptr && std::string(std::getenv("STRATA_BATCH_MTP")) != "0")) && E.n_sess > 1 && E.mtp_d > 0; 4054 if (batch_mtp && !E.bmtp) std::fprintf(stderr, "strata-q36: --batch-mtp needs --batch N (2 or more) and --mtp N: ignored\n"); 4055 if (warm) E.warmup(); 4056 if (serve_mode) return serve(E); 4057 if (bench_pp > 0 || bench_tg > 0) { 4058 // llama-bench's shapes: a prompt of bench_pp tokens from a fresh state, then bench_tg tokens one at a time 4059 std::vector<int32_t> toks((size_t) std::max(bench_pp, 1)); 4060 std::mt19937 rng(1234); 4061 for (auto& t : toks) t = (int32_t) (rng() % 200000u); 4062 for (int rep = 0; rep < 3; ++rep) { 4063 E.reset(); 4064 const auto t0 = Clock::now(); 4065 E.process(toks.data(), (int64_t) toks.size(), [](int64_t) {}); 4066 CK(cudaStreamSynchronize(E.st)); 4067 const double pp_ms = ms_since(t0); 4068 const auto t1 = Clock::now(); 4069 int nx = E.greedy(); 4070 for (int i = 0; i < bench_tg; ++i) { 4071 const int32_t one = nx; 4072 E.process(&one, 1, [](int64_t) {}); 4073 nx = E.greedy(); 4074 } 4075 const double tg_ms = ms_since(t1); 4076 std::printf("bench %d: pp%d %.1f tok/s, tg%d %.1f tok/s\n", rep, (int) toks.size(), 4077 (double) toks.size() / (pp_ms / 1000.0), bench_tg, 4078 bench_tg > 0 ? (double) bench_tg / (tg_ms / 1000.0) : 0.0); 4079 std::fflush(stdout); 4080 } 4081 return 0; 4082 } 4083 const std::vector<int32_t> prompt = parse_ids(tokens.c_str()), forced = parse_ids(force.c_str()); 4084 if (prompt.empty()) { std::fprintf(stderr, "strata-q36: --tokens, --serve or --bench-pp is required\n"); return 2; } 4085 if (!forced.empty()) n_gen = (int) forced.size() + 1; 4086 FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); 4087 std::vector<float> lg; 4088 std::vector<int32_t> gen; 4089 if (!emb_file.empty()) { 4090 if (!vision) { std::fprintf(stderr, "strata-q36: --emb needs --vision\n"); return 2; } 4091 ImgReq ir; 4092 const std::string ve = build_images(emb_file, prompt, m.g.n_embd, {}, ir); 4093 if (!ve.empty()) { std::fprintf(stderr, "strata-q36: %s\n", ve.c_str()); return 2; } 4094 E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) prompt.size(), ir.delta); 4095 std::fprintf(stderr, "strata-q36: %zu picture(s), %zu rows, text after them at cell + %d\n", ir.imgs.size(), 4096 ir.rows.size() / (size_t) m.g.n_embd, (int) ir.delta); 4097 } 4098 const auto t0 = Clock::now(); 4099 E.process(prompt.data(), (int64_t) prompt.size(), [](int64_t) {}); 4100 const double pp_ms = ms_since(t0); 4101 const auto t1 = Clock::now(); 4102 if (E.mtp_d > 0 && forced.empty() && !ff) { 4103 long long offered = 0, accepted = 0; 4104 std::vector<int32_t> fix, drafts; 4105 int32_t picks[16]; 4106 int nx = E.greedy(); 4107 while ((int) gen.size() < n_gen) { 4108 gen.push_back(nx); 4109 if ((int) gen.size() >= n_gen) break; 4110 const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); 4111 offered += E.mtp_d; 4112 accepted += a; 4113 fix.assign(drafts.begin(), drafts.begin() + a); 4114 for (int i = 0; i < a && (int) gen.size() < n_gen; ++i) gen.push_back(drafts[(size_t) i]); 4115 nx = picks[a]; 4116 } 4117 gen.resize((size_t) n_gen); 4118 std::printf("gen:"); 4119 for (int t : gen) std::printf(" %d", t); 4120 std::printf("\n"); 4121 std::fprintf(stderr, "strata-q36: prompt %zu tokens in %.1f ms, %zu generated in %.1f ms (%.1f tok/s), MTP %d drafts: " 4122 "%lld of %lld accepted (%.0f%%)\n", prompt.size(), pp_ms, gen.size(), ms_since(t1), 4123 gen.size() / (ms_since(t1) / 1000.0), E.mtp_d, accepted, offered, 4124 offered ? 100.0 * accepted / offered : 0.0); 4125 return 0; 4126 } 4127 for (int i = 0; i < n_gen; ++i) { 4128 const int a = E.greedy(); 4129 gen.push_back(a); 4130 if (ff) { 4131 E.host_logits(lg); 4132 std::fwrite(lg.data(), 4, lg.size(), ff); 4133 } 4134 if (i + 1 == n_gen) break; 4135 const int32_t nx = i < (int) forced.size() ? forced[(size_t) i] : a; 4136 E.process(&nx, 1, [](int64_t) {}); 4137 } 4138 if (ff) std::fclose(ff); 4139 std::printf("gen:"); 4140 for (int t : gen) std::printf(" %d", t); 4141 std::printf("\n"); 4142 std::fprintf(stderr, "strata-q36: prompt %zu tokens in %.1f ms (%.1f tok/s), %zu generated in %.1f ms (%.1f tok/s)\n", 4143 prompt.size(), pp_ms, prompt.size() / (pp_ms / 1000.0), gen.size(), ms_since(t1), 4144 gen.size() / (ms_since(t1) / 1000.0)); 4145 return 0; 4146}