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_batch_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_batch_qwen36.py` 229 lines · 11451 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Qwen3.6-35B MXFP4 in C engine batch_forward B=1 benchmark.""" 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 8 print("Loading engine...", flush=True) 9 from turbo_engine_v7_moe import TurboEngineV7MoE 10 e = TurboEngineV7MoE(MODEL, 32) 11 N=e.n_embd; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim 12 FF=e.n_ff; L=e.n_layers; V=e.vocab_size 13 EXP=e.n_experts; ET=e.n_experts_per_tok; EFF=e.n_ff_expert 14 print(f" {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd MoE {EXP}x{ET} ef={EFF}", flush=True) 15 16 libfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels', 'cengine_batch_instr.so') 17 ce = ctypes.CDLL(libfile) 18 cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float 19 20 def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr]) 21 def ia(arr): return (ci*L)(*[int(a) for a in arr]) 22 23 # ── Collect all weight arrays ── 24 LT = e.layer_types if hasattr(e, 'layer_types') else [0]*L 25 26 # Attention paths 27 wQKV = [cv(0)]*L; qkv_qt = [0]*L 28 wQ_sep = [cv(0)]*L; nQ_sep = [0]*L; qQ_sep = [0]*L 29 wK_sep = [cv(0)]*L; nK_sep = [0]*L; qK_sep = [0]*L 30 wV_sep = [cv(0)]*L; nV_sep = [0]*L; qV_sep = [0]*L 31 wAG = [cv(0)]*L; ag_qt = [0]*L 32 wO_attn = [cv(0)]*L; nO_attn = [0]*L; qO_attn = [0]*L 33 wSO = [cv(0)]*L; so_qt = [0]*L 34 ssm_c1d = [cv(0)]*L; ssm_a = [cv(0)]*L; ssm_db = [cv(0)]*L 35 ssm_al = [cv(0)]*L; ssm_be = [cv(0)]*L; ssm_nm = [cv(0)]*L 36 wSHG = [cv(0)]*L; wSHU = [cv(0)]*L; wSHD = [cv(0)]*L; wSHR = [cv(0)]*L 37 shg_qt = [0]*L; shu_qt = [0]*L; shd_qt = [0]*L 38 wAN = [0]*L; wFN = [0]*L 39 # MoE 40 wGI = [cv(0)]*L; wGE = [cv(0)]*L; wUE = [cv(0)]*L; wDE = [cv(0)]*L 41 ns_G = [0]*L; ns_U = [0]*L; ns_D = [0]*L 42 qt_G = [0]*L; qt_U = [0]*L; qt_D = [0]*L 43 44 print("Building weight arrays...", flush=True) 45 for i in range(L): 46 lw = e._layers[i]; me = e._moe_layers[i] 47 # QKV fused (attn layers) 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 # Separate Q/K/V (SSM-sub layers) 51 if hasattr(lw,'attn_q_raw') and lw.attn_q_raw is not None: 52 wQ_sep[i]=lw.attn_q_raw; nQ_sep[i]=lw.attn_q_nr.value; qQ_sep[i]=lw.attn_q_qt.value 53 if hasattr(lw,'attn_k_raw') and lw.attn_k_raw is not None: 54 wK_sep[i]=lw.attn_k_raw; nK_sep[i]=lw.attn_k_nr.value; qK_sep[i]=lw.attn_k_qt.value 55 if hasattr(lw,'attn_v_raw') and lw.attn_v_raw is not None: 56 wV_sep[i]=lw.attn_v_raw; nV_sep[i]=lw.attn_v_nr.value; qV_sep[i]=lw.attn_v_qt.value 57 # Attention gate (all layers) 58 if hasattr(lw,'attn_gate_raw') and lw.attn_gate_raw is not None: 59 wAG[i]=lw.attn_gate_raw; ag_qt[i]=lw.attn_gate_qt.value 60 # Attention output (for layers without attn_gate) 61 if hasattr(lw,'attn_out_raw') and lw.attn_out_raw is not None: 62 wO_attn[i]=lw.attn_out_raw 63 nO_attn[i]=lw.attn_out_nr.value if hasattr(lw,'attn_out_nr') else N 64 qO_attn[i]=lw.attn_out_qt.value if hasattr(lw,'attn_out_qt') else 8 65 # SSM specific 66 if hasattr(lw,'ssm_conv1d_ptr') and lw.ssm_conv1d_ptr is not None: 67 ssm_c1d[i]=lw.ssm_conv1d_ptr; ssm_a[i]=lw.ssm_a_ptr; ssm_db[i]=lw.ssm_dt_bias_ptr 68 ssm_al[i]=lw.ssm_alpha_ptr; ssm_be[i]=lw.ssm_beta_ptr; ssm_nm[i]=lw.ssm_norm_ptr 69 if hasattr(lw,'ssm_out_raw') and lw.ssm_out_raw is not None: 70 wSO[i]=lw.ssm_out_raw; so_qt[i]=lw.ssm_out_qt.value 71 # Shared expert 72 if hasattr(lw,'shexp_gate_raw') and lw.shexp_gate_raw is not None: 73 wSHG[i]=lw.shexp_gate_raw; shg_qt[i]=lw.shexp_gate_qt.value 74 if hasattr(lw,'shexp_up_raw') and lw.shexp_up_raw is not None: 75 wSHU[i]=lw.shexp_up_raw; shu_qt[i]=lw.shexp_up_qt.value 76 if hasattr(lw,'shexp_down_raw') and lw.shexp_down_raw is not None: 77 wSHD[i]=lw.shexp_down_raw; shd_qt[i]=lw.shexp_down_qt.value 78 if hasattr(lw,'shexp_router_ptr') and lw.shexp_router_ptr is not None: 79 wSHR[i]=lw.shexp_router_ptr 80 # MoE router 81 if hasattr(me,'router_f32') and me.router_f32 is not None: 82 wGI[i]=me.router_f32.ctypes.data_as(cv) 83 # MoE experts (first expert's pointer — stride handles rest) 84 if me.gate_raw and len(me.gate_raw)>0: 85 wGE[i]=me.gate_raw[0].ctypes.data_as(cv) 86 ns_G[i]=me.gate_nr.value; qt_G[i]=me.gate_qt.value 87 if me.up_raw and len(me.up_raw)>0: 88 wUE[i]=me.up_raw[0].ctypes.data_as(cv) 89 ns_U[i]=me.up_nr.value; qt_U[i]=me.up_qt.value 90 if me.down_raw and len(me.down_raw)>0: 91 wDE[i]=me.down_raw[0].ctypes.data_as(cv) 92 ns_D[i]=me.down_nr.value; qt_D[i]=me.down_qt.value 93 # Norm weights 94 if hasattr(lw,'attn_norm_w') and lw.attn_norm_w is not None: 95 wAN[i]=lw.attn_norm_w.ctypes.data_as(cv) 96 if hasattr(lw,'ffn_norm_w') and lw.ffn_norm_w is not None: 97 wFN[i]=lw.ffn_norm_w.ctypes.data_as(cv) 98 99 me0 = e._moe_layers[0] 100 gate_qt_all = me0.gate_qt.value; up_qt_all = me0.up_qt.value; down_qt_all = me0.down_qt.value 101 102 # ── Build BC ── 103 class PageTable(ctypes.Structure): 104 _fields_=[('page_size',ci),('n_pages',ci),('pages',cv),('table',cv), 105 ('free_pages',cv),('free_count',ci),('_nkh',ci),('_hd',ci),('_n_layers',ci)] 106 class KVBlock(ctypes.Structure): 107 _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64), 108 ('block_map',(ci*1024)*64),('pt',PageTable)] 109 class BC(ctypes.Structure): 110 _fields_=[ 111 ('L',ci),('N',ci),('NH',ci),('NKH',ci),('HD',ci),('FF',ci),('V',ci),('eps',cf), 112 ('wQ',cv),('wK',cv),('wV',cv),('wO',cv),('wG',cv),('wU',cv),('wD',cv), 113 ('wAN',cv),('wFN',cv),('nQ',cv),('nK',cv),('nV',cv),('nO',cv),('nG',cv),('nU',cv),('nD',cv), 114 ('nc',ci),('emb',cv),('onw',cv),('wOut',cv),('outNR',ci),('outNC',ci),('outQuant',ci), 115 ('kv_array',cv),('logits',cv), 116 ('n_experts',ci),('n_experts_per_tok',ci),('moe_intermediate',ci), 117 ('w_gate_inp',cv),('w_gate_exps',cv),('w_up_exps',cv),('w_down_exps',cv), 118 ('gate_exp_quant',ci),('up_exp_quant',ci),('down_exp_quant',ci), 119 ('q_quant',cv),('k_quant',cv),('v_quant',cv),('o_quant',cv), 120 ('g_quant',cv),('u_quant',cv),('d_quant',cv),('emb_quant',ci), 121 ('wQK',cv),('qk_quant',cv),('cos_table',cv),('sin_table',cv),('max_ctx',ci), 122 ('workspace',cv),('ws_size',ci), 123 ('rope_dim',ci),('full_attn_interval',ci), 124 ('wQKV',cv),('qkv_quant',cv),('wAttnG',cv),('attnG_quant',cv), 125 ('ssm_conv1d',cv),('ssm_a',cv),('ssm_dt_bias',cv),('ssm_alpha',cv), 126 ('ssm_beta',cv),('ssm_norm',cv),('wSsmOut',cv),('ssm_out_quant',cv),('ssm_state',cv), 127 ('wSHexpG',cv),('wSHexpU',cv),('wSHexpD',cv), 128 ('shexp_g_quant',cv),('shexp_u_quant',cv),('shexp_d_quant',cv),('wShexpRouter',cv), 129 ('layer_types',cv),('n_layers_actual',ci) 130 ] 131 132 MAX_CTX = 4096 133 bc = BC() 134 for a,v in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps), 135 ('nc',N),('outNR',V),('outNC',N),('outQuant',8), 136 ('n_experts',EXP),('n_experts_per_tok',ET),('moe_intermediate',EFF), 137 ('gate_exp_quant',gate_qt_all),('up_exp_quant',up_qt_all),('down_exp_quant',down_qt_all), 138 ('emb_quant',0),('max_ctx',MAX_CTX), 139 ('rope_dim',HD),('full_attn_interval',4),('n_layers_actual',L)]: 140 setattr(bc,a,v) 141 142 # Wire all attention paths 143 bc.wQKV = ctypes.cast(wa(wQKV), cv); bc.qkv_quant = ctypes.cast(ia(qkv_qt), cv) 144 bc.wQ = ctypes.cast(wa(wQ_sep), cv); bc.wK = ctypes.cast(wa(wK_sep), cv); bc.wV = ctypes.cast(wa(wV_sep), cv) 145 bc.nQ = ctypes.cast(ia(nQ_sep), cv); bc.nK = ctypes.cast(ia(nK_sep), cv); bc.nV = ctypes.cast(ia(nV_sep), cv) 146 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) 147 bc.wAttnG = ctypes.cast(wa(wAG), cv); bc.attnG_quant = ctypes.cast(ia(ag_qt), cv) 148 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) 149 bc.wSsmOut = ctypes.cast(wa(wSO), cv); bc.ssm_out_quant = ctypes.cast(ia(so_qt), cv) 150 bc.ssm_conv1d = ctypes.cast(wa(ssm_c1d), cv); bc.ssm_a = ctypes.cast(wa(ssm_a), cv) 151 bc.ssm_dt_bias = ctypes.cast(wa(ssm_db), cv); bc.ssm_alpha = ctypes.cast(wa(ssm_al), cv) 152 bc.ssm_beta = ctypes.cast(wa(ssm_be), cv); bc.ssm_norm = ctypes.cast(wa(ssm_nm), cv) 153 bc.wSHexpG = ctypes.cast(wa(wSHG), cv); bc.wSHexpU = ctypes.cast(wa(wSHU), cv) 154 bc.wSHexpD = ctypes.cast(wa(wSHD), cv); bc.wShexpRouter = ctypes.cast(wa(wSHR), cv) 155 bc.shexp_g_quant = ctypes.cast(ia(shg_qt), cv); bc.shexp_u_quant = ctypes.cast(ia(shu_qt), cv) 156 bc.shexp_d_quant = ctypes.cast(ia(shd_qt), cv) 157 bc.wAN = ctypes.cast(wa(wAN), cv); bc.wFN = ctypes.cast(wa(wFN), cv) 158 159 # MoE 160 bc.w_gate_inp = ctypes.cast(wa(wGI), cv) 161 bc.w_gate_exps = ctypes.cast(wa(wGE), cv) 162 bc.w_up_exps = ctypes.cast(wa(wUE), cv) 163 bc.w_down_exps = ctypes.cast(wa(wDE), cv) 164 bc.nG = ctypes.cast(ia(ns_G), cv); bc.nU = ctypes.cast(ia(ns_U), cv); bc.nD = ctypes.cast(ia(ns_D), cv) 165 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) 166 167 # NULL unused fields (Qwen3.6 doesn't use dense FFN weight arrays) 168 for pf in ['wG','wU','wD','nG','nU','nD', 169 'g_quant','u_quant','d_quant', 170 'wQK','qk_quant']: 171 setattr(bc, pf, cv(0)) 172 173 bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e,'emb') and e.emb is not None else cv(0) 174 bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0) 175 bc.wOut = ctypes.cast(e._out_raw, cv) 176 177 # SSM state 178 ssm_state = np.zeros(L * e.ssm_groups * e.ssm_state_size, dtype=np.float32) 179 bc.ssm_state = ssm_state.ctypes.data_as(cv) 180 181 # Layer types 182 lt_arr = (ci * L)(*LT) 183 bc.layer_types = ctypes.cast(lt_arr, cv) 184 185 # RoPE 186 cos_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32) 187 sin_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32) 188 for p in range(MAX_CTX): 189 for j in range(HD // 2): 190 ang = p / (10000.0 ** (2.0 * j / HD)) 191 cos_t[p*HD//2+j]=np.cos(ang); sin_t[p*HD//2+j]=np.sin(ang) 192 bc.cos_table=cos_t.ctypes.data_as(cv); bc.sin_table=sin_t.ctypes.data_as(cv) 193 194 S_act = max(N, NH*HD, FF, NKH, NH*HD+NKH, 8192) 195 min_ws = 12 * 1 * S_act + 2 * MAX_CTX * NKH * HD + 100000 196 ws = np.zeros(min_ws, dtype=np.float32) 197 bc.workspace = ws.ctypes.data_as(cv); bc.ws_size = min_ws 198 print(f" Workspace: {min_ws:,} floats", flush=True) 199 200 ce.kv_init.argtypes=[cv,ci,ci,ci]; ce.kv_init.restype=None 201 ce.batch_forward.argtypes=[cv,cv,ci,cv]; ce.batch_forward.restype=None 202 ce.rope_init.argtypes=[cv,cv,ci,ci,ci]; ce.rope_init.restype=None 203 ce.rope_init(bc.cos_table, bc.sin_table, ci(MAX_CTX), ci(HD), ci(HD)) 204 205 ws_ptr = ws.ctypes.data_as(cv) 206 def bf(tok, B=1): 207 ce.batch_forward(ctypes.byref(bc), (ci*B)(*([tok]*B)), ci(B), ws_ptr) 208 209 # ── Benchmark ── 210 print("\nB=1 test...", flush=True) 211 kv = KVBlock(); ce.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) 212 bc.kv_array = ctypes.cast((cv*1)(ctypes.cast(ctypes.pointer(kv), cv)), cv) 213 lbuf = np.zeros(V, dtype=np.float32) 214 bc.logits = lbuf.ctypes.data_as(cv) 215 216 for _ in range(3): bf(1); kv.seq_len[0] = 0 217 218 times = [] 219 for _ in range(30): 220 t0 = time.perf_counter(); bf(1); t1 = time.perf_counter() 221 times.append(t1 - t0); kv.seq_len[0] = 0 222 223 times = times[5:] 224 avg = np.mean(times); tps = 1.0/avg 225 mx = float(lbuf.max()); nc = int(np.isnan(lbuf).sum()) 226 print(f" C engine B=1: {avg*1000:.1f}ms → {tps:.1f} tok/s", flush=True) 227 print(f" max={mx:.1f}, nan={nc}", flush=True) 228 print(f" VS Python: 40.1ms → 24.9 tok/s", flush=True) 229 print(f" Ratio: {tps/24.9:.2f}x", flush=True)