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 / 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)."""
3import sys, os, time, ctypes, numpy as np
4
5sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels'))
6MODEL = "/tmp/models/qwen3.6-mxfp4.gguf"
7N_USERS = 10
8PROMPT_LEN = 128 # shorter prefill for faster benchmark
9GEN_TOKENS = 20
10
11# ── Load engine ──
12print(f"Loading Qwen3.6 MXFP4 ({N_USERS} users, {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen)...", flush=True)
13from turbo_engine_v7_moe import TurboEngineV7MoE
14e = TurboEngineV7MoE(MODEL, 32)
15N=e.n_embd; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim
16FF=e.n_ff; L=e.n_layers; V=e.vocab_size
17EXP=e.n_experts; ET=e.n_experts_per_tok; EFF=e.n_ff_expert
18print(f" {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd MoE {EXP}x{ET} ef={EFF}", flush=True)
19
20libfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels', 'cengine_batch_instr.so')
21ce = ctypes.CDLL(libfile)
22cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float
23def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr])
24def ia(arr): return (ci*L)(*[int(a) for a in arr])
25
26# ── Build BC struct ──
27LT = e.layer_types if hasattr(e, 'layer_types') else [0]*L
28
29wQKV = [cv(0)]*L; qkv_qt = [0]*L
30wQ_sep = [cv(0)]*L; nQ_sep = [0]*L; qQ_sep = [0]*L
31wK_sep = [cv(0)]*L; nK_sep = [0]*L; qK_sep = [0]*L
32wV_sep = [cv(0)]*L; nV_sep = [0]*L; qV_sep = [0]*L
33wAG = [cv(0)]*L; ag_qt = [0]*L
34wO_attn = [cv(0)]*L; nO_attn = [0]*L; qO_attn = [0]*L
35wSO = [cv(0)]*L; so_qt = [0]*L
36ssm_c1d = [cv(0)]*L; ssm_a = [cv(0)]*L; ssm_db = [cv(0)]*L
37ssm_al = [cv(0)]*L; ssm_be = [cv(0)]*L; ssm_nm = [cv(0)]*L
38wSHG = [cv(0)]*L; wSHU = [cv(0)]*L; wSHD = [cv(0)]*L; wSHR = [cv(0)]*L
39shg_qt = [0]*L; shu_qt = [0]*L; shd_qt = [0]*L
40wAN = [0]*L; wFN = [0]*L
41wGI = [cv(0)]*L; wGE = [cv(0)]*L; wUE = [cv(0)]*L; wDE = [cv(0)]*L
42ns_G = [0]*L; ns_U = [0]*L; ns_D = [0]*L
43qt_G = [0]*L; qt_U = [0]*L; qt_D = [0]*L
44
45print("Building weight arrays...", flush=True)
46for 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
84me0 = e._moe_layers[0]
85gate_qt_all = me0.gate_qt.value; up_qt_all = me0.up_qt.value; down_qt_all = me0.down_qt.value
86
87class 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)]
89class KVBlock(ctypes.Structure):
90 _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64),('block_map',(ci*1024)*64),('pt',PageTable)]
91class 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
114MAX_CTX=4096
115bc=BC()
116for 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
124bc.wQKV = ctypes.cast(wa(wQKV),cv); bc.qkv_quant = ctypes.cast(ia(qkv_qt),cv)
125bc.wQ = ctypes.cast(wa(wQ_sep),cv); bc.wK = ctypes.cast(wa(wK_sep),cv); bc.wV = ctypes.cast(wa(wV_sep),cv)
126bc.nQ = ctypes.cast(ia(nQ_sep),cv); bc.nK = ctypes.cast(ia(nK_sep),cv); bc.nV = ctypes.cast(ia(nV_sep),cv)
127bc.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)
128bc.wAttnG = ctypes.cast(wa(wAG),cv); bc.attnG_quant = ctypes.cast(ia(ag_qt),cv)
129bc.wO = ctypes.cast(wa(wO_attn),cv); bc.nO = ctypes.cast(ia(nO_attn),cv); bc.o_quant = ctypes.cast(ia(qO_attn),cv)
130bc.wSsmOut = ctypes.cast(wa(wSO),cv); bc.ssm_out_quant = ctypes.cast(ia(so_qt),cv)
131bc.ssm_conv1d = ctypes.cast(wa(ssm_c1d),cv); bc.ssm_a = ctypes.cast(wa(ssm_a),cv)
132bc.ssm_dt_bias = ctypes.cast(wa(ssm_db),cv); bc.ssm_alpha = ctypes.cast(wa(ssm_al),cv)
133bc.ssm_beta = ctypes.cast(wa(ssm_be),cv); bc.ssm_norm = ctypes.cast(wa(ssm_nm),cv)
134bc.wSHexpG = ctypes.cast(wa(wSHG),cv); bc.wSHexpU = ctypes.cast(wa(wSHU),cv)
135bc.wSHexpD = ctypes.cast(wa(wSHD),cv); bc.wShexpRouter = ctypes.cast(wa(wSHR),cv)
136bc.shexp_g_quant = ctypes.cast(ia(shg_qt),cv); bc.shexp_u_quant = ctypes.cast(ia(shu_qt),cv)
137bc.shexp_d_quant = ctypes.cast(ia(shd_qt),cv)
138bc.wAN = ctypes.cast(wa(wAN),cv); bc.wFN = ctypes.cast(wa(wFN),cv)
139bc.w_gate_inp = ctypes.cast(wa(wGI),cv)
140bc.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)
141bc.nG = ctypes.cast(ia(ns_G),cv); bc.nU = ctypes.cast(ia(ns_U),cv); bc.nD = ctypes.cast(ia(ns_D),cv)
142bc.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)
143for pf in ['wG','wU','wD','nG','nU','nD','g_quant','u_quant','d_quant','wQK','qk_quant']:
144 setattr(bc,pf,cv(0))
145bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e,'emb') and e.emb is not None else cv(0)
146bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0)
147bc.wOut = ctypes.cast(e._out_raw, cv)
148ssm_state = np.zeros(L * e.ssm_groups * e.ssm_state_size, dtype=np.float32)
149bc.ssm_state = ssm_state.ctypes.data_as(cv)
150
151lt_arr = (ci * L)(*LT); bc.layer_types = ctypes.cast(lt_arr, cv)
152cos_t = np.zeros(MAX_CTX*HD//2,np.float32); sin_t = np.zeros(MAX_CTX*HD//2,np.float32)
153for 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)
157bc.cos_table=cos_t.ctypes.data_as(cv); bc.sin_table=sin_t.ctypes.data_as(cv)
158
159S_act = max(N, NH*HD, FF, NKH, NH*HD+NKH, 8192)
160KVscr = 2 * MAX_CTX * NKH * HD
161ws = np.zeros(12 * N_USERS * S_act + KVscr + 100000, dtype=np.float32)
162bc.workspace = ws.ctypes.data_as(cv); bc.ws_size = len(ws)
163print(f" Workspace: {len(ws):,} floats ({len(ws)*4/1024/1024:.0f} MB)", flush=True)
164
165ce.kv_init.argtypes=[cv,ci,ci,ci]; ce.kv_init.restype=None
166ce.batch_forward.argtypes=[cv,cv,ci,cv]; ce.batch_forward.restype=None
167ce.rope_init.argtypes=[cv,cv,ci,ci,ci]; ce.rope_init.restype=None
168ce.rope_init(bc.cos_table, bc.sin_table, ci(MAX_CTX), ci(HD), ci(HD))
169
170ws_ptr = ws.ctypes.data_as(cv)
171def 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# ═══════════════════════════════════════
177print(f"\nStep 1: B=1 baseline...", flush=True)
178kv_single = KVBlock(); ce.kv_init(ctypes.byref(kv_single), ci(L), ci(NKH), ci(HD))
179bc.kv_array = ctypes.cast((cv*1)(ctypes.cast(ctypes.pointer(kv_single), cv)), cv)
180lbuf = np.zeros(V, dtype=np.float32)
181bc.logits = lbuf.ctypes.data_as(cv)
182
183for _ in range(3): bf([1], 1); kv_single.seq_len[0] = 0
184t1 = []
185for _ in range(30):
186 t0 = time.perf_counter(); bf([1], 1); t1.append(time.perf_counter()-t0)
187 kv_single.seq_len[0] = 0
188t1 = t1[5:]
189avg1 = np.mean(t1)
190print(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# ═══════════════════════════════════════
195print(f"\nStep 2: B={N_USERS} single step...", flush=True)
196kvs = [KVBlock() for _ in range(N_USERS)]
197for kv in kvs: ce.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD))
198bc.kv_array = ctypes.cast((cv*N_USERS)(*[ctypes.cast(ctypes.pointer(k), cv) for k in kvs]), cv)
199lbuf10 = np.zeros(N_USERS * V, dtype=np.float32)
200bc.logits = lbuf10.ctypes.data_as(cv)
201
202t10 = []
203for _ 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
207t10 = t10[3:]
208avg10 = np.mean(t10)
209ok = all(np.isnan(lbuf10[u*V:(u+1)*V]).sum() == 0 for u in range(N_USERS))
210print(f" B={N_USERS}: {avg10*1000:.1f}ms → {N_USERS/avg10:.1f} tok/s aggregate", flush=True)
211print(f" Per-user: {N_USERS/avg10/N_USERS:.1f} tok/s/user (no, aggregate/{N_USERS})", flush=True)
212print(f" Correct: {'✅' if ok else '❌'} NaN={int(np.isnan(lbuf10).sum())}", flush=True)
213
214# ═══════════════════════════════════════
215# BENCHMARK: B=10 prefill + gen
216# ═══════════════════════════════════════
217print(f"\nStep 3: {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen, B={N_USERS}...", flush=True)
218for kv in kvs: kv.seq_len[0] = 0; ce.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD))
219
220print(f" Prefill {PROMPT_LEN} steps...", flush=True)
221pt0 = time.perf_counter()
222for 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)
225prefill_s = time.perf_counter() - pt0
226print(f" Prefill: {prefill_s:.1f}s", flush=True)
227
228print(f" Generate {GEN_TOKENS} tokens...", flush=True)
229gt0 = time.perf_counter()
230for 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)
233gen_s = time.perf_counter() - gt0
234tps = N_USERS * GEN_TOKENS / gen_s
235
236print(f"\n ╔══════════════════════════════════════════════╗")
237print(f" ║ Qwen3.6 MXFP4 batch B={N_USERS} Results ║")
238print(f" ╠══════════════════════════════════════════════╣")
239print(f" ║ C engine B=1: {1000*avg1:6.0f}ms ({1/avg1:5.1f} tok/s) ║")
240print(f" ║ C engine B={N_USERS}: {1000*avg10:6.0f}ms ({N_USERS/avg10:5.1f} tok/s aggr) ║")
241print(f" ║ Prefill ({PROMPT_LEN} steps): {prefill_s:6.1f}s ║")
242print(f" ║ Generate ({GEN_TOKENS} steps): {gen_s*1000:6.0f}ms ║")
243print(f" ║ Throughput: {tps:6.0f} tok/s ({tps/N_USERS:.0f}/user) ║")
244print(f" ╟──────────────────────────────────────────────╢")
245print(f" ║ VS Python single: 39.2ms → 25.5 tok/s ║")
246print(f" ║ VS llama.cpp: ~16 tok/s single ║")
247print(f" ║ Efficiency (B=10/B=1): {N_USERS/avg10/(1/avg1):.2f}x ║")
248print(f" ╚══════════════════════════════════════════════╝")