interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

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."""
3import sys, os, numpy as np
4sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels')
5
6os.environ['OMP_NUM_THREADS'] = '1'
7os.environ['OPENBLAS_NUM_THREADS'] = '1'
8
9from turbo_engine_v7_moe import TurboEngineV7MoE
10
11print("Loading model...", flush=True)
12e = TurboEngineV7MoE('/tmp/models/gpt-oss-20b-Q4_K_M.gguf', n_threads=1)
13print("Model loaded.", flush=True)
14
15import ctypes
16cf = ctypes.POINTER(ctypes.c_float)
17ci = ctypes.c_int
18
19N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head * e.head_dim; HD = e.head_dim
20NK = NH * HD
21print(f"N={N}, NH={NH}, NKH={NKH}, HD={HD}")
22
23e.reset()
24
25# Run layer 0 manually, but save Q/K/V BEFORE attention
26def 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
58e.reset()
59e.pos = 0
60print("\n=== Step 1 (pos=0) ===")
61qkv1 = run_layer_and_capture_qkv(0)
62
63# Store K, V in cache at position 0
64e.kv_k[0, 0, :NKH] = qkv1['k'][:NKH]
65e.kv_v[0, 0, :NKH] = qkv1['v'][:NKH]
66e.kv_len[0] = 1
67
68# Step 2: Run with different pos but DO NOT store in cache
69e.pos = 1
70print("\n=== Step 2 (pos=1) - fresh Q, K, V but NOT stored ===")
71qkv2 = 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
79print("\n\n=== TEST 1: C attention seq_len=1 with qkv1's Q ===")
80att_c_1 = np.zeros(NK, dtype=np.float32)
81e._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)
88print(f"C att[:5] = {att_c_1[:5]}")
89
90# Test 2: Python attention with seq_len=1
91print("\n=== TEST 2: Python attention seq_len=1 with qkv1's Q ===")
92k_cache = e.kv_k[0, :1].reshape(1, e.n_kv_head, HD)
93v_cache = e.kv_v[0, :1].reshape(1, e.n_kv_head, HD)
94q_2d = qkv1['q'].reshape(NH, HD)
95nk = e.n_kv_head; gqa = e._gqa_rep
96q_g = q_2d.reshape(nk, gqa, HD)
97k_T = k_cache.transpose(1, 0, 2)
98scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD))
99scores = scores.reshape(NH, 1)
100scores -= np.max(scores, axis=1, keepdims=True)
101np.exp(scores, out=scores)
102scores /= np.sum(scores, axis=1, keepdims=True)
103v_T = v_cache.transpose(1, 0, 2)
104att_py_1 = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, 1), v_T).reshape(-1)
105print(f"Py att[:5] = {att_py_1[:5]}")
106print(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
109print("\n\n=== TEST 3: C attention seq_len=2 with qkv2's Q (pos=1), only pos 0 in cache ===")
110att_c_2 = np.zeros(NK, dtype=np.float32)
111e._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)
118print(f"C att[:5] = {att_c_2[:5]}")
119print(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)
122e.kv_k[0, 1, :NKH] = qkv2['k'][:NKH]
123e.kv_v[0, 1, :NKH] = qkv2['v'][:NKH]
124e.kv_len[0] = 2
125
126# Test 4: C attention with seq_len=2, BOTH positions in cache
127print("\n\n=== TEST 4: C attention seq_len=2 with qkv2's Q, BOTH positions in cache ===")
128att_c_3 = np.zeros(NK, dtype=np.float32)
129e._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)
136print(f"C att[:5] = {att_c_3[:5]}")
137print(f"Diff from test 1: {np.max(np.abs(att_c_3 - att_c_1)):.8f}")
138print(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
141print("\n\n=== TEST 5: Python attention seq_len=2 with qkv2's Q, both positions ===")
142k_cache2 = e.kv_k[0, :2].reshape(2, e.n_kv_head, HD)
143v_cache2 = e.kv_v[0, :2].reshape(2, e.n_kv_head, HD)
144q_2d2 = qkv2['q'].reshape(NH, HD)
145q_g2 = q_2d2.reshape(nk, gqa, HD)
146k_T2 = k_cache2.transpose(1, 0, 2)
147scores2 = np.einsum('khd,ksd->khs', q_g2, k_T2) / np.sqrt(float(HD))
148scores2 = scores2.reshape(NH, 2)
149scores2 -= np.max(scores2, axis=1, keepdims=True)
150np.exp(scores2, out=scores2)
151scores2 /= np.sum(scores2, axis=1, keepdims=True)
152v_T2 = v_cache2.transpose(1, 0, 2)
153att_py_2 = np.einsum('khs,ksd->khd', scores2.reshape(nk, gqa, 2), v_T2).reshape(-1)
154print(f"Py att[:5] = {att_py_2[:5]}")
155print(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
158print("\n\n=== TEST 6: C attention seq_len=2 with qkv1's Q (pos=0), both positions in cache ===")
159att_c_4 = np.zeros(NK, dtype=np.float32)
160e._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)
167print(f"C att[:5] = {att_c_4[:5]}")
168print(f"Diff from test 1 (same Q, seq_len=1): {np.max(np.abs(att_c_4 - att_c_1)):.8f}")