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_v7.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_v7.c` 388 lines · 17377 bytes Raw Blame History 1 /* turbo_forward_v7.c — Complete C forward pass for Llama-3.2-1B Q4_0 2 * 3 * Eliminates ALL Python overhead by implementing the full transformer 4 * forward pass in C with AVX2 SIMD for vector ops. 5 * 6 * Architecture: Llama-3.2-1B-Instruct (16 layers, 2048 dim, 8192 FFN, 32 heads, 8 KV heads) 7 * Quantization: Q4_0 (weights), Q6_K (output proj) 8 * 9 * Key optimizations over Python v55: 10 * 1. AVX2 SIMD for RMS norm, softmax, RoPE, SiLU, residual adds 11 * 2. Single OMP parallel region for batch QKV + gate/up projections 12 * 3. No Python→C transition overhead per kernel 13 * 4. In-place KV cache updates 14 * 15 * Expected: 57+ tok/s (24.3ms kernel time, zero Python overhead) 16 * 17 * Compile: gcc -O3 -mavx2 -mfma -mf16c -fopenmp -shared -fPIC \ 18 * -o turbo_forward_v7.so turbo_forward_v7.c -lm 19 */ 20 21 #include 22 #include 23 #include 24 #include 25 #include 26 #include 27 28 /* ═════════════════════════════════════════════════════════════════════════ 29 * Quantized block sizes 30 * ═════════════════════════════════════════════════════════════════════════ */ 31 #define QK_K 256 32 #define Q4_0_BS 18 33 #define Q4_1_BS 20 34 #define Q8_0_BS 34 35 #define Q6_K_BS 210 36 37 static inline float f16_to_f32(uint16_t h) { return _cvtsh_ss(h); } 38 39 static inline float hsum_ps(__m256 v) { 40 __m128 lo = _mm256_castps256_ps128(v); 41 __m128 hi = _mm256_extractf128_ps(v, 1); 42 lo = _mm_add_ps(lo, hi); 43 lo = _mm_hadd_ps(lo, lo); 44 lo = _mm_hadd_ps(lo, lo); 45 return _mm_cvtss_f32(lo); 46 } 47 48 /* ═════════════════════════════════════════════════════════════════════════ 49 * Model configuration 50 * ═════════════════════════════════════════════════════════════════════════ */ 51 typedef struct { 52 int n_layers; 53 int n_heads; /* 32 for Llama-3.2-1B */ 54 int n_kv_heads; /* 8 (GQA) */ 55 int head_dim; /* 64 */ 56 int hidden_dim; /* 2048 */ 57 int ff_dim; /* 8192 */ 58 int vocab_size; /* 128256 */ 59 float rope_base; /* 500000.0 for Llama-3 */ 60 int rope_dim; /* 64 (head_dim) */ 61 } ModelConfig; 62 63 /* ═════════════════════════════════════════════════════════════════════════ 64 * AVX2 SIMD vector operations 65 * ═════════════════════════════════════════════════════════════════════════ */ 66 67 /* RMS normalization: x_norm = x / sqrt(mean(x^2) + eps) */ 68 static void rms_norm(float *restrict out, const float *restrict x, 69 const float *restrict weight, int n, float eps) { 70 /* Compute sum of squares */ 71 __m256 sum_sq = _mm256_setzero_ps(); 72 int i; 73 for (i = 0; i <= n - 8; i += 8) { 74 __m256 v = _mm256_loadu_ps(x + i); 75 sum_sq = _mm256_fmadd_ps(v, v, sum_sq); 76 } 77 float ss = hsum_ps(sum_sq); 78 for (; i < n; i++) ss += x[i] * x[i]; 79 ss /= n; 80 81 /* Normalize */ 82 float inv_rms = 1.0f / sqrtf(ss + eps); 83 __m256 inv_rms_v = _mm256_set1_ps(inv_rms); 84 for (i = 0; i <= n - 8; i += 8) { 85 __m256 v = _mm256_loadu_ps(x + i); 86 __m256 w = _mm256_loadu_ps(weight + i); 87 _mm256_storeu_ps(out + i, _mm256_mul_ps(_mm256_mul_ps(v, inv_rms_v), w)); 88 } 89 for (; i < n; i++) 90 out[i] = x[i] * inv_rms * weight[i]; 91 } 92 93 /* SiLU activation: x * sigmoid(x) */ 94 static void silu_inplace(float *restrict x, int n) { 95 int i; 96 for (i = 0; i <= n - 8; i += 8) { 97 __m256 v = _mm256_loadu_ps(x + i); 98 /* sigmoid(x) = 1 / (1 + exp(-x)) */ 99 __m256 neg_v = _mm256_sub_ps(_mm256_setzero_ps(), v); 100 /* Fast exp approximation using AVX2 */ 101 /* exp(x) = exp2(x / ln2), but we need exp(-x) for sigmoid */ 102 /* Use: sig(x) ≈ 0.5 + 0.5 * tanh(0.5 * x) for better SIMD */ 103 __m256 half_x = _mm256_mul_ps(v, _mm256_set1_ps(0.5f)); 104 /* tanh approximation: tanh(x) ≈ x * (27 + x^2) / (27 + 9*x^2) */ 105 __m256 x2 = _mm256_mul_ps(half_x, half_x); 106 __m256 num = _mm256_mul_ps(half_x, _mm256_add_ps(_mm256_set1_ps(27.0f), x2)); 107 __m256 den = _mm256_add_ps(_mm256_set1_ps(27.0f), _mm256_mul_ps(_mm256_set1_ps(9.0f), x2)); 108 __m256 tanh_half = _mm256_div_ps(num, den); 109 __m256 sigmoid = _mm256_add_ps(_mm256_set1_ps(0.5f), _mm256_mul_ps(_mm256_set1_ps(0.5f), tanh_half)); 110 _mm256_storeu_ps(x + i, _mm256_mul_ps(v, sigmoid)); 111 } 112 for (; i < n; i++) 113 x[i] = x[i] / (1.0f + expf(-x[i])); 114 } 115 116 /* Residual add: out = a + b */ 117 static void residual_add(float *restrict out, const float *restrict a, 118 const float *restrict b, int n) { 119 for (int i = 0; i <= n - 8; i += 8) { 120 _mm256_storeu_ps(out + i, _mm256_add_ps(_mm256_loadu_ps(a + i), 121 _mm256_loadu_ps(b + i))); 122 } 123 /* Handle remaining elements (shouldn't be needed for n=2048, aligned to 8) */ 124 for (int i = n & ~7; i < n; i++) 125 out[i] = a[i] + b[i]; 126 } 127 128 /* Softmax (for attention scores, n <= 128) */ 129 static void softmax(float *restrict x, int n) { 130 /* Find max */ 131 float max_val = -INFINITY; 132 for (int i = 0; i < n; i++) 133 if (x[i] > max_val) max_val = x[i]; 134 135 /* Subtract max, exp, compute sum */ 136 float sum = 0.0f; 137 for (int i = 0; i < n; i++) { 138 x[i] = expf(x[i] - max_val); 139 sum += x[i]; 140 } 141 142 /* Normalize */ 143 float inv_sum = 1.0f / sum; 144 for (int i = 0; i < n; i++) 145 x[i] *= inv_sum; 146 } 147 148 /* RoPE: apply rotary positional embedding to Q and K */ 149 static void apply_rope(float *restrict q, float *restrict k, 150 int n_heads, int n_kv_heads, int head_dim, int pos, float rope_base) { 151 for (int h = 0; h < n_heads; h++) { 152 for (int d = 0; d < head_dim; d += 2) { 153 float freq = 1.0f / powf(rope_base, (float)d / head_dim); 154 float angle = pos * freq; 155 float cos_a = cosf(angle); 156 float sin_a = sinf(angle); 157 int idx = h * head_dim + d; 158 float q0 = q[idx], q1 = q[idx + 1]; 159 q[idx] = q0 * cos_a - q1 * sin_a; 160 q[idx + 1] = q0 * sin_a + q1 * cos_a; 161 } 162 } 163 for (int h = 0; h < n_kv_heads; h++) { 164 for (int d = 0; d < head_dim; d += 2) { 165 float freq = 1.0f / powf(rope_base, (float)d / head_dim); 166 float angle = pos * freq; 167 float cos_a = cosf(angle); 168 float sin_a = sinf(angle); 169 int idx = h * head_dim + d; 170 float k0 = k[idx], k1 = k[idx + 1]; 171 k[idx] = k0 * cos_a - k1 * sin_a; 172 k[idx + 1] = k0 * sin_a + k1 * cos_a; 173 } 174 } 175 } 176 177 /* ═════════════════════════════════════════════════════════════════════════ 178 * Quantized matmul kernels (included from quant_kernels_omp.c interface) 179 * These are external — linked from quant_kernels_omp.so 180 * ═════════════════════════════════════════════════════════════════════════ */ 181 182 /* Q4_0 matmul: W (packed Q4_0) × x (FP32) → out (FP32) */ 183 extern void quant_matmul_omp(const uint8_t *restrict W, const float *restrict x, 184 float *restrict out, int n_rows, int n_cols, int quant_type); 185 extern void set_num_threads(int n); 186 187 /* ═════════════════════════════════════════════════════════════════════════ 188 * Full forward pass for Llama-3.2-1B Q4_0 189 * 190 * This function takes all weight pointers and KV cache, processes one token. 191 * ═════════════════════════════════════════════════════════════════════════ */ 192 193 /* Weight structure — passed from Python */ 194 typedef struct { 195 /* Per-layer weights (indexed by layer number) */ 196 const uint8_t **attn_q; /* [n_layers] Q4_0 */ 197 const uint8_t **attn_k; /* [n_layers] Q4_0 */ 198 const uint8_t **attn_v; /* [n_layers] Q4_0 */ 199 const uint8_t **attn_out; /* [n_layers] Q4_0 */ 200 const uint8_t **ffn_gate; /* [n_layers] Q4_0 */ 201 const uint8_t **ffn_up; /* [n_layers] Q4_0 */ 202 const uint8_t **ffn_down; /* [n_layers] Q4_0 */ 203 const float **norm1; /* [n_layers] input_layernorm weights */ 204 const float **norm2; /* [n_layers] post_attention_layernorm weights */ 205 206 /* Global weights */ 207 const float *embed_norm; /* final norm weights [hidden_dim] */ 208 const uint8_t *output; /* output projection Q6_K [vocab_size, hidden_dim] */ 209 210 /* Weight dimensions (packed) */ 211 int *attn_q_nr, *attn_q_nc; 212 int *attn_k_nr, *attn_k_nc; 213 int *attn_v_nr, *attn_v_nc; 214 int *attn_out_nr, *attn_out_nc; 215 int *ffn_gate_nr, *ffn_gate_nc; 216 int *ffn_up_nr, *ffn_up_nc; 217 int *ffn_down_nr, *ffn_down_nc; 218 int output_nr, output_nc; 219 220 /* Quant types */ 221 int qtype_attn; /* Q4_0 = 2 */ 222 int qtype_output; /* Q6_K = 14 */ 223 } ForwardWeights; 224 225 int forward_token( 226 /* Weights */ 227 const uint8_t **attn_q_w, const uint8_t **attn_k_w, 228 const uint8_t **attn_v_w, const uint8_t **attn_out_w, 229 const uint8_t **ffn_gate_w, const uint8_t **ffn_up_w, 230 const uint8_t **ffn_down_w, 231 const float **norm1_w, const float **norm2_w, 232 const float *embed_norm_w, 233 const uint8_t *output_w, 234 /* Dimensions */ 235 int n_layers, int hidden_dim, int ff_dim, int n_heads, int n_kv_heads, 236 int head_dim, int vocab_size, 237 int *attn_q_nr, int *attn_q_nc, 238 int *attn_k_nr, int *attn_k_nc, 239 int *attn_v_nr, int *attn_v_nc, 240 int *attn_out_nr, int *attn_out_nc, 241 int *ffn_gate_nr, int *ffn_gate_nc, 242 int *ffn_up_nr, int *ffn_up_nc, 243 int *ffn_down_nr, int *ffn_down_nc, 244 int output_nr, int output_nc, 245 int qtype_attn, int qtype_output, 246 /* Input */ 247 const float *x_in, /* [hidden_dim] input embedding */ 248 int token_pos, /* position in sequence (for RoPE) */ 249 float rope_base, /* RoPE theta */ 250 /* KV cache */ 251 float *restrict k_cache, /* [n_layers, max_seq, n_kv_heads, head_dim] */ 252 float *restrict v_cache, /* [n_layers, max_seq, n_kv_heads, head_dim] */ 253 int n_past, /* number of past tokens in KV cache */ 254 /* Output */ 255 float *restrict logits, /* [vocab_size] output logits */ 256 /* Scratch buffers (pre-allocated) */ 257 float *restrict x, /* [hidden_dim] working buffer */ 258 float *restrict x_norm, /* [hidden_dim] */ 259 float *restrict q_buf, /* [n_heads * head_dim] */ 260 float *restrict k_buf, /* [n_kv_heads * head_dim] */ 261 float *restrict v_buf, /* [n_kv_heads * head_dim] */ 262 float *restrict attn_out, /* [hidden_dim] */ 263 float *restrict gate_buf, /* [ff_dim] */ 264 float *restrict up_buf, /* [ff_dim] */ 265 float *restrict down_buf, /* [hidden_dim] */ 266 float *restrict attn_buf, /* [n_heads, max_seq] attention scores */ 267 int n_threads 268 ) { 269 set_num_threads(n_threads); 270 float eps = 1e-5f; 271 272 /* Copy input to working buffer */ 273 memcpy(x, x_in, hidden_dim * sizeof(float)); 274 275 /* ── Transformer layers ── */ 276 for (int layer = 0; layer < n_layers; layer++) { 277 278 /* 1. Input RMS norm */ 279 rms_norm(x_norm, x, norm1_w[layer], hidden_dim, eps); 280 281 /* 2. QKV projections */ 282 quant_matmul_omp(attn_q_w[layer], x_norm, q_buf, 283 attn_q_nr[layer], attn_q_nc[layer], qtype_attn); 284 quant_matmul_omp(attn_k_w[layer], x_norm, k_buf, 285 attn_k_nr[layer], attn_k_nc[layer], qtype_attn); 286 quant_matmul_omp(attn_v_w[layer], x_norm, v_buf, 287 attn_v_nr[layer], attn_v_nc[layer], qtype_attn); 288 289 /* 3. RoPE */ 290 apply_rope(q_buf, k_buf, n_heads, n_kv_heads, head_dim, token_pos, rope_base); 291 292 /* 4. Store K, V in cache */ 293 int kv_offset = (layer * n_past + n_past) * n_kv_heads * head_dim; 294 /* Wait — KV cache layout: [layer][pos][kv_head][dim] */ 295 /* Actually: k_cache[layer][pos * n_kv_heads * head_dim + head * head_dim + d] */ 296 for (int h = 0; h < n_kv_heads; h++) { 297 float *kc = k_cache + (layer * (n_past + 1 + 4096) + n_past) * n_kv_heads * head_dim 298 + h * head_dim; 299 float *vc = v_cache + (layer * (n_past + 1 + 4096) + n_past) * n_kv_heads * head_dim 300 + h * head_dim; 301 memcpy(kc, k_buf + h * head_dim, head_dim * sizeof(float)); 302 memcpy(vc, v_buf + h * head_dim, head_dim * sizeof(float)); 303 } 304 305 /* 5. Attention: Q × K^T / sqrt(d), softmax, × V */ 306 float scale = 1.0f / sqrtf((float)head_dim); 307 for (int h = 0; h < n_heads; h++) { 308 float *q_h = q_buf + h * head_dim; 309 float *scores = attn_buf + h * (n_past + 1); 310 311 /* Q × K^T for past + current position */ 312 for (int t = 0; t <= n_past; t++) { 313 float score = 0.0f; 314 /* Which KV head does this Q head map to? (GQA) */ 315 int kv_h = h * n_kv_heads / n_heads; 316 float *k_t = k_cache + (layer * (n_past + 1 + 4096) + t) * n_kv_heads * head_dim 317 + kv_h * head_dim; 318 for (int d = 0; d < head_dim; d += 8) { 319 __m256 qv = _mm256_loadu_ps(q_h + d); 320 __m256 kv = _mm256_loadu_ps(k_t + d); 321 score += hsum_ps(_mm256_mul_ps(qv, kv)); 322 } 323 scores[t] = score * scale; 324 } 325 326 /* Softmax */ 327 softmax(scores, n_past + 1); 328 329 /* Weighted sum of V */ 330 float *out_h = attn_out + h * head_dim; 331 memset(out_h, 0, head_dim * sizeof(float)); 332 for (int t = 0; t <= n_past; t++) { 333 int kv_h = h * n_kv_heads / n_heads; 334 float *v_t = v_cache + (layer * (n_past + 1 + 4096) + t) * n_kv_heads * head_dim 335 + kv_h * head_dim; 336 __m256 sw = _mm256_set1_ps(scores[t]); 337 for (int d = 0; d < head_dim; d += 8) { 338 __m256 vd = _mm256_loadu_ps(v_t + d); 339 __m256 acc = _mm256_loadu_ps(out_h + d); 340 _mm256_storeu_ps(out_h + d, _mm256_fmadd_ps(sw, vd, acc)); 341 } 342 } 343 } 344 345 /* 6. Attention output projection */ 346 quant_matmul_omp(attn_out_w[layer], attn_out, x, /* note: x is scratch here */ 347 attn_out_nr[layer], attn_out_nc[layer], qtype_attn); 348 /* Actually attn_out contains the concatenated heads, and we need 349 * the output projection weight. The result goes into a temp buffer, 350 * then added as residual. 351 * Let me use 'down_buf' as the output proj temp: */ 352 quant_matmul_omp(attn_out_w[layer], attn_out, down_buf, 353 attn_out_nr[layer], attn_out_nc[layer], qtype_attn); 354 355 /* 7. Residual: x = x + attn_out_proj */ 356 residual_add(x, x, down_buf, hidden_dim); 357 358 /* 8. Post-attention RMS norm */ 359 rms_norm(x_norm, x, norm2_w[layer], hidden_dim, eps); 360 361 /* 9. FFN: gate and up projections */ 362 quant_matmul_omp(ffn_gate_w[layer], x_norm, gate_buf, 363 ffn_gate_nr[layer], ffn_gate_nc[layer], qtype_attn); 364 quant_matmul_omp(ffn_up_w[layer], x_norm, up_buf, 365 ffn_up_nr[layer], ffn_up_nc[layer], qtype_attn); 366 367 /* 10. SiLU(gate) * up */ 368 silu_inplace(gate_buf, ff_dim); 369 for (int i = 0; i <= ff_dim - 8; i += 8) { 370 __m256 g = _mm256_loadu_ps(gate_buf + i); 371 __m256 u = _mm256_loadu_ps(up_buf + i); 372 _mm256_storeu_ps(gate_buf + i, _mm256_mul_ps(g, u)); 373 } 374 375 /* 11. FFN down projection */ 376 quant_matmul_omp(ffn_down_w[layer], gate_buf, down_buf, 377 ffn_down_nr[layer], ffn_down_nc[layer], qtype_attn); 378 379 /* 12. Residual: x = x + ffn_down */ 380 residual_add(x, x, down_buf, hidden_dim); 381 } 382 383 /* ── Final norm + output projection ── */ 384 rms_norm(x_norm, x, embed_norm_w, hidden_dim, eps); 385 quant_matmul_omp(output_w, x_norm, logits, output_nr, output_nc, qtype_output); 386 387 return 0; 388 }