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 / src / mojollama / numpy_reference.py

195 lines · 7031 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Pure numpy inference on Qwen3-30B-A3B for correctness validation.
3Uses gguf.dequantize for all weights. Slow but mathematically exact."""
4import sys, os, time, numpy as np
5os.environ['OMP_NUM_THREADS'] = '32'
6sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels')
7import gguf
8from gguf.constants import GGMLQuantizationType as QT
9from transformers import AutoTokenizer
10
11MODEL = sys.argv[1] if len(sys.argv) > 1 else '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf'
12TOKENIZER_PATH = '/tmp/qwen3-tokenizer/'
13
14t0 = time.perf_counter()
15reader = gguf.GGUFReader(MODEL)
16r = reader
17tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
18
19# Architecture
20arch = 'qwen3moe'
21def get_field(name):
22 for k, v in r.fields.items():
23 if k == name:
24 p = v.parts if hasattr(v, 'parts') else []
25 if len(p) >= 1:
26 d = p[-1]
27 if hasattr(d, '__iter__'):
28 return int(d) if len(d) == 1 else float(d[0]) if hasattr(d[0], '__float__') else d
29 return int(d) if hasattr(d, '__int__') else float(d)
30 return None
31
32L = int(get_field(f'{arch}.block_count'))
33N = int(get_field(f'{arch}.embedding_length'))
34FF = int(get_field(f'{arch}.feed_forward_length'))
35NH = int(get_field(f'{arch}.attention.head_count'))
36NKH = int(get_field(f'{arch}.attention.head_count_kv'))
37HD = int(get_field(f'{arch}.attention.key_length') or (N // NH))
38NE = int(get_field(f'{arch}.expert_count'))
39NK = int(get_field(f'{arch}.expert_used_count'))
40M = int(get_field(f'{arch}.expert_feed_forward_length'))
41eps = float(get_field(f'{arch}.attention.layer_norm_rms_epsilon'))
42freq = float(get_field(f'{arch}.rope.freq_base'))
43V = int(get_field('general.vocab_size') or 0)
44print(f'{L}L/{N}D/{FF}FF/{NH}H/{NKH}KV HD={HD} MoE {NE}x{NK} M={M} V={V} eps={eps}', flush=True)
45
46def get_t(name):
47 for t in r.tensors:
48 if t.name == name: return t
49 return None
50
51def load_f32(name, shape2d=None):
52 """Load and dequantize a 2D tensor to FP32."""
53 t = get_t(name)
54 if t is None: return None
55 f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32)
56 if len(t.shape) == 2:
57 in_dim, out_dim = int(t.shape[0]), int(t.shape[1])
58 f32 = f32.reshape(out_dim, in_dim)
59 return np.ascontiguousarray(f32)
60
61def load_f32_3d(name):
62 """Load and dequantize a 3D tensor (MoE experts)."""
63 t = get_t(name)
64 if t is None: return None
65 f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32)
66 if len(t.shape) == 3:
67 in_dim, out_dim, n_exp = int(t.shape[0]), int(t.shape[1]), int(t.shape[2])
68 f32 = f32.reshape(n_exp, out_dim, in_dim)
69 return np.ascontiguousarray(f32)
70
71# Load embedding
72emb_t = get_t('token_embd.weight')
73emb = gguf.dequantize(emb_t.data, emb_t.tensor_type).astype(np.float32)
74emb = emb.reshape(int(emb_t.shape[1]), int(emb_t.shape[0]))
75print(f'Embedding: {emb.shape}', flush=True)
76
77# Load weights per layer
78print('Loading weights...', flush=True)
79Wq = [load_f32(f'blk.{i}.attn_q.weight') for i in range(L)]
80Wk = [load_f32(f'blk.{i}.attn_k.weight') for i in range(L)]
81Wv = [load_f32(f'blk.{i}.attn_v.weight') for i in range(L)]
82Wo = [load_f32(f'blk.{i}.attn_output.weight') for i in range(L)]
83Wrouter = [load_f32(f'blk.{i}.ffn_gate_inp.weight') for i in range(L)]
84Wgate = [load_f32_3d(f'blk.{i}.ffn_gate_exps.weight') for i in range(L)]
85Wup = [load_f32_3d(f'blk.{i}.ffn_up_exps.weight') for i in range(L)]
86Wdown = [load_f32_3d(f'blk.{i}.ffn_down_exps.weight') for i in range(L)]
87AN = [load_f32(f'blk.{i}.attn_norm.weight') for i in range(L)]
88FN = [load_f32(f'blk.{i}.ffn_norm.weight') for i in range(L)]
89onw = load_f32('output_norm.weight')
90outw = load_f32('output.weight')
91print(f'Loaded in {time.perf_counter()-t0:.1f}s', flush=True)
92
93def rms_norm(x, w, e=eps):
94 return x * (1.0 / np.sqrt(np.mean(x*x) + e)) * w
95
96def rope(x, pos, hd=HD):
97 """Apply RoPE to Q/K vectors (x has shape (n_heads*hd,))."""
98 h2 = hd // 2
99 freqs = freq ** (np.arange(0, hd, 2, dtype=np.float32) / hd)
100 cos = np.cos(pos / freqs).astype(np.float32)
101 sin = np.sin(pos / freqs).astype(np.float32)
102 xr = x.reshape(-1, hd)
103 out = xr.copy()
104 out[:, :h2] = xr[:, :h2] * cos - xr[:, h2:] * sin
105 out[:, h2:] = xr[:, h2:] * cos + xr[:, :h2] * sin
106 return out.reshape(-1)
107
108def gqa(q, k, v, nh=NH, nkh=NKH, hd=HD):
109 """Grouped-query attention."""
110 gr = nh // nkh # heads per KV group
111 ks = nkh * hd
112 q = q.reshape(nh, hd)
113 k = k.reshape(nkh, hd)
114 v = v.reshape(nkh, hd)
115 out = np.zeros(nh * hd, dtype=np.float32)
116 for h in range(nh):
117 kv = h // gr
118 scores = np.dot(q[h], k[kv]) / np.sqrt(hd)
119 w = np.exp(scores - np.max(scores))
120 w = w / np.sum(w + 1e-10)
121 out[h*hd:(h+1)*hd] = w * v[kv]
122 return out
123
124def silu(x):
125 return x / (1.0 + np.exp(-x))
126
127def forward(token_id):
128 """Pure numpy forward pass for one token."""
129 x = emb[token_id].copy()
130 kv_cache_k = np.zeros((L, 4096, NKH * HD), dtype=np.float32) # dummy
131 kv_cache_v = np.zeros((L, 4096, NKH * HD), dtype=np.float32)
132
133 for l in range(L):
134 # Attention
135 res = x.copy()
136 xn = rms_norm(x, AN[l])
137 q = Wq[l] @ xn
138 k = Wk[l] @ xn
139 v = Wv[l] @ xn
140
141 pos = l # simplified: position 0 for first token then l
142 q = rope(q, 0, HD)
143 k = rope(k, 0, HD)
144
145 # Store KV (simplified: always at position 0)
146 kv_cache_k[l, 0] = k
147 kv_cache_v[l, 0] = v
148
149 # Attention
150 sl = 1
151 kct = kv_cache_k[l, :sl].reshape(sl * NKH * HD)
152 vct = kv_cache_v[l, :sl].reshape(sl * NKH * HD)
153 att = gqa(q, kct, vct)
154
155 x = res + Wo[l] @ att
156
157 # MoE FFN
158 res2 = x.copy()
159 xn2 = rms_norm(x, FN[l])
160
161 router = Wrouter[l] @ xn2 # [NE]
162 scores = np.exp(router - np.max(router))
163 scores = scores / np.sum(scores + 1e-10)
164 topk = np.argsort(scores)[-NK:][::-1]
165
166 ffn_out = np.zeros(N, dtype=np.float32)
167 for e_idx in topk:
168 w = scores[e_idx]
169 gate = Wgate[l][e_idx] @ xn2 # [M]
170 up = Wup[l][e_idx] @ xn2 # [M]
171 act = silu(gate) * up # [M]
172 down = Wdown[l][e_idx] @ act # [N]
173 ffn_out += w * down
174
175 x = res2 + ffn_out
176
177 # Final norm + output
178 xn = rms_norm(x, onw)
179 logits = outw @ xn
180
181 # Check for NaN
182 nan_count = np.isnan(logits).sum()
183 return logits, nan_count
184
185# Test
186print('\n--- Pure numpy forward ---', flush=True)
187t0 = time.perf_counter()
188logits, nan_count = forward(785)
189t1 = time.perf_counter()
190print(f'Time: {(t1-t0)*1000:.1f}ms', flush=True)
191print(f'NaN: {nan_count}/{V}', flush=True)
192if nan_count == 0:
193 top5 = np.argsort(logits)[-5:][::-1]
194 print(f'Top-5 tokens: {[tokenizer.decode([t]) for t in top5]}', flush=True)
195 print(f'Logits: max={logits.max():.2f} min={logits.min():.2f}', flush=True)