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 / ssm_forward.c

389 lines · 15934 bytes Raw Blame History
1/* ── SSM forward for qwen35moe hybrid SSM+Attention ──
2 *
3 * For single-token decode (B=1):
4 * 1. Conv1d (depthwise, kernel_size=4) on input
5 * 2. SSM step: discretize A, update state, apply C
6 * 3. Output gating + down projection
7 *
8 * Compile as part of quant_kernels_omp.so
9 */
10
11#include <stdint.h>
12#include <stdlib.h>
13#include <string.h>
14#include <math.h>
15#include <immintrin.h>
16#include <omp.h>
17
18#ifndef QK_K
19#define QK_K 256
20#endif
21#ifndef Q4_K_BS
22#define Q4_K_BS 144
23#endif
24#ifndef Q8_0_BS
25#define Q8_0_BS 34
26#endif
27
28static inline float hsum_ps_s(__m256 v) {
29 __m128 l = _mm256_castps256_ps128(v), h = _mm256_extractf128_ps(v, 1);
30 l = _mm_add_ps(l, h); l = _mm_hadd_ps(l, l); l = _mm_hadd_ps(l, l);
31 return _mm_cvtss_f32(l);
32}
33
34static inline float f16_to_f32_s(uint16_t h) { return _cvtsh_ss(h); }
35
36/* Softplus: log(1 + exp(x)) */
37static inline float softplus(float x) {
38 if (x > 20.0f) return x;
39 if (x < -20.0f) return 0.0f;
40 return logf(1.0f + expf(x));
41}
42
43/* ── Q8_0 row-dot helper (single row of Q8_0 weight × f32 vec) ── */
44static inline float q8_0_row_dot(const uint8_t *W, const float *x, int n_cols, int row) {
45 int bpr = n_cols / 32;
46 float total = 0.0f;
47 for (int blk = 0; blk < bpr; blk++) {
48 const uint8_t *bp = W + ((size_t)row * bpr + blk) * Q8_0_BS;
49 float sc = f16_to_f32_s((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
50 const int8_t *qs = (const int8_t*)(bp + 2);
51 __m256 sv = _mm256_set1_ps(sc);
52 int o = blk * 32;
53 __m128i q8 = _mm_loadu_si128((const __m128i*)(qs));
54 __m128i q8b = _mm_loadu_si128((const __m128i*)(qs + 16));
55 __m128i q8_lo = q8;
56 __m128i q8_hi = _mm_srli_si128(q8, 8);
57 __m128i q8b_lo = q8b;
58 __m128i q8b_hi = _mm_srli_si128(q8b, 8);
59 __m256 d0 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8_lo)), sv);
60 __m256 d1 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8_hi)), sv);
61 __m256 d2 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8b_lo)), sv);
62 __m256 d3 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8b_hi)), sv);
63 __m256 s01 = _mm256_add_ps(
64 _mm256_mul_ps(d0, _mm256_loadu_ps(x + o)),
65 _mm256_mul_ps(d1, _mm256_loadu_ps(x + o + 8)));
66 __m256 s23 = _mm256_add_ps(
67 _mm256_mul_ps(d2, _mm256_loadu_ps(x + o + 16)),
68 _mm256_mul_ps(d3, _mm256_loadu_ps(x + o + 24)));
69 total += hsum_ps_s(_mm256_add_ps(s01, s23));
70 }
71 return total;
72}
73
74/* ── Q4_K row-dot helper (for Q4_K quantized weight × f32 vec) ── */
75static inline float q4_k_row_dot_ssm(const uint8_t *W, const float *x, int n_cols, int row) {
76 int bpr = n_cols / QK_K;
77 float total = 0.0f;
78 for (int blk = 0; blk < bpr; blk++) {
79 const uint8_t *bp = W + ((size_t)row * bpr + blk) * Q4_K_BS;
80 /* Simplified: use existing q4_k dequant + dot pattern */
81 /* For now, use a scalar fallback */
82 /* This would be optimized with AVX2 but for correctnes we keep it simple */
83 float d = f16_to_f32_s((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
84 float dm = f16_to_f32_s((uint16_t)bp[2] | ((uint16_t)bp[3] << 8));
85 const uint8_t *q = bp + 4; /* qs start after d/dm */
86 const uint8_t *scales = bp + 4 + 128; /* scales after qs */
87 int o = blk * QK_K;
88 for (int g = 0; g < 8; g++) {
89 uint8_t sc, mn;
90 if (g < 4) { sc = scales[g] & 63; mn = scales[g+4] & 63; }
91 else { sc = (scales[g+4] & 0xF) | ((scales[g-4] >> 6) << 4);
92 mn = (scales[g+4] >> 4) | ((scales[g] >> 6) << 4); }
93 float d1 = d * sc, m1 = dm * mn;
94 for (int j = g*32; j < (g+1)*32; j++) {
95 int nib = (q[j/2] >> ((j & 1) * 4)) & 0xF;
96 float val = d1 * (float)(nib - 8) - m1 * 6.0f;
97 total += val * x[o + j];
98 }
99 }
100 }
101 return total;
102}
103
104/* ── Q6_K row-dot helper (for Q6_K quantized weight × f32 vec) ── */
105/* Use a simple scalar version */
106static inline float q6_k_row_dot_ssm(const uint8_t *W, const float *x, int n_cols, int row) {
107 int bpr = n_cols / QK_K;
108 float total = 0.0f;
109 for (int blk = 0; blk < bpr; blk++) {
110 const uint8_t *bp = W + ((size_t)row * bpr + blk) * 210;
111 float d = f16_to_f32_s((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
112 const uint8_t *ql = bp + 2;
113 const uint8_t *qh = bp + 2 + 128;
114 const int8_t *sc = (const int8_t*)(bp + 2 + 128 + 64);
115 int o = blk * QK_K;
116 for (int j = 0; j < QK_K; j++) {
117 int lo = (ql[j/2] >> ((j & 1) * 4)) & 0xF;
118 int hi = ((qh[j/4] >> ((j & 3) * 2)) & 3) << 4;
119 int val = (lo | hi) - 32;
120 float sc_val = d * sc[j/16];
121 total += sc_val * (float)val * x[o + j];
122 }
123 }
124 return total;
125}
126
127/* Helper: dequantize single Q8_0 row to float buffer */
128static inline void dequantize_q8_0_row(const uint8_t *W, float *dst, int n_cols, int row) {
129 int bpr = n_cols / 32;
130 for (int blk = 0; blk < bpr; blk++) {
131 const uint8_t *bp = W + ((size_t)row * bpr + blk) * Q8_0_BS;
132 float sc = f16_to_f32_s((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
133 const int8_t *qs = (const int8_t*)(bp + 2);
134 __m256 sv = _mm256_set1_ps(sc);
135 int o = blk * 32;
136 __m128i q8 = _mm_loadu_si128((const __m128i*)(qs));
137 __m128i q8b = _mm_loadu_si128((const __m128i*)(qs + 16));
138 __m128i lo = q8, hi = _mm_srli_si128(q8, 8);
139 __m128i lo2 = q8b, hi2 = _mm_srli_si128(q8b, 8);
140 _mm256_storeu_ps(dst + o, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo)), sv));
141 _mm256_storeu_ps(dst + o + 8, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi)), sv));
142 _mm256_storeu_ps(dst + o + 16, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo2)), sv));
143 _mm256_storeu_ps(dst + o + 24, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi2)), sv));
144 }
145}
146
147/* ──────────────────────────────────────────────────────────────────────────
148 * ssm_forward — Single-token SSM layer forward pass for qwen35moe
149 *
150 * This function implements ONE SSM layer for batch=1:
151 *
152 * Input: x_norm (RMS-normed input, n_embd=2048)
153 * Output: out (n_embd=2048)
154 *
155 * Internal steps:
156 * 1. QKV projection: qkv = W_qkv @ x_norm (Q8_0 matmul, output qkv_dim=8192)
157 * 2. Depthwise conv1d: conv_out[i] = qkv[i] * conv_w[0, i] + conv_bias[i]
158 * 3. Split: x_ssm = conv_out[0:inner] (first 4096 dims)
159 * 4. Gate: gate = W_gate @ x_norm (Q8_0 matmul, output inner=4096)
160 * 5. SSM step on x_ssm (groups=16, state_size=128)
161 * 6. y_ssm = y_ssm * silu(gate) (element-wise)
162 * 7. Output: out = W_down @ y_ssm (Q8_0 matmul, output n_embd=2048)
163 *
164 * Parameters:
165 * x_norm - RMS-normed input [n_embd]
166 * out - output buffer [n_embd]
167 * w_qkv - QKV projection weight (Q8_0) [qkv_dim, n_embd]
168 * w_gate - Gate projection weight (Q8_0) [inner, n_embd]
169 * w_down - Output projection weight (Q8_0) [n_embd, inner]
170 * conv_w - Depthwise conv1d weights [conv_kernel, qkv_dim] F32
171 * ssm_state - SSM state buffer [groups * state_size] (persistent)
172 * ssm_a - A_log parameters [dt_rank] F32
173 * ssm_alpha - B_proj weights [groups*state_size, dt_rank] F32
174 * ssm_beta - C_proj weights [groups*state_size, dt_rank] F32
175 * ssm_dt_bias - dt bias [dt_rank] F32
176 * n_embd, inner, qkv_dim, groups, state_size, conv_kernel, dt_rank
177 * qt_qkv, qt_gate, qt_down - quant types for Q8_0 matmuls
178 * gate_row_dot_fn, down_row_dot_fn - function pointers for row-dot
179 * ────────────────────────────────────────────────────────────────────────── */
180void ssm_forward(
181 const float *x_norm,
182 float *out,
183 const uint8_t *w_qkv,
184 const uint8_t *w_gate,
185 const uint8_t *w_down,
186 const float *conv_w,
187 float *ssm_state,
188 const float *ssm_a,
189 const float *ssm_alpha,
190 const float *ssm_beta,
191 const float *ssm_dt_bias,
192 int n_embd,
193 int inner,
194 int qkv_dim,
195 int groups,
196 int state_size,
197 int conv_kernel,
198 int dt_rank,
199 int qt_qkv,
200 int qt_gate,
201 int qt_down
202) {
203 /* Temporary buffers on stack (sizes known at compile time for qwen35moe) */
204 /* qkv output: qkv_dim = ~8192, inner = ~4096 */
205 /* Allocate on heap for safety with large sizes */
206 float *qkv = (float*)malloc(qkv_dim * sizeof(float));
207 float *gate = (float*)malloc(inner * sizeof(float));
208 float *x_ssm = (float*)malloc(inner * sizeof(float));
209 float *gate_silu = (float*)malloc(inner * sizeof(float));
210 float *y_mid = (float*)malloc(inner * sizeof(float));
211
212 if (!qkv || !gate || !x_ssm || !gate_silu || !y_mid) {
213 free(qkv); free(gate); free(x_ssm); free(gate_silu); free(y_mid);
214 return;
215 }
216
217 /* ── Step 1: QKV projection ── */
218 /* Dequantize w_qkv rows and compute dot products */
219 #pragma omp parallel for schedule(static, 32)
220 for (int r = 0; r < qkv_dim; r++) {
221 if (qt_qkv == 8) {
222 qkv[r] = q8_0_row_dot(w_qkv, x_norm, n_embd, r);
223 } else {
224 qkv[r] = 0.0f;
225 }
226 }
227
228 /* ── Step 2: Depthwise conv1d (single-token: only first kernel element) ── */
229 /* conv_w shape: [conv_kernel, qkv_dim], we use conv_w[0][i] */
230 for (int i = 0; i < qkv_dim; i++) {
231 qkv[i] = qkv[i] * conv_w[i]; /* conv_w is stored as flat [qkv_dim] (first kernel row) */
232 }
233
234 /* ── Step 3: Split — take first `inner` dims as SSM input ── */
235 memcpy(x_ssm, qkv, inner * sizeof(float));
236
237 /* ── Step 4: Gate projection ── */
238 #pragma omp parallel for schedule(static, 32)
239 for (int r = 0; r < inner; r++) {
240 if (qt_gate == 8) {
241 gate[r] = q8_0_row_dot(w_gate, x_norm, n_embd, r);
242 } else if (qt_gate == 12) {
243 gate[r] = q4_k_row_dot_ssm(w_gate, x_norm, n_embd, r);
244 } else {
245 gate[r] = 0.0f;
246 }
247 }
248
249 /* ── Step 4.5: SiLU gate ── */
250 #pragma omp parallel for schedule(static)
251 for (int i = 0; i < inner; i++) {
252 float g = gate[i];
253 gate_silu[i] = g / (1.0f + expf(-g));
254 }
255
256 /* ── Step 5: SSM step ── */
257 /* For each group:
258 * - Compute x_dt = projection of x_ssm group to dt_rank
259 * In qwen35moe, dt_proj uses ssm_alpha @ x_norm (not x_ssm)
260 * x_dt[dt] = sum_j ssm_alpha[g*state_size + s, dt] * x_norm[j] -- per group?
261 *
262 * Actually, simpler: dt and B, C all use the same dt_rank-dim projection of x_norm
263 */
264 float x_dt[128]; /* max dt_rank, safe allocation */
265 memset(x_dt, 0, dt_rank * sizeof(float));
266
267 /* Project x_norm to dt_rank using ssm_alpha as the dt_proj */
268 /* ssm_alpha has shape [groups*state_size, dt_rank] = [2048, 32]
269 * We use the FIRST dt_rank rows? Or average over all groups?
270 * For simplicity: use the mean projection over the first group's state dims
271 */
272 for (int d = 0; d < dt_rank; d++) {
273 float sum = 0.0f;
274 /* Use first group's first state dimension as dt projection */
275 for (int j = 0; j < n_embd && j < dt_rank * 16; j++) {
276 /* Per-group projection would be ssm_alpha[group*state_size + state, dt] */
277 /* Simplified: average over groups */
278 sum += ssm_alpha[j % (groups * state_size) * dt_rank + d] * x_norm[j % n_embd];
279 }
280 /* Better: use the ssm_alpha weights more directly */
281 /* For now use a simple average approximation */
282 x_dt[d] = 0.0f;
283 for (int j = 0; j < n_embd; j++) {
284 x_dt[d] += ssm_alpha[(j % groups) * state_size + (j / 16) % state_size] * x_norm[j];
285 }
286 }
287
288 /* This is a SIMPLIFIED SSM step for single-token decode */
289 float dt[128];
290 /* Compute dt for each dt_rank dimension */
291 for (int d = 0; d < dt_rank; d++) {
292 float dt_raw = ssm_dt_bias[d] + x_dt[d];
293 dt[d] = softplus(dt_raw);
294 }
295
296 /* Per-group SSM update */
297 int per_group_state = state_size; /* state size per group */
298 int per_group_inner = inner / groups; /* input dims per group */
299
300 #pragma omp parallel for schedule(static)
301 for (int g = 0; g < groups; g++) {
302 float *state_g = ssm_state + g * per_group_state;
303 float *x_g = x_ssm + g * per_group_inner;
304 float *y_g = y_mid + g * per_group_inner;
305
306 /* Compute B = B_proj_g @ x_dt (B_proj shape: [state_size, dt_rank]) */
307 float B[128]; /* max state_size */
308 for (int s = 0; s < per_group_state; s++) {
309 B[s] = 0.0f;
310 for (int d = 0; d < dt_rank; d++) {
311 B[s] += ssm_alpha[(g * per_group_state + s) * dt_rank + d] * x_dt[d];
312 }
313 }
314
315 /* Compute C = C_proj_g @ x_dt (C shape: [state_size] for each group)
316 * For qwen35moe, C produces per_group_inner output dims.
317 * We use ssm_beta as C_proj same way as B.
318 * But for the output dimension, we project state with C and use x_g as scale.
319 */
320 float C[128];
321 for (int s = 0; s < per_group_state; s++) {
322 C[s] = 0.0f;
323 for (int d = 0; d < dt_rank; d++) {
324 C[s] += ssm_beta[(g * per_group_state + s) * dt_rank + d] * x_dt[d];
325 }
326 }
327
328 /* A_discrete = exp(A * dt) for all state dimensions */
329 /* ssm_a has [dt_rank] values; spread across state dimensions */
330 float A_discrete[128];
331 for (int s = 0; s < per_group_state; s++) {
332 int a_idx = s % dt_rank; /* Map state dim to dt_rank position */
333 A_discrete[s] = expf(ssm_a[a_idx] * dt[a_idx]);
334 }
335
336 /* Compute input contribution: Bx_g */
337 float Bx[128];
338 float x_g_sum = 0.0f;
339 for (int j = 0; j < per_group_inner; j++) x_g_sum += x_g[j];
340 x_g_sum /= per_group_inner > 0 ? per_group_inner : 1;
341
342 for (int s = 0; s < per_group_state; s++) {
343 Bx[s] = B[s] * x_g_sum * dt[s % dt_rank];
344 }
345
346 /* State update: h = A * h + Bx */
347 for (int s = 0; s < per_group_state; s++) {
348 state_g[s] = A_discrete[s] * state_g[s] + Bx[s];
349 }
350
351 /* Output: y = C * h (scalar per group) then expand to per_group_inner */
352 float y_scalar = 0.0f;
353 for (int s = 0; s < per_group_state; s++) {
354 y_scalar += C[s] * state_g[s];
355 }
356
357 /* Expand scalar to all output dims for this group, modulated by input */
358 for (int j = 0; j < per_group_inner; j++) {
359 y_g[j] = y_scalar * x_g[j]; /* Simple modulation by input */
360 }
361 }
362
363 /* ── Step 6: Output gating ── */
364 #pragma omp parallel for schedule(static)
365 for (int i = 0; i < inner; i++) {
366 y_mid[i] = y_mid[i] * gate_silu[i];
367 }
368
369 /* ── Step 7: Output projection ── */
370 /* Apply w_down (Q8_0) [n_embd, inner] to y_mid[inner] → out[n_embd] */
371 #pragma omp parallel for schedule(static, 32)
372 for (int r = 0; r < n_embd; r++) {
373 if (qt_down == 8) {
374 out[r] = q8_0_row_dot(w_down, y_mid, inner, r);
375 } else if (qt_down == 14) {
376 out[r] = q6_k_row_dot_ssm(w_down, y_mid, inner, r);
377 } else if (qt_down == 12) {
378 out[r] = q4_k_row_dot_ssm(w_down, y_mid, inner, r);
379 } else {
380 out[r] = 0.0f;
381 }
382 }
383
384 free(qkv);
385 free(gate);
386 free(x_ssm);
387 free(gate_silu);
388 free(y_mid);
389}