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

99 lines · 4131 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Check workspace buffer overflow and other potential issues."""
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
15N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head * e.head_dim; HD = e.head_dim
16gqa_rep = NH // e.n_kv_head
17
18print(f"\nModel dimensions:", flush=True)
19print(f" N={N}, NH={NH}, NKH={NKH}, HD={HD}, gqa_rep={gqa_rep}", flush=True)
20
21# Check workspace size
22ws_size = e._gqa_ws_size
23print(f"\nWorkspace allocated: {ws_size} floats ({ws_size * 4 / 1024:.0f} KB)", flush=True)
24print(f" For seq_len=4096: needs NH*seq_len + gqa_rep*seq_len = {NH*4096 + gqa_rep*4096}", flush=True)
25if ws_size < NH * 4096 + gqa_rep * 4096:
26 print(f" *** WORKSPACE OVERFLOW for seq_len=4096! Missing {(NH + gqa_rep)*4096 - ws_size} floats", flush=True)
27else:
28 print(f" Workspace OK for seq_len=4096", flush=True)
29
30# Check: does _p_gqa_ws point to the right place?
31print(f"\n_gqa_workspace addr: {e._gqa_workspace.ctypes.data}", flush=True)
32print(f"_p_gqa_ws addr: {e._p_gqa_ws}", flush=True)
33
34# Check batch_forward path — is there a bug there?
35print(f"\nChecking batch forward availability:", flush=True)
36print(f" _c_batch_ready: {getattr(e, '_c_batch_ready', 'N/A')}", flush=True)
37print(f" Has batch forward: {hasattr(e, 'forward_c_batch')}", flush=True)
38
39# Check if there's a forward_c_batch for gpt-oss
40if hasattr(e, '_kern') and e._kern is not None:
41 for attr in dir(e._kern):
42 if 'batch' in attr.lower() or 'forward' in attr.lower():
43 print(f" C function: {attr}", flush=True)
44
45# Check if pos is correctly handled
46print(f"\npos = {e.pos}", flush=True)
47
48# CRITICAL TEST: monkey-patch to check the actual seq_len passed to GQA
49import ctypes
50cf = ctypes.POINTER(ctypes.c_float)
51ci = ctypes.c_int
52
53original_gqa = e._gqa_attn.gqa_attention_decode
54
55call_count = [0]
56def traced_gqa(q, k, v, out, seq_len, n_head, n_kv_head, head_dim, ws):
57 call_count[0] += 1
58 print(f" GQA call {call_count[0]}: seq_len={seq_len}, n_head={n_head}, n_kv_head={n_kv_head}, head_dim={head_dim}", flush=True)
59 return original_gqa(q, k, v, out, seq_len, n_head, n_kv_head, head_dim, ws)
60
61e._gqa_attn.gqa_attention_decode = traced_gqa
62
63# Now do 2 forward calls
64e.reset()
65print(f"\n=== Forward call 1 (token 42) ===", flush=True)
66l1 = e.forward(42).copy()
67print(f"pos after call 1: {e.pos}", flush=True)
68
69print(f"\n=== Forward call 2 (token 99) ===", flush=True)
70l2 = e.forward(99).copy()
71print(f"pos after call 2: {e.pos}", flush=True)
72
73print(f"\n=== Forward call 3 (token 42) ===", flush=True)
74l3 = e.forward(42).copy()
75print(f"pos after call 3: {e.pos}", flush=True)
76
77# Check: is l2 (token 99 with context) different from just token 99 with no context?
78e.reset()
79l99_alone = e.forward(99).copy()
80print(f"\nToken 99 alone vs with context (token 42 then 99): {np.max(np.abs(l2 - l99_alone)):.6f}")
81
82# Check: is l3 (token 42 with 42 and 99 in cache) different from l1 (token 42 alone)?
83print(f"Token 42 alone vs with 2 tokens context: {np.max(np.abs(l3 - l1)):.6f}")
84
85# The KEY question: is the output on step 3 different from step 1?
86# If V values for token 42 are the same at all positions (which they are for the same layer input),
87# then the attention output would be the same, and the hidden state propagation would make
88# everything identical.
89#
90# BUT! After step 2 with token 99, the hidden state at step 3 should be DIFFERENT from
91# the hidden state at step 1 (because step 2's output was different, affecting subsequent layers).
92#
93# So: step 3 output should be different from step 1!
94
95print(f"\nCRITICAL: Is step 3 (token 42 after token 99) different from step 1 (token 42 alone)?")
96print(f" Step 1 logits[:5] = {l1[:5]}")
97print(f" Step 3 logits[:5] = {l3[:5]}")
98print(f" Diff = {np.max(np.abs(l3 - l1)):.6f}")
99print(f" Different? {np.max(np.abs(l3 - l1)) > 0.001}")