MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / turbo_engine_v77.py
| 1 | #!/usr/bin/env python3 |
| 2 | """TurboEngine v7.7 — v7 + C GQA attention + AVX2 v2 kernels + RoPE precompute. |
| 3 | |
| 4 | Changes from v7.5: |
| 5 | 1. C GQA attention kernel (replaces numpy einsum + GQA repeat) |
| 6 | 2. AVX2 v2 for individual matmuls (O proj, Down) |
| 7 | 3. Pre-computed RoPE tables for all positions up to max_seq_len |
| 8 | 4. Keep batch_qkv_omp and batch_gate_up_omp for fused OMP matmuls |
| 9 | |
| 10 | Combined expected: 78 → ~86 tok/s = 92% of llama.cpp |
| 11 | """ |
| 12 | import numpy as np, ctypes, os, gguf |
| 13 | from gguf.constants import GGMLQuantizationType as QT |
| 14 | import math |
| 15 | |
| 16 | GGML_F32=0; GGML_F16=1; GGML_Q4_0=2; GGML_Q4_1=3; GGML_Q8_0=8 |
| 17 | GGML_Q4_K=12; GGML_Q5_K=13; GGML_Q6_K=14 |
| 18 | BLOCK_SIZES={2:18,3:20,12:144,13:176,14:210,8:34} |
| 19 | C_KERNEL_TYPES={GGML_Q4_0,GGML_Q4_1,GGML_Q4_K,GGML_Q5_K,GGML_Q6_K,GGML_Q8_0} |
| 20 | AVX2_TYPES={GGML_Q4_0,GGML_Q4_1,GGML_Q8_0} |
| 21 | |
| 22 | class TurboEngineV77: |
| 23 | def __init__(self, model_path, n_threads=32): |
| 24 | os.environ['OMP_NUM_THREADS']=str(n_threads) |
| 25 | self.n_threads=n_threads |
| 26 | self.reader=gguf.GGUFReader(model_path) |
| 27 | self._parse_metadata() |
| 28 | self._load_weights() |
| 29 | self._load_kernels() |
| 30 | self._preload_layer_weights() |
| 31 | self._init_kv_cache() |
| 32 | self._precompute_rope() |
| 33 | self._eps_f=ctypes.c_float(self.eps) |
| 34 | self.reset() |
| 35 | print(f"TurboEngine v7.7: {self.n_layers}L/{self.n_embd}D/" |
| 36 | f"{self.n_ff}FF/{self.n_head}H/{self.n_kv_head}KV | t={n_threads}") |
| 37 | |
| 38 | def _parse_metadata(self): |
| 39 | fields=self.reader.fields |
| 40 | def _get(n): |
| 41 | for k,v in fields.items(): |
| 42 | if k==n: |
| 43 | p=v.parts if hasattr(v,'parts') else [] |
| 44 | if len(p)>=1: |
| 45 | d=p[-1] |
| 46 | if hasattr(d,'__iter__') and len(d)==1: return int(d[0]) |
| 47 | return d |
| 48 | arch='llama' |
| 49 | for p in ['qwen3moe','qwen2moe','qwen2vl','qwen2','llama','mistral']: |
| 50 | for k in fields: |
| 51 | if f'{p}.block_count' in k: arch=p; break |
| 52 | self.n_layers=int(_get(f'{arch}.block_count') or 16) |
| 53 | self.n_embd=int(_get(f'{arch}.embedding_length') or 2048) |
| 54 | self.n_ff=int(_get(f'{arch}.feed_forward_length') or self.n_embd*4) |
| 55 | self.n_head=int(_get(f'{arch}.attention.head_count') or 32) |
| 56 | self.n_kv_head=int(_get(f'{arch}.attention.head_count_kv') or self.n_head) |
| 57 | self.head_dim=int(_get(f'{arch}.attention.key_length') or (self.n_embd//self.n_head)) |
| 58 | self.rope_freq_base=float(_get(f'{arch}.rope.freq_base') or 10000.0) |
| 59 | self.eps=float(_get(f'{arch}.attention.layer_norm_rms_epsilon') or 1e-6) |
| 60 | self.vocab_size=int(_get(f'{arch}.vocab_size') or 0) |
| 61 | self.n_experts=_get(f'{arch}.expert_count') |
| 62 | self.n_experts_per_tok=_get(f'{arch}.expert_used_count') |
| 63 | self.is_moe=self.n_experts is not None |
| 64 | if not self.is_moe: self.n_experts=1; self.n_experts_per_tok=1 |
| 65 | else: self.n_experts=int(self.n_experts); self.n_experts_per_tok=int(self.n_experts_per_tok) |
| 66 | self.arch_prefix=arch |
| 67 | |
| 68 | def _load_weights(self): |
| 69 | self.weights={}; self.raw_weights={}; self.weight_info={} |
| 70 | for t in self.reader.tensors: |
| 71 | name=t.name; qt=QT(t.tensor_type).value |
| 72 | if len(t.shape)==2: |
| 73 | in_dim,out_dim=int(t.shape[0]),int(t.shape[1]) |
| 74 | f32=gguf.dequantize(t.data,t.tensor_type).astype(np.float32).reshape(out_dim,in_dim) |
| 75 | self.weights[name]=np.ascontiguousarray(f32) |
| 76 | if qt in C_KERNEL_TYPES: |
| 77 | raw=np.ascontiguousarray(t.data.reshape(-1),dtype=np.uint8).copy() |
| 78 | self.raw_weights[name]=raw |
| 79 | self.weight_info[name]=(out_dim,in_dim,BLOCK_SIZES[qt],qt) |
| 80 | elif len(t.shape)==3: |
| 81 | in_dim,out_dim,ne=int(t.shape[0]),int(t.shape[1]),int(t.shape[2]) |
| 82 | f32=gguf.dequantize(t.data,t.tensor_type).astype(np.float32).reshape(ne,out_dim,in_dim) |
| 83 | self.weights[name]=np.ascontiguousarray(f32) |
| 84 | elif len(t.shape)==1: |
| 85 | f32=gguf.dequantize(t.data,t.tensor_type).astype(np.float32).reshape(-1) |
| 86 | self.weights[name]=np.ascontiguousarray(f32) |
| 87 | self.out_w_name='output.weight' if 'output.weight' in self.weights else 'token_embd.weight' |
| 88 | emb=self.weights['token_embd.weight'] |
| 89 | if emb.ndim==2 and emb.shape[1]!=self.n_embd: emb=np.ascontiguousarray(emb.T); self.weights['token_embd.weight']=emb |
| 90 | if self.vocab_size==0: self.vocab_size=emb.shape[0] |
| 91 | self.emb=emb |
| 92 | |
| 93 | def _load_kernels(self): |
| 94 | kd=os.path.dirname(os.path.abspath(__file__)) |
| 95 | cf=ctypes.POINTER(ctypes.c_float); cu=ctypes.POINTER(ctypes.c_uint8); ci=ctypes.c_int |
| 96 | |
| 97 | # OMP kernels |
| 98 | o=ctypes.CDLL(os.path.join(kd,'quant_kernels_omp.so')) |
| 99 | o.quant_matmul_omp.argtypes=[cu,cf,cf,ci,ci,ci]; o.quant_matmul_omp.restype=None |
| 100 | o.batch_qkv_omp.argtypes=[cu,cu,cu,cf,cf,cf,cf,ci,ci,ci,ci,ci,ci]; o.batch_qkv_omp.restype=None |
| 101 | o.batch_gate_up_omp.argtypes=[cu,cu,cf,cf,cf,ci,ci,ci,ci]; o.batch_gate_up_omp.restype=None |
| 102 | o.set_num_threads.argtypes=[ci]; o.set_num_threads.restype=None; o.set_num_threads(self.n_threads) |
| 103 | self._kern=o |
| 104 | |
| 105 | # AVX2 v2 kernels |
| 106 | v2p=os.path.join(kd,'turbo_kernels_v2.so') |
| 107 | if os.path.exists(v2p): |
| 108 | v2=ctypes.CDLL(v2p) |
| 109 | v2.quant_matmul_v2.argtypes=[cu,cf,cf,ci,ci,ci]; v2.quant_matmul_v2.restype=None |
| 110 | self._v2=v2 |
| 111 | else: self._v2=None |
| 112 | |
| 113 | # SIMD ops |
| 114 | s=ctypes.CDLL(os.path.join(kd,'simd_ops.so')) |
| 115 | s.rms_norm.argtypes=[cf,cf,cf,ci,ctypes.c_float]; s.rms_norm.restype=None |
| 116 | s.silu.argtypes=[cf,cf,ci]; s.silu.restype=None |
| 117 | self._simd=s |
| 118 | |
| 119 | # GQA attention |
| 120 | a=ctypes.CDLL(os.path.join(kd,'gqa_attention.so')) |
| 121 | a.gqa_attention_decode.argtypes=[cf,cf,cf,cf,ci,ci,ci,ci]; a.gqa_attention_decode.restype=None |
| 122 | self._attn=a |
| 123 | |
| 124 | def _matmul(self, rp, xp, op, nr, nc, qt, v2): |
| 125 | if v2 and self._v2: self._v2.quant_matmul_v2(rp,xp,op,nr,nc,qt) |
| 126 | else: self._kern.quant_matmul_omp(rp,xp,op,nr,nc,qt) |
| 127 | |
| 128 | def _preload_layer_weights(self): |
| 129 | self._layers=[] |
| 130 | for i in range(self.n_layers): |
| 131 | pfx=f'blk.{i}' |
| 132 | pn=['attn_q','attn_k','attn_v','attn_output','ffn_gate','ffn_up','ffn_down'] |
| 133 | lw={} |
| 134 | for a in pn: |
| 135 | n=f'{pfx}.{a}.weight' |
| 136 | info=self.weight_info.get(n) |
| 137 | if info: |
| 138 | r=self.raw_weights[n] |
| 139 | lw[a]={'raw':r.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), |
| 140 | 'nr':ctypes.c_int(info[0]),'nc':ctypes.c_int(info[1]), |
| 141 | 'qt':ctypes.c_int(info[3]),'v2':info[3] in AVX2_TYPES and self._v2} |
| 142 | else: lw[a]={'f32':self.weights[n],'v2':False} |
| 143 | lw['ann_w']=self.weights[f'{pfx}.attn_norm.weight'] |
| 144 | lw['fnn_w']=self.weights[f'{pfx}.ffn_norm.weight'] |
| 145 | self._layers.append(lw) |
| 146 | # Output proj |
| 147 | oi=self.weight_info.get(self.out_w_name) |
| 148 | if oi: |
| 149 | self._onr=ctypes.c_int(oi[0]); self._onc=ctypes.c_int(oi[1]) |
| 150 | if oi[3] in (6,14,12,10): |
| 151 | self._or=self._requant(oi) |
| 152 | self._oqt=ctypes.c_int(8); self._ov2=True |
| 153 | else: |
| 154 | self._or=self.raw_weights[self.out_w_name].ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 155 | self._oqt=ctypes.c_int(oi[3]); self._ov2=oi[3] in AVX2_TYPES |
| 156 | else: self._or=None |
| 157 | self._onw=self.weights['output_norm.weight'] |
| 158 | |
| 159 | def _requant(self, oi): |
| 160 | nr,nc=oi[0],oi[1]; nb=nc//32 |
| 161 | f32=np.zeros((nr,nc),dtype=np.float32) |
| 162 | if oi[3]==14: |
| 163 | nblk=nc//256 |
| 164 | self._kern.q6_k_dequantize_row.argtypes=[ctypes.POINTER(ctypes.c_uint8),ctypes.POINTER(ctypes.c_float),ctypes.c_int] |
| 165 | self._kern.q6_k_dequantize_row.restype=None |
| 166 | rp=self.raw_weights[self.out_w_name].ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 167 | ba=ctypes.addressof(rp.contents) |
| 168 | for r in range(nr): |
| 169 | ptr=ctypes.cast(ba+r*nblk*210,ctypes.POINTER(ctypes.c_uint8)) |
| 170 | self._kern.q6_k_dequantize_row(ptr,f32[r].ctypes.data_as(ctypes.POINTER(ctypes.c_float)),ctypes.c_int(nc)) |
| 171 | blks=f32.reshape(nr,nb,32); amax=np.max(np.abs(blks),axis=2,keepdims=True) |
| 172 | amax=np.clip(amax,1e-10,None); d=amax/127.0 |
| 173 | qs=np.clip(np.round(blks/d),-127,127).astype(np.int8) |
| 174 | dh=d[:,:,0].astype(np.float16).view(np.uint16) |
| 175 | q8=np.zeros((nr,nb,34),dtype=np.uint8) |
| 176 | q8[:,:,0]=dh&0xFF; q8[:,:,1]=(dh>>8)&0xFF; q8[:,:,2:]=qs.view(np.uint8) |
| 177 | self._oq8=np.ascontiguousarray(q8.reshape(-1),dtype=np.uint8) |
| 178 | print(f" Output: {nr}×{nc} → Q8_0 ({len(self._oq8)/1024/1024:.0f} MB)") |
| 179 | return self._oq8.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 180 | |
| 181 | def _init_kv_cache(self): |
| 182 | N=self.n_embd; NKH=self.n_kv_head; HD=self.head_dim; MP=4096 |
| 183 | self.kvk=np.zeros((self.n_layers,MP,NKH*HD),dtype=np.float32) |
| 184 | self.kvv=np.zeros((self.n_layers,MP,NKH*HD),dtype=np.float32) |
| 185 | self.kvl=np.zeros(self.n_layers,dtype=np.int32) |
| 186 | NK=self.n_head*HD; FF=self.n_ff |
| 187 | self._x=np.zeros(N,dtype=np.float32); self._xn=np.zeros(N,dtype=np.float32) |
| 188 | self._res=np.zeros(N,dtype=np.float32) |
| 189 | self._q=np.zeros(NK,dtype=np.float32); self._k=np.zeros(NKH*HD,dtype=np.float32) |
| 190 | self._v=np.zeros(NKH*HD,dtype=np.float32); self._att=np.zeros(NK,dtype=np.float32) |
| 191 | self._g=np.zeros(FF,dtype=np.float32); self._u=np.zeros(FF,dtype=np.float32) |
| 192 | self._s=np.zeros(FF,dtype=np.float32); self._o=np.zeros(N,dtype=np.float32) |
| 193 | self._f=np.zeros(N,dtype=np.float32); self._lg=np.zeros(self.vocab_size,dtype=np.float32) |
| 194 | |
| 195 | def _precompute_rope(self): |
| 196 | """Pre-compute all RoPE cos/sin tables for positions 0-4095.""" |
| 197 | hd=self.head_dim; half=hd//2 |
| 198 | freq=self.rope_freq_base**(np.arange(0,hd,2,dtype=np.float32)/hd) |
| 199 | self._rc=np.zeros((4096,half),dtype=np.float32) |
| 200 | self._rs=np.zeros((4096,half),dtype=np.float32) |
| 201 | for p in range(4096): |
| 202 | ang=p/freq |
| 203 | self._rc[p]=np.cos(ang).astype(np.float32) |
| 204 | self._rs[p]=np.sin(ang).astype(np.float32) |
| 205 | |
| 206 | def _rope(self, x, pos, nh): |
| 207 | hd=self.head_dim; h=hd//2 |
| 208 | c=self._rc[pos]; s=self._rs[pos] |
| 209 | x2=x.reshape(nh,hd); o=x2.copy() |
| 210 | o[:,:h]=x2[:,:h]*c-x2[:,h:]*s; o[:,h:]=x2[:,h:]*c+x2[:,:h]*s |
| 211 | return o.reshape(-1) |
| 212 | |
| 213 | def reset(self): self.kvl[:]=0; self.pos=0 |
| 214 | |
| 215 | def forward(self, token_id): |
| 216 | bx=self._x; bxn=self._xn; br=self._res; bq=self._q; bk=self._k; bv=self._v |
| 217 | ba=self._att; bg=self._g; bu=self._u; bs=self._s; bo=self._o; bf=self._f |
| 218 | N=self.n_embd; NH=self.n_head; NKH=self.n_kv_head; HD=self.head_dim |
| 219 | FF=self.n_ff; L=self.n_layers |
| 220 | k=self._kern; d=self._simd; a=self._attn; e=self._eps_f |
| 221 | px=self._x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 222 | pxn=self._xn.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 223 | pr=self._res.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 224 | pq=self._q.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 225 | pk=self._k.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 226 | pv=self._v.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 227 | pa=self._att.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 228 | pg=self._g.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 229 | pu=self._u.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 230 | ps=self._s.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 231 | po=self._o.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 232 | pf=self._f.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 233 | pl=self._lg.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 234 | ci=ctypes.c_int |
| 235 | |
| 236 | np.copyto(bx, self.emb[token_id]) |
| 237 | |
| 238 | for i in range(L): |
| 239 | lw=self._layers[i] |
| 240 | np.clip(bx, -1000.0, 1000.0, out=bx) |
| 241 | np.copyto(br, bx) |
| 242 | d.rms_norm(pxn, px, lw['ann_w'].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), N, e) |
| 243 | |
| 244 | # QKV batch |
| 245 | if 'attn_q' in lw and 'raw' in lw['attn_q']: |
| 246 | k.batch_qkv_omp(lw['attn_q']['raw'],lw['attn_k']['raw'],lw['attn_v']['raw'], |
| 247 | pxn,pq,pk,pv,lw['attn_q']['nr'],lw['attn_k']['nr'],lw['attn_v']['nr'], |
| 248 | lw['attn_q']['nc'],lw['attn_q']['qt'],lw['attn_k']['qt'],lw['attn_v']['qt']) |
| 249 | |
| 250 | # RoPE |
| 251 | bq[:]=self._rope(bq, self.pos, NH) |
| 252 | bk[:]=self._rope(bk, self.pos, NKH) |
| 253 | |
| 254 | # KV store |
| 255 | self.kvk[i,self.kvl[i],:NKH*HD]=bk[:NKH*HD] |
| 256 | self.kvv[i,self.kvl[i],:NKH*HD]=bv[:NKH*HD] |
| 257 | |
| 258 | # ── C GQA attention ── |
| 259 | sl=self.kvl[i]+1 |
| 260 | kc=self.kvk[i,:sl].reshape(-1); vc=self.kvv[i,:sl].reshape(-1) |
| 261 | a.gqa_attention_decode(bq.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 262 | kc.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 263 | vc.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 264 | ba.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 265 | ci(sl),ci(NH),ci(NKH),ci(HD)) |
| 266 | self.kvl[i]+=1 |
| 267 | |
| 268 | # O proj + residual |
| 269 | self._matmul(lw['attn_output']['raw'], pa, po, |
| 270 | lw['attn_output']['nr'], lw['attn_output']['nc'], lw['attn_output']['qt'], |
| 271 | lw['attn_output'].get('v2',False)) |
| 272 | bx[:N]=br[:N]+bo[:N] |
| 273 | |
| 274 | # FFN |
| 275 | np.clip(bx, -1000.0, 1000.0, out=bx) |
| 276 | np.copyto(br, bx) |
| 277 | d.rms_norm(pxn, px, lw['fnn_w'].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), N, e) |
| 278 | |
| 279 | # Gate+Up batch |
| 280 | k.batch_gate_up_omp(lw['ffn_gate']['raw'],lw['ffn_up']['raw'],pxn,pg,pu, |
| 281 | lw['ffn_gate']['nr'],lw['ffn_up']['nr'], |
| 282 | lw['ffn_gate']['nc'],lw['ffn_gate']['qt'],lw['ffn_up']['qt']) |
| 283 | |
| 284 | # SiLU * up |
| 285 | d.silu(ps, pg, ci(FF)) |
| 286 | bs[:FF]=bs[:FF]*bu[:FF] |
| 287 | |
| 288 | # Down + residual |
| 289 | self._matmul(lw['ffn_down']['raw'], ps, pf, |
| 290 | lw['ffn_down']['nr'], lw['ffn_down']['nc'], lw['ffn_down']['qt'], |
| 291 | lw['ffn_down'].get('v2',False)) |
| 292 | bx[:N]=br[:N]+bf[:N] |
| 293 | |
| 294 | # Final |
| 295 | np.clip(bx, -1000.0, 1000.0, out=bx) |
| 296 | d.rms_norm(pxn, px, self._onw.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), N, e) |
| 297 | self._matmul(self._or, pxn, pl, self._onr, self._onc, self._oqt, self._ov2) |
| 298 | self.pos+=1 |
| 299 | return self._lg |