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