MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / server_moe.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MoE K-quant server using cengine_batch.so with TurboEngineV7MoE.""" |
| 3 | import sys,os,json,time,threading,queue,ctypes |
| 4 | import numpy as np |
| 5 | from http.server import HTTPServer, BaseHTTPRequestHandler |
| 6 | from urllib.parse import urlparse |
| 7 | from socketserver import ThreadingMixIn |
| 8 | |
| 9 | MODEL_PATH = sys.argv[1] if len(sys.argv) > 1 else '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf' |
| 10 | PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8080 |
| 11 | |
| 12 | # Auto-load tuned config for thread count & concurrency |
| 13 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 14 | _moe_threads = 32 |
| 15 | try: |
| 16 | from mojollama.backends import load_tuned_config |
| 17 | _cfg = load_tuned_config() |
| 18 | if _cfg and 'mojollama_engine' in _cfg: |
| 19 | _me = _cfg['mojollama_engine'] |
| 20 | _moe_threads = _me.get('threads', 32) |
| 21 | os.environ['OMP_NUM_THREADS'] = str(_moe_threads) |
| 22 | print(f"[Config] Loaded auto-tuned settings: {_moe_threads} threads, " |
| 23 | f"optimal concurrency {_me.get('optimal_concurrency', '?')}", flush=True) |
| 24 | except Exception: |
| 25 | pass |
| 26 | |
| 27 | sys.path.insert(0,os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'kernels')) |
| 28 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 29 | e = TurboEngineV7MoE(MODEL_PATH, _moe_threads) |
| 30 | L=e.n_layers; N=e.n_embd; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim; FF=e.n_ff; V=e.vocab_size |
| 31 | NE=e.n_experts; NK=e.n_experts_per_tok; moe_int=e.n_ff_expert |
| 32 | S = max(N, NH*HD, FF, NKH*HD, moe_int); BOS=1; EOS=2 |
| 33 | print(f"Engine: {L}L/{N}D/{FF}FF/{NH}H/{NKH}KV | MoE {NE}×{NK} | int={moe_int} | V={V}", flush=True) |
| 34 | |
| 35 | cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float |
| 36 | lib=ctypes.CDLL(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'kernels','cengine_batch_instr.so')) |
| 37 | |
| 38 | class BC(ctypes.Structure): |
| 39 | _fields_ = [("L",ci),("N",ci),("NH",ci),("NKH",ci),("HD",ci),("FF",ci),("V",ci),("eps",cf), |
| 40 | ("wQ",cv),("wK",cv),("wV",cv),("wO",cv),("wG",cv),("wU",cv),("wD",cv), |
| 41 | ("wAN",cv),("wFN",cv),("nQ",cv),("nK",cv),("nV",cv),("nO",cv),("nG",cv),("nU",cv),("nD",cv), |
| 42 | ("nc",ci),("emb",cv),("onw",cv),("wOut",cv),("outNR",ci),("outNC",ci),("outQuant",ci), |
| 43 | ("kv_array",cv),("logits",cv), |
| 44 | ("n_experts",ci),("n_experts_per_tok",ci),("moe_intermediate",ci), |
| 45 | ("w_gate_inp",cv),("w_gate_exps",cv),("w_up_exps",cv),("w_down_exps",cv), |
| 46 | ("gate_exp_quant",ci),("up_exp_quant",ci),("down_exp_quant",ci), |
| 47 | ("q_quant",cv),("k_quant",cv),("v_quant",cv),("o_quant",cv), |
| 48 | ("g_quant",cv),("u_quant",cv),("d_quant",cv),("emb_quant",ci), |
| 49 | ("wQK",cv),("qk_quant",cv), |
| 50 | ("cos_table",cv),("sin_table",cv),("max_ctx",ci), |
| 51 | ("workspace",cv),("ws_size",ci)] |
| 52 | |
| 53 | class KVBlock(ctypes.Structure): |
| 54 | _fields_ = [("k",cv),("v",cv),("n_blocks",ci),("seq_len",ci*64),("block_map",(ci*1024)*64)] |
| 55 | |
| 56 | lib.kv_init.argtypes=[cv,ci,ci,ci]; lib.kv_init.restype=None |
| 57 | lib.batch_forward.argtypes=[cv,cv,ci,cv]; lib.batch_forward.restype=None |
| 58 | |
| 59 | # Build per-layer pointer arrays |
| 60 | def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr]) |
| 61 | def ia(arr): return (ci*L)(*[int(a) for a in arr]) |
| 62 | |
| 63 | wQ_arr=[0]*L; wK_arr=[0]*L; wV_arr=[0]*L; wO_arr=[0]*L |
| 64 | wG_arr=[0]*L; wU_arr=[0]*L; wD_arr=[0]*L |
| 65 | wAN_arr=[0]*L; wFN_arr=[0]*L |
| 66 | wQK_arr=[0]*L; qkQ_arr=[0]*L # fused Q+K weight (NULL if types don't match) |
| 67 | nQ_arr=[0]*L; nK_arr=[0]*L; nV_arr=[0]*L; nO_arr=[0]*L; nG_arr=[0]*L; nU_arr=[0]*L; nD_arr=[0]*L |
| 68 | qQ_arr=[0]*L; qK_arr=[0]*L; qV_arr=[0]*L; qO_arr=[0]*L; qG_arr=[0]*L; qU_arr=[0]*L; qD_arr=[0]*L |
| 69 | |
| 70 | for i,lw in enumerate(e._layers): |
| 71 | wQ_arr[i]=lw.attn_q_raw; nQ_arr[i]=lw.attn_q_nr.value; qQ_arr[i]=lw.attn_q_qt.value |
| 72 | wK_arr[i]=lw.attn_k_raw; nK_arr[i]=lw.attn_k_nr.value; qK_arr[i]=lw.attn_k_qt.value |
| 73 | wV_arr[i]=lw.attn_v_raw; nV_arr[i]=lw.attn_v_nr.value; qV_arr[i]=lw.attn_v_qt.value |
| 74 | wO_arr[i]=lw.attn_out_raw; nO_arr[i]=lw.attn_out_nr.value; qO_arr[i]=lw.attn_out_qt.value |
| 75 | wAN_arr[i]=lw.attn_norm_w.ctypes.data_as(cv); wFN_arr[i]=lw.ffn_norm_w.ctypes.data_as(cv) |
| 76 | # Fused Q+K weight (if available) |
| 77 | if hasattr(lw,'attn_qk_use_c') and lw.attn_qk_use_c: |
| 78 | wQK_arr[i]=lw.attn_qk_raw; qkQ_arr[i]=lw.attn_qk_qt.value |
| 79 | else: |
| 80 | wQK_arr[i]=cv(0); qkQ_arr[i]=0 |
| 81 | for i,me in enumerate(e._moe_layers): |
| 82 | wG_arr[i]=me.gate_raw[0].ctypes.data_as(cv) if me.gate_raw else cv(0) |
| 83 | wU_arr[i]=me.up_raw[0].ctypes.data_as(cv) if me.up_raw else cv(0) |
| 84 | wD_arr[i]=me.down_raw[0].ctypes.data_as(cv) if me.down_raw else cv(0) |
| 85 | nG_arr[i]=me.gate_nr.value; nU_arr[i]=me.up_nr.value; nD_arr[i]=me.down_nr.value |
| 86 | qG_arr[i]=me.gate_qt.value; qU_arr[i]=me.up_qt.value; qD_arr[i]=me.down_qt.value |
| 87 | |
| 88 | # MoE pointers |
| 89 | w_gate_inp_arr=[0]*L; w_gate_exps_arr=[0]*L; w_up_exps_arr=[0]*L; w_down_exps_arr=[0]*L |
| 90 | for i,lw in enumerate(e._layers): |
| 91 | if e.is_moe: |
| 92 | me = e._moe_layers[i] |
| 93 | if me.router_raw is not None: |
| 94 | w_gate_inp_arr[i] = me.router_raw.ctypes.data_as(cv) |
| 95 | elif me.router_f32 is not None: |
| 96 | w_gate_inp_arr[i] = me.router_f32.ctypes.data_as(cv) |
| 97 | else: |
| 98 | w_gate_inp_arr[i] = cv(0) |
| 99 | # Expert weight pointers — pass raw blob pointer, C code offsets by stride |
| 100 | # Use the underlying contiguous raw weight data address |
| 101 | gate_raw_t = me.gate_raw # list of numpy expert views (contiguous in memory) |
| 102 | up_raw_t = me.up_raw |
| 103 | down_raw_t = me.down_raw |
| 104 | if gate_raw_t and len(gate_raw_t) > 0: |
| 105 | # All experts are contiguous; first expert's pointer = base for all |
| 106 | w_gate_exps_arr[i] = gate_raw_t[0].ctypes.data_as(cv) |
| 107 | else: |
| 108 | w_gate_exps_arr[i] = cv(0) |
| 109 | if up_raw_t and len(up_raw_t) > 0: |
| 110 | w_up_exps_arr[i] = up_raw_t[0].ctypes.data_as(cv) |
| 111 | else: |
| 112 | w_up_exps_arr[i] = cv(0) |
| 113 | if down_raw_t and len(down_raw_t) > 0: |
| 114 | w_down_exps_arr[i] = down_raw_t[0].ctypes.data_as(cv) |
| 115 | else: |
| 116 | w_down_exps_arr[i] = cv(0) |
| 117 | |
| 118 | # Read actual expert quant types from engine (like test_fixed.py) |
| 119 | if e.is_moe and len(e._moe_layers) > 0: |
| 120 | me = e._moe_layers[0] |
| 121 | gate_qt = me.gate_qt.value; up_qt = me.up_qt.value; down_qt = me.down_qt.value |
| 122 | else: |
| 123 | gate_qt = 2; up_qt = 2; down_qt = 2 |
| 124 | print(f"Expert quant types: gate={gate_qt} up={up_qt} down={down_qt}", flush=True) |
| 125 | |
| 126 | bc=BC() |
| 127 | for attr,val in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps), |
| 128 | ('nc',N),('outNR',V),('outNC',N),('outQuant',8), |
| 129 | ('n_experts',NE),('n_experts_per_tok',NK),('moe_intermediate',moe_int), |
| 130 | ('gate_exp_quant',gate_qt),('up_exp_quant',up_qt),('down_exp_quant',down_qt), |
| 131 | ('emb_quant',0)]: |
| 132 | setattr(bc,attr,val) |
| 133 | bc.wQ=ctypes.cast(wa(wQ_arr),cv); bc.wK=ctypes.cast(wa(wK_arr),cv); bc.wV=ctypes.cast(wa(wV_arr),cv); bc.wO=ctypes.cast(wa(wO_arr),cv) |
| 134 | bc.wG=ctypes.cast(wa(wG_arr),cv); bc.wU=ctypes.cast(wa(wU_arr),cv); bc.wD=ctypes.cast(wa(wD_arr),cv) |
| 135 | bc.wAN=ctypes.cast(wa(wAN_arr),cv); bc.wFN=ctypes.cast(wa(wFN_arr),cv) |
| 136 | bc.wQK=ctypes.cast(wa(wQK_arr),cv); bc.qk_quant=ctypes.cast(ia(qkQ_arr),cv) |
| 137 | bc.nQ=ctypes.cast(ia(nQ_arr),cv); bc.nK=ctypes.cast(ia(nK_arr),cv); bc.nV=ctypes.cast(ia(nV_arr),cv); bc.nO=ctypes.cast(ia(nO_arr),cv) |
| 138 | bc.nG=ctypes.cast(ia(nG_arr),cv); bc.nU=ctypes.cast(ia(nU_arr),cv); bc.nD=ctypes.cast(ia(nD_arr),cv) |
| 139 | bc.q_quant=ctypes.cast(ia(qQ_arr),cv); bc.k_quant=ctypes.cast(ia(qK_arr),cv); bc.v_quant=ctypes.cast(ia(qV_arr),cv); bc.o_quant=ctypes.cast(ia(qO_arr),cv) |
| 140 | bc.g_quant=ctypes.cast(ia(qG_arr),cv); bc.u_quant=ctypes.cast(ia(qU_arr),cv); bc.d_quant=ctypes.cast(ia(qD_arr),cv) |
| 141 | bc.w_gate_inp=ctypes.cast(wa(w_gate_inp_arr),cv); bc.w_gate_exps=ctypes.cast(wa(w_gate_exps_arr),cv) |
| 142 | bc.w_up_exps=ctypes.cast(wa(w_up_exps_arr),cv); bc.w_down_exps=ctypes.cast(wa(w_down_exps_arr),cv) |
| 143 | bc.emb=e.emb.ctypes.data_as(cv) if hasattr(e,'emb') else cv(0) |
| 144 | bc.onw=e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0) |
| 145 | # FIX: use _out_raw instead of _or (like test_fixed.py) |
| 146 | bc.wOut=ctypes.cast(e._out_raw,cv) if hasattr(e,'_out_raw') else cv(0) |
| 147 | |
| 148 | # RoPE precompute — Python approach from test_fixed.py |
| 149 | max_ctx=4096; hd2=HD//2 |
| 150 | freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD) |
| 151 | ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1) |
| 152 | cos_all = np.cos(ang).astype(np.float32).reshape(-1) |
| 153 | sin_all = np.sin(ang).astype(np.float32).reshape(-1) |
| 154 | cos_t = cos_all.ctypes.data_as(cv) |
| 155 | sin_t = sin_all.ctypes.data_as(cv) |
| 156 | bc.cos_table=cos_t; bc.sin_table=sin_t; bc.max_ctx=max_ctx |
| 157 | print(f"RoPE table: {max_ctx}x{hd2} = {len(cos_all)*4*2//1024}KB", flush=True) |
| 158 | |
| 159 | # BC workspace: replaces __builtin_alloca for kct/vct in batch_forward |
| 160 | # Size = 2 * max_ctx * NKH * HD (kct + vct) + safety margin |
| 161 | ws_bc_size = 2 * max_ctx * NKH * HD + 4096 |
| 162 | ws_bc = np.zeros(ws_bc_size, dtype=np.float32) |
| 163 | bc.workspace = ws_bc.ctypes.data_as(cv) |
| 164 | bc.ws_size = ws_bc_size |
| 165 | print(f"BC workspace: {ws_bc_size} floats = {ws_bc_size*4//1024}KB", flush=True) |
| 166 | |
| 167 | MAX_SEQ=32; ws=np.zeros(MAX_SEQ*12*S,dtype=np.float32); logits_buf=np.zeros(MAX_SEQ*V,dtype=np.float32) |
| 168 | |
| 169 | def sample_token(logits,temperature=0.0): |
| 170 | safe=np.nan_to_num(logits,nan=-1e10,posinf=1e10,neginf=-1e10) |
| 171 | if temperature<=0: return int(np.argmax(safe)) |
| 172 | safe-=safe.max(); p=np.exp(np.clip(safe/temperature,-50,50)); p[np.isnan(p)]=0 |
| 173 | s=p.sum() |
| 174 | return int(np.random.choice(len(p),p=p/s)) if s>0 else 0 |
| 175 | |
| 176 | from transformers import AutoTokenizer |
| 177 | tokenizer = AutoTokenizer.from_pretrained('/tmp/qwen3-tokenizer/') |
| 178 | |
| 179 | class Seq: |
| 180 | __slots__ = ('kv','tokens','gen_tokens','done','result','event','max_tokens','temperature','token_queue') |
| 181 | def __init__(s): s.kv=KVBlock(); lib.kv_init(ctypes.byref(s.kv),ci(L),ci(NKH),ci(HD)); s.tokens=[]; s.gen_tokens=[]; s.done=False; s.result=None; s.event=threading.Event(); s.max_tokens=100; s.temperature=0.0; s.token_queue=None |
| 182 | |
| 183 | pending=queue.Queue(); active=[None]*MAX_SEQ |
| 184 | forward_lock = threading.Lock() |
| 185 | |
| 186 | def scheduler(): |
| 187 | while True: |
| 188 | while not pending.empty(): |
| 189 | try: s=pending.get_nowait() |
| 190 | except: break |
| 191 | for i in range(MAX_SEQ): |
| 192 | if active[i] is None: active[i]=s; break |
| 193 | batch=[(i,s) for i,s in enumerate(active) if s and not s.done] |
| 194 | if not batch: time.sleep(0.002); continue |
| 195 | B=len(batch); tok_arr=(ci*B)(); kv_arr=(cv*B)() |
| 196 | for j,(i,s) in enumerate(batch): tok_arr[j]=s.tokens[-1] if s.tokens else 1; kv_arr[j]=ctypes.cast(ctypes.pointer(s.kv),cv) |
| 197 | with forward_lock: |
| 198 | bc.kv_array=ctypes.cast(kv_arr,cv); bc.logits=logits_buf.ctypes.data_as(cv) |
| 199 | lib.batch_forward(ctypes.byref(bc),tok_arr,ci(B),ws.ctypes.data_as(cv)) |
| 200 | for j,(i,s) in enumerate(batch): |
| 201 | tok=sample_token(logits_buf[j*V:(j+1)*V].copy(),s.temperature) |
| 202 | s.tokens.append(tok); s.gen_tokens.append(tok) |
| 203 | if s.token_queue: s.token_queue.put(tok) |
| 204 | if tok==2 or len(s.gen_tokens)>=s.max_tokens: |
| 205 | s.done=True; s.result={'tokens':s.gen_tokens.copy(),'finish_reason':'stop'if tok==2 else'length'} |
| 206 | if s.token_queue: s.token_queue.put(None) |
| 207 | s.event.set(); active[i]=None |
| 208 | threading.Thread(target=scheduler,daemon=True).start() |
| 209 | |
| 210 | class ThreadedHTTPServer(ThreadingMixIn,HTTPServer): |
| 211 | allow_reuse_address=True; daemon_threads=True |
| 212 | |
| 213 | class Handler(BaseHTTPRequestHandler): |
| 214 | def do_POST(self): |
| 215 | if urlparse(self.path).path!='/v1/completions': self.send_error(404); return |
| 216 | n=int(self.headers.get('Content-Length',0)) |
| 217 | body=json.loads(self.rfile.read(n)) if n else {} |
| 218 | prompt=body.get('prompt',''); max_tokens=body.get('max_tokens',100) |
| 219 | temperature=body.get('temperature',0.0); stream=body.get('stream',False) |
| 220 | t0=time.perf_counter() |
| 221 | try: |
| 222 | ids=tokenizer.encode(prompt) if isinstance(prompt,str) else prompt[:512] |
| 223 | print(f" Encode: {len(ids)} ids", flush=True) |
| 224 | # Filter out-of-range tokens |
| 225 | ids=[t for t in ids if 0 <= t < V][:512] |
| 226 | if not ids: ids=[1] |
| 227 | s=Seq(); s.max_tokens=max_tokens; s.temperature=temperature |
| 228 | print(f" Prefill {len(ids)} tokens...", flush=True) |
| 229 | if ids: |
| 230 | kva1=(cv*1)(ctypes.cast(ctypes.pointer(s.kv),cv)) |
| 231 | with forward_lock: |
| 232 | bc.kv_array=ctypes.cast(kva1,cv); bc.logits=logits_buf[0:V].ctypes.data_as(cv) |
| 233 | logits_buf[:V]=0 |
| 234 | for pt in ids: |
| 235 | lib.batch_forward(ctypes.byref(bc),(ci*1)(pt),ci(1),ws.ctypes.data_as(cv)) |
| 236 | print(f" First sample...", flush=True) |
| 237 | ft=sample_token(logits_buf[:V].copy(),temperature) |
| 238 | print(f" First token: {ft}", flush=True) |
| 239 | if stream: s.token_queue=queue.Queue(); s.token_queue.put(ft) |
| 240 | s.tokens.append(ft) |
| 241 | pending.put(s) |
| 242 | if stream: |
| 243 | self.send_response(200); self.send_header('Content-Type','text/event-stream') |
| 244 | self.send_header('Cache-Control','no-cache'); self.end_headers() |
| 245 | while True: |
| 246 | t=s.token_queue.get() |
| 247 | if t is None: break |
| 248 | self.wfile.write(f'data: {json.dumps({"choices":[{"text":tokenizer.decode([t],skip_special_tokens=True),"index":0}]})}\n\n'.encode()); self.wfile.flush() |
| 249 | self.wfile.write(b'data: [DONE]\n\n') |
| 250 | else: |
| 251 | s.event.wait(timeout=600) |
| 252 | gt=s.gen_tokens if s.result is None else s.result['tokens'] |
| 253 | text=tokenizer.decode(gt,skip_special_tokens=True) |
| 254 | self.send_response(200); self.send_header('Content-Type','application/json'); self.end_headers() |
| 255 | self.wfile.write(json.dumps({'id':f'cmpl-{int(time.time())}','object':'text_completion','model':'mojollama','choices':[{'text':text,'index':0,'finish_reason':'length'if len(gt)>=max_tokens else'stop'}],'usage':{'prompt_tokens':len(ids),'completion_tokens':len(gt),'total_tokens':len(ids)+len(gt)}}).encode()) |
| 256 | print(f" [{len(ids)}p+{len(s.gen_tokens)}g {time.perf_counter()-t0:.1f}s] '{tokenizer.decode(s.gen_tokens,skip_special_tokens=True)[:60]}'",flush=True) |
| 257 | except Exception as ex: |
| 258 | self.send_response(500); self.send_header('Content-Type','application/json'); self.end_headers() |
| 259 | self.wfile.write(json.dumps({'error':str(ex)}).encode()) |
| 260 | import traceback; traceback.print_exc() |
| 261 | def log_message(self,*a): pass |
| 262 | |
| 263 | if __name__=='__main__': |
| 264 | print(f"Serving on 0.0.0.0:{PORT} | MoE K-quant engine", flush=True) |
| 265 | HTTPServer(('0.0.0.0',PORT),Handler).serve_forever() |