interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / kernels / legacy-c / layer_forward.c

282 lines · 11837 bytes Raw Blame History
1/* layer_forward.c — Complete per-layer forward pass in C
2 *
3 * Eliminates all Python overhead from the hot path by performing:
4 * RMS norm, QKV matmul, RoPE, KV cache store,
5 * GQA attention (softmax QK^T, weighted V sum),
6 * O projection + residual, RMS norm 2,
7 * Gate+Up matmul, SiLU × multiply, Down projection + residual
8 *
9 * All in a single C call per layer.
10 */
11#include <stdint.h>
12#include <string.h>
13#include <math.h>
14#include <immintrin.h>
15
16/* ═════════════════════════════════════════════════════════════════════════
17 * SIMD helpers (from simd_ops.c)
18 * ═════════════════════════════════════════════════════════════════════════ */
19
20static inline float f16_to_f32(uint16_t h) {
21 __m128i v = _mm_cvtsi32_si128((uint32_t)h);
22 __m128 f = _mm_cvtph_ps(v);
23 return _mm_cvtss_f32(f);
24}
25
26static inline void rms_norm_f32(float *restrict out, const float *restrict x,
27 const float *restrict w, int n, float eps) {
28 float ss = 0.0f;
29 for (int i = 0; i < n; i++) ss += x[i] * x[i];
30 float inv_rms = 1.0f / sqrtf(ss / n + eps);
31 for (int i = 0; i < n; i++) out[i] = x[i] * inv_rms * w[i];
32}
33
34static inline void silu_f32(float *restrict out, const float *restrict x, int n) {
35 for (int i = 0; i < n; i++) {
36 out[i] = x[i] / (1.0f + expf(-x[i]));
37 }
38}
39
40static inline void vec_mul_f32(float *restrict out, const float *restrict a,
41 const float *restrict b, int n) {
42 for (int i = 0; i < n; i++) out[i] = a[i] * b[i];
43}
44
45static inline void vec_add_f32(float *restrict out, const float *restrict a,
46 const float *restrict b, int n) {
47 for (int i = 0; i < n; i++) out[i] = a[i] + b[i];
48}
49
50static inline void apply_rope_f32(float *restrict q, float *restrict k,
51 int pos, int n_head, int n_kv_head, int head_dim) {
52 int half = head_dim / 2;
53 for (int h = 0; h < n_head; h++) {
54 float *qh = q + h * head_dim;
55 for (int j = 0; j < half; j++) {
56 double freq = 1.0 / pow(10000.0, (2.0 * j) / (double)head_dim);
57 double angle = (double)pos * freq;
58 double cos_a = cos(angle);
59 double sin_a = sin(angle);
60 float x0 = qh[j];
61 float x1 = qh[j + half]; /* NOTE: RoPE pairs (j, j+half) NOT (2j, 2j+1) */
62 qh[j] = (float)((double)x0 * cos_a - (double)x1 * sin_a);
63 qh[j + half] = (float)((double)x1 * cos_a + (double)x0 * sin_a);
64 }
65 }
66 for (int h = 0; h < n_kv_head; h++) {
67 float *kh = k + h * head_dim;
68 for (int j = 0; j < half; j++) {
69 double freq = 1.0 / pow(10000.0, (2.0 * j) / (double)head_dim);
70 double angle = (double)pos * freq;
71 double cos_a = cos(angle);
72 double sin_a = sin(angle);
73 float x0 = kh[j];
74 float x1 = kh[j + half];
75 kh[j] = (float)((double)x0 * cos_a - (double)x1 * sin_a);
76 kh[j + half] = (float)((double)x1 * cos_a + (double)x0 * sin_a);
77 }
78 }
79}
80
81/* GQA attention in C — eliminates numpy einsum overhead
82 * q: [n_head, head_dim] (row-major)
83 * k_cache: [seq_len, n_kv_head, head_dim]
84 * v_cache: [seq_len, n_kv_head, head_dim]
85 * out: [n_head * head_dim]
86 * gqa_rep: number of Q heads per KV head (e.g., 4 for Llama-3.2-1B)
87 */
88static inline void gqa_attention_f32(
89 const float *restrict q, const float *restrict k_cache,
90 const float *restrict v_cache, float *restrict out,
91 int seq_len, int n_head, int n_kv_head, int head_dim, int gqa_rep) {
92
93 float scale = 1.0f / sqrtf((float)head_dim);
94 int nq = n_head;
95 int nkv = n_kv_head;
96
97 /* Temporary storage for scores: n_head × seq_len */
98 /* We process one Q head at a time to keep memory footprint small */
99 float *scores = (float *)malloc(seq_len * sizeof(float));
100
101 for (int h = 0; h < nq; h++) {
102 int kv_h = h / gqa_rep; /* which KV head this Q head attends to */
103 const float *qh = q + h * head_dim;
104 const float *kh_base = k_cache + kv_h * head_dim; /* [seq_len, head_dim] stride=nkv*HD */
105 int kv_stride = nkv * head_dim;
106
107 /* Compute scores: Q × K^T / sqrt(d) */
108 float max_score = -1e30f;
109 for (int s = 0; s < seq_len; s++) {
110 const float *ks = kh_base + s * kv_stride;
111 float dot = 0.0f;
112 for (int d = 0; d < head_dim; d++) {
113 dot += qh[d] * ks[d];
114 }
115 scores[s] = dot * scale;
116 if (scores[s] > max_score) max_score = scores[s];
117 }
118
119 /* Softmax */
120 float sum = 0.0f;
121 for (int s = 0; s < seq_len; s++) {
122 scores[s] = expf(scores[s] - max_score);
123 sum += scores[s];
124 }
125 float inv_sum = 1.0f / sum;
126 for (int s = 0; s < seq_len; s++) {
127 scores[s] *= inv_sum;
128 }
129
130 /* Weighted V sum: out[h] = sum_s scores[s] * V[s, kv_h, :] */
131 float *oh = out + h * head_dim;
132 memset(oh, 0, head_dim * sizeof(float));
133 const float *vh_base = v_cache + kv_h * head_dim;
134 for (int s = 0; s < seq_len; s++) {
135 const float *vs = vh_base + s * kv_stride;
136 float w = scores[s];
137 for (int d = 0; d < head_dim; d++) {
138 oh[d] += w * vs[d];
139 }
140 }
141 }
142 free(scores);
143}
144
145/* ═════════════════════════════════════════════════════════════════════════
146 * Extern declarations — matmul kernels from quant_kernels_omp.so
147 * ═════════════════════════════════════════════════════════════════════════ */
148
149extern void quant_matmul_omp(const uint8_t *W, const float *x, float *out,
150 int n_rows, int n_cols, int quant_type);
151extern void batch_qkv_omp(const uint8_t *Wq, const uint8_t *Wk, const uint8_t *Wv,
152 const float *x, float *out_q, float *out_k, float *out_v,
153 int nr_q, int nr_k, int nr_v, int n_cols,
154 int qt_q, int qt_k, int qt_v);
155extern void batch_gate_up_omp(const uint8_t *Wgate, const uint8_t *Wup,
156 const float *x, float *out_gate, float *out_up,
157 int nr_gate, int nr_up, int n_cols,
158 int qt_gate, int qt_up);
159
160/* ═════════════════════════════════════════════════════════════════════════
161 * Layer forward parameters struct
162 * ═════════════════════════════════════════════════════════════════════════ */
163
164typedef struct {
165 /* Weight pointers (quantized) */
166 const uint8_t *attn_q_raw;
167 const uint8_t *attn_k_raw;
168 const uint8_t *attn_v_raw;
169 const uint8_t *attn_out_raw;
170 const uint8_t *ffn_gate_raw;
171 const uint8_t *ffn_up_raw;
172 const uint8_t *ffn_down_raw;
173
174 /* Norm weights */
175 const float *attn_norm_w;
176 const float *ffn_norm_w;
177
178 /* Quant types */
179 int qt_q, qt_k, qt_v, qt_out, qt_gate, qt_up, qt_down;
180
181 /* Dimensions */
182 int nr_q, nr_k, nr_v, nr_out, nr_gate, nr_up, nr_down;
183 int nc; /* n_embd (same for all) */
184
185 /* Flags */
186 int use_c_qkv; /* all 3 QKV use C kernels */
187 int use_c_gate_up; /* both gate+up use C kernels */
188} LayerParams;
189
190/* ═════════════════════════════════════════════════════════════════════════
191 * Full layer forward pass — single C call per layer
192 * ═════════════════════════════════════════════════════════════════════════ */
193
194void layer_forward(
195 const LayerParams *lp,
196 /* Buffers — caller pre-allocates */
197 float *restrict x, /* [n_embd] input/output */
198 float *restrict x_norm, /* [n_embd] temp */
199 float *restrict residual, /* [n_embd] temp */
200 float *restrict q, /* [n_head * head_dim] */
201 float *restrict k, /* [n_kv_head * head_dim] */
202 float *restrict v, /* [n_kv_head * head_dim] */
203 float *restrict att_out, /* [n_head * head_dim] */
204 float *restrict o_proj, /* [n_embd] */
205 float *restrict gate, /* [n_ff] */
206 float *restrict up, /* [n_ff] */
207 float *restrict silu_gate, /* [n_ff] */
208 float *restrict ffn_out, /* [n_embd] */
209 /* KV cache */
210 float *restrict kv_k, /* [max_seq, n_kv_head, head_dim] */
211 float *restrict kv_v, /* [max_seq, n_kv_head, head_dim] */
212 /* Model parameters */
213 int pos, /* current position */
214 int n_embd,
215 int n_head,
216 int n_kv_head,
217 int head_dim,
218 int n_ff,
219 float eps,
220 int kv_len /* current KV cache length (before this token) */
221) {
222 int NKH = n_kv_head * head_dim;
223 int NH = n_head * head_dim;
224 float scale = 1.0f / sqrtf((float)head_dim);
225
226 /* 1. Residual copy */
227 memcpy(residual, x, n_embd * sizeof(float));
228
229 /* 2. RMS norm 1 */
230 rms_norm_f32(x_norm, x, lp->attn_norm_w, n_embd, eps);
231
232 /* 3. QKV projections */
233 if (lp->use_c_qkv) {
234 batch_qkv_omp(lp->attn_q_raw, lp->attn_k_raw, lp->attn_v_raw,
235 x_norm, q, k, v,
236 lp->nr_q, lp->nr_k, lp->nr_v, lp->nc,
237 lp->qt_q, lp->qt_k, lp->qt_v);
238 }
239 /* Fallback for mixed quant types not implemented — use Python path */
240
241 /* 4. RoPE */
242 apply_rope_f32(q, k, pos, n_head, n_kv_head, head_dim);
243
244 /* 5. Store K, V in cache */
245 int kv_idx = kv_len;
246 memcpy(kv_k + kv_idx * NKH, k, NKH * sizeof(float));
247 memcpy(kv_v + kv_idx * NKH, v, NKH * sizeof(float));
248
249 /* 6. GQA Attention */
250 int seq_len = kv_len + 1;
251 int gqa_rep = n_head / n_kv_head;
252 gqa_attention_f32(q, kv_k, kv_v, att_out,
253 seq_len, n_head, n_kv_head, head_dim, gqa_rep);
254
255 /* 7. O projection + residual */
256 quant_matmul_omp(lp->attn_out_raw, att_out, o_proj,
257 lp->nr_out, lp->nc, lp->qt_out);
258 vec_add_f32(x, residual, o_proj, n_embd);
259
260 /* 8. Residual copy */
261 memcpy(residual, x, n_embd * sizeof(float));
262
263 /* 9. RMS norm 2 */
264 rms_norm_f32(x_norm, x, lp->ffn_norm_w, n_embd, eps);
265
266 /* 10. Gate + Up projections */
267 if (lp->use_c_gate_up) {
268 batch_gate_up_omp(lp->ffn_gate_raw, lp->ffn_up_raw,
269 x_norm, gate, up,
270 lp->nr_gate, lp->nr_up, lp->nc,
271 lp->qt_gate, lp->qt_up);
272 }
273
274 /* 11. SiLU(gate) * up */
275 silu_f32(silu_gate, gate, n_ff);
276 vec_mul_f32(silu_gate, silu_gate, up, n_ff);
277
278 /* 12. Down projection + residual */
279 quant_matmul_omp(lp->ffn_down_raw, silu_gate, ffn_out,
280 lp->nr_down, n_ff, lp->qt_down);
281 vec_add_f32(x, residual, ffn_out, n_embd);
282}