Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/tests/test_diag.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / tests / test_diag.py` 202 lines ยท 9093 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Run with diagnostic cengine to dump expert weight data.""" 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 # Use diagnostic library 30 lib = ctypes.CDLL('/onedev-workspace/work/src/mojollama/kernels/cengine_batch_diag.so') 31 cv = ctypes.c_void_p; ci = ctypes.c_int; cf = ctypes.c_float 32 33 class BC(ctypes.Structure): 34 _fields_ = [ 35 ("L",ci),("N",ci),("NH",ci),("NKH",ci),("HD",ci),("FF",ci),("V",ci),("eps",cf), 36 ("wQ",cv),("wK",cv),("wV",cv),("wO",cv),("wG",cv),("wU",cv),("wD",cv), 37 ("wAN",cv),("wFN",cv),("nQ",cv),("nK",cv),("nV",cv),("nO",cv),("nG",cv),("nU",cv),("nD",cv), 38 ("nc",ci),("emb",cv),("onw",cv),("wOut",cv),("outNR",ci),("outNC",ci),("outQuant",ci), 39 ("kv_array",cv),("logits",cv), 40 ("n_experts",ci),("n_experts_per_tok",ci),("moe_intermediate",ci), 41 ("w_gate_inp",cv),("w_gate_exps",cv),("w_up_exps",cv),("w_down_exps",cv), 42 ("gate_exp_quant",ci),("up_exp_quant",ci),("down_exp_quant",ci), 43 ("q_quant",cv),("k_quant",cv),("v_quant",cv),("o_quant",cv), 44 ("g_quant",cv),("u_quant",cv),("d_quant",cv),("emb_quant",ci), 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 moe_layer = e._moe_layers[0] if e.is_moe else None 62 if moe_layer: 63 gate_qt = moe_layer.gate_qt.value if hasattr(moe_layer, 'gate_qt') else 2 64 up_qt = moe_layer.up_qt.value if hasattr(moe_layer, 'up_qt') else 2 65 down_qt = moe_layer.down_qt.value if hasattr(moe_layer, 'down_qt') else 2 66 else: 67 gate_qt = 2; up_qt = 2; down_qt = 2 68 69 print(f"Expert quant types from engine: gate={gate_qt} up={up_qt} down={down_qt}", flush=True) 70 71 for attr, val in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',eps), 72 ('nc',N),('outNR',V),('outNC',N),('outQuant',8), 73 ('n_experts',NE),('n_experts_per_tok',NK),('moe_intermediate',moe_int), 74 ('gate_exp_quant',gate_qt),('up_exp_quant',up_qt),('down_exp_quant',down_qt), 75 ('emb_quant',0)]: 76 setattr(bc, attr, val) 77 78 wQ_arr = [0]*L; wK_arr = [0]*L; wV_arr = [0]*L; wO_arr = [0]*L 79 wG_arr = [0]*L; wU_arr = [0]*L; wD_arr = [0]*L 80 wAN_arr = [0]*L; wFN_arr = [0]*L 81 nQ_arr = [0]*L; nK_arr = [0]*L; nV_arr = [0]*L; nO_arr = [0]*L 82 nG_arr = [0]*L; nU_arr = [0]*L; nD_arr = [0]*L 83 qQ_arr = [0]*L; qK_arr = [0]*L; qV_arr = [0]*L; qO_arr = [0]*L 84 qG_arr = [0]*L; qU_arr = [0]*L; qD_arr = [0]*L 85 86 for i, lw in enumerate(e._layers): 87 for attr, nm in [('attn_q','Q'),('attn_k','K'),('attn_v','V'),('attn_out','O'), 88 ('ffn_gate','G'),('ffn_up','U'),('ffn_down','D')]: 89 raw_attr = f'{attr}_raw' 90 if hasattr(lw, raw_attr): 91 raw = getattr(lw, raw_attr) 92 nr = getattr(lw, f'{attr}_nr').value 93 qt = getattr(lw, f'{attr}_qt').value 94 else: 95 f32 = getattr(lw, f'{attr}_f32') 96 raw = f32.ctypes.data_as(cv) if f32 is not None else cv(0) 97 nr = f32.shape[0] if f32 is not None else 0 98 qt = 0 99 target = nm 100 if target == 'Q': wQ_arr[i] = raw; nQ_arr[i] = nr; qQ_arr[i] = qt 101 elif target == 'K': wK_arr[i] = raw; nK_arr[i] = nr; qK_arr[i] = qt 102 elif target == 'V': wV_arr[i] = raw; nV_arr[i] = nr; qV_arr[i] = qt 103 elif target == 'O': wO_arr[i] = raw; nO_arr[i] = nr; qO_arr[i] = qt 104 elif target == 'G': wG_arr[i] = raw; nG_arr[i] = nr; qG_arr[i] = qt 105 elif target == 'U': wU_arr[i] = raw; nU_arr[i] = nr; qU_arr[i] = qt 106 elif target == 'D': wD_arr[i] = raw; nD_arr[i] = nr; qD_arr[i] = qt 107 wAN_arr[i] = lw.attn_norm_w.ctypes.data_as(cv) 108 wFN_arr[i] = lw.ffn_norm_w.ctypes.data_as(cv) 109 110 # MoE pointers 111 w_gate_inp_arr = [0]*L; w_gate_exps_arr = [0]*L; w_up_exps_arr = [0]*L; w_down_exps_arr = [0]*L 112 for i, lw in enumerate(e._layers): 113 if e.is_moe: 114 me = e._moe_layers[i] 115 if me.router_raw is not None: 116 w_gate_inp_arr[i] = me.router_raw.ctypes.data_as(cv) 117 elif me.router_f32 is not None: 118 w_gate_inp_arr[i] = me.router_f32.ctypes.data_as(cv) 119 else: 120 w_gate_inp_arr[i] = cv(0) 121 gate_raw_t = me.gate_raw 122 up_raw_t = me.up_raw 123 down_raw_t = me.down_raw 124 if gate_raw_t and len(gate_raw_t) > 0: 125 w_gate_exps_arr[i] = gate_raw_t[0].ctypes.data_as(cv) 126 else: 127 w_gate_exps_arr[i] = cv(0) 128 if up_raw_t and len(up_raw_t) > 0: 129 w_up_exps_arr[i] = up_raw_t[0].ctypes.data_as(cv) 130 else: 131 w_up_exps_arr[i] = cv(0) 132 if down_raw_t and len(down_raw_t) > 0: 133 w_down_exps_arr[i] = down_raw_t[0].ctypes.data_as(cv) 134 else: 135 w_down_exps_arr[i] = cv(0) 136 137 bc.wQ = ctypes.cast(wa(wQ_arr), cv); bc.wK = ctypes.cast(wa(wK_arr), cv) 138 bc.wV = ctypes.cast(wa(wV_arr), cv); bc.wO = ctypes.cast(wa(wO_arr), cv) 139 bc.wG = ctypes.cast(wa(wG_arr), cv); bc.wU = ctypes.cast(wa(wU_arr), cv) 140 bc.wD = ctypes.cast(wa(wD_arr), cv) 141 bc.wAN = ctypes.cast(wa(wAN_arr), cv); bc.wFN = ctypes.cast(wa(wFN_arr), cv) 142 bc.nQ = ctypes.cast(ia(nQ_arr), cv); bc.nK = ctypes.cast(ia(nK_arr), cv) 143 bc.nV = ctypes.cast(ia(nV_arr), cv); bc.nO = ctypes.cast(ia(nO_arr), cv) 144 bc.nG = ctypes.cast(ia(nG_arr), cv); bc.nU = ctypes.cast(ia(nU_arr), cv) 145 bc.nD = ctypes.cast(ia(nD_arr), cv) 146 bc.q_quant = ctypes.cast(ia(qQ_arr), cv); bc.k_quant = ctypes.cast(ia(qK_arr), cv) 147 bc.v_quant = ctypes.cast(ia(qV_arr), cv); bc.o_quant = ctypes.cast(ia(qO_arr), cv) 148 bc.g_quant = ctypes.cast(ia(qG_arr), cv); bc.u_quant = ctypes.cast(ia(qU_arr), cv) 149 bc.d_quant = ctypes.cast(ia(qD_arr), cv) 150 bc.w_gate_inp = ctypes.cast(wa(w_gate_inp_arr), cv) 151 bc.w_gate_exps = ctypes.cast(wa(w_gate_exps_arr), cv) 152 bc.w_up_exps = ctypes.cast(wa(w_up_exps_arr), cv) 153 bc.w_down_exps = ctypes.cast(wa(w_down_exps_arr), cv) 154 bc.emb = e.emb.ctypes.data_as(cv) if hasattr(e, 'emb') else cv(0) 155 bc.onw = e._onw.ctypes.data_as(cv) if hasattr(e, '_onw') else cv(0) 156 bc.wOut = ctypes.cast(e._or, cv) if hasattr(e, '_or') else cv(0) 157 158 hd2 = HD // 2 159 max_ctx = 4096 160 freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD) 161 ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1) 162 cos_all = np.cos(ang).astype(np.float32).reshape(-1) 163 sin_all = np.sin(ang).astype(np.float32).reshape(-1) 164 cos_t = cos_all.ctypes.data_as(cv) 165 sin_t = sin_all.ctypes.data_as(cv) 166 bc.cos_table = cos_t 167 bc.sin_table = sin_t 168 bc.max_ctx = max_ctx 169 print(f"RoPE table: {max_ctx}x{hd2}", flush=True) 170 171 ws = np.zeros(12 * S, dtype=np.float32) 172 logits_buf = np.zeros(V, dtype=np.float32) 173 174 kv = KVBlock() 175 lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) 176 kva = (cv*1)(ctypes.cast(ctypes.pointer(kv), cv)) 177 bc.kv_array = ctypes.cast(kva, cv) 178 bc.logits = logits_buf.ctypes.data_as(cv) 179 180 token = 785 181 print(f"\n--- Running batch_forward(token={token}) ---", flush=True) 182 sys.stdout.flush() 183 sys.stderr.flush() 184 t0 = time.perf_counter() 185 lib.batch_forward(ctypes.byref(bc), (ci*1)(token), ci(1), ws.ctypes.data_as(cv)) 186 elapsed = time.perf_counter() - t0 187 188 logits = logits_buf[:V].copy() 189 nan_count = np.isnan(logits).sum() 190 inf_count = np.isinf(logits).sum() 191 max_val = float(np.max(logits)) 192 min_val = float(np.min(logits)) 193 mean_val = float(np.mean(logits)) 194 top5 = np.argsort(logits)[-5:][::-1] 195 196 print(f" Time: {elapsed*1000:.1f}ms ({1/elapsed:.1f} tok/s)", flush=True) 197 print(f" Logits: nan={nan_count}/{V}, inf={inf_count}, max={max_val:.2f}, min={min_val:.2f}, mean={mean_val:.4f}", flush=True) 198 print(f" Top-5 tokens: {top5.tolist()}", flush=True) 199 200 from transformers import AutoTokenizer 201 tok = AutoTokenizer.from_pretrained(TOKENIZER_PATH) 202 print(f" Top-5 decoded: {[tok.decode([t], skip_special_tokens=True) for t in top5]}", flush=True)