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/q4k_compare.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 / q4k_compare.py` 170 lines ยท 9013 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Compare C engine vs numpy reference per-layer for ONE layer. 3 Only dequantizes ONE layer's weights for speed.""" 4 import sys, os, time, ctypes, numpy as np 5 os.environ['OMP_NUM_THREADS'] = '32' 6 sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') 7 from turbo_engine_v7_moe import TurboEngineV7MoE 8 9 e = TurboEngineV7MoE('/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf', 32) 10 lib = ctypes.CDLL('/onedev-workspace/work/src/mojollama/kernels/cengine_batch_instr.so') 11 cv, ci = ctypes.c_void_p, ctypes.c_int 12 L, N, NH, NKH, HD, FF, V = e.n_layers, e.n_embd, e.n_head, e.n_kv_head, e.head_dim, e.n_ff, e.vocab_size 13 S = max(N, NH*HD, FF, NKH*HD, e.n_ff_expert) 14 15 class BC(ctypes.Structure): 16 _fields_=[('L',ci),('N',ci),('NH',ci),('NKH',ci),('HD',ci),('FF',ci),('V',ci),('eps',ctypes.c_float), 17 ('wQ',cv),('wK',cv),('wV',cv),('wO',cv),('wG',cv),('wU',cv),('wD',cv), 18 ('wAN',cv),('wFN',cv),('nQ',cv),('nK',cv),('nV',cv),('nO',cv),('nG',cv),('nU',cv),('nD',cv), 19 ('nc',ci),('emb',cv),('onw',cv),('wOut',cv),('outNR',ci),('outNC',ci),('outQuant',ci), 20 ('kv_array',cv),('logits',cv),('n_experts',ci),('n_experts_per_tok',ci),('moe_intermediate',ci), 21 ('w_gate_inp',cv),('w_gate_exps',cv),('w_up_exps',cv),('w_down_exps',cv), 22 ('gate_exp_quant',ci),('up_exp_quant',ci),('down_exp_quant',ci), 23 ('q_quant',cv),('k_quant',cv),('v_quant',cv),('o_quant',cv), 24 ('g_quant',cv),('u_quant',cv),('d_quant',cv),('emb_quant',ci), 25 ('cos_table',cv),('sin_table',cv),('max_ctx',ci), 26 ('workspace',cv),('ws_size',ci)] 27 class KVBlock(ctypes.Structure): 28 _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64),('block_map',(ci*1024)*64)] 29 lib.batch_forward.argtypes=[cv,cv,ci,cv];lib.batch_forward.restype=None 30 lib.kv_init.argtypes=[cv,ci,ci,ci];lib.kv_init.restype=None 31 lib.q4_k_batch_matmul.argtypes=[cv,cv,cv,ci,ci,ci];lib.q4_k_batch_matmul.restype=None 32 33 # Build BC 34 def wa(a): return (cv*L)(*[ctypes.cast(t, cv) for t in a]) 35 def ia(a): return (ci*L)(*[int(t) for t in a]) 36 37 bc = BC() 38 for a, v in [('L', L), ('N', N), ('NH', NH), ('NKH', NKH), ('HD', HD), ('FF', FF), ('V', V), 39 ('eps', e.eps), ('nc', N), ('outNR', V), ('outNC', N), ('outQuant', 8), 40 ('n_experts', e.n_experts), ('n_experts_per_tok', e.n_experts_per_tok), 41 ('moe_intermediate', e.n_ff_expert), ('gate_exp_quant', 12), ('up_exp_quant', 12), 42 ('down_exp_quant', 14), ('emb_quant', 0)]: 43 setattr(bc, a, v) 44 45 wQ,wK,wV,wO,wG,wU,wD,wAN,wFN=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L 46 nQ,nK,nV,nO,nG,nU,nD=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L 47 qQ,qK,qV,qO,qG,qU,qD=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L 48 for i,lw in enumerate(e._layers): 49 wQ[i]=lw.attn_q_raw;nQ[i]=lw.attn_q_nr.value;qQ[i]=lw.attn_q_qt.value 50 wK[i]=lw.attn_k_raw;nK[i]=lw.attn_k_nr.value;qK[i]=lw.attn_k_qt.value 51 wV[i]=lw.attn_v_raw;nV[i]=lw.attn_v_nr.value;qV[i]=lw.attn_v_qt.value 52 wO[i]=lw.attn_out_raw;nO[i]=lw.attn_out_nr.value;qO[i]=lw.attn_out_qt.value 53 wAN[i]=lw.attn_norm_w.ctypes.data_as(cv);wFN[i]=lw.ffn_norm_w.ctypes.data_as(cv) 54 for i,me2 in enumerate(e._moe_layers): 55 wG[i]=me2.gate_raw[0].ctypes.data_as(cv);nG[i]=me2.gate_nr.value;qG[i]=12 # Q4_K 56 wU[i]=me2.up_raw[0].ctypes.data_as(cv);nU[i]=me2.up_nr.value;qU[i]=12 # Q4_K 57 wD[i]=me2.down_raw[0].ctypes.data_as(cv);nD[i]=me2.down_nr.value;qD[i]=14 # Q6_K 58 59 w_gi,w_ge,w_ue,w_de=[0]*L,[0]*L,[0]*L,[0]*L 60 for i in range(L): 61 me2=e._moe_layers[i] 62 w_gi[i]=me2.router_f32.ctypes.data_as(cv)if me2.router_f32 is not None else cv(0) 63 if me2.gate_raw and len(me2.gate_raw):w_ge[i]=me2.gate_raw[0].ctypes.data_as(cv) 64 if me2.up_raw and len(me2.up_raw):w_ue[i]=me2.up_raw[0].ctypes.data_as(cv) 65 if me2.down_raw and len(me2.down_raw):w_de[i]=me2.down_raw[0].ctypes.data_as(cv) 66 67 bc.wQ=ctypes.cast(wa(wQ),cv);bc.wK=ctypes.cast(wa(wK),cv);bc.wV=ctypes.cast(wa(wV),cv);bc.wO=ctypes.cast(wa(wO),cv) 68 bc.wG=ctypes.cast(wa(wG),cv);bc.wU=ctypes.cast(wa(wU),cv);bc.wD=ctypes.cast(wa(wD),cv) 69 bc.wAN=ctypes.cast(wa(wAN),cv);bc.wFN=ctypes.cast(wa(wFN),cv) 70 bc.nQ=ctypes.cast(ia(nQ),cv);bc.nK=ctypes.cast(ia(nK),cv);bc.nV=ctypes.cast(ia(nV),cv);bc.nO=ctypes.cast(ia(nO),cv) 71 bc.nG=ctypes.cast(ia(nG),cv);bc.nU=ctypes.cast(ia(nU),cv);bc.nD=ctypes.cast(ia(nD),cv) 72 bc.q_quant=ctypes.cast(ia(qQ),cv);bc.k_quant=ctypes.cast(ia(qK),cv);bc.v_quant=ctypes.cast(ia(qV),cv);bc.o_quant=ctypes.cast(ia(qO),cv) 73 bc.g_quant=ctypes.cast(ia(qG),cv);bc.u_quant=ctypes.cast(ia(qU),cv);bc.d_quant=ctypes.cast(ia(qD),cv) 74 bc.w_gate_inp=ctypes.cast(wa(w_gi),cv);bc.w_gate_exps=ctypes.cast(wa(w_ge),cv) 75 bc.w_up_exps=ctypes.cast(wa(w_ue),cv);bc.w_down_exps=ctypes.cast(wa(w_de),cv) 76 bc.emb=e.emb.ctypes.data_as(cv);bc.onw=e._out_norm_w.ctypes.data_as(cv);bc.wOut=ctypes.cast(e._out_raw,cv) 77 mc=4096;hd2=HD//2 78 freq_v=e.rope_freq_base**(np.arange(0,HD,2,dtype=np.float32)/HD) 79 ang=np.arange(mc,dtype=np.float32).reshape(-1,1)/freq_v.reshape(1,-1) 80 ct=np.cos(ang).astype(np.float32).reshape(-1);st=np.sin(ang).astype(np.float32).reshape(-1) 81 bc.cos_table=ct.ctypes.data_as(cv);bc.sin_table=st.ctypes.data_as(cv);bc.max_ctx=mc 82 83 ws=np.zeros(12*S,dtype=np.float32);lb=np.zeros(V,dtype=np.float32) 84 kv=KVBlock();lib.kv_init(ctypes.byref(kv),ci(L),ci(NKH),ci(HD)) 85 kva=(cv*1)(ctypes.cast(ctypes.pointer(kv),cv)) 86 bc.kv_array=ctypes.cast(kva,cv);bc.logits=lb.ctypes.data_as(cv) 87 88 # Run 1 layer at a time and capture intermediate outputs 89 print('Running C engine layer by layer, capturing outputs...', flush=True) 90 for target_layer in [1, 4]: # check layers 1 and 4 91 # Reset 92 ws2 = np.zeros(12*S, dtype=np.float32) 93 lb2 = np.zeros(V, dtype=np.float32) 94 kv2 = KVBlock(); lib.kv_init(ctypes.byref(kv2), ci(L), ci(NKH), ci(HD)) 95 bc2 = BC(); 96 for a in BC._fields_: setattr(bc2, a[0], getattr(bc, a[0])) 97 bc2.kv_array = ctypes.cast((cv*1)(ctypes.cast(ctypes.pointer(kv2), cv)), cv) 98 bc2.logits = lb2.ctypes.data_as(cv) 99 bc2.L = target_layer 100 101 lib.batch_forward(ctypes.byref(bc2), (ci*1)(785), ci(1), ws2.ctypes.data_as(cv)) 102 103 # The workspace after the last layer has the hidden state in ws2[:N] 104 h = ws2[:N].copy() 105 nan_c = np.isnan(h).sum() 106 max_v = np.max(np.abs(h)) 107 print(f' L={target_layer}: x NaN={nan_c}/{N} max_abs={max_v:.4f}', flush=True) 108 109 # Now extract the intermediate xn (RMS-normed hidden state) for layer 0 110 # and test with Q4_K matmul + compare to dequantized FP32 reference 111 print('\n--- Q4_K numerical verification ---', flush=True) 112 import gguf 113 114 # For layer 0: dequantize gate weights to FP32 using gguf reference 115 for t in e.reader.tensors: 116 if t.name == 'blk.0.ffn_gate_exps.weight': 117 f32_ref = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) 118 sh = t.shape # [2048, 768, 128] 119 f32_ref = f32_ref.reshape(int(sh[2]), int(sh[1]), int(sh[0])) 120 # Expert 50 (router-selected) 121 expert_50_ref = np.ascontiguousarray(f32_ref[50]) # [768, 2048] 122 expert_106_ref = np.ascontiguousarray(f32_ref[106]) 123 break 124 125 # Run layer 0 with workspace and extract xn 126 ws3 = np.zeros(12*S, dtype=np.float32) 127 lb3 = np.zeros(V, dtype=np.float32) 128 kv3 = KVBlock(); lib.kv_init(ctypes.byref(kv3), ci(1), ci(NKH), ci(HD)) 129 bc3 = BC() 130 for a in BC._fields_: setattr(bc3, a[0], getattr(bc, a[0])) 131 bc3.L = 1 132 bc3.kv_array = ctypes.cast((cv*1)(ctypes.cast(ctypes.pointer(kv3), cv)), cv) 133 bc3.logits = lb3.ctypes.data_as(cv) 134 135 lib.batch_forward(ctypes.byref(bc3), (ci*1)(785), ci(1), ws3.ctypes.data_as(cv)) 136 137 # Extract xn from workspace (after RMS norm and QKV, but before MoE FFN) 138 xn_ref = ws3[:N].copy() 139 print(f'xn from ws: NaN={np.isnan(xn_ref).sum()}/{N} range=[{xn_ref.min():.4f}, {xn_ref.max():.4f}]', flush=True) 140 141 # Compare C Q4_K matmul output vs numpy FP32 reference 142 M = e._moe_layers[0].gate_nr.value 143 base_addr = e._moe_layers[0].gate_raw[0].ctypes.data 144 stride = M * (N // 256) * 144 145 146 for e_idx, name in [(50, 'Expert 50'), (106, 'Expert 106')]: 147 ptr = ctypes.cast(base_addr + e_idx * stride, cv) 148 out_c = np.zeros(M, dtype=np.float32) 149 lib.q4_k_batch_matmul(ptr, xn_ref.ctypes.data_as(cv), out_c.ctypes.data_as(cv), ci(M), ci(N), ci(1)) 150 151 # Numpy FP32 reference 152 w_ref = f32_ref[0] if name == 'Expert 50' else f32_ref[106] if name == 'Expert 106' else None 153 if name == 'Expert 50': 154 w_ref = expert_50_ref 155 else: 156 w_ref = expert_106_ref 157 out_np = w_ref @ xn_ref # [768] = [768, 2048] @ [2048] 158 159 diff = np.abs(out_c - out_np) 160 mae = diff.mean() 161 max_err = diff.max() 162 std_err = diff.std() 163 rel_err = diff / (np.abs(out_np) + 1e-10) 164 mre = rel_err.mean() 165 166 print(f' {name}: MAE={mae:.6f} MAX={max_err:.6f} MRE={mre:.4f}', flush=True) 167 print(f' C output: [{out_c[:5].tolist()}]', flush=True) 168 print(f' NP output: [{out_np[:5].tolist()}]', flush=True) 169 print(f' Differences: [{diff[:5].tolist()}]', flush=True) 170 print(f' C NaN={np.isnan(out_c).sum()} NP NaN={np.isnan(out_np).sum()}', flush=True)