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_diff_tokens.py

149 lines · 5548 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Critical test: compare attention with different-token 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
21nk = e.n_kv_head
22gqa = e._gqa_rep
23
24def compute_qkv(engine, token_id, pos):
25 """Compute Q, K, V for one layer."""
26 e._x[:] = e.emb[token_id]
27 lw = e._layers[0]
28
29 b_r = e._residual
30 b_r[:] = e._x
31
32 e._simd.rms_norm(e._p_x_norm, e._p_x,
33 lw.attn_norm_w.ctypes.data_as(cf),
34 N, e._eps_f)
35
36 # Fused QK
37 e._kern.quant_matmul_omp(lw.attn_qk_raw, e._p_x_norm, e._p_qk,
38 lw.attn_qk_nr, lw.attn_qk_nc, lw.attn_qk_qt)
39 e._kern.quant_matmul_omp(lw.attn_v_raw, e._p_x_norm, e._p_v,
40 lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt)
41
42 # RoPE
43 orig_pos = e.pos
44 e.pos = pos
45 e._q[:] = e._apply_rope_fast(e._q, pos, NH, rope_dim=HD)
46 e._k[:] = e._apply_rope_fast(e._k, pos, nk, rope_dim=HD)
47 e.pos = orig_pos
48
49 return {
50 'q': e._q.copy(),
51 'k': e._k.copy(),
52 'v': e._v.copy(),
53 }
54
55# Compute QKV for token 42 at pos 0
56qkv42_0 = compute_qkv(e, 42, 0)
57print(f"Token 42 V[:5] = {qkv42_0['v'][:5]}")
58
59# Compute QKV for token 99 at pos 1
60qkv99_1 = compute_qkv(e, 99, 1)
61print(f"Token 99 V[:5] = {qkv99_1['v'][:5]}")
62
63# Compute QKV for token 99 at pos 0 (for baseline comparison)
64qkv99_0 = compute_qkv(e, 99, 0)
65print(f"Token 99 (pos0) V[:5] = {qkv99_0['v'][:5]}")
66
67# Are V values different for different tokens?
68print(f"\nV42 vs V99 max diff: {np.max(np.abs(qkv42_0['v'] - qkv99_1['v'])):.6f}")
69print(f"V99 pos0 vs pos1 max diff: {np.max(np.abs(qkv99_0['v'] - qkv99_1['v'])):.6f}")
70
71# Now test C attention with DIFFERENT tokens at different positions
72cache_k = np.zeros((4096, NKH), dtype=np.float32)
73cache_v = np.zeros((4096, NKH), dtype=np.float32)
74
75# Fill position 0 with token 42 K,V
76cache_k[0, :NKH] = qkv42_0['k'][:NKH]
77cache_v[0, :NKH] = qkv42_0['v'][:NKH]
78
79# Fill position 1 with token 99 K,V
80cache_k[1, :NKH] = qkv99_1['k'][:NKH]
81cache_v[1, :NKH] = qkv99_1['v'][:NKH]
82
83# Python attention with seq_len=2, Q from token 99 at pos 1
84def python_attention(q, k_cache, v_cache, seq_len):
85 k_3d = k_cache[:seq_len].reshape(seq_len, nk, HD)
86 v_3d = v_cache[:seq_len].reshape(seq_len, nk, HD)
87 q_2d = q.reshape(NH, HD)
88 q_g = q_2d.reshape(nk, gqa, HD)
89 k_T = k_3d.transpose(1, 0, 2)
90 scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD))
91 scores = scores.reshape(NH, seq_len)
92 scores -= np.max(scores, axis=1, keepdims=True)
93 np.exp(scores, out=scores)
94 scores /= np.sum(scores, axis=1, keepdims=True)
95 v_T = v_3d.transpose(1, 0, 2)
96 att = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, seq_len), v_T)
97 return att.reshape(-1)
98
99# C attention
100def c_attention(q, k_cache, v_cache, seq_len):
101 att = np.zeros(NK, dtype=np.float32)
102 e._gqa_attn.gqa_attention_decode(
103 q.ctypes.data_as(cf),
104 k_cache.ctypes.data_as(cf),
105 v_cache.ctypes.data_as(cf),
106 att.ctypes.data_as(cf),
107 ci(seq_len), ci(NH), ci(nk), ci(HD),
108 e._p_gqa_ws)
109 return att
110
111# Test: Q from token 99 at pos 1, cache has token 42 at pos 0, token 99 at pos 1
112print("\n\n=== Test: seq_len=2, different tokens at different positions ===")
113py_att = python_attention(qkv99_1['q'], cache_k, cache_v, 2)
114c_att = c_attention(qkv99_1['q'], cache_k, cache_v, 2)
115print(f"Py att[:5] = {py_att[:5]}")
116print(f"C att[:5] = {c_att[:5]}")
117print(f"Py vs C diff: {np.max(np.abs(py_att - c_att)):.8f}")
118
119# Compare with attending to only pos 0 (token 42) or only pos 1 (token 99)
120py_att_pos0 = python_attention(qkv99_1['q'], cache_k[:1], cache_v[:1], 1)
121py_att_pos1 = python_attention(qkv99_1['q'], cache_k[1:2], cache_v[1:2], 1)
122print(f"\nPy att only pos0 (token 42)[:5] = {py_att_pos0[:5]}")
123print(f"Py att only pos1 (token 99)[:5] = {py_att_pos1[:5]}")
124print(f"Are they different? {np.max(np.abs(py_att_pos0 - py_att_pos1)):.6f}")
125print(f"Seq=2 vs only pos1 diff: {np.max(np.abs(py_att - py_att_pos1)):.8f}")
126print(f"Seq=2 vs only pos0 diff: {np.max(np.abs(py_att - py_att_pos0)):.8f}")
127
128# NOW: Full model test with different tokens
129print("\n\n=== Full model test: token 42 then token 99 ===")
130e.reset()
131l1 = e.forward(42).copy()
132l2 = e.forward(99).copy()
133print(f"Step 1 (token 42) logits[:5] = {l1[:5]}")
134print(f"Step 2 (token 99) logits[:5] = {l2[:5]}")
135print(f"Diff: {np.max(np.abs(l1 - l2)):.6f}")
136
137# Reset and do token 99 alone
138print("\n=== Baseline: token 99 alone (no context) ===")
139e.reset()
140l99_alone = e.forward(99).copy()
141print(f"Token 99 alone logits[:5] = {l99_alone[:5]}")
142
143# Compare: step 2 with token 99 vs token 99 alone
144print(f"\nToken 99 step 2 vs token 99 alone diff: {np.max(np.abs(l2 - l99_alone)):.6f}")
145
146# This is the key test: does step 2 output with different token depend on KV cache?
147# If diff > 0, the attention is correctly using the cache
148print("\n=== Is the KV cache being used? ===")
149print(f"Token 99 step 2 (with 42 in cache) != token 99 alone: {np.max(np.abs(l2 - l99_alone)) > 0.001}")