diff --git a/CMakeLists.txt b/CMakeLists.txt index 566349ce..e0a3f170 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -609,6 +609,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) + # NEW-MODELS-PLAN.md T1: Qwen3.6-35B-A3B's reference path (one GPU, the model resident, plain kernels), checked + # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet + 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_warnings ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_HIP) enable_testing() set(_strata_hip_tests) diff --git a/src/qwen35/q36ref.cu b/src/qwen35/q36ref.cu new file mode 100644 index 00000000..3cfbf95b --- /dev/null +++ b/src/qwen35/q36ref.cu @@ -0,0 +1,765 @@ +// src/qwen35/q36ref.cu - NEW-MODELS-PLAN.md phase T1: the reference path for Qwen3.6-35B-A3B (GGUF architecture +// qwen35moe), exactness first. One GPU, the whole model resident in VRAM (UD-Q4_K_XL: 21.3 GiB on a 32 GB card), +// one token at a time (the prompt too), fp32 activations, every weight read in its GGUF form by plain kernels. +// No expert cache, no MTP, no graphs: this is the thing the optimised path is checked against, and itself checked +// against llama.cpp (per-layer hidden states and greedy tokens, tools/qwen35/). +// +// The forward pass, as llama.cpp's src/models/qwen35moe.cpp builds it: +// x = token_embd[tok] +// per layer l < 40: h = rms(x) * attn_norm +// GDN (l % 4 != 3): qkv = W_qkv h (8192), z = W_gate h (4096), b = sigmoid(W_beta h), a = W_alpha h (32 each) +// c = silu(causal conv4(qkv)); q, k = l2norm(c[0:2048]), l2norm(c[2048:4096]) (16 heads), v = c[4096:] (32) +// g = softplus(a + dt_bias) * ssm_a; per V head h (K head h % 16): S = S * exp(g_h); +// d = (v - S k) * b_h; S += d k^T; o = S q / sqrt(128); o = rms(o) * ssm_norm * silu(z_h) +// y = W_ssm_out o +// attention (l % 4 == 3): attn_q -> per head [q 256 | gate 256]; q, k = rms(.) * q_norm/k_norm; NEOX RoPE over the +// first 64 dims (base 1e7; text positions: the M-RoPE sections all carry the same position); GQA 16 / 2; +// y = W_o (softmax(q k^T / 16) v * sigmoid(gate)) +// x += y; h2 = rms(x) * post_attention_norm +// MoE: p = softmax(W_router h2) over 256, top-8, renormalised; sum_e p_e W_down_e (silu(W_gate_e h2) * W_up_e h2) +// + sigmoid(w_shexp_gate . h2) * W_down_s (silu(W_gate_s h2) * W_up_s h2); x += moe +// logits = W_output (rms(x) * output_norm) +// +// Usage: strata-q36ref --model Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --tokens 248045,846,198,... [--n 64] [--ctx 4096] +// [--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--force IDS] [--dump-full-logits F] +// prints the greedy ids ("gen: id id ..."); --dump-layers writes every processed position's 40 layer outputs (f32, +// [pos][layer][2048]); --dump-logits writes each greedy step's top-2 (id, logit) pairs for the near-tie report; +// --force feeds the given continuation instead of the greedy ids and --dump-full-logits writes every step's +// logits (f32, [step][vocab]) for the teacher-forced KL check (tools/qwen35/kl.py). +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "q36ref: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \ + std::exit(1); \ + } \ + } while (0) + +// ------------------------------------------------------------------------------------------------ dequantisation +// ggml's block formats, 32 values at a time ("chunk" c of a row). The formulas are ggml-quants.c's dequantize_row_*. +enum : int { T_F32 = 0, T_F16 = 1, T_Q8_0 = 8, T_Q4_K = 12, T_Q5_K = 13, T_Q6_K = 14, T_BF16 = 30 }; + +__device__ __forceinline__ float h2f(uint16_t h) { + const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff; + if (e == 0) { + const float v = ldexpf((float) m, -24); + return s ? -v : v; + } + const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13)); + return __uint_as_float(f); +} +__device__ __forceinline__ uint16_t ld16(const uint8_t* p) { return (uint16_t) (p[0] | (p[1] << 8)); } + +__device__ __forceinline__ void scale_min_k4(int j, const uint8_t* q, int& d, int& m) { + if (j < 4) { + d = q[j] & 63; + m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); + } +} + +/// The 32 values of chunk `c` of one row (`row` = the row's first byte). +template __device__ void deq32(const uint8_t* row, int c, float* out) { + if constexpr (T == T_F32) { + const float* r = (const float*) row + 32 * c; + for (int l = 0; l < 32; ++l) out[l] = r[l]; + } else if constexpr (T == T_F16) { + const uint8_t* r = row + 64 * c; + for (int l = 0; l < 32; ++l) out[l] = h2f(ld16(r + 2 * l)); + } else if constexpr (T == T_BF16) { + const uint8_t* r = row + 64 * c; + for (int l = 0; l < 32; ++l) out[l] = __uint_as_float((uint32_t) ld16(r + 2 * l) << 16); + } else if constexpr (T == T_Q8_0) { + const uint8_t* b = row + 34 * c; + const float d = h2f(ld16(b)); + const int8_t* q = (const int8_t*) (b + 2); + for (int l = 0; l < 32; ++l) out[l] = d * (float) q[l]; + } else if constexpr (T == T_Q4_K) { + const uint8_t* b = row + 144 * (c >> 3); + const int j = c & 7; + const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2)); + int sc, m; + scale_min_k4(j, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* qs = b + 16 + 32 * (j >> 1); + for (int l = 0; l < 32; ++l) out[l] = d1 * (float) ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) - m1; + } else if constexpr (T == T_Q5_K) { + const uint8_t* b = row + 176 * (c >> 3); + const int j = c & 7; + const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2)); + int sc, m; + scale_min_k4(j, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* qh = b + 16; + const uint8_t* qs = b + 48 + 32 * (j >> 1); + for (int l = 0; l < 32; ++l) { + const int q = ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) + ((qh[l] >> j) & 1 ? 16 : 0); + out[l] = d1 * (float) q - m1; + } + } else if constexpr (T == T_Q6_K) { + const uint8_t* b = row + 210 * (c >> 3); + const int j = c & 7, n = j >> 2, r = j & 3; + const uint8_t* ql = b + 64 * n; + const uint8_t* qh = b + 128 + 32 * n; + const int8_t* sc = (const int8_t*) (b + 192) + 8 * n; + const float d = h2f(ld16(b + 208)); + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + int q; + if (r == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4); + else if (r == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4); + else if (r == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4); + else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4); + out[l] = d * (float) sc[is + 2 * r] * (float) (q - 32); + } + } +} + +__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; +} + +constexpr int kThreads = 128; + +/// y[sel][o] = W_e[o] . x[sel] for row o (grid.x), selection `sel` (grid.y): expert ids[sel] (or 0 without ids), +/// x of selection sel at x + sel * x_stride. `beta` != 0 adds into y. +template +__global__ void k_gemv(const uint8_t* W, size_t row_bytes, size_t expert_bytes, const int* ids, int n_in, const float* x, + size_t x_stride, float* y, int n_out) { + __shared__ float sh[kThreads]; + const int o = blockIdx.x, sel = blockIdx.y; + const int e = ids ? ids[sel] : 0; + const uint8_t* row = W + (size_t) e * expert_bytes + (size_t) o * row_bytes; + const float* xs = x + (size_t) sel * x_stride; + float acc = 0.f, v[32]; + for (int c = threadIdx.x; c < n_in / 32; c += blockDim.x) { + deq32(row, c, v); + const float* xc = xs + 32 * c; + for (int l = 0; l < 32; ++l) acc += v[l] * xc[l]; + } + acc = block_sum(acc, sh); + if (threadIdx.x == 0) y[(size_t) sel * n_out + o] = acc; +} + +template __global__ void k_row(const uint8_t* W, size_t row_bytes, int row, int n, float* out) { + const uint8_t* r = W + (size_t) row * row_bytes; + for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < n / 32; c += gridDim.x * blockDim.x) deq32(r, c, out + 32 * c); +} + +/// y = x / sqrt(mean(x^2) + eps) * w, per group of n (grid = groups); w (length n) may be null. +__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) { + __shared__ float sh[kThreads]; + const float* xg = x + (size_t) blockIdx.x * n; + float* yg = y + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xg[i] * xg[i]; + s = block_sum(s, sh); + const float r = 1.0f / sqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) yg[i] = xg[i] * r * (w ? w[i] : 1.0f); +} + +__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)); } + +/// The causal 4-tap conv over the 8192 qkv channels with its 3-input state, then SiLU; the state moves by one. +__global__ void k_conv(const float* qkv, float* state, const float* w, float* out, int C, int K) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float acc = 0.f; + for (int k = 0; k < K - 1; ++k) acc += state[(size_t) k * C + c] * w[(size_t) c * K + k]; + acc += qkv[c] * w[(size_t) c * K + K - 1]; + for (int k = 0; k < K - 2; ++k) state[(size_t) k * C + c] = state[(size_t) (k + 1) * C + c]; + state[(size_t) (K - 2) * C + c] = qkv[c]; + out[c] = silu(acc); +} + +/// One gated delta-rule step per V head (grid = HV, block = D = 128): S[i][j] row i owned by thread i. +__global__ void k_gdn(const float* conv, const float* alpha, const float* dt_bias, const float* ssm_a, + const float* beta_raw, float* S, float* out, int HK, int /*HV: the grid*/, int D, float eps) { + extern __shared__ float sm[]; + float* q = sm; + float* k = sm + D; + float* red = sm + 2 * D; + const int h = blockIdx.x, kh = h % HK, i = threadIdx.x; + const float qi = conv[kh * D + i], ki = conv[HK * D + kh * D + i], vi = conv[2 * HK * D + h * D + i]; + const float qn = block_sum(qi * qi, red), kn = block_sum(ki * ki, red); + q[i] = qi / sqrtf(qn + eps) / sqrtf((float) D); + k[i] = ki / sqrtf(kn + eps); + __syncthreads(); + const float g = expf(softplus(alpha[h] + dt_bias[h]) * ssm_a[h]); + const float b = sigm(beta_raw[h]); + float* Si = S + ((size_t) h * D + i) * D; + float sk = 0.f; + for (int j = 0; j < D; ++j) { + Si[j] *= g; + sk += Si[j] * k[j]; + } + const float d = (vi - sk) * b; + float o = 0.f; + for (int j = 0; j < D; ++j) { + Si[j] += d * k[j]; + o += Si[j] * q[j]; + } + out[h * D + i] = o; +} + +/// o = rms(o) * w * silu(z), per V head (grid = HV, block = D). +__global__ void k_gated_norm(float* o, const float* w, const float* z, int D, float eps) { + __shared__ float sh[kThreads]; + float* oh = o + (size_t) blockIdx.x * D; + const float v = oh[threadIdx.x]; + const float s = block_sum(v * v, sh); + oh[threadIdx.x] = v / sqrtf(s / (float) D + eps) * w[threadIdx.x] * silu(z[blockIdx.x * D + threadIdx.x]); +} + +/// The attention layer's per-token preparation: q (from the [q | gate] pairs) and k RMS-normed per head with their +/// weights, NEOX RoPE over the first n_rot dims, k and v appended to the cache at `pos`, the gate kept. +__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: the grid*/, int D, int n_rot, int pos, + int ctx, float base, float eps) { + __shared__ float sh[kThreads]; + __shared__ float buf[512]; + const int head = blockIdx.x; // 0..H-1: query heads, H..H+HKV-1: key heads + const bool isq = head < H; + const float* src = isq ? qg + (size_t) head * 2 * D : kx + (size_t) (head - H) * D; + float s = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) s += src[i] * src[i]; + s = block_sum(s, sh); + const float r = 1.0f / sqrtf(s / (float) D + eps); + for (int i = threadIdx.x; i < D; i += blockDim.x) buf[i] = src[i] * r * (isq ? qw[i] : kw[i]); + __syncthreads(); + float* dst = isq ? q + (size_t) head * D : kc + ((size_t) (head - H) * ctx + pos) * D; + const int half = n_rot / 2; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float v = buf[i]; + 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); + const float cs = cosf(theta), sn = sinf(theta); + v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; + } + dst[i] = v; + } + if (isq) + for (int i = threadIdx.x; i < D; i += blockDim.x) gate[(size_t) head * D + i] = qg[(size_t) head * 2 * D + D + i]; + else + for (int i = threadIdx.x; i < D; i += blockDim.x) + vc[((size_t) (head - H) * ctx + pos) * D + i] = vx[(size_t) (head - H) * D + i]; +} + +/// softmax(q k^T * scale) v for one query head per block (GQA: KV head = head / (H / HKV)), times sigmoid(gate). +__global__ void k_attn(const float* q, const float* kc, const float* vc, const float* gate, float* out, int H, int HKV, + int D, int n_pos, int ctx, float scale) { + extern __shared__ float sc[]; + __shared__ float sh[kThreads]; + const int h = blockIdx.x, kvh = h / (H / HKV); + const float* qh = q + (size_t) h * D; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) { + const float* kp = kc + ((size_t) kvh * ctx + p) * D; + float s = 0.f; + for (int i = 0; i < D; ++i) s += qh[i] * kp[i]; + sc[p] = s * scale; + } + __syncthreads(); + float mx = -INFINITY; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) mx = fmaxf(mx, sc[p]); + sh[threadIdx.x] = mx; + __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(); + } + mx = sh[0]; + __syncthreads(); + float sum = 0.f; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) { + sc[p] = expf(sc[p] - mx); + sum += sc[p]; + } + sum = block_sum(sum, sh); + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float acc = 0.f; + for (int p = 0; p < n_pos; ++p) acc += sc[p] * vc[((size_t) kvh * ctx + p) * D + i]; + out[(size_t) h * D + i] = acc / sum * sigm(gate[(size_t) h * D + i]); + } +} + +__global__ void k_swiglu(const float* g, const float* u, float* h, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) h[i] = silu(g[i]) * u[i]; +} +__global__ void k_add(float* x, const float* y, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} +/// x += sum_s w[s] * y[s] (the routed experts), + sigmoid(gs) * ys (the shared expert) +__global__ void k_moe_sum(float* x, const float* y, const float* w, int k, const float* ys, const float* gs, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float acc = 0.f; + for (int s = 0; s < k; ++s) acc += w[s] * y[(size_t) s * n + i]; + x[i] += acc + sigm(gs[0]) * ys[i]; +} + +// ------------------------------------------------------------------------------------------------ the model +struct Tensor { + const uint8_t* d = nullptr; // device + int type = -1; + std::vector shape; + size_t row_bytes = 0; +}; + +size_t row_bytes_of(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; +} + +template +void gemv_t(const Tensor& w, size_t expert_bytes, const int* ids, int n_sel, const float* x, size_t x_stride, float* y) { + const int n_in = (int) w.shape[0], n_out = (int) w.shape[1]; + k_gemv<<>>(w.d, w.row_bytes, expert_bytes, ids, n_in, x, x_stride, y, n_out); +} + +/// llama.cpp's GPU matmuls on quantized weights (MMVQ for one token, MMQ for a batch) read the activations as q8_1: +/// per 32 values d = amax / 127, q = round(x / d). --act q8 (the default) gives this path the same rounding, so +/// its numbers follow llama.cpp's instead of drifting from them by the activation rounding; --act f32 reads them as +/// they are. `x` (n_sel vectors of n, `stride` apart) -> `out` (packed, n apart). +__global__ void k_act_q8(const float* x, size_t stride, int n, float* out) { + const int sel = blockIdx.y, blk = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, l = threadIdx.x % 32; + if (blk * 32 >= n) return; + const float v = x[(size_t) sel * stride + blk * 32 + l]; + __shared__ float am[kThreads]; + am[threadIdx.x] = fabsf(v); + __syncthreads(); + const int base = threadIdx.x - l; + float amax = 0.f; + for (int i = 0; i < 32; ++i) amax = fmaxf(amax, am[base + i]); + const float d = amax / 127.0f; + const float q = amax == 0.0f ? 0.0f : roundf(v / d); + out[(size_t) sel * n + blk * 32 + l] = q * d; +} + +bool g_act_q8 = true; +float* g_act_buf = nullptr; +constexpr size_t kActBuf = 1 << 16; + +void gemv(const Tensor& w, const float* x, float* y, const int* ids = nullptr, int n_sel = 1, size_t x_stride = 0) { + const size_t eb = w.shape.size() == 3 ? w.row_bytes * (size_t) w.shape[1] : 0; + const bool quant = w.type == T_Q8_0 || w.type == T_Q4_K || w.type == T_Q5_K || w.type == T_Q6_K; + if (quant && g_act_q8) { + const int n = (int) w.shape[0], sel = x_stride ? n_sel : 1; + if ((size_t) n * sel > kActBuf) { + std::fprintf(stderr, "q36ref: activation scratch too small\n"); + std::exit(1); + } + k_act_q8<<>>(x, x_stride, n, g_act_buf); + x = g_act_buf; + x_stride = x_stride ? (size_t) n : 0; + } + switch (w.type) { + case T_F32: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_F16: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_BF16: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q8_0: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q4_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q5_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q6_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + default: + std::fprintf(stderr, "q36ref: no kernel for ggml type %d (%s)\n", w.type, strata::ggml_type_name((uint32_t) w.type)); + std::exit(1); + } + CK(cudaGetLastError()); +} + +/// A 1-D tensor as f32 on the device (F32 as is, BF16 widened at load). +struct Model { + strata::core::ModelGeometry g; + int64_t top_k = 8; + float eps = 1e-6f, rope_base = 1e7f; + int n_rot = 64; + std::map t; + std::map f32; // the small vectors, f32 + + const Tensor& W(const std::string& n) const { + auto it = t.find(n); + if (it == t.end()) { + std::fprintf(stderr, "q36ref: missing tensor %s\n", n.c_str()); + std::exit(1); + } + return it->second; + } + const float* F(const std::string& n) const { + auto it = f32.find(n); + if (it == f32.end()) { + std::fprintf(stderr, "q36ref: missing vector %s\n", n.c_str()); + std::exit(1); + } + return it->second; + } +}; + +float h2f_host(uint16_t h) { + const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff; + if (e == 0) return (s ? -1.f : 1.f) * std::ldexp((float) m, -24); + const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13)); + float r; + std::memcpy(&r, &f, 4); + return r; +} + +bool load(const std::string& path, Model& m, std::string& err) { + const auto t0 = std::chrono::steady_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 = "this reference path is for Qwen3.6-35B-A3B (qwen35moe) only"; + return false; + } + size_t checked = 0; + if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) 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; + for (size_t s = 0; s < gm.size(); ++s) { + const strata::GgufFile& f = gm.shard(s); + for (const strata::TensorInfo& ti : f.tensors()) { + const uint64_t nb = strata::tensor_payload_bytes(ti); + const uint8_t* src = f.tensor_data(ti); + // the MTP block (blk.40) is not run by this path: not loaded + if (ti.name.rfind("blk." + std::to_string(m.g.n_layers) + ".", 0) == 0) continue; + const bool conv = ti.name.size() > 17 && ti.name.compare(ti.name.size() - 17, 17, "ssm_conv1d.weight") == 0; + if (ti.shape.size() == 1 || conv) { + // the small vectors (and the conv taps): f32 on the device + std::vector h(ti.elements()); + if (ti.type == T_F32) std::memcpy(h.data(), src, h.size() * 4); + else if (ti.type == T_BF16) + for (size_t i = 0; i < h.size(); ++i) { + const uint32_t u = (uint32_t) (src[2 * i] | (src[2 * i + 1] << 8)) << 16; + std::memcpy(&h[i], &u, 4); + } + else if (ti.type == T_F16) + for (size_t i = 0; i < h.size(); ++i) h[i] = h2f_host((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); + else { + err = ti.name + ": a 1-D tensor of type " + ti.type_name(); + return false; + } + float* d = nullptr; + CK(cudaMalloc(&d, h.size() * 4)); + CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); + m.f32[ti.name] = d; + bytes += h.size() * 4; + continue; + } + Tensor w; + w.type = (int) ti.type; + for (uint64_t d : ti.shape) w.shape.push_back((int64_t) d); + w.row_bytes = row_bytes_of(w.type, w.shape[0]); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, src, nb, cudaMemcpyHostToDevice)); + w.d = d; + m.t[ti.name] = w; + bytes += nb; + } + } + std::fprintf(stderr, "q36ref: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s\n", path.c_str(), + checked, (double) bytes / (1 << 30), + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + return true; +} + +struct State { + int ctx = 4096, pos = 0; + // scratch + float *x, *h, *y, *qkv, *z, *alpha, *beta, *conv_out, *gdn_out, *qg, *k, *v, *q, *gate, *att, *router, *eg, *eu, *eh, + *ey, *sg, *su, *sh, *sy, *sgate, *wts, *logits; + int* ids; + std::vector conv_state, S, kc, vc; // per layer (GDN: conv + S; attention: K/V cache) +}; + +float* dalloc(size_t n) { + float* p = nullptr; + CK(cudaMalloc(&p, n * 4)); + CK(cudaMemset(p, 0, n * 4)); + return p; +} + +void init_state(const Model& m, State& s) { + const auto& g = m.g; + const int N = (int) g.n_embd, FF = (int) g.n_ff, K = (int) m.top_k; + s.x = dalloc(N); s.h = dalloc(N); s.y = dalloc(N); + s.qkv = dalloc(g.ssm_conv_channels); s.z = dalloc(g.ssm_value_dim); s.alpha = dalloc(g.ssm_v_heads); + s.beta = dalloc(g.ssm_v_heads); s.conv_out = dalloc(g.ssm_conv_channels); s.gdn_out = dalloc(g.ssm_value_dim); + s.qg = dalloc(2 * g.n_head * g.head_dim); s.k = dalloc(g.n_head_kv * g.head_dim); s.v = dalloc(g.n_head_kv * g.head_dim); + s.q = dalloc(g.n_head * g.head_dim); s.gate = dalloc(g.n_head * g.head_dim); s.att = dalloc(g.n_head * g.head_dim); + s.router = dalloc(g.n_expert); + s.eg = dalloc((size_t) K * FF); s.eu = dalloc((size_t) K * FF); s.eh = dalloc((size_t) K * FF); s.ey = dalloc((size_t) K * N); + s.sg = dalloc(g.n_ff_shexp); s.su = dalloc(g.n_ff_shexp); s.sh = dalloc(g.n_ff_shexp); s.sy = dalloc(N); s.sgate = dalloc(1); + s.wts = dalloc(K); + s.logits = dalloc(g.n_vocab); + CK(cudaMalloc(&s.ids, K * sizeof(int))); + g_act_buf = dalloc(kActBuf); + for (int64_t l = 0; l < g.n_layers; ++l) { + if (strata::core::is_qsa_layer(g, l)) { + s.conv_state.push_back(nullptr); + s.S.push_back(nullptr); + s.kc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim)); + s.vc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim)); + } else { + s.conv_state.push_back(dalloc((size_t) (g.ssm_d_conv - 1) * g.ssm_conv_channels)); + s.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + s.kc.push_back(nullptr); + s.vc.push_back(nullptr); + } + } +} + +std::string L(int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; } + +void embed(const Model& m, State& s, int tok) { + const Tensor& e = m.W("token_embd.weight"); + const int N = (int) m.g.n_embd; + switch (e.type) { + case T_Q8_0: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_Q4_K: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_Q6_K: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_BF16: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_F16: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + default: + std::fprintf(stderr, "q36ref: token_embd type %d has no row reader\n", e.type); + std::exit(1); + } + CK(cudaGetLastError()); +} + +/// One token through the model at position s.pos; the layer outputs into `layers` (host, n_layers x N) when given. +void forward(const Model& m, State& s, int tok, float* layers) { + const auto& g = m.g; + const int N = (int) g.n_embd, K = (int) m.top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp; + const int B = 256; + embed(m, s, tok); + for (int64_t l = 0; l < g.n_layers; ++l) { + k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "attn_norm.weight")), s.h, N, m.eps); + if (!strata::core::is_qsa_layer(g, l)) { + 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; + gemv(m.W(L(l, "attn_qkv.weight")), s.h, s.qkv); + gemv(m.W(L(l, "attn_gate.weight")), s.h, s.z); + gemv(m.W(L(l, "ssm_beta.weight")), s.h, s.beta); + gemv(m.W(L(l, "ssm_alpha.weight")), s.h, s.alpha); + k_conv<<<(C + B - 1) / B, B>>>(s.qkv, s.conv_state[l], m.F(L(l, "ssm_conv1d.weight")), s.conv_out, C, + (int) g.ssm_d_conv); + k_gdn<<>>(s.conv_out, s.alpha, m.F(L(l, "ssm_dt.bias")), + m.F(L(l, "ssm_a")), s.beta, s.S[l], s.gdn_out, HK, HV, D, m.eps); + k_gated_norm<<>>(s.gdn_out, m.F(L(l, "ssm_norm.weight")), s.z, D, m.eps); + gemv(m.W(L(l, "ssm_out.weight")), s.gdn_out, s.y); + } else { + const int H = (int) g.n_head, HKV = (int) g.n_head_kv, D = (int) g.head_dim; + gemv(m.W(L(l, "attn_q.weight")), s.h, s.qg); + gemv(m.W(L(l, "attn_k.weight")), s.h, s.k); + gemv(m.W(L(l, "attn_v.weight")), s.h, s.v); + k_attn_prep<<>>(s.qg, s.k, s.v, m.F(L(l, "attn_q_norm.weight")), + m.F(L(l, "attn_k_norm.weight")), s.q, s.gate, s.kc[l], s.vc[l], H, HKV, D, + m.n_rot, s.pos, s.ctx, m.rope_base, m.eps); + k_attn<<>>(s.q, s.kc[l], s.vc[l], s.gate, s.att, H, HKV, D, + s.pos + 1, s.ctx, 1.0f / sqrtf((float) D)); + gemv(m.W(L(l, "attn_output.weight")), s.att, s.y); + } + CK(cudaGetLastError()); + k_add<<<(N + B - 1) / B, B>>>(s.x, s.y, N); + k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "post_attention_norm.weight")), s.h, N, m.eps); + // router: softmax over every expert, top-k, renormalised (host side: exact and simple) + gemv(m.W(L(l, "ffn_gate_inp.weight")), s.h, s.router); + std::vector r((size_t) g.n_expert); + CK(cudaMemcpy(r.data(), s.router, r.size() * 4, cudaMemcpyDeviceToHost)); + const float mx = *std::max_element(r.begin(), r.end()); + double sum = 0; + for (float& v : r) sum += (v = std::exp(v - mx)); + for (float& v : r) v = (float) (v / sum); + std::vector idx((size_t) g.n_expert); + for (int i = 0; i < (int) idx.size(); ++i) idx[i] = i; + std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), [&](int a, int b) { return r[a] > r[b] || (r[a] == r[b] && a < b); }); + std::vector w(K); + float ws = 0; + for (int i = 0; i < K; ++i) ws += (w[i] = r[idx[i]]); + for (float& v : w) v /= ws; + CK(cudaMemcpy(s.ids, idx.data(), K * sizeof(int), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(s.wts, w.data(), K * 4, cudaMemcpyHostToDevice)); + gemv(m.W(L(l, "ffn_gate_exps.weight")), s.h, s.eg, s.ids, K, 0); + gemv(m.W(L(l, "ffn_up_exps.weight")), s.h, s.eu, s.ids, K, 0); + k_swiglu<<<(K * FF + B - 1) / B, B>>>(s.eg, s.eu, s.eh, K * FF); + gemv(m.W(L(l, "ffn_down_exps.weight")), s.eh, s.ey, s.ids, K, FF); + // shared expert with its sigmoid scalar gate + gemv(m.W(L(l, "ffn_gate_shexp.weight")), s.h, s.sg); + gemv(m.W(L(l, "ffn_up_shexp.weight")), s.h, s.su); + k_swiglu<<<(FS + B - 1) / B, B>>>(s.sg, s.su, s.sh, FS); + gemv(m.W(L(l, "ffn_down_shexp.weight")), s.sh, s.sy); + { + Tensor gs; + gs.d = (const uint8_t*) m.F(L(l, "ffn_gate_inp_shexp.weight")); + gs.type = T_F32; + gs.shape = {N, 1}; + gs.row_bytes = (size_t) N * 4; + gemv(gs, s.h, s.sgate); + } + k_moe_sum<<<(N + B - 1) / B, B>>>(s.x, s.ey, s.wts, K, s.sy, s.sgate, N); + CK(cudaGetLastError()); + if (layers) CK(cudaMemcpy(layers + (size_t) l * N, s.x, (size_t) N * 4, cudaMemcpyDeviceToHost)); + } + k_rms<<<1, kThreads>>>(s.x, m.F("output_norm.weight"), s.h, N, m.eps); + gemv(m.W("output.weight"), s.h, s.logits); + CK(cudaDeviceSynchronize()); + ++s.pos; +} + +std::vector parse_ids(const std::string& s) { + std::vector v; + size_t i = 0; + while (i < s.size()) { + while (i < s.size() && (s[i] == ',' || s[i] == ' ' || s[i] == '\n' || s[i] == '\r')) ++i; + if (i >= s.size()) break; + v.push_back(std::atoi(s.c_str() + i)); + while (i < s.size() && s[i] != ',' && s[i] != ' ' && s[i] != '\n') ++i; + } + return v; +} + +} // namespace + +int main(int argc, char** argv) { + std::string model, tokens, dump_layers, dump_logits, force, dump_full; + int n_gen = 64, ctx = 4096; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { + std::fprintf(stderr, "q36ref: %s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--model") model = next(); + else if (a == "--tokens") tokens = next(); + else if (a == "--tokens-file") { + FILE* f = std::fopen(next().c_str(), "rb"); + if (!f) { std::fprintf(stderr, "q36ref: cannot read the tokens file\n"); return 2; } + char buf[4096]; + size_t n; + while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) tokens.append(buf, n); + std::fclose(f); + } else if (a == "--n") n_gen = std::atoi(next().c_str()); + else if (a == "--ctx") ctx = std::atoi(next().c_str()); + else if (a == "--dump-layers") dump_layers = next(); + else if (a == "--dump-logits") dump_logits = next(); + else if (a == "--force") force = next(); + else if (a == "--dump-full-logits") dump_full = next(); + else if (a == "--act") { + const std::string v = next(); + if (v != "q8" && v != "f32") { std::fprintf(stderr, "q36ref: --act q8 or f32\n"); return 2; } + g_act_q8 = v == "q8"; + } + else { + std::fprintf(stderr, "usage: strata-q36ref --model GGUF --tokens ID,ID,... | --tokens-file F [--n 64] [--ctx 4096] " + "[--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--force ID,ID,...] [--dump-full-logits FILE]\n"); + return 2; + } + } + const std::vector prompt = parse_ids(tokens); + // --force: the continuation is these tokens (teacher forcing: the KL check reads both engines on one sequence); + // the greedy ids are still printed + const std::vector forced = parse_ids(force); + if (!forced.empty()) n_gen = (int) forced.size() + 1; + if (model.empty() || prompt.empty()) { + std::fprintf(stderr, "q36ref: --model and --tokens are required\n"); + return 2; + } + Model m; + std::string err; + try { + if (!load(model, m, err)) { + std::fprintf(stderr, "q36ref: %s\n", err.c_str()); + return 1; + } + } catch (const std::exception& e) { + std::fprintf(stderr, "q36ref: %s\n", e.what()); + return 1; + } + State s; + s.ctx = ctx; + init_state(m, s); + const int N = (int) m.g.n_embd, NL = (int) m.g.n_layers, V = (int) m.g.n_vocab; + FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb"); + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + std::vector layers((size_t) NL * N), logits((size_t) V); + const auto t0 = std::chrono::steady_clock::now(); + int next = -1; + std::vector gen; + const int total = (int) prompt.size() + n_gen - 1; + if (total > ctx) { + std::fprintf(stderr, "q36ref: %d positions do not fit --ctx %d\n", total, ctx); + return 2; + } + for (int i = 0; i < total; ++i) { + const int tok = i < (int) prompt.size() ? prompt[i] : next; + forward(m, s, tok, fl ? layers.data() : nullptr); + if (fl) std::fwrite(layers.data(), 4, layers.size(), fl); + if (i + 1 >= (int) prompt.size()) { + CK(cudaMemcpy(logits.data(), s.logits, (size_t) V * 4, cudaMemcpyDeviceToHost)); + int a = 0, b = -1; + for (int j = 1; j < V; ++j) + if (logits[j] > logits[a]) a = j; + for (int j = 0; j < V; ++j) + if (j != a && (b < 0 || logits[j] > logits[b])) b = j; + next = gen.size() < forced.size() ? forced[gen.size()] : a; + gen.push_back(a); + if (ff) std::fwrite(logits.data(), 4, logits.size(), ff); + if (fg) { + const float rec[4] = {(float) a, logits[a], (float) b, logits[b]}; + std::fwrite(rec, 4, 4, fg); + } + } + } + const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (fl) std::fclose(fl); + if (fg) std::fclose(fg); + if (ff) std::fclose(ff); + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + std::fprintf(stderr, "q36ref: %zu prompt + %zu generated positions in %.2f s (%.2f tok/s, one token at a time)\n", + prompt.size(), gen.size(), sec, (double) total / sec); + return 0; +} diff --git a/tools/qwen35/compare_dumps.py b/tools/qwen35/compare_dumps.py new file mode 100644 index 00000000..7b94a040 --- /dev/null +++ b/tools/qwen35/compare_dumps.py @@ -0,0 +1,67 @@ +"""tools/qwen35/compare_dumps.py - two runs of the Qwen3.6 parity dumps against each other (e.g. llama.cpp GPU vs +llama.cpp CPU: the noise floor the strata-q36ref comparison is judged against). + + python tools/qwen35/compare_dumps.py DIR_A KIND_A DIR_B KIND_B (KIND: llama or strata) +Per prompt: greedy tokens equal up to the answer's end (llama.cpp's first <|im_end|> in run A), the first divergence's +top-1/top-2 margins, and the layer outputs' median and max ||a-b||/||b|| over the positions before the divergence. +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np + +N_EMBD, N_LAYER, EOS = 2048, 40, 248046 + + +def gen_of(d: Path, tag: str, kind: str) -> list[int]: + f = d / (f"{tag}.strata.gen" if kind == "strata" else f"{tag}.llama.log") + for line in f.read_text(encoding="utf-8").splitlines(): + if line.startswith("gen:"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no gen line in {f}") + + +def prompt_len(d: Path, tag: str) -> int: + for line in (d / f"{tag}.llama.log").read_text(encoding="utf-8").splitlines(): + if line.startswith("prompt:"): + return len(line.split(":", 1)[1].split()) + raise SystemExit("no prompt line") + + +def main() -> int: + da, ka, db, kb = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]), sys.argv[4] + tags = sorted({p.name.split(".")[0] for p in da.glob(f"p*.{ka}.layers")}) + rows = [] + for tag in tags: + ga, gb = gen_of(da, tag, ka), gen_of(db, tag, kb) + upto = min(len(ga), len(gb)) + if EOS in ga[:upto]: + upto = ga.index(EOS) + 1 + same = 0 + while same < upto and ga[same] == gb[same]: + same += 1 + la = np.fromfile(da / f"{tag}.{ka}.logits", dtype=np.float32).reshape(-1, 4) + lb = np.fromfile(db / f"{tag}.{kb}.logits", dtype=np.float32).reshape(-1, 4) + A = np.fromfile(da / f"{tag}.{ka}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + B = np.fromfile(db / f"{tag}.{kb}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + npos = min(len(A), len(B), prompt_len(da, tag) + same) + nb = np.linalg.norm(B[:npos], axis=2) + na = np.linalg.norm(A[:npos], axis=2) + err = np.where((nb > 0) & (na > 0), np.linalg.norm(A[:npos] - B[:npos], axis=2) / np.maximum(nb, 1e-30), np.nan) + div = "" + if same < upto: + div = (f"; step {same}: A {int(la[same, 0])} (margin {la[same, 1] - la[same, 3]:.3f}) vs B {int(lb[same, 0])} " + f"(margin {lb[same, 1] - lb[same, 3]:.3f})") + per_layer = np.nanmedian(err, axis=0) + rows.append((same == upto, np.nanmedian(err), np.nanmax(err))) + print(f"{tag}: {same}/{upto} equal; layer err median {np.nanmedian(err):.4f} max {np.nanmax(err):.4f}; " + f"median by layer 0/10/20/30/39: " + " ".join(f"{per_layer[i]:.4f}" for i in (0, 10, 20, 30, 39)) + div) + print(f"answers identical: {sum(r[0] for r in rows)} of {len(rows)}; layer err median of medians " + f"{np.median([r[1] for r in rows]):.4f}, worst max {max(r[2] for r in rows):.4f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/kl.py b/tools/qwen35/kl.py new file mode 100644 index 00000000..f0279204 --- /dev/null +++ b/tools/qwen35/kl.py @@ -0,0 +1,88 @@ +"""tools/qwen35/kl.py - teacher-forced KL for Qwen3.6-35B-A3B (NEW-MODELS-PLAN.md T1/T2): on one token sequence per +prompt (the prompt + llama.cpp GPU's greedy answer, from a parity.py run), the next-token distributions of +llama.cpp HIP (the reference P), llama.cpp CPU (the noise floor) and strata-q36ref. Reported: mean KL(P || Q) and +the top-1 agreement over all steps, per engine; the plan's gate is Strata's KL within 1.5x of the floor. + + python tools/qwen35/kl.py --ref BIN --dump BIN --model GGUF --parity DIR --out DIR [--lock "..."] [--cpu-lock "..."] +""" +from __future__ import annotations + +import argparse +import shlex +import subprocess +import sys +from pathlib import Path + +import numpy as np + +V = 248320 + + +def ids(path: Path, key: str) -> list[int]: + for line in path.read_text(encoding="utf-8").splitlines(): + if line.startswith(key + ":"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no {key}: in {path}") + + +def run(cmd: list[str], lock: str, log: Path) -> None: + r = subprocess.run((shlex.split(lock) if lock else []) + cmd, capture_output=True, text=True, timeout=3600) + log.write_text(r.stdout + "\n--- stderr ---\n" + r.stderr, encoding="utf-8") + if r.returncode != 0: + raise SystemExit(f"{cmd[0]} failed (rc {r.returncode}), see {log}") + + +def log_softmax(x: np.ndarray) -> np.ndarray: + x = x.astype(np.float64) + m = x.max(axis=1, keepdims=True) + return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True)) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ref", required=True) + ap.add_argument("--dump", required=True) + ap.add_argument("--model", required=True) + ap.add_argument("--parity", required=True, help="a parity.py output dir (its llama.cpp logs give the sequences)") + ap.add_argument("--out", required=True) + ap.add_argument("--lock", default="") + ap.add_argument("--cpu-lock", default="") + ap.add_argument("--ref-args", default="", help="extra strata-q36ref arguments (e.g. '--act f32')") + a = ap.parse_args() + out, par = Path(a.out), Path(a.parity) + out.mkdir(parents=True, exist_ok=True) + tags = sorted(p.name.split(".")[0] for p in par.glob("p*.llama.log")) + kl = {"cpu": [], "strata": []} + top1 = {"cpu": [], "strata": []} + for tag in tags: + prompt, gen = ids(par / f"{tag}.llama.log", "prompt"), ids(par / f"{tag}.llama.log", "gen") + force = ",".join(map(str, gen)) + toks = ",".join(map(str, prompt)) + f = {k: out / f"{tag}.{k}.full" for k in ("gpu", "cpu", "strata")} + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "99", "--dump-full-logits", + str(f["gpu"])], a.lock, out / f"{tag}.gpu.log") + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "0", "--dump-full-logits", + str(f["cpu"])], a.cpu_lock, out / f"{tag}.cpu.log") + run([a.ref, "--model", a.model, "--tokens", toks, "--force", force, "--dump-full-logits", str(f["strata"]), + *shlex.split(a.ref_args)], a.lock, out / f"{tag}.strata.log") + P = log_softmax(np.fromfile(f["gpu"], dtype=np.float32).reshape(-1, V)) + line = f"{tag}: {len(P)} steps" + for k in ("cpu", "strata"): + Q = log_softmax(np.fromfile(f[k], dtype=np.float32).reshape(-1, V)) + n = min(len(P), len(Q)) + d = (np.exp(P[:n]) * (P[:n] - Q[:n])).sum(axis=1) + kl[k].extend(d.tolist()) + top1[k].extend((P[:n].argmax(axis=1) == Q[:n].argmax(axis=1)).tolist()) + line += f"; {k}: KL {d.mean():.5f} top-1 {np.mean(P[:n].argmax(axis=1) == Q[:n].argmax(axis=1)):.3f}" + for p in f.values(): + p.unlink(missing_ok=True) # 250 MB each: the numbers are what is kept + print(line, flush=True) + for k in ("cpu", "strata"): + print(f"{k:6s} vs llama.cpp HIP: mean KL {np.mean(kl[k]):.5f} (p99 {np.percentile(kl[k], 99):.4f}), top-1 " + f"{np.mean(top1[k]):.4f} over {len(kl[k])} steps") + print(f"ratio strata / floor: {np.mean(kl['strata']) / max(np.mean(kl['cpu']), 1e-12):.2f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/parity.py b/tools/qwen35/parity.py new file mode 100644 index 00000000..640415f3 --- /dev/null +++ b/tools/qwen35/parity.py @@ -0,0 +1,112 @@ +"""tools/qwen35/parity.py - NEW-MODELS-PLAN.md T1's exit gate for Qwen3.6-35B-A3B: strata-q36ref against llama.cpp +(tools/qwen35/q36_llama_dump.cpp) on the same GGUF, the same box and the same token ids. + +For each prompt (parity_prompts.json, ChatML with thinking off): llama.cpp tokenizes it and runs it (the reference +ids, layer outputs and greedy tokens); strata-q36ref runs the same ids. Reported per prompt: the greedy tokens that +agree (of --n), the first divergence with both engines' top-1/top-2 logit margins (a near tie is a margin < 0.05), and +the per-layer hidden-state error max over positions of ||strata - llama|| / ||llama||. + + python tools/qwen35/parity.py --ref BIN --dump BIN --model GGUF --out DIR [--n 64] [--ngl 99] [--lock "flock ..."] +""" +from __future__ import annotations + +import argparse +import json +import shlex +import subprocess +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +TEMPLATE = "<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" +N_EMBD, N_LAYER = 2048, 40 +EOS = 248046 # <|im_end|> + + +def run(cmd: list[str], lock: str, log: Path) -> str: + full = shlex.split(lock) + cmd if lock else cmd + r = subprocess.run(full, capture_output=True, text=True, timeout=1800) + log.write_text(r.stdout + "\n--- stderr ---\n" + r.stderr, encoding="utf-8") + if r.returncode != 0: + raise SystemExit(f"{cmd[0]} failed (rc {r.returncode}), see {log}") + return r.stdout + + +def ids_of(out: str, key: str) -> list[int]: + for line in out.splitlines(): + if line.startswith(key + ":"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no '{key}:' line") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ref", required=True, help="strata-q36ref") + ap.add_argument("--dump", required=True, help="q36_llama_dump") + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=64) + ap.add_argument("--ngl", type=int, default=99, help="llama.cpp's GPU layers (0 = its CPU backend)") + ap.add_argument("--lock", default="", help="a command prefix for the GPU runs (the box's flock)") + ap.add_argument("--prompts", default=str(HERE / "parity_prompts.json")) + ap.add_argument("--skip-ref", action="store_true", help="reuse strata-q36ref's outputs in --out") + ap.add_argument("--past-eos", action="store_true", help="compare all --n tokens, not only up to the answer's end") + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + prompts = json.loads(Path(a.prompts).read_text(encoding="utf-8")) + summary = [] + for i, p in enumerate(prompts): + tag = f"p{i:02d}" + lo = run([a.dump, "--model", a.model, "--prompt", TEMPLATE.format(p=p), "--n", str(a.n), "--ngl", str(a.ngl), + "--dump-layers", str(out / f"{tag}.llama.layers"), "--dump-logits", str(out / f"{tag}.llama.logits")], + a.lock, out / f"{tag}.llama.log") + prompt_ids, lgen = ids_of(lo, "prompt"), ids_of(lo, "gen") + if not a.skip_ref: + so = run([a.ref, "--model", a.model, "--tokens", ",".join(map(str, prompt_ids)), "--n", str(a.n), + "--dump-layers", str(out / f"{tag}.strata.layers"), "--dump-logits", str(out / f"{tag}.strata.logits")], + a.lock, out / f"{tag}.strata.log") + (out / f"{tag}.strata.gen").write_text(so, encoding="utf-8") + sgen = ids_of((out / f"{tag}.strata.gen").read_text(encoding="utf-8"), "gen") + # the answer ends at llama.cpp's first <|im_end|> (included); past it both engines run on in a context no chat + # ever reaches, so the comparison stops there (--past-eos compares all --n tokens) + upto = min(len(sgen), len(lgen)) + if not a.past_eos and EOS in lgen[:upto]: + upto = lgen.index(EOS) + 1 + same = 0 + while same < upto and sgen[same] == lgen[same]: + same += 1 + sl = np.fromfile(out / f"{tag}.strata.logits", dtype=np.float32).reshape(-1, 4) + ll = np.fromfile(out / f"{tag}.llama.logits", dtype=np.float32).reshape(-1, 4) + div = None + if same < upto: + div = {"step": same, "strata": [int(sl[same, 0]), float(sl[same, 1] - sl[same, 3])], + "llama": [int(ll[same, 0]), float(ll[same, 1] - ll[same, 3])]} + # the layer outputs up to the divergence (after it the two engines read different tokens) + sL = np.fromfile(out / f"{tag}.strata.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + lL = np.fromfile(out / f"{tag}.llama.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + npos = min(len(sL), len(lL), len(prompt_ids) + same) + ln = np.linalg.norm(lL[:npos], axis=2) + err = np.linalg.norm(sL[:npos] - lL[:npos], axis=2) / np.maximum(ln, 1e-30) # [pos, layer] + # llama.cpp keeps only the output rows of the last layer of a prompt batch: rows it did not compute are 0 + err = np.where(ln > 0, err, np.nan) + per_layer = np.nanmax(err, axis=0) + rec = {"prompt": i, "tokens": len(prompt_ids), "same": same, "of": upto, + "divergence": div, "max_rel_err": float(np.nanmax(per_layer)), "worst_layer": int(np.nanargmax(per_layer)), + "median_rel_err": float(np.nanmedian(err)), "per_layer_max": [round(float(x), 5) for x in per_layer]} + summary.append(rec) + print(f"{tag}: {same}/{rec['of']} greedy tokens equal; layers max rel err {rec['max_rel_err']:.4f} (layer " + f"{rec['worst_layer']}), median {rec['median_rel_err']:.5f}" + (f"; diverges at {div}" if div else ""), + flush=True) + (out / "summary.json").write_text(json.dumps(summary, indent=1), encoding="utf-8") + full = sum(r["same"] == r["of"] for r in summary) + print(f"identical greedy answers (up to {a.n} tokens{'' if a.past_eos else ' or the end of the answer'}): {full} of " + f"{len(summary)} prompts; worst layer error " + f"{max(r['max_rel_err'] for r in summary):.4f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/parity_prompts.json b/tools/qwen35/parity_prompts.json new file mode 100644 index 00000000..75881bac --- /dev/null +++ b/tools/qwen35/parity_prompts.json @@ -0,0 +1,12 @@ +[ + "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "Implement an LRU cache in Python with get and put in O(1), and add three unit tests.", + "What is 17 * 23 + 144 / 12? Show the steps.", + "Explain how a refrigerator works to a ten-year-old.", + "Translate into German: The train to Munich leaves at half past seven, platform four.", + "List five differences between TCP and UDP.", + "Summarize the plot of Romeo and Juliet in three sentences.", + "Write a JSON object describing a book with title, author, year and three tags.", + "If all bloops are razzies and all razzies are lazzies, are all bloops lazzies? Explain.", + "Write a haiku about autumn rain on a city street." +] diff --git a/tools/qwen35/q36_llama_dump.cpp b/tools/qwen35/q36_llama_dump.cpp new file mode 100644 index 00000000..0b1a7508 --- /dev/null +++ b/tools/qwen35/q36_llama_dump.cpp @@ -0,0 +1,150 @@ +// tools/qwen35/q36_llama_dump.cpp - llama.cpp's side of the Qwen3.6 parity check (NEW-MODELS-PLAN.md T1): the same GGUF, +// the same token ids, llama.cpp's own graph. Prints the prompt's ids and the greedy ids, and dumps every processed +// position's layer outputs ("l_out-N", through the scheduler's eval callback) in strata-q36ref's format +// ([pos][layer][n_embd] f32) plus each greedy step's top-2 (id, logit). +// +// Built against a llama.cpp checkout (not part of Strata's build): +// g++ -O2 -std=c++17 q36_llama_dump.cpp -I/include -I/ggml/include -L/build/bin -lllama -lggml +// -lggml-base -Wl,-rpath,/build/bin -o q36_llama_dump +// Usage: q36_llama_dump --model GGUF (--prompt TEXT | --tokens ID,ID,...) [--n 64] [--ngl 99] [--dump-layers F] +// [--dump-logits F] [--force ID,ID,...] [--dump-full-logits F] +// --force feeds that continuation instead of the greedy ids (teacher forcing); --dump-full-logits writes every +// step's logits (f32, [step][vocab]). +// --prompt is tokenized with special tokens parsed and no BOS added (Qwen adds none). +#include "llama.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct Capture { + int n_embd = 0, n_layer = 0, n_tok = 0; + std::map> layers; // layer -> [n_tok][n_embd] of the current batch +}; + +bool on_tensor(struct ggml_tensor* t, bool ask, void* user) { + auto* c = (Capture*) user; + const char* name = ggml_get_name(t); + if (std::strncmp(name, "l_out-", 6) != 0) return ask ? false : true; + if (ask) return true; + const int il = std::atoi(name + 6); + if (t->type != GGML_TYPE_F32 || t->ne[0] != c->n_embd) return true; + std::vector& v = c->layers[il]; + v.resize((size_t) ggml_nelements(t)); + ggml_backend_tensor_get(t, v.data(), 0, ggml_nbytes(t)); + return true; +} + +std::vector parse_ids(const std::string& s) { + std::vector v; + const char* p = s.c_str(); + while (*p) { + while (*p == ',' || *p == ' ') ++p; + if (!*p) break; + v.push_back(std::atoi(p)); + while (*p && *p != ',' && *p != ' ') ++p; + } + return v; +} +} // namespace + +int main(int argc, char** argv) { + std::string model, prompt, tokens, dump_layers, dump_logits, force, dump_full; + int n_gen = 64, ngl = 99; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string a = argv[i], v = argv[i + 1]; + if (a == "--model") model = v; + else if (a == "--prompt") prompt = v; + else if (a == "--tokens") tokens = v; + else if (a == "--n") n_gen = std::atoi(v.c_str()); + else if (a == "--ngl") ngl = std::atoi(v.c_str()); + else if (a == "--dump-layers") dump_layers = v; + else if (a == "--dump-logits") dump_logits = v; + else if (a == "--force") force = v; + else if (a == "--dump-full-logits") dump_full = v; + else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } + } + llama_backend_init(); + llama_model_params mp = llama_model_default_params(); + mp.n_gpu_layers = ngl; + llama_model* mdl = llama_model_load_from_file(model.c_str(), mp); + if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; } + const llama_vocab* vocab = llama_model_get_vocab(mdl); + std::vector ids; + if (!tokens.empty()) { + for (int t : parse_ids(tokens)) ids.push_back(t); + } else { + ids.resize(prompt.size() + 16); + const int n = llama_tokenize(vocab, prompt.c_str(), (int) prompt.size(), ids.data(), (int) ids.size(), false, true); + if (n < 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } + ids.resize(n); + } + Capture cap; + cap.n_embd = llama_model_n_embd(mdl); + cap.n_layer = llama_model_n_layer(mdl); + llama_context_params cp = llama_context_default_params(); + cp.n_ctx = 4096; + cp.n_batch = cp.n_ubatch = 4096; + cp.op_offload = ngl > 0; // --ngl 0 is the CPU backend: no prompt matmuls offloaded to a GPU either + cp.cb_eval = on_tensor; + cp.cb_eval_user_data = ∩ + llama_context* ctx = llama_init_from_model(mdl, cp); + if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; } + FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb"); + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + const std::vector forced = parse_ids(force); + if (!forced.empty()) n_gen = (int) forced.size() + 1; + const int V = llama_vocab_n_tokens(vocab); + auto write_layers = [&](int n_tok) { + if (!fl) return; + // a layer may keep fewer rows than the batch (the last layer keeps only the output rows): those are the + // batch's LAST positions; the positions it did not compute are written as zeros + std::vector zero(cap.n_embd, 0.f); + for (int t = 0; t < n_tok; ++t) + for (int l = 0; l < cap.n_layer; ++l) { + auto it = cap.layers.find(l); + const int rows = it == cap.layers.end() ? 0 : (int) (it->second.size() / cap.n_embd); + const int r = t - (n_tok - rows); + const float* src = r >= 0 ? it->second.data() + (size_t) r * cap.n_embd : zero.data(); + std::fwrite(src, 4, cap.n_embd, fl); + } + cap.layers.clear(); + }; + std::printf("prompt:"); + for (int t : ids) std::printf(" %d", t); + std::printf("\n"); + std::vector gen; + llama_batch b = llama_batch_get_one(ids.data(), (int) ids.size()); + if (llama_decode(ctx, b) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; } + write_layers((int) ids.size()); + for (int i = 0; i < n_gen; ++i) { + const float* lg = llama_get_logits_ith(ctx, -1); + int a = 0, c = -1; + for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j; + for (int j = 0; j < V; ++j) if (j != a && (c < 0 || lg[j] > lg[c])) c = j; + if (fg) { const float rec[4] = {(float) a, lg[a], (float) c, lg[c]}; std::fwrite(rec, 4, 4, fg); } + gen.push_back(a); + if (ff) std::fwrite(lg, 4, V, ff); + if (i + 1 == n_gen) break; + llama_token t = i < (int) forced.size() ? forced[i] : a; + llama_batch one = llama_batch_get_one(&t, 1); + if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; } + write_layers(1); + } + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + if (fl) std::fclose(fl); + if (fg) std::fclose(fg); + if (ff) std::fclose(ff); + llama_free(ctx); + llama_model_free(mdl); + llama_backend_free(); + return 0; +}