Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/benchmarks/bench_concurrent_qwen36.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / benchmarks / bench_concurrent_qwen36.py` 248 lines · 14728 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Qwen3.6 MXFP4 multi-user concurrency benchmark (C engine batch_forward).""" 3 import sys, os, time, ctypes, numpy as np 4 5 sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels')) 6 MODEL = "/tmp/models/qwen3.6-mxfp4.gguf" 7 N_USERS = 10 8 PROMPT_LEN = 128 # shorter prefill for faster benchmark 9 GEN_TOKENS = 20 10 11 # ── Load engine ── 12 print(f"Loading Qwen3.6 MXFP4 ({N_USERS} users, {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen)...", flush=True) 13 from turbo_engine_v7_moe import TurboEngineV7MoE 14 e = TurboEngineV7MoE(MODEL, 32) 15 N=e.n_embd; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim 16 FF=e.n_ff; L=e.n_layers; V=e.vocab_size 17 EXP=e.n_experts; ET=e.n_experts_per_tok; EFF=e.n_ff_expert 18 print(f" {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd MoE {EXP}x{ET} ef={EFF}", flush=True) 19 20 libfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels', 'cengine_batch_instr.so') 21 ce = ctypes.CDLL(libfile) 22 cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float 23 def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr]) 24 def ia(arr): return (ci*L)(*[int(a) for a in arr]) 25 26 # ── Build BC struct ── 27 LT = e.layer_types if hasattr(e, 'layer_types') else [0]*L 28 29 wQKV = [cv(0)]*L; qkv_qt = [0]*L 30 wQ_sep = [cv(0)]*L; nQ_sep = [0]*L; qQ_sep = [0]*L 31 wK_sep = [cv(0)]*L; nK_sep = [0]*L; qK_sep = [0]*L 32 wV_sep = [cv(0)]*L; nV_sep = [0]*L; qV_sep = [0]*L 33 wAG = [cv(0)]*L; ag_qt = [0]*L 34 wO_attn = [cv(0)]*L; nO_attn = [0]*L; qO_attn = [0]*L 35 wSO = [cv(0)]*L; so_qt = [0]*L 36 ssm_c1d = [cv(0)]*L; ssm_a = [cv(0)]*L; ssm_db = [cv(0)]*L 37 ssm_al = [cv(0)]*L; ssm_be = [cv(0)]*L; ssm_nm = [cv(0)]*L 38 wSHG = [cv(0)]*L; wSHU = [cv(0)]*L; wSHD = [cv(0)]*L; wSHR = [cv(0)]*L 39 shg_qt = [0]*L; shu_qt = [0]*L; shd_qt = [0]*L 40 wAN = [0]*L; wFN = [0]*L 41 wGI = [cv(0)]*L; wGE = [cv(0)]*L; wUE = [cv(0)]*L; wDE = [cv(0)]*L 42 ns_G = [0]*L; ns_U = [0]*L; ns_D = [0]*L 43 qt_G = [0]*L; qt_U = [0]*L; qt_D = [0]*L 44 45 print("Building weight arrays...", flush=True) 46 for i in range(L): 47 lw = e._layers[i]; me = e._moe_layers[i] 48 if hasattr(lw,'attn_qkv_raw') and lw.attn_qkv_raw is not None: 49 wQKV[i]=lw.attn_qkv_raw; qkv_qt[i]=lw.attn_qkv_qt.value 50 if hasattr(lw,'attn_q_raw') and lw.attn_q_raw is not None: 51 wQ_sep[i]=lw.attn_q_raw; nQ_sep[i]=lw.attn_q_nr.value; qQ_sep[i]=lw.attn_q_qt.value 52 if hasattr(lw,'attn_k_raw') and lw.attn_k_raw is not None: 53 wK_sep[i]=lw.attn_k_raw; nK_sep[i]=lw.attn_k_nr.value; qK_sep[i]=lw.attn_k_qt.value 54 if hasattr(lw,'attn_v_raw') and lw.attn_v_raw is not None: 55 wV_sep[i]=lw.attn_v_raw; nV_sep[i]=lw.attn_v_nr.value; qV_sep[i]=lw.attn_v_qt.value 56 if hasattr(lw,'attn_gate_raw') and lw.attn_gate_raw is not None: 57 wAG[i]=lw.attn_gate_raw; ag_qt[i]=lw.attn_gate_qt.value 58 if hasattr(lw,'attn_out_raw') and lw.attn_out_raw is not None: 59 wO_attn[i]=lw.attn_out_raw; nO_attn[i]=lw.attn_out_nr.value; qO_attn[i]=lw.attn_out_qt.value 60 if hasattr(lw,'ssm_conv1d_ptr') and lw.ssm_conv1d_ptr is not None: 61 ssm_c1d[i]=lw.ssm_conv1d_ptr; ssm_a[i]=lw.ssm_a_ptr; ssm_db[i]=lw.ssm_dt_bias_ptr 62 ssm_al[i]=lw.ssm_alpha_ptr; ssm_be[i]=lw.ssm_beta_ptr; ssm_nm[i]=lw.ssm_norm_ptr 63 if hasattr(lw,'ssm_out_raw') and lw.ssm_out_raw is not None: 64 wSO[i]=lw.ssm_out_raw; so_qt[i]=lw.ssm_out_qt.value 65 if hasattr(lw,'shexp_gate_raw') and lw.shexp_gate_raw is not None: 66 wSHG[i]=lw.shexp_gate_raw; shg_qt[i]=lw.shexp_gate_qt.value 67 if hasattr(lw,'shexp_up_raw') and lw.shexp_up_raw is not None: 68 wSHU[i]=lw.shexp_up_raw; shu_qt[i]=lw.shexp_up_qt.value 69 if hasattr(lw,'shexp_down_raw') and lw.shexp_down_raw is not None: 70 wSHD[i]=lw.shexp_down_raw; shd_qt[i]=lw.shexp_down_qt.value 71 if hasattr(lw,'shexp_router_ptr') and lw.shexp_router_ptr is not None: 72 wSHR[i]=lw.shexp_router_ptr 73 if hasattr(me,'router_f32') and me.router_f32 is not None: 74 wGI[i]=me.router_f32.ctypes.data_as(cv) 75 if me.gate_raw and len(me.gate_raw)>0: 76 wGE[i]=me.gate_raw[0].ctypes.data_as(cv); ns_G[i]=me.gate_nr.value; qt_G[i]=me.gate_qt.value 77 if me.up_raw and len(me.up_raw)>0: 78 wUE[i]=me.up_raw[0].ctypes.data_as(cv); ns_U[i]=me.up_nr.value; qt_U[i]=me.up_qt.value 79 if me.down_raw and len(me.down_raw)>0: 80 wDE[i]=me.down_raw[0].ctypes.data_as(cv); ns_D[i]=me.down_nr.value; qt_D[i]=me.down_qt.value 81 if hasattr(lw,'attn_norm_w') and lw.attn_norm_w is not None: wAN[i]=lw.attn_norm_w.ctypes.data_as(cv) 82 if hasattr(lw,'ffn_norm_w') and lw.ffn_norm_w is not None: wFN[i]=lw.ffn_norm_w.ctypes.data_as(cv) 83 84 me0 = e._moe_layers[0] 85 gate_qt_all = me0.gate_qt.value; up_qt_all = me0.up_qt.value; down_qt_all = me0.down_qt.value 86 87 class PageTable(ctypes.Structure): 88 _fields_=[('page_size',ci),('n_pages',ci),('pages',cv),('table',cv),('free_pages',cv),('free_count',ci),('_nkh',ci),('_hd',ci),('_n_layers',ci)] 89 class KVBlock(ctypes.Structure): 90 _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64),('block_map',(ci*1024)*64),('pt',PageTable)] 91 class BC(ctypes.Structure): 92 _fields_=[ 93 ('L',ci),('N',ci),('NH',ci),('NKH',ci),('HD',ci),('FF',ci),('V',ci),('eps',cf), 94 ('wQ',cv),('wK',cv),('wV',cv),('wO',cv),('wG',cv),('wU',cv),('wD',cv), 95 ('wAN',cv),('wFN',cv),('nQ',cv),('nK',cv),('nV',cv),('nO',cv),('nG',cv),('nU',cv),('nD',cv), 96 ('nc',ci),('emb',cv),('onw',cv),('wOut',cv),('outNR',ci),('outNC',ci),('outQuant',ci), 97 ('kv_array',cv),('logits',cv), 98 ('n_experts',ci),('n_experts_per_tok',ci),('moe_intermediate',ci), 99 ('w_gate_inp',cv),('w_gate_exps',cv),('w_up_exps',cv),('w_down_exps',cv), 100 ('gate_exp_quant',ci),('up_exp_quant',ci),('down_exp_quant',ci), 101 ('q_quant',cv),('k_quant',cv),('v_quant',cv),('o_quant',cv), 102 ('g_quant',cv),('u_quant',cv),('d_quant',cv),('emb_quant',ci), 103 ('wQK',cv),('qk_quant',cv),('cos_table',cv),('sin_table',cv),('max_ctx',ci), 104 ('workspace',cv),('ws_size',ci), 105 ('rope_dim',ci),('full_attn_interval',ci), 106 ('wQKV',cv),('qkv_quant',cv),('wAttnG',cv),('attnG_quant',cv), 107 ('ssm_conv1d',cv),('ssm_a',cv),('ssm_dt_bias',cv),('ssm_alpha',cv), 108 ('ssm_beta',cv),('ssm_norm',cv),('wSsmOut',cv),('ssm_out_quant',cv),('ssm_state',cv), 109 ('wSHexpG',cv),('wSHexpU',cv),('wSHexpD',cv), 110 ('shexp_g_quant',cv),('shexp_u_quant',cv),('shexp_d_quant',cv),('wShexpRouter',cv), 111 ('layer_types',cv),('n_layers_actual',ci) 112 ] 113 114 MAX_CTX=4096 115 bc=BC() 116 for a,v in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps), 117 ('nc',N),('outNR',V),('outNC',N),('outQuant',8), 118 ('n_experts',EXP),('n_experts_per_tok',ET),('moe_intermediate',EFF), 119 ('gate_exp_quant',gate_qt_all),('up_exp_quant',up_qt_all),('down_exp_quant',down_qt_all), 120 ('emb_quant',0),('max_ctx',MAX_CTX), 121 ('rope_dim',HD),('full_attn_interval',4),('n_layers_actual',L)]: 122 setattr(bc,a,v) 123 124 bc.wQKV = ctypes.cast(wa(wQKV),cv); bc.qkv_quant = ctypes.cast(ia(qkv_qt),cv) 125 bc.wQ = ctypes.cast(wa(wQ_sep),cv); bc.wK = ctypes.cast(wa(wK_sep),cv); bc.wV = ctypes.cast(wa(wV_sep),cv) 126 bc.nQ = ctypes.cast(ia(nQ_sep),cv); bc.nK = ctypes.cast(ia(nK_sep),cv); bc.nV = ctypes.cast(ia(nV_sep),cv) 127 bc.q_quant = ctypes.cast(ia(qQ_sep),cv); bc.k_quant = ctypes.cast(ia(qK_sep),cv); bc.v_quant = ctypes.cast(ia(qV_sep),cv) 128 bc.wAttnG = ctypes.cast(wa(wAG),cv); bc.attnG_quant = ctypes.cast(ia(ag_qt),cv) 129 bc.wO = ctypes.cast(wa(wO_attn),cv); bc.nO = ctypes.cast(ia(nO_attn),cv); bc.o_quant = ctypes.cast(ia(qO_attn),cv) 130 bc.wSsmOut = ctypes.cast(wa(wSO),cv); bc.ssm_out_quant = ctypes.cast(ia(so_qt),cv) 131 bc.ssm_conv1d = ctypes.cast(wa(ssm_c1d),cv); bc.ssm_a = ctypes.cast(wa(ssm_a),cv) 132 bc.ssm_dt_bias = ctypes.cast(wa(ssm_db),cv); bc.ssm_alpha = ctypes.cast(wa(ssm_al),cv) 133 bc.ssm_beta = ctypes.cast(wa(ssm_be),cv); bc.ssm_norm = ctypes.cast(wa(ssm_nm),cv) 134 bc.wSHexpG = ctypes.cast(wa(wSHG),cv); bc.wSHexpU = ctypes.cast(wa(wSHU),cv) 135 bc.wSHexpD = ctypes.cast(wa(wSHD),cv); bc.wShexpRouter = ctypes.cast(wa(wSHR),cv) 136 bc.shexp_g_quant = ctypes.cast(ia(shg_qt),cv); bc.shexp_u_quant = ctypes.cast(ia(shu_qt),cv) 137 bc.shexp_d_quant = ctypes.cast(ia(shd_qt),cv) 138 bc.wAN = ctypes.cast(wa(wAN),cv); bc.wFN = ctypes.cast(wa(wFN),cv) 139 bc.w_gate_inp = ctypes.cast(wa(wGI),cv) 140 bc.w_gate_exps = ctypes.cast(wa(wGE),cv); bc.w_up_exps = ctypes.cast(wa(wUE),cv); bc.w_down_exps = ctypes.cast(wa(wDE),cv) 141 bc.nG = ctypes.cast(ia(ns_G),cv); bc.nU = ctypes.cast(ia(ns_U),cv); bc.nD = ctypes.cast(ia(ns_D),cv) 142 bc.g_quant = ctypes.cast(ia(qt_G),cv); bc.u_quant = ctypes.cast(ia(qt_U),cv); bc.d_quant = ctypes.cast(ia(qt_D),cv) 143 for pf in ['wG','wU','wD','nG','nU','nD','g_quant','u_quant','d_quant','wQK','qk_quant']: 144 setattr(bc,pf,cv(0)) 145 bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e,'emb') and e.emb is not None else cv(0) 146 bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0) 147 bc.wOut = ctypes.cast(e._out_raw, cv) 148 ssm_state = np.zeros(L * e.ssm_groups * e.ssm_state_size, dtype=np.float32) 149 bc.ssm_state = ssm_state.ctypes.data_as(cv) 150 151 lt_arr = (ci * L)(*LT); bc.layer_types = ctypes.cast(lt_arr, cv) 152 cos_t = np.zeros(MAX_CTX*HD//2,np.float32); sin_t = np.zeros(MAX_CTX*HD//2,np.float32) 153 for p in range(MAX_CTX): 154 for j in range(HD//2): 155 ang = p/(10000.0**(2.0*j/HD)) 156 cos_t[p*HD//2+j]=np.cos(ang); sin_t[p*HD//2+j]=np.sin(ang) 157 bc.cos_table=cos_t.ctypes.data_as(cv); bc.sin_table=sin_t.ctypes.data_as(cv) 158 159 S_act = max(N, NH*HD, FF, NKH, NH*HD+NKH, 8192) 160 KVscr = 2 * MAX_CTX * NKH * HD 161 ws = np.zeros(12 * N_USERS * S_act + KVscr + 100000, dtype=np.float32) 162 bc.workspace = ws.ctypes.data_as(cv); bc.ws_size = len(ws) 163 print(f" Workspace: {len(ws):,} floats ({len(ws)*4/1024/1024:.0f} MB)", flush=True) 164 165 ce.kv_init.argtypes=[cv,ci,ci,ci]; ce.kv_init.restype=None 166 ce.batch_forward.argtypes=[cv,cv,ci,cv]; ce.batch_forward.restype=None 167 ce.rope_init.argtypes=[cv,cv,ci,ci,ci]; ce.rope_init.restype=None 168 ce.rope_init(bc.cos_table, bc.sin_table, ci(MAX_CTX), ci(HD), ci(HD)) 169 170 ws_ptr = ws.ctypes.data_as(cv) 171 def bf(tokens, B): 172 ce.batch_forward(ctypes.byref(bc), (ci*B)(*tokens), ci(B), ws_ptr) 173 174 # ═══════════════════════════════════════ 175 # BENCHMARK: B=1 baseline 176 # ═══════════════════════════════════════ 177 print(f"\nStep 1: B=1 baseline...", flush=True) 178 kv_single = KVBlock(); ce.kv_init(ctypes.byref(kv_single), ci(L), ci(NKH), ci(HD)) 179 bc.kv_array = ctypes.cast((cv*1)(ctypes.cast(ctypes.pointer(kv_single), cv)), cv) 180 lbuf = np.zeros(V, dtype=np.float32) 181 bc.logits = lbuf.ctypes.data_as(cv) 182 183 for _ in range(3): bf([1], 1); kv_single.seq_len[0] = 0 184 t1 = [] 185 for _ in range(30): 186 t0 = time.perf_counter(); bf([1], 1); t1.append(time.perf_counter()-t0) 187 kv_single.seq_len[0] = 0 188 t1 = t1[5:] 189 avg1 = np.mean(t1) 190 print(f" B=1: {avg1*1000:.1f}ms → {1/avg1:.1f} tok/s, max={lbuf.max():.1f}", flush=True) 191 192 # ═══════════════════════════════════════ 193 # BENCHMARK: B=10 single step 194 # ═══════════════════════════════════════ 195 print(f"\nStep 2: B={N_USERS} single step...", flush=True) 196 kvs = [KVBlock() for _ in range(N_USERS)] 197 for kv in kvs: ce.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) 198 bc.kv_array = ctypes.cast((cv*N_USERS)(*[ctypes.cast(ctypes.pointer(k), cv) for k in kvs]), cv) 199 lbuf10 = np.zeros(N_USERS * V, dtype=np.float32) 200 bc.logits = lbuf10.ctypes.data_as(cv) 201 202 t10 = [] 203 for _ in range(10): 204 t0 = time.perf_counter(); bf([1]*N_USERS, N_USERS) 205 t10.append(time.perf_counter()-t0) 206 for kv in kvs: kv.seq_len[0] = 0 207 t10 = t10[3:] 208 avg10 = np.mean(t10) 209 ok = all(np.isnan(lbuf10[u*V:(u+1)*V]).sum() == 0 for u in range(N_USERS)) 210 print(f" B={N_USERS}: {avg10*1000:.1f}ms → {N_USERS/avg10:.1f} tok/s aggregate", flush=True) 211 print(f" Per-user: {N_USERS/avg10/N_USERS:.1f} tok/s/user (no, aggregate/{N_USERS})", flush=True) 212 print(f" Correct: {'✅' if ok else '❌'} NaN={int(np.isnan(lbuf10).sum())}", flush=True) 213 214 # ═══════════════════════════════════════ 215 # BENCHMARK: B=10 prefill + gen 216 # ═══════════════════════════════════════ 217 print(f"\nStep 3: {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen, B={N_USERS}...", flush=True) 218 for kv in kvs: kv.seq_len[0] = 0; ce.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) 219 220 print(f" Prefill {PROMPT_LEN} steps...", flush=True) 221 pt0 = time.perf_counter() 222 for pos in range(PROMPT_LEN): 223 bf([100+(pos%50000)]*N_USERS, N_USERS) 224 if pos % 32 == 31: print(f" pos {pos+1}/{PROMPT_LEN} ({time.perf_counter()-pt0:.1f}s)", flush=True) 225 prefill_s = time.perf_counter() - pt0 226 print(f" Prefill: {prefill_s:.1f}s", flush=True) 227 228 print(f" Generate {GEN_TOKENS} tokens...", flush=True) 229 gt0 = time.perf_counter() 230 for step in range(GEN_TOKENS): 231 if step == 0: bf([1]*N_USERS, N_USERS) 232 else: bf([int(np.argmax(lbuf10[u*V:(u+1)*V])) for u in range(N_USERS)], N_USERS) 233 gen_s = time.perf_counter() - gt0 234 tps = N_USERS * GEN_TOKENS / gen_s 235 236 print(f"\n ╔══════════════════════════════════════════════╗") 237 print(f" ║ Qwen3.6 MXFP4 batch B={N_USERS} Results ║") 238 print(f" ╠══════════════════════════════════════════════╣") 239 print(f" ║ C engine B=1: {1000*avg1:6.0f}ms ({1/avg1:5.1f} tok/s) ║") 240 print(f" ║ C engine B={N_USERS}: {1000*avg10:6.0f}ms ({N_USERS/avg10:5.1f} tok/s aggr) ║") 241 print(f" ║ Prefill ({PROMPT_LEN} steps): {prefill_s:6.1f}s ║") 242 print(f" ║ Generate ({GEN_TOKENS} steps): {gen_s*1000:6.0f}ms ║") 243 print(f" ║ Throughput: {tps:6.0f} tok/s ({tps/N_USERS:.0f}/user) ║") 244 print(f" ╟──────────────────────────────────────────────╢") 245 print(f" ║ VS Python single: 39.2ms → 25.5 tok/s ║") 246 print(f" ║ VS llama.cpp: ~16 tok/s single ║") 247 print(f" ║ Efficiency (B=10/B=1): {N_USERS/avg10/(1/avg1):.2f}x ║") 248 print(f" ╚══════════════════════════════════════════════╝")