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