diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e9806e4..119cd8df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -614,6 +614,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(strata-q36ref src/qwen35/q36ref.cu) target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu + add_executable(strata-q36 src/qwen35/q36_engine.cu) + target_include_directories(strata-q36 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata-q36 PRIVATE strata_prefill strata_kernels strata_warnings ${_strata_gpu_runtime_target}) if(STRATA_ENABLE_HIP) enable_testing() diff --git a/include/strata/hip_compat/cublas_v2.h b/include/strata/hip_compat/cublas_v2.h index 87944796..2a482cfa 100644 --- a/include/strata/hip_compat/cublas_v2.h +++ b/include/strata/hip_compat/cublas_v2.h @@ -52,6 +52,8 @@ inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a, #define cublasCreate hipblasCreate #define cublasDestroy hipblasDestroy #define cublasGemmEx hipblasGemmEx +#define cublasSgemm hipblasSgemm // the Qwen3.6 engine's FP32 prompt products +#define cublasSgemmStridedBatched hipblasSgemmStridedBatched #define cublasHandle_t hipblasHandle_t #define cublasSetMathMode hipblasSetMathMode #define cublasSetStream hipblasSetStream diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index c2e44270..ebed142b 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -612,7 +612,12 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, #else #define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) #endif -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) +// Q5_K / Q6_K downs: Qwen3.6-35B-A3B (FF 512, whole 256-blocks per row); Flash-Next's FF 640 never selects them +#ifdef STRATA_Q6K_EXPERTS +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) +#else +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) +#endif #define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) __device__ __forceinline__ float warp_sum(float v) { diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu new file mode 100644 index 00000000..abfca866 --- /dev/null +++ b/src/qwen35/q36_engine.cu @@ -0,0 +1,1454 @@ +// src/qwen35/q36_engine.cu - strata-q36: the engine path for Qwen3.6-35B-A3B (GGUF architecture qwen35moe), +// NEW-MODELS-PLAN.md T1. A driver of its own beside Flash-Next's (generate/verify/prefill stay untouched, so the +// Flash-Next identity gate cannot move), built from Strata's kernels: +// +// * weights straight from the GGUF: dense Q8_0 / K-quant matrices in their blocks (native MMVQ), the 1-D tensors and +// the F32 projections (ssm_alpha/beta, the router, the shared-expert gate) as f32, the routed experts repacked at +// load into native expert blobs [gate | up | down] per (layer, expert) for `native_expert_grouped`; +// * the plain pre-norm residual layer driver: x += mixer(rms(x) * attn_norm); x += moe(rms(x) * post_attention_norm); +// * GDN: fused conv + L2 and the fused step with the SiLU-gated norm (per token, the state carried); +// * attention without an indexer: dense, 16 query heads over 2 KV heads, split-K over 256-cell chunks with a +// log-sum-exp merge, causal for a batch of queries (the prompt) and for one (decode); +// * MoE: the native router (256 / top-8), the experts grouped per expert on the device (one weight read per expert +// for the whole batch), the shared expert with its sigmoid gate, the native combine; +// * the prompt read in chunks of --chunk tokens through the same driver (batched matmuls, ncols <= 8 per launch); +// * decode one token at a time from a captured graph (positions on the device), or with --no-graph eagerly. +// +// Modes: --serve (serve/server.py's engine protocol: READY / GEN / T / DONE / STOP / PP), --tokens IDS [--n N] +// [--force IDS] [--dump-full-logits F] (tools/qwen35/kl.py's reference interface), --bench-pp N / --bench-tg N. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/prefill/gemm.hpp" +#include "strata/prefill/moe_mmq.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace K = strata::kernels; +namespace MMQ = strata::prefill::mmq; + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "strata-q36: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \ + std::exit(1); \ + } \ + } while (0) + +using Clock = std::chrono::steady_clock; +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +constexpr int kThreads = 256; +constexpr int kChunkCells = 256; // attention split-K chunk + +// ------------------------------------------------------------------------------------------------ small kernels +__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } +__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } +__device__ __forceinline__ float softplus(float v) { return v > 20.f ? v : log1pf(expf(v)); } + +__device__ float block_sum(float v, float* sh) { + sh[threadIdx.x] = v; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s]; + __syncthreads(); + } + const float r = sh[0]; + __syncthreads(); + return r; +} +__device__ float block_max(float v, float* sh) { + sh[threadIdx.x] = v; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]); + __syncthreads(); + } + const float r = sh[0]; + __syncthreads(); + return r; +} + +/// y[r] = rms(x[r]) * w, one block per row of n. +__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) { + __shared__ float sh[kThreads]; + const float* xr = x + (size_t) blockIdx.x * n; + float* yr = y + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) yr[i] = xr[i] * r * w[i]; +} +/// 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. +__global__ void k_add_rms(float* x, const float* y, const float* w, float* h, int n, float eps) { + __shared__ float sh[kThreads]; + float* xr = x + (size_t) blockIdx.x * n; + const float* yr = y + (size_t) blockIdx.x * n; + float* hr = h + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const float v = xr[i] + yr[i]; + xr[i] = v; + s += v * v; + } + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) hr[i] = xr[i] * r * w[i]; +} +/// 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 +/// product, as native_moe_combine) + sigmoid(sgate) * shared; then, with `wn`, h = rms(x) * wn (the next layer's +/// attention norm). Replaces combine + gate + add + rms. +__global__ void k_moe_out(float* x, const float* parts, const int32_t* prow, const float* wts, int K_, + const float* shared, const float* sgate, int sg_stride, const float* wn, float* h, int n, + float eps) { + __shared__ float sh[kThreads]; + __shared__ const float* pk[16]; + const int t = blockIdx.x; + float* xr = x + (size_t) t * n; + if (threadIdx.x < K_) // pick k's row: t * K + k, or its sorted row (`prow`, the prompt's MMQ order) + pk[threadIdx.x] = parts + (size_t) (prow ? prow[t * K_ + threadIdx.x] : t * K_ + threadIdx.x) * n; + __syncthreads(); + const float* wr = wts + (size_t) t * K_; + const float gs = sigm(sgate[(size_t) t * sg_stride]); + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + float acc = wr[0] * pk[0][i]; + for (int k = 1; k < K_; ++k) acc = fmaf(wr[k], pk[k][i], acc); + acc += gs * shared[(size_t) t * n + i]; + const float v = xr[i] + acc; + xr[i] = v; + s += v * v; + } + if (wn == nullptr) return; + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) h[(size_t) t * n + i] = xr[i] * r * wn[i]; +} +/// GDN alpha and beta for T <= 8 rows in one launch, their epilogues applied: rows [0, HV) of the output are +/// softplus(alpha . x + dt) * ssm_a, rows [HV, 2 HV) sigmoid(beta . x). Warp per row (grid (ceil(2 HV / 8), T)). +__global__ void k_gdn_ab(const float* Wa, const float* Wb, const float* x, const float* dt, const float* ssm_a, + float* alpha, float* beta, int n_in, int HV) { + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; + const int o = blockIdx.x * 8 + warp; + if (o >= 2 * HV) return; + const bool isb = o >= HV; + const int r = isb ? o - HV : o; + const float4* wr = (const float4*) ((isb ? Wb : Wa) + (size_t) r * n_in); + const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); + float acc = 0.f; + for (int i = lane; i < n_in / 4; i += 32) { + const float4 a = wr[i], b = xr[i]; + acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); + if (lane != 0) return; + if (isb) beta[(size_t) blockIdx.y * HV + r] = sigm(acc); + else alpha[(size_t) blockIdx.y * HV + r] = softplus(acc + dt[r]) * ssm_a[r]; +} +__global__ void k_add(float* x, const float* y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} +__global__ void k_swiglu(const float* g, const float* u, float* h, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) h[i] = silu(g[i]) * u[i]; +} +/// 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 +/// block (grid (ceil(n_out / 8), T)). +__global__ void k_gemv_f32(const float* W, const float* x, float* y, int n_in, int n_out) { + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; + const int o = blockIdx.x * 8 + warp; + if (o >= n_out) return; + const float4* wr = (const float4*) (W + (size_t) o * n_in); + const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); + float acc = 0.f; + for (int i = lane; i < n_in / 4; i += 32) { + const float4 a = wr[i], b = xr[i]; + acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); + if (lane == 0) y[(size_t) blockIdx.y * n_out + o] = acc; +} +unsigned rows8(int n) { return (unsigned) ((n + 7) / 8); } +/// GDN gate / beta in place for T rows of HV: alpha -> softplus(alpha + dt) * ssm_a, beta -> sigmoid(beta). +__global__ void k_gdn_gb(float* alpha, const float* dt, const float* ssm_a, float* beta, int HV, int T) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= HV * T) return; + const int h = i % HV; + alpha[i] = softplus(alpha[i] + dt[h]) * ssm_a[h]; + beta[i] = sigm(beta[i]); +} +/// sh[t] *= sigmoid(gate[t]) (the shared expert's scalar gate), rows of n. +__global__ void k_gate_rows(float* sh, const float* gate, int n, int T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (int64_t) n * T) return; + sh[i] *= sigm(gate[i / n]); +} + +/// The attention layer's per-token preparation for T rows at positions *pos0 + t: q (from the [q | gate] pairs) and k +/// RMS-normed per head with their weights, NEOX RoPE over the first n_rot dims, k / v into the cache, the gate kept. +/// grid (H + HKV, T), block 256 (HD <= 256). +__global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, + float* q, float* gate, float* kc, float* vc, int H, int HKV, int HD, int n_rot, + const int32_t* pos0, int ctx, float base, float eps) { + __shared__ float sh[kThreads]; + __shared__ float buf[256]; + const int head = blockIdx.x, t = blockIdx.y; + const int pos = *pos0 + t; + const bool isq = head < H; + const float* src = isq ? qg + ((size_t) t * H + head) * 2 * HD : kx + ((size_t) t * HKV + head - H) * HD; + const int i = threadIdx.x; + const float v0 = i < HD ? src[i] : 0.f; + const float s = block_sum(v0 * v0, sh); + const float r = rsqrtf(s / (float) HD + eps); + if (i < HD) buf[i] = v0 * r * (isq ? qw[i] : kw[i]); + __syncthreads(); + if (i >= HD) return; + float v = buf[i]; + const int half = n_rot / 2; + if (i < n_rot) { + const int p = i < half ? i : i - half; + const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot); + float sn, cs; + sincosf(theta, &sn, &cs); + v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; + } + if (isq) { + q[((size_t) t * H + head) * HD + i] = v; + gate[((size_t) t * H + head) * HD + i] = qg[((size_t) t * H + head) * 2 * HD + HD + i]; + } else { + const int kh = head - H; + kc[((size_t) kh * ctx + pos) * HD + i] = v; + vc[((size_t) kh * ctx + pos) * HD + i] = vx[((size_t) t * HKV + kh) * HD + i]; + } +} + +/// Split-K attention, one block per (chunk of 256 cells, query row): query row qi = t * H + h (t from t0) sees the +/// cells [0, *pos0 + t]. Writes the chunk's partial accumulator, max and sum; chunks past the query's cells write +/// nothing (the merge stops before them). grid (n_chunk, n_rows), block 256, HD == 256. +__global__ void k_attn_part(const float* q, const float* kc, const float* vc, const int32_t* pos0, int t0, int H, + int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl) { + constexpr int HD = 256; + __shared__ float qs[HD], sc[kChunkCells], sh[kThreads]; + const int c = blockIdx.x, row = blockIdx.y; + const int t = t0 + row / H, h = row % H, kvh = h / (H / HKV); + const int npos = *pos0 + t + 1; + const int p0 = c * kChunkCells; + if (p0 >= npos) return; + const int j = threadIdx.x; + qs[j] = q[((size_t) t * H + h) * HD + j]; + __syncthreads(); + const int p = p0 + j; + float s = -INFINITY; + if (p < npos) { + const float* kp = kc + ((size_t) kvh * ctx + p) * HD; + float a = 0.f; + for (int i = 0; i < HD; ++i) a += qs[i] * kp[i]; + s = a * scale; + } + const float m = block_max(s, sh); + const float e = p < npos ? expf(s - m) : 0.f; + sc[j] = e; + const float l = block_sum(e, sh); + const int n = min(kChunkCells, npos - p0); + float acc = 0.f; + const float* vp = vc + ((size_t) kvh * ctx + p0) * HD + j; + for (int k = 0; k < n; ++k) acc += sc[k] * vp[(size_t) k * HD]; + const size_t o = (size_t) row * n_chunk + c; + pacc[o * HD + j] = acc; + if (j == 0) { + pm[o] = m; + pl[o] = l; + } +} +/// The chunks merged, times sigmoid(gate): grid (n_rows), block HD. +__global__ void k_attn_merge(const float* pacc, const float* pm, const float* pl, const float* gate, + const int32_t* pos0, int t0, int H, int n_chunk, float* out) { + constexpr int HD = 256; + const int row = blockIdx.x, t = t0 + row / H, h = row % H, d = threadIdx.x; + const int npos = *pos0 + t + 1; + const int nc = (npos + kChunkCells - 1) / kChunkCells; + float M = -INFINITY; + for (int c = 0; c < nc; ++c) M = fmaxf(M, pm[(size_t) row * n_chunk + c]); + float num = 0.f, den = 0.f; + for (int c = 0; c < nc; ++c) { + const size_t o = (size_t) row * n_chunk + c; + const float w = expf(pm[o] - M); + num += w * pacc[o * HD + d]; + den += w * pl[o]; + } + const size_t gi = ((size_t) t * H + h) * HD + d; + out[gi] = num / den * sigm(gate[gi]); +} + +/// The routed entries (T tokens x K picks, entry e = t * K + k) grouped per expert, on the device: one group per +/// expert used (ascending id), its blob address, its entries in entry order. One block. +__global__ void k_group(const int32_t* ids, int n_ent, int K_, int n_expert, const uint8_t* blobs, unsigned long long blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups, int32_t* ent_dst, + int32_t* ent_tok) { + __shared__ int cnt[512], off[512]; + for (int x = threadIdx.x; x < n_expert; x += blockDim.x) cnt[x] = 0; + __syncthreads(); + for (int e = threadIdx.x; e < n_ent; e += blockDim.x) atomicAdd(&cnt[ids[e]], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int g = 0, pos = 0; + for (int x = 0; x < n_expert; ++x) { + off[x] = pos; + if (cnt[x] == 0) continue; + grp_ptr[g] = (unsigned long long) (blobs + (size_t) x * blob); + grp_start[g] = pos; + pos += cnt[x]; + ++g; + } + grp_start[g] = pos; + *n_groups = g; + for (int e = 0; e < n_ent; ++e) { + const int p = off[ids[e]]++; + ent_dst[p] = e; + ent_tok[p] = e / K_; + } + } +} +/// The prompt's attention probabilities in place: row (h, t) of S (ld floats, P cells) -> softmax(S * scale) over the +/// cells [0, pos0 + t], 0 past them (causal). grid (T, H), block 256. +__global__ void k_attn_softmax(float* S, int ld, int T, int P, int pos0, float scale) { + __shared__ float sh[kThreads]; + const int t = blockIdx.x, h = blockIdx.y; + float* row = S + ((size_t) h * T + t) * ld; + const int n = min(P, pos0 + t + 1); + float mx = -INFINITY; + for (int p = threadIdx.x; p < n; p += blockDim.x) mx = fmaxf(mx, row[p] * scale); + mx = block_max(mx, sh); + float sum = 0.f; + for (int p = threadIdx.x; p < n; p += blockDim.x) sum += expf(row[p] * scale - mx); + sum = block_sum(sum, sh); + const float inv = 1.0f / sum; + for (int p = threadIdx.x; p < P; p += blockDim.x) row[p] = p < n ? expf(row[p] * scale - mx) * inv : 0.f; +} +/// att *= sigmoid(gate) (the attention output gate), n values. +__global__ void k_gate_mul(float* att, const float* gate, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) att[i] *= sigm(gate[i]); +} + +/// The prompt's routed entries sorted by expert for MMQ: bounds[x] .. bounds[x + 1] are expert x's rows; sorted row r +/// 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 +/// atomics' (no output depends on it: every row's products are its own). cnt / cur: n_expert ints of scratch. +__global__ void k_route_count(const int32_t* ids, int n_ent, int32_t* cnt) { + const int e = blockIdx.x * blockDim.x + threadIdx.x; + if (e < n_ent) atomicAdd(&cnt[ids[e]], 1); +} +__global__ void k_route_scan(const int32_t* cnt, int n_expert, int32_t* bounds, int32_t* cur, int32_t* max_rows) { + if (threadIdx.x != 0) return; + int pos = 0, mx = 0; + for (int x = 0; x < n_expert; ++x) { + bounds[x] = pos; + cur[x] = pos; + pos += cnt[x]; + mx = max(mx, cnt[x]); + } + bounds[n_expert] = pos; + *max_rows = mx; +} +__global__ void k_route_scatter(const int32_t* ids, int n_ent, int K_, int32_t* cur, int32_t* dst, int32_t* src, + int32_t* inv) { + const int e = blockIdx.x * blockDim.x + threadIdx.x; + if (e >= n_ent) return; + const int r = atomicAdd(&cur[ids[e]], 1); + dst[r] = e; + src[r] = e / K_; + inv[e] = r; // entry e's sorted row: where its down product lands +} + +/// The greedy pick of one logits row: out = argmax (lowest id on ties). Stage 1: `gridDim.x` blocks each write the +/// best of their stride into (pv, pi); stage 2 (one block, n = the stage-1 block count) reads those. +__global__ void k_argmax(const float* x, int n, int32_t* out, float* pv, int32_t* pi, bool stage2) { + __shared__ float bv[kThreads]; + __shared__ int bi[kThreads]; + float v = -INFINITY; + int id = 0x7fffffff; + if (stage2) { + for (int i = threadIdx.x; i < n; i += blockDim.x) + if (pv[i] > v || (pv[i] == v && pi[i] < id)) { v = pv[i]; id = pi[i]; } + } else { + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) + if (x[i] > v) { v = x[i]; id = i; } + } + bv[threadIdx.x] = v; + bi[threadIdx.x] = id; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) { + const float ov = bv[threadIdx.x + s]; + const int oi = bi[threadIdx.x + s]; + if (ov > bv[threadIdx.x] || (ov == bv[threadIdx.x] && oi < bi[threadIdx.x])) { + bv[threadIdx.x] = ov; + bi[threadIdx.x] = oi; + } + } + __syncthreads(); + } + if (threadIdx.x == 0) { + if (stage2) *out = bi[0]; + else { pv[blockIdx.x] = bv[0]; pi[blockIdx.x] = bi[0]; } + } +} +constexpr int kArgBlocks = 128; + +unsigned grid1(int64_t n, int b = kThreads) { return (unsigned) ((n + b - 1) / b); } + +/// x f32 -> FP16 bits (the prompt GEMMs' activations). +__global__ void k_to_f16(const float* x, __half* y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = __float2half(x[i]); +} + +/// The GDN conv for T tokens in ONE launch (the prompt): one block per 128-channel head, thread = channel, the +/// 3-entry history carried in registers across the tokens and written back at the end; SiLU, then the L2 norm of the +/// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. +__global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, + int qk_heads, float eps, int T) { + __shared__ float part[4]; + const int c = blockIdx.x * 128 + threadIdx.x; + float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + const bool qk = (int) blockIdx.x < qk_heads; + for (int t = 0; t < T; ++t) { + const float x = qkv[(size_t) t * C + c]; + const float sum = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + v0 = v1; + v1 = v2; + v2 = x; + float y = sum / (1.0f + __expf(-sum)); + if (qk) { + float sq = y * y; + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + __syncthreads(); + y *= rsqrtf(ss + eps); + } + h[(size_t) t * C + c] = y; + } + hist[c * 3] = v0; + hist[c * 3 + 1] = v1; + hist[c * 3 + 2] = v2; +} + +/// The gated delta rule + SiLU-gated norm for T tokens in ONE launch (the prompt): fused_gdn_step_norm's kernel +/// (block = one V head, 128 columns x 4 row groups, state [row][head][col]) with its 32 state rows per thread kept in +/// registers across the tokens. h (T, C) = q | k | v, gate / beta (T, HV), z / y (T, ZV). +__global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, + float* y, int h_k, int h_v, int T) { + constexpr int S = 128, RG = 4, RPG = 32; + __shared__ float sk[S], sq[S]; + __shared__ float red_kv[RG][S]; + __shared__ float red_o[RG][S]; + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; + const int qh = head % h_k; + const int ZV = h_v * S; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + for (int t = 0; t < T; ++t) { + const float* ht = h + (size_t) t * C; + if (tid < S) { sk[tid] = ht[h_k * S + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red_kv[rg][col] = kv; + __syncthreads(); + const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col]; + const float delta = (ht[2 * h_k * S + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + red_o[rg][col] = o; + __syncthreads(); + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) * rsqrtf((float) S); + sq_part = oc * oc; + } + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; + __syncthreads(); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * ZV + head * S + col]; + y[(size_t) t * ZV + head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz))); + } + __syncthreads(); // sk / sq / the reductions are rewritten by the next token + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; +} + +// ------------------------------------------------------------------------------------------------ the model +struct Mat { + const uint8_t* d = nullptr; // device, GGUF blocks + int type = -1; + int n_in = 0, n_out = 0; +}; + +struct Layer { + bool attn = false; + const float *attn_norm = nullptr, *post_norm = nullptr; + // GDN + Mat qkv, zg, ssm_out; + const float *alpha = nullptr, *beta = nullptr, *dt = nullptr, *ssm_a = nullptr, *conv = nullptr, *ssm_norm = nullptr; + // attention + Mat wq, wk, wv, wo; + const float *q_norm = nullptr, *k_norm = nullptr; + // MoE + const float* router = nullptr; // [n_expert][N] f32 + float* router_ext = nullptr; // the same with the shared expert's gate row appended: [n_expert + 1][N] + Mat sh_gate, sh_up, sh_down; + const float* sh_gate_inp = nullptr; // [N] + K::NativeExpertLayout L; + uint8_t* blobs = nullptr; // n_expert blobs, `stride` bytes apart (L.bytes rounded up to whole blocks of every + size_t stride = 0; // part's type, so MMQ can step over them by blocks), then kMmqTail zero bytes +}; + +struct Model { + strata::core::ModelGeometry g; + int64_t top_k = 8; + float eps = 1e-6f, rope_base = 1e7f; + int n_rot = 64; + std::vector layers; + const float* out_norm = nullptr; + Mat head; + const uint8_t* embd = nullptr; + int embd_type = -1; + size_t embd_row = 0; +}; + +constexpr size_t kMmqTail = 4096; +size_t gcd_sz(size_t a, size_t b) { return b ? gcd_sz(b, a % b) : a; } +size_t lcm_sz(size_t a, size_t b) { return a / gcd_sz(a, b) * b; } +size_t block_bytes(int type) { + int be = 0, bb = 0; + return strata::block_geometry((uint32_t) type, be, bb) ? (size_t) bb : 1; +} // zeroed bytes after the last expert (MMQ reads a little past a matrix) + +size_t row_bytes(int type, int64_t n) { + int be = 0, bb = 0; + if (!strata::block_geometry((uint32_t) type, be, bb)) return 0; + return (size_t) (n / be) * (size_t) bb; +} + +float bf16_to_f32(uint16_t b) { + const uint32_t u = (uint32_t) b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +/// A tensor as f32 on the device (F32 as it is, BF16 / F16 widened). +float* upload_f32(const strata::TensorInfo& t, const uint8_t* src) { + std::vector h((size_t) t.elements()); + if (t.type == 0) std::memcpy(h.data(), src, h.size() * 4); + else if (t.type == 30) + for (size_t i = 0; i < h.size(); ++i) h[i] = bf16_to_f32((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); + else { + std::fprintf(stderr, "strata-q36: %s is %s, expected F32 or BF16\n", t.name.c_str(), t.type_name()); + std::exit(1); + } + float* d = nullptr; + CK(cudaMalloc(&d, h.size() * 4)); + CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); + return d; +} + +bool load(const std::string& path, Model& m, std::string& err) { + const auto t0 = Clock::now(); + const strata::GgufModel gm = strata::GgufModel::open(path); + if (!strata::core::geometry_from_gguf(gm.meta(), m.g, m.top_k, err)) return false; + if (m.g.family != strata::ModelFamily::Qwen35Moe) { + err = "strata-q36 runs Qwen3.6-35B-A3B (qwen35moe) files only"; + return false; + } + size_t checked = 0; + if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) return false; + const auto& g = m.g; + if (g.head_dim != 256 || g.ssm_state_size != 128 || g.ssm_d_conv != 4 || g.n_expert > 512 || m.top_k > 15) { + err = "a geometry this driver's kernels do not take (head 256, state 128, conv 4, <= 512 experts, top-k <= 15)"; + return false; + } + const std::string p = "qwen35moe."; + if (const strata::MetaValue* v = gm.meta().get(p + "attention.layer_norm_rms_epsilon")) m.eps = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.freq_base")) m.rope_base = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.dimension_count")) m.n_rot = (int) v->u; + uint64_t bytes = 0; + auto find = [&](const std::string& name, size_t& s) -> const strata::TensorInfo* { + const strata::TensorInfo* t = gm.find(name, &s); + if (!t) { + std::fprintf(stderr, "strata-q36: missing %s\n", name.c_str()); + std::exit(1); + } + return t; + }; + auto f32 = [&](const std::string& name) -> const float* { + size_t s = 0; + const strata::TensorInfo* t = find(name, s); + bytes += t->elements() * 4; + return upload_f32(*t, gm.shard(s).tensor_data(*t)); + }; + auto mat = [&](const std::string& name) -> Mat { + size_t s = 0; + const strata::TensorInfo* t = find(name, s); + Mat w; + w.type = (int) t->type; + w.n_in = (int) t->shape[0]; + w.n_out = (int) t->shape[1]; + if (!K::native_mmvq_supported(w.type)) { + std::fprintf(stderr, "strata-q36: %s is %s, which the native MMVQ does not take\n", name.c_str(), t->type_name()); + std::exit(1); + } + const uint64_t nb = strata::tensor_payload_bytes(*t); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); + bytes += nb; + w.d = d; + // STRATA_Q8_PACKED (on by default here): the lossless qs / d plane copy the Q8_0 decode kernels read instead, + // bitwise the same outputs + if (w.type == 8 && K::native_q8_0_packed_enabled() && K::native_q8_0_packed_eligible(w.n_in, w.n_out)) { + std::vector packed(nb); + K::native_q8_0_pack_host(gm.shard(s).tensor_data(*t), packed.data(), w.n_in, w.n_out); + uint8_t* pd = nullptr; + CK(cudaMalloc(&pd, nb)); + CK(cudaMemcpy(pd, packed.data(), nb, cudaMemcpyHostToDevice)); + K::native_q8_0_packed_register(d, pd, w.n_in, w.n_out); + bytes += nb; + } + return w; + }; + auto L = [](int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; }; + m.layers.resize((size_t) g.n_layers); + for (int64_t l = 0; l < g.n_layers; ++l) { + Layer& y = m.layers[(size_t) l]; + y.attn = strata::core::is_qsa_layer(g, l); + y.attn_norm = f32(L(l, "attn_norm.weight")); + y.post_norm = f32(L(l, "post_attention_norm.weight")); + if (!y.attn) { + y.qkv = mat(L(l, "attn_qkv.weight")); + y.zg = mat(L(l, "attn_gate.weight")); + y.ssm_out = mat(L(l, "ssm_out.weight")); + y.alpha = f32(L(l, "ssm_alpha.weight")); + y.beta = f32(L(l, "ssm_beta.weight")); + y.dt = f32(L(l, "ssm_dt.bias")); + y.ssm_a = f32(L(l, "ssm_a")); + y.conv = f32(L(l, "ssm_conv1d.weight")); + y.ssm_norm = f32(L(l, "ssm_norm.weight")); + } else { + y.wq = mat(L(l, "attn_q.weight")); + y.wk = mat(L(l, "attn_k.weight")); + y.wv = mat(L(l, "attn_v.weight")); + y.wo = mat(L(l, "attn_output.weight")); + y.q_norm = f32(L(l, "attn_q_norm.weight")); + y.k_norm = f32(L(l, "attn_k_norm.weight")); + } + y.router = f32(L(l, "ffn_gate_inp.weight")); + y.sh_gate = mat(L(l, "ffn_gate_shexp.weight")); + y.sh_up = mat(L(l, "ffn_up_shexp.weight")); + y.sh_down = mat(L(l, "ffn_down_shexp.weight")); + y.sh_gate_inp = f32(L(l, "ffn_gate_inp_shexp.weight")); + CK(cudaMalloc(&y.router_ext, (size_t) (g.n_expert + 1) * g.n_embd * 4)); + CK(cudaMemcpy(y.router_ext, y.router, (size_t) g.n_expert * g.n_embd * 4, cudaMemcpyDeviceToDevice)); + CK(cudaMemcpy(y.router_ext + (size_t) g.n_expert * g.n_embd, y.sh_gate_inp, (size_t) g.n_embd * 4, + cudaMemcpyDeviceToDevice)); + bytes += (size_t) (g.n_expert + 1) * g.n_embd * 4; + // the routed experts: [gate | up | down] per expert, the native expert layout + size_t sg = 0, su = 0, sd = 0; + const strata::TensorInfo* tg = find(L(l, "ffn_gate_exps.weight"), sg); + const strata::TensorInfo* tu = find(L(l, "ffn_up_exps.weight"), su); + const strata::TensorInfo* td = find(L(l, "ffn_down_exps.weight"), sd); + if (tg->type != tu->type) { + err = L(l, "ffn_gate_exps / ffn_up_exps differ in type"); + return false; + } + if (!K::native_expert_supported((int) tg->type, (int) td->type, g.n_embd, g.n_ff)) { + err = L(l, "experts are ") + tg->type_name() + "/" + td->type_name() + ", which the native expert kernels " + + "do not take (build with -DSTRATA_Q6K_EXPERTS=ON for Q6_K)"; + return false; + } + y.L = K::native_expert_layout((int) tg->type, (int) td->type, g.n_embd, g.n_ff); + const size_t gsz = (size_t) g.n_ff * y.L.gu_row, dsz = (size_t) g.n_embd * y.L.d_row; + // a stride in whole blocks of both parts' types (MMQ steps over the experts by blocks), 16-byte aligned + const size_t al = lcm_sz(lcm_sz(block_bytes(y.L.gu_type), block_bytes(y.L.d_type)), 16); + y.stride = (y.L.bytes + al - 1) / al * al; + CK(cudaMalloc(&y.blobs, y.stride * (size_t) g.n_expert + kMmqTail)); + CK(cudaMemset(y.blobs, 0, y.stride * (size_t) g.n_expert + kMmqTail)); + const uint8_t* G0 = gm.shard(sg).tensor_data(*tg); + const uint8_t* U0 = gm.shard(su).tensor_data(*tu); + const uint8_t* D0 = gm.shard(sd).tensor_data(*td); + // one expert's three parts staged in host memory, then one copy per expert + std::vector stage(y.L.bytes); + for (int64_t e = 0; e < g.n_expert; ++e) { + std::memcpy(stage.data(), G0 + (size_t) e * gsz, gsz); + std::memcpy(stage.data() + y.L.up_off, U0 + (size_t) e * gsz, gsz); + std::memcpy(stage.data() + y.L.down_off, D0 + (size_t) e * dsz, dsz); + CK(cudaMemcpy(y.blobs + (size_t) e * y.stride, stage.data(), y.L.bytes, cudaMemcpyHostToDevice)); + } + bytes += y.stride * (size_t) g.n_expert; + } + m.out_norm = f32("output_norm.weight"); + m.head = mat("output.weight"); + { + size_t s = 0; + const strata::TensorInfo* t = find("token_embd.weight", s); + m.embd_type = (int) t->type; + m.embd_row = row_bytes(m.embd_type, (int64_t) t->shape[0]); + const uint64_t nb = strata::tensor_payload_bytes(*t); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); + m.embd = d; + bytes += nb; + } + std::fprintf(stderr, "strata-q36: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s\n", path.c_str(), + checked, (double) bytes / (1 << 30), ms_since(t0) / 1000.0); + return true; +} + +// ------------------------------------------------------------------------------------------------ the engine +float* dalloc(size_t n) { + float* p = nullptr; + CK(cudaMalloc(&p, n * 4)); + CK(cudaMemset(p, 0, n * 4)); + return p; +} +template T* dalloc_t(size_t n) { + T* p = nullptr; + CK(cudaMalloc(&p, n * sizeof(T))); + CK(cudaMemset(p, 0, n * sizeof(T))); + return p; +} + +struct Engine { + const Model* m = nullptr; + cudaStream_t st = nullptr; + int ctx = 32768, tmax = 512; + int64_t pos = 0; // cells holding a processed token + // activations [tmax][...] + float *x, *h, *y, *qkv, *hc, *z, *alpha, *beta, *gdn_y, *qg, *kx, *vx, *q, *gate, *att, *logits_r, *eparts, *moe_out, + *sg, *su, *shh, *sy, *sgate, *ewts, *logits; + void *q8, *xq, *escr; + int32_t *ids, *grp_start, *n_groups, *ent_dst, *ent_tok, *tok, *pos0, *pick; + int32_t* hpin = nullptr; // pinned staging: [0] the decode token, [1] its position, [2] the greedy pick + unsigned long long* grp_ptr; + float *pacc, *pm, *pl, *amv; + int32_t* ami; + int n_chunk = 0, att_rows = 0; // attention partials: att_rows query rows x n_chunk chunks + std::vector conv, S, kc, vc; + // the decode graph (T = 1) + cudaGraphExec_t g1 = nullptr; + strata::prefill::Gemm gemm; + cublasHandle_t blas = nullptr; + float* att_s = nullptr; // the prompt attention's scores / probabilities, kAttScoreFloats floats + static constexpr size_t kAttScoreFloats = (size_t) 64 << 20; // 256 MB + // the prompt's MMQ experts + bool use_mmq = false; + std::unique_ptr mctx; + int32_t *rcnt = nullptr, *rcur = nullptr, *rbounds = nullptr, *rmax = nullptr, *ident = nullptr, *rinv = nullptr; + void *mq_x = nullptr, *mq_hq = nullptr; + float *mq_gu = nullptr, *mq_h = nullptr; + __half* x16 = nullptr; + bool use_graph = true; + + void init(const Model& model, int ctx_, int tmax_) { + m = &model; + ctx = ctx_; + tmax = tmax_; + const auto& g = m->g; + 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; + CK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking)); + x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); + qkv = dalloc(T * g.ssm_conv_channels); hc = dalloc(T * g.ssm_conv_channels); z = dalloc(T * g.ssm_value_dim); + alpha = dalloc(T * g.ssm_v_heads); beta = dalloc(T * g.ssm_v_heads); gdn_y = dalloc(T * g.ssm_value_dim); + qg = dalloc(T * 2 * g.n_head * g.head_dim); kx = dalloc(T * g.n_head_kv * g.head_dim); + vx = dalloc(T * g.n_head_kv * g.head_dim); q = dalloc(T * g.n_head * g.head_dim); + gate = dalloc(T * g.n_head * g.head_dim); att = dalloc(T * g.n_head * g.head_dim); + logits_r = dalloc(T * (g.n_expert + 1)); + eparts = dalloc(T * Kp * N); moe_out = dalloc(T * N); + 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); + sgate = dalloc(T); ewts = dalloc(T * Kp); logits = dalloc((size_t) g.n_vocab); + const int max_in = (int) std::max({g.n_embd, g.ssm_value_dim, g.n_head * g.head_dim, g.n_ff_shexp}); + CK(cudaMalloc(&q8, K::native_q8_1_bytes(max_in, 1) * T)); + CK(cudaMalloc(&xq, K::native_q8_1_bytes((int) N, 1) * T)); + x16 = dalloc_t<__half>(T * (size_t) max_in); + if (cublasCreate(&blas) != CUBLAS_STATUS_SUCCESS || cublasSetStream(blas, st) != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: cuBLAS handle failed\n"); + std::exit(1); + } + att_s = dalloc(kAttScoreFloats); + use_mmq = MMQ::built() && std::getenv("STRATA_Q36_NO_MMQ") == nullptr; + for (const Layer& L : m->layers) + use_mmq = use_mmq && MMQ::supported(L.L.gu_type) && MMQ::supported(L.L.d_type) && + MMQ::fits(L.L.gu_type, 2 * g.n_ff) && MMQ::fits(L.L.d_type, g.n_embd); + if (use_mmq) { + const int64_t ne = (int64_t) T * Kp; + mctx = std::make_unique(); + rcnt = dalloc_t((size_t) g.n_expert); + rcur = dalloc_t((size_t) g.n_expert); + rbounds = dalloc_t((size_t) g.n_expert + 1); + rmax = dalloc_t(1); + ident = dalloc_t((size_t) ne); + rinv = dalloc_t((size_t) ne); + CK(cudaDeviceSynchronize()); // ident's cudaMemset (legacy stream) before the iota on the non-blocking stream + MMQ::iota(ident, ne, st); + CK(cudaMalloc(&mq_x, MMQ::q8_bytes(ne, g.n_embd))); + CK(cudaMalloc(&mq_hq, MMQ::q8_bytes(ne, g.n_ff))); + mq_gu = dalloc((size_t) ne * 2 * FF); + mq_h = dalloc((size_t) ne * FF); + } + std::fprintf(stderr, "strata-q36: prompt experts on %s\n", use_mmq ? "MMQ (int8)" : "the native grouped kernels"); + { + std::string gerr; + int64_t big = 0; + for (const Layer& L : m->layers) + 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}) + big = std::max(big, (int64_t) w->n_in * w->n_out); + if (!gemm.init(st, big, gerr)) { + std::fprintf(stderr, "strata-q36: prompt GEMM: %s\n", gerr.c_str()); + std::exit(1); + } + } + CK(cudaMalloc(&escr, K::native_expert_scratch_bytes((int64_t) (T * Kp), (int64_t) FF))); + ids = dalloc_t(T * Kp); + grp_ptr = dalloc_t(std::min(T * Kp, (size_t) g.n_expert) + 1); + grp_start = dalloc_t(std::min(T * Kp, (size_t) g.n_expert) + 1); + n_groups = dalloc_t(1); + ent_dst = dalloc_t(T * Kp); + ent_tok = dalloc_t(T * Kp); + tok = dalloc_t(T); + pos0 = dalloc_t(1); + pick = dalloc_t(1); + amv = dalloc(kArgBlocks); + ami = dalloc_t(kArgBlocks); + CK(cudaHostAlloc((void**) &hpin, 16 * sizeof(int32_t), cudaHostAllocDefault)); + n_chunk = (ctx + kChunkCells - 1) / kChunkCells; + att_rows = (int) (g.n_head * std::min((int64_t) T, 64)); // 64 query tokens per attention batch + pacc = dalloc((size_t) att_rows * n_chunk * g.head_dim); + pm = dalloc((size_t) att_rows * n_chunk); + pl = dalloc((size_t) att_rows * n_chunk); + for (const Layer& L : m->layers) { + if (L.attn) { + conv.push_back(nullptr); + S.push_back(nullptr); + kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + } else { + conv.push_back(dalloc((size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1))); + S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + kc.push_back(nullptr); + vc.push_back(nullptr); + } + } + CK(cudaDeviceSynchronize()); // every legacy-stream cudaMemset of the buffers above is done + size_t fr = 0, tot = 0; + CK(cudaMemGetInfo(&fr, &tot)); + std::fprintf(stderr, "strata-q36: context %d cells, prompt chunk %d, %.2f GiB of VRAM free\n", ctx, tmax, + (double) fr / (1 << 30)); + } + + /// The recurrent state and the cache to a fresh sequence. + void reset() { + const auto& g = m->g; + for (size_t l = 0; l < m->layers.size(); ++l) { + if (conv[l]) CK(cudaMemsetAsync(conv[l], 0, (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * 4, st)); + if (S[l]) CK(cudaMemsetAsync(S[l], 0, (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, st)); + } + CK(cudaStreamSynchronize(st)); + pos = 0; + } + + /// y [T][n_out] = W x [T][n_in] on the native MMVQ, 8 columns per launch. + void mm(const Mat& w, const float* xin, float* out, int T) { + prep(xin, w.n_in, T, q8); + apply(w, q8, out, T); + } + /// 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 + /// cuBLAS's FP32 GEMM (the router and the GDN alpha / beta stay in FP32, as llama.cpp keeps them). + void f32mm(const float* W, const float* xin, float* out, int n_in, int n_out, int T) { + if (T <= kGemmT) { + k_gemv_f32<<>>(W, xin, out, n_in, n_out); + return; + } + const float one = 1.0f, zero = 0.0f; + 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) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: cublasSgemm failed\n"); + std::exit(1); + } + } + + /// A batch above kGemmT tokens (a prompt chunk) runs its projections as GEMMs (prefill::Gemm::native: the GGUF + /// blocks dequantized to FP16, the activations FP16); a decode batch on the native MMVQ (q8_1 activations). + static constexpr int kGemmT = 8; + void prep(const float* xin, int n, int T, void* q) { + if (T > kGemmT) k_to_f16<<>>(xin, x16, (int64_t) n * T); + else quant(xin, n, T, q); + } + void apply(const Mat& w, const void* q, float* out, int T) { + if (T > kGemmT) gemm.native((const uint16_t*) x16, w.type, w.d, out, T, w.n_out, w.n_in); + else mmq(w, q, out, T); + } + /// x [T][n] -> its q8_1 image (T contiguous columns: one vector of T * n), for every matrix that reads x. + void quant(const float* xin, int n, int T, void* q) { K::native_quantize_q8_1(xin, q, n * T, 1, st); } + /// y [T][n_out] = W x from x's q8_1 image, 8 columns per launch. + void mmq(const Mat& w, const void* q, float* out, int T) { + const size_t qb = K::native_q8_1_bytes(w.n_in, 1); + for (int c0 = 0; c0 < T; c0 += 8) { + const int nc = std::min(8, T - c0); + 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); + } + } + + /// T tokens (device `tok`, positions *pos0 .. *pos0 + T - 1) through the model; the logits of the last row when + /// `want_logits`. Every launch is on `st` and reads the positions from the device (graph-capturable for T = 1). + void forward(int T, bool want_logits, bool graph_mode) { + const auto& g = m->g; + const int N = (int) g.n_embd, Kp = (int) m->top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp; + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, D = (int) g.ssm_state_size; + const int C = (int) g.ssm_conv_channels, ZV = (int) g.ssm_value_dim; + const int H = (int) g.n_head, HKV = (int) g.n_head_kv, HD = (int) g.head_dim; + K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok, T, N, x, st); + k_rms<<>>(x, m->layers[0].attn_norm, h, N, m->eps); // later layers: from k_moe_out + for (size_t l = 0; l < m->layers.size(); ++l) { + const Layer& L = m->layers[l]; + if (!L.attn) { + prep(h, N, T, xq); + apply(L.qkv, xq, qkv, T); + apply(L.zg, xq, z, T); + if (T <= kGemmT) { + k_gdn_ab<<>>(L.alpha, L.beta, h, L.dt, L.ssm_a, alpha, beta, + N, HV); + } else { + f32mm(L.alpha, h, alpha, N, HV, T); + f32mm(L.beta, h, beta, N, HV, T); + k_gdn_gb<<>>(alpha, L.dt, L.ssm_a, beta, HV, T); + } + if (T == 1) { // decode: Strata's fused kernels + K::fused_gdn_conv_l2(conv[l], qkv, L.conv, hc, C, 2 * HK, m->eps, st); + K::fused_gdn_step_norm_silu(S[l], hc, hc + HK * D, hc + 2 * HK * D, alpha, beta, z, L.ssm_norm, + m->eps, gdn_y, HK, HV, st); + } else { // a prompt chunk: the same arithmetic, every token in one launch each + k_conv_seq<<>>(conv[l], qkv, L.conv, hc, C, 2 * HK, m->eps, T); + k_gdn_seq<<>>(S[l], hc, C, alpha, beta, z, L.ssm_norm, m->eps, gdn_y, HK, + HV, T); + } + mm(L.ssm_out, gdn_y, y, T); + } else { + prep(h, N, T, xq); + apply(L.wq, xq, qg, T); + apply(L.wk, xq, kx, T); + apply(L.wv, xq, vx, T); + k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, kc[l], vc[l], + H, HKV, HD, m->n_rot, pos0, ctx, m->rope_base, m->eps); + // the query rows in batches that fit the partials; the chunk grid covers every cell a row of this + // batch can see (graph mode: the whole context, past-the-end chunks return at once) + if (T > kGemmT) { + // a prompt chunk: scores = Q K^T and out = P V as FP32 GEMMs per KV head (its query heads one + // strided batch over the shared K / V), the causal softmax in between; the queries in slices + // whose scores fit att_s + const int P = (int) pos + T; + const int ldp = (P + 3) / 4 * 4; + const int tq = (int) std::max(1, std::min(T, (int64_t) (kAttScoreFloats / ((size_t) H * ldp)))); + const int G = H / HKV; + const float one = 1.0f, zero = 0.0f; + for (int t0 = 0; t0 < T; t0 += tq) { + const int nt = std::min(tq, T - t0); + for (int kvh = 0; kvh < HKV; ++kvh) { + const float* Kh = kc[l] + (size_t) kvh * ctx * HD; + const float* Qh = q + ((size_t) t0 * H + kvh * G) * HD; + float* Sh = att_s + (size_t) kvh * G * nt * ldp; + if (cublasSgemmStridedBatched(blas, CUBLAS_OP_T, CUBLAS_OP_N, P, nt, HD, &one, Kh, HD, 0, Qh, + H * HD, HD, &zero, Sh, ldp, (long long) nt * ldp, G) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: attention scores GEMM failed\n"); + std::exit(1); + } + } + k_attn_softmax<<>>(att_s, ldp, nt, P, (int) pos + t0, + 1.0f / sqrtf((float) HD)); + for (int kvh = 0; kvh < HKV; ++kvh) { + const float* Vh = vc[l] + (size_t) kvh * ctx * HD; + const float* Sh = att_s + (size_t) kvh * G * nt * ldp; + float* Oh = att + ((size_t) t0 * H + kvh * G) * HD; + if (cublasSgemmStridedBatched(blas, CUBLAS_OP_N, CUBLAS_OP_N, HD, nt, P, &one, Vh, HD, 0, Sh, + ldp, (long long) nt * ldp, &zero, Oh, H * HD, HD, G) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: attention values GEMM failed\n"); + std::exit(1); + } + } + } + k_gate_mul<<>>(att, gate, (int64_t) T * H * HD); + } else { + const int rows_per = att_rows / H; + for (int t0 = 0; t0 < T; t0 += rows_per) { + const int nt = std::min(rows_per, T - t0); + const int nc = graph_mode ? n_chunk + : (int) std::min(n_chunk, (pos + t0 + nt + kChunkCells - 1) / kChunkCells); + k_attn_part<<>>(q, kc[l], vc[l], pos0, t0, H, HKV, ctx, + 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl); + k_attn_merge<<>>(pacc, pm, pl, gate, pos0, t0, H, n_chunk, att); + } + } + mm(L.wo, att, y, T); + } + k_add_rms<<>>(x, y, L.post_norm, h, N, m->eps); + // routed experts (one token: the router and the shared expert's gate in one product, the gate its last row) + const bool one = T == 1; + if (one) f32mm(L.router_ext, h, logits_r, N, (int) g.n_expert + 1, 1); + else f32mm(L.router, h, logits_r, N, (int) g.n_expert, T); + K::native_router_topk(logits_r, ids, ewts, (int) g.n_expert, Kp, T, st); + const int64_t n_ent = (int64_t) T * Kp; + const int32_t* prow = nullptr; + if (T > kGemmT && use_mmq) { + // a prompt chunk: the experts on llama.cpp's MMQ (int8, the weights read once per expert): the entries + // sorted by expert on the device, gate+up as one [2 FF] product per expert, SwiGLU, down into the + // per-slot rows the combine reads + const int ne = (int) g.n_expert; + CK(cudaMemsetAsync(rcnt, 0, (size_t) ne * 4, st)); + k_route_count<<>>(ids, (int) n_ent, rcnt); + k_route_scan<<<1, 32, 0, st>>>(rcnt, ne, rbounds, rcur, rmax); + k_route_scatter<<>>(ids, (int) n_ent, Kp, rcur, ent_dst, ent_tok, rinv); + CK(cudaMemcpyAsync(hpin + 3, rmax, 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + const int64_t maxr = hpin[3]; + MMQ::quantize(h, ent_tok, mq_x, L.L.gu_type, N, N, n_ent, st); + { + MMQ::Product gu; + gu.w = L.blobs; gu.type = L.L.gu_type; gu.w_rows = 2 * FF; gu.w_cols = N; gu.expert_bytes = L.stride; + gu.n = ne; gu.xq = mq_x; gu.bounds = rbounds; gu.ids = ident; gu.total_rows = n_ent; gu.max_rows = maxr; + gu.dst = mq_gu; gu.ld_dst = 2 * FF; + mctx->run(gu, st); + MMQ::swiglu(mq_gu, mq_h, n_ent, FF, false, st); + MMQ::quantize(mq_h, nullptr, mq_hq, L.L.d_type, FF, FF, n_ent, st); + MMQ::Product dn; + dn.w = L.blobs + L.L.down_off; dn.type = L.L.d_type; dn.w_rows = N; dn.w_cols = FF; + dn.expert_bytes = L.stride; dn.n = ne; dn.xq = mq_hq; dn.bounds = rbounds; dn.ids = ident; + dn.total_rows = n_ent; dn.max_rows = maxr; dn.dst = eparts; dn.ld_dst = N; + mctx->run(dn, st); + } + prow = rinv; // the down rows stay in sorted order; the combine reads them through entry -> row + } else { + k_group<<<1, kThreads, 0, st>>>(ids, (int) n_ent, Kp, (int) g.n_expert, L.blobs, L.stride, grp_ptr, + grp_start, n_groups, ent_dst, ent_tok); + quant(h, N, T, xq); // the experts' and the shared expert's input + K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, + std::min(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); + } + // the shared expert, scaled by sigmoid(w . h) + if (T > kGemmT) k_to_f16<<>>(h, x16, (int64_t) N * T); + apply(L.sh_gate, xq, sg, T); + apply(L.sh_up, xq, su, T); + if (T <= kGemmT) { // SwiGLU and its q8_1 image in one launch + K::native_swiglu_quantize_q8_1(sg, su, q8, FS, T, st); + mmq(L.sh_down, q8, sy, T); + } else { + k_swiglu<<>>(sg, su, shh, (int64_t) T * FS); + mm(L.sh_down, shh, sy, T); + } + if (!one) f32mm(L.sh_gate_inp, h, sgate, N, 1, T); + // the combine, the shared expert's gate, the residual add and the next layer's norm in one launch + const float* wn = l + 1 < m->layers.size() ? m->layers[l + 1].attn_norm : nullptr; + k_moe_out<<>>(x, eparts, prow, ewts, Kp, sy, one ? logits_r + g.n_expert : sgate, 1, wn, h, N, + m->eps); + (void) FF; + (void) moe_out; + } + if (want_logits) { + const float* xl = x + (size_t) (T - 1) * N; + k_rms<<<1, kThreads, 0, st>>>(xl, m->out_norm, h, N, m->eps); + mm(m->head, h, logits, 1); + k_argmax<<>>(logits, (int) g.n_vocab, pick, amv, ami, false); + k_argmax<<<1, kThreads, 0, st>>>(logits, kArgBlocks, pick, amv, ami, true); + } + } + + /// The tokens at the current position: a prompt in chunks (eager), one token from the decode graph. The last + /// token's logits stay in `logits` (and its greedy pick in `pick`). `on_chunk(done)` after each chunk. + template void process(const int32_t* toks, int64_t n, F on_chunk) { + if (n == 1 && use_graph) { + CK(cudaStreamSynchronize(st)); // the pinned staging is free again + hpin[0] = toks[0]; + hpin[1] = (int32_t) pos; + CK(cudaMemcpyAsync(tok, hpin, 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + if (!g1) { + cudaGraph_t graph = nullptr; + CK(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal)); + forward(1, true, true); + CK(cudaStreamEndCapture(st, &graph)); + CK(cudaGraphInstantiate(&g1, graph, 0)); + CK(cudaGraphDestroy(graph)); + } + CK(cudaGraphLaunch(g1, st)); + pos += 1; + on_chunk(1); + return; + } + for (int64_t i = 0; i < n; i += tmax) { + const int T = (int) std::min(tmax, n - i); + CK(cudaStreamSynchronize(st)); + hpin[1] = (int32_t) pos; + CK(cudaMemcpyAsync(tok, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + forward(T, i + T == n, false); + pos += T; + CK(cudaStreamSynchronize(st)); + on_chunk(i + T); + } + } + + int greedy() { + CK(cudaMemcpyAsync(hpin + 2, pick, 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + return hpin[2]; + } + void host_logits(std::vector& out) { + out.resize((size_t) m->g.n_vocab); + CK(cudaMemcpyAsync(out.data(), logits, out.size() * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + } +}; + +// ------------------------------------------------------------------------------------------------ sampling +struct Sampling { + float temperature = 0.f, top_p = 1.f, min_p = 0.f, repeat = 1.f, freq = 0.f, present = 0.f; + int top_k = 20, last_n = 0; + unsigned long long seed = 0; + bool needs_logits() const { return temperature > 0.f || repeat != 1.f || freq != 0.f || present != 0.f; } +}; + +int sample(std::vector& lg, const Sampling& s, const std::vector& hist, std::mt19937_64& rng) { + if (s.last_n != 0 && (s.repeat != 1.f || s.freq != 0.f || s.present != 0.f)) { + std::map cnt; + const size_t from = s.last_n < 0 || (size_t) s.last_n >= hist.size() ? 0 : hist.size() - (size_t) s.last_n; + for (size_t i = from; i < hist.size(); ++i) ++cnt[hist[i]]; + for (const auto& [id, c] : cnt) { + float& v = lg[(size_t) id]; + if (s.repeat != 1.f) v = v > 0 ? v / s.repeat : v * s.repeat; + v -= (float) c * s.freq + s.present; + } + } + if (s.temperature <= 0.f) return (int) (std::max_element(lg.begin(), lg.end()) - lg.begin()); + const int kk = std::max(1, std::min(s.top_k > 0 ? s.top_k : 64, (int) lg.size())); + std::vector idx(lg.size()); + for (size_t i = 0; i < idx.size(); ++i) idx[i] = (int) i; + std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int a, int b) { return lg[a] > lg[b]; }); + idx.resize((size_t) kk); + std::vector p(idx.size()); + const double mx = lg[(size_t) idx[0]]; + double sum = 0; + for (size_t i = 0; i < idx.size(); ++i) sum += (p[i] = std::exp((lg[(size_t) idx[i]] - mx) / s.temperature)); + size_t keep = idx.size(); + double cum = 0; + for (size_t i = 0; i < idx.size(); ++i) { + if (p[i] / sum < s.min_p * (p[0] / sum)) { keep = i; break; } + cum += p[i] / sum; + if (cum >= s.top_p) { keep = i + 1; break; } + } + keep = std::max(1, keep); + double tot = 0; + for (size_t i = 0; i < keep; ++i) tot += p[i]; + std::uniform_real_distribution u(0.0, tot); + double r = u(rng); + for (size_t i = 0; i < keep; ++i) { + if ((r -= p[i]) <= 0) return idx[i]; + } + return idx[keep - 1]; +} + +std::vector parse_ids(const char* s) { + std::vector v; + while (*s) { + while (*s == ',' || *s == ' ') ++s; + if (!*s) break; + char* e = nullptr; + const long x = std::strtol(s, &e, 10); + if (e == s) break; + v.push_back((int32_t) x); + s = e; + } + return v; +} + +bool is_eos(int t) { return t == 248044 || t == 248046; } + +// ------------------------------------------------------------------------------------------------ serve +int serve(Engine& E) { + std::printf("READY %d stop\n", E.ctx); + std::fflush(stdout); + std::mutex mu; + std::condition_variable cv; + std::deque lines; + bool eof = false; + std::atomic stop{false}; + std::thread reader([&] { + std::string l; + while (std::getline(std::cin, l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop.store(true); continue; } + std::lock_guard lk(mu); + lines.push_back(l); + cv.notify_one(); + } + std::lock_guard lk(mu); + eof = true; + cv.notify_one(); + }); + reader.detach(); + std::vector live; // the tokens whose state the engine holds (cell i = live[i]) + std::vector lg; + for (;;) { + std::string line; + { + std::unique_lock lk(mu); + cv.wait(lk, [&] { return eof || !lines.empty(); }); + if (lines.empty()) return 0; + line = lines.front(); + lines.pop_front(); + } + if (line.empty()) continue; + if (line.rfind("GEN ", 0) != 0) { + std::printf("ERR expected: GEN [key=value ...] \n"); + std::fflush(stdout); + continue; + } + char* p = nullptr; + const long long max_new = std::strtoll(line.c_str() + 4, &p, 10); + Sampling smp; + for (;;) { + while (*p == ' ') ++p; + const char* st0 = p; + while (*p && *p != ' ') ++p; + const std::string tk(st0, (size_t) (p - st0)); + const size_t eq = tk.find('='); + if (tk.empty() || eq == std::string::npos) { p = const_cast(st0); break; } + const std::string key = tk.substr(0, eq); + const char* v = tk.c_str() + eq + 1; + if (key == "temperature") smp.temperature = std::strtof(v, nullptr); + else if (key == "top_p") smp.top_p = std::strtof(v, nullptr); + else if (key == "top_k") smp.top_k = std::atoi(v); + else if (key == "min_p") smp.min_p = std::strtof(v, nullptr); + else if (key == "penalty_last_n") smp.last_n = std::atoi(v); + else if (key == "penalty_repeat") smp.repeat = std::strtof(v, nullptr); + else if (key == "penalty_freq") smp.freq = std::strtof(v, nullptr); + else if (key == "penalty_present") smp.present = std::strtof(v, nullptr); + else if (key == "seed") smp.seed = std::strtoull(v, nullptr, 10); + } + const std::vector ids = parse_ids(p); + if (max_new < 1 || ids.empty()) { + std::printf("ERR bad request: max_new or the ids\n"); + std::fflush(stdout); + continue; + } + if ((int64_t) ids.size() + max_new > E.ctx) { + std::printf("ERR prompt (%zu tokens) + max_new (%lld) exceeds the context (%d)\n", ids.size(), max_new, E.ctx); + std::fflush(stdout); + continue; + } + bool bad = false; + for (int32_t t : ids) bad |= t < 0 || t >= (int32_t) E.m->g.n_vocab; + if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); continue; } + stop.store(false); + // the held state continues when the request extends it (the recurrent state cannot step back) + size_t reuse = 0; + if (live.size() < ids.size() && std::equal(live.begin(), live.end(), ids.begin())) reuse = live.size(); + else { + E.reset(); + live.clear(); + } + const auto t0 = Clock::now(); + const int64_t fresh = (int64_t) (ids.size() - reuse); + E.process(ids.data() + reuse, fresh, [&](int64_t done) { + std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0), + (double) done / std::max(1e-9, ms_since(t0) / 1000.0)); + std::fflush(stdout); + }); + live.insert(live.end(), ids.begin() + (long) reuse, ids.end()); + const double prompt_ms = ms_since(t0); + std::mt19937_64 rng(smp.seed); + std::vector hist = ids; + const auto d0 = Clock::now(); + long long produced = 0; + const char* finish = "length"; + for (;;) { + int nx; + if (smp.needs_logits()) { + E.host_logits(lg); + nx = sample(lg, smp, hist, rng); + } else { + nx = E.greedy(); + } + std::printf("T %d\n", nx); + std::fflush(stdout); + ++produced; + hist.push_back(nx); + if (is_eos(nx)) { finish = "stop"; break; } + if (produced >= max_new) break; + if (stop.load()) { finish = "cancel"; break; } + if (E.pos + 1 > E.ctx) break; + const int32_t one = nx; + E.process(&one, 1, [](int64_t) {}); + live.push_back(nx); + } + const double decode_ms = ms_since(d0); + 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, + decode_ms, finish, reuse, (long long) fresh); + std::fflush(stdout); + } +} + +} // namespace + +int main(int argc, char** argv) { + std::string model, tokens, force, dump_full; + int ctx = 32768, chunk = 512, n_gen = 64, bench_pp = 0, bench_tg = 0; + bool serve_mode = false, graph = true; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { std::fprintf(stderr, "strata-q36: %s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + if (a == "--model" || a == "--native") model = next(); + else if (a == "--serve") serve_mode = true; + else if (a == "--max-context" || a == "--ctx") ctx = std::atoi(next().c_str()); + else if (a == "--chunk" || a == "--prefill") { const std::string v = next(); chunk = v == "auto" ? 512 : std::atoi(v.c_str()); } + else if (a == "--tokens") tokens = next(); + else if (a == "--n") n_gen = std::atoi(next().c_str()); + else if (a == "--force") force = next(); + else if (a == "--dump-full-logits") dump_full = next(); + else if (a == "--bench-pp") bench_pp = std::atoi(next().c_str()); + else if (a == "--bench-tg") bench_tg = std::atoi(next().c_str()); + else if (a == "--no-graph") graph = false; + else { + std::fprintf(stderr, + "usage: strata-q36 --model GGUF [--max-context 32768] [--chunk 512] [--no-graph]\n" + " (--serve | --tokens IDS [--n 64] [--force IDS] [--dump-full-logits F] | --bench-pp N " + "--bench-tg N)\n"); + return 2; + } + } + if (model.empty()) { std::fprintf(stderr, "strata-q36: --model is required\n"); return 2; } +#if !defined(_WIN32) + setenv("STRATA_Q8_PACKED", "1", 0); // the packed Q8_0 decode copy unless STRATA_Q8_PACKED is set otherwise +#endif + if (chunk < 1 || chunk > 4096 || ctx < 256) { std::fprintf(stderr, "strata-q36: bad --chunk / --max-context\n"); return 2; } + Model m; + std::string err; + try { + if (!load(model, m, err)) { std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); return 1; } + } catch (const std::exception& e) { + std::fprintf(stderr, "strata-q36: %s\n", e.what()); + return 1; + } + Engine E; + E.use_graph = graph; + E.init(m, ctx, chunk); + E.reset(); + if (serve_mode) return serve(E); + if (bench_pp > 0 || bench_tg > 0) { + // llama-bench's shapes: a prompt of bench_pp tokens from a fresh state, then bench_tg tokens one at a time + std::vector toks((size_t) std::max(bench_pp, 1)); + std::mt19937 rng(1234); + for (auto& t : toks) t = (int32_t) (rng() % 200000u); + for (int rep = 0; rep < 3; ++rep) { + E.reset(); + const auto t0 = Clock::now(); + E.process(toks.data(), (int64_t) toks.size(), [](int64_t) {}); + CK(cudaStreamSynchronize(E.st)); + const double pp_ms = ms_since(t0); + const auto t1 = Clock::now(); + int nx = E.greedy(); + for (int i = 0; i < bench_tg; ++i) { + const int32_t one = nx; + E.process(&one, 1, [](int64_t) {}); + nx = E.greedy(); + } + const double tg_ms = ms_since(t1); + std::printf("bench %d: pp%d %.1f tok/s, tg%d %.1f tok/s\n", rep, (int) toks.size(), + (double) toks.size() / (pp_ms / 1000.0), bench_tg, + bench_tg > 0 ? (double) bench_tg / (tg_ms / 1000.0) : 0.0); + std::fflush(stdout); + } + return 0; + } + const std::vector prompt = parse_ids(tokens.c_str()), forced = parse_ids(force.c_str()); + if (prompt.empty()) { std::fprintf(stderr, "strata-q36: --tokens, --serve or --bench-pp is required\n"); return 2; } + if (!forced.empty()) n_gen = (int) forced.size() + 1; + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + std::vector lg; + std::vector gen; + const auto t0 = Clock::now(); + E.process(prompt.data(), (int64_t) prompt.size(), [](int64_t) {}); + const double pp_ms = ms_since(t0); + const auto t1 = Clock::now(); + for (int i = 0; i < n_gen; ++i) { + const int a = E.greedy(); + gen.push_back(a); + if (ff) { + E.host_logits(lg); + std::fwrite(lg.data(), 4, lg.size(), ff); + } + if (i + 1 == n_gen) break; + const int32_t nx = i < (int) forced.size() ? forced[(size_t) i] : a; + E.process(&nx, 1, [](int64_t) {}); + } + if (ff) std::fclose(ff); + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + std::fprintf(stderr, "strata-q36: prompt %zu tokens in %.1f ms (%.1f tok/s), %zu generated in %.1f ms (%.1f tok/s)\n", + prompt.size(), pp_ms, prompt.size() / (pp_ms / 1000.0), gen.size(), ms_since(t1), + gen.size() / (ms_since(t1) / 1000.0)); + return 0; +}