Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/kernels/legacy-c/turbo_forward.c # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / kernels / legacy-c / turbo_forward.c` 706 lines · 32712 bytes Raw Blame History 1 /** 2 * turbo_forward.c — Full transformer forward pass in C 3 * 4 * Eliminates all Python per-layer overhead by keeping the entire 5 * forward pass in C. Python only calls once per token. 6 * 7 * Architecture supports: Llama (dense) and Qwen3 (MoE) 8 * Quant types: Q4_0, Q4_1, Q8_0, Q4_K, Q5_K, Q6_K, F32 9 */ 10 11 #include 12 #include 13 #include 14 #include 15 #include 16 #include 17 #include 18 19 #define QK_K 256 20 #define QK8_0 32 21 22 /* ── Quant type codes (GGML convention) ── */ 23 #define GGML_F32 0 24 #define GGML_F16 1 25 #define GGML_Q4_0 2 26 #define GGML_Q4_1 3 27 #define GGML_Q8_0 8 28 #define GGML_Q4_K 12 29 #define GGML_Q5_K 13 30 #define GGML_Q6_K 14 31 32 /* ── Weight descriptor: one per model weight tensor ── */ 33 typedef struct { 34 void* data; /* Pointer to raw quantized bytes or F32 data */ 35 int nrows; /* out_dim */ 36 int ncols; /* in_dim */ 37 int qtype; /* GGML quant type code */ 38 int block_size; /* bytes per block (18 for Q4_0, 144 for Q4_K, etc) */ 39 int vals_per_block; /* values per block (32 for Q4_0, 256 for Q4_K) */ 40 } WeightDesc; 41 42 /* ── Layer descriptor: all weights for one transformer layer ── */ 43 typedef struct { 44 WeightDesc attn_norm; /* RMSNorm weight [n_embd] */ 45 WeightDesc attn_q; /* Q projection [n_embd, n_embd] */ 46 WeightDesc attn_k; /* K projection [n_kv_head*head_dim, n_embd] */ 47 WeightDesc attn_v; /* V projection [n_kv_head*head_dim, n_embd] */ 48 WeightDesc attn_out; /* Output projection [n_embd, n_embd] */ 49 WeightDesc attn_q_norm; /* Q per-head norm [head_dim] (Qwen3 GQA norm) */ 50 WeightDesc attn_k_norm; /* K per-head norm [head_dim] */ 51 WeightDesc ffn_norm; /* FFN RMSNorm [n_embd] */ 52 53 /* Dense FFN */ 54 WeightDesc ffn_gate; /* [n_ff, n_embd] */ 55 WeightDesc ffn_up; /* [n_ff, n_embd] */ 56 WeightDesc ffn_down; /* [n_embd, n_ff] */ 57 58 /* MoE */ 59 int is_moe; 60 WeightDesc moe_gate_inp; /* Router [n_experts, n_embd] */ 61 int n_experts; 62 int n_experts_per_tok; 63 int n_ff_expert; 64 WeightDesc* moe_gate_exps; /* [n_experts] each [n_ff_expert, n_embd] */ 65 WeightDesc* moe_up_exps; /* [n_experts] each [n_ff_expert, n_embd] */ 66 WeightDesc* moe_down_exps; /* [n_experts] each [n_embd, n_ff_expert] */ 67 68 /* Shared expert (Qwen3 MoE) */ 69 int has_shared_expert; 70 WeightDesc shared_gate; /* [2*n_ff_expert, n_embd] */ 71 WeightDesc shared_up; /* [2*n_ff_expert, n_embd] */ 72 WeightDesc shared_down; /* [n_embd, 2*n_ff_expert] */ 73 } LayerDesc; 74 75 /* ── Model descriptor: full transformer ── */ 76 typedef struct { 77 int n_layers; 78 int n_embd; 79 int n_head; 80 int n_kv_head; 81 int head_dim; 82 int n_ff; 83 float rope_freq_base; 84 float eps; 85 int vocab_size; 86 int is_moe; 87 88 WeightDesc token_embd; /* [vocab_size, n_embd] */ 89 WeightDesc output_norm; /* [n_embd] */ 90 WeightDesc output_weight; /* [vocab_size, n_embd] or tied with token_embd */ 91 92 LayerDesc* layers; /* [n_layers] */ 93 94 /* Precomputed rope tables */ 95 float* rope_cos; /* [max_pos, head_dim/2] */ 96 float* rope_sin; /* [max_pos, head_dim/2] */ 97 int max_pos; 98 } ModelDesc; 99 100 /* ── Forward pass state ── */ 101 typedef struct { 102 float* kv_k; /* [n_layers, max_pos, n_kv_head*head_dim] */ 103 float* kv_v; /* [n_layers, max_pos, n_kv_head*head_dim] */ 104 int* kv_len; /* [n_layers] */ 105 int pos; 106 107 /* Pre-allocated work buffers */ 108 float* h; /* [n_embd] */ 109 float* residual; /* [n_embd] */ 110 float* q; /* [n_head*head_dim] */ 111 float* k; /* [n_kv_head*head_dim] */ 112 float* v; /* [n_kv_head*head_dim] */ 113 float* att_out; /* [n_head*head_dim] */ 114 float* gate; /* [n_ff] */ 115 float* up; /* [n_ff] */ 116 float* silu_gate; /* [n_ff] */ 117 float* ffn_out; /* [n_embd] */ 118 float* logits; /* [vocab_size] */ 119 float* scores; /* [n_head, max_pos] for attention */ 120 float* expert_result;/* [n_embd] for MoE accumulation */ 121 122 int max_pos; 123 int n_embd; 124 int n_head; 125 int n_kv_head; 126 int head_dim; 127 int n_ff; 128 int n_layers; 129 } ForwardState; 130 131 /* ── f16 to f32 conversion ── */ 132 static inline float f16_to_f32(uint16_t h) { 133 uint32_t sign = (h >> 15) & 1; 134 uint32_t exp = (h >> 10) & 0x1f; 135 uint32_t mant = h & 0x3ff; 136 float out; 137 if (exp == 0) { 138 if (mant == 0) { out = 0.0f; } 139 else { out = ldexpf((float)mant / 1024.0f, -14); } 140 } else if (exp == 31) { 141 out = (mant == 0) ? INFINITY : NAN; 142 } else { 143 out = ldexpf(1.0f + (float)mant / 1024.0f, (int)exp - 15); 144 } 145 return sign ? -out : out; 146 } 147 148 /* ══════════════════════════════════════════════════════════════════════════ 149 * Quantized matmul kernels (AVX2 + FMA) 150 * ══════════════════════════════════════════════════════════════════════════ */ 151 152 static inline float hsum_ps(__m256 v) { 153 __m256 h = _mm256_hadd_ps(v, _mm256_permute2f128_ps(v, v, 1)); 154 h = _mm256_hadd_ps(h, h); 155 h = _mm256_hadd_ps(h, h); 156 return _mm256_cvtss_f32(h); 157 } 158 159 /* ── F32 matmul (AVX2 + FMA) ── */ 160 static void f32_matmul(const float* W, const float* x, float* out, int nrows, int ncols) { 161 #pragma omp parallel for schedule(static) 162 for (int r = 0; r < nrows; r++) { 163 const float* row = W + (size_t)r * ncols; 164 __m256 s0 = _mm256_setzero_ps(), s1 = _mm256_setzero_ps(); 165 int c; 166 for (c = 0; c <= ncols - 16; c += 16) { 167 s0 = _mm256_fmadd_ps(_mm256_loadu_ps(row + c), _mm256_loadu_ps(x + c), s0); 168 s1 = _mm256_fmadd_ps(_mm256_loadu_ps(row + c + 8), _mm256_loadu_ps(x + c + 8), s1); 169 } 170 __m256 total = _mm256_add_ps(s0, s1); 171 float result = hsum_ps(total); 172 for (; c < ncols; c++) result += row[c] * x[c]; 173 out[r] = result; 174 } 175 } 176 177 /* ── RMS Norm (AVX2) ── */ 178 static void rms_norm(const float* x, const float* w, float* out, int n, float eps) { 179 __m256 ss_vec = _mm256_setzero_ps(); 180 int i; 181 for (i = 0; i <= n - 8; i += 8) { 182 __m256 v = _mm256_loadu_ps(x + i); 183 ss_vec = _mm256_fmadd_ps(v, v, ss_vec); 184 } 185 float ss = hsum_ps(ss_vec); 186 for (; i < n; i++) ss += x[i] * x[i]; 187 float inv_rms = 1.0f / sqrtf(ss / n + eps); 188 __m256 inv_v = _mm256_set1_ps(inv_rms); 189 for (i = 0; i <= n - 8; i += 8) { 190 _mm256_storeu_ps(out + i, _mm256_mul_ps(_mm256_mul_ps(_mm256_loadu_ps(x + i), inv_v), _mm256_loadu_ps(w + i))); 191 } 192 for (; i < n; i++) out[i] = x[i] * inv_rms * w[i]; 193 } 194 195 /* ── SiLU activation (vectorized) ── */ 196 static void silu_inplace(float* x, int n) { 197 int i; 198 for (i = 0; i <= n - 8; i += 8) { 199 __m256 v = _mm256_loadu_ps(x + i); 200 /* silu(x) = x / (1 + exp(-x)) = x * sigmoid(x) */ 201 /* Compute -x */ 202 __m256 neg_v = _mm256_sub_ps(_mm256_setzero_ps(), v); 203 /* Approximate exp: use expf in a loop for now — AVX2 doesn't have native exp */ 204 float tmp[8], neg_tmp[8], result[8]; 205 _mm256_storeu_ps(tmp, v); 206 _mm256_storeu_ps(neg_tmp, neg_v); 207 for (int j = 0; j < 8; j++) { 208 result[j] = tmp[j] / (1.0f + expf(neg_tmp[j])); 209 } 210 _mm256_storeu_ps(x + i, _mm256_loadu_ps(result)); 211 } 212 for (; i < n; i++) x[i] = x[i] / (1.0f + expf(-x[i])); 213 } 214 215 /* ── Q4_0 matmul (18 bytes per 32 values) ── */ 216 static void q4_0_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 217 int bpr = ncols / 32; 218 #pragma omp parallel for schedule(static) 219 for (int r = 0; r < nrows; r++) { 220 float total = 0.0f; 221 for (int blk = 0; blk < bpr; blk++) { 222 const uint8_t* bp = W + ((size_t)r * bpr + blk) * 18; 223 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8)); 224 __m256 dv = _mm256_set1_ps(d); 225 __m128i nb = _mm_loadu_si128((__m128i*)(bp + 2)); 226 __m128i lo = _mm_and_si128(nb, _mm_set1_epi8(15)); 227 __m128i hi = _mm_and_si128(_mm_srli_epi16(_mm_and_si128(nb, _mm_set1_epi8((char)0xF0)), 4), _mm_set1_epi8(15)); 228 __m128i lo_s = _mm_sub_epi8(lo, _mm_set1_epi8(8)); 229 __m128i hi_s = _mm_sub_epi8(hi, _mm_set1_epi8(8)); 230 /* Expand lo[0:7], lo[8:15], hi[0:7], hi[8:15] to 4 x __m256 */ 231 __m128i e00 = _mm_cvtepi8_epi16(lo_s), e01 = _mm_cvtepi8_epi16(_mm_shuffle_epi32(lo_s, 0x4e)); 232 __m128i e10 = _mm_cvtepi8_epi16(hi_s), e11 = _mm_cvtepi8_epi16(_mm_shuffle_epi32(hi_s, 0x4e)); 233 __m256 v0 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e00, 0x4e)), _mm_cvtepi16_epi32(e00))), dv); 234 __m256 v1 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e01, 0x4e)), _mm_cvtepi16_epi32(e01))), dv); 235 __m256 v2 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e10, 0x4e)), _mm_cvtepi16_epi32(e10))), dv); 236 __m256 v3 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e11, 0x4e)), _mm_cvtepi16_epi32(e11))), dv); 237 int off = blk * 32; 238 __m256 a = _mm256_mul_ps(v0, _mm256_loadu_ps(x + off)); 239 a = _mm256_fmadd_ps(v1, _mm256_loadu_ps(x + off + 8), a); 240 a = _mm256_fmadd_ps(v2, _mm256_loadu_ps(x + off + 16), a); 241 a = _mm256_fmadd_ps(v3, _mm256_loadu_ps(x + off + 24), a); 242 total += hsum_ps(a); 243 } 244 out[r] = total; 245 } 246 } 247 248 /* ── Q4_1 matmul (20 bytes per 32 values) ── */ 249 static void q4_1_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 250 int bpr = ncols / 32; 251 #pragma omp parallel for schedule(static) 252 for (int r = 0; r < nrows; r++) { 253 float total = 0.0f; 254 for (int blk = 0; blk < bpr; blk++) { 255 const uint8_t* bp = W + ((size_t)r * bpr + blk) * 20; 256 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8)); 257 float m = f16_to_f32((uint16_t)bp[2] | ((uint16_t)bp[3] << 8)); 258 __m256 d_v = _mm256_set1_ps(d), m_v = _mm256_set1_ps(m); 259 __m128i nb = _mm_loadu_si128((__m128i*)(bp + 4)); 260 __m128i lo = _mm_and_si128(nb, _mm_set1_epi8(15)); 261 __m128i hi = _mm_and_si128(_mm_srli_epi16(_mm_and_si128(nb, _mm_set1_epi8((char)0xF0)), 4), _mm_set1_epi8(15)); 262 __m128i e00 = _mm_cvtepu8_epi16(lo), e01 = _mm_cvtepu8_epi16(_mm_shuffle_epi32(lo, 0x4e)); 263 __m128i e10 = _mm_cvtepu8_epi16(hi), e11 = _mm_cvtepu8_epi16(_mm_shuffle_epi32(hi, 0x4e)); 264 __m256 v0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e00,0x4e)),_mm_cvtepi16_epi32(e00))), d_v, m_v); 265 __m256 v1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e01,0x4e)),_mm_cvtepi16_epi32(e01))), d_v, m_v); 266 __m256 v2 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e10,0x4e)),_mm_cvtepi16_epi32(e10))), d_v, m_v); 267 __m256 v3 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(_mm_cvtepi16_epi32(_mm_shuffle_epi32(e11,0x4e)),_mm_cvtepi16_epi32(e11))), d_v, m_v); 268 int off = blk * 32; 269 __m256 a = _mm256_mul_ps(v0, _mm256_loadu_ps(x + off)); 270 a = _mm256_fmadd_ps(v1, _mm256_loadu_ps(x + off + 8), a); 271 a = _mm256_fmadd_ps(v2, _mm256_loadu_ps(x + off + 16), a); 272 a = _mm256_fmadd_ps(v3, _mm256_loadu_ps(x + off + 24), a); 273 total += hsum_ps(a); 274 } 275 out[r] = total; 276 } 277 } 278 279 /* ── Q8_0 matmul (34 bytes per 32 values) ── */ 280 static void q8_0_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 281 int bpr = ncols / 32; 282 #pragma omp parallel for schedule(static) 283 for (int r = 0; r < nrows; r++) { 284 __m256 acc = _mm256_setzero_ps(); 285 for (int blk = 0; blk < bpr; blk++) { 286 const uint8_t* bp = W + ((size_t)r * bpr + blk) * 34; 287 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8)); 288 const int8_t* qs = (const int8_t*)(bp + 2); 289 __m256 dv = _mm256_set1_ps(d); 290 int off = blk * 32; 291 for (int i = 0; i < 32; i += 8) { 292 __m256i qi = _mm256_cvtepi8_epi32(_mm_loadl_epi64((__m128i*)(qs + i))); 293 __m256 qf = _mm256_cvtepi32_ps(qi); 294 acc = _mm256_fmadd_ps(_mm256_mul_ps(qf, dv), _mm256_loadu_ps(x + off + i), acc); 295 } 296 } 297 out[r] = hsum_ps(acc); 298 } 299 } 300 301 /* ── K-Quant scale extraction helpers ── */ 302 static inline void get_scale_min_k4(int j, const uint8_t *q, uint8_t *d, uint8_t *m) { 303 if (j < 4) { 304 *d = q[j] & 63; *m = q[j] >> 6; 305 } else if (j < 20) { 306 *d = (q[j+4] & 15) | ((q[j-2] >> 6) << 4); *m = (q[j+4] >> 4); 307 } else { 308 *d = (q[j+4] & 63) >> 2; *m = (q[j+4] >> 4); 309 } 310 } 311 312 /* ── Q4_K matmul (144 bytes per 256 values) ── */ 313 static void q4_k_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 314 int nb = ncols / 256; 315 #pragma omp parallel for schedule(static) 316 for (int r = 0; r < nrows; r++) { 317 const uint8_t* row = W + (size_t)r * nb * 144; 318 __m256 acc = _mm256_setzero_ps(); 319 for (int b = 0; b < nb; b++) { 320 const uint8_t* blk = row + (size_t)b * 144; 321 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8)); 322 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8)); 323 const uint8_t* scales = blk + 4; 324 const uint8_t* q = blk + 16; 325 int x_off = b * 256; 326 int is = 0; 327 for (int j = 0; j < 256; j += 64) { 328 uint8_t sc, m; 329 float d1, d2, m1, m2; 330 get_scale_min_k4(is+0, scales, &sc, &m); d1 = d*sc; m1 = min*m; 331 get_scale_min_k4(is+1, scales, &sc, &m); d2 = d*sc; m2 = min*m; 332 __m256 d1v = _mm256_set1_ps(d1), d2v = _mm256_set1_ps(d2); 333 __m256 m1v = _mm256_set1_ps(m1), m2v = _mm256_set1_ps(m2); 334 __m256i mask4 = _mm256_set1_epi32(0xF); 335 /* Lo nibbles */ 336 for (int l = 0; l < 32; l += 8) { 337 __m256i qi = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(q+l))); 338 __m256 fv = _mm256_sub_ps(_mm256_mul_ps(d1v, _mm256_cvtepi32_ps(_mm256_and_si256(qi, mask4))), m1v); 339 acc = _mm256_fmadd_ps(fv, _mm256_loadu_ps(x + x_off + j + l), acc); 340 } 341 /* Hi nibbles */ 342 for (int l = 0; l < 32; l += 8) { 343 __m256i qi = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(q+l))); 344 __m256 fv = _mm256_sub_ps(_mm256_mul_ps(d2v, _mm256_cvtepi32_ps(_mm256_srli_epi32(_mm256_and_si256(qi, _mm256_set1_epi32(0xFF)), 4))), m2v); 345 acc = _mm256_fmadd_ps(fv, _mm256_loadu_ps(x + x_off + j + 32 + l), acc); 346 } 347 q += 32; is += 2; 348 } 349 } 350 out[r] = hsum_ps(acc); 351 } 352 } 353 354 /* ── Q5_K matmul (176 bytes per 256 values) ── */ 355 static void q5_k_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 356 int nb = ncols / 256; 357 #pragma omp parallel for schedule(static) 358 for (int r = 0; r < nrows; r++) { 359 const uint8_t* row = W + (size_t)r * nb * 176; 360 __m256 acc = _mm256_setzero_ps(); 361 for (int b = 0; b < nb; b++) { 362 const uint8_t* blk = row + (size_t)b * 176; 363 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8)); 364 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8)); 365 const uint8_t* scales = blk + 4; 366 const uint8_t* qh = blk + 16; 367 const uint8_t* ql = blk + 48; 368 int x_off = b * 256; 369 int is = 0; 370 uint8_t u1 = 1, u2 = 2; 371 for (int j = 0; j < 256; j += 64) { 372 uint8_t sc, m; 373 float d1, d2, m1, m2; 374 get_scale_min_k4(is+0, scales, &sc, &m); d1 = d*sc; m1 = min*m; 375 get_scale_min_k4(is+1, scales, &sc, &m); d2 = d*sc; m2 = min*m; 376 __m256 d1v = _mm256_set1_ps(d1), d2v = _mm256_set1_ps(d2); 377 __m256 m1v = _mm256_set1_ps(m1), m2v = _mm256_set1_ps(m2); 378 __m256i u1v = _mm256_set1_epi32(u1), u2v = _mm256_set1_epi32(u2); 379 /* Lo+5th bit */ 380 for (int l = 0; l < 32; l += 8) { 381 __m256i qi = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(ql+l))); 382 __m256i qh8 = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(qh+l))); 383 __m256 fv = _mm256_sub_ps(_mm256_mul_ps(d1v, _mm256_cvtepi32_ps( 384 _mm256_add_epi32(_mm256_and_si256(qi, _mm256_set1_epi32(0xF)), 385 _mm256_slli_epi32(_mm256_and_si256(qh8, u1v), 1)))), m1v); 386 acc = _mm256_fmadd_ps(fv, _mm256_loadu_ps(x + x_off + j + l), acc); 387 } 388 /* Hi+5th bit */ 389 for (int l = 0; l < 32; l += 8) { 390 __m256i qi = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(ql+l))); 391 __m256i qh8 = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(qh+l))); 392 __m256 fv = _mm256_sub_ps(_mm256_mul_ps(d2v, _mm256_cvtepi32_ps( 393 _mm256_add_epi32(_mm256_srli_epi32(_mm256_and_si256(qi, _mm256_set1_epi32(0xFF)), 4), 394 _mm256_slli_epi32(_mm256_and_si256(qh8, u2v), 1)))), m2v); 395 acc = _mm256_fmadd_ps(fv, _mm256_loadu_ps(x + x_off + j + 32 + l), acc); 396 } 397 ql += 32; is += 2; u1 <<= 2; u2 <<= 2; 398 } 399 } 400 out[r] = hsum_ps(acc); 401 } 402 } 403 404 /* ── Q6_K matmul (210 bytes per 256 values) ── */ 405 static void q6_k_matmul(const uint8_t* W, const float* x, float* out, int nrows, int ncols) { 406 int nb = ncols / 256; 407 #pragma omp parallel for schedule(static) 408 for (int r = 0; r < nrows; r++) { 409 const uint8_t* row = W + (size_t)r * nb * 210; 410 __m256 acc = _mm256_setzero_ps(); 411 for (int b = 0; b < nb; b++) { 412 const uint8_t* blk = row + (size_t)b * 210; 413 float d = f16_to_f32((uint16_t)blk[208] | ((uint16_t)blk[209] << 8)); 414 const int8_t* sc = (const int8_t*)(blk + 192); 415 const uint8_t* ql = blk; 416 const uint8_t* qh = blk + 128; 417 int base = b * 256; 418 for (int n = 0; n < 256; n += 128) { 419 for (int l = 0; l < 32; l += 8) { 420 int is_ = l / 16; 421 __m256i ql_lo = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(ql + l))); 422 __m256i ql_hi = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(ql + l + 32))); 423 __m256i qh8 = _mm256_cvtepu8_epi32(_mm_loadl_epi64((__m128i*)(qh + l))); 424 __m256i mask4 = _mm256_set1_epi32(0xF); 425 __m256i mask3 = _mm256_set1_epi32(3); 426 __m256i off32 = _mm256_set1_epi32(32); 427 428 __m256i q1 = _mm256_add_epi32(_mm256_and_si256(ql_lo, mask4), 429 _mm256_slli_epi32(_mm256_and_si256(qh8, mask3), 4)); 430 __m256i q2 = _mm256_add_epi32(_mm256_and_si256(ql_hi, mask4), 431 _mm256_slli_epi32(_mm256_and_si256(_mm256_srli_epi32(qh8, 2), mask3), 4)); 432 __m256i q3 = _mm256_add_epi32(_mm256_srli_epi32(_mm256_and_si256(ql_lo, _mm256_set1_epi32(0xFF)), 4), 433 _mm256_slli_epi32(_mm256_and_si256(_mm256_srli_epi32(qh8, 4), mask3), 4)); 434 __m256i q4 = _mm256_add_epi32(_mm256_srli_epi32(_mm256_and_si256(ql_hi, _mm256_set1_epi32(0xFF)), 4), 435 _mm256_slli_epi32(_mm256_and_si256(_mm256_srli_epi32(qh8, 6), mask3), 4)); 436 437 q1 = _mm256_sub_epi32(q1, off32); 438 q2 = _mm256_sub_epi32(q2, off32); 439 q3 = _mm256_sub_epi32(q3, off32); 440 q4 = _mm256_sub_epi32(q4, off32); 441 442 acc = _mm256_fmadd_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(q1), _mm256_set1_ps(d * sc[is_+0])), 443 _mm256_loadu_ps(x + base + n + l), acc); 444 acc = _mm256_fmadd_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(q2), _mm256_set1_ps(d * sc[is_+2])), 445 _mm256_loadu_ps(x + base + n + l + 32), acc); 446 acc = _mm256_fmadd_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(q3), _mm256_set1_ps(d * sc[is_+4])), 447 _mm256_loadu_ps(x + base + n + l + 64), acc); 448 acc = _mm256_fmadd_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(q4), _mm256_set1_ps(d * sc[is_+6])), 449 _mm256_loadu_ps(x + base + n + l + 96), acc); 450 } 451 ql += 64; qh += 32; sc += 8; 452 } 453 } 454 out[r] = hsum_ps(acc); 455 } 456 } 457 458 /* ── Unified quant matmul dispatch ── */ 459 static void quant_matmul(const WeightDesc* w, const float* x, float* out) { 460 switch (w->qtype) { 461 case GGML_F32: f32_matmul((const float*)w->data, x, out, w->nrows, w->ncols); break; 462 case GGML_Q4_0: q4_0_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 463 case GGML_Q4_1: q4_1_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 464 case GGML_Q8_0: q8_0_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 465 case GGML_Q4_K: q4_k_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 466 case GGML_Q5_K: q5_k_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 467 case GGML_Q6_K: q6_k_matmul((const uint8_t*)w->data, x, out, w->nrows, w->ncols); break; 468 } 469 } 470 471 /* ── Apply RoPE to Q and K vectors ── */ 472 static void apply_rope(float* vec, int pos, int n_heads, int head_dim, 473 float rope_freq_base) { 474 int half = head_dim / 2; 475 for (int h = 0; h < n_heads; h++) { 476 float* v = vec + h * head_dim; 477 for (int i = 0; i < half; i++) { 478 float freq = powf(rope_freq_base, -2.0f * i / head_dim); 479 float angle = pos * freq; 480 float cos_a = cosf(angle); 481 float sin_a = sinf(angle); 482 float x0 = v[i]; 483 float x1 = v[i + half]; 484 v[i] = x0 * cos_a - x1 * sin_a; 485 v[i + half] = x1 * cos_a + x0 * sin_a; 486 } 487 } 488 } 489 490 /* ── Per-head RMS norm (Qwen3 QK norm) ── */ 491 static void per_head_rms_norm(float* vec, const float* w, int n_heads, int head_dim, float eps) { 492 for (int h = 0; h < n_heads; h++) { 493 float* v = vec + h * head_dim; 494 float ss = 0.0f; 495 for (int i = 0; i < head_dim; i++) ss += v[i] * v[i]; 496 float inv_rms = 1.0f / sqrtf(ss / head_dim + eps); 497 for (int i = 0; i < head_dim; i++) v[i] = v[i] * inv_rms * w[i]; 498 } 499 } 500 501 /* ══════════════════════════════════════════════════════════════════════════ 502 * Full transformer forward pass — single C call per token 503 * ══════════════════════════════════════════════════════════════════════════ */ 504 505 void turbo_forward(ForwardState* st, ModelDesc* model, int token_id, float* logits_out) { 506 int N = model->n_embd; 507 int NH = model->n_head; 508 int NKH = model->n_kv_head; 509 int HD = model->head_dim; 510 int L = model->n_layers; 511 int pos = st->pos; 512 513 /* ── Embedding lookup ── */ 514 /* token_embd is [vocab_size, n_embd] */ 515 float* embd = (float*)model->token_embd.data; 516 memcpy(st->h, embd + (size_t)token_id * N, N * sizeof(float)); 517 518 for (int i = 0; i < L; i++) { 519 LayerDesc* layer = &model->layers[i]; 520 521 /* ── Attention ── */ 522 memcpy(st->residual, st->h, N * sizeof(float)); 523 rms_norm(st->h, (float*)layer->attn_norm.data, st->h, N, model->eps); 524 525 /* Q/K/V projections */ 526 quant_matmul(&layer->attn_q, st->h, st->q); 527 quant_matmul(&layer->attn_k, st->h, st->k); 528 529 /* Per-head QK norm (Qwen3) */ 530 if (layer->attn_q_norm.data) { 531 per_head_rms_norm(st->q, (float*)layer->attn_q_norm.data, NH, HD, model->eps); 532 } 533 if (layer->attn_k_norm.data) { 534 per_head_rms_norm(st->k, (float*)layer->attn_k_norm.data, NKH, HD, model->eps); 535 } 536 537 /* V projection */ 538 quant_matmul(&layer->attn_v, st->h, st->v); 539 540 /* RoPE */ 541 apply_rope(st->q, pos, NH, HD, model->rope_freq_base); 542 apply_rope(st->k, pos, NKH, HD, model->rope_freq_base); 543 544 /* KV cache */ 545 int kv_dim = NKH * HD; 546 memcpy(st->kv_k + (size_t)i * st->max_pos * kv_dim + (size_t)st->kv_len[i] * kv_dim, 547 st->k, kv_dim * sizeof(float)); 548 memcpy(st->kv_v + (size_t)i * st->max_pos * kv_dim + (size_t)st->kv_len[i] * kv_dim, 549 st->v, kv_dim * sizeof(float)); 550 551 /* GQA attention */ 552 int seq_len = st->kv_len[i] + 1; 553 float scale = 1.0f / sqrtf((float)HD); 554 int n_rep = NH / NKH; 555 556 memset(st->att_out, 0, NH * HD * sizeof(float)); 557 558 for (int h = 0; h < NH; h++) { 559 int kv_h = h / n_rep; /* which KV head this Q head maps to */ 560 float* q_vec = st->q + h * HD; 561 562 /* Compute attention scores for this head */ 563 float* scores_h = st->scores + h * st->max_pos; 564 float max_score = -1e30f; 565 566 for (int s = 0; s < seq_len; s++) { 567 float* k_vec = st->kv_k + (size_t)i * st->max_pos * kv_dim + s * kv_dim + kv_h * HD; 568 float dot = 0.0f; 569 for (int d = 0; d < HD; d++) dot += q_vec[d] * k_vec[d]; 570 scores_h[s] = dot * scale; 571 if (scores_h[s] > max_score) max_score = scores_h[s]; 572 } 573 574 /* Softmax */ 575 float sum = 0.0f; 576 for (int s = 0; s < seq_len; s++) { 577 scores_h[s] = expf(scores_h[s] - max_score); 578 sum += scores_h[s]; 579 } 580 for (int s = 0; s < seq_len; s++) scores_h[s] /= sum; 581 582 /* Weighted sum of V */ 583 float* out_vec = st->att_out + h * HD; 584 for (int s = 0; s < seq_len; s++) { 585 float* v_vec = st->kv_v + (size_t)i * st->max_pos * kv_dim + s * kv_dim + kv_h * HD; 586 float w = scores_h[s]; 587 for (int d = 0; d < HD; d++) out_vec[d] += w * v_vec[d]; 588 } 589 } 590 591 /* Output projection + residual */ 592 quant_matmul(&layer->attn_out, st->att_out, st->h); /* reuse h buffer */ 593 for (int d = 0; d < N; d++) st->h[d] = st->residual[d] + st->h[d]; 594 595 /* ── FFN / MoE ── */ 596 memcpy(st->residual, st->h, N * sizeof(float)); 597 rms_norm(st->h, (float*)layer->ffn_norm.data, st->h, N, model->eps); 598 599 if (layer->is_moe) { 600 /* ── MoE routing ── */ 601 float* gate_scores = st->gate; /* reuse gate buffer for scores */ 602 quant_matmul(&layer->moe_gate_inp, st->h, gate_scores); 603 604 /* Softmax */ 605 int n_exp = layer->n_experts; 606 float max_g = gate_scores[0]; 607 for (int e = 1; e < n_exp; e++) if (gate_scores[e] > max_g) max_g = gate_scores[e]; 608 float sum_g = 0.0f; 609 for (int e = 0; e < n_exp; e++) { gate_scores[e] = expf(gate_scores[e] - max_g); sum_g += gate_scores[e]; } 610 for (int e = 0; e < n_exp; e++) gate_scores[e] /= sum_g; 611 612 /* Top-K selection (simple O(n*k) for small k) */ 613 int top_k = layer->n_experts_per_tok; 614 int top_indices[8]; /* max top_k = 8 */ 615 float top_weights[8]; 616 for (int k = 0; k < top_k; k++) { 617 int best = -1; 618 float best_val = -1e30f; 619 for (int e = 0; e < n_exp; e++) { 620 if (gate_scores[e] > best_val) { best_val = gate_scores[e]; best = e; } 621 } 622 top_indices[k] = best; 623 top_weights[k] = best_val; 624 gate_scores[best] = -1e30f; /* remove from consideration */ 625 } 626 /* Re-normalize */ 627 float tw_sum = 0.0f; 628 for (int k = 0; k < top_k; k++) tw_sum += top_weights[k]; 629 for (int k = 0; k < top_k; k++) top_weights[k] /= tw_sum; 630 631 /* Compute selected experts */ 632 int ff_exp = layer->n_ff_expert; 633 memset(st->ffn_out, 0, N * sizeof(float)); 634 635 for (int k = 0; k < top_k; k++) { 636 int eid = top_indices[k]; 637 float w = top_weights[k]; 638 639 /* gate_proj */ 640 quant_matmul(&layer->moe_gate_exps[eid], st->h, st->gate); 641 /* up_proj */ 642 quant_matmul(&layer->moe_up_exps[eid], st->h, st->up); 643 644 /* SiLU(gate) * up */ 645 for (int j = 0; j < ff_exp && j < ff_exp; j++) { 646 st->silu_gate[j] = st->gate[j] / (1.0f + expf(-st->gate[j])) * st->up[j]; 647 } 648 649 /* down_proj */ 650 quant_matmul(&layer->moe_down_exps[eid], st->silu_gate, st->expert_result); 651 652 /* Accumulate weighted */ 653 for (int d = 0; d < N; d++) st->ffn_out[d] += w * st->expert_result[d]; 654 } 655 656 /* Shared expert (Qwen3 MoE) */ 657 if (layer->has_shared_expert) { 658 int shared_ff = layer->shared_down.ncols; /* = 2 * n_ff_expert */ 659 quant_matmul(&layer->shared_gate, st->h, st->gate); 660 quant_matmul(&layer->shared_up, st->h, st->up); 661 int sff = layer->shared_gate.nrows; 662 for (int j = 0; j < sff && j < sff; j++) { 663 st->gate[j] = st->gate[j] / (1.0f + expf(-st->gate[j])); 664 st->gate[j] *= st->up[j]; 665 } 666 quant_matmul(&layer->shared_down, st->gate, st->expert_result); 667 for (int d = 0; d < N; d++) st->ffn_out[d] += st->expert_result[d]; 668 } 669 } else { 670 /* ── Dense FFN (SwiGLU) ── */ 671 int FF = layer->ffn_gate.nrows; 672 quant_matmul(&layer->ffn_gate, st->h, st->gate); 673 quant_matmul(&layer->ffn_up, st->h, st->up); 674 silu_inplace(st->gate, FF); 675 for (int j = 0; j < FF; j++) st->silu_gate[j] = st->gate[j] * st->up[j]; 676 quant_matmul(&layer->ffn_down, st->silu_gate, st->ffn_out); 677 } 678 679 /* Residual connection */ 680 for (int d = 0; d < N; d++) st->h[d] = st->residual[d] + st->ffn_out[d]; 681 682 st->kv_len[i]++; 683 } 684 685 /* ── Final norm + output projection ── */ 686 rms_norm(st->h, (float*)model->output_norm.data, st->h, N, model->eps); 687 quant_matmul(&model->output_weight, st->h, logits_out); 688 st->pos++; 689 } 690 691 /* ── Helper: compute rope table ── */ 692 void compute_rope_table(float* cos_table, float* sin_table, 693 int max_pos, int head_dim, float freq_base) { 694 for (int p = 0; p < max_pos; p++) { 695 for (int i = 0; i < head_dim / 2; i++) { 696 float freq = powf(freq_base, -2.0f * i / head_dim); 697 float angle = p * freq; 698 cos_table[p * (head_dim/2) + i] = cosf(angle); 699 sin_table[p * (head_dim/2) + i] = sinf(angle); 700 } 701 } 702 } 703 704 /* ── Utility: get/set OMP threads ── */ 705 int get_max_threads(void) { return omp_get_max_threads(); } 706 void set_num_threads(int n) { omp_set_num_threads(n); }