MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / tests / test_forward_standalone.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Standalone MoE engine test — loads model, runs 1 forward step, prints logits.""" |
| 3 | import signal, faulthandler, sys, os, time, ctypes, json |
| 4 | faulthandler.enable() |
| 5 | # Also register a signal handler for SIGSEGV |
| 6 | def 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) |
| 11 | signal.signal(signal.SIGSEGV, debug_segfault) |
| 12 | import numpy as np |
| 13 | |
| 14 | sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') |
| 15 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 16 | |
| 17 | MODEL = sys.argv[1] if len(sys.argv) > 1 else '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf' |
| 18 | TOKENIZER_PATH = '/tmp/qwen3-tokenizer/' |
| 19 | |
| 20 | # ── Load engine ── |
| 21 | t0 = time.perf_counter() |
| 22 | e = TurboEngineV7MoE(MODEL, 32) |
| 23 | L = e.n_layers; N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head |
| 24 | HD = e.head_dim; FF = e.n_ff; V = e.vocab_size; eps = e.eps |
| 25 | NE = e.n_experts; NK = e.n_experts_per_tok |
| 26 | moe_int = e.n_ff_expert if hasattr(e, 'n_ff_expert') else FF |
| 27 | S = max(N, NH*HD, FF, NKH*HD, moe_int) |
| 28 | print(f"Loaded: {L}L/{N}D/{FF}FF/{NH}H/{NKH}KV | MoE {NE}x{NK} | V={V} | S={S}", flush=True) |
| 29 | print(f"Load time: {time.perf_counter()-t0:.1f}s", flush=True) |
| 30 | |
| 31 | # ── Build BC struct ── |
| 32 | lib = ctypes.CDLL('/onedev-workspace/work/src/mojollama/kernels/cengine_batch.so') |
| 33 | cv = ctypes.c_void_p; ci = ctypes.c_int; cf = ctypes.c_float |
| 34 | |
| 35 | class 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 | |
| 50 | class KVBlock(ctypes.Structure): |
| 51 | _fields_ = [("k",cv),("v",cv),("n_blocks",ci),("seq_len",ci*64),("block_map",(ci*1024)*64)] |
| 52 | |
| 53 | lib.batch_forward.argtypes = [cv, cv, ci, cv]; lib.batch_forward.restype = None |
| 54 | lib.kv_init.argtypes = [cv, ci, ci, ci]; lib.kv_init.restype = None |
| 55 | |
| 56 | def wa(arr): |
| 57 | return (cv*L)(*[ctypes.cast(a, cv) for a in arr]) |
| 58 | def ia(arr): |
| 59 | return (ci*L)(*[int(a) for a in arr]) |
| 60 | |
| 61 | bc = BC() |
| 62 | for 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 |
| 70 | wQ_arr = [0]*L; wK_arr = [0]*L; wV_arr = [0]*L; wO_arr = [0]*L |
| 71 | wG_arr = [0]*L; wU_arr = [0]*L; wD_arr = [0]*L |
| 72 | wAN_arr = [0]*L; wFN_arr = [0]*L |
| 73 | nQ_arr = [0]*L; nK_arr = [0]*L; nV_arr = [0]*L; nO_arr = [0]*L |
| 74 | nG_arr = [0]*L; nU_arr = [0]*L; nD_arr = [0]*L |
| 75 | qQ_arr = [0]*L; qK_arr = [0]*L; qV_arr = [0]*L; qO_arr = [0]*L |
| 76 | qG_arr = [0]*L; qU_arr = [0]*L; qD_arr = [0]*L |
| 77 | |
| 78 | for 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 |
| 103 | w_gate_inp_arr = [0]*L; w_gate_exps_arr = [0]*L; w_up_exps_arr = [0]*L; w_down_exps_arr = [0]*L |
| 104 | for 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 | |
| 129 | bc.wQ = ctypes.cast(wa(wQ_arr), cv); bc.wK = ctypes.cast(wa(wK_arr), cv) |
| 130 | bc.wV = ctypes.cast(wa(wV_arr), cv); bc.wO = ctypes.cast(wa(wO_arr), cv) |
| 131 | bc.wG = ctypes.cast(wa(wG_arr), cv); bc.wU = ctypes.cast(wa(wU_arr), cv) |
| 132 | bc.wD = ctypes.cast(wa(wD_arr), cv) |
| 133 | bc.wAN = ctypes.cast(wa(wAN_arr), cv); bc.wFN = ctypes.cast(wa(wFN_arr), cv) |
| 134 | bc.nQ = ctypes.cast(ia(nQ_arr), cv); bc.nK = ctypes.cast(ia(nK_arr), cv) |
| 135 | bc.nV = ctypes.cast(ia(nV_arr), cv); bc.nO = ctypes.cast(ia(nO_arr), cv) |
| 136 | bc.nG = ctypes.cast(ia(nG_arr), cv); bc.nU = ctypes.cast(ia(nU_arr), cv) |
| 137 | bc.nD = ctypes.cast(ia(nD_arr), cv) |
| 138 | bc.q_quant = ctypes.cast(ia(qQ_arr), cv); bc.k_quant = ctypes.cast(ia(qK_arr), cv) |
| 139 | bc.v_quant = ctypes.cast(ia(qV_arr), cv); bc.o_quant = ctypes.cast(ia(qO_arr), cv) |
| 140 | bc.g_quant = ctypes.cast(ia(qG_arr), cv); bc.u_quant = ctypes.cast(ia(qU_arr), cv) |
| 141 | bc.d_quant = ctypes.cast(ia(qD_arr), cv) |
| 142 | bc.w_gate_inp = ctypes.cast(wa(w_gate_inp_arr), cv) |
| 143 | bc.w_gate_exps = ctypes.cast(wa(w_gate_exps_arr), cv) |
| 144 | bc.w_up_exps = ctypes.cast(wa(w_up_exps_arr), cv) |
| 145 | bc.w_down_exps = ctypes.cast(wa(w_down_exps_arr), cv) |
| 146 | bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e, 'emb') else cv(0) |
| 147 | bc.onw = e._out_norm_w.ctypes.data_as(cv) if hasattr(e, '_out_norm_w') else cv(0) |
| 148 | bc.wOut = ctypes.cast(e._out_raw, cv) if hasattr(e, '_out_raw') else cv(0) |
| 149 | |
| 150 | # RoPE table - precompute using numpy |
| 151 | hd2 = HD // 2 |
| 152 | max_ctx = 4096 |
| 153 | freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD) |
| 154 | ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1) |
| 155 | cos_all = np.cos(ang).astype(np.float32).reshape(-1) |
| 156 | sin_all = np.sin(ang).astype(np.float32).reshape(-1) |
| 157 | cos_t = cos_all.ctypes.data_as(cv) |
| 158 | sin_t = sin_all.ctypes.data_as(cv) |
| 159 | bc.cos_table = cos_t |
| 160 | bc.sin_table = sin_t |
| 161 | bc.max_ctx = max_ctx |
| 162 | print(f"RoPE table: {max_ctx}x{hd2}", flush=True) |
| 163 | |
| 164 | # ── Workspace buffers ── |
| 165 | ws = np.zeros(12 * S, dtype=np.float32) |
| 166 | logits_buf = np.zeros(V, dtype=np.float32) |
| 167 | |
| 168 | # ── KV cache ── |
| 169 | kv = KVBlock() |
| 170 | lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) |
| 171 | kva = (cv*1)(ctypes.cast(ctypes.pointer(kv), cv)) |
| 172 | bc.kv_array = ctypes.cast(kva, cv) |
| 173 | bc.logits = logits_buf.ctypes.data_as(cv) |
| 174 | |
| 175 | # Run with all layers |
| 176 | token = 785 # "The" in Qwen3 tokenizer |
| 177 | print(f"\n--- Running batch_forward(token={token}) ---", flush=True) |
| 178 | t0 = time.perf_counter() |
| 179 | lib.batch_forward(ctypes.byref(bc), (ci*1)(token), ci(1), ws.ctypes.data_as(cv)) |
| 180 | elapsed = time.perf_counter() - t0 |
| 181 | |
| 182 | logits = logits_buf[:V].copy() |
| 183 | nan_count = np.isnan(logits).sum() |
| 184 | inf_count = np.isinf(logits).sum() |
| 185 | max_val = float(np.max(logits)) |
| 186 | min_val = float(np.min(logits)) |
| 187 | mean_val = float(np.mean(logits)) |
| 188 | top5 = np.argsort(logits)[-5:][::-1] |
| 189 | |
| 190 | print(f" Time: {elapsed*1000:.1f}ms ({1/elapsed:.1f} tok/s)", flush=True) |
| 191 | print(f" Logits: nan={nan_count}/{V}, inf={inf_count}, max={max_val:.2f}, min={min_val:.2f}, mean={mean_val:.4f}", flush=True) |
| 192 | print(f" Top-5 tokens: {top5.tolist()}", flush=True) |
| 193 | |
| 194 | # Decode top tokens |
| 195 | from transformers import AutoTokenizer |
| 196 | tok = AutoTokenizer.from_pretrained(TOKENIZER_PATH) |
| 197 | print(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 ── |
| 200 | print(f"\n--- Generating 5 more tokens ---", flush=True) |
| 201 | t0 = time.perf_counter() |
| 202 | for _ 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() |
| 208 | elapsed = time.perf_counter() - t0 |
| 209 | print(f" 5 tokens: {elapsed*1000:.1f}ms ({5/elapsed:.1f} tok/s)", flush=True) |