interplane.Get Omega
Read in your language

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

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)."""
3import json
4import struct
5import sys
6import numpy as np
7
8
9def read_safetensors_header(path):
10 with open(path, "rb") as f:
11 n = struct.unpack("<Q", f.read(8))[0]
12 return json.loads(f.read(n)), 8 + n
13
14
15def load_tensor(path, header, base, name):
16 info = header[name]
17 b0, b1 = info["data_offsets"]
18 dt = info["dtype"]
19 sh = info["shape"]
20 with open(path, "rb") as f:
21 f.seek(base + b0)
22 raw = f.read(b1 - b0)
23 if dt == "F32":
24 return np.frombuffer(raw, dtype="<f4").reshape(sh).copy()
25 if dt == "BF16":
26 u16 = np.frombuffer(raw, dtype="<u2").reshape(sh)
27 return (u16.astype(np.uint32) << 16).view(np.float32).copy()
28 if dt in ("F8_E4M3", "F8_E8M0", "I8", "U8"):
29 return np.frombuffer(raw, dtype=np.uint8).reshape(sh).copy()
30 raise ValueError(f"Unsupported dtype {dt} for {name}")
31
32
33def bf16(x):
34 x = np.asarray(x, dtype=np.float32)
35 u = x.view(np.uint32)
36 return ((u + 32767 + ((u >> 16) & 1)) & 0xFFFF0000).view(np.float32)
37
38
39def 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
51LUT = make_lut()
52
53
54def 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
70def 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
77def 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
88def 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
94def 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
100def 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
106def 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
122def 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="<u2").astype(np.uint32) << 16).view(np.float32)
135 res = np.repeat(emb[None, :], 4, axis=0)
136 pre_mix = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
137
138 # Attention HC
139 attn_pre, attn_post, attn_comb = hc_mixes(res, L("hc_attn_fn"), L("hc_attn_scale"), L("hc_attn_base"))
140 x = bf16(np.einsum("id,i->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="<f4").reshape(4, 5120)
200 g_pm = np.frombuffer(raw_gpu[81920:81936], dtype="<f4")
201 g_ids = np.frombuffer(raw_gpu[81936:81960], dtype="<i4")
202 g_wts = np.frombuffer(raw_gpu[81960:81984], dtype="<f4")
203
204 print("CPU routed IDs:", sel.tolist())
205 print("GPU routed IDs:", g_ids.tolist())
206 print("CPU weights: ", [round(float(v), 6) for v in sw])
207 print("GPU weights: ", [round(float(v), 6) for v in g_wts])
208 print("pre_mix max abs diff:", float(np.max(np.abs(ffn_pre - g_pm))))
209 res_diff = np.abs(res_out - g_res)
210 cos = float(np.dot(res_out.ravel(), g_res.ravel()) / (np.linalg.norm(res_out) * np.linalg.norm(g_res)))
211 print(f"residual max_abs={float(res_diff.max()):.6g} mean_abs={float(res_diff.mean()):.6g} cos={cos:.8f}")
212 assert np.array_equal(sel, g_ids), "Routed expert IDs mismatch!"
213 assert np.allclose(sw, g_wts, atol=1e-4, rtol=1e-4), "Router weights mismatch!"
214 assert np.allclose(ffn_pre, g_pm, atol=1e-4, rtol=1e-4), "pre_mix mismatch!"
215 assert cos > 0.9999, f"Residual cosine too low: {cos}"
216 print("GATE2_LAYER0_PARITY_PASS")
217
218
219if __name__ == "__main__":
220 main()