MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / bench_batch_gptoss.py
| 1 | #!/usr/bin/env python3 |
| 2 | """GPT-OSS-20B batch benchmark — optimized Q8_0 conversion + 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/gpt-oss-20b-Q4_K_M.gguf" |
| 7 | N_USERS = 10 |
| 8 | PROMPT_LEN = 512 |
| 9 | GEN_TOKENS = 20 |
| 10 | |
| 11 | # ── Fast Q8_0 converter (vectorized) ── |
| 12 | def f32_to_q8_vectorized(arr): |
| 13 | """Convert F32 (rows, cols) to Q8_0. Each 32-element block: float16 scale (2B) + 32×int8 (32B) = 34B.""" |
| 14 | assert arr.dtype == np.float32 |
| 15 | n_rows, nc = arr.shape |
| 16 | bpr = nc // 32 |
| 17 | blocks = arr.reshape(n_rows, bpr, 32) |
| 18 | abs_max = np.max(np.abs(blocks), axis=-1, keepdims=True) |
| 19 | d = np.where(abs_max > 0, abs_max / 127.0, 1.0) |
| 20 | q = np.clip(np.round(blocks / d), -128, 127).astype(np.int8) |
| 21 | d_f16 = d.reshape(-1).astype(np.float16).view(np.uint16) |
| 22 | q_flat = q.reshape(-1, 32) |
| 23 | n_blocks = q_flat.shape[0] |
| 24 | out = np.empty(n_blocks * 34, dtype=np.uint8).reshape(n_blocks, 34) |
| 25 | out[:, 0:2] = d_f16.reshape(-1, 1).view(np.uint8).reshape(n_blocks, 2) |
| 26 | out[:, 2:34] = q_flat.view(np.uint8).reshape(n_blocks, 32) |
| 27 | return out.reshape(-1) |
| 28 | |
| 29 | print("Loading engine...", flush=True) |
| 30 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 31 | e = TurboEngineV7MoE(MODEL, 32) |
| 32 | N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head; HD = e.head_dim |
| 33 | FF = e.n_ff; L = e.n_layers; V = e.vocab_size |
| 34 | print(f" {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd MoE {e.n_experts}x{e.n_experts_per_tok}", flush=True) |
| 35 | |
| 36 | libfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels', 'cengine_batch_instr.so') |
| 37 | lib = ctypes.CDLL(libfile) |
| 38 | cv = ctypes.c_void_p; ci = ctypes.c_int; cf = ctypes.c_float |
| 39 | |
| 40 | def wa(arr): |
| 41 | return (cv * L)(*[ctypes.cast(a, cv) for a in arr]) |
| 42 | def ia(arr): |
| 43 | return (ci * L)(*[int(a) for a in arr]) |
| 44 | |
| 45 | wQ = [0]*L; nQ = [0]*L; qQ = [0]*L |
| 46 | wK = [0]*L; nK = [0]*L; qK = [0]*L |
| 47 | wV = [0]*L; nV = [0]*L; qV = [0]*L |
| 48 | wO = [0]*L; nO = [0]*L; qO = [0]*L |
| 49 | wG = [0]*L; nG = [0]*L; qG = [0]*L |
| 50 | wU = [0]*L; nU = [0]*L; qU = [0]*L |
| 51 | wD = [0]*L; nD = [0]*L; qD = [0]*L |
| 52 | wAN = [0]*L; wFN = [0]*L |
| 53 | _q8_bufs = [] |
| 54 | |
| 55 | print("Converting F32 attention weights → Q8_0 (vectorized)...", flush=True) |
| 56 | t0 = time.perf_counter() |
| 57 | for i, lw in enumerate(e._layers): |
| 58 | if hasattr(lw, 'attn_q_f32') and lw.attn_q_f32 is not None: |
| 59 | q8 = f32_to_q8_vectorized(lw.attn_q_f32); _q8_bufs.append(q8) |
| 60 | wQ[i] = q8.ctypes.data_as(cv); nQ[i] = NH * HD; qQ[i] = 8 |
| 61 | elif hasattr(lw, 'attn_q_raw') and lw.attn_q_raw is not None: |
| 62 | wQ[i] = lw.attn_q_raw; nQ[i] = lw.attn_q_nr.value; qQ[i] = lw.attn_q_qt.value |
| 63 | if hasattr(lw, 'attn_k_f32') and lw.attn_k_f32 is not None: |
| 64 | q8 = f32_to_q8_vectorized(lw.attn_k_f32); _q8_bufs.append(q8) |
| 65 | wK[i] = q8.ctypes.data_as(cv); nK[i] = NKH * HD; qK[i] = 8 |
| 66 | elif hasattr(lw, 'attn_k_raw') and lw.attn_k_raw is not None: |
| 67 | wK[i] = lw.attn_k_raw; nK[i] = lw.attn_k_nr.value; qK[i] = lw.attn_k_qt.value |
| 68 | if hasattr(lw, 'attn_v_raw') and lw.attn_v_raw is not None: |
| 69 | wV[i] = lw.attn_v_raw; nV[i] = lw.attn_v_nr.value; qV[i] = lw.attn_v_qt.value |
| 70 | if hasattr(lw, 'attn_out_raw') and lw.attn_out_raw is not None: |
| 71 | wO[i] = lw.attn_out_raw; nO[i] = lw.attn_out_nr.value; qO[i] = lw.attn_out_qt.value |
| 72 | if hasattr(lw, 'attn_norm_w') and lw.attn_norm_w is not None: |
| 73 | wAN[i] = lw.attn_norm_w.ctypes.data_as(cv) |
| 74 | if hasattr(lw, 'ffn_norm_w') and lw.ffn_norm_w is not None: |
| 75 | wFN[i] = lw.ffn_norm_w.ctypes.data_as(cv) |
| 76 | conv_s = time.perf_counter() - t0 |
| 77 | print(f" Conversion: {conv_s:.1f}s", flush=True) |
| 78 | |
| 79 | print("Loading MoE expert pointers...", flush=True) |
| 80 | wgi_arr = [0]*L; wge_arr = [0]*L; wue_arr = [0]*L; wde_arr = [0]*L |
| 81 | for i, me in enumerate(e._moe_layers): |
| 82 | wgi_arr[i] = me.router_f32.ctypes.data_as(cv) if me.router_f32 is not None else cv(0) |
| 83 | if me.gate_raw and len(me.gate_raw) > 0: |
| 84 | wge_arr[i] = me.gate_raw[0].ctypes.data_as(cv) |
| 85 | wG[i] = me.gate_raw[0].ctypes.data_as(cv); nG[i] = me.gate_nr.value; qG[i] = me.gate_qt.value |
| 86 | if me.up_raw and len(me.up_raw) > 0: |
| 87 | wue_arr[i] = me.up_raw[0].ctypes.data_as(cv) |
| 88 | wU[i] = me.up_raw[0].ctypes.data_as(cv); nU[i] = me.up_nr.value; qU[i] = me.up_qt.value |
| 89 | if me.down_raw and len(me.down_raw) > 0: |
| 90 | wde_arr[i] = me.down_raw[0].ctypes.data_as(cv) |
| 91 | wD[i] = me.down_raw[0].ctypes.data_as(cv); nD[i] = me.down_nr.value; qD[i] = me.down_qt.value |
| 92 | |
| 93 | gate_qt = qG[0] if qG[0] else 39; up_qt = qU[0] if qU[0] else 39; down_qt = qD[0] if qD[0] else 39 |
| 94 | |
| 95 | # ── BC struct ── |
| 96 | class PageTable(ctypes.Structure): |
| 97 | _fields_ = [('page_size', ci), ('n_pages', ci), ('pages', cv), ('table', cv), |
| 98 | ('free_pages', cv), ('free_count', ci), ('_nkh', ci), ('_hd', ci), ('_n_layers', ci)] |
| 99 | class KVBlock(ctypes.Structure): |
| 100 | _fields_ = [('k', cv), ('v', cv), ('n_blocks', ci), ('seq_len', ci*64), |
| 101 | ('block_map', (ci*1024)*64), ('pt', PageTable)] |
| 102 | class BC(ctypes.Structure): |
| 103 | _fields_ = [ |
| 104 | ('L', ci), ('N', ci), ('NH', ci), ('NKH', ci), ('HD', ci), ('FF', ci), ('V', ci), ('eps', cf), |
| 105 | ('wQ', cv), ('wK', cv), ('wV', cv), ('wO', cv), ('wG', cv), ('wU', cv), ('wD', cv), |
| 106 | ('wAN', cv), ('wFN', cv), |
| 107 | ('nQ', cv), ('nK', cv), ('nV', cv), ('nO', cv), ('nG', cv), ('nU', cv), ('nD', cv), |
| 108 | ('nc', ci), ('emb', cv), ('onw', cv), ('wOut', cv), ('outNR', ci), ('outNC', ci), ('outQuant', ci), |
| 109 | ('kv_array', cv), ('logits', cv), |
| 110 | ('n_experts', ci), ('n_experts_per_tok', ci), ('moe_intermediate', ci), |
| 111 | ('w_gate_inp', cv), ('w_gate_exps', cv), ('w_up_exps', cv), ('w_down_exps', cv), |
| 112 | ('gate_exp_quant', ci), ('up_exp_quant', ci), ('down_exp_quant', ci), |
| 113 | ('q_quant', cv), ('k_quant', cv), ('v_quant', cv), ('o_quant', cv), |
| 114 | ('g_quant', cv), ('u_quant', cv), ('d_quant', cv), ('emb_quant', ci), |
| 115 | ('wQK', cv), ('qk_quant', cv), ('cos_table', cv), ('sin_table', cv), ('max_ctx', ci), |
| 116 | ('workspace', cv), ('ws_size', ci), |
| 117 | ('rope_dim', ci), ('full_attn_interval', ci), ('wQKV', cv), ('qkv_quant', cv), |
| 118 | ('wAttnG', cv), ('attnG_quant', cv), |
| 119 | ('ssm_conv1d', cv), ('ssm_a', cv), ('ssm_dt_bias', cv), ('ssm_alpha', cv), |
| 120 | ('ssm_beta', cv), ('ssm_norm', cv), ('wSsmOut', cv), ('ssm_out_quant', cv), ('ssm_state', cv), |
| 121 | ('wSHexpG', cv), ('wSHexpU', cv), ('wSHexpD', cv), |
| 122 | ('shexp_g_quant', cv), ('shexp_u_quant', cv), ('shexp_d_quant', cv), ('wShexpRouter', cv), |
| 123 | ('layer_types', cv), ('n_layers_actual', ci) |
| 124 | ] |
| 125 | |
| 126 | MAX_CTX = 4096 |
| 127 | bc = BC() |
| 128 | for a, v in [('L', L), ('N', N), ('NH', NH), ('NKH', NKH), ('HD', HD), ('FF', FF), ('V', V), ('eps', e.eps), |
| 129 | ('nc', N), ('outNR', V), ('outNC', N), ('outQuant', 8), |
| 130 | ('n_experts', e.n_experts), ('n_experts_per_tok', e.n_experts_per_tok), |
| 131 | ('moe_intermediate', e.n_ff_expert), |
| 132 | ('gate_exp_quant', gate_qt), ('up_exp_quant', up_qt), ('down_exp_quant', down_qt), |
| 133 | ('emb_quant', 0), ('max_ctx', MAX_CTX), |
| 134 | ('rope_dim', HD), ('full_attn_interval', 0), ('n_layers_actual', L)]: |
| 135 | setattr(bc, a, v) |
| 136 | |
| 137 | bc.wQ = ctypes.cast(wa(wQ), cv); bc.wK = ctypes.cast(wa(wK), cv) |
| 138 | bc.wV = ctypes.cast(wa(wV), cv); bc.wO = ctypes.cast(wa(wO), cv) |
| 139 | bc.wG = ctypes.cast(wa(wG), cv); bc.wU = ctypes.cast(wa(wU), cv); bc.wD = ctypes.cast(wa(wD), cv) |
| 140 | bc.wAN = ctypes.cast(wa(wAN), cv); bc.wFN = ctypes.cast(wa(wFN), cv) |
| 141 | bc.nQ = ctypes.cast(ia(nQ), cv); bc.nK = ctypes.cast(ia(nK), cv) |
| 142 | bc.nV = ctypes.cast(ia(nV), cv); bc.nO = ctypes.cast(ia(nO), cv) |
| 143 | bc.nG = ctypes.cast(ia(nG), cv); bc.nU = ctypes.cast(ia(nU), cv); bc.nD = ctypes.cast(ia(nD), cv) |
| 144 | bc.q_quant = ctypes.cast(ia(qQ), cv); bc.k_quant = ctypes.cast(ia(qK), cv) |
| 145 | bc.v_quant = ctypes.cast(ia(qV), cv); bc.o_quant = ctypes.cast(ia(qO), cv) |
| 146 | bc.g_quant = ctypes.cast(ia(qG), cv); bc.u_quant = ctypes.cast(ia(qU), cv); bc.d_quant = ctypes.cast(ia(qD), cv) |
| 147 | bc.w_gate_inp = ctypes.cast(wa(wgi_arr), cv) |
| 148 | bc.w_gate_exps = ctypes.cast(wa(wge_arr), cv) |
| 149 | bc.w_up_exps = ctypes.cast(wa(wue_arr), cv) |
| 150 | bc.w_down_exps = ctypes.cast(wa(wde_arr), cv) |
| 151 | bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e, 'emb') and e.emb is not None else cv(0) |
| 152 | bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e, '_out_norm_w') else cv(0) |
| 153 | if hasattr(e, '_out_raw') and e._out_raw is not None: |
| 154 | bc.wOut = ctypes.cast(e._out_raw, cv) |
| 155 | elif hasattr(e, 'weights'): |
| 156 | for k in ('output.weight', 'lm_head.weight'): |
| 157 | if k in e.weights and e.weights[k] is not None: |
| 158 | ow = np.ascontiguousarray(e.weights[k].astype(np.float32)); _q8_bufs.append(ow) |
| 159 | bc.wOut = ow.ctypes.data_as(cv); break |
| 160 | for pf in ['wQKV','wAttnG','ssm_conv1d','ssm_a','ssm_dt_bias','ssm_alpha','ssm_beta', |
| 161 | 'ssm_norm','wSsmOut','ssm_state','wSHexpG','wSHexpU','wSHexpD','wShexpRouter', |
| 162 | 'layer_types','qkv_quant','attnG_quant','ssm_out_quant','shexp_g_quant', |
| 163 | 'shexp_u_quant','shexp_d_quant']: |
| 164 | setattr(bc, pf, cv(0)) |
| 165 | bc.wQK = cv(0); bc.qk_quant = cv(0) |
| 166 | |
| 167 | cos_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32) |
| 168 | sin_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32) |
| 169 | for p in range(MAX_CTX): |
| 170 | for j in range(HD // 2): |
| 171 | ang = p / (10000.0 ** (2.0 * j / HD)) |
| 172 | cos_t[p * HD // 2 + j] = np.cos(ang); sin_t[p * HD // 2 + j] = np.sin(ang) |
| 173 | bc.cos_table = cos_t.ctypes.data_as(cv); bc.sin_table = sin_t.ctypes.data_as(cv) |
| 174 | |
| 175 | S_actual = max(N, NH*HD, FF, NKH*HD, NH*HD+NKH*HD, 8192) |
| 176 | KV_scratch = 2 * MAX_CTX * NKH * HD |
| 177 | min_ws = 12 * N_USERS * S_actual + KV_scratch + 100000 |
| 178 | ws = np.zeros(min_ws, dtype=np.float32) |
| 179 | bc.workspace = ws.ctypes.data_as(cv) |
| 180 | bc.ws_size = min_ws |
| 181 | print(f" Workspace: {min_ws:,} floats ({min_ws*4/1024/1024:.0f} MB)", flush=True) |
| 182 | |
| 183 | lib.kv_init.argtypes = [cv, ci, ci, ci]; lib.kv_init.restype = None |
| 184 | lib.batch_forward.argtypes = [cv, cv, ci, cv]; lib.batch_forward.restype = None |
| 185 | lib.rope_init.argtypes = [cv, cv, ci, ci, ci]; lib.rope_init.restype = None |
| 186 | lib.rope_init(bc.cos_table, bc.sin_table, ci(MAX_CTX), ci(HD), ci(HD)) |
| 187 | |
| 188 | # Helper: call batch_forward with correct ws pointer |
| 189 | ws_ptr = ws.ctypes.data_as(cv) |
| 190 | def bf(tokens, B): |
| 191 | lib.batch_forward( |
| 192 | ctypes.byref(bc), |
| 193 | (ci * B)(*tokens) if isinstance(tokens, (list, tuple)) else tokens, |
| 194 | ci(B), ws_ptr |
| 195 | ) |
| 196 | |
| 197 | # ── Step 1: B=1 test ── |
| 198 | print("\nStep 1: batch_forward B=1...", flush=True) |
| 199 | kv1 = KVBlock() |
| 200 | lib.kv_init(ctypes.byref(kv1), ci(L), ci(NKH), ci(HD)) |
| 201 | kv_arr1 = (cv*1)(ctypes.cast(ctypes.pointer(kv1), cv)) |
| 202 | bc.kv_array = ctypes.cast(kv_arr1, cv) |
| 203 | lbuf1 = np.zeros(V, dtype=np.float32) |
| 204 | bc.logits = lbuf1.ctypes.data_as(cv) |
| 205 | |
| 206 | try: |
| 207 | t0 = time.perf_counter() |
| 208 | bf([1], 1) |
| 209 | elapsed = time.perf_counter() - t0 |
| 210 | maxv = float(lbuf1.max()); nan_c = int(np.isnan(lbuf1).sum()) |
| 211 | print(f" B=1: max={maxv:.1f}, nan={nan_c}, {elapsed*1000:.0f}ms", flush=True) |
| 212 | if nan_c == 0 and maxv > 0: print(" ✅ B=1 PASS", flush=True) |
| 213 | else: print(" ❌ B=1 FAIL", flush=True); sys.exit(1) |
| 214 | except Exception as ex: |
| 215 | print(f" ❌ B=1 CRASH: {ex}", flush=True); import traceback; traceback.print_exc(); sys.exit(1) |
| 216 | |
| 217 | # ── Step 2: B=10 same token ── |
| 218 | print(f"\nStep 2: batch_forward B={N_USERS}...", flush=True) |
| 219 | kvs = [KVBlock() for _ in range(N_USERS)] |
| 220 | for kv in kvs: lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) |
| 221 | bc.kv_array = ctypes.cast((cv*N_USERS)(*[ctypes.cast(ctypes.pointer(k), cv) for k in kvs]), cv) |
| 222 | lbuf = np.zeros(N_USERS * V, dtype=np.float32) |
| 223 | bc.logits = lbuf.ctypes.data_as(cv) |
| 224 | |
| 225 | try: |
| 226 | t0 = time.perf_counter() |
| 227 | bf([1]*N_USERS, N_USERS) |
| 228 | elapsed = time.perf_counter() - t0 |
| 229 | ok = all(np.isnan(lbuf[u*V:(u+1)*V]).sum() == 0 for u in range(N_USERS)) |
| 230 | if ok: print(f" B=10: max={lbuf.max():.1f}, {elapsed*1000:.0f}ms", flush=True); print(" ✅ B=10 PASS", flush=True) |
| 231 | else: print(" ❌ B=10 NaN", flush=True); sys.exit(1) |
| 232 | except Exception as ex: |
| 233 | print(f" ❌ B=10 CRASH: {ex}", flush=True); sys.exit(1) |
| 234 | |
| 235 | # ── Step 3: 512-tok prefill + 20-tok gen ── |
| 236 | print(f"\nStep 3: {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen", flush=True) |
| 237 | for kv in kvs: kv.seq_len[0] = 0 |
| 238 | print(" Warmup (3 steps)...", flush=True) |
| 239 | for _ in range(3): bf([100]*N_USERS, N_USERS) |
| 240 | for kv in kvs: kv.seq_len[0] = 0 |
| 241 | |
| 242 | print(f" Prefill {PROMPT_LEN}x{N_USERS} = {PROMPT_LEN*N_USERS} tokens...", flush=True) |
| 243 | t0 = time.perf_counter() |
| 244 | for pos in range(PROMPT_LEN): |
| 245 | bf([100+(pos%50000)]*N_USERS, N_USERS) |
| 246 | if pos % 100 == 99: print(f" pos {pos+1}/{PROMPT_LEN} ({time.perf_counter()-t0:.1f}s)", flush=True) |
| 247 | prefill_s = time.perf_counter() - t0 |
| 248 | print(f" Prefill done in {prefill_s:.1f}s", flush=True) |
| 249 | |
| 250 | print(f" Generate {GEN_TOKENS} tokens...", flush=True) |
| 251 | gen_t0 = time.perf_counter() |
| 252 | for step in range(GEN_TOKENS): |
| 253 | if step == 0: bf([1]*N_USERS, N_USERS) |
| 254 | else: bf([int(np.argmax(lbuf[u*V:(u+1)*V])) for u in range(N_USERS)], N_USERS) |
| 255 | gen_s = time.perf_counter() - gen_t0 |
| 256 | total_s = prefill_s + gen_s |
| 257 | tps = N_USERS * GEN_TOKENS / gen_s |
| 258 | lat_ms = gen_s / GEN_TOKENS * 1000 |
| 259 | |
| 260 | print(f"\n ╔══════════════════════════════════════╗") |
| 261 | print(f" ║ GPT-OSS-20B batch B={N_USERS} Results ║") |
| 262 | print(f" ╠══════════════════════════════════════╣") |
| 263 | print(f" ║ Prefill: {prefill_s:.1f}s ({PROMPT_LEN} steps) ║") |
| 264 | print(f" ║ Generate: {gen_s*1000:.0f}ms ({GEN_TOKENS} steps) ║") |
| 265 | print(f" ║ Throughput: {tps:.0f} tok/s ({tps/N_USERS:.0f}/user) ║") |
| 266 | print(f" ║ Avg step: {lat_ms:.0f}ms ║") |
| 267 | print(f" ╟──────────────────────────────────────╢") |
| 268 | ref = 9.1 |
| 269 | ratio = tps / ref |
| 270 | if ratio > 1: |
| 271 | print(f" ║ VS llama.cpp 512-prefill: {ref} tok/s ║") |
| 272 | print(f" ║ ✅ MojoLlama {ratio:.1f}x FASTER! ║") |
| 273 | else: |
| 274 | print(f" ║ VS llama.cpp: {ref} tok/s → {ratio:.1f}x ║") |
| 275 | print(f" ╚══════════════════════════════════════╝") |