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/omega-mv/blob/main/om/gpu/dsv41/decoder/check-layer0.py # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / om / gpu / dsv41 / decoder / check-layer0.py` 220 lines ยท 8828 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Independent CPU reference verifier for DeepSeek-V4.1-Flash Layer 0 (pos=0).""" 3 import json 4 import struct 5 import sys 6 import numpy as np 7 8 9 def read_safetensors_header(path): 10 with open(path, "rb") as f: 11 n = struct.unpack("> 16) & 1)) & 0xFFFF0000).view(np.float32) 37 38 39 def make_lut(): 40 vals = [] 41 for code in range(256): 42 exp, frac = (code >> 3) & 15, code & 7 43 mag = frac / 512.0 if exp == 0 else (1.0 + frac / 8.0) * (2.0 ** (exp - 7)) 44 if exp == 15 and frac == 7: 45 mag = np.nan 46 vals.append(-mag if code & 128 else mag) 47 fp4 = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0] 48 return np.array(vals + fp4 + [-v for v in fp4], dtype=np.float32) 49 50 51 LUT = make_lut() 52 53 54 def quant_fp8_recon(x): 55 v = x.reshape(-1, 32).astype(np.float32) 56 ratio = np.maximum(np.abs(v).max(axis=1), 1e-4) / np.float32(448.0) 57 exps = np.ceil(np.log2(ratio.astype(np.float64))) 58 scales = np.exp2(exps).astype(np.float32) 59 tbl = LUT[:127] 60 mids = (tbl[:-1] + tbl[1:]).astype(np.float64) / 2.0 61 q = v / scales[:, None] 62 mag = np.abs(q).astype(np.float64) 63 code = np.searchsorted(mids, mag, side="left") 64 tie = (code < len(mids)) & (mag == mids[np.minimum(code, len(mids) - 1)]) 65 code = (code + (tie & (code % 2 == 1)) + np.signbit(q) * 128).astype(np.uint8) 66 recon = bf16(LUT[code] * scales[:, None]) 67 return recon.reshape(x.shape) 68 69 70 def dequant_fp8(w, s): 71 n, k = w.shape 72 sc = np.exp2(s.astype(np.float32) - 127.0) 73 sc = np.repeat(np.repeat(sc, 32, axis=0)[:n], 32, axis=1)[:, :k] 74 return LUT[w] * sc 75 76 77 def dequant_fp4(w_packed, s): 78 n, half_k = w_packed.shape 79 lo = w_packed & 0x0F 80 hi = (w_packed >> 4) & 0x0F 81 w = np.empty((n, half_k * 2), dtype=np.uint8) 82 w[:, 0::2] = lo 83 w[:, 1::2] = hi 84 sc = np.repeat(np.exp2(s.astype(np.float32) - 127.0), 32, axis=1) 85 return LUT[256 + w.astype(np.int32)] * sc 86 87 88 def fp8_linear(x, w, s): 89 xq = quant_fp8_recon(x) 90 wf = dequant_fp8(w, s) 91 return bf16(xq @ wf.T) 92 93 94 def fp4_linear(x, w, s): 95 xq = quant_fp8_recon(x) 96 wf = dequant_fp4(w, s) 97 return bf16(xq @ wf.T) 98 99 100 def rms_norm(x, gain, eps=1e-20): 101 x = x.astype(np.float32) 102 inv = np.float32(1.0) / np.sqrt(np.mean(x * x) + np.float32(eps)) 103 return bf16(x * inv * gain) 104 105 106 def hc_mixes(x, hc_fn, hc_scale, hc_base): 107 flat = x.reshape(-1).astype(np.float32) 108 inv = np.float32(1.0) / np.sqrt(np.mean(flat * flat) + np.float32(1e-20)) 109 raw = (flat @ hc_fn.T) * inv 110 logits = raw * np.repeat(hc_scale, [4, 4, 16]) + hc_base 111 sig = 1.0 / (1.0 + np.exp(-logits[:8])) 112 mat = logits[8:].reshape(4, 4) 113 mat = np.exp(mat - mat.max(axis=1, keepdims=True)) 114 mat = mat / mat.sum(axis=1, keepdims=True) + 1e-6 115 mat = mat / (mat.sum(axis=0, keepdims=True) + 1e-6) 116 for _ in range(19): 117 mat = mat / (mat.sum(axis=1, keepdims=True) + 1e-6) 118 mat = mat / (mat.sum(axis=0, keepdims=True) + 1e-6) 119 return (sig[:4] + 1e-6).astype(np.float32), (sig[4:] * 2.0).astype(np.float32), mat.astype(np.float32) 120 121 122 def main(): 123 ckpt, tok_id, gpu_bin = sys.argv[1], int(sys.argv[2]), sys.argv[3] 124 s2 = f"{ckpt}/model-00002-of-00048.safetensors" 125 s3 = f"{ckpt}/model-00003-of-00048.safetensors" 126 h2, b2 = read_safetensors_header(s2) 127 h3, b3 = read_safetensors_header(s3) 128 L = lambda name: load_tensor(s3, h3, b3, f"layers.0.{name}") 129 130 # Token embedding (row tok_id) 131 einfo = h2["embed.weight"] 132 with open(s2, "rb") as f: 133 f.seek(b2 + einfo["data_offsets"][0] + tok_id * 5120 * 2) 134 emb = (np.frombuffer(f.read(5120 * 2), dtype="d", res, pre_mix)) 141 x = rms_norm(x, L("attn_norm.weight")) 142 143 # Attention (pos=0 -> RoPE is identity!) 144 qr = rms_norm(fp8_linear(x, L("attn.wq_a.weight"), L("attn.wq_a.scale")), L("attn.q_norm.weight")) 145 q = fp8_linear(qr, L("attn.wq_b.weight"), L("attn.wq_b.scale")).reshape(64, 512) 146 kv = quant_fp8_recon(rms_norm(fp8_linear(x, L("attn.wkv.weight"), L("attn.wkv.scale")), L("attn.kv_norm.weight"))) 147 148 # Single-position sparse attention with sink 149 scores = (q @ kv) / np.float32(np.sqrt(512.0)) 150 sink = L("attn.attn_sink") 151 peak = scores 152 p = np.ones_like(scores, dtype=np.float32) 153 denom = p + np.exp(sink - peak) 154 o = (bf16(p)[:, None] * kv[None, :]) / denom[:, None] 155 o = bf16(o) 156 157 # Grouped wo_a + wo_b 158 woa_w = L("attn.wo_a.weight").reshape(8, 1024, 4096) 159 woa_s = L("attn.wo_a.scale").reshape(8, 32, 128) 160 og = o.reshape(8, 4096) 161 woa_out = np.concatenate([fp8_linear(og[g], woa_w[g], woa_s[g]) for g in range(8)]) 162 attn_out = fp8_linear(woa_out, L("attn.wo_b.weight"), L("attn.wo_b.scale")) 163 res = bf16(attn_post[:, None] * attn_out[None, :] + np.einsum("id,ij->jd", res, attn_comb)) 164 165 # FFN HC + Router 166 ffn_pre, ffn_post, ffn_comb = hc_mixes(res, L("hc_ffn_fn"), L("hc_ffn_scale"), L("hc_ffn_base")) 167 x = bf16(np.einsum("id,i->d", res, attn_pre)) 168 x = rms_norm(x, L("ffn_norm.weight")) 169 170 logits = x @ L("ffn.gate.weight").T 171 raw = np.sqrt(np.logaddexp(np.float32(0.0), logits)) 172 bias = L("ffn.gate.bias") 173 sel = np.argsort(-(raw + bias), kind="stable")[:6].astype(np.int32) 174 sw = raw[sel] 175 sw = sw * np.float32(1.5) / (sw.sum() + np.float32(1e-20)) 176 177 # Shared expert 178 sh_g = fp8_linear(x, L("ffn.shared_experts.w1.weight"), L("ffn.shared_experts.w1.scale")) 179 sh_u = fp8_linear(x, L("ffn.shared_experts.w3.weight"), L("ffn.shared_experts.w3.scale")) 180 gl = np.minimum(np.float32(10.0), sh_g) 181 sh_act = bf16(gl / (1.0 + np.exp(-gl)) * np.clip(sh_u, -10.0, 10.0)) 182 sh_out = fp8_linear(sh_act, L("ffn.shared_experts.w2.weight"), L("ffn.shared_experts.w2.scale")) 183 184 # 6 Routed experts 185 routed_sum = np.zeros(5120, dtype=np.float32) 186 for k in range(6): 187 e = int(sel[k]) 188 eg = fp4_linear(x, L(f"ffn.experts.{e}.w1.weight"), L(f"ffn.experts.{e}.w1.scale")) 189 eu = fp4_linear(x, L(f"ffn.experts.{e}.w3.weight"), L(f"ffn.experts.{e}.w3.scale")) 190 gl = np.minimum(np.float32(10.0), eg) 191 ea = bf16(gl / (1.0 + np.exp(-gl)) * np.clip(eu, -10.0, 10.0) * sw[k]) 192 routed_sum += fp4_linear(ea, L(f"ffn.experts.{e}.w2.weight"), L(f"ffn.experts.{e}.w2.scale")) 193 moe_out = bf16(routed_sum + sh_out) 194 res_out = bf16(ffn_post[:, None] * moe_out[None, :] + np.einsum("id,ij->jd", res, ffn_comb)) 195 196 # Load GPU dump 197 raw_gpu = open(gpu_bin, "rb").read() 198 assert len(raw_gpu) == 81920 + 16 + 24 + 24, f"Unexpected dump size {len(raw_gpu)}" 199 g_res = np.frombuffer(raw_gpu[:81920], dtype=" 0.9999, f"Residual cosine too low: {cos}" 216 print("GATE2_LAYER0_PARITY_PASS") 217 218 219 if __name__ == "__main__": 220 main()