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_batch_gptoss.py

275 lines · 14132 bytes Raw Blame History
1#!/usr/bin/env python3
2"""GPT-OSS-20B batch benchmark — optimized Q8_0 conversion + 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/gpt-oss-20b-Q4_K_M.gguf"
7N_USERS = 10
8PROMPT_LEN = 512
9GEN_TOKENS = 20
10
11# ── Fast Q8_0 converter (vectorized) ──
12def 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
29print("Loading engine...", flush=True)
30from turbo_engine_v7_moe import TurboEngineV7MoE
31e = TurboEngineV7MoE(MODEL, 32)
32N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head; HD = e.head_dim
33FF = e.n_ff; L = e.n_layers; V = e.vocab_size
34print(f" {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd MoE {e.n_experts}x{e.n_experts_per_tok}", flush=True)
35
36libfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels', 'cengine_batch_instr.so')
37lib = ctypes.CDLL(libfile)
38cv = ctypes.c_void_p; ci = ctypes.c_int; cf = ctypes.c_float
39
40def wa(arr):
41 return (cv * L)(*[ctypes.cast(a, cv) for a in arr])
42def ia(arr):
43 return (ci * L)(*[int(a) for a in arr])
44
45wQ = [0]*L; nQ = [0]*L; qQ = [0]*L
46wK = [0]*L; nK = [0]*L; qK = [0]*L
47wV = [0]*L; nV = [0]*L; qV = [0]*L
48wO = [0]*L; nO = [0]*L; qO = [0]*L
49wG = [0]*L; nG = [0]*L; qG = [0]*L
50wU = [0]*L; nU = [0]*L; qU = [0]*L
51wD = [0]*L; nD = [0]*L; qD = [0]*L
52wAN = [0]*L; wFN = [0]*L
53_q8_bufs = []
54
55print("Converting F32 attention weights → Q8_0 (vectorized)...", flush=True)
56t0 = time.perf_counter()
57for 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)
76conv_s = time.perf_counter() - t0
77print(f" Conversion: {conv_s:.1f}s", flush=True)
78
79print("Loading MoE expert pointers...", flush=True)
80wgi_arr = [0]*L; wge_arr = [0]*L; wue_arr = [0]*L; wde_arr = [0]*L
81for 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
93gate_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 ──
96class 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)]
99class KVBlock(ctypes.Structure):
100 _fields_ = [('k', cv), ('v', cv), ('n_blocks', ci), ('seq_len', ci*64),
101 ('block_map', (ci*1024)*64), ('pt', PageTable)]
102class 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
126MAX_CTX = 4096
127bc = BC()
128for 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
137bc.wQ = ctypes.cast(wa(wQ), cv); bc.wK = ctypes.cast(wa(wK), cv)
138bc.wV = ctypes.cast(wa(wV), cv); bc.wO = ctypes.cast(wa(wO), cv)
139bc.wG = ctypes.cast(wa(wG), cv); bc.wU = ctypes.cast(wa(wU), cv); bc.wD = ctypes.cast(wa(wD), cv)
140bc.wAN = ctypes.cast(wa(wAN), cv); bc.wFN = ctypes.cast(wa(wFN), cv)
141bc.nQ = ctypes.cast(ia(nQ), cv); bc.nK = ctypes.cast(ia(nK), cv)
142bc.nV = ctypes.cast(ia(nV), cv); bc.nO = ctypes.cast(ia(nO), cv)
143bc.nG = ctypes.cast(ia(nG), cv); bc.nU = ctypes.cast(ia(nU), cv); bc.nD = ctypes.cast(ia(nD), cv)
144bc.q_quant = ctypes.cast(ia(qQ), cv); bc.k_quant = ctypes.cast(ia(qK), cv)
145bc.v_quant = ctypes.cast(ia(qV), cv); bc.o_quant = ctypes.cast(ia(qO), cv)
146bc.g_quant = ctypes.cast(ia(qG), cv); bc.u_quant = ctypes.cast(ia(qU), cv); bc.d_quant = ctypes.cast(ia(qD), cv)
147bc.w_gate_inp = ctypes.cast(wa(wgi_arr), cv)
148bc.w_gate_exps = ctypes.cast(wa(wge_arr), cv)
149bc.w_up_exps = ctypes.cast(wa(wue_arr), cv)
150bc.w_down_exps = ctypes.cast(wa(wde_arr), cv)
151bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e, 'emb') and e.emb is not None else cv(0)
152bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e, '_out_norm_w') else cv(0)
153if hasattr(e, '_out_raw') and e._out_raw is not None:
154 bc.wOut = ctypes.cast(e._out_raw, cv)
155elif 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
160for 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))
165bc.wQK = cv(0); bc.qk_quant = cv(0)
166
167cos_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32)
168sin_t = np.zeros(MAX_CTX * HD // 2, dtype=np.float32)
169for 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)
173bc.cos_table = cos_t.ctypes.data_as(cv); bc.sin_table = sin_t.ctypes.data_as(cv)
174
175S_actual = max(N, NH*HD, FF, NKH*HD, NH*HD+NKH*HD, 8192)
176KV_scratch = 2 * MAX_CTX * NKH * HD
177min_ws = 12 * N_USERS * S_actual + KV_scratch + 100000
178ws = np.zeros(min_ws, dtype=np.float32)
179bc.workspace = ws.ctypes.data_as(cv)
180bc.ws_size = min_ws
181print(f" Workspace: {min_ws:,} floats ({min_ws*4/1024/1024:.0f} MB)", flush=True)
182
183lib.kv_init.argtypes = [cv, ci, ci, ci]; lib.kv_init.restype = None
184lib.batch_forward.argtypes = [cv, cv, ci, cv]; lib.batch_forward.restype = None
185lib.rope_init.argtypes = [cv, cv, ci, ci, ci]; lib.rope_init.restype = None
186lib.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
189ws_ptr = ws.ctypes.data_as(cv)
190def 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 ──
198print("\nStep 1: batch_forward B=1...", flush=True)
199kv1 = KVBlock()
200lib.kv_init(ctypes.byref(kv1), ci(L), ci(NKH), ci(HD))
201kv_arr1 = (cv*1)(ctypes.cast(ctypes.pointer(kv1), cv))
202bc.kv_array = ctypes.cast(kv_arr1, cv)
203lbuf1 = np.zeros(V, dtype=np.float32)
204bc.logits = lbuf1.ctypes.data_as(cv)
205
206try:
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)
214except 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 ──
218print(f"\nStep 2: batch_forward B={N_USERS}...", flush=True)
219kvs = [KVBlock() for _ in range(N_USERS)]
220for kv in kvs: lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD))
221bc.kv_array = ctypes.cast((cv*N_USERS)(*[ctypes.cast(ctypes.pointer(k), cv) for k in kvs]), cv)
222lbuf = np.zeros(N_USERS * V, dtype=np.float32)
223bc.logits = lbuf.ctypes.data_as(cv)
224
225try:
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)
232except 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 ──
236print(f"\nStep 3: {PROMPT_LEN}-tok prefill + {GEN_TOKENS}-tok gen", flush=True)
237for kv in kvs: kv.seq_len[0] = 0
238print(" Warmup (3 steps)...", flush=True)
239for _ in range(3): bf([100]*N_USERS, N_USERS)
240for kv in kvs: kv.seq_len[0] = 0
241
242print(f" Prefill {PROMPT_LEN}x{N_USERS} = {PROMPT_LEN*N_USERS} tokens...", flush=True)
243t0 = time.perf_counter()
244for 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)
247prefill_s = time.perf_counter() - t0
248print(f" Prefill done in {prefill_s:.1f}s", flush=True)
249
250print(f" Generate {GEN_TOKENS} tokens...", flush=True)
251gen_t0 = time.perf_counter()
252for 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)
255gen_s = time.perf_counter() - gen_t0
256total_s = prefill_s + gen_s
257tps = N_USERS * GEN_TOKENS / gen_s
258lat_ms = gen_s / GEN_TOKENS * 1000
259
260print(f"\n ╔══════════════════════════════════════╗")
261print(f" ║ GPT-OSS-20B batch B={N_USERS} Results ║")
262print(f" ╠══════════════════════════════════════╣")
263print(f" ║ Prefill: {prefill_s:.1f}s ({PROMPT_LEN} steps) ║")
264print(f" ║ Generate: {gen_s*1000:.0f}ms ({GEN_TOKENS} steps) ║")
265print(f" ║ Throughput: {tps:.0f} tok/s ({tps/N_USERS:.0f}/user) ║")
266print(f" ║ Avg step: {lat_ms:.0f}ms ║")
267print(f" ╟──────────────────────────────────────╢")
268ref = 9.1
269ratio = tps / ref
270if ratio > 1:
271 print(f" ║ VS llama.cpp 512-prefill: {ref} tok/s ║")
272 print(f" ║ ✅ MojoLlama {ratio:.1f}x FASTER! ║")
273else:
274 print(f" ║ VS llama.cpp: {ref} tok/s → {ratio:.1f}x ║")
275print(f" ╚══════════════════════════════════════╝")