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/debug_c_vs_python.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 / debug_c_vs_python.py` 168 lines ยท 6264 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Compare C GQA attention vs Python attention with identical inputs.""" 3 import sys, os, numpy as np 4 sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') 5 6 os.environ['OMP_NUM_THREADS'] = '1' 7 os.environ['OPENBLAS_NUM_THREADS'] = '1' 8 9 from turbo_engine_v7_moe import TurboEngineV7MoE 10 11 print("Loading model...", flush=True) 12 e = TurboEngineV7MoE('/tmp/models/gpt-oss-20b-Q4_K_M.gguf', n_threads=1) 13 print("Model loaded.", flush=True) 14 15 import ctypes 16 cf = ctypes.POINTER(ctypes.c_float) 17 ci = ctypes.c_int 18 19 N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head * e.head_dim; HD = e.head_dim 20 NK = NH * HD 21 print(f"N={N}, NH={NH}, NKH={NKH}, HD={HD}") 22 23 e.reset() 24 25 # Run layer 0 manually, but save Q/K/V BEFORE attention 26 def run_layer_and_capture_qkv(layer_idx): 27 """Run layer up to GQA attention and return (q_rope, k_rope, v, kv_k, kv_v, kv_len, b_r).""" 28 lw = e._layers[layer_idx] 29 b_x = e._x; b_r = e._residual; b_x_norm = e._x_norm 30 b_q = e._q; b_k = e._k; b_v = e._v 31 32 np.copyto(b_x, e.emb[42]) # token 42 33 34 b_r[:] = b_x 35 e._simd.rms_norm(e._p_x_norm, e._p_x, 36 lw.attn_norm_w.ctypes.data_as(cf), 37 N, e._eps_f) 38 39 # Fused QK 40 e._kern.quant_matmul_omp(lw.attn_qk_raw, e._p_x_norm, e._p_qk, 41 lw.attn_qk_nr, lw.attn_qk_nc, lw.attn_qk_qt) 42 e._kern.quant_matmul_omp(lw.attn_v_raw, e._p_x_norm, e._p_v, 43 lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt) 44 45 # RoPE 46 e._q[:] = e._apply_rope_fast(e._q, e.pos, NH, rope_dim=HD) 47 e._k[:] = e._apply_rope_fast(e._k, e.pos, e.n_kv_head, rope_dim=HD) 48 49 # Return copies 50 return { 51 'q': e._q.copy(), 52 'k': e._k.copy(), 53 'v': e._v.copy(), 54 'b_r': b_r.copy(), 55 } 56 57 # Step 1: Run and capture Q, K, V 58 e.reset() 59 e.pos = 0 60 print("\n=== Step 1 (pos=0) ===") 61 qkv1 = run_layer_and_capture_qkv(0) 62 63 # Store K, V in cache at position 0 64 e.kv_k[0, 0, :NKH] = qkv1['k'][:NKH] 65 e.kv_v[0, 0, :NKH] = qkv1['v'][:NKH] 66 e.kv_len[0] = 1 67 68 # Step 2: Run with different pos but DO NOT store in cache 69 e.pos = 1 70 print("\n=== Step 2 (pos=1) - fresh Q, K, V but NOT stored ===") 71 qkv2 = run_layer_and_capture_qkv(0) 72 73 # Now we have: 74 # qkv1: Q at pos=0, K at pos=0, V at pos=0 75 # qkv2: Q at pos=1, K at pos=1, V at pos=1 (but not in cache) 76 # kv_cache has position 0 only (from qkv1) 77 78 # Test 1: C attention with seq_len=1, call 1's Q 79 print("\n\n=== TEST 1: C attention seq_len=1 with qkv1's Q ===") 80 att_c_1 = np.zeros(NK, dtype=np.float32) 81 e._gqa_attn.gqa_attention_decode( 82 qkv1['q'].ctypes.data_as(cf), 83 e.kv_k[0].ctypes.data_as(cf), 84 e.kv_v[0].ctypes.data_as(cf), 85 att_c_1.ctypes.data_as(cf), 86 ci(1), ci(NH), ci(e.n_kv_head), ci(HD), 87 e._p_gqa_ws) 88 print(f"C att[:5] = {att_c_1[:5]}") 89 90 # Test 2: Python attention with seq_len=1 91 print("\n=== TEST 2: Python attention seq_len=1 with qkv1's Q ===") 92 k_cache = e.kv_k[0, :1].reshape(1, e.n_kv_head, HD) 93 v_cache = e.kv_v[0, :1].reshape(1, e.n_kv_head, HD) 94 q_2d = qkv1['q'].reshape(NH, HD) 95 nk = e.n_kv_head; gqa = e._gqa_rep 96 q_g = q_2d.reshape(nk, gqa, HD) 97 k_T = k_cache.transpose(1, 0, 2) 98 scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD)) 99 scores = scores.reshape(NH, 1) 100 scores -= np.max(scores, axis=1, keepdims=True) 101 np.exp(scores, out=scores) 102 scores /= np.sum(scores, axis=1, keepdims=True) 103 v_T = v_cache.transpose(1, 0, 2) 104 att_py_1 = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, 1), v_T).reshape(-1) 105 print(f"Py att[:5] = {att_py_1[:5]}") 106 print(f"C vs Py diff: {np.max(np.abs(att_c_1 - att_py_1)):.8f}") 107 108 # Test 3: C attention with seq_len=2, qkv2's Q (pos=1 Q), but ONLY position 0 in cache 109 print("\n\n=== TEST 3: C attention seq_len=2 with qkv2's Q (pos=1), only pos 0 in cache ===") 110 att_c_2 = np.zeros(NK, dtype=np.float32) 111 e._gqa_attn.gqa_attention_decode( 112 qkv2['q'].ctypes.data_as(cf), 113 e.kv_k[0].ctypes.data_as(cf), 114 e.kv_v[0].ctypes.data_as(cf), 115 att_c_2.ctypes.data_as(cf), 116 ci(2), ci(NH), ci(e.n_kv_head), ci(HD), 117 e._p_gqa_ws) 118 print(f"C att[:5] = {att_c_2[:5]}") 119 print(f"Diff from test 1: {np.max(np.abs(att_c_2 - att_c_1)):.8f}") 120 121 # Now add position 1 to cache (simulating normal operation) 122 e.kv_k[0, 1, :NKH] = qkv2['k'][:NKH] 123 e.kv_v[0, 1, :NKH] = qkv2['v'][:NKH] 124 e.kv_len[0] = 2 125 126 # Test 4: C attention with seq_len=2, BOTH positions in cache 127 print("\n\n=== TEST 4: C attention seq_len=2 with qkv2's Q, BOTH positions in cache ===") 128 att_c_3 = np.zeros(NK, dtype=np.float32) 129 e._gqa_attn.gqa_attention_decode( 130 qkv2['q'].ctypes.data_as(cf), 131 e.kv_k[0].ctypes.data_as(cf), 132 e.kv_v[0].ctypes.data_as(cf), 133 att_c_3.ctypes.data_as(cf), 134 ci(2), ci(NH), ci(e.n_kv_head), ci(HD), 135 e._p_gqa_ws) 136 print(f"C att[:5] = {att_c_3[:5]}") 137 print(f"Diff from test 1: {np.max(np.abs(att_c_3 - att_c_1)):.8f}") 138 print(f"Diff from test 3: {np.max(np.abs(att_c_3 - att_c_2)):.8f}") 139 140 # Test 5: Python attention with seq_len=2, BOTH positions 141 print("\n\n=== TEST 5: Python attention seq_len=2 with qkv2's Q, both positions ===") 142 k_cache2 = e.kv_k[0, :2].reshape(2, e.n_kv_head, HD) 143 v_cache2 = e.kv_v[0, :2].reshape(2, e.n_kv_head, HD) 144 q_2d2 = qkv2['q'].reshape(NH, HD) 145 q_g2 = q_2d2.reshape(nk, gqa, HD) 146 k_T2 = k_cache2.transpose(1, 0, 2) 147 scores2 = np.einsum('khd,ksd->khs', q_g2, k_T2) / np.sqrt(float(HD)) 148 scores2 = scores2.reshape(NH, 2) 149 scores2 -= np.max(scores2, axis=1, keepdims=True) 150 np.exp(scores2, out=scores2) 151 scores2 /= np.sum(scores2, axis=1, keepdims=True) 152 v_T2 = v_cache2.transpose(1, 0, 2) 153 att_py_2 = np.einsum('khs,ksd->khd', scores2.reshape(nk, gqa, 2), v_T2).reshape(-1) 154 print(f"Py att[:5] = {att_py_2[:5]}") 155 print(f"C vs Py diff (test 4 vs test 5): {np.max(np.abs(att_c_3 - att_py_2)):.8f}") 156 157 # Test 6: Use same Q (qkv1's Q) but seq_len=2 158 print("\n\n=== TEST 6: C attention seq_len=2 with qkv1's Q (pos=0), both positions in cache ===") 159 att_c_4 = np.zeros(NK, dtype=np.float32) 160 e._gqa_attn.gqa_attention_decode( 161 qkv1['q'].ctypes.data_as(cf), 162 e.kv_k[0].ctypes.data_as(cf), 163 e.kv_v[0].ctypes.data_as(cf), 164 att_c_4.ctypes.data_as(cf), 165 ci(2), ci(NH), ci(e.n_kv_head), ci(HD), 166 e._p_gqa_ws) 167 print(f"C att[:5] = {att_c_4[:5]}") 168 print(f"Diff from test 1 (same Q, seq_len=1): {np.max(np.abs(att_c_4 - att_c_1)):.8f}")