MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / cengine_batch.c.rope_backup
| 1 | /* cengine_batch.c — vLLM-style concurrent batched inference. |
| 2 | * Uses q4_0_batch_matmul for all weight projections across B tokens. |
| 3 | */ |
| 4 | #include <stdint.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <string.h> |
| 7 | #include <math.h> |
| 8 | #include <immintrin.h> |
| 9 | #include <omp.h> |
| 10 | #define Q4_0_BS 18 |
| 11 | #define Q8_0_BS 34 |
| 12 | #define BLOCK_SIZE 64 |
| 13 | #define MAX_BLOCKS 1024 |
| 14 | #define QK_K 256 |
| 15 | |
| 16 | /* K-quant block structures (from llama.cpp) */ |
| 17 | typedef struct { |
| 18 | uint16_t d; // half: super-block scale |
| 19 | uint16_t dm; // half: super-block min |
| 20 | uint8_t scales[12]; // 8 × 6-bit scale/min pairs |
| 21 | uint8_t qs[128]; // 4-bit nibbles (256 elements) |
| 22 | } block_q4_K; |
| 23 | |
| 24 | typedef struct { |
| 25 | uint8_t ql[128]; // lower 4 bits of quants |
| 26 | uint8_t qh[64]; // upper 2 bits of quants |
| 27 | int8_t scales[16]; // 16 × int8 scales (one per 16 elements) |
| 28 | uint16_t d; // half: super-block scale |
| 29 | } block_q6_K; |
| 30 | |
| 31 | /* GGML half <-> float conversion */ |
| 32 | static inline float gf16(uint16_t h) { |
| 33 | return _cvtsh_ss(h); |
| 34 | } |
| 35 | |
| 36 | /* Q4_K scale extraction */ |
| 37 | static inline void k4_scale(int j, const uint8_t *q, uint8_t *d, uint8_t *m) { |
| 38 | if (j < 4) { *d = q[j] & 63; *m = q[j+4] & 63; } |
| 39 | else { *d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4); |
| 40 | *m = (q[j+4] >> 4) | ((q[j] >> 6) << 4); } |
| 41 | } |
| 42 | |
| 43 | static inline float f16_to_f32(uint16_t h) { return _cvtsh_ss(h); } |
| 44 | static inline float hsum_ps(__m256 v) { |
| 45 | __m128 l=_mm256_castps256_ps128(v),h=_mm256_extractf128_ps(v,1); |
| 46 | l=_mm_add_ps(l,h);l=_mm_hadd_ps(l,l);l=_mm_hadd_ps(l,l);return _mm_cvtss_f32(l); |
| 47 | } |
| 48 | |
| 49 | /* AVX2-accelerated Batched Q4_0 matmul */ |
| 50 | void q4_0_batch_matmul(const uint8_t *W, const float *x, float *out, |
| 51 | int n_rows, int nc, int B) { |
| 52 | int bpr = nc / 32; |
| 53 | #pragma omp parallel for schedule(static, 8) |
| 54 | for (int r = 0; r < n_rows; r++) { |
| 55 | float acc[1024]; |
| 56 | for (int b = 0; b < B; b++) acc[b] = 0.0f; |
| 57 | for (int blk = 0; blk < bpr; blk++) { |
| 58 | const uint8_t *bp = W + ((size_t)r * bpr + blk) * Q4_0_BS; |
| 59 | float sc = f16_to_f32((uint16_t)bp[0]|((uint16_t)bp[1]<<8)); |
| 60 | |
| 61 | // SIMD dequant: 16 bytes of nibbles -> 32 floats |
| 62 | __m128i nib = _mm_loadu_si128((const __m128i*)(bp + 2)); |
| 63 | __m128i lo = _mm_and_si128(nib, _mm_set1_epi8(0x0F)); |
| 64 | __m128i hi = _mm_srli_epi16(nib, 4); |
| 65 | hi = _mm_and_si128(hi, _mm_set1_epi8(0x0F)); |
| 66 | __m256 sv = _mm256_set1_ps(sc); |
| 67 | |
| 68 | // lo has 16 nibbles (elements 0-15, value 0-15). Split into [0:7] and [8:15] |
| 69 | __m128i lo_lo = lo; |
| 70 | __m128i lo_hi = _mm_srli_si128(lo, 8); |
| 71 | __m256i i32_0 = _mm256_sub_epi32(_mm256_cvtepi8_epi32(lo_lo), _mm256_set1_epi32(8)); |
| 72 | __m256i i32_1 = _mm256_sub_epi32(_mm256_cvtepi8_epi32(lo_hi), _mm256_set1_epi32(8)); |
| 73 | __m256 blk0 = _mm256_mul_ps(_mm256_cvtepi32_ps(i32_0), sv); |
| 74 | __m256 blk1 = _mm256_mul_ps(_mm256_cvtepi32_ps(i32_1), sv); |
| 75 | |
| 76 | // hi has 16 nibbles (elements 16-31) |
| 77 | __m128i hi_lo = hi; |
| 78 | __m128i hi_hi = _mm_srli_si128(hi, 8); |
| 79 | __m256i i32_2 = _mm256_sub_epi32(_mm256_cvtepi8_epi32(hi_lo), _mm256_set1_epi32(8)); |
| 80 | __m256i i32_3 = _mm256_sub_epi32(_mm256_cvtepi8_epi32(hi_hi), _mm256_set1_epi32(8)); |
| 81 | __m256 blk2 = _mm256_mul_ps(_mm256_cvtepi32_ps(i32_2), sv); |
| 82 | __m256 blk3 = _mm256_mul_ps(_mm256_cvtepi32_ps(i32_3), sv); |
| 83 | |
| 84 | int o = blk * 32; |
| 85 | for (int b = 0; b < B; b++) { |
| 86 | const float *xb = x + (size_t)b * nc + o; |
| 87 | __m256 p0 = _mm256_mul_ps(blk0, _mm256_loadu_ps(xb)); |
| 88 | __m256 p1 = _mm256_mul_ps(blk1, _mm256_loadu_ps(xb + 8)); |
| 89 | __m256 p2 = _mm256_mul_ps(blk2, _mm256_loadu_ps(xb + 16)); |
| 90 | __m256 p3 = _mm256_mul_ps(blk3, _mm256_loadu_ps(xb + 24)); |
| 91 | __m256 s01 = _mm256_add_ps(p0, p1); |
| 92 | __m256 s23 = _mm256_add_ps(p2, p3); |
| 93 | __m256 s = _mm256_add_ps(s01, s23); |
| 94 | acc[b] += hsum_ps(s); |
| 95 | } |
| 96 | } |
| 97 | for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b]; |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /* Scalar Q4_0 dot (for single-token fallback) */ |
| 102 | static inline float q4d(const uint8_t *W, const float *x, int nc, int r) { |
| 103 | int bp=nc/32; float total=0.0f; |
| 104 | for(int b=0;b<bp;b++){ |
| 105 | const uint8_t *p=W+((size_t)r*bp+b)*Q4_0_BS; |
| 106 | float sc=f16_to_f32((uint16_t)p[0]|((uint16_t)p[1]<<8)); |
| 107 | int o=b*32; float d=0; |
| 108 | for (int j=0;j<32;j++) { |
| 109 | int by=j/16,bx=j%16; |
| 110 | int nib=(by==0)?(p[2+bx]&0x0F):((p[2+bx]>>4)&0x0F); |
| 111 | d += (float)(nib-8)*sc*x[o+j]; |
| 112 | } |
| 113 | total+=d; |
| 114 | } |
| 115 | return total; |
| 116 | } |
| 117 | static inline float q8d(const uint8_t *W, const float *x, int nc, int r) { |
| 118 | int bp=nc/32; float t=0; |
| 119 | for(int b=0;b<bp;b++){ |
| 120 | const uint8_t *p=W+((size_t)r*bp+b)*Q8_0_BS; |
| 121 | float d=f16_to_f32((uint16_t)p[0]|((uint16_t)p[1]<<8)); |
| 122 | const int8_t *qs=(const int8_t*)(p+2); int o=b*32; |
| 123 | for(int i=0;i<32;i++) t += d * (float)qs[i] * x[o+i]; |
| 124 | } |
| 125 | return t; |
| 126 | } |
| 127 | static inline void rms(float *o, const float *x, const float *w, int n, float e){ |
| 128 | float ss=0; for(int i=0;i<n;i++) ss+=x[i]*x[i]; |
| 129 | float ir=1.0f/sqrtf(ss/n+e); for(int i=0;i<n;i++) o[i]=x[i]*ir*w[i]; |
| 130 | } |
| 131 | static void gqa(float *o, const float *q, const float *kc, const float *vc, |
| 132 | int sl, int nh, int nkh, int hd){ |
| 133 | int gr=nh/nkh; |
| 134 | #pragma omp parallel for schedule(static) |
| 135 | for(int h=0;h<nh;h++){ |
| 136 | int kv=h/gr;const float *qh=q+h*hd,*kb=kc+kv*hd,*vb=vc+kv*hd; |
| 137 | int ks=nkh*hd;float *oh=o+h*hd,sc[4096],mx=-1e30f,inv=1.0f/sqrtf(hd); |
| 138 | for(int s=0;s<sl;s++){const float*ks_=kb+s*ks;__m256 su=_mm256_setzero_ps();int d; |
| 139 | for(d=0;d<=hd-8;d+=8)su=_mm256_fmadd_ps(_mm256_loadu_ps(qh+d),_mm256_loadu_ps(ks_+d),su); |
| 140 | float dot=hsum_ps(su);for(;d<hd;d++)dot+=qh[d]*ks_[d];dot*=inv;sc[s]=dot;if(dot>mx)mx=dot;} |
| 141 | float se=0;for(int s=0;s<sl;s++){sc[s]=expf(sc[s]-mx);se+=sc[s];}float is=1.0f/se; |
| 142 | memset(oh,0,hd*sizeof(float)); |
| 143 | for(int s=0;s<sl;s++){const float*vs_=vb+s*ks;float w=sc[s]*is;__m256 wv=_mm256_set1_ps(w);int d; |
| 144 | for(d=0;d<=hd-8;d+=8){__m256 vv=_mm256_loadu_ps(vs_+d); |
| 145 | __m256 ac=_mm256_loadu_ps(oh+d);_mm256_storeu_ps(oh+d,_mm256_fmadd_ps(wv,vv,ac));} |
| 146 | for(;d<hd;d++)oh[d]+=w*vs_[d];} |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /* Block-based KV cache */ |
| 151 | typedef struct { |
| 152 | float *k, *v; int n_blocks, seq_len[64], block_map[64][1024]; |
| 153 | } KVBlock; |
| 154 | void kv_init(KVBlock *kv, int L, int NKH, int HD) { |
| 155 | size_t sz = (size_t)L * MAX_BLOCKS * BLOCK_SIZE * NKH * HD * sizeof(float); |
| 156 | kv->k = (float*)calloc(1, sz); kv->v = (float*)calloc(1, sz); kv->n_blocks = 0; |
| 157 | memset(kv->block_map, -1, sizeof(kv->block_map)); memset(kv->seq_len, 0, sizeof(kv->seq_len)); |
| 158 | } |
| 159 | int kv_alloc(KVBlock *kv) { return kv->n_blocks < MAX_BLOCKS ? kv->n_blocks++ : -1; } |
| 160 | |
| 161 | /* AVX2-accelerated Batched Q8_0 matmul */ |
| 162 | void q8_0_batch_matmul(const uint8_t *W, const float *x, float *out, |
| 163 | int n_rows, int nc, int B) { |
| 164 | int bpr = nc / 32; |
| 165 | #pragma omp parallel for schedule(static, 8) |
| 166 | for (int r = 0; r < n_rows; r++) { |
| 167 | float acc[1024]; |
| 168 | for (int b = 0; b < B; b++) acc[b] = 0.0f; |
| 169 | for (int blk = 0; blk < bpr; blk++) { |
| 170 | const uint8_t *bp = W + ((size_t)r * bpr + blk) * Q8_0_BS; |
| 171 | float sc = f16_to_f32((uint16_t)bp[0]|((uint16_t)bp[1]<<8)); |
| 172 | const int8_t *qs = (const int8_t*)(bp + 2); |
| 173 | __m256 sv = _mm256_set1_ps(sc); |
| 174 | |
| 175 | // SIMD: load 32 int8 values, convert to float, multiply by scale |
| 176 | __m128i q8 = _mm_loadu_si128((const __m128i*)(qs)); // bytes 0-15 |
| 177 | __m128i q8b = _mm_loadu_si128((const __m128i*)(qs + 16)); // bytes 16-31 |
| 178 | __m128i q8_low = q8; |
| 179 | __m128i q8_high = _mm_srli_si128(q8, 8); |
| 180 | __m128i q8b_low = q8b; |
| 181 | __m128i q8b_high = _mm_srli_si128(q8b, 8); |
| 182 | __m256 blk0 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8_low)), sv); |
| 183 | __m256 blk1 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8_high)), sv); |
| 184 | __m256 blk2 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8b_low)), sv); |
| 185 | __m256 blk3 = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(q8b_high)), sv); |
| 186 | |
| 187 | int o = blk * 32; |
| 188 | for (int b = 0; b < B; b++) { |
| 189 | const float *xb = x + (size_t)b * nc + o; |
| 190 | __m256 p0 = _mm256_mul_ps(blk0, _mm256_loadu_ps(xb)); |
| 191 | __m256 p1 = _mm256_mul_ps(blk1, _mm256_loadu_ps(xb + 8)); |
| 192 | __m256 p2 = _mm256_mul_ps(blk2, _mm256_loadu_ps(xb + 16)); |
| 193 | __m256 p3 = _mm256_mul_ps(blk3, _mm256_loadu_ps(xb + 24)); |
| 194 | __m256 s01 = _mm256_add_ps(p0, p1); |
| 195 | __m256 s23 = _mm256_add_ps(p2, p3); |
| 196 | __m256 s = _mm256_add_ps(s01, s23); |
| 197 | acc[b] += hsum_ps(s); |
| 198 | } |
| 199 | } |
| 200 | for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b]; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /* Batched Q4_K matmul: 256-element super-blocks, 4-bit K-quant (AVX2) */ |
| 205 | void q4_k_batch_matmul(const uint8_t *W, const float *x, float *out, |
| 206 | int n_rows, int nc, int B) { |
| 207 | int bpr = nc / QK_K; |
| 208 | #pragma omp parallel for schedule(static, 8) |
| 209 | for (int r = 0; r < n_rows; r++) { |
| 210 | float acc[1024]; |
| 211 | for (int b = 0; b < B; b++) acc[b] = 0.0f; |
| 212 | for (int blk = 0; blk < bpr; blk++) { |
| 213 | const block_q4_K *bp = (const block_q4_K*)(W + ((size_t)r * bpr + blk) * sizeof(block_q4_K)); |
| 214 | float d = gf16(bp->d), dm = gf16(bp->dm); |
| 215 | const uint8_t *q = bp->qs; |
| 216 | int is = 0; |
| 217 | |
| 218 | // Dequantize all 256 elements to stack array (small, L1-cached) |
| 219 | float deq[QK_K]; |
| 220 | for (int s = 0; s < QK_K; s += 64, q += 32, is += 2) { |
| 221 | uint8_t sc1, sc2, m1, m2; |
| 222 | k4_scale(is, bp->scales, &sc1, &m1); |
| 223 | float d1 = d * sc1, mm1 = dm * m1; |
| 224 | k4_scale(is+1, bp->scales, &sc2, &m2); |
| 225 | float d2 = d * sc2, mm2 = dm * m2; |
| 226 | |
| 227 | // Load all 32 bytes of q (2×16-byte loads for 32 lower + 32 upper nibbles) |
| 228 | __m128i qb = _mm_loadu_si128((const __m128i*)q); // q[0..15] |
| 229 | __m128i qb2 = _mm_loadu_si128((const __m128i*)(q+16)); // q[16..31] |
| 230 | |
| 231 | // Lower nibbles from q[0..15] and q[16..31] |
| 232 | __m128i lo1 = _mm_and_si128(qb, _mm_set1_epi8(0x0F)); |
| 233 | __m128i lo2 = _mm_and_si128(qb2, _mm_set1_epi8(0x0F)); |
| 234 | // Upper nibbles from q[0..15] and q[16..31] |
| 235 | __m128i hi1 = _mm_and_si128(_mm_srli_epi16(qb, 4), _mm_set1_epi8(0x0F)); |
| 236 | __m128i hi2 = _mm_and_si128(_mm_srli_epi16(qb2, 4), _mm_set1_epi8(0x0F)); |
| 237 | |
| 238 | __m256 d1v = _mm256_set1_ps(d1), mm1v = _mm256_set1_ps(mm1); |
| 239 | __m256 d2v = _mm256_set1_ps(d2), mm2v = _mm256_set1_ps(mm2); |
| 240 | |
| 241 | // Dequant lower nibbles (32 values → 4×__m256) |
| 242 | for (int k = 0; k < 4; k++) { |
| 243 | __m128i src = (k < 2) ? lo1 : lo2; |
| 244 | __m128i src_split = (k & 1) ? _mm_srli_si128(src, 8) : src; |
| 245 | int out_off = s + k * 8; |
| 246 | _mm256_storeu_ps(deq + out_off, _mm256_sub_ps( |
| 247 | _mm256_mul_ps(_mm256_cvtepi32_ps( |
| 248 | _mm256_cvtepi8_epi32(src_split)), d1v), mm1v)); |
| 249 | } |
| 250 | // Dequant upper nibbles (32 values → 4×__m256) |
| 251 | for (int k = 0; k < 4; k++) { |
| 252 | __m128i src = (k < 2) ? hi1 : hi2; |
| 253 | __m128i src_split = (k & 1) ? _mm_srli_si128(src, 8) : src; |
| 254 | int out_off = s + 32 + k * 8; |
| 255 | _mm256_storeu_ps(deq + out_off, _mm256_sub_ps( |
| 256 | _mm256_mul_ps(_mm256_cvtepi32_ps( |
| 257 | _mm256_cvtepi8_epi32(src_split)), d2v), mm2v)); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // AVX2 dot product for each token with the dequantized block |
| 262 | int o = blk * QK_K; |
| 263 | for (int b = 0; b < B; b++) { |
| 264 | const float *xb = x + (size_t)b * nc + o; |
| 265 | __m256 sum = _mm256_setzero_ps(); |
| 266 | for (int j = 0; j < QK_K; j += 8) { |
| 267 | sum = _mm256_fmadd_ps(_mm256_loadu_ps(deq + j), |
| 268 | _mm256_loadu_ps(xb + j), sum); |
| 269 | } |
| 270 | acc[b] += hsum_ps(sum); |
| 271 | } |
| 272 | } |
| 273 | for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b]; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /* AVX2 Batched Q6_K matmul: 256-element blocks, 6-bit K-quant */ |
| 278 | void q6_k_batch_matmul(const uint8_t *W, const float *x, float *out, |
| 279 | int n_rows, int nc, int B) { |
| 280 | int bpr = nc / QK_K; |
| 281 | #pragma omp parallel for schedule(static, 8) |
| 282 | for (int r = 0; r < n_rows; r++) { |
| 283 | float acc[1024]; |
| 284 | for (int b = 0; b < B; b++) acc[b] = 0.0f; |
| 285 | for (int blk = 0; blk < bpr; blk++) { |
| 286 | const block_q6_K *bp = (const block_q6_K*)(W + ((size_t)r * bpr + blk) * sizeof(block_q6_K)); |
| 287 | float d = gf16(bp->d); |
| 288 | |
| 289 | // Dequant all 256 elements to stack |
| 290 | float deq[QK_K]; |
| 291 | for (int j = 0; j < QK_K; j++) { |
| 292 | uint8_t ql = bp->ql[j/2]; |
| 293 | uint8_t qh = bp->qh[j/4]; |
| 294 | int s = (j & 1) ? (ql >> 4) : (ql & 0xF); |
| 295 | int sh = (qh >> ((j & 3) * 2)) & 3; |
| 296 | s |= (sh << 4); s -= 32; |
| 297 | deq[j] = d * bp->scales[j/16] * s; |
| 298 | } |
| 299 | |
| 300 | int o = blk * QK_K; |
| 301 | for (int b = 0; b < B; b++) { |
| 302 | const float *xb = x + (size_t)b * nc + o; |
| 303 | __m256 sum = _mm256_setzero_ps(); |
| 304 | for (int j = 0; j < QK_K; j += 8) |
| 305 | sum = _mm256_fmadd_ps(_mm256_loadu_ps(deq + j), |
| 306 | _mm256_loadu_ps(xb + j), sum); |
| 307 | acc[b] += hsum_ps(sum); |
| 308 | } |
| 309 | } |
| 310 | for (int b = 0; b < B; b++) out[(size_t)b * n_rows + r] = acc[b]; |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /* Config struct */ |
| 315 | typedef struct { |
| 316 | int L,N,NH,NKH,HD,FF,V; float eps; |
| 317 | const uint8_t **wQ,**wK,**wV,**wO,**wG,**wU,**wD; |
| 318 | const float **wAN,**wFN; const int *nQ,*nK,*nV,*nO,*nG,*nU,*nD; |
| 319 | int nc; const float *emb,*onw; const uint8_t *wOut; int outNR,outNC,outQuant; |
| 320 | KVBlock **kv_array; float *logits; |
| 321 | // MoE fields |
| 322 | int n_experts, n_experts_per_tok, moe_intermediate; |
| 323 | const float **w_gate_inp; // [L][N, n_experts] — router weights (FP32) |
| 324 | const uint8_t **w_gate_exps; // [L][intermediate, N, experts] — packed expert gate |
| 325 | const uint8_t **w_up_exps; // same |
| 326 | const uint8_t **w_down_exps; // same |
| 327 | int gate_exp_quant, up_exp_quant, down_exp_quant; |
| 328 | // Quant types per tensor (0=use default Q4_0, 12=Q4_K, 14=Q6_K) |
| 329 | const int *q_quant, *k_quant, *v_quant, *o_quant; |
| 330 | const int *g_quant, *u_quant, *d_quant; |
| 331 | int emb_quant; // quantization type for embedding table |
| 332 | // Precomputed RoPE tables (AVX2 lookup instead of double trig) |
| 333 | float *cos_table; // [max_ctx * hd/2] — precomputed cos(pos_theta_j) |
| 334 | float *sin_table; // [max_ctx * hd/2] — precomputed sin(pos_theta_j) |
| 335 | int max_ctx; // model context length |
| 336 | } BC; |
| 337 | |
| 338 | /* MoE FFN: compute sparse expert mixture for B tokens. |
| 339 | * Uses packed expert weights from c->w_gate_exps/up_exps/down_exps. |
| 340 | * Workspace: ffn_buf[intermediate], gate_buf[intermediate], up_buf[intermediate]. */ |
| 341 | void moe_ffn(const BC *c, int l, float *x, float *gate_buf, float *up_buf, float *ffn_buf, int B) { |
| 342 | int N = c->N, NE = c->n_experts, NK = c->n_experts_per_tok, M = c->moe_intermediate; |
| 343 | size_t exp_stride = (size_t)M * (N / QK_K) * sizeof(block_q4_K); |
| 344 | float router_logits[256]; // max experts |
| 345 | int top_idx[16]; float top_val[16]; // max top-K |
| 346 | const float *w_router = c->w_gate_inp[l]; |
| 347 | |
| 348 | for (int b = 0; b < B; b++) { |
| 349 | float *xb = x + b*N; |
| 350 | |
| 351 | // ── Router: FP32 matmul xb[N] @ w_router[N, NE] ── |
| 352 | for (int e = 0; e < NE; e++) { |
| 353 | float dot = 0; |
| 354 | for (int i = 0; i < N; i++) dot += xb[i] * w_router[e * N + i]; |
| 355 | router_logits[e] = dot; |
| 356 | } |
| 357 | |
| 358 | // ── Softmax ── |
| 359 | float mx = router_logits[0]; |
| 360 | for (int e = 1; e < NE; e++) if (router_logits[e] > mx) mx = router_logits[e]; |
| 361 | float sum = 0; |
| 362 | for (int e = 0; e < NE; e++) { router_logits[e] = expf(router_logits[e] - mx); sum += router_logits[e]; } |
| 363 | float inv_sum = 1.0f / (sum + 1e-10f); |
| 364 | for (int e = 0; e < NE; e++) router_logits[e] *= inv_sum; |
| 365 | |
| 366 | // ── Top-K selection (simple partial sort) ── |
| 367 | for (int k = 0; k < NK; k++) { top_val[k] = -1e30f; top_idx[k] = -1; } |
| 368 | for (int e = 0; e < NE; e++) { |
| 369 | float v = router_logits[e]; |
| 370 | for (int k = 0; k < NK; k++) { |
| 371 | if (v > top_val[k]) { |
| 372 | for (int k2 = NK-1; k2 > k; k2--) { top_val[k2] = top_val[k2-1]; top_idx[k2] = top_idx[k2-1]; } |
| 373 | top_val[k] = v; top_idx[k] = e; break; |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | // ── Sparse expert FFN ── |
| 379 | memset(ffn_buf, 0, N * sizeof(float)); |
| 380 | for (int k = 0; k < NK; k++) { |
| 381 | int e = top_idx[k]; |
| 382 | if (e < 0) continue; |
| 383 | float weight = top_val[k]; |
| 384 | |
| 385 | // Gate projection |
| 386 | const uint8_t *gate_w = c->w_gate_exps[l] + e * exp_stride; |
| 387 | if (c->gate_exp_quant == 12) // Q4_K |
| 388 | q4_k_batch_matmul(gate_w, xb, gate_buf, M, N, 1); |
| 389 | else if (c->gate_exp_quant == 2) // Q4_0 fallback |
| 390 | q4_0_batch_matmul(gate_w, xb, gate_buf, M, N, 1); |
| 391 | |
| 392 | // Up projection |
| 393 | const uint8_t *up_w = c->w_up_exps[l] + e * exp_stride; |
| 394 | if (c->up_exp_quant == 12) |
| 395 | q4_k_batch_matmul(up_w, xb, up_buf, M, N, 1); |
| 396 | else if (c->up_exp_quant == 2) |
| 397 | q4_0_batch_matmul(up_w, xb, up_buf, M, N, 1); |
| 398 | |
| 399 | // SiLU(gate) * up |
| 400 | for (int i = 0; i < M; i++) { |
| 401 | float g = gate_buf[i]; |
| 402 | gate_buf[i] = (g / (1.0f + expf(-g))) * up_buf[i]; |
| 403 | } |
| 404 | |
| 405 | // Down projection |
| 406 | const uint8_t *down_w = c->w_down_exps[l] + e * exp_stride; |
| 407 | if (c->down_exp_quant == 14) // Q6_K |
| 408 | q6_k_batch_matmul(down_w, gate_buf, up_buf, N, M, 1); |
| 409 | else if (c->down_exp_quant == 2) |
| 410 | q4_0_batch_matmul(down_w, gate_buf, up_buf, N, M, 1); |
| 411 | |
| 412 | // Weighted accumulate into ffn_buf |
| 413 | for (int i = 0; i < N; i++) ffn_buf[i] += weight * up_buf[i]; |
| 414 | } |
| 415 | |
| 416 | // No residual add here — caller does x = res + ffn_buf |
| 417 | } |
| 418 | } |
| 419 | /* Dispatch batch matmul by quant type. qt=0:Q4_0, 8:Q8_0, 12:Q4_K, 14:Q6_K */ |
| 420 | static inline void batch_matmul(int qt, const uint8_t *W, const float *x, float *out, |
| 421 | int n_rows, int nc, int B) { |
| 422 | if (qt == 12) q4_k_batch_matmul(W, x, out, n_rows, nc, B); |
| 423 | else if (qt == 14) q6_k_batch_matmul(W, x, out, n_rows, nc, B); |
| 424 | else if (qt == 8) q8_0_batch_matmul(W, x, out, n_rows, nc, B); |
| 425 | else q4_0_batch_matmul(W, x, out, n_rows, nc, B); // default |
| 426 | } |
| 427 | |
| 428 | /* Precompute RoPE sin/cos tables for all positions up to max_ctx. |
| 429 | * cos_table[pos * hd2 + j] = cos(pos / 10000^(2j/hd)) |
| 430 | * Call once at model load. Tables owned by BC struct, freed by caller. */ |
| 431 | void rope_init(float *cos_table, float *sin_table, int max_ctx, int hd) { |
| 432 | int hd2 = hd / 2; |
| 433 | for (int pos = 0; pos < max_ctx; pos++) { |
| 434 | for (int j = 0; j < hd2; j++) { |
| 435 | double theta = (double)pos / pow(10000.0, 2.0 * j / hd); |
| 436 | cos_table[pos * hd2 + j] = (float)cos(theta); |
| 437 | sin_table[pos * hd2 + j] = (float)sin(theta); |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | /* Apply RoPE to buffer using precomputed tables (AVX2). |
| 443 | * buf[nh * hd] — Q or K projection for one token, rotated in-place. |
| 444 | * cos_t, sin_t — precomputed tables [max_ctx * hd/2]. */ |
| 445 | static inline void rope_apply(float *buf, int nh, int hd, int pos, |
| 446 | const float *cos_t, const float *sin_t) { |
| 447 | int hd2 = hd / 2; |
| 448 | const float *cos_row = cos_t + (size_t)pos * hd2; |
| 449 | const float *sin_row = sin_t + (size_t)pos * hd2; |
| 450 | for (int h = 0; h < nh; h++) { |
| 451 | float *b = buf + (size_t)h * hd; |
| 452 | int j = 0; |
| 453 | for (; j <= hd2 - 8; j += 8) { |
| 454 | __m256 v0 = _mm256_loadu_ps(b + j); |
| 455 | __m256 v1 = _mm256_loadu_ps(b + j + hd2); |
| 456 | __m256 cv = _mm256_loadu_ps(cos_row + j); |
| 457 | __m256 sv = _mm256_loadu_ps(sin_row + j); |
| 458 | __m256 nv0 = _mm256_sub_ps(_mm256_mul_ps(v0, cv), _mm256_mul_ps(v1, sv)); |
| 459 | __m256 nv1 = _mm256_add_ps(_mm256_mul_ps(v0, sv), _mm256_mul_ps(v1, cv)); |
| 460 | _mm256_storeu_ps(b + j, nv0); |
| 461 | _mm256_storeu_ps(b + j + hd2, nv1); |
| 462 | } |
| 463 | for (; j < hd2; j++) { |
| 464 | float a0 = b[j], a1 = b[j + hd2]; |
| 465 | float cs = cos_row[j], sn = sin_row[j]; |
| 466 | b[j] = a0 * cs - a1 * sn; |
| 467 | b[j + hd2] = a1 * cs + a0 * sn; |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /* Embedding lookup: dequantize a single row of quantized embedding table */ |
| 473 | void emb_lookup(const uint8_t *emb, int token, float *out, int N, int quant) { |
| 474 | if (quant == 12) { // Q4_K |
| 475 | int bpr = N / QK_K, blk_size = sizeof(block_q4_K); |
| 476 | for (int bi = 0; bi < bpr; bi++) { |
| 477 | const block_q4_K *bp = (const block_q4_K*)(emb + ((size_t)token * bpr + bi) * blk_size); |
| 478 | float d = gf16(bp->d), dm = gf16(bp->dm); |
| 479 | int o = bi * QK_K; |
| 480 | for (int g = 0; g < 8; g++) { // 8 groups of 32 per block |
| 481 | uint8_t sc, mn; k4_scale(g, bp->scales, &sc, &mn); |
| 482 | float d_sc = d * ((int)sc - 32) / 8.0f; |
| 483 | float d_mn = dm * ((int)mn - 32) / 8.0f; |
| 484 | for (int j = g*32; j < (g+1)*32; j++) { |
| 485 | int s = (bp->qs[j/2] >> ((j & 1) * 4)) & 0xF; |
| 486 | out[o + j] = d_sc * (s - 8) - d_mn * 6.0f; |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | } else { // FP32 raw |
| 491 | memcpy(out, emb + (size_t)token * N * sizeof(float), N * sizeof(float)); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | void batch_forward(const BC *c, const int *tokens, int B, float *ws) { |
| 496 | int N=c->N, NH=c->NH, NKH=c->NKH, HD=c->HD, FF=c->FF, L=c->L, nc=c->nc; |
| 497 | int S = N; if (NH*HD > S) S = NH*HD; if (FF > S) S = FF; if (NKH*HD > S) S = NKH*HD; |
| 498 | |
| 499 | // Workspace pointers from flat buffer (size = B * (12*S + N + NKH*HD)) |
| 500 | float *x = ws, *xn = ws + B*S, *res = ws + 2*B*S; |
| 501 | float *q = ws + 3*B*S, *k = ws + 4*B*S, *v = ws + 5*B*S; |
| 502 | float *att = ws + 6*B*S, *gate = ws + 7*B*S, *up = ws + 8*B*S; |
| 503 | float *silu = ws + 9*B*S, *oproj = ws + 10*B*S, *ffn = ws + 11*B*S; |
| 504 | |
| 505 | for (int b = 0; b < B; b++) |
| 506 | memcpy(x + b*N, c->emb + (size_t)tokens[b] * N, N * sizeof(float)); |
| 507 | |
| 508 | for (int l = 0; l < L; l++) { |
| 509 | for (int b = 0; b < B; b++) { |
| 510 | memcpy(res + b*N, x + b*N, N * sizeof(float)); |
| 511 | rms(xn + b*N, x + b*N, c->wAN[l], N, c->eps); |
| 512 | } |
| 513 | batch_matmul(c->q_quant[l], c->wQ[l], xn, q, c->nQ[l], nc, B); |
| 514 | batch_matmul(c->k_quant[l], c->wK[l], xn, k, c->nK[l], nc, B); |
| 515 | batch_matmul(c->v_quant[l], c->wV[l], xn, v, c->nV[l], nc, B); |
| 516 | |
| 517 | for (int b = 0; b < B; b++) { |
| 518 | float *qb = q + b*c->nQ[l], *kb = k + b*c->nK[l], *vb = v + b*c->nV[l]; |
| 519 | KVBlock *kv = c->kv_array[b]; |
| 520 | int pos = kv->seq_len[0]; |
| 521 | rope_apply(qb, NH, HD, pos, c->cos_table, c->sin_table); |
| 522 | rope_apply(kb, NKH, HD, pos, c->cos_table, c->sin_table); |
| 523 | |
| 524 | size_t base=(size_t)l*MAX_BLOCKS*BLOCK_SIZE*NKH*HD; |
| 525 | int blk=pos/BLOCK_SIZE,off=pos%BLOCK_SIZE; |
| 526 | int bid=kv->block_map[0][blk]; |
| 527 | if(bid<0){bid=kv_alloc(kv);kv->block_map[0][blk]=bid;} |
| 528 | memcpy(kv->k+base+(size_t)bid*BLOCK_SIZE*NKH*HD+off*NKH*HD, kb, NKH*HD*sizeof(float)); |
| 529 | memcpy(kv->v+base+(size_t)bid*BLOCK_SIZE*NKH*HD+off*NKH*HD, vb, NKH*HD*sizeof(float)); |
| 530 | |
| 531 | int sl = pos + 1; |
| 532 | float *kct=(float*)__builtin_alloca(sl*NKH*HD*sizeof(float)); |
| 533 | float *vct=(float*)__builtin_alloca(sl*NKH*HD*sizeof(float)); |
| 534 | for(int s=0;s<sl;s++){ |
| 535 | int sb=s/BLOCK_SIZE,so=s%BLOCK_SIZE,sbid=kv->block_map[0][sb]; |
| 536 | size_t src=base+(size_t)sbid*BLOCK_SIZE*NKH*HD+(size_t)so*NKH*HD; |
| 537 | memcpy(kct+s*NKH*HD, kv->k+src, NKH*HD*sizeof(float)); |
| 538 | memcpy(vct+s*NKH*HD, kv->v+src, NKH*HD*sizeof(float)); |
| 539 | } |
| 540 | gqa(att+b*N, qb, kct, vct, sl, NH, NKH, HD); |
| 541 | } |
| 542 | |
| 543 | batch_matmul(c->o_quant[l], c->wO[l], att, oproj, c->nO[l], nc, B); |
| 544 | for(int b=0;b<B;b++)for(int i=0;i<N;i++)x[b*N+i]=res[b*N+i]+oproj[b*N+i]; |
| 545 | |
| 546 | for(int b=0;b<B;b++){ |
| 547 | memcpy(res+b*N, x+b*N, N*sizeof(float)); |
| 548 | rms(xn+b*N, x+b*N, c->wFN[l], N, c->eps); |
| 549 | } |
| 550 | if (c->n_experts > 0 && c->n_experts_per_tok > 0) { |
| 551 | // MoE FFN path (call per-token to avoid stride issues) |
| 552 | for(int b=0;b<B;b++){ |
| 553 | float *gate_buf = gate; float *up_buf = silu; float *ffn_buf = ffn; |
| 554 | memset(ffn_buf, 0, N * sizeof(float)); |
| 555 | moe_ffn(c, l, xn + b*N, gate_buf, up_buf, ffn_buf, 1); |
| 556 | for(int i=0;i<N;i++)x[b*N+i]=res[b*N+i]+ffn_buf[i]; |
| 557 | } |
| 558 | } else { |
| 559 | // Dense FFN path |
| 560 | batch_matmul(c->g_quant[l], c->wG[l], xn, gate, c->nG[l], nc, B); |
| 561 | batch_matmul(c->u_quant[l], c->wU[l], xn, up, c->nU[l], nc, B); |
| 562 | for(int b=0;b<B;b++) |
| 563 | for(int i=0;i<FF;i++){float g=gate[b*FF+i];silu[b*FF+i]=(g/(1+expf(-g)))*up[b*FF+i];} |
| 564 | batch_matmul(c->d_quant[l], c->wD[l], silu, ffn, c->nD[l], FF, B); |
| 565 | for(int b=0;b<B;b++)for(int i=0;i<N;i++)x[b*N+i]=res[b*N+i]+ffn[b*N+i]; |
| 566 | } |
| 567 | } |
| 568 | for(int b=0;b<B;b++) c->kv_array[b]->seq_len[0]++; // increment once per forward pass |
| 569 | for(int b=0;b<B;b++) rms(xn+b*N, x+b*N, c->onw, N, c->eps); |
| 570 | batch_matmul(c->outQuant, c->wOut, xn, c->logits, c->outNR, c->outNC, B); |
| 571 | } |
| 572 | |
| 573 | /* Fast prefill: process N prompt tokens in one pass, storing KV at positions 0..N-1. |
| 574 | * All tokens belong to one sequence (kv_array[0]). Output logits predict next token. |
| 575 | * Workspace must be at least N * 12 * S floats (S = max dimension). */ |
| 576 | void prefill_forward(const BC *c, const int *tokens, int N, float *ws) { |
| 577 | if (N <= 0) return; |
| 578 | int L=c->L, Ntok=N, Ndim=c->N, NH=c->NH, NKH=c->NKH, HD=c->HD, FF=c->FF, nc=c->nc; |
| 579 | KVBlock *kv = c->kv_array[0]; |
| 580 | int S = Ndim; if (NH*HD > S) S = NH*HD; if (FF > S) S = FF; if (NKH*HD > S) S = NKH*HD; |
| 581 | |
| 582 | // Per-token workspace: each region holds all N tokens' data for one layer step |
| 583 | // Layout: x[t*S], xn[t*S], q[t*nQ[l]], k[t*nK[l]], v[t*nV[l]], res[t*S], att[t*S], etc. |
| 584 | // We use B=1 matmuls to avoid stride issues, so only x, xn, res need per-token storage. |
| 585 | // q, k, v, att, gate, up, silu, oproj, ffn are single-token (overwritten each t). |
| 586 | float *x = ws; // N * S: per-token hidden states, preserved across layers |
| 587 | float *xn = ws + N*S; // N * S: per-token RMS norm outputs (for batch QKV if we fix stride) |
| 588 | float *res = ws + 2*N*S; // N * S: per-token residuals |
| 589 | // Single-token buffers (B=1, shared across all tokens): |
| 590 | float *q1 = ws + 3*N*S, *k1 = ws + 4*N*S, *v1 = ws + 5*N*S; |
| 591 | float *att1 = ws + 6*N*S, *gate1 = ws + 7*N*S, *up1 = ws + 8*N*S; |
| 592 | float *silu1 = ws + 9*N*S, *oproj1 = ws + 10*N*S, *ffn1 = ws + 11*N*S; |
| 593 | |
| 594 | // Load all token embeddings into per-token x |
| 595 | for (int t = 0; t < Ntok; t++) |
| 596 | memcpy(x + t*S, c->emb + (size_t)tokens[t] * Ndim, Ndim * sizeof(float)); |
| 597 | |
| 598 | for (int l = 0; l < L; l++) { |
| 599 | for (int t = 0; t < Ntok; t++) { |
| 600 | float *xt = x + t*S, *xnt = xn + t*S, *rest = res + t*S; |
| 601 | memcpy(rest, xt, Ndim * sizeof(float)); |
| 602 | rms(xnt, xt, c->wAN[l], Ndim, c->eps); |
| 603 | } |
| 604 | // QKV projections individually per-token to avoid stride issues |
| 605 | for (int t = 0; t < Ntok; t++) { |
| 606 | int pos = t; |
| 607 | float *xnt = xn + t*S; |
| 608 | q4_0_batch_matmul(c->wQ[l], xnt, q1, c->nQ[l], nc, 1); |
| 609 | q4_0_batch_matmul(c->wK[l], xnt, k1, c->nK[l], nc, 1); |
| 610 | q4_0_batch_matmul(c->wV[l], xnt, v1, c->nV[l], nc, 1); |
| 611 | |
| 612 | // RoPE (precomputed table, AVX2) |
| 613 | rope_apply(q1, NH, HD, pos, c->cos_table, c->sin_table); |
| 614 | rope_apply(k1, NKH, HD, pos, c->cos_table, c->sin_table); |
| 615 | |
| 616 | // Store KV |
| 617 | size_t base=(size_t)l*MAX_BLOCKS*BLOCK_SIZE*NKH*HD; |
| 618 | int blk=pos/BLOCK_SIZE,off=pos%BLOCK_SIZE; |
| 619 | int bid=kv->block_map[0][blk]; |
| 620 | if(bid<0){bid=kv_alloc(kv);kv->block_map[0][blk]=bid;} |
| 621 | memcpy(kv->k+base+(size_t)bid*BLOCK_SIZE*NKH*HD+off*NKH*HD, k1, NKH*HD*sizeof(float)); |
| 622 | memcpy(kv->v+base+(size_t)bid*BLOCK_SIZE*NKH*HD+off*NKH*HD, v1, NKH*HD*sizeof(float)); |
| 623 | |
| 624 | // Attention: attend to positions 0..t |
| 625 | int sl = t + 1; |
| 626 | float *kct=(float*)__builtin_alloca(sl*NKH*HD*sizeof(float)); |
| 627 | float *vct=(float*)__builtin_alloca(sl*NKH*HD*sizeof(float)); |
| 628 | for(int s=0;s<sl;s++){ |
| 629 | int sb=s/BLOCK_SIZE,so=s%BLOCK_SIZE,sbid=kv->block_map[0][sb]; |
| 630 | size_t src=base+(size_t)sbid*BLOCK_SIZE*NKH*HD+(size_t)so*NKH*HD; |
| 631 | memcpy(kct+s*NKH*HD, kv->k+src, NKH*HD*sizeof(float)); |
| 632 | memcpy(vct+s*NKH*HD, kv->v+src, NKH*HD*sizeof(float)); |
| 633 | } |
| 634 | gqa(att1, q1, kct, vct, sl, NH, NKH, HD); |
| 635 | |
| 636 | // O projection + residual |
| 637 | q4_0_batch_matmul(c->wO[l], att1, oproj1, c->nO[l], nc, 1); |
| 638 | float *xt = x + t*S, *rest = res + t*S; |
| 639 | for(int i=0;i<Ndim;i++) xt[i] = rest[i] + oproj1[i]; |
| 640 | |
| 641 | // FFN |
| 642 | memcpy(rest, xt, Ndim * sizeof(float)); |
| 643 | rms(xnt, xt, c->wFN[l], Ndim, c->eps); |
| 644 | q4_0_batch_matmul(c->wG[l], xnt, gate1, c->nG[l], nc, 1); |
| 645 | q4_0_batch_matmul(c->wU[l], xnt, up1, c->nU[l], nc, 1); |
| 646 | for(int i=0;i<FF;i++){float g=gate1[i];silu1[i]=(g/(1+expf(-g)))*up1[i];} |
| 647 | q4_0_batch_matmul(c->wD[l], silu1, ffn1, c->nD[l], FF, 1); |
| 648 | for(int i=0;i<Ndim;i++) xt[i]=rest[i]+ffn1[i]; |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | // Final norm + output on LAST token's hidden state |
| 653 | float *last_x = x + (Ntok-1)*S; |
| 654 | float *xn_last = xn; // reuse xn as single-temp |
| 655 | rms(xn_last, last_x, c->onw, Ndim, c->eps); |
| 656 | if (c->outQuant) |
| 657 | q8_0_batch_matmul(c->wOut, xn_last, c->logits, c->outNR, c->outNC, 1); |
| 658 | else |
| 659 | q4_0_batch_matmul(c->wOut, xn_last, c->logits, c->outNR, c->outNC, 1); |
| 660 | kv->seq_len[0] += Ntok; |
| 661 | } |