interplane.Get Omega
Read in your language

MojoLlama

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

Brought by drakestapleton

branch main Branches Tags History

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

197 lines · 9254 bytes Raw Blame History
1/* c_engine.c — Complete transformer forward pass with struct API.
2 *
3 * engine_forward() does 22-layer TinyLlama forward pass in C.
4 * Uses EngineConfig struct for clean API.
5 *
6 * Compile:
7 * gcc -O3 -mavx2 -mfma -mf16c -fopenmp -shared -fPIC \
8 * -o c_engine.so c_engine.c -lm
9 */
10#include <stdint.h>
11#include <string.h>
12#include <math.h>
13#include <immintrin.h>
14#include <omp.h>
15
16#define Q4_0_BS 18
17#define Q8_0_BS 34
18
19/* ═══ AVX2 helpers ═════════════════════════════════════════════════════ */
20static inline float f16_to_f32(uint16_t h) { return _cvtsh_ss(h); }
21static inline float hsum_ps(__m256 v) {
22 __m128 lo=_mm256_castps256_ps128(v), hi=_mm256_extractf128_ps(v,1);
23 lo=_mm_add_ps(lo,hi); lo=_mm_hadd_ps(lo,lo); lo=_mm_hadd_ps(lo,lo);
24 return _mm_cvtss_f32(lo);
25}
26
27/* ═══ Q4_0 dot (inline AVX2, no function pointers) ═══════════════════ */
28static inline float q4_row(const uint8_t *W, const float *x, int nc, int r) {
29 int bp=nc/32; __m256 s0=_mm256_setzero_ps(),s1=_mm256_setzero_ps();
30 for(int b=0;b<bp;b++){
31 const uint8_t *p=W+((size_t)r*bp+b)*Q4_0_BS;
32 float sc=f16_to_f32((uint16_t)p[0]|((uint16_t)p[1]<<8));
33 __m256 sv=_mm256_set1_ps(sc);
34 __m128i nb=_mm_loadu_si128((const __m128i*)(p+2));
35 __m128i lo=_mm_and_si128(nb,_mm_set1_epi8(15));
36 __m128i hi=_mm_and_si128(_mm_srli_epi16(nb,4),_mm_set1_epi8(15));
37 __m128i ls=_mm_sub_epi8(lo,_mm_set1_epi8(8)),hs=_mm_sub_epi8(hi,_mm_set1_epi8(8));
38 __m256 v0=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(ls)));
39 __m256 v1=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(_mm_shuffle_epi32(ls,0x4e))));
40 __m256 v2=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(hs)));
41 __m256 v3=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(_mm_shuffle_epi32(hs,0x4e))));
42 v0=_mm256_mul_ps(v0,sv);v1=_mm256_mul_ps(v1,sv);v2=_mm256_mul_ps(v2,sv);v3=_mm256_mul_ps(v3,sv);
43 int o=b*32;
44 s0=_mm256_fmadd_ps(v0,_mm256_loadu_ps(x+o),s0);
45 s0=_mm256_fmadd_ps(v1,_mm256_loadu_ps(x+o+8),s0);
46 s1=_mm256_fmadd_ps(v2,_mm256_loadu_ps(x+o+16),s1);
47 s1=_mm256_fmadd_ps(v3,_mm256_loadu_ps(x+o+24),s1);
48 }
49 return hsum_ps(_mm256_add_ps(s0,s1));
50}
51
52/* Q8_0 dot for output projection */
53static inline float q8_row(const uint8_t *W, const float *x, int nc, int r) {
54 int bp=nc/32; float t=0;
55 for(int b=0;b<bp;b++){
56 const uint8_t *p=W+((size_t)r*bp+b)*Q8_0_BS;
57 float d=f16_to_f32((uint16_t)p[0]|((uint16_t)p[1]<<8));
58 const int8_t *qs=(const int8_t*)(p+2);
59 __m256 dv=_mm256_set1_ps(d),bs=_mm256_setzero_ps(); int o=b*32;
60 for(int i=0;i<32;i+=8){
61 __m128i q8=_mm_loadl_epi64((const __m128i*)(qs+i));
62 __m256 v=_mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(q8))),dv);
63 bs=_mm256_fmadd_ps(v,_mm256_loadu_ps(x+o+i),bs);
64 }
65 t+=hsum_ps(bs);
66 }
67 return t;
68}
69
70/* ═══ RMS norm ══════════════════════════════════════════════════════ */
71static inline void rms(float *o, const float *x, const float *w, int n, float e){
72 __m256 ss=_mm256_setzero_ps(); int i;
73 for(i=0;i<=n-8;i+=8){__m256 v=_mm256_loadu_ps(x+i);ss=_mm256_fmadd_ps(v,v,ss);}
74 __m256 hh=_mm256_hadd_ps(ss,_mm256_permute2f128_ps(ss,ss,1));
75 hh=_mm256_hadd_ps(hh,hh);hh=_mm256_hadd_ps(hh,hh);
76 float sse=_mm256_cvtss_f32(hh); for(;i<n;i++)sse+=x[i]*x[i];
77 float ir=1.0f/sqrtf(sse/n+e);__m256 iv=_mm256_set1_ps(ir);
78 for(i=0;i<=n-8;i+=8){__m256 xv=_mm256_loadu_ps(x+i),wv=_mm256_loadu_ps(w+i);
79 _mm256_storeu_ps(o+i,_mm256_mul_ps(_mm256_mul_ps(xv,iv),wv));}
80 for(;i<n;i++)o[i]=x[i]*ir*w[i];
81}
82
83/* ═══ GQA attention ═══════════════════════════════════════════════════ */
84static void gqa(float *o, const float *q, const float *kc, const float *vc,
85 int sl, int nh, int nkh, int hd){
86 int gr=nh/nkh;
87 #pragma omp parallel for schedule(static)
88 for(int h=0;h<nh;h++){
89 int kv=h/gr;const float *qh=q+h*hd,*kb=kc+kv*hd,*vb=vc+kv*hd;
90 int ks=nkh*hd;float *oh=o+h*hd,sc[4096],mx=-1e30f,inv=1.0f/sqrtf(hd);
91 for(int s=0;s<sl;s++){const float*ks_=kb+s*ks;__m256 su=_mm256_setzero_ps();
92 int d;for(d=0;d<=hd-8;d+=8)su=_mm256_fmadd_ps(_mm256_loadu_ps(qh+d),_mm256_loadu_ps(ks_+d),su);
93 float dot=hsum_ps(su)*inv;for(;d<hd;d++)dot+=qh[d]*ks_[d];
94 sc[s]=dot;if(dot>mx)mx=dot;}
95 float se=0;for(int s=0;s<sl;s++){sc[s]=expf(sc[s]-mx);se+=sc[s];}
96 float is=1.0f/se;memset(oh,0,hd*sizeof(float));
97 for(int s=0;s<sl;s++){const float*vs_=vb+s*ks;float w=sc[s]*is;__m256 wv=_mm256_set1_ps(w);
98 int d;for(d=0;d<=hd-8;d+=8){__m256 vv=_mm256_loadu_ps(vs_+d);
99 __m256 ac=_mm256_loadu_ps(oh+d);_mm256_storeu_ps(oh+d,_mm256_fmadd_ps(wv,vv,ac));}
100 for(;d<hd;d++)oh[d]+=w*vs_[d];}
101 }
102}
103
104/* ═══ EngineConfig struct ════════════════════════════════════════════ */
105typedef struct {
106 int L,N,NH,NKH,HD,FF,V;
107 float eps;
108 /* Per-layer pointers [L] */
109 const uint8_t **wQ,**wK,**wV,**wO,**wG,**wU,**wD;
110 const float **wAN,**wFN;
111 const int *nQ,*nK,*nV,*nO,*nG,*nU,*nD;
112 int nc;
113 /* Embed + output */
114 const float *emb,*onw;
115 const uint8_t *wOut; int outNR,outNC;
116 /* KV cache + workspace (mutable) */
117 float *kvK,*kvV; int *kvL; int MP;
118 float *x,*xn,*res,*q,*k,*v,*att,*gate,*up,*silu,*oproj,*ffn;
119} EC;
120
121/* ═══ engine_forward — one token, no Python ═════════════════════════ */
122void engine_forward(int tok, EC *c, float *logits) {
123 int N=c->N,NH=c->NH,NKH=c->NKH,HD=c->HD,FF=c->FF,L=c->L,nc=c->nc;
124 float *x=c->x,*xn=c->xn,*res=c->res,*q=c->q,*k=c->k,*v=c->v;
125 float *att=c->att,*gate=c->gate,*up=c->up,*silu=c->silu,*o=c->oproj,*ffn=c->ffn;
126
127 memcpy(x, c->emb + (size_t)tok * N, N*sizeof(float));
128
129 for(int l=0;l<L;l++){
130 memcpy(res, x, N*sizeof(float));
131 rms(xn, x, c->wAN[l], N, c->eps);
132
133 /* QKV batch */
134 int tq=c->nQ[l]+c->nK[l]+c->nV[l];
135 #pragma omp parallel for schedule(static)
136 for(int i=0;i<tq;i++){
137 if(i<c->nQ[l]) q[i]=q4_row(c->wQ[l],xn,nc,i);
138 else if(i<c->nQ[l]+c->nK[l]) k[i-c->nQ[l]]=q4_row(c->wK[l],xn,nc,i-c->nQ[l]);
139 else v[i-c->nQ[l]-c->nK[l]]=q4_row(c->wV[l],xn,nc,i-c->nQ[l]-c->nK[l]);
140 }
141
142 /* RoPE (pre-computed tables — cos_tbl/sin_tbl stored at end of EC) */
143 int pos=c->kvL[l], hd=HD, h=hd/2;
144 const float *ct=c->x+4096*h; /* FIXME: use proper cos/sin pointers */
145 /* Simple RoPE with on-the-fly computation (fast enough for <100 pos) */
146 for(int hh=0;hh<NH;hh++){float *qh=q+hh*hd;
147 for(int j=0;j<h;j++){
148 double ang=(double)pos/pow(10000.0,2.0*j/hd);
149 double cs=cos(ang),sn=sin(ang);
150 float a=qh[j],b=qh[j+h];qh[j]=(float)(a*cs-b*sn);qh[j+h]=(float)(b*cs+a*sn);}}
151 for(int hh=0;hh<NKH;hh++){float *kh=k+hh*hd;
152 for(int j=0;j<h;j++){
153 double ang=(double)pos/pow(10000.0,2.0*j/hd);
154 double cs=cos(ang),sn=sin(ang);
155 float a=kh[j],b=kh[j+h];kh[j]=(float)(a*cs-b*sn);kh[j+h]=(float)(b*cs+a*sn);}}
156
157 /* KV store */
158 memcpy(c->kvK+((size_t)l*c->MP+c->kvL[l])*NKH*HD, k, NKH*HD*sizeof(float));
159 memcpy(c->kvV+((size_t)l*c->MP+c->kvL[l])*NKH*HD, v, NKH*HD*sizeof(float));
160
161 /* GQA attention */
162 int sl=c->kvL[l]+1;
163 gqa(att, q, c->kvK+(size_t)l*c->MP*NKH*HD, c->kvV+(size_t)l*c->MP*NKH*HD,
164 sl, NH, NKH, HD);
165 c->kvL[l]++;
166
167 /* O proj + residual */
168 #pragma omp parallel for schedule(static)
169 for(int i=0;i<c->nO[l];i++) o[i]=q4_row(c->wO[l],att,nc,i);
170 for(int i=0;i<N;i++) x[i]=res[i]+o[i];
171
172 /* FFN: norm2 */
173 memcpy(res, x, N*sizeof(float));
174 rms(xn, x, c->wFN[l], N, c->eps);
175
176 /* Gate+Up batch */
177 int tg=c->nG[l]+c->nU[l];
178 #pragma omp parallel for schedule(static)
179 for(int i=0;i<tg;i++){
180 if(i<c->nG[l]) gate[i]=q4_row(c->wG[l],xn,nc,i);
181 else up[i-c->nG[l]]=q4_row(c->wU[l],xn,nc,i-c->nG[l]);
182 }
183
184 /* SiLU * up */
185 for(int i=0;i<FF;i++){float g=gate[i];silu[i]=(g/(1.0f+expf(-g)))*up[i];}
186
187 /* Down + residual */
188 #pragma omp parallel for schedule(static)
189 for(int i=0;i<c->nD[l];i++) ffn[i]=q4_row(c->wD[l],silu,nc,i);
190 for(int i=0;i<N;i++) x[i]=res[i]+ffn[i];
191 }
192
193 /* Final norm + output */
194 rms(xn, x, c->onw, N, c->eps);
195 #pragma omp parallel for schedule(static)
196 for(int i=0;i<c->outNR;i++) logits[i]=q8_row(c->wOut,xn,c->outNC,i);
197}