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

2289 lines · 103825 bytes Raw Blame History
1/* Unified quantized matmul kernels — AVX2+FMA+OpenMP
2 *
3 * Supports: F32, Q4_0, Q4_1, Q4_K, Q5_K, Q6_K, Q8_0
4 * Plus: rms_norm, silu, softmax, batch_matmul, thread control
5 *
6 * Quant type codes (ggml/GGUF convention):
7 * 0 = F32
8 * 2 = Q4_0 (18 bytes/32 vals)
9 * 3 = Q4_1 (20 bytes/32 vals)
10 * 8 = Q8_0 (34 bytes/32 vals)
11 * 12 = Q4_K (144 bytes/256 vals)
12 * 13 = Q5_K (176 bytes/256 vals)
13 * 14 = Q6_K (210 bytes/256 vals)
14 * 39 = MXFP4 (17 bytes/32 vals)
15 *
16 * Compile: gcc -O3 -mavx2 -mfma -mf16c -fopenmp -shared -fPIC \
17 * -o quant_kernels_omp.so quant_kernels_omp.c -lm
18 */
19
20#include <stdint.h>
21#include <math.h>
22#include <immintrin.h>
23#include <omp.h>
24#include <string.h>
25
26#define QK_K 256
27#define QK8_0 32
28
29/* Block sizes in bytes */
30#define Q4_0_BS 18
31#define Q4_1_BS 20
32#define Q4_K_BS 144
33#define Q5_K_BS 176
34#define Q6_K_BS 210
35#define Q8_0_BS 34
36#define Q5_0_BS 22
37#define MXFP4_BS 17
38
39static inline float f16_to_f32(uint16_t h) { return _cvtsh_ss(h); }
40
41/* Forward declarations for functions called before definition */
42int quantize_row_q8_0(const float *restrict x, uint8_t *restrict q8, int n_cols);
43void q4_k_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
44 float *restrict out, int n_rows, int n_cols);
45void q6_k_matmul_avx2_omp(const uint8_t *restrict W, const float *restrict x,
46 float *restrict out, int n_rows, int n_cols);
47float q4_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x, int n_cols, int row);
48float q5_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x, int n_cols, int row);
49float q6_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x, int n_cols, int row);
50float q4_k_row_dot_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8, int n_cols, int row);
51float q6_k_row_dot_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8, int n_cols, int row);
52
53/* =========================================================================
54 * Q4_K scale/min unpacking (from ggml get_scale_min_k4)
55 *
56 * The 12-byte scales[] array packs 8 (scale, min) pairs using 6 bits each.
57 * Pairs 0..3: scale = scales[0..3] & 63, min = scales[4..7] & 63
58 * Pairs 4..7: scale and min reconstructed from bits of scales[8..11]
59 * plus upper 2 bits of scales[0..3] and scales[4..7].
60 * ======================================================================= */
61
62static inline void get_scale_min_k4(int j, const uint8_t *q,
63 uint8_t *d, uint8_t *m) {
64 if (j < 4) {
65 *d = q[j] & 63;
66 *m = q[j + 4] & 63;
67 } else {
68 *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
69 *m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4);
70 }
71}
72
73/* =========================================================================
74 * Q4_0 / Q4_1 AVX2 decode + dot (from q4_kernel_omp.c)
75 * ======================================================================= */
76
77static inline void decode_q4_0(const uint8_t* bp, __m256 v[4]) {
78 float scale = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
79 __m256 s = _mm256_set1_ps(scale);
80 __m128i nb = _mm_loadu_si128((__m128i*)(bp + 2));
81 __m128i lo = _mm_and_si128(nb, _mm_set1_epi8(15));
82 __m128i hi = _mm_and_si128(_mm_srli_epi16(_mm_and_si128(nb, _mm_set1_epi8((char)0xF0)), 4), _mm_set1_epi8(15));
83 __m128i lo_s = _mm_sub_epi8(lo, _mm_set1_epi8(8));
84 __m128i hi_s = _mm_sub_epi8(hi, _mm_set1_epi8(8));
85 __m128i e00 = _mm_cvtepi8_epi16(lo_s), e01 = _mm_cvtepi8_epi16(_mm_shuffle_epi32(lo_s, 0x4e));
86 __m128i e10 = _mm_cvtepi8_epi16(hi_s), e11 = _mm_cvtepi8_epi16(_mm_shuffle_epi32(hi_s, 0x4e));
87 v[0] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
88 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e00, 0x4e)), _mm_cvtepi16_epi32(e00))), s);
89 v[1] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
90 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e01, 0x4e)), _mm_cvtepi16_epi32(e01))), s);
91 v[2] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
92 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e10, 0x4e)), _mm_cvtepi16_epi32(e10))), s);
93 v[3] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
94 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e11, 0x4e)), _mm_cvtepi16_epi32(e11))), s);
95}
96
97static inline void decode_q4_1(const uint8_t* bp, __m256 v[4]) {
98 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
99 float m = f16_to_f32((uint16_t)bp[2] | ((uint16_t)bp[3] << 8));
100 __m256 d_v = _mm256_set1_ps(d), m_v = _mm256_set1_ps(m);
101 __m128i nb = _mm_loadu_si128((__m128i*)(bp + 4));
102 __m128i lo = _mm_and_si128(nb, _mm_set1_epi8(15));
103 __m128i hi = _mm_and_si128(_mm_srli_epi16(_mm_and_si128(nb, _mm_set1_epi8((char)0xF0)), 4), _mm_set1_epi8(15));
104 __m128i e00 = _mm_cvtepu8_epi16(lo), e01 = _mm_cvtepu8_epi16(_mm_shuffle_epi32(lo, 0x4e));
105 __m128i e10 = _mm_cvtepu8_epi16(hi), e11 = _mm_cvtepu8_epi16(_mm_shuffle_epi32(hi, 0x4e));
106 v[0] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
107 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e00,0x4e)),_mm_cvtepi16_epi32(e00))), d_v, m_v);
108 v[1] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
109 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e01,0x4e)),_mm_cvtepi16_epi32(e01))), d_v, m_v);
110 v[2] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
111 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e10,0x4e)),_mm_cvtepi16_epi32(e10))), d_v, m_v);
112 v[3] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_set_m128i(
113 _mm_cvtepi16_epi32(_mm_shuffle_epi32(e11,0x4e)),_mm_cvtepi16_epi32(e11))), d_v, m_v);
114}
115
116static inline float block_dot_fma(const __m256 v[4], const float* x_base) {
117 __m256 x0 = _mm256_loadu_ps(x_base);
118 __m256 x1 = _mm256_loadu_ps(x_base + 8);
119 __m256 x2 = _mm256_loadu_ps(x_base + 16);
120 __m256 x3 = _mm256_loadu_ps(x_base + 24);
121 __m256 a = _mm256_mul_ps(v[0], x0);
122 a = _mm256_fmadd_ps(v[1], x1, a);
123 a = _mm256_fmadd_ps(v[2], x2, a);
124 a = _mm256_fmadd_ps(v[3], x3, a);
125 __m256 h = _mm256_hadd_ps(a, _mm256_permute2f128_ps(a, a, 1));
126 h = _mm256_hadd_ps(h, h);
127 h = _mm256_hadd_ps(h, h);
128 return _mm256_cvtss_f32(h);
129}
130
131/* =========================================================================
132 * Q4_0 matmul
133 * ======================================================================= */
134
135void q4_0_matmul_omp(const uint8_t *restrict W, const float *restrict x,
136 float *restrict out, int n_rows, int n_cols) {
137 int bpr = n_cols / 32;
138 #pragma omp parallel for schedule(static)
139 for (int r = 0; r < n_rows; r++) {
140 float total = 0.0f;
141 const uint8_t *row = W + (size_t)r * bpr * Q4_0_BS;
142 for (int blk = 0; blk < bpr; blk++) {
143 /* Prefetch next weight block and next activation chunk */
144 if (blk + 1 < bpr) {
145 __builtin_prefetch(row + (blk + 1) * Q4_0_BS, 0, 1);
146 __builtin_prefetch(x + (blk + 1) * 32, 0, 1);
147 }
148 __m256 v[4];
149 decode_q4_0(row + blk * Q4_0_BS, v);
150 total += block_dot_fma(v, x + blk * 32);
151 }
152 out[r] = total;
153 }
154}
155
156/* =========================================================================
157 * Q4_1 matmul
158 * ======================================================================= */
159
160void q4_1_matmul_omp(const uint8_t *restrict W, const float *restrict x,
161 float *restrict out, int n_rows, int n_cols) {
162 int bpr = n_cols / 32;
163 #pragma omp parallel for schedule(static)
164 for (int r = 0; r < n_rows; r++) {
165 float total = 0.0f;
166 const uint8_t *row = W + (size_t)r * bpr * Q4_1_BS;
167 for (int blk = 0; blk < bpr; blk++) {
168 if (blk + 1 < bpr) {
169 __builtin_prefetch(row + (blk + 1) * Q4_1_BS, 0, 1);
170 __builtin_prefetch(x + (blk + 1) * 32, 0, 1);
171 }
172 __m256 v[4];
173 decode_q4_1(row + blk * Q4_1_BS, v);
174 total += block_dot_fma(v, x + blk * 32);
175 }
176 out[r] = total;
177 }
178}
179
180/* =========================================================================
181 * Q4_K matmul (144 bytes per 256 values)
182 *
183 * Block layout:
184 * offset 0: d (fp16, 2 bytes) — super-block scale
185 * offset 2: dmin (fp16, 2 bytes) — super-block min scale
186 * offset 4: scales (12 bytes) — packed 6-bit scale/min pairs
187 * offset 16: qs (128 bytes) — 4-bit quantized values
188 *
189 * Dequantization (per group of 64 values, 4 groups per super-block):
190 * For each group (j = 0, 64, 128, 192):
191 * scale_idx = 2*(j/64)
192 * get_scale_min_k4(scale_idx+0, scales, &sc, &m) → d1=d*sc, m1=min*m
193 * get_scale_min_k4(scale_idx+1, scales, &sc, &m) → d2=d*sc, m2=min*m
194 * pos j+0..j+31: d1 * (qs[l] & 0xF) - m1
195 * pos j+32..j+63: d2 * (qs[l] >> 4) - m2
196 * qs advances by 32 per group
197 * ======================================================================= */
198
199void q4_k_matmul_omp(const uint8_t *restrict W, const float *restrict x,
200 float *restrict out, int n_rows, int n_cols) {
201 int nb_blocks = n_cols / 32;
202 uint8_t x_q8_buf[2048 / 32 * Q8_0_BS]; /* stack alloc for up to 2048 dims */
203 int q8_sz = (size_t)nb_blocks * Q8_0_BS;
204 uint8_t *x_q8 = q8_sz <= sizeof(x_q8_buf) ? x_q8_buf : (uint8_t*)malloc(q8_sz);
205 if (!x_q8) { for (int r = 0; r < n_rows; r++) out[r] = 0.0f; return; }
206 quantize_row_q8_0(x, x_q8, n_cols);
207 q4_k_q8_0_matmul_omp(W, x_q8, out, n_rows, n_cols);
208 if (x_q8 != x_q8_buf) free(x_q8);
209}
210
211/* =========================================================================
212 * Q5_K matmul (176 bytes per 256 values)
213 *
214 * Block layout:
215 * offset 0: d (fp16, 2 bytes)
216 * offset 2: dmin (fp16, 2 bytes)
217 * offset 4: scales (12 bytes)
218 * offset 16: qh (32 bytes) — 5th bit per value (1 bit/value for 256 values)
219 * offset 48: qs (128 bytes) — lower 4 bits per value (nibbles)
220 *
221 * Dequantization: same scales as Q4_K, plus 5th bit from qh.
222 * For each group j (j = 0, 64, 128, 192), with shift counters u1, u2:
223 * u1 starts at 1, u2 starts at 2; after each group u1<<=2, u2<<=2
224 * pos j+0..j+31: d1 * ((qs[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1
225 * pos j+32..j+63: d2 * ((qs[l] >> 4) + (qh[l] & u2 ? 16 : 0)) - m2
226 * ======================================================================= */
227
228/* =========================================================================
229 * Q5_K matmul — AVX2 vectorized dequant + FMA
230 *
231 * Block layout (176 bytes per 256 values):
232 * offset 0: d (fp16, 2 bytes)
233 * offset 2: dmin (fp16, 2 bytes)
234 * offset 4: scales (12 bytes) — packed 6-bit pairs (same as Q4_K)
235 * offset 16: qh (32 bytes) — 1 extra bit per value
236 * offset 48: qs (128 bytes) — lower 4 bits (2 nibbles/byte)
237 *
238 * Each super-block has 4 sub-blocks of 64 values. Each sub-block has 2
239 * scale/min pairs (d1,m1 for lo-nibble, d2,m2 for hi-nibble).
240 *
241 * Q5_K value = (qs nibble) + ((qh & mask) ? 16 : 0)
242 * lo-nibble group mask = u1 (1, 4, 16, 64)
243 * hi-nibble group mask = u2 (2, 8, 32, 128)
244 *
245 * Uses identity: sum((d1*val - m1)*x) = d1*sum(val*x) - m1*sum(x)
246 * ======================================================================= */
247
248/* Q5_K row-dot with AVX2 dequant + FMA (extracted for batch_qkv_omp) */
249float q5_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x,
250 int n_cols, int row) {
251 int nb = n_cols / QK_K;
252 const uint8_t *row_ptr = W + (size_t)row * nb * Q5_K_BS;
253 float sum = 0.0f;
254
255 for (int b = 0; b < nb; b++) {
256 const uint8_t *blk = row_ptr + (size_t)b * Q5_K_BS;
257 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8));
258 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8));
259 const uint8_t *scales = blk + 4;
260 const uint8_t *qh_arr = blk + 16;
261 const uint8_t *qs = blk + 48;
262 int x_off = b * QK_K;
263 int is = 0;
264 uint8_t u1 = 1, u2 = 2;
265
266 for (int j = 0; j < QK_K; j += 64) {
267 uint8_t sc, m;
268 get_scale_min_k4(is + 0, scales, &sc, &m);
269 float d1 = d * (float)sc; float m1 = min * (float)m;
270 get_scale_min_k4(is + 1, scales, &sc, &m);
271 float d2 = d * (float)sc; float m2 = min * (float)m;
272
273 /* ── AVX2: lo-nibble group (32 values) ── */
274 __m256 acc_nx = _mm256_setzero_ps();
275 __m256 acc_x = _mm256_setzero_ps();
276
277 for (int l = 0; l < 32; l += 16) {
278 __m128i qs16 = _mm_loadu_si128((const __m128i*)(qs + l));
279 __m128i nib = _mm_and_si128(qs16, _mm_set1_epi8(0x0F));
280 __m128i qh16 = _mm_loadu_si128((const __m128i*)(qh_arr + l));
281 __m128i qh_test = _mm_and_si128(qh16, _mm_set1_epi8((char)u1));
282 __m128i qh_cond = _mm_cmpeq_epi8(qh_test, _mm_setzero_si128());
283 qh_cond = _mm_xor_si128(qh_cond, _mm_set1_epi8(0xFF));
284 qh_cond = _mm_and_si128(qh_cond, _mm_set1_epi8(16));
285 __m128i val = _mm_or_si128(nib, qh_cond);
286 __m128i v16a = _mm_cvtepu8_epi16(val);
287 __m128i v16b = _mm_cvtepu8_epi16(_mm_shuffle_epi32(val, 0x4e));
288 __m256 vfa = _mm256_cvtepi32_ps(_mm256_set_m128i(
289 _mm_cvtepi16_epi32(_mm_shuffle_epi32(v16a, 0x4e)),
290 _mm_cvtepi16_epi32(v16a)));
291 __m256 vfb = _mm256_cvtepi32_ps(_mm256_set_m128i(
292 _mm_cvtepi16_epi32(_mm_shuffle_epi32(v16b, 0x4e)),
293 _mm_cvtepi16_epi32(v16b)));
294 __m256 xa = _mm256_loadu_ps(x + x_off + j + l);
295 __m256 xb = _mm256_loadu_ps(x + x_off + j + l + 8);
296 acc_nx = _mm256_fmadd_ps(vfa, xa, acc_nx);
297 acc_nx = _mm256_fmadd_ps(vfb, xb, acc_nx);
298 acc_x = _mm256_add_ps(xa, acc_x);
299 acc_x = _mm256_add_ps(xb, acc_x);
300 }
301 __m256 h_nx = _mm256_hadd_ps(acc_nx, _mm256_permute2f128_ps(acc_nx, acc_nx, 1));
302 h_nx = _mm256_hadd_ps(h_nx, h_nx); h_nx = _mm256_hadd_ps(h_nx, h_nx);
303 __m256 h_x = _mm256_hadd_ps(acc_x, _mm256_permute2f128_ps(acc_x, acc_x, 1));
304 h_x = _mm256_hadd_ps(h_x, h_x); h_x = _mm256_hadd_ps(h_x, h_x);
305 sum += d1 * _mm256_cvtss_f32(h_nx) - m1 * _mm256_cvtss_f32(h_x);
306
307 /* ── AVX2: hi-nibble group (32 values) ── */
308 acc_nx = _mm256_setzero_ps();
309 acc_x = _mm256_setzero_ps();
310 for (int l = 0; l < 32; l += 16) {
311 __m128i qs16 = _mm_loadu_si128((const __m128i*)(qs + l));
312 __m128i nib = _mm_and_si128(_mm_srli_epi16(qs16, 4), _mm_set1_epi8(0x0F));
313 __m128i qh16 = _mm_loadu_si128((const __m128i*)(qh_arr + l));
314 __m128i qh_test = _mm_and_si128(qh16, _mm_set1_epi8((char)u2));
315 __m128i qh_cond = _mm_cmpeq_epi8(qh_test, _mm_setzero_si128());
316 qh_cond = _mm_xor_si128(qh_cond, _mm_set1_epi8(0xFF));
317 qh_cond = _mm_and_si128(qh_cond, _mm_set1_epi8(16));
318 __m128i val = _mm_or_si128(nib, qh_cond);
319 __m128i v16a = _mm_cvtepu8_epi16(val);
320 __m128i v16b = _mm_cvtepu8_epi16(_mm_shuffle_epi32(val, 0x4e));
321 __m256 vfa = _mm256_cvtepi32_ps(_mm256_set_m128i(
322 _mm_cvtepi16_epi32(_mm_shuffle_epi32(v16a, 0x4e)),
323 _mm_cvtepi16_epi32(v16a)));
324 __m256 vfb = _mm256_cvtepi32_ps(_mm256_set_m128i(
325 _mm_cvtepi16_epi32(_mm_shuffle_epi32(v16b, 0x4e)),
326 _mm_cvtepi16_epi32(v16b)));
327 __m256 xa = _mm256_loadu_ps(x + x_off + j + 32 + l);
328 __m256 xb = _mm256_loadu_ps(x + x_off + j + 32 + l + 8);
329 acc_nx = _mm256_fmadd_ps(vfa, xa, acc_nx);
330 acc_nx = _mm256_fmadd_ps(vfb, xb, acc_nx);
331 acc_x = _mm256_add_ps(xa, acc_x);
332 acc_x = _mm256_add_ps(xb, acc_x);
333 }
334 h_nx = _mm256_hadd_ps(acc_nx, _mm256_permute2f128_ps(acc_nx, acc_nx, 1));
335 h_nx = _mm256_hadd_ps(h_nx, h_nx); h_nx = _mm256_hadd_ps(h_nx, h_nx);
336 h_x = _mm256_hadd_ps(acc_x, _mm256_permute2f128_ps(acc_x, acc_x, 1));
337 h_x = _mm256_hadd_ps(h_x, h_x); h_x = _mm256_hadd_ps(h_x, h_x);
338 sum += d2 * _mm256_cvtss_f32(h_nx) - m2 * _mm256_cvtss_f32(h_x);
339
340 qs += 32; is += 2; u1 <<= 2; u2 <<= 2;
341 }
342 }
343 return sum;
344}
345
346/* Q5_K matmul — AVX2 vectorized, uses q5_k_row_dot_avx2 per row */
347/* Q5_0 (type 6) */
348void q5_0_matmul_omp(const uint8_t *restrict W, const float *restrict x,
349 float *restrict out, int n_rows, int n_cols);
350float q5_0_row_dot(const uint8_t *row, const float *x, int n_cols);
351/* Q5_0 × Q8_0 activation path */
352void q5_0_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
353 float *restrict out, int n_rows, int n_cols, int B);
354float q5_0_row_dot_q8(const uint8_t *restrict row, const uint8_t *restrict x_q8, int n_cols);
355
356void q5_k_matmul_omp(const uint8_t *restrict W, const float *restrict x,
357 float *restrict out, int n_rows, int n_cols) {
358 int nb = n_cols / QK_K;
359
360 #pragma omp parallel for schedule(static)
361 for (int r = 0; r < n_rows; r++) {
362 out[r] = q5_k_row_dot_avx2(W, x, n_cols, r);
363 }
364}
365
366/* =========================================================================
367 * Q8_0 matmul (34 bytes per 32 values)
368 *
369 * Block layout:
370 * offset 0: d (fp16, 2 bytes) — scale
371 * offset 2: qs (int8_t[32]) — quantized values
372 *
373 * Dequantization: value = d * qs[i]
374 * ======================================================================= */
375
376void q8_0_matmul_omp(const uint8_t *restrict W, const float *restrict x,
377 float *restrict out, int n_rows, int n_cols) {
378 int bpr = n_cols / QK8_0; /* blocks of 32 per row */
379 #pragma omp parallel for schedule(static)
380 for (int r = 0; r < n_rows; r++) {
381 volatile float no_opt_total = 0.0f; /* volatile prevents vectorized overrun */
382 float total = 0.0f;
383 const uint8_t *row = W + (size_t)r * bpr * Q8_0_BS;
384 for (int blk = 0; blk < bpr; blk++) {
385 if (blk + 1 < bpr) {
386 __builtin_prefetch(row + (blk + 1) * Q8_0_BS, 0, 1);
387 __builtin_prefetch(x + (blk + 1) * 32, 0, 1);
388 }
389 const uint8_t *bp = row + blk * Q8_0_BS;
390 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
391 const int8_t *qs = (const int8_t *)(bp + 2);
392 int off = blk * 32;
393 __m256 d_v = _mm256_set1_ps(d);
394
395 /* Process 32 int8 values: 4 groups of 8. */
396 __m256 acc = _mm256_setzero_ps();
397 for (int i = 0; i < 32; i += 8) {
398 __m128i q8 = _mm_loadl_epi64((__m128i*)(qs + i));
399 __m128i q16lo = _mm_cvtepi8_epi16(q8);
400 __m128i q16hi = _mm_cvtepi16_epi32(q16lo);
401 __m128i q16lo2 = _mm_cvtepi16_epi32(_mm_unpackhi_epi64(q16lo, q16lo));
402 __m256 qf = _mm256_cvtepi32_ps(_mm256_set_m128i(q16lo2, q16hi));
403 __m256 xv = _mm256_loadu_ps(x + off + i);
404 acc = _mm256_fmadd_ps(_mm256_mul_ps(qf, d_v), xv, acc);
405 }
406 __m128 hi128 = _mm256_extractf128_ps(acc, 1);
407 __m128 lo128 = _mm256_castps256_ps128(acc);
408 __m128 sum = _mm_add_ps(lo128, hi128);
409 sum = _mm_hadd_ps(sum, sum);
410 sum = _mm_hadd_ps(sum, sum);
411 total += _mm_cvtss_f32(sum);
412 }
413 no_opt_total = total;
414 out[r] = no_opt_total;
415 }
416}
417
418/* V8: Q8_0 × Q8_0 batch matmul — uses VPMADDUBSW for integer dot product.
419 * Takes Q8_0 quantized input (pre-quantized from F32 upstream).
420 * Reads 34 bytes per block for both weight and input, computes int8×int8→int32
421 * via zero-extend to int16 → VPMADDWD → combined scale.
422 * For B>1, each batch item has its own input Q8_0 scale.
423 * ~2x faster than dequant+FMA path (q8_0_matmul_omp) because:
424 * 1. Input reads are 34 bytes/block instead of 128 bytes/block
425 * 2. Integer SIMD (VPMADDWD) is higher throughput than FP dequant+multiply
426 * 3. Combined scale applied once per block instead of per-element
427 */
428void q8_0_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
429 float *restrict out, int n_rows, int n_cols, int B) {
430 int bpr = n_cols / QK8_0; /* blocks of 32 per row */
431 #pragma omp parallel for schedule(static, 8)
432 for (int r = 0; r < n_rows; r++) {
433 float acc_buf[8];
434 float *acc = B <= 8 ? acc_buf : (float*)malloc(B * sizeof(float));
435 for (int b = 0; b < B; b++) acc[b] = 0.0f;
436
437 const uint8_t *row = W + (size_t)r * bpr * Q8_0_BS;
438 for (int blk = 0; blk < bpr; blk++) {
439 if (blk + 1 < bpr) {
440 __builtin_prefetch(row + (blk + 1) * Q8_0_BS, 0, 1);
441 }
442
443 const uint8_t *bp = row + blk * Q8_0_BS;
444 float w_d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
445
446 /* Load weight int8 values: 32 bytes starting at bp[2] */
447 __m256i w_i8 = _mm256_loadu_si256((const __m256i*)(bp + 2));
448
449 /* Split into low/high 16 for sign-extension */
450 __m256i w_lo = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(w_i8));
451 __m256i w_hi = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(w_i8, 1));
452
453 int off = blk * 32;
454 for (int b = 0; b < B; b++) {
455 const uint8_t *xbp = x_q8 + (size_t)b * bpr * Q8_0_BS + blk * Q8_0_BS;
456 float x_d = f16_to_f32((uint16_t)xbp[0] | ((uint16_t)xbp[1] << 8));
457 float combined_sc = w_d * x_d;
458
459 /* Load input int8 values */
460 __m256i x_i8 = _mm256_loadu_si256((const __m256i*)(xbp + 2));
461 __m256i x_lo = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(x_i8));
462 __m256i x_hi = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(x_i8, 1));
463
464 /* VPMADDWD: int16×int16→int32 with adjacent pair summation */
465 __m256i dot = _mm256_add_epi32(
466 _mm256_madd_epi16(w_lo, x_lo),
467 _mm256_madd_epi16(w_hi, x_hi));
468
469 /* Horizontal sum of 8 int32 → single int32 */
470 __m128i sum_hi = _mm256_extracti128_si256(dot, 1);
471 __m128i sum_lo = _mm256_castsi256_si128(dot);
472 sum_lo = _mm_add_epi32(sum_lo, sum_hi);
473 sum_lo = _mm_hadd_epi32(sum_lo, sum_lo);
474 sum_lo = _mm_hadd_epi32(sum_lo, sum_lo);
475 int dot_val = _mm_cvtsi128_si32(sum_lo);
476
477 acc[b] += combined_sc * (float)dot_val;
478 }
479 }
480 for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b];
481 if (B > 8 && acc != acc_buf) free(acc);
482 }
483}
484
485/* =========================================================================
486 * MXFP4 matmul (17 bytes per 32 values)
487 *
488 * Block layout:
489 * q[16] — 32 × 4-bit twos-complement mantissas packed into 16 bytes
490 * e[1] — E8M0 scale exponent (unsigned, bias=127)
491 *
492 * Dequantization: value = nibble_sign_ext * 2^(e - 127)
493 * Optimizations: int-bit-trick scale, FMA, vertical accum, prefetch
494 * ======================================================================= */
495
496/* MXFP4 block structure */
497typedef struct {
498 uint8_t q[16];
499 uint8_t e;
500} block_mxfp4;
501
502void mxfp4_matmul_omp(const uint8_t *restrict W, const float *restrict x,
503 float *restrict out, int n_rows, int n_cols) {
504 int bpr = n_cols / 32; /* blocks of 32 per row */
505
506 #pragma omp parallel for schedule(static)
507 for (int r = 0; r < n_rows; r++) {
508 __m256 acc0 = _mm256_setzero_ps();
509 __m256 acc1 = _mm256_setzero_ps();
510 __m256 acc2 = _mm256_setzero_ps();
511 __m256 acc3 = _mm256_setzero_ps();
512
513 const uint8_t *row = W + (size_t)r * bpr * sizeof(block_mxfp4);
514 for (int blk = 0; blk < bpr; blk++) {
515 int next = blk + 1;
516 if (next < bpr) {
517 __builtin_prefetch(row + next * sizeof(block_mxfp4), 0, 1);
518 }
519
520 const uint8_t *bp = row + blk * sizeof(block_mxfp4);
521 /* E8M0 exponent → IEEE754 float32: 2^(e-127) = float with bits (e << 23) */
522 union { uint32_t u; float f; } sc = { .u = ((uint32_t)bp[16]) << 23 };
523 __m256 sv = _mm256_set1_ps(sc.f);
524
525 __m128i packed = _mm_loadu_si128((const __m128i*)bp);
526 /* Extract lower/upper 4-bit nibbles */
527 __m128i lo = _mm_and_si128(packed, _mm_set1_epi8(0x0F));
528 __m128i hi = _mm_and_si128(_mm_srli_epi16(packed, 4), _mm_set1_epi8(0x0F));
529 /* Sign extend 4-bit to signed int8: nibble >= 8 → nibble - 16 */
530 __m128i sign_lo = _mm_cmpgt_epi8(lo, _mm_set1_epi8(7));
531 __m128i sign_hi = _mm_cmpgt_epi8(hi, _mm_set1_epi8(7));
532 lo = _mm_sub_epi8(lo, _mm_and_si128(sign_lo, _mm_set1_epi8(16)));
533 hi = _mm_sub_epi8(hi, _mm_and_si128(sign_hi, _mm_set1_epi8(16)));
534 /* Interleave to restore natural order */
535 __m128i vals_lo = _mm_unpacklo_epi8(lo, hi);
536 __m128i vals_hi = _mm_unpackhi_epi8(lo, hi);
537
538 /* Dequant + vertical FMA accumulate across 4 quarter-blocks */
539 int o = blk * 32;
540 __m256 d0 = _mm256_mul_ps(
541 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vals_lo)), sv);
542 acc0 = _mm256_fmadd_ps(d0, _mm256_loadu_ps(x + o), acc0);
543
544 __m256 d1 = _mm256_mul_ps(
545 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(
546 _mm_srli_si128(vals_lo, 8))), sv);
547 acc1 = _mm256_fmadd_ps(d1, _mm256_loadu_ps(x + o + 8), acc1);
548
549 __m256 d2 = _mm256_mul_ps(
550 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vals_hi)), sv);
551 acc2 = _mm256_fmadd_ps(d2, _mm256_loadu_ps(x + o + 16), acc2);
552
553 __m256 d3 = _mm256_mul_ps(
554 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(
555 _mm_srli_si128(vals_hi, 8))), sv);
556 acc3 = _mm256_fmadd_ps(d3, _mm256_loadu_ps(x + o + 24), acc3);
557 }
558
559 /* Single horizontal reduction per row */
560 __m128 hi0 = _mm256_extractf128_ps(acc0, 1);
561 __m128 lo0 = _mm256_castps256_ps128(acc0);
562 __m128 hi1 = _mm256_extractf128_ps(acc1, 1);
563 __m128 lo1 = _mm256_castps256_ps128(acc1);
564 __m128 hi2 = _mm256_extractf128_ps(acc2, 1);
565 __m128 lo2 = _mm256_castps256_ps128(acc2);
566 __m128 hi3 = _mm256_extractf128_ps(acc3, 1);
567 __m128 lo3 = _mm256_castps256_ps128(acc3);
568
569 __m128 sum01 = _mm_add_ps(_mm_add_ps(lo0, hi0), _mm_add_ps(lo1, hi1));
570 __m128 sum23 = _mm_add_ps(_mm_add_ps(lo2, hi2), _mm_add_ps(lo3, hi3));
571 __m128 total = _mm_add_ps(sum01, sum23);
572 total = _mm_hadd_ps(total, total);
573 total = _mm_hadd_ps(total, total);
574 out[r] = _mm_cvtss_f32(total);
575 }
576}
577
578/* Scalar row dot for row_range dispatcher (bpr = n_cols / 32) */
579static float mxfp4_row_dot(const uint8_t *restrict W, const float *restrict x,
580 int bpr, int row) {
581 __m256 acc0 = _mm256_setzero_ps();
582 __m256 acc1 = _mm256_setzero_ps();
583 __m256 acc2 = _mm256_setzero_ps();
584 __m256 acc3 = _mm256_setzero_ps();
585 const uint8_t *row_ptr = W + (size_t)row * bpr * sizeof(block_mxfp4);
586 for (int blk = 0; blk < bpr; blk++) {
587 const uint8_t *bp = row_ptr + blk * sizeof(block_mxfp4);
588 union { uint32_t u; float f; } sc = { .u = ((uint32_t)bp[16]) << 23 };
589 __m256 sv = _mm256_set1_ps(sc.f);
590 __m128i packed = _mm_loadu_si128((const __m128i*)bp);
591 __m128i lo = _mm_and_si128(packed, _mm_set1_epi8(0x0F));
592 __m128i hi = _mm_and_si128(_mm_srli_epi16(packed, 4), _mm_set1_epi8(0x0F));
593 __m128i sign_lo = _mm_cmpgt_epi8(lo, _mm_set1_epi8(7));
594 __m128i sign_hi = _mm_cmpgt_epi8(hi, _mm_set1_epi8(7));
595 lo = _mm_sub_epi8(lo, _mm_and_si128(sign_lo, _mm_set1_epi8(16)));
596 hi = _mm_sub_epi8(hi, _mm_and_si128(sign_hi, _mm_set1_epi8(16)));
597 __m128i vals_lo = _mm_unpacklo_epi8(lo, hi);
598 __m128i vals_hi = _mm_unpackhi_epi8(lo, hi);
599 int o = blk * 32;
600 __m256 d0 = _mm256_mul_ps(
601 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vals_lo)), sv);
602 acc0 = _mm256_fmadd_ps(d0, _mm256_loadu_ps(x + o), acc0);
603 __m256 d1 = _mm256_mul_ps(
604 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(vals_lo, 8))), sv);
605 acc1 = _mm256_fmadd_ps(d1, _mm256_loadu_ps(x + o + 8), acc1);
606 __m256 d2 = _mm256_mul_ps(
607 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vals_hi)), sv);
608 acc2 = _mm256_fmadd_ps(d2, _mm256_loadu_ps(x + o + 16), acc2);
609 __m256 d3 = _mm256_mul_ps(
610 _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(vals_hi, 8))), sv);
611 acc3 = _mm256_fmadd_ps(d3, _mm256_loadu_ps(x + o + 24), acc3);
612 }
613 __m128 hi0 = _mm256_extractf128_ps(acc0, 1);
614 __m128 lo0 = _mm256_castps256_ps128(acc0);
615 __m128 hi1 = _mm256_extractf128_ps(acc1, 1);
616 __m128 lo1 = _mm256_castps256_ps128(acc1);
617 __m128 hi2 = _mm256_extractf128_ps(acc2, 1);
618 __m128 lo2 = _mm256_castps256_ps128(acc2);
619 __m128 hi3 = _mm256_extractf128_ps(acc3, 1);
620 __m128 lo3 = _mm256_castps256_ps128(acc3);
621 __m128 sum01 = _mm_add_ps(_mm_add_ps(lo0, hi0), _mm_add_ps(lo1, hi1));
622 __m128 sum23 = _mm_add_ps(_mm_add_ps(lo2, hi2), _mm_add_ps(lo3, hi3));
623 __m128 total = _mm_add_ps(sum01, sum23);
624 total = _mm_hadd_ps(total, total);
625 total = _mm_hadd_ps(total, total);
626 return _mm_cvtss_f32(total);
627}
628
629/* MXFP4 row dot using Q8_0 quantized input — uses VPMADDWD for integer dot product.
630 * x_q8 has been quantized to Q8_0 format (34 bytes per 32 values) once upstream.
631 * Combined scale = mxfp4_scale * q8_scale applied per block via FMA. */
632static float mxfp4_row_dot_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8,
633 int n_cols, int row) {
634 int bpr = n_cols / 32;
635 const uint8_t *rp = W + (size_t)row * bpr * sizeof(block_mxfp4);
636 __m256 acc0 = _mm256_setzero_ps();
637 __m256 acc1 = _mm256_setzero_ps();
638 for (int blk = 0; blk < bpr; blk++) {
639 const uint8_t *bp = rp + blk * sizeof(block_mxfp4);
640 const uint8_t *xbp = x_q8 + blk * Q8_0_BS;
641 float q8_d = f16_to_f32(*(const uint16_t*)xbp);
642 union { uint32_t u; float f; } sc = { .u = ((uint32_t)bp[16]) << 23 };
643 /* Clamp combined scale to prevent FMA overflow → inf → NaN in reduction.
644 * bp[16] (MXFP4 exponent byte) when ebyte=255 produces +inf as float via the
645 * (ebyte<<23) encoding. inf * q8_d = inf, and _mm256_fmadd_ps with inf produces
646 * mixed ±inf lanes → _mm256_add_ps(+inf,-inf) = NaN in final reduction.
647 * Clamp to 1e20 (safely below float32 max 3.4e38) preserves all normal values. */
648 float cs = sc.f * q8_d;
649 if (cs > 1e20f) cs = 1e20f;
650 if (cs < -1e20f) cs = -1e20f;
651 __m256 cv = _mm256_set1_ps(cs);
652 __m128i p = _mm_loadu_si128((const __m128i*)bp);
653 __m128i lo = _mm_and_si128(p, _mm_set1_epi8(0x0F));
654 __m128i hi = _mm_and_si128(_mm_srli_epi16(p, 4), _mm_set1_epi8(0x0F));
655 __m128i sl = _mm_cmpgt_epi8(lo, _mm_set1_epi8(7));
656 __m128i sh = _mm_cmpgt_epi8(hi, _mm_set1_epi8(7));
657 lo = _mm_sub_epi8(lo, _mm_and_si128(sl, _mm_set1_epi8(16)));
658 hi = _mm_sub_epi8(hi, _mm_and_si128(sh, _mm_set1_epi8(16)));
659 __m128i vlo = _mm_unpacklo_epi8(lo, hi);
660 __m128i vhi = _mm_unpackhi_epi8(lo, hi);
661 __m256i q8v = _mm256_loadu_si256((const __m256i*)(xbp + 2));
662 /* int16 × int16 → int32 via VPMADDWD */
663 __m256i dl = _mm256_madd_epi16(
664 _mm256_cvtepi8_epi16(vlo),
665 _mm256_cvtepi8_epi16(_mm256_castsi256_si128(q8v)));
666 __m256i dh = _mm256_madd_epi16(
667 _mm256_cvtepi8_epi16(vhi),
668 _mm256_cvtepi8_epi16(_mm256_extracti128_si256(q8v, 1)));
669 acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(dl), cv, acc0);
670 acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(dh), cv, acc1);
671 }
672 __m256 t = _mm256_add_ps(acc0, acc1);
673 __m128 th = _mm256_extractf128_ps(t, 1);
674 __m128 tl = _mm256_castps256_ps128(t);
675 __m128 s = _mm_add_ps(tl, th);
676 s = _mm_hadd_ps(s, s); s = _mm_hadd_ps(s, s);
677 return _mm_cvtss_f32(s);
678}
679
680/* MXFP4 row dot using F32 input — vertical accum + FMA + int-bit scale.
681 * For use when input is F32 (not pre-quantized), like the down projection
682 * which takes SiLU'd expert output as input. */
683static float mxfp4_row_dot_f32(const uint8_t *restrict W, const float *restrict x,
684 int n_cols, int row) {
685 int bpr = n_cols / 32;
686 const uint8_t *rp = W + (size_t)row * bpr * sizeof(block_mxfp4);
687 __m256 acc0 = _mm256_setzero_ps();
688 __m256 acc1 = _mm256_setzero_ps();
689 __m256 acc2 = _mm256_setzero_ps();
690 __m256 acc3 = _mm256_setzero_ps();
691 for (int blk = 0; blk < bpr; blk++) {
692 const uint8_t *bp = rp + blk * sizeof(block_mxfp4);
693 union { uint32_t u; float f; } sc = { .u = ((uint32_t)bp[16]) << 23 };
694 __m256 sv = _mm256_set1_ps(sc.f);
695 __m128i p = _mm_loadu_si128((const __m128i*)bp);
696 __m128i lo = _mm_and_si128(p, _mm_set1_epi8(0x0F));
697 __m128i hi = _mm_and_si128(_mm_srli_epi16(p, 4), _mm_set1_epi8(0x0F));
698 __m128i sl = _mm_cmpgt_epi8(lo, _mm_set1_epi8(7));
699 __m128i sh = _mm_cmpgt_epi8(hi, _mm_set1_epi8(7));
700 lo = _mm_sub_epi8(lo, _mm_and_si128(sl, _mm_set1_epi8(16)));
701 hi = _mm_sub_epi8(hi, _mm_and_si128(sh, _mm_set1_epi8(16)));
702 __m128i vlo = _mm_unpacklo_epi8(lo, hi);
703 __m128i vhi = _mm_unpackhi_epi8(lo, hi);
704 int o = blk * 32;
705 __m256 d0 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vlo)), sv);
706 __m256 d1 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(vlo, 8))), sv);
707 __m256 d2 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(vhi)), sv);
708 __m256 d3 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(vhi, 8))), sv);
709 acc0 = _mm256_fmadd_ps(d0, _mm256_loadu_ps(x + o), acc0);
710 acc1 = _mm256_fmadd_ps(d1, _mm256_loadu_ps(x + o + 8), acc1);
711 acc2 = _mm256_fmadd_ps(d2, _mm256_loadu_ps(x + o + 16), acc2);
712 acc3 = _mm256_fmadd_ps(d3, _mm256_loadu_ps(x + o + 24), acc3);
713 }
714 __m256 t = _mm256_add_ps(_mm256_add_ps(acc0, acc1), _mm256_add_ps(acc2, acc3));
715 __m128 th = _mm256_extractf128_ps(t, 1);
716 __m128 tl = _mm256_castps256_ps128(t);
717 __m128 s = _mm_add_ps(tl, th);
718 s = _mm_hadd_ps(s, s); s = _mm_hadd_ps(s, s);
719 return _mm_cvtss_f32(s);
720}
721
722/* MXFP4 full matmul using Q8_0 pre-quantized input — calls row_dot_q8
723 * in a single OMP parallel region. Much faster than per-row dispatch
724 * from moe_forward_omp because OMP overhead is amortized across all rows. */
725static void mxfp4_matmul_omp_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8,
726 float *restrict out, int n_rows, int n_cols) {
727 int bpr = n_cols / 32;
728 #pragma omp parallel for schedule(static)
729 for (int r = 0; r < n_rows; r++) {
730 out[r] = mxfp4_row_dot_q8(W, x_q8, n_cols, r);
731 }
732}
733
734void q6_k_matmul_omp(const uint8_t *restrict W, const float *restrict x,
735 float *restrict out, int n_rows, int n_cols) {
736 q6_k_matmul_avx2_omp(W, x, out, n_rows, n_cols);
737}
738
739/* =========================================================================
740 * Q6_K dequantize to F32 (for verification and output requantization)
741 *
742 * Q6_K layout (210 bytes per 256 values):
743 * offset 0: ql[128] — lower 4 bits (2 nibbles/byte)
744 * offset 128: qh[64] — upper 2 bits (4 groups of 2 bits per byte)
745 * offset 192: sc[16] — signed 6-bit per-sub-block scales
746 * offset 208: d (fp16, 2 bytes) — super-block scale
747 *
748 * Dequantization:
749 * For each 128-element half-block (h=0,128):
750 * for l in 0..31:
751 * is = l/16 (0 or 1, selects sc[is*2+0..7] within half)
752 * q1 = ((ql[l] & 0xF) | ((qh[l] >> 0) & 0x3) << 4) - 32
753 * q2 = ((ql[l+32] & 0xF) | ((qh[l] >> 2) & 0x3) << 4) - 32
754 * q3 = ((ql[l] >> 4) | ((qh[l] >> 4) & 0x3) << 4) - 32
755 * q4 = ((ql[l+32] >> 4) | ((qh[l] >> 6) & 0x3) << 4) - 32
756 * val = d * sc[is*2+0] * q1,
757 * d * sc[is*2+2] * q2,
758 * d * sc[is*2+4] * q3,
759 * d * sc[is*2+6] * q4
760 * ======================================================================= */
761
762void q6_k_dequantize_row(const uint8_t *restrict W, float *restrict out, int n_values) {
763 int nb = n_values / QK_K;
764 for (int b = 0; b < nb; b++) {
765 const uint8_t *blk = W + (size_t)b * Q6_K_BS;
766 const uint8_t *ql = blk; /* offset 0: ql[128] */
767 const uint8_t *qh = blk + 128; /* offset 128: qh[64] */
768 const int8_t *sc = (const int8_t *)(blk + 192); /* offset 192: scales[16] */
769 float d = f16_to_f32((uint16_t)blk[208] | ((uint16_t)blk[209] << 8));
770
771 for (int h = 0; h < 2; h++) {
772 int ql_off = h * 64;
773 int qh_off = h * 32;
774 int sc_off = h * 8;
775
776 for (int l = 0; l < 32; l++) {
777 int is = l / 16; /* 0 or 1 */
778
779 int q1 = ((ql[ql_off + l] & 0x0F) | ((qh[qh_off + l] & 0x03) << 4)) - 32;
780 int q2 = ((ql[ql_off + l + 32] & 0x0F) | ((qh[qh_off + l] & 0x0C) << 2)) - 32;
781 int q3 = ((ql[ql_off + l] >> 4) | ((qh[qh_off + l] & 0x30) )) - 32;
782 int q4 = ((ql[ql_off + l + 32] >> 4) | ((qh[qh_off + l] & 0xC0) >> 2)) - 32;
783
784 float ds1 = d * (float)sc[sc_off + is + 0];
785 float ds2 = d * (float)sc[sc_off + is + 2];
786 float ds3 = d * (float)sc[sc_off + is + 4];
787 float ds4 = d * (float)sc[sc_off + is + 6];
788
789 out[h * 128 + l] = ds1 * (float)q1;
790 out[h * 128 + l + 32] = ds2 * (float)q2;
791 out[h * 128 + l + 64] = ds3 * (float)q3;
792 out[h * 128 + l + 96] = ds4 * (float)q4;
793 }
794 }
795 out += QK_K;
796 }
797}
798
799/* =========================================================================
800 * Q5_K dequantize to F32 (for verification)
801 * ======================================================================= */
802
803
804void q4_k_dequantize_row(const uint8_t *restrict W, float *restrict out, int n_values) {
805 int nb = n_values / QK_K;
806 for (int b = 0; b < nb; b++) {
807 const uint8_t *blk = W + (size_t)b * Q4_K_BS;
808 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8));
809 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8));
810 const uint8_t *scales = blk + 4;
811 const uint8_t *q = blk + 16;
812 int is = 0;
813
814 for (int j = 0; j < QK_K; j += 64) {
815 uint8_t sc, m;
816 get_scale_min_k4(is + 0, scales, &sc, &m);
817 float d1 = d * sc; float m1 = min * m;
818 get_scale_min_k4(is + 1, scales, &sc, &m);
819 float d2 = d * sc; float m2 = min * m;
820
821 for (int l = 0; l < 32; ++l) out[l] = d1 * (q[l] & 0xF) - m1;
822 for (int l = 0; l < 32; ++l) out[l + 32] = d2 * (q[l] >> 4) - m2;
823 out += 64;
824 q += 32;
825 is += 2;
826 }
827 }
828}
829
830void q5_k_dequantize_row(const uint8_t *restrict W, float *restrict out, int n_values) {
831 int nb = n_values / QK_K;
832 for (int b = 0; b < nb; b++) {
833 const uint8_t *blk = W + (size_t)b * Q5_K_BS;
834 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8));
835 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8));
836 const uint8_t *scales = blk + 4;
837 const uint8_t *qh_arr = blk + 16;
838 const uint8_t *ql = blk + 48;
839 int is = 0;
840 uint8_t u1 = 1, u2 = 2;
841
842 for (int j = 0; j < QK_K; j += 64) {
843 uint8_t sc, m;
844 get_scale_min_k4(is + 0, scales, &sc, &m);
845 float d1 = d * sc; float m1 = min * m;
846 get_scale_min_k4(is + 1, scales, &sc, &m);
847 float d2 = d * sc; float m2 = min * m;
848
849 for (int l = 0; l < 32; ++l) {
850 out[l] = d1 * ((ql[l] & 0xF) + ((qh_arr[l] & u1) ? 16 : 0)) - m1;
851 }
852 for (int l = 0; l < 32; ++l) {
853 out[l + 32] = d2 * ((ql[l] >> 4) + ((qh_arr[l] & u2) ? 16 : 0)) - m2;
854 }
855 out += 64;
856 ql += 32;
857 is += 2;
858 u1 <<= 2;
859 u2 <<= 2;
860 }
861 }
862}
863
864/* =========================================================================
865 * Q8_0 dequantize to F32 (for verification)
866 * ======================================================================= */
867
868void q8_0_dequantize_row(const uint8_t *restrict W, float *restrict out, int n_values) {
869 int nb = n_values / QK8_0;
870 for (int b = 0; b < nb; b++) {
871 const uint8_t *bp = W + (size_t)b * Q8_0_BS;
872 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
873 const int8_t *qs = (const int8_t *)(bp + 2);
874 for (int j = 0; j < QK8_0; ++j) {
875 out[b * QK8_0 + j] = qs[j] * d;
876 }
877 }
878}
879
880/* =========================================================================
881 * F32 matrix-vector multiply (OMP parallel)
882 * ======================================================================= */
883
884void f32_matmul_omp(const float *restrict W, const float *restrict x,
885 float *restrict out, int n_rows, int n_cols) {
886 #pragma omp parallel for schedule(static)
887 for (int r = 0; r < n_rows; r++) {
888 const float *row = W + (size_t)r * n_cols;
889 __m256 sum0 = _mm256_setzero_ps();
890 __m256 sum1 = _mm256_setzero_ps();
891 int c;
892 for (c = 0; c <= n_cols - 16; c += 16) {
893 __m256 w0 = _mm256_loadu_ps(row + c);
894 __m256 w1 = _mm256_loadu_ps(row + c + 8);
895 __m256 x0 = _mm256_loadu_ps(x + c);
896 __m256 x1 = _mm256_loadu_ps(x + c + 8);
897 sum0 = _mm256_fmadd_ps(w0, x0, sum0);
898 sum1 = _mm256_fmadd_ps(w1, x1, sum1);
899 }
900 __m256 total = _mm256_add_ps(sum0, sum1);
901 for (; c < n_cols; c++) {
902 /* handled below */
903 }
904 __m256 h = _mm256_hadd_ps(total, _mm256_permute2f128_ps(total, total, 1));
905 h = _mm256_hadd_ps(h, h);
906 h = _mm256_hadd_ps(h, h);
907 float result = _mm256_cvtss_f32(h);
908 for (c = (n_cols / 16) * 16; c < n_cols; c++) {
909 result += row[c] * x[c];
910 }
911 out[r] = result;
912 }
913}
914
915/* =========================================================================
916 * Batched matmul: up to 7 projections in one OpenMP call (Q4_0/Q4_1 only)
917 * ======================================================================= */
918
919#define MAX_PROJ 7
920
921static void process_row(const uint8_t* w[MAX_PROJ], const float* x, float* out[MAX_PROJ],
922 int nrows[MAX_PROJ], int ncols[MAX_PROJ], int ts[MAX_PROJ],
923 int n_proj, int row) {
924 for (int p = 0; p < n_proj; p++) {
925 if (row >= nrows[p]) continue;
926 float total = 0.0f;
927 int nc = ncols[p], bp = nc / 32;
928 void (*dec)(const uint8_t*, __m256*) = (ts[p] == Q4_1_BS) ? decode_q4_1 : decode_q4_0;
929 for (int blk = 0; blk < bp; blk++) {
930 const uint8_t* bp_w = w[p] + ((size_t)row * bp + blk) * ts[p];
931 __m256 v[4]; dec(bp_w, v);
932 total += block_dot_fma(v, x + blk * 32);
933 }
934 out[p][row] = total;
935 }
936}
937
938void batch_matmul(const uint8_t* w[MAX_PROJ], const float* x, float* out[MAX_PROJ],
939 int nrows[MAX_PROJ], int ncols[MAX_PROJ], int ts[MAX_PROJ],
940 int n_proj) {
941 int max_rows = 0;
942 for (int p = 0; p < n_proj; p++) {
943 memset(out[p], 0, nrows[p] * sizeof(float));
944 if (nrows[p] > max_rows) max_rows = nrows[p];
945 }
946 #pragma omp parallel for schedule(static)
947 for (int row = 0; row < max_rows; row++) {
948 process_row(w, x, out, nrows, ncols, ts, n_proj, row);
949 }
950}
951
952/* =========================================================================
953 * RMS normalization (AVX2 vectorized)
954 * ======================================================================= */
955
956void rms_norm(const float* x, const float* weight, float* out, int n) {
957 __m256 ss_vec = _mm256_setzero_ps();
958 int i;
959 for (i = 0; i <= n - 8; i += 8) {
960 __m256 v = _mm256_loadu_ps(x + i);
961 ss_vec = _mm256_fmadd_ps(v, v, ss_vec);
962 }
963 __m256 h = _mm256_hadd_ps(ss_vec, _mm256_permute2f128_ps(ss_vec, ss_vec, 1));
964 h = _mm256_hadd_ps(h, h); h = _mm256_hadd_ps(h, h);
965 float ss = _mm256_cvtss_f32(h);
966 for (; i < n; i++) ss += x[i] * x[i];
967 float inv_rms = 1.0f / sqrtf(ss / n + 1e-5f);
968 __m256 inv_v = _mm256_set1_ps(inv_rms);
969 for (i = 0; i <= n - 8; i += 8) {
970 __m256 v = _mm256_loadu_ps(x + i);
971 __m256 w = _mm256_loadu_ps(weight + i);
972 _mm256_storeu_ps(out + i, _mm256_mul_ps(_mm256_mul_ps(v, inv_v), w));
973 }
974 for (; i < n; i++) out[i] = x[i] * inv_rms * weight[i];
975}
976
977/* =========================================================================
978 * SiLU activation
979 * ======================================================================= */
980
981void silu(float* x, int n) {
982 int i;
983 for (i = 0; i <= n - 8; i += 8) {
984 __m256 v = _mm256_loadu_ps(x + i);
985 float tmp[8];
986 _mm256_storeu_ps(tmp, v);
987 for (int j = 0; j < 8; j++) tmp[j] = tmp[j] / (1.0f + expf(-tmp[j]));
988 _mm256_storeu_ps(x + i, _mm256_loadu_ps(tmp));
989 }
990 for (; i < n; i++) {
991 float v = x[i];
992 x[i] = v / (1.0f + expf(-v));
993 }
994}
995
996/* =========================================================================
997 * Softmax
998 * ======================================================================= */
999
1000void softmax(float* x, int n) {
1001 float max_val = x[0];
1002 for (int i = 1; i < n; i++) if (x[i] > max_val) max_val = x[i];
1003
1004 float sum = 0.0f;
1005 for (int i = 0; i < n; i++) {
1006 x[i] = expf(x[i] - max_val);
1007 sum += x[i];
1008 }
1009 float inv = 1.0f / sum;
1010 for (int i = 0; i < n; i++) x[i] *= inv;
1011}
1012
1013/* =========================================================================
1014 * OMP SiLU (parallel)
1015 * ======================================================================= */
1016
1017void silu_omp(float* x, int n) {
1018 #pragma omp parallel for schedule(static)
1019 for (int i = 0; i < n; i++) {
1020 float v = x[i];
1021 x[i] = v / (1.0f + expf(-v));
1022 }
1023}
1024
1025/* =========================================================================
1026 * Thread control
1027 * ======================================================================= */
1028
1029int get_max_threads(void) { return omp_get_max_threads(); }
1030void set_num_threads(int n) { omp_set_num_threads(n); }
1031
1032/* =========================================================================
1033 * Batched layer matmul — computes attention QKV + output in a single
1034 * OMP parallel region, eliminating 6 fork/join barriers per layer.
1035 *
1036 * Compared to 7 separate quant_matmul_omp calls, this saves ~0.1-0.3ms
1037 * per layer from reduced thread synchronization overhead.
1038 * ========================================================================= */
1039
1040/* Internal: compute a single matmul row for Q4_0 */
1041static float q4_0_row_dot(const uint8_t *restrict W, const float *restrict x,
1042 int bpr, int row) {
1043 float total = 0.0f;
1044 for (int blk = 0; blk < bpr; blk++) {
1045 __m256 v[4];
1046 decode_q4_0(W + ((size_t)row * bpr + blk) * Q4_0_BS, v);
1047 total += block_dot_fma(v, x + blk * 32);
1048 }
1049 return total;
1050}
1051
1052/* Internal: compute a single matmul row for Q4_1 */
1053static float q4_1_row_dot(const uint8_t *restrict W, const float *restrict x,
1054 int bpr, int row) {
1055 float total = 0.0f;
1056 for (int blk = 0; blk < bpr; blk++) {
1057 __m256 v[4];
1058 decode_q4_1(W + ((size_t)row * bpr + blk) * Q4_1_BS, v);
1059 total += block_dot_fma(v, x + blk * 32);
1060 }
1061 return total;
1062}
1063
1064/* Internal: compute a single matmul row for Q8_0 — uses same logic as q8_0_matmul_omp */
1065static float q8_0_row_dot(const uint8_t *restrict W, const float *restrict x,
1066 int bpr, int row) {
1067 float total = 0.0f;
1068 for (int blk = 0; blk < bpr; blk++) {
1069 const uint8_t *bp = W + ((size_t)row * bpr + blk) * Q8_0_BS;
1070 float d = f16_to_f32((uint16_t)bp[0] | ((uint16_t)bp[1] << 8));
1071 const int8_t *qs = (const int8_t *)(bp + 2);
1072 int off = blk * 32;
1073 __m256 d_v = _mm256_set1_ps(d);
1074 __m256 acc = _mm256_setzero_ps();
1075 for (int i = 0; i < 32; i += 8) {
1076 __m128i q8 = _mm_loadl_epi64((__m128i*)(qs + i));
1077 __m128i q16lo = _mm_cvtepi8_epi16(q8);
1078 __m128i q16hi = _mm_cvtepi16_epi32(q16lo);
1079 __m128i q16lo2 = _mm_cvtepi16_epi32(_mm_unpackhi_epi64(q16lo, q16lo));
1080 __m256 qf = _mm256_cvtepi32_ps(_mm256_set_m128i(q16lo2, q16hi));
1081 __m256 xv = _mm256_loadu_ps(x + off + i);
1082 acc = _mm256_fmadd_ps(_mm256_mul_ps(qf, d_v), xv, acc);
1083 }
1084 __m128 hi128 = _mm256_extractf128_ps(acc, 1);
1085 __m128 lo128 = _mm256_castps256_ps128(acc);
1086 __m128 sum = _mm_add_ps(lo128, hi128);
1087 sum = _mm_hadd_ps(sum, sum);
1088 sum = _mm_hadd_ps(sum, sum);
1089 total += _mm_cvtss_f32(sum);
1090 }
1091 return total;
1092}
1093
1094/* Internal: compute a range of rows [row_start, row_end) for quant_matmul */
1095static void matmul_row_range(const uint8_t *restrict W, const float *restrict x,
1096 float *restrict out, int n_rows, int n_cols,
1097 int quant_type, int row_start, int row_end) {
1098 int bpr32 = n_cols / 32; /* blocks per row for 32-val quants */
1099 int bpr256 = n_cols / 256;
1100 for (int r = row_start; r < row_end; r++) {
1101 float total = 0.0f;
1102 switch (quant_type) {
1103 case 2: /* Q4_0 */
1104 total = q4_0_row_dot(W, x, bpr32, r);
1105 break;
1106 case 3: /* Q4_1 */
1107 total = q4_1_row_dot(W, x, bpr32, r);
1108 break;
1109 case 6: /* Q5_0 */
1110 total = q5_0_row_dot(W + (size_t)r * ((n_cols+31)/32) * 22, x, n_cols);
1111 break;
1112 case 8: /* Q8_0 */
1113 total = q8_0_row_dot(W, x, bpr32, r);
1114 break;
1115 case 12: /* Q4_K */
1116 total = q4_k_row_dot_avx2(W, x, n_cols, r);
1117 break;
1118 case 13: /* Q5_K */
1119 total = q5_k_row_dot_avx2(W, x, n_cols, r);
1120 break;
1121 case 14: /* Q6_K */
1122 total = q6_k_row_dot_avx2(W, x, n_cols, r);
1123 break;
1124 case 39: /* MXFP4 */
1125 total = mxfp4_row_dot(W, x, bpr32, r);
1126 break;
1127 default:
1128 total = 0.0f;
1129 break;
1130 }
1131 out[r] = total;
1132 }
1133}
1134
1135/* Batch QKV projections: compute Q, K, V matmuls in a single OMP region.
1136 * Since Q, K, V all use the same input vector (x_norm), we can parallelize
1137 * across all output rows of all three projections simultaneously.
1138 */
1139void batch_qkv_omp(const uint8_t *restrict Wq, const uint8_t *restrict Wk,
1140 const uint8_t *restrict Wv,
1141 const float *restrict x,
1142 float *restrict out_q, float *restrict out_k, float *restrict out_v,
1143 int nq, int nk, int nv, int n_cols,
1144 int qtype_q, int qtype_k, int qtype_v) {
1145 /* Quantize x to Q8_0 once if any projection uses Q4_K — saves 30× x reads */
1146 int has_q4k = (qtype_q == 12 || qtype_k == 12 || qtype_v == 12);
1147 int nb_blocks = n_cols / 32;
1148 int q8_sz = (size_t)nb_blocks * Q8_0_BS;
1149 uint8_t x_q8_buf[2048 / 32 * Q8_0_BS];
1150 uint8_t *x_q8 = NULL;
1151 if (has_q4k) {
1152 x_q8 = q8_sz <= (int)sizeof(x_q8_buf) ? x_q8_buf : (uint8_t*)malloc((size_t)q8_sz);
1153 if (x_q8) quantize_row_q8_0(x, x_q8, n_cols);
1154 }
1155
1156 int total_rows = nq + nk + nv;
1157 #pragma omp parallel for schedule(static)
1158 for (int i = 0; i < total_rows; i++) {
1159 if (i < nq) {
1160 if (qtype_q == 12 && x_q8) {
1161 out_q[i] = q4_k_row_dot_q8(Wq, x_q8, n_cols, i);
1162 } else {
1163 matmul_row_range(Wq, x, out_q, nq, n_cols, qtype_q, i, i + 1);
1164 }
1165 } else if (i < nq + nk) {
1166 int r = i - nq;
1167 if (qtype_k == 12 && x_q8) {
1168 out_k[r] = q4_k_row_dot_q8(Wk, x_q8, n_cols, r);
1169 } else {
1170 matmul_row_range(Wk, x, out_k, nk, n_cols, qtype_k, r, r + 1);
1171 }
1172 } else {
1173 int r = i - nq - nk;
1174 if (qtype_v == 12 && x_q8) {
1175 out_v[r] = q4_k_row_dot_q8(Wv, x_q8, n_cols, r);
1176 } else {
1177 matmul_row_range(Wv, x, out_v, nv, n_cols, qtype_v, r, r + 1);
1178 }
1179 }
1180 }
1181
1182 if (x_q8 && x_q8 != x_q8_buf) free(x_q8);
1183}
1184
1185/* Batch Gate+Up projections: compute both with single fork/join */
1186void batch_gate_up_omp(const uint8_t *restrict Wg, const uint8_t *restrict Wu,
1187 const float *restrict x,
1188 float *restrict out_gate, float *restrict out_up,
1189 int ng, int nu, int n_cols,
1190 int qtype_g, int qtype_u) {
1191 /* Quantize x to Q8_0 once if Q4_K — saves 30× x reads for gate+up */
1192 int has_q4k = (qtype_g == 12 || qtype_u == 12);
1193 int nb_blocks = n_cols / 32;
1194 int q8_sz = (size_t)nb_blocks * Q8_0_BS;
1195 uint8_t x_q8_buf[2048 / 32 * Q8_0_BS];
1196 uint8_t *x_q8 = NULL;
1197 if (has_q4k) {
1198 x_q8 = q8_sz <= (int)sizeof(x_q8_buf) ? x_q8_buf : (uint8_t*)malloc((size_t)q8_sz);
1199 if (x_q8) quantize_row_q8_0(x, x_q8, n_cols);
1200 }
1201
1202 int total_rows = ng + nu;
1203 #pragma omp parallel for schedule(static)
1204 for (int i = 0; i < total_rows; i++) {
1205 if (i < ng) {
1206 if (qtype_g == 12 && x_q8) {
1207 out_gate[i] = q4_k_row_dot_q8(Wg, x_q8, n_cols, i);
1208 } else {
1209 matmul_row_range(Wg, x, out_gate, ng, n_cols, qtype_g, i, i + 1);
1210 }
1211 } else {
1212 int r = i - ng;
1213 if (qtype_u == 12 && x_q8) {
1214 out_up[r] = q4_k_row_dot_q8(Wu, x_q8, n_cols, r);
1215 } else {
1216 matmul_row_range(Wu, x, out_up, nu, n_cols, qtype_u, r, r + 1);
1217 }
1218 }
1219 }
1220
1221 if (x_q8 && x_q8 != x_q8_buf) free(x_q8);
1222}
1223
1224/* =========================================================================
1225
1226/* =========================================================================
1227 * Q5_0 matmul (type 6) — 22 bytes per 32-element block
1228 * Format: 2B f16 scale + 4B high bits + 16B low nibbles
1229 * Dequant: signed_val = (nibble | (high_bit << 4)) - 16
1230 * ======================================================================= */
1231
1232void q5_0_matmul_omp(const uint8_t *restrict W, const float *restrict x,
1233 float *restrict out, int n_rows, int n_cols) {
1234 /* Quantize input to Q8_0, then use VPMADDUBSW integer path */
1235 int nb_blocks = n_cols / 32;
1236 uint8_t x_q8_buf[4096 / 32 * Q8_0_BS];
1237 int q8_sz = nb_blocks * Q8_0_BS;
1238 uint8_t *x_q8 = q8_sz <= (int)sizeof(x_q8_buf) ? x_q8_buf : (uint8_t*)malloc(q8_sz);
1239 if (!x_q8) { for (int r = 0; r < n_rows; r++) out[r] = 0.0f; return; }
1240 quantize_row_q8_0(x, x_q8, n_cols);
1241 q5_0_q8_0_matmul_omp(W, x_q8, out, n_rows, n_cols, 1);
1242 if (x_q8 != x_q8_buf) free(x_q8);
1243}
1244
1245float q5_0_row_dot(const uint8_t *row, const float *x, int n_cols) {
1246 int bpr = n_cols / 32; float total = 0;
1247 for (int b = 0; b < bpr; b++) {
1248 const uint8_t *bp = row + b * 22;
1249 float d = f16_to_f32(*(const uint16_t*)bp);
1250 const uint8_t *qh = bp+2, *ql = bp+6;
1251 for (int j = 0; j < 32; j++) {
1252 int8_t v = (int8_t)(((ql[j/2]>>((j%2)*4))&0x0F)|(((qh[j/8]>>(j%8))&1)<<4))-16;
1253 total += v * d * x[b*32+j];
1254 }
1255 }
1256 return total;
1257}
1258
1259/* =========================================================================
1260 * Q5_0 × Q8_0 quantized activation path
1261 *
1262 * Q5_0 block (22 bytes per 32 values): [d:fp16][qh:4B][ql:16B]
1263 * stored = nibble | (qh_bit << 4) range 0..31, actual = stored - 16
1264 * Q8_0 block: [d:fp16][qs:32 int8]
1265 *
1266 * dot = d5 * d8 * (VPMADDUBSW(nibbles,q8) + 16*Σ(qh_bit*q8) - 16*Σ(q8))
1267 * ========================================================================= */
1268static inline float dot_q5_0_q8_0(const uint8_t *restrict q5, const uint8_t *restrict q8) {
1269 float d5 = f16_to_f32(*(const uint16_t*)q5);
1270 float d8 = f16_to_f32(*(const uint16_t*)q8);
1271 const uint8_t *qh = q5 + 2, *ql = q5 + 6;
1272 const int8_t *q8v = (const int8_t *)(q8 + 2);
1273
1274 /* Part 1: nibble × q8 via VPMADDUBSW (same as Q4_0) */
1275 __m128i ql_raw = _mm_loadu_si128((const __m128i*)ql);
1276 __m128i lo_mask = _mm_set1_epi8(0x0F);
1277 __m128i lo = _mm_and_si128(ql_raw, lo_mask);
1278 __m128i hi = _mm_and_si128(_mm_srli_epi16(ql_raw, 4), lo_mask);
1279 __m128i nib_lo = _mm_unpacklo_epi8(lo, hi);
1280 __m128i nib_hi = _mm_unpackhi_epi8(lo, hi);
1281 __m128i ql8 = _mm_loadu_si128((const __m128i*)q8v);
1282 __m128i qh8 = _mm_loadu_si128((const __m128i*)(q8v + 16));
1283 __m128i ml = _mm_maddubs_epi16(nib_lo, ql8);
1284 __m128i mh = _mm_maddubs_epi16(nib_hi, qh8);
1285 __m128i ones16 = _mm_set1_epi16(1);
1286 __m128i s0 = _mm_madd_epi16(ml, ones16);
1287 __m128i s1 = _mm_madd_epi16(mh, ones16);
1288 __m128i s01 = _mm_hadd_epi32(s0, s1);
1289 __m128i s_all = _mm_hadd_epi32(s01, _mm_setzero_si128());
1290 int32_t nib_sum = _mm_cvtsi128_si32(s_all) + _mm_extract_epi32(s_all, 1);
1291
1292 /* Part 2: high-bit dot + Σ(q8) — per half (2 halves of 16 values) */
1293 int32_t high_dot = 0, q8_sum = 0;
1294 for (int h = 0; h < 2; h++) {
1295 uint16_t qw; memcpy(&qw, qh + h * 2, 2);
1296 __m256i qw_bc = _mm256_set1_epi16((short)qw);
1297 __m256i bitmask = _mm256_set_epi16(
1298 0x8000,0x4000,0x2000,0x1000,0x0800,0x0400,0x0200,0x0100,
1299 0x0080,0x0040,0x0020,0x0010,0x0008,0x0004,0x0002,0x0001);
1300 __m256i bt = _mm256_andnot_si256(
1301 _mm256_cmpeq_epi16(_mm256_and_si256(qw_bc, bitmask), _mm256_setzero_si256()),
1302 _mm256_set1_epi16(16));
1303 __m128i q8h = _mm_loadu_si128((const __m128i*)(q8v + h * 16));
1304 __m256i q8_16 = _mm256_cvtepi8_epi16(q8h);
1305 __m256i hd = _mm256_madd_epi16(bt, q8_16);
1306 __m128i hdl = _mm256_castsi256_si128(hd), hdh = _mm256_extracti128_si256(hd, 1);
1307 __m128i hds = _mm_hadd_epi32(hdl, hdh);
1308 hds = _mm_hadd_epi32(hds, hds);
1309 high_dot += _mm_cvtsi128_si32(hds) + _mm_extract_epi32(hds, 1);
1310 /* Σ(q8) */
1311 __m256i qs = _mm256_hadd_epi16(q8_16, _mm256_setzero_si256());
1312 __m128i qsl = _mm256_castsi256_si128(qs), qsh = _mm256_extracti128_si256(qs, 1);
1313 __m128i qss = _mm_add_epi32(_mm_cvtepi16_epi32(qsl), _mm_cvtepi16_epi32(qsh));
1314 qss = _mm_hadd_epi32(qss, qss); qss = _mm_hadd_epi32(qss, qss);
1315 q8_sum += _mm_cvtsi128_si32(qss);
1316 }
1317 int32_t acc = nib_sum + high_dot - 16 * q8_sum;
1318 return d5 * d8 * (float)acc;
1319}
1320
1321/* Q5_0 × Q8_0 matmul */
1322void q5_0_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
1323 float *restrict out, int n_rows, int n_cols, int B) {
1324 int bpr = n_cols / 32;
1325 #pragma omp parallel for schedule(static)
1326 for (int r = 0; r < n_rows; r++) {
1327 float *acc = (float*)__builtin_alloca(B * sizeof(float));
1328 for (int b = 0; b < B; b++) acc[b] = 0.0f;
1329 const uint8_t *row = W + (size_t)r * bpr * Q5_0_BS;
1330 for (int blk = 0; blk < bpr; blk++) {
1331 const uint8_t *bp = row + (size_t)blk * Q5_0_BS;
1332 float d5 = f16_to_f32(*(const uint16_t*)bp);
1333 for (int b = 0; b < B; b++) {
1334 acc[b] += dot_q5_0_q8_0(bp, x_q8 + (size_t)b * bpr * Q8_0_BS + (size_t)blk * Q8_0_BS);
1335 }
1336 }
1337 for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b];
1338 }
1339}
1340
1341/* Q5_0 × Q8_0 single row dot */
1342float q5_0_row_dot_q8(const uint8_t *restrict row, const uint8_t *restrict x_q8, int n_cols) {
1343 int bpr = n_cols / 32;
1344 float total = 0.0f;
1345 for (int b = 0; b < bpr; b++)
1346 total += dot_q5_0_q8_0(row + (size_t)b * Q5_0_BS, x_q8 + (size_t)b * Q8_0_BS);
1347 return total;
1348}
1349
1350/* Unified dispatch: quant_matmul_omp
1351 *
1352 * quant_type: 0=F32, 2=Q4_0, 3=Q4_1, 7=Q4_K, 8=Q8_0, 9=Q5_K, 14=Q6_K
1353 * ======================================================================= */
1354
1355void quant_matmul_omp(const uint8_t *restrict W, const float *restrict x,
1356 float *restrict out, int n_rows, int n_cols, int quant_type) {
1357 switch (quant_type) {
1358 case 0: /* F32 */
1359 f32_matmul_omp((const float *)W, x, out, n_rows, n_cols);
1360 break;
1361 case 2: /* Q4_0 */
1362 q4_0_matmul_omp(W, x, out, n_rows, n_cols);
1363 break;
1364 case 3: /* Q4_1 */
1365 q4_1_matmul_omp(W, x, out, n_rows, n_cols);
1366 break;
1367 case 6: /* Q5_0 */
1368 q5_0_matmul_omp(W, x, out, n_rows, n_cols);
1369 break;
1370 case 8: /* Q8_0 */
1371 q8_0_matmul_omp(W, x, out, n_rows, n_cols);
1372 break;
1373 case 12: /* Q4_K */
1374 q4_k_matmul_omp(W, x, out, n_rows, n_cols);
1375 break;
1376 case 13: /* Q5_K */
1377 q5_k_matmul_omp(W, x, out, n_rows, n_cols);
1378 break;
1379 case 14: /* Q6_K */
1380 q6_k_matmul_omp(W, x, out, n_rows, n_cols);
1381 break;
1382 case 39: /* MXFP4 */
1383 mxfp4_matmul_omp(W, x, out, n_rows, n_cols);
1384 break;
1385 default:
1386 break;
1387 }
1388}
1389
1390/* =========================================================================
1391 * QUANTIZED-ACTIVATION PATH — the key llama.cpp optimization
1392 *
1393 * Instead of dequantizing weights to FP32, we:
1394 * 1. Quantize the activation vector x to Q8_0 (tiny, ~34 bytes per 32 values)
1395 * 2. Compute packed integer dot products using _mm256_maddubs_epi16
1396 * 3. Apply per-block scales with a single FMA at the end
1397 *
1398 * This halves memory bandwidth because weight data stays in packed form
1399 * (4-6 bits/value) instead of being expanded to FP32 (32 bits/value).
1400 * ========================================================================= */
1401
1402/* Quantize FP32 vector to Q8_0 (34 bytes per 32 values: 2-byte fp16 scale + 32 int8 values)
1403 * AVX2 vectorized: processes 8 floats per iteration for absmax + quantize.
1404 * Returns number of Q8_0 blocks written (= n_cols / 32)
1405 */
1406int quantize_row_q8_0(const float *restrict x, uint8_t *restrict q8, int n_cols) {
1407 int nb = n_cols / 32;
1408 __m256 clamp_min = _mm256_set1_ps(-127.0f);
1409 __m256 clamp_max = _mm256_set1_ps(127.0f);
1410 __m256i mask_abs = _mm256_set1_epi32(0x7FFFFFFF);
1411
1412 for (int b = 0; b < nb; b++) {
1413 const float *src = x + b * 32;
1414 uint8_t *dst = q8 + (size_t)b * Q8_0_BS;
1415
1416 /* AVX2 absmax: process 8 floats at a time, 4 iterations for 32 total */
1417 __m256 absmax = _mm256_setzero_ps();
1418 for (int i = 0; i < 32; i += 8) {
1419 __m256 v = _mm256_loadu_ps(src + i);
1420 __m256 av = _mm256_and_ps(v, _mm256_castsi256_ps(mask_abs));
1421 absmax = _mm256_max_ps(absmax, av);
1422 }
1423 /* Horizontal max of 8 lanes */
1424 __m256 tmp = _mm256_max_ps(absmax, _mm256_permute2f128_ps(absmax, absmax, 1));
1425 tmp = _mm256_max_ps(tmp, _mm256_shuffle_ps(tmp, tmp, 0x4E));
1426 tmp = _mm256_max_ps(tmp, _mm256_shuffle_ps(tmp, tmp, 0xB1));
1427 float amax = _mm256_cvtss_f32(tmp);
1428 float d = amax / 127.0f;
1429 if (d == 0.0f) d = 1.0f;
1430 float id = 1.0f / d;
1431
1432 /* Store fp16 scale */
1433 __m128 fv = _mm_load_ss(&d);
1434 __m128i hv = _mm_cvtps_ph(fv, _MM_FROUND_TO_NEAREST_INT);
1435 uint16_t d16;
1436 memcpy(&d16, &hv, 2);
1437 memcpy(dst, &d16, 2);
1438
1439 /* AVX2 quantize: 8 floats at a time, saturate to int8 */
1440 int8_t *qs = (int8_t *)(dst + 2);
1441 __m256 id_v = _mm256_set1_ps(id);
1442 for (int i = 0; i < 32; i += 8) {
1443 __m256 v = _mm256_loadu_ps(src + i);
1444 v = _mm256_mul_ps(v, id_v);
1445 v = _mm256_min_ps(_mm256_max_ps(v, clamp_min), clamp_max);
1446 __m256i vi = _mm256_cvtps_epi32(v); /* round to nearest (MXCSR default) */
1447 __m128i lo32 = _mm256_castsi256_si128(vi);
1448 __m128i hi32 = _mm256_extractf128_si256(vi, 1);
1449 __m128i i16 = _mm_packs_epi32(lo32, hi32); /* signed sat 4×int32 → 8×int16 */
1450 __m128i i8 = _mm_packs_epi16(i16, i16); /* signed sat 8×int16 → 8×int8 */
1451 _mm_storel_epi64((__m128i*)(qs + i), i8);
1452 }
1453 }
1454 return nb;
1455}
1456
1457/* Q4_0 × Q8_0 dot product (32 values = 1 Q4_0 block × 1 Q8_0 block)
1458/* Q4_0 × Q8_0 dot product (32 values = 1 Q4_0 block × 1 Q8_0 block)
1459 *
1460 * Q4_0 layout: 18 bytes = [d:fp16][qs:16 bytes packed 4-bit]
1461 * lo nibble of byte i → value[i] (positions 0..15)
1462 * hi nibble of byte i → value[i+16] (positions 16..31)
1463 * Q4_0 value = d * (nibble - 8) where nibble is unsigned 0..15
1464 *
1465 * Q8_0 layout: 34 bytes = [d8:fp16][qs:32 int8]
1466 * value[j] = d8 * qs8[j]
1467 *
1468 * dot = d4 * d8 * (sum(nibble_i * q8_i) - 8 * sum(q8_i))
1469 */
1470static inline float dot_q4_0_q8_0(const uint8_t *restrict q4, const uint8_t *restrict q8) {
1471 float d4 = f16_to_f32((uint16_t)q4[0] | ((uint16_t)q4[1] << 8));
1472 float d8 = f16_to_f32((uint16_t)q8[0] | ((uint16_t)q8[1] << 8));
1473 const uint8_t *q4_qs = q4 + 2;
1474 const int8_t *q8_qs = (const int8_t *)(q8 + 2);
1475
1476 /* AVX2 implementation */
1477 __m128i q4_raw = _mm_loadu_si128((const __m128i *)q4_qs);
1478 __m128i lo_mask = _mm_set1_epi8(0x0F);
1479 __m128i q4_lo = _mm_and_si128(q4_raw, lo_mask); /* unsigned 0-15, positions 0-15 */
1480 __m128i q4_hi = _mm_and_si128(_mm_srli_epi16(q4_raw, 4), lo_mask); /* unsigned 0-15, positions 16-31 */
1481
1482 __m128i q8v0 = _mm_loadu_si128((const __m128i *)(q8_qs)); /* q8[0..15] */
1483 __m128i q8v1 = _mm_loadu_si128((const __m128i *)(q8_qs + 16)); /* q8[16..31] */
1484
1485 /* maddubs: unsigned × signed → i16 pair-sums
1486 * madd_lo[j] = q4_lo[2j]*q8[2j] + q4_lo[2j+1]*q8[2j+1] (8 i16 values)
1487 * madd_hi[j] = q4_hi[2j]*q8[2j+16] + q4_hi[2j+1]*q8[2j+17] (8 i16 values)
1488 * Total acc = sum(madd_lo) + sum(madd_hi) = sum(all nibble*q8 pairs)
1489 */
1490 __m128i madd_lo = _mm_maddubs_epi16(q4_lo, q8v0);
1491 __m128i madd_hi = _mm_maddubs_epi16(q4_hi, q8v1);
1492
1493 /* Horizontal sum of madd_lo and madd_hi: each has 8 i16 values
1494 * Use madd with ones to get 4 i32, then hadd */
1495 __m128i ones = _mm_set1_epi16(1);
1496 __m128i s0 = _mm_madd_epi16(madd_lo, ones);
1497 __m128i s1 = _mm_madd_epi16(madd_hi, ones);
1498 __m128i s01 = _mm_hadd_epi32(s0, s1);
1499 __m128i s_all = _mm_hadd_epi32(s01, _mm_setzero_si128());
1500 int32_t acc = _mm_cvtsi128_si32(s_all) + _mm_extract_epi32(s_all, 1);
1501
1502 /* Sum of all q8 values for the -8 offset correction */
1503 /* Extend int8 → int16 → int32, then hadd sum */
1504 __m128i q8v0_16lo = _mm_cvtepi8_epi16(q8v0);
1505 __m128i q8v0_16hi = _mm_cvtepi8_epi16(_mm_shuffle_epi32(q8v0, 0x4e));
1506 __m128i q8v1_16lo = _mm_cvtepi8_epi16(q8v1);
1507 __m128i q8v1_16hi = _mm_cvtepi8_epi16(_mm_shuffle_epi32(q8v1, 0x4e));
1508 /* Sum all 4 × 8 = 32 int8 values as int16, then hadd */
1509 __m128i q8_s0 = _mm_hadd_epi16(q8v0_16lo, q8v0_16hi);
1510 __m128i q8_s1 = _mm_hadd_epi16(q8v1_16lo, q8v1_16hi);
1511 __m128i q8_sum16 = _mm_hadd_epi16(q8_s0, q8_s1);
1512 __m128i q8_sum32 = _mm_cvtepi16_epi32(q8_sum16);
1513 __m128i q8_sum32b = _mm_cvtepi16_epi32(_mm_shuffle_epi32(q8_sum16, 0x4e));
1514 __m128i q8_total = _mm_hadd_epi32(q8_sum32, q8_sum32b);
1515 q8_total = _mm_hadd_epi32(q8_total, _mm_setzero_si128());
1516 int32_t q8_sum = _mm_cvtsi128_si32(q8_total) + _mm_extract_epi32(q8_total, 1);
1517
1518 return d4 * d8 * ((float)acc - 8.0f * (float)q8_sum);
1519}
1520
1521/* Q4_0 × Q8_0 matmul — quantized activation path
1522 * Computes W[Q4_0] @ x_quantized[Q8_0] using packed integer dot products
1523 */
1524void q4_0_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
1525 float *restrict out, int n_rows, int n_cols,
1526 int n_blocks_x) {
1527 /* n_blocks_x = n_cols / 32 = number of Q8_0 blocks in x
1528 * Each weight row has n_cols/32 Q4_0 blocks
1529 * Each activation has n_blocks_x Q8_0 blocks */
1530 int bpr = n_cols / 32; /* blocks per row for Q4_0 (32 values per block) */
1531
1532 #pragma omp parallel for schedule(static)
1533 for (int r = 0; r < n_rows; r++) {
1534 float total = 0.0f;
1535 const uint8_t *row = W + (size_t)r * bpr * Q4_0_BS;
1536 for (int b = 0; b < bpr; b++) {
1537 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1538 x_q8 + (size_t)b * Q8_0_BS);
1539 }
1540 out[r] = total;
1541 }
1542}
1543
1544/* Batch QKV with Q8_0 quantized activation — eliminates 3 dequantize-to-float steps */
1545void batch_qkv_q8_omp(const uint8_t *restrict Wq, const uint8_t *restrict Wk,
1546 const uint8_t *restrict Wv,
1547 const uint8_t *restrict x_q8,
1548 float *restrict out_q, float *restrict out_k, float *restrict out_v,
1549 int nq, int nk, int nv, int n_cols,
1550 int qtype_q, int qtype_k, int qtype_v,
1551 int n_blocks_x) {
1552 /* For now, only Q4_0 × Q8_0 is implemented; K-quant types fall back to
1553 * the float activation path via matmul_row_range */
1554 int total_rows = nq + nk + nv;
1555 #pragma omp parallel for schedule(static)
1556 for (int i = 0; i < total_rows; i++) {
1557 if (i < nq) {
1558 if (qtype_q == 2) {
1559 /* Q4_0 × Q8_0 fast path */
1560 int bpr = nq / nq * (n_cols / 32); /* just n_cols/32 */
1561 float total = 0.0f;
1562 const uint8_t *row = Wq + (size_t)i * (n_cols/32) * Q4_0_BS;
1563 for (int b = 0; b < n_cols/32; b++) {
1564 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1565 x_q8 + (size_t)b * Q8_0_BS);
1566 }
1567 out_q[i] = total;
1568 } else {
1569 /* Fallback: need float activation */
1570 /* This shouldn't be called for non-Q4_0 types */
1571 out_q[i] = 0.0f;
1572 }
1573 } else if (i < nq + nk) {
1574 int r = i - nq;
1575 if (qtype_k == 2) {
1576 float total = 0.0f;
1577 const uint8_t *row = Wk + (size_t)r * (n_cols/32) * Q4_0_BS;
1578 for (int b = 0; b < n_cols/32; b++) {
1579 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1580 x_q8 + (size_t)b * Q8_0_BS);
1581 }
1582 out_k[r] = total;
1583 } else {
1584 out_k[r] = 0.0f;
1585 }
1586 } else {
1587 int r = i - nq - nk;
1588 if (qtype_v == 2) {
1589 float total = 0.0f;
1590 const uint8_t *row = Wv + (size_t)r * (n_cols/32) * Q4_0_BS;
1591 for (int b = 0; b < n_cols/32; b++) {
1592 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1593 x_q8 + (size_t)b * Q8_0_BS);
1594 }
1595 out_v[r] = total;
1596 } else {
1597 out_v[r] = 0.0f;
1598 }
1599 }
1600 }
1601}
1602
1603/* Batch Gate+Up with Q8_0 quantized activation */
1604void batch_gate_up_q8_omp(const uint8_t *restrict Wg, const uint8_t *restrict Wu,
1605 const uint8_t *restrict x_q8,
1606 float *restrict out_gate, float *restrict out_up,
1607 int ng, int nu, int n_cols,
1608 int qtype_g, int qtype_u,
1609 int n_blocks_x) {
1610 int total_rows = ng + nu;
1611 #pragma omp parallel for schedule(static)
1612 for (int i = 0; i < total_rows; i++) {
1613 if (i < ng) {
1614 if (qtype_g == 2) {
1615 float total = 0.0f;
1616 const uint8_t *row = Wg + (size_t)i * (n_cols/32) * Q4_0_BS;
1617 for (int b = 0; b < n_cols/32; b++) {
1618 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1619 x_q8 + (size_t)b * Q8_0_BS);
1620 }
1621 out_gate[i] = total;
1622 } else {
1623 out_gate[i] = 0.0f;
1624 }
1625 } else {
1626 int r = i - ng;
1627 if (qtype_u == 2) {
1628 float total = 0.0f;
1629 const uint8_t *row = Wu + (size_t)r * (n_cols/32) * Q4_0_BS;
1630 for (int b = 0; b < n_cols/32; b++) {
1631 total += dot_q4_0_q8_0(row + (size_t)b * Q4_0_BS,
1632 x_q8 + (size_t)b * Q8_0_BS);
1633 }
1634 out_up[r] = total;
1635 } else {
1636 out_up[r] = 0.0f;
1637 }
1638 }
1639 }
1640}
1641/* =========================================================================
1642 * Q4_K × Q8_0 QUANTIZED-ACTIVATION DOT — AVX2 vectorized
1643 *
1644 * Uses _mm_maddubs_epi16 for packed integer dot products.
1645 * 8 Q8_0 blocks × 32 values each, matching Q4_K's 8 sub-groups.
1646 * ======================================================================= */
1647static inline float dot_q4_k_q8_0(const uint8_t *restrict qk, const uint8_t *restrict q8) {
1648 float d = f16_to_f32(*(const uint16_t*)qk);
1649 float min = f16_to_f32(*(const uint16_t*)(qk + 2));
1650 const uint8_t *scales = qk + 4;
1651 const uint8_t *qs_nib = qk + 16;
1652
1653 /* Pre-extract 8 scale+min pairs using llama.cpp's bit-unpacking */
1654 uint32_t utmp[4];
1655 memcpy(utmp, scales, 12);
1656 static const uint32_t kmask1 = 0x3f3f3f3f;
1657 static const uint32_t kmask2 = 0x0f0f0f0f;
1658 static const uint32_t kmask3 = 0x03030303;
1659 utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
1660 uint32_t uaux = utmp[1] & kmask1;
1661 utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
1662 utmp[2] = uaux;
1663 utmp[0] &= kmask1;
1664 /* 8 int16 scales in low 128 bits */
1665 __m128i scales128 = _mm_cvtepu8_epi16(_mm_set_epi32(utmp[3], utmp[2], utmp[1], utmp[0]));
1666 /* Duplicate to both AVX lanes */
1667 __m256i scales_v = _mm256_insertf128_si256(_mm256_castsi128_si256(scales128), scales128, 1);
1668
1669 /* Scale shuffle masks (from llama.cpp) for sub-block 2*j+0 (lo nibbles) */
1670 static const uint8_t k_shuffle[256] = {
1671 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1672 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,
1673 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5,
1674 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7,
1675 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9,
1676 10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,
1677 12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,
1678 14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15
1679 };
1680 __m256i mask_lo = _mm256_set1_epi8(0x0F);
1681 __m256i ones16 = _mm256_set1_epi16(1);
1682 __m256i sumi = _mm256_setzero_si256();
1683 float sum_min = 0.0f;
1684
1685 for (int i = 0; i < 8; i++) {
1686 int grp = i >> 1;
1687 int sub = i & 1;
1688
1689 const uint8_t *q8b = q8 + (size_t)i * Q8_0_BS;
1690 float d8 = f16_to_f32(*(const uint16_t*)q8b);
1691 const int8_t *q8qs = (const int8_t *)(q8b + 2);
1692
1693 const uint8_t *nib = qs_nib + (size_t)grp * 32;
1694
1695 /* Load 32 nibbles, extract lo or hi */
1696 __m256i nv = _mm256_loadu_si256((const __m256i*)nib);
1697 nv = (sub == 0)
1698 ? _mm256_and_si256(nv, mask_lo)
1699 : _mm256_and_si256(_mm256_srli_epi16(nv, 4), mask_lo);
1700
1701 /* Load 32 Q8_0 int8 values */
1702 __m256i q8v = _mm256_loadu_si256((const __m256i*)q8qs);
1703
1704 /* maddubs: unsigned(nibble) × signed(q8) → 16 int16 pair-sums */
1705 __m256i p16 = _mm256_maddubs_epi16(nv, q8v);
1706
1707 /* Apply scale using shuffle: sub-block 2*grp+sub picks scale[2*grp+sub] */
1708 __m256i scl = _mm256_loadu_si256((const __m256i*)k_shuffle + (2*grp + sub));
1709 p16 = _mm256_madd_epi16(_mm256_shuffle_epi8(scales_v, scl), p16);
1710
1711 sumi = _mm256_add_epi32(sumi, p16);
1712
1713 /* Sum of Q8 int8 for min*Σ(q8) correction */
1714 __m256i e_lo = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(q8v));
1715 __m256i e_hi = _mm256_cvtepi8_epi16(_mm256_extractf128_si256(q8v, 1));
1716 __m128i q8ps128 = _mm_hadd_epi32(
1717 _mm_hadd_epi32(
1718 _mm256_castsi256_si128(_mm256_add_epi32(
1719 _mm256_madd_epi16(e_lo, ones16),
1720 _mm256_madd_epi16(e_hi, ones16))),
1721 _mm_setzero_si128()),
1722 _mm_setzero_si128());
1723 int32_t q8_total = _mm_cvtsi128_si32(q8ps128);
1724 sum_min += min * d8 * (float)q8_total;
1725 }
1726
1727 /* Final horizontal reduction of sumi */
1728 __m128i lo = _mm256_castsi256_si128(sumi);
1729 __m128i hi = _mm256_extractf128_si256(sumi, 1);
1730 __m128i h = _mm_hadd_epi32(lo, hi);
1731 h = _mm_hadd_epi32(h, h);
1732 int32_t int_sum = _mm_cvtsi128_si32(h);
1733
1734 return d * (float)int_sum - sum_min;
1735}
1736
1737/* Q4_K matrix × Q8_0 activation row-dot */
1738float q4_k_row_dot_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8,
1739 int n_cols, int row) {
1740 int nb = n_cols / QK_K;
1741 const uint8_t *row_ptr = W + (size_t)row * nb * Q4_K_BS;
1742 float sum = 0.0f;
1743 for (int b = 0; b < nb; b++) {
1744 sum += dot_q4_k_q8_0(row_ptr + (size_t)b * Q4_K_BS,
1745 x_q8 + (size_t)b * 8 * Q8_0_BS);
1746 }
1747 return sum;
1748}
1749
1750/* OMP Q4_K × Q8_0 matmul */
1751void q4_k_q8_0_matmul_omp(const uint8_t *restrict W, const uint8_t *restrict x_q8,
1752 float *restrict out, int n_rows, int n_cols) {
1753 int nb = n_cols / QK_K;
1754 #pragma omp parallel for schedule(static)
1755 for (int r = 0; r < n_rows; r++) {
1756 out[r] = q4_k_row_dot_q8(W, x_q8, n_cols, r);
1757 }
1758}
1759
1760/* =========================================================================
1761 * Q6_K AVX2 DEQUANT + FMA — vectorized inner loop
1762 *
1763 * Q6_K layout per 256-value super-block:
1764 * ql[128]: nibbles for lower 4 bits
1765 * qh[64]: upper 2 bits (4 packed per byte)
1766 * scales[16]: signed 6-bit per-sub-block scales
1767 * d[2]: fp16 super-block scale
1768 *
1769 * AVX2 processes the 4 quadrants in parallel, 8 values at a time per quadrant.
1770 * ======================================================================= */
1771
1772/* Dequant 8 Q6_K values from one quadrant into 8 floats.
1773 * ql_ptr: points to ql[l] for this quadrant
1774 * qh_ptr: points to qh[l] for this quadrant
1775 * shift: bit shift for qh (0, 2, 4, or 6 for q1,q2,q3,q4)
1776 * mask: bit mask for qh (0x03 for q1/q2, 0x30 for q3/q4 with special handling)
1777 * Uses SSE for byte processing, then extends to AVX2 floats. */
1778static inline __m256 q6k_dequant_8(const uint8_t *ql_ptr, const uint8_t *qh_ptr, int shift) {
1779 /* Load 8 bytes from each source */
1780 __m128i ql8 = _mm_loadl_epi64((const __m128i*)(ql_ptr));
1781 __m128i qh8 = _mm_loadl_epi64((const __m128i*)(qh_ptr));
1782
1783 /* Extract low nibble: ql & 0x0F */
1784 __m128i ql_nib = _mm_and_si128(ql8, _mm_set1_epi8(0x0F));
1785
1786 /* Extract upper 2 bits from qh at the right shift position */
1787 __m128i qh_shifted;
1788 if (shift == 0) {
1789 qh_shifted = _mm_and_si128(qh8, _mm_set1_epi8(0x03));
1790 } else if (shift == 2) {
1791 qh_shifted = _mm_and_si128(_mm_srli_epi16(qh8, 2), _mm_set1_epi8(0x03));
1792 } else if (shift == 4) {
1793 qh_shifted = _mm_and_si128(_mm_srli_epi16(qh8, 4), _mm_set1_epi8(0x03));
1794 } else { /* shift == 6 */
1795 qh_shifted = _mm_and_si128(_mm_srli_epi16(qh8, 6), _mm_set1_epi8(0x03));
1796 }
1797 qh_shifted = _mm_slli_epi16(qh_shifted, 4); /* shift upper bits to position 4 */
1798
1799 /* Combine: (ql & 0x0F) | ((qh >> shift) & 0x03) << 4 */
1800 __m128i combined = _mm_or_si128(ql_nib, qh_shifted);
1801
1802 /* Subtract 32 to get signed -32..31 */
1803 __m128i q6_s8 = _mm_sub_epi8(combined, _mm_set1_epi8(32));
1804
1805 /* Sign-extend: int8 → int16 → int32 → float via SSE then AVX2 */
1806 /* cvtepi8_epi16 reads LOW 8 bytes → 8 int16. No data in upper 8 bytes. */
1807 __m128i q6_16 = _mm_cvtepi8_epi16(q6_s8); /* 8 int8 → 8 int16, all valid */
1808 __m128i q6_32a = _mm_cvtepi16_epi32(q6_16); /* LOW 4 int16 → 4 int32 */
1809 /* Shuffle q6_16 (all valid data), then read LOW 4 int16 = original's HIGH 4 */
1810 __m128i q6_32b = _mm_cvtepi16_epi32(_mm_shuffle_epi32(q6_16, 0x4e));
1811 return _mm256_cvtepi32_ps(_mm256_set_m128i(q6_32b, q6_32a));
1812}
1813
1814/* Process one Q6_K super-block (256 values) with AVX2 dequant + FMA.
1815 * Returns the dot product: Σ d * sc[i] * q6[i] * x[i]
1816 *
1817 * v2 optimization: accumulate per-quadrant sums in 4 separate __m256
1818 * accumulators, apply per-quadrant scales at the end, then do a single
1819 * horizontal sum per sub-block (4 hsums/super-block vs 32 before). */
1820static inline float dot_q6_k_f32_avx2(const uint8_t *restrict blk,
1821 const float *restrict x, int x_off) {
1822 float d = f16_to_f32((uint16_t)blk[208] | ((uint16_t)blk[209] << 8));
1823 const int8_t *sc = (const int8_t *)(blk + 192);
1824 const uint8_t *ql = blk;
1825 const uint8_t *qh = blk + 128;
1826
1827 float block_sum = 0.0f;
1828
1829 /* Two halves of 128 values each */
1830 for (int half = 0; half < 2; half++) {
1831 int ql_h = half * 64; /* ql offset: 0 or 64 */
1832 int qh_h = half * 32; /* qh offset: 0 or 32 */
1833 int sc_h = half * 8; /* scale offset: 0 or 8 */
1834
1835 /* Two sub-blocks per half (l=0..15 and l=16..31) */
1836 for (int sub = 0; sub < 2; sub++) {
1837 /* Per-quadrant scales for this sub-block */
1838 float ds_q1 = d * (float)sc[sc_h + sub + 0];
1839 float ds_q2 = d * (float)sc[sc_h + sub + 2];
1840 float ds_q3 = d * (float)sc[sc_h + sub + 4];
1841 float ds_q4 = d * (float)sc[sc_h + sub + 6];
1842
1843 __m256 ds1 = _mm256_set1_ps(ds_q1);
1844 __m256 ds2 = _mm256_set1_ps(ds_q2);
1845 __m256 ds3 = _mm256_set1_ps(ds_q3);
1846 __m256 ds4 = _mm256_set1_ps(ds_q4);
1847
1848 __m256 acc1 = _mm256_setzero_ps();
1849 __m256 acc2 = _mm256_setzero_ps();
1850 __m256 acc3 = _mm256_setzero_ps();
1851 __m256 acc4 = _mm256_setzero_ps();
1852
1853 /* Process 8 values at a time (AVX2 width), 2 iterations for 16 ql */
1854 for (int inner = 0; inner < 2; inner++) {
1855 int l = sub * 16 + inner * 8;
1856
1857 /* 4 quadrants in parallel */
1858 __m256 q1f = q6k_dequant_8(ql + ql_h + l, qh + qh_h + l, 0);
1859 __m256 q2f = q6k_dequant_8(ql + ql_h + l + 32, qh + qh_h + l, 2);
1860 __m256 q3f = q6k_dequant_8(ql + ql_h + l, qh + qh_h + l, 4);
1861 __m256 q4f = q6k_dequant_8(ql + ql_h + l + 32, qh + qh_h + l, 6);
1862
1863 /* Load x (quadrants are interleaved at +0, +32, +64, +96) */
1864 int base = x_off + half * 128 + l;
1865 __m256 x1 = _mm256_loadu_ps(x + base);
1866 __m256 x2 = _mm256_loadu_ps(x + base + 32);
1867 __m256 x3 = _mm256_loadu_ps(x + base + 64);
1868 __m256 x4 = _mm256_loadu_ps(x + base + 96);
1869
1870 /* Accumulate per-quadrant (no hsum yet) */
1871 acc1 = _mm256_fmadd_ps(q1f, x1, acc1);
1872 acc2 = _mm256_fmadd_ps(q2f, x2, acc2);
1873 acc3 = _mm256_fmadd_ps(q3f, x3, acc3);
1874 acc4 = _mm256_fmadd_ps(q4f, x4, acc4);
1875 }
1876
1877 /* Apply per-quadrant scales and combine into one sum */
1878 __m256 sum = _mm256_mul_ps(acc1, ds1);
1879 sum = _mm256_fmadd_ps(acc2, ds2, sum);
1880 sum = _mm256_fmadd_ps(acc3, ds3, sum);
1881 sum = _mm256_fmadd_ps(acc4, ds4, sum);
1882
1883 /* Single horizontal sum for this sub-block (64 values) */
1884 __m256 h = _mm256_hadd_ps(sum, _mm256_permute2f128_ps(sum, sum, 1));
1885 h = _mm256_hadd_ps(h, h);
1886 h = _mm256_hadd_ps(h, h);
1887 block_sum += _mm256_cvtss_f32(h);
1888 }
1889 }
1890 return block_sum;
1891}
1892
1893/* Q6_K row dot using AVX2 dequant + FMA */
1894float q6_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x,
1895 int n_cols, int row) {
1896 int nb = n_cols / QK_K;
1897 const uint8_t *row_ptr = W + (size_t)row * nb * Q6_K_BS;
1898 float sum = 0.0f;
1899 for (int b = 0; b < nb; b++) {
1900 sum += dot_q6_k_f32_avx2(row_ptr + (size_t)b * Q6_K_BS, x, b * QK_K);
1901 }
1902 return sum;
1903}
1904
1905/* Q6_K row-dot with Q8_0 activation — VPMADDUBSW path */
1906float q6_k_row_dot_q8(const uint8_t *restrict W, const uint8_t *restrict x_q8,
1907 int n_cols, int row) {
1908 int nb = n_cols / QK_K;
1909 const uint8_t *row_ptr = W + (size_t)row * nb * Q6_K_BS;
1910 float sum = 0.0f;
1911 static const uint8_t kShuf[16] = {0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15};
1912 __m128i shuf_nib = _mm_loadu_si128((const __m128i*)kShuf);
1913 __m128i ones8 = _mm_set1_epi8(1);
1914 __m128i ones16 = _mm_set1_epi16(1);
1915 __m128i mask0f = _mm_set1_epi8(0x0F);
1916 for (int b = 0; b < nb; b++) {
1917 const uint8_t *blk = row_ptr + (size_t)b * Q6_K_BS;
1918 const uint8_t *ql = blk;
1919 const uint8_t *qh = blk + 128;
1920 const int8_t *sc = (const int8_t*)(blk + 192);
1921 float d = f16_to_f32(*(const uint16_t*)(blk + 208));
1922 for (int j = 0; j < QK_K; j += 16) {
1923 float scale = d * (float)sc[j/16];
1924 __m128i ql8 = _mm_loadl_epi64((const __m128i*)(ql + j/2));
1925 __m128i lo = _mm_and_si128(ql8, mask0f);
1926 __m128i hi = _mm_and_si128(_mm_srli_epi16(ql8, 4), mask0f);
1927 __m128i nib = _mm_shuffle_epi8(_mm_unpacklo_epi64(lo, hi), shuf_nib);
1928 uint32_t qh4; memcpy(&qh4, qh + j/4, 4);
1929 uint8_t qh16[16];
1930 for (int k = 0; k < 4; k++) {
1931 uint8_t byte = (qh4 >> (k*8)) & 0xFF;
1932 qh16[k*4+0]=byte&3; qh16[k*4+1]=(byte>>2)&3;
1933 qh16[k*4+2]=(byte>>4)&3; qh16[k*4+3]=(byte>>6)&3;
1934 }
1935 __m128i up = _mm_loadu_si128((const __m128i*)qh16);
1936 __m128i val6 = _mm_or_si128(nib, _mm_slli_epi16(up, 4));
1937 int q8_idx = (b * QK_K + j) / 32;
1938 int q8_off = (b * QK_K + j) % 32;
1939 const uint8_t *q8b = x_q8 + (size_t)q8_idx * Q8_0_BS;
1940 float d8 = f16_to_f32(*(const uint16_t*)q8b);
1941 __m128i q8v = _mm_loadu_si128((const __m128i*)(q8b + 2 + q8_off));
1942 __m128i prod = _mm_maddubs_epi16(val6, q8v);
1943 __m128i sum_v = _mm_madd_epi16(prod, ones16);
1944 int total_val = _mm_extract_epi32(sum_v,0)+_mm_extract_epi32(sum_v,1)
1945 + _mm_extract_epi32(sum_v,2)+_mm_extract_epi32(sum_v,3);
1946 __m128i q8sp = _mm_maddubs_epi16(ones8, q8v);
1947 __m128i q8si = _mm_madd_epi16(q8sp, ones16);
1948 int total_q8 = _mm_extract_epi32(q8si,0)+_mm_extract_epi32(q8si,1)
1949 + _mm_extract_epi32(q8si,2)+_mm_extract_epi32(q8si,3);
1950 sum += d8 * scale * ((float)total_val - 32.0f * (float)total_q8);
1951 }
1952 }
1953 return sum;
1954}
1955
1956/* OMP Q6_K matmul using AVX2 dequant + FMA */
1957void q6_k_matmul_avx2_omp(const uint8_t *restrict W, const float *restrict x,
1958 float *restrict out, int n_rows, int n_cols) {
1959 int nb = n_cols / QK_K;
1960 #pragma omp parallel for schedule(static)
1961 for (int r = 0; r < n_rows; r++) {
1962 out[r] = q6_k_row_dot_avx2(W, x, n_cols, r);
1963 }
1964}
1965
1966/* =========================================================================
1967 * MOE FUSED KERNEL — AVX2-accelerated
1968 *
1969 * Phase 1: Quantize x_norm to Q8_0 once for Q4_K gate/up matmuls
1970 * Phase 2: Gate + Up using Q4_K × Q8_0 quantized-activation path
1971 * Phase 3: Down using Q6_K AVX2 dequant + FMA
1972 * ========================================================================= */
1973
1974/* ─── Q4_K row-dot with float activation — AVX2 vectorized ───
1975 *
1976 * Uses the identity: sum((d1*nibble - m1)*x) = d1*sum(nibble*x) - m1*sum(x)
1977 * This lets us compute two accumulators (nibble*x and x) with AVX2,
1978 * then apply d1/m1 once at the end per 32-value group.
1979 */
1980float q4_k_row_dot_avx2(const uint8_t *restrict W, const float *restrict x,
1981 int n_cols, int row) {
1982 int nb = n_cols / QK_K;
1983 const uint8_t *row_ptr = W + (size_t)row * nb * Q4_K_BS;
1984 float sum = 0.0f;
1985 for (int b = 0; b < nb; b++) {
1986 const uint8_t *blk = row_ptr + (size_t)b * Q4_K_BS;
1987 float d = f16_to_f32((uint16_t)blk[0] | ((uint16_t)blk[1] << 8));
1988 float min = f16_to_f32((uint16_t)blk[2] | ((uint16_t)blk[3] << 8));
1989 const uint8_t *scales = blk + 4;
1990 const uint8_t *q = blk + 16;
1991 int x_off = b * QK_K;
1992 int is = 0;
1993 for (int j = 0; j < QK_K; j += 64) {
1994 uint8_t sc, m;
1995 get_scale_min_k4(is + 0, scales, &sc, &m);
1996 float d1 = d * (float)sc; float m1 = min * (float)m;
1997 get_scale_min_k4(is + 1, scales, &sc, &m);
1998 float d2 = d * (float)sc; float m2 = min * (float)m;
1999
2000 /* Process 32 lo-nibble values: sum += d1*nibble*x - m1*x */
2001 __m256 acc_nx = _mm256_setzero_ps();
2002 __m256 acc_x = _mm256_setzero_ps();
2003 for (int l = 0; l < 32; l += 16) {
2004 /* Load 16 bytes, extract lo nibbles (0-15) */
2005 __m128i q16 = _mm_loadu_si128((const __m128i*)(q + l));
2006 __m128i nib = _mm_and_si128(q16, _mm_set1_epi8(0x0F));
2007 __m128i n16a = _mm_cvtepu8_epi16(nib);
2008 __m128i n16b = _mm_cvtepu8_epi16(_mm_shuffle_epi32(nib, 0x4e));
2009 __m256 nf_a = _mm256_cvtepi32_ps(_mm256_set_m128i(
2010 _mm_cvtepi16_epi32(_mm_shuffle_epi32(n16a, 0x4e)),
2011 _mm_cvtepi16_epi32(n16a)));
2012 __m256 nf_b = _mm256_cvtepi32_ps(_mm256_set_m128i(
2013 _mm_cvtepi16_epi32(_mm_shuffle_epi32(n16b, 0x4e)),
2014 _mm_cvtepi16_epi32(n16b)));
2015 __m256 xa = _mm256_loadu_ps(x + x_off + j + l);
2016 __m256 xb = _mm256_loadu_ps(x + x_off + j + l + 8);
2017 acc_nx = _mm256_fmadd_ps(nf_a, xa, acc_nx);
2018 acc_nx = _mm256_fmadd_ps(nf_b, xb, acc_nx);
2019 acc_x = _mm256_add_ps(xa, acc_x);
2020 acc_x = _mm256_add_ps(xb, acc_x);
2021 }
2022 __m256 h_nx = _mm256_hadd_ps(acc_nx, _mm256_permute2f128_ps(acc_nx, acc_nx, 1));
2023 h_nx = _mm256_hadd_ps(h_nx, h_nx); h_nx = _mm256_hadd_ps(h_nx, h_nx);
2024 __m256 h_x = _mm256_hadd_ps(acc_x, _mm256_permute2f128_ps(acc_x, acc_x, 1));
2025 h_x = _mm256_hadd_ps(h_x, h_x); h_x = _mm256_hadd_ps(h_x, h_x);
2026 float nx_sum = _mm256_cvtss_f32(h_nx);
2027 float x_sum = _mm256_cvtss_f32(h_x);
2028 sum += d1 * nx_sum - m1 * x_sum;
2029
2030 /* Process 32 hi-nibble values: sum += d2*nibble*x - m2*x */
2031 acc_nx = _mm256_setzero_ps();
2032 acc_x = _mm256_setzero_ps();
2033 for (int l = 0; l < 32; l += 16) {
2034 __m128i q16 = _mm_loadu_si128((const __m128i*)(q + l));
2035 __m128i nib = _mm_and_si128(_mm_srli_epi16(q16, 4), _mm_set1_epi8(0x0F));
2036 __m128i n16a = _mm_cvtepu8_epi16(nib);
2037 __m128i n16b = _mm_cvtepu8_epi16(_mm_shuffle_epi32(nib, 0x4e));
2038 __m256 nf_a = _mm256_cvtepi32_ps(_mm256_set_m128i(
2039 _mm_cvtepi16_epi32(_mm_shuffle_epi32(n16a, 0x4e)),
2040 _mm_cvtepi16_epi32(n16a)));
2041 __m256 nf_b = _mm256_cvtepi32_ps(_mm256_set_m128i(
2042 _mm_cvtepi16_epi32(_mm_shuffle_epi32(n16b, 0x4e)),
2043 _mm_cvtepi16_epi32(n16b)));
2044 __m256 xa = _mm256_loadu_ps(x + x_off + j + 32 + l);
2045 __m256 xb = _mm256_loadu_ps(x + x_off + j + 32 + l + 8);
2046 acc_nx = _mm256_fmadd_ps(nf_a, xa, acc_nx);
2047 acc_nx = _mm256_fmadd_ps(nf_b, xb, acc_nx);
2048 acc_x = _mm256_add_ps(xa, acc_x);
2049 acc_x = _mm256_add_ps(xb, acc_x);
2050 }
2051 h_nx = _mm256_hadd_ps(acc_nx, _mm256_permute2f128_ps(acc_nx, acc_nx, 1));
2052 h_nx = _mm256_hadd_ps(h_nx, h_nx); h_nx = _mm256_hadd_ps(h_nx, h_nx);
2053 h_x = _mm256_hadd_ps(acc_x, _mm256_permute2f128_ps(acc_x, acc_x, 1));
2054 h_x = _mm256_hadd_ps(h_x, h_x); h_x = _mm256_hadd_ps(h_x, h_x);
2055 nx_sum = _mm256_cvtss_f32(h_nx);
2056 x_sum = _mm256_cvtss_f32(h_x);
2057 sum += d2 * nx_sum - m2 * x_sum;
2058
2059 q += 32; is += 2;
2060 }
2061 }
2062 return sum;
2063}
2064
2065
2066void moe_forward_omp(
2067 const uint8_t** gate_raw, const uint8_t** up_raw, const uint8_t** down_raw,
2068 const float* x_norm, int n_ff_expert, int n_embd,
2069 int qt_gate, int qt_up, int qt_down,
2070 const int* top_indices, const float* top_weights, int top_k,
2071 float* combined,
2072 float* prealloc_buf, uint8_t* prealloc_q8
2073) {
2074 size_t exp_buf_sz = (size_t)top_k * n_ff_expert;
2075 float *all_bufs = prealloc_buf ? prealloc_buf : (float*)malloc(3 * exp_buf_sz * sizeof(float));
2076 float *gate_buf = all_bufs;
2077 float *up_buf = all_bufs + exp_buf_sz;
2078 float *silu_buf = all_bufs + 2 * exp_buf_sz;
2079
2080 if (!all_bufs) return;
2081
2082 /* ── Quantize x_norm to Q8_0 once for all Q4_K/MXFP4 quantized-activation rows ── */
2083 int n_blocks_x = n_embd / 32;
2084 uint8_t x_q8_buf[4096 / 32 * Q8_0_BS]; /* stack alloc for up to 4096 dims */
2085 int q8_sz = (size_t)n_blocks_x * Q8_0_BS;
2086 uint8_t *x_q8 = q8_sz <= sizeof(x_q8_buf) ? x_q8_buf : (uint8_t*)malloc(q8_sz);
2087 uint8_t *x_q8_alloced = (x_q8 != x_q8_buf) ? x_q8 : NULL;
2088 (void)prealloc_q8;
2089 quantize_row_q8_0(x_norm, x_q8, n_embd);
2090
2091 int total_gate = top_k * n_ff_expert;
2092 int total_down = top_k * n_embd;
2093
2094 /* ── Phase 1: Gate + Up (V8 fused with contiguous rows per chunk) ── */
2095 if (qt_gate == 39 && qt_up == 39) {
2096 /* V8: Keep fused OMP region but group iterations by expert for better L3 reuse.
2097 * Gate/up uses f32 path (not q8) because Q8 quantization of x_norm loses
2098 * precision for the MoE router's gating signal, causing degraded output on
2099 * some models (GPT-OSS 2880-dim experts). Down path still uses q8 with
2100 * clamped scale for numerical stability. */
2101 int total = total_gate;
2102 #pragma omp parallel for schedule(static)
2103 for (int i = 0; i < total * 2; i++) {
2104 int is_up = i >= total;
2105 int idx = is_up ? i - total : i;
2106 int ei = idx / n_ff_expert;
2107 int row = idx % n_ff_expert;
2108 int e = top_indices[ei];
2109 const uint8_t *W = is_up ? up_raw[e] : gate_raw[e];
2110 float *buf = is_up ? up_buf : gate_buf;
2111 buf[idx] = mxfp4_row_dot_f32(W, x_norm, n_embd, row);
2112 }
2113 } else {
2114 /* Per-row dispatch for other quant types */
2115 #pragma omp parallel for schedule(static)
2116 for (int i = 0; i < total_gate; i++) {
2117 int ei = i / n_ff_expert;
2118 int row = i % n_ff_expert;
2119 int e = top_indices[ei];
2120 float gv, uv;
2121 if (qt_gate == 12) {
2122 gv = q4_k_row_dot_q8(gate_raw[e], x_q8, n_embd, row);
2123 } else if (qt_gate == 14) {
2124 gv = q6_k_row_dot_avx2(gate_raw[e], x_norm, n_embd, row);
2125 } else if (qt_gate == 2) {
2126 int bpr = n_embd / 32;
2127 gv = q4_0_row_dot(gate_raw[e], x_norm, bpr, row);
2128 } else if (qt_gate == 3) {
2129 int bpr = n_embd / 32;
2130 gv = q4_1_row_dot(gate_raw[e], x_norm, bpr, row);
2131 } else if (qt_gate == 6) {
2132 gv = q5_0_row_dot_q8(gate_raw[e] + (size_t)row * ((n_embd+31)/32) * Q5_0_BS, x_q8, n_embd);
2133 } else {
2134 gv = 0.0f;
2135 }
2136 if (qt_up == 12) {
2137 uv = q4_k_row_dot_q8(up_raw[e], x_q8, n_embd, row);
2138 } else if (qt_up == 14) {
2139 uv = q6_k_row_dot_avx2(up_raw[e], x_norm, n_embd, row);
2140 } else if (qt_up == 2) {
2141 int bpr = n_embd / 32;
2142 uv = q4_0_row_dot(up_raw[e], x_norm, bpr, row);
2143 } else if (qt_up == 3) {
2144 int bpr = n_embd / 32;
2145 uv = q4_1_row_dot(up_raw[e], x_norm, bpr, row);
2146 } else if (qt_up == 6) {
2147 uv = q5_0_row_dot_q8(up_raw[e] + (size_t)row * ((n_embd+31)/32) * Q5_0_BS, x_q8, n_embd);
2148 } else {
2149 uv = 0.0f;
2150 }
2151 gate_buf[i] = gv;
2152 up_buf[i] = uv;
2153 }
2154 }
2155
2156 /* ── Phase 1.5: SiLU(gate) * up (parallel) ── */
2157 #pragma omp parallel for schedule(static)
2158 for (int i = 0; i < top_k * n_ff_expert; i++) {
2159 float gv = gate_buf[i];
2160 /* Clamp to prevent expf overflow → inf/inf = NaN */
2161 if (gv < -80.0f) gv = -80.0f;
2162 if (gv > 80.0f) gv = 80.0f;
2163 silu_buf[i] = (gv / (1.0f + expf(-gv))) * up_buf[i];
2164 }
2165
2166 /* ── Pre-quantize silu to Q8_0 for Q4_K down path ── */
2167 uint8_t *silu_q8_base = NULL;
2168 int q8_bpe = 0; /* Q8_0 blocks per expert */
2169 if (qt_down == 12 && prealloc_q8) {
2170 q8_bpe = (n_ff_expert + 31) / 32;
2171 silu_q8_base = prealloc_q8;
2172 for (int ei = 0; ei < top_k; ei++) {
2173 uint8_t *sq = silu_q8_base + (size_t)ei * q8_bpe * Q8_0_BS;
2174 quantize_row_q8_0(silu_buf + (size_t)ei * n_ff_expert, sq, n_ff_expert);
2175 }
2176 }
2177
2178 /* ── Phase 2: Down matmuls + weighted accumulation ── */
2179 memset(combined, 0, n_embd * sizeof(float));
2180 if (qt_down == 39 || qt_down == 12) {
2181 /* Quantize silu to Q8_0 for MXFP4/Q4_K down path */
2182 if (!silu_q8_base && prealloc_q8) {
2183 q8_bpe = (n_ff_expert + 31) / 32;
2184 silu_q8_base = prealloc_q8;
2185 for (int ei = 0; ei < top_k; ei++) {
2186 uint8_t *sq = silu_q8_base + (size_t)ei * q8_bpe * Q8_0_BS;
2187 quantize_row_q8_0(silu_buf + (size_t)ei * n_ff_expert, sq, n_ff_expert);
2188 }
2189 }
2190 if (qt_down == 39) {
2191 /* MXFP4 down path with Q8_0 activation */
2192 #pragma omp parallel for schedule(static)
2193 for (int i = 0; i < total_down; i++) {
2194 int exp_idx = i / n_embd;
2195 int row = i % n_embd;
2196 int e = top_indices[exp_idx];
2197 uint8_t *sq = silu_q8_base + (size_t)exp_idx * q8_bpe * Q8_0_BS;
2198 float dot = mxfp4_row_dot_q8(down_raw[e], sq, n_ff_expert, row);
2199 #pragma omp atomic
2200 combined[row] += top_weights[exp_idx] * dot;
2201 }
2202 } else {
2203 #pragma omp parallel for schedule(static)
2204 for (int i = 0; i < total_down; i++) {
2205 int exp_idx = i / n_embd;
2206 int row = i % n_embd;
2207 int e = top_indices[exp_idx];
2208 const float *s = silu_buf + exp_idx * n_ff_expert;
2209 float dot;
2210 if (qt_down == 14) {
2211 dot = q6_k_row_dot_avx2(down_raw[e], s, n_ff_expert, row);
2212 } else if (qt_down == 2) {
2213 int bpr = n_ff_expert / 32;
2214 dot = q4_0_row_dot(down_raw[e], s, bpr, row);
2215 } else if (qt_down == 6) {
2216 dot = q5_0_row_dot(down_raw[e] + (size_t)row * ((n_embd+31)/32)*22, s, n_ff_expert);
2217 } else {
2218 dot = 0.0f;
2219 }
2220 #pragma omp atomic
2221 combined[row] += top_weights[exp_idx] * dot;
2222 }
2223 }
2224 } else {
2225 /* ── Other quant types (Q6_K, Q4_0, Q5_0): dequant + FMA ── */
2226 #pragma omp parallel for schedule(static)
2227 for (int i = 0; i < total_down; i++) {
2228 int exp_idx = i / n_embd;
2229 int row = i % n_embd;
2230 int e = top_indices[exp_idx];
2231 const float *s = silu_buf + exp_idx * n_ff_expert;
2232 float dot;
2233 if (qt_down == 14) {
2234 dot = q6_k_row_dot_avx2(down_raw[e], s, n_ff_expert, row);
2235 } else if (qt_down == 2) {
2236 int bpr = n_ff_expert / 32;
2237 dot = q4_0_row_dot(down_raw[e], s, bpr, row);
2238 } else if (qt_down == 6) {
2239 dot = q5_0_row_dot(down_raw[e] + (size_t)row * ((n_embd+31)/32)*22, s, n_ff_expert);
2240 } else {
2241 dot = 0.0f;
2242 }
2243 #pragma omp atomic
2244 combined[row] += top_weights[exp_idx] * dot;
2245 }
2246 }
2247
2248 if (!prealloc_buf) free(all_bufs);
2249 if (x_q8_alloced) free(x_q8_alloced);
2250}
2251
2252/* =========================================================================
2253 * Gemma4 fused matmuls — all 6 projections in one OMP region with shared Q8_0
2254 */
2255void gemma4_batch_matmuls(
2256 const float *x_norm,
2257 float *q, float *k, float *v,
2258 int N, int nq, int nk, int nv,
2259 const uint8_t *w_q, const uint8_t *w_k, const uint8_t *w_v,
2260 int qt_q, int qt_k, int qt_v
2261) {
2262 int nb = N / 32;
2263 /* Stack buffer for up to 4096 dims; malloc for larger (e.g., 8192 for Gemma4 26B).
2264 * MOTIVATION: Fixed 4KB stack buffer <q8 overflowed for N=8192, causing stack
2265 * corruption. Using the moe_forward_omp pattern: stack for small, malloc for large. */
2266 uint8_t q8_stack[4096 / 32 * Q8_0_BS];
2267 int q8_sz = (size_t)nb * Q8_0_BS;
2268 uint8_t *x_q8 = q8_sz <= sizeof(q8_stack) ? q8_stack : (uint8_t*)malloc(q8_sz);
2269 uint8_t *x_q8_alloced = (x_q8 != q8_stack) ? x_q8 : NULL;
2270 quantize_row_q8_0(x_norm, x_q8, N);
2271 int total = nq + nk + nv;
2272 #pragma omp parallel for schedule(static)
2273 for (int i = 0; i < total; i++) {
2274 if (i < nq) {
2275 q[i] = q4_k_row_dot_q8(w_q, x_q8, N, i);
2276 } else if (i < nq + nk) {
2277 k[i - nq] = q4_k_row_dot_q8(w_k, x_q8, N, i - nq);
2278 } else {
2279 v[i - nq - nk] = q6_k_row_dot_avx2(w_v, x_norm, N, i - nq - nk);
2280 }
2281 }
2282 /* Free malloc'd Q8 buffer if we allocated one (N > 4096) */
2283 if (x_q8_alloced) free(x_q8_alloced);
2284}
2285
2286/* =========================================================================
2287 * Q4_K matmul replacement — auto-quantizes activation to Q8_0
2288 * Backward-compatible replacement for the old scalar q4_k_matmul_omp.
2289 * ======================================================================= */