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/src/mojollama/kernels/dsv4/test_dsv4_forward.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 / src / mojollama / kernels / dsv4 / test_dsv4_forward.py` 294 lines · 12195 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Minimal DeepSeek V4 forward pass test - 1 layer, 1 token.""" 3 import sys, os, time, json, argparse 4 sys.path.insert(0, '/onedev-workspace/work/src') 5 import numpy as np 6 7 from mojollama.kernels.turbo_engine_dsv4 import ( 8 SafetensorsLoader, DeepSeekV4Config, dequantize_w4a16, 9 rms_norm, linear, apply_rotary_emb, precompute_freqs, 10 hc_split_sinkhorn 11 ) 12 13 def main(): 14 parser = argparse.ArgumentParser() 15 parser.add_argument("--layers", type=int, default=1) 16 parser.add_argument("--quick", action="store_true", help="Skip weight downloads if cached") 17 args = parser.parse_args() 18 19 cfg = DeepSeekV4Config(n_layers=args.layers) 20 print(f"DeepSeek V4 Flash Test: {cfg.n_layers} layer(s)") 21 print(f" dim={cfg.dim}, n_heads={cfg.n_heads}, head_dim={cfg.head_dim}") 22 print(f" rope_dim={cfg.rope_head_dim}, q_lora={cfg.q_lora_rank}") 23 print(f" experts={cfg.n_routed_experts}, top-k={cfg.n_activated_experts}") 24 print(f" hc_mult={cfg.hc_mult}") 25 26 loader = SafetensorsLoader(cfg.model_id) 27 28 # Load global weights 29 print("\nLoading global weights...") 30 embed_w = loader.get_tensor('embed.weight').astype(np.float32) 31 head_w = loader.get_tensor('head.weight').astype(np.float32) 32 norm_w = loader.get_tensor('norm.weight').astype(np.float32) 33 hc_head_fn = loader.get_tensor('hc_head_fn') 34 hc_head_base = loader.get_tensor('hc_head_base') 35 hc_head_scale = loader.get_tensor('hc_head_scale') 36 print(f" embed: {embed_w.shape}, head: {head_w.shape}, norm: {norm_w.shape}") 37 38 # Load per-layer weights (only what we need) 39 layer_weights = {} 40 for l in range(args.layers): 41 print(f"\nLoading layer {l}...") 42 lw = {} 43 44 # Norms 45 lw['attn_norm'] = loader.get_tensor(f'layers.{l}.attn_norm.weight').astype(np.float32) 46 lw['ffn_norm'] = loader.get_tensor(f'layers.{l}.ffn_norm.weight').astype(np.float32) 47 48 # Attention (W4A16 -> dequantized) 49 for wname in ['wq_a', 'wkv', 'wo_a', 'wo_b']: 50 key = f'layers.{l}.attn.{wname}' 51 qw = loader.get_tensor(key + '.qweight') 52 qz = loader.get_tensor(key + '.qzeros') 53 sc = loader.get_tensor(key + '.scales') 54 lw[f'attn_{wname}'] = dequantize_w4a16(qw, qz, sc) 55 print(f" attn.{wname}: {lw[f'attn_{wname}'].shape}") 56 57 # wq_b: [128, 32768] qweight 58 key = f'layers.{l}.attn.wq_b' 59 qw = loader.get_tensor(key + '.qweight') 60 qz = loader.get_tensor(key + '.qzeros') 61 sc = loader.get_tensor(key + '.scales') 62 lw['attn_wq_b'] = dequantize_w4a16(qw, qz, sc) 63 print(f" attn.wq_b: {lw['attn_wq_b'].shape}") 64 65 # q_norm, kv_norm 66 lw['q_norm'] = loader.get_tensor(f'layers.{l}.attn.q_norm.weight').astype(np.float32) 67 lw['kv_norm'] = loader.get_tensor(f'layers.{l}.attn.kv_norm.weight').astype(np.float32) 68 lw['attn_sink'] = loader.get_tensor(f'layers.{l}.attn.attn_sink').astype(np.float32) 69 print(f" attn_sink: {lw['attn_sink'].shape}, q_norm: {lw['q_norm'].shape}") 70 71 # Gate (W4A16 or F32) 72 try: 73 key = f'layers.{l}.ffn.gate' 74 qw = loader.get_tensor(key + '.qweight') 75 qz = loader.get_tensor(key + '.qzeros') 76 sc = loader.get_tensor(key + '.scales') 77 lw['gate_w'] = dequantize_w4a16(qw, qz, sc) 78 except: 79 lw['gate_w'] = loader.get_tensor(f'layers.{l}.ffn.gate.weight').astype(np.float32) 80 try: 81 lw['gate_bias'] = loader.get_tensor(f'layers.{l}.ffn.gate.bias') 82 except: 83 lw['gate_bias'] = None 84 try: 85 lw['tid2eid'] = loader.get_tensor(f'layers.{l}.ffn.gate.tid2eid') 86 except: 87 lw['tid2eid'] = None 88 print(f" gate_w: {lw['gate_w'].shape}, bias={'yes' if lw['gate_bias'] is not None else 'no'}, hash={'yes' if lw['tid2eid'] is not None else 'no'}") 89 90 # Shared expert 91 for wname in ['w1', 'w2', 'w3']: 92 key = f'layers.{l}.ffn.shared_experts.{wname}' 93 qw = loader.get_tensor(key + '.qweight') 94 qz = loader.get_tensor(key + '.qzeros') 95 sc = loader.get_tensor(key + '.scales') 96 lw[f'shared_{wname}'] = dequantize_w4a16(qw, qz, sc) 97 print(f" shared.{wname}: {lw[f'shared_{wname}'].shape}") 98 99 # HC params 100 for kind in ['attn', 'ffn']: 101 prefix = f'layers.{l}.hc_{kind}_' 102 lw[f'hc_{kind}_fn'] = loader.get_tensor(prefix + 'fn') 103 lw[f'hc_{kind}_base'] = loader.get_tensor(prefix + 'base') 104 lw[f'hc_{kind}_scale'] = loader.get_tensor(prefix + 'scale') 105 print(f" hc_{kind}_fn: {lw[f'hc_{kind}_fn'].shape}") 106 107 layer_weights[l] = lw 108 109 print("\n" + "=" * 60) 110 print("Running forward pass...") 111 print("=" * 60) 112 113 D = cfg.dim 114 HC = cfg.hc_mult 115 NH = cfg.n_heads 116 HD = cfg.head_dim 117 RHD = cfg.rope_head_dim 118 119 # Init hidden state 120 token = 1 # arbitrary token 121 bx = embed_w[token].copy() 122 br = np.zeros((HC, D), dtype=np.float32) 123 br[:] = bx[np.newaxis, :] / HC 124 125 # KV cache 126 kv_cache = np.zeros((cfg.window_size, HD), dtype=np.float32) 127 128 t_start = time.perf_counter() 129 130 for l in range(args.layers): 131 lw = layer_weights[l] 132 133 # ── HC Pre (Attention) ── 134 # mixes = hc_fn @ flatten(br) * rsqrt 135 x_flat = br.flatten() 136 rsqrt = 1.0 / np.sqrt(np.mean(x_flat * x_flat) + 1e-6) 137 mixes = np.dot(lw['hc_attn_fn'], x_flat * rsqrt) 138 pre, post, comb = hc_split_sinkhorn( 139 mixes[np.newaxis, np.newaxis, :], 140 lw['hc_attn_scale'], lw['hc_attn_base'], HC, 1, 1e-6) 141 pre = pre[0, 0]; post = post[0, 0]; comb = comb[0, 0] 142 # Weighted sum 143 x = np.sum(pre[:, None] * br, axis=0) 144 145 # ── Attention Norm ── 146 x = rms_norm(x, lw['attn_norm'], cfg.eps) 147 148 # ── MLA Attention ── 149 # Q: wq_a -> q_norm -> wq_b -> reshape 150 latent = np.dot(lw['attn_wq_a'], x) 151 latent = rms_norm(latent, lw['q_norm'], cfg.eps) 152 q = np.dot(lw['attn_wq_b'], latent) 153 q = q.reshape(NH, HD) 154 155 # QK norm 156 q = q / np.sqrt(np.mean(q * q, axis=-1, keepdims=True) + cfg.eps) 157 158 # KV: wkv -> kv_norm 159 kv = np.dot(lw['attn_wkv'], x) 160 kv = rms_norm(kv, lw['kv_norm'], cfg.eps) 161 162 # RoPE 163 rope_dim = RHD 164 cos, sin = precompute_freqs(rope_dim, 2, 0, cfg.rope_theta, 1.0, 32, 1) 165 apply_rotary_emb(q[:, :rope_dim], cos, sin, 0, rope_dim, NH) 166 apply_rotary_emb(kv[np.newaxis, :rope_dim], cos, sin, 0, rope_dim, 1) 167 168 # Sliding window attention (pos=0, no compression) 169 kv_cache[0] = kv 170 # For pos=0, attention is over just this token 171 scale = HD ** -0.5 172 scores = np.dot(q, kv) * scale # [NH] 173 scores += lw['attn_sink'] 174 # Softmax 175 scores = scores - np.max(scores) 176 exp_scores = np.exp(scores) 177 weights = exp_scores / (np.sum(exp_scores) + 1e-10) 178 o = weights[:, np.newaxis] * kv[np.newaxis, :] # [NH, HD] 179 180 # Output projection 181 # wo_a: [groups*o_lora_rank, NHG*HD] = [8192, 4096] block-diagonal: 8 blocks of [1024, 4096] 182 # wo_b: [D, groups*o_lora_rank] = [4096, 8192] 183 groups, o_lora = cfg.o_groups, cfg.o_lora_rank 184 NHG = NH // groups # heads per group = 8 185 o_r = o.reshape(groups, NHG * HD) # [8, 4096] 186 o_proj = np.zeros(groups * o_lora, dtype=np.float32) 187 for g in range(groups): 188 w_g = lw['attn_wo_a'][g * o_lora:(g + 1) * o_lora, :] # [1024, 4096] 189 o_proj[g * o_lora:(g + 1) * o_lora] = w_g @ o_r[g] # [1024] 190 o_out = np.dot(lw['attn_wo_b'], o_proj) # [D] 191 192 # ── HC Post (Attention) ── 193 br_new = post[:, None] * o_out[np.newaxis, :] + np.dot(comb, br) 194 br = br_new.astype(np.float32) 195 196 # ── HC Pre (FFN) ── 197 x_flat = br.flatten() 198 rsqrt = 1.0 / np.sqrt(np.mean(x_flat * x_flat) + 1e-6) 199 mixes = np.dot(lw['hc_ffn_fn'], x_flat * rsqrt) 200 pre, post, comb = hc_split_sinkhorn( 201 mixes[np.newaxis, np.newaxis, :], 202 lw['hc_ffn_scale'], lw['hc_ffn_base'], HC, 1, 1e-6) 203 pre = pre[0, 0]; post = post[0, 0]; comb = comb[0, 0] 204 x = np.sum(pre[:, None] * br, axis=0) 205 206 # ── FFN Norm ── 207 x = rms_norm(x, lw['ffn_norm'], cfg.eps) 208 209 # ── MoE FFN (just shared expert for first test) ── 210 # Gate: compute scores (top-1 for simplicity) 211 scores = np.dot(lw['gate_w'], x) 212 if lw['gate_bias'] is not None: 213 scores += lw['gate_bias'] 214 # sqrtsoftplus 215 scores = np.sqrt(np.log1p(np.exp(scores))) 216 topk = min(cfg.n_activated_experts, cfg.n_routed_experts) 217 indices = np.argpartition(-scores, topk)[:topk] 218 weights = scores[indices] 219 weights = weights / (np.sum(weights) + 1e-10) 220 weights *= cfg.route_scale 221 222 moe_out = np.zeros(D, dtype=np.float32) 223 # Only load and compute activated experts 224 for k, (eid, w) in enumerate(zip(indices, weights)): 225 if w <= 0: 226 continue 227 # Load expert weights on-demand 228 key_w1 = f'layers.{l}.ffn.experts.{int(eid)}.w1' 229 key_w2 = f'layers.{l}.ffn.experts.{int(eid)}.w2' 230 key_w3 = f'layers.{l}.ffn.experts.{int(eid)}.w3' 231 qw1 = loader.get_tensor(key_w1 + '.qweight') 232 qz1 = loader.get_tensor(key_w1 + '.qzeros') 233 sc1 = loader.get_tensor(key_w1 + '.scales') 234 w1 = dequantize_w4a16(qw1, qz1, sc1) 235 qw2 = loader.get_tensor(key_w2 + '.qweight') 236 qz2 = loader.get_tensor(key_w2 + '.qzeros') 237 sc2 = loader.get_tensor(key_w2 + '.scales') 238 w2 = dequantize_w4a16(qw2, qz2, sc2) 239 qw3 = loader.get_tensor(key_w3 + '.qweight') 240 qz3 = loader.get_tensor(key_w3 + '.qzeros') 241 sc3 = loader.get_tensor(key_w3 + '.scales') 242 w3 = dequantize_w4a16(qw3, qz3, sc3) 243 244 gate_act = np.dot(w1, x) 245 up_act = np.dot(w3, x) 246 if cfg.swiglu_limit > 0: 247 up_act = np.clip(up_act, -cfg.swiglu_limit, cfg.swiglu_limit) 248 gate_act = np.clip(gate_act, None, cfg.swiglu_limit) 249 sig = 1.0 / (1.0 + np.exp(-gate_act)) 250 activated = sig * gate_act * up_act 251 if w != 1.0: 252 activated *= w 253 moe_out += np.dot(w2, activated) 254 255 # Shared expert 256 gate_s = np.dot(lw['shared_w1'], x) 257 up_s = np.dot(lw['shared_w3'], x) 258 if cfg.swiglu_limit > 0: 259 up_s = np.clip(up_s, -cfg.swiglu_limit, cfg.swiglu_limit) 260 gate_s = np.clip(gate_s, None, cfg.swiglu_limit) 261 sig_s = 1.0 / (1.0 + np.exp(-gate_s)) 262 activated_s = sig_s * gate_s * up_s 263 moe_out += np.dot(lw['shared_w2'], activated_s) 264 265 # ── HC Post (FFN) ── 266 br_new = post[:, None] * moe_out[np.newaxis, :] + np.dot(comb, br) 267 br = br_new.astype(np.float32) 268 269 elapsed = time.perf_counter() - t_start 270 print(f" Layer {l}: {elapsed*1000:.0f}ms, bx_norm={np.linalg.norm(x):.4f}, " 271 f"moe_out_norm={np.linalg.norm(moe_out):.4f}, " 272 f"br_norm={np.linalg.norm(br):.4f}", flush=True) 273 274 # ── HC Head + Norm + LM Head ── 275 x_flat = br.flatten() 276 rsqrt = 1.0 / np.sqrt(np.mean(x_flat * x_flat) + cfg.eps) 277 mixes = np.dot(hc_head_fn, x_flat * rsqrt) 278 pre = 1.0 / (1.0 + np.exp(-(mixes * hc_head_scale[0] + hc_head_base))) + cfg.hc_eps 279 x = np.sum(pre[:, None] * br, axis=0) 280 x = rms_norm(x, norm_w, cfg.eps) 281 logits = np.dot(head_w, x) 282 283 elapsed = time.perf_counter() - t_start 284 print(f"\nLogits: shape={logits.shape}, range=[{logits.min():.4f}, {logits.max():.4f}]") 285 top5 = np.argsort(-logits)[:5] 286 print(f"Top-5 tokens: {top5.tolist()}") 287 print(f"Top-5 logits: {logits[top5].tolist()}") 288 print(f"Total forward time: {elapsed*1000:.0f}ms") 289 290 loader.close() 291 print("\nSUCCESS!") 292 293 if __name__ == "__main__": 294 main()