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 / tests / test_forward_standalone.py

209 lines · 9407 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Standalone MoE engine test — loads model, runs 1 forward step, prints logits."""
3import signal, faulthandler, sys, os, time, ctypes, json
4faulthandler.enable()
5# Also register a signal handler for SIGSEGV
6def debug_segfault(sig, frame):
7 print(f"\n!!! SIGNAL {sig} at frame: {frame}", flush=True)
8 import traceback
9 traceback.print_stack(frame)
10 sys.exit(1)
11signal.signal(signal.SIGSEGV, debug_segfault)
12import numpy as np
13
14sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels')
15from turbo_engine_v7_moe import TurboEngineV7MoE
16
17MODEL = sys.argv[1] if len(sys.argv) > 1 else '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf'
18TOKENIZER_PATH = '/tmp/qwen3-tokenizer/'
19
20# ── Load engine ──
21t0 = time.perf_counter()
22e = TurboEngineV7MoE(MODEL, 32)
23L = e.n_layers; N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head
24HD = e.head_dim; FF = e.n_ff; V = e.vocab_size; eps = e.eps
25NE = e.n_experts; NK = e.n_experts_per_tok
26moe_int = e.n_ff_expert if hasattr(e, 'n_ff_expert') else FF
27S = max(N, NH*HD, FF, NKH*HD, moe_int)
28print(f"Loaded: {L}L/{N}D/{FF}FF/{NH}H/{NKH}KV | MoE {NE}x{NK} | V={V} | S={S}", flush=True)
29print(f"Load time: {time.perf_counter()-t0:.1f}s", flush=True)
30
31# ── Build BC struct ──
32lib = ctypes.CDLL('/onedev-workspace/work/src/mojollama/kernels/cengine_batch.so')
33cv = ctypes.c_void_p; ci = ctypes.c_int; cf = ctypes.c_float
34
35class BC(ctypes.Structure):
36 _fields_ = [
37 ("L",ci),("N",ci),("NH",ci),("NKH",ci),("HD",ci),("FF",ci),("V",ci),("eps",cf),
38 ("wQ",cv),("wK",cv),("wV",cv),("wO",cv),("wG",cv),("wU",cv),("wD",cv),
39 ("wAN",cv),("wFN",cv),("nQ",cv),("nK",cv),("nV",cv),("nO",cv),("nG",cv),("nU",cv),("nD",cv),
40 ("nc",ci),("emb",cv),("onw",cv),("wOut",cv),("outNR",ci),("outNC",ci),("outQuant",ci),
41 ("kv_array",cv),("logits",cv),
42 ("n_experts",ci),("n_experts_per_tok",ci),("moe_intermediate",ci),
43 ("w_gate_inp",cv),("w_gate_exps",cv),("w_up_exps",cv),("w_down_exps",cv),
44 ("gate_exp_quant",ci),("up_exp_quant",ci),("down_exp_quant",ci),
45 ("q_quant",cv),("k_quant",cv),("v_quant",cv),("o_quant",cv),
46 ("g_quant",cv),("u_quant",cv),("d_quant",cv),("emb_quant",ci),
47 ("cos_table",cv),("sin_table",cv),("max_ctx",ci),
48 ]
49
50class KVBlock(ctypes.Structure):
51 _fields_ = [("k",cv),("v",cv),("n_blocks",ci),("seq_len",ci*64),("block_map",(ci*1024)*64)]
52
53lib.batch_forward.argtypes = [cv, cv, ci, cv]; lib.batch_forward.restype = None
54lib.kv_init.argtypes = [cv, ci, ci, ci]; lib.kv_init.restype = None
55
56def wa(arr):
57 return (cv*L)(*[ctypes.cast(a, cv) for a in arr])
58def ia(arr):
59 return (ci*L)(*[int(a) for a in arr])
60
61bc = BC()
62for attr, val in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',eps),
63 ('nc',N),('outNR',V),('outNC',N),('outQuant',8),
64 ('n_experts',NE),('n_experts_per_tok',NK),('moe_intermediate',moe_int),
65 ('gate_exp_quant',12),('up_exp_quant',12),('down_exp_quant',14),
66 ('emb_quant',0)]:
67 setattr(bc, attr, val)
68
69# Weight pointers from engine
70wQ_arr = [0]*L; wK_arr = [0]*L; wV_arr = [0]*L; wO_arr = [0]*L
71wG_arr = [0]*L; wU_arr = [0]*L; wD_arr = [0]*L
72wAN_arr = [0]*L; wFN_arr = [0]*L
73nQ_arr = [0]*L; nK_arr = [0]*L; nV_arr = [0]*L; nO_arr = [0]*L
74nG_arr = [0]*L; nU_arr = [0]*L; nD_arr = [0]*L
75qQ_arr = [0]*L; qK_arr = [0]*L; qV_arr = [0]*L; qO_arr = [0]*L
76qG_arr = [0]*L; qU_arr = [0]*L; qD_arr = [0]*L
77
78for i, lw in enumerate(e._layers):
79 for attr, nm in [('attn_q','Q'),('attn_k','K'),('attn_v','V'),('attn_out','O'),
80 ('ffn_gate','G'),('ffn_up','U'),('ffn_down','D')]:
81 raw_attr = f'{attr}_raw'
82 if hasattr(lw, raw_attr):
83 raw = getattr(lw, raw_attr)
84 nr = getattr(lw, f'{attr}_nr').value
85 qt = getattr(lw, f'{attr}_qt').value
86 else:
87 f32 = getattr(lw, f'{attr}_f32')
88 raw = f32.ctypes.data_as(cv) if f32 is not None else cv(0)
89 nr = f32.shape[0] if f32 is not None else 0
90 qt = 0
91 target = nm
92 if target == 'Q': wQ_arr[i] = raw; nQ_arr[i] = nr; qQ_arr[i] = qt
93 elif target == 'K': wK_arr[i] = raw; nK_arr[i] = nr; qK_arr[i] = qt
94 elif target == 'V': wV_arr[i] = raw; nV_arr[i] = nr; qV_arr[i] = qt
95 elif target == 'O': wO_arr[i] = raw; nO_arr[i] = nr; qO_arr[i] = qt
96 elif target == 'G': wG_arr[i] = raw; nG_arr[i] = nr; qG_arr[i] = qt
97 elif target == 'U': wU_arr[i] = raw; nU_arr[i] = nr; qU_arr[i] = qt
98 elif target == 'D': wD_arr[i] = raw; nD_arr[i] = nr; qD_arr[i] = qt
99 wAN_arr[i] = lw.attn_norm_w.ctypes.data_as(cv)
100 wFN_arr[i] = lw.ffn_norm_w.ctypes.data_as(cv)
101
102# MoE pointers
103w_gate_inp_arr = [0]*L; w_gate_exps_arr = [0]*L; w_up_exps_arr = [0]*L; w_down_exps_arr = [0]*L
104for i, lw in enumerate(e._layers):
105 if e.is_moe:
106 me = e._moe_layers[i]
107 if me.router_raw is not None:
108 w_gate_inp_arr[i] = me.router_raw.ctypes.data_as(cv)
109 elif me.router_f32 is not None:
110 w_gate_inp_arr[i] = me.router_f32.ctypes.data_as(cv)
111 else:
112 w_gate_inp_arr[i] = cv(0)
113 gate_raw_t = me.gate_raw
114 up_raw_t = me.up_raw
115 down_raw_t = me.down_raw
116 if gate_raw_t and len(gate_raw_t) > 0:
117 w_gate_exps_arr[i] = gate_raw_t[0].ctypes.data_as(cv)
118 else:
119 w_gate_exps_arr[i] = cv(0)
120 if up_raw_t and len(up_raw_t) > 0:
121 w_up_exps_arr[i] = up_raw_t[0].ctypes.data_as(cv)
122 else:
123 w_up_exps_arr[i] = cv(0)
124 if down_raw_t and len(down_raw_t) > 0:
125 w_down_exps_arr[i] = down_raw_t[0].ctypes.data_as(cv)
126 else:
127 w_down_exps_arr[i] = cv(0)
128
129bc.wQ = ctypes.cast(wa(wQ_arr), cv); bc.wK = ctypes.cast(wa(wK_arr), cv)
130bc.wV = ctypes.cast(wa(wV_arr), cv); bc.wO = ctypes.cast(wa(wO_arr), cv)
131bc.wG = ctypes.cast(wa(wG_arr), cv); bc.wU = ctypes.cast(wa(wU_arr), cv)
132bc.wD = ctypes.cast(wa(wD_arr), cv)
133bc.wAN = ctypes.cast(wa(wAN_arr), cv); bc.wFN = ctypes.cast(wa(wFN_arr), cv)
134bc.nQ = ctypes.cast(ia(nQ_arr), cv); bc.nK = ctypes.cast(ia(nK_arr), cv)
135bc.nV = ctypes.cast(ia(nV_arr), cv); bc.nO = ctypes.cast(ia(nO_arr), cv)
136bc.nG = ctypes.cast(ia(nG_arr), cv); bc.nU = ctypes.cast(ia(nU_arr), cv)
137bc.nD = ctypes.cast(ia(nD_arr), cv)
138bc.q_quant = ctypes.cast(ia(qQ_arr), cv); bc.k_quant = ctypes.cast(ia(qK_arr), cv)
139bc.v_quant = ctypes.cast(ia(qV_arr), cv); bc.o_quant = ctypes.cast(ia(qO_arr), cv)
140bc.g_quant = ctypes.cast(ia(qG_arr), cv); bc.u_quant = ctypes.cast(ia(qU_arr), cv)
141bc.d_quant = ctypes.cast(ia(qD_arr), cv)
142bc.w_gate_inp = ctypes.cast(wa(w_gate_inp_arr), cv)
143bc.w_gate_exps = ctypes.cast(wa(w_gate_exps_arr), cv)
144bc.w_up_exps = ctypes.cast(wa(w_up_exps_arr), cv)
145bc.w_down_exps = ctypes.cast(wa(w_down_exps_arr), cv)
146bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e, 'emb') else cv(0)
147bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e, '_out_norm_w') else cv(0)
148bc.wOut = ctypes.cast(e._out_raw, cv) if hasattr(e, '_out_raw') else cv(0)
149
150# RoPE table - precompute using numpy
151hd2 = HD // 2
152max_ctx = 4096
153freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD)
154ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1)
155cos_all = np.cos(ang).astype(np.float32).reshape(-1)
156sin_all = np.sin(ang).astype(np.float32).reshape(-1)
157cos_t = cos_all.ctypes.data_as(cv)
158sin_t = sin_all.ctypes.data_as(cv)
159bc.cos_table = cos_t
160bc.sin_table = sin_t
161bc.max_ctx = max_ctx
162print(f"RoPE table: {max_ctx}x{hd2}", flush=True)
163
164# ── Workspace buffers ──
165ws = np.zeros(12 * S, dtype=np.float32)
166logits_buf = np.zeros(V, dtype=np.float32)
167
168# ── KV cache ──
169kv = KVBlock()
170lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD))
171kva = (cv*1)(ctypes.cast(ctypes.pointer(kv), cv))
172bc.kv_array = ctypes.cast(kva, cv)
173bc.logits = logits_buf.ctypes.data_as(cv)
174
175# Run with all layers
176token = 785 # "The" in Qwen3 tokenizer
177print(f"\n--- Running batch_forward(token={token}) ---", flush=True)
178t0 = time.perf_counter()
179lib.batch_forward(ctypes.byref(bc), (ci*1)(token), ci(1), ws.ctypes.data_as(cv))
180elapsed = time.perf_counter() - t0
181
182logits = logits_buf[:V].copy()
183nan_count = np.isnan(logits).sum()
184inf_count = np.isinf(logits).sum()
185max_val = float(np.max(logits))
186min_val = float(np.min(logits))
187mean_val = float(np.mean(logits))
188top5 = np.argsort(logits)[-5:][::-1]
189
190print(f" Time: {elapsed*1000:.1f}ms ({1/elapsed:.1f} tok/s)", flush=True)
191print(f" Logits: nan={nan_count}/{V}, inf={inf_count}, max={max_val:.2f}, min={min_val:.2f}, mean={mean_val:.4f}", flush=True)
192print(f" Top-5 tokens: {top5.tolist()}", flush=True)
193
194# Decode top tokens
195from transformers import AutoTokenizer
196tok = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
197print(f" Top-5 decoded: {[tok.decode([t], skip_special_tokens=True) for t in top5]}", flush=True)
198
199# ── Run 5 more tokens for speed test ──
200print(f"\n--- Generating 5 more tokens ---", flush=True)
201t0 = time.perf_counter()
202for _ in range(5):
203 logits_buf[:] = 0
204 safe = np.nan_to_num(logits, nan=-1e10)
205 token = int(np.argmax(safe))
206 lib.batch_forward(ctypes.byref(bc), (ci*1)(token), ci(1), ws.ctypes.data_as(cv))
207 logits = logits_buf[:V].copy()
208elapsed = time.perf_counter() - t0
209print(f" 5 tokens: {elapsed*1000:.1f}ms ({5/elapsed:.1f} tok/s)", flush=True)