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 / gpu / nvidia / native / models / flash-next / check.py

186 lines · 8377 bytes Raw Blame History
1"""Compare the seeded lookup with the installed Transformers model and real FP8 rows."""
2import argparse
3import bisect
4import contextlib
5import hashlib
6import json
7import random
8import struct
9import subprocess
10import tempfile
11from pathlib import Path
12
13import torch
14from safetensors import safe_open
15from transformers import AutoConfig
16from transformers.models.qwen4_exp.modeling_qwen4_exp import (
17 Qwen4ExpTextModel, Qwen4ExpTextNGramEmbedding, Qwen4ExpTextRotaryEmbedding,
18)
19
20
21PREFIX = "model.language_model.layers.1.ple.ple_embedding."
22INDEX_HASH = "0419e2c2dfbb925257d7409405433a793cf7ff7d96f3eba882a815ec6d9fe7a6"
23CHAT = [248045, 846, 198, 20206, 440, 799, 15262, 1132, 13, 220, 17, 10,
24 17, 30, 248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271, 19, 248046]
25
26
27class ReferenceTable(torch.nn.Module):
28 def __init__(self, tables, scale):
29 super().__init__()
30 self.register_buffer("weight", torch.empty(0))
31 self.tables = tables
32 self.scale = scale
33 self.ends = []
34 self.used = set()
35 rows = 0
36 for table in tables:
37 count, width = table.get_shape()
38 assert width == 160
39 rows += count
40 self.ends.append(rows)
41
42 def forward(self, indices):
43 rows = []
44 for row in indices.flatten().tolist():
45 shard = bisect.bisect_right(self.ends, row)
46 self.used.add(shard)
47 local = row - (self.ends[shard - 1] if shard else 0)
48 rows.append(self.tables[shard][local:local + 1])
49 values = torch.cat(rows).float() * self.scale.float()
50 return values.bfloat16().reshape(*indices.shape, 160)
51
52
53def decoder_input(cfg, weight, ids):
54 """Capture the real input to the first Transformers decoder block without loading later blocks."""
55 class ReachedDecoder(Exception):
56 pass
57
58 def capture(_module, args):
59 raise ReachedDecoder(args[0].view(torch.uint16).numpy().tobytes())
60
61 with torch.device("meta"):
62 model = Qwen4ExpTextModel(cfg)
63 model.embed_tokens = torch.nn.Embedding.from_pretrained(weight)
64 model.rotary_emb = Qwen4ExpTextRotaryEmbedding(cfg)
65 model.layers[0].register_forward_pre_hook(capture)
66 masks = {"linear_attention": None, "qwen_sparse_attention": None}
67 try:
68 with torch.inference_mode():
69 model(torch.tensor([ids]), attention_mask=masks, use_cache=False)
70 except ReachedDecoder as result:
71 return result.args[0]
72 raise AssertionError("Transformers did not enter the first decoder block")
73
74
75def check(exe, model):
76 index = (model / "model.safetensors.index.json").read_bytes()
77 assert hashlib.sha256(index).hexdigest() == INDEX_HASH
78 locations = json.loads(index)["weight_map"]
79 cfg = AutoConfig.from_pretrained(model, local_files_only=True).text_config
80 rng = random.Random(1331)
81 ids = CHAT + [cfg.eos_token_id, 0, cfg.eos_token_id, cfg.eos_token_id,
82 cfg.vocab_size - 1] + [rng.randrange(cfg.vocab_size) for _ in range(240)]
83 data = struct.pack(f"<{len(ids)}I", *ids)
84 with safe_open(model / locations["model.language_model.embed_tokens.weight"], framework="pt") as shard:
85 weight = shard.get_tensor("model.language_model.embed_tokens.weight")
86 assert weight.shape == (cfg.vocab_size, cfg.hidden_size)
87 residual = decoder_input(cfg, weight, ids)
88
89 def input_run(payload, cwd=model, mode="--decoder-input"):
90 return subprocess.run([exe, mode], input=payload, stdout=subprocess.PIPE, cwd=cwd, timeout=60)
91
92 actual = input_run(data)
93 assert actual.returncode == 0 and actual.stdout == residual
94 assert len(residual) == len(ids) * 4 * 5120
95 assert input_run(b"").returncode == 0
96 for bad in (b"x", struct.pack("<I", cfg.vocab_size)):
97 result = input_run(bad)
98 assert (result.returncode, result.stdout) == (3, b"")
99 assert input_run(b"", mode="--decoder-input-extra").returncode == 1
100 with tempfile.TemporaryDirectory() as scratch:
101 root = Path(scratch)
102 assert input_run(data, root).returncode == 2
103 name = locations["model.language_model.embed_tokens.weight"]
104 with (model / name).open("rb") as src:
105 n, = struct.unpack("<Q", src.read(8))
106 header = json.loads(src.read(n))
107 key = "model.language_model.embed_tokens.weight"
108 for field, value in (("dtype", "F16"), ("shape", [cfg.vocab_size - 1, cfg.hidden_size]),
109 ("data_offsets", [0, 2])):
110 changed = {**header, key: {**header[key], field: value}}
111 raw = json.dumps(changed).encode()
112 with (root / name).open("wb") as out:
113 out.write(struct.pack("<Q", len(raw)) + raw)
114 out.truncate((model / name).stat().st_size - n + len(raw))
115 result = input_run(data, root)
116 assert (result.returncode, result.stdout) == (2, b"")
117 print(f"PASS decoder input: {len(ids)} tokens, {len(residual)} identical BF16 bytes, sha256 {hashlib.sha256(residual).hexdigest()}")
118 with contextlib.ExitStack() as stack:
119 filenames = {name for key, name in locations.items() if key.startswith(PREFIX)}
120 shards = {name: stack.enter_context(safe_open(model / name, framework="pt"))
121 for name in sorted(filenames)}
122 def tensor(suffix):
123 key = PREFIX + suffix
124 return shards[locations[key]].get_tensor(key)
125
126 with torch.device("meta"):
127 lookup = Qwen4ExpTextNGramEmbedding(cfg, cfg.ple_embed_dim, 1)
128 for name in ("layer_multipliers", "ngram_heads_offsets", "ngram_heads_vocab_sizes"):
129 setattr(lookup, name, tensor(name))
130 tables = []
131 for i in range(cfg.split_ngram_parts):
132 key = PREFIX + f"ngram_embedding.shard_{i}.weight"
133 tables.append(shards[locations[key]].get_slice(key))
134 table = ReferenceTable(tables, tensor("ngram_embedding.weight_scale"))
135 lookup.ngram_embedding = table
136 with torch.inference_mode():
137 expected = lookup(torch.tensor([ids]), None).view(torch.uint16).numpy().tobytes()
138 assert len(table.used) == 128
139
140 def run(payload, cwd=model):
141 return subprocess.run([exe], input=payload, stdout=subprocess.PIPE, cwd=cwd, timeout=60)
142
143 good = run(data)
144 assert good.returncode == 0 and good.stdout == expected
145 assert len(expected) == len(ids) * 5120
146 # The real model input detects dropped history; a restart agrees only after EOS.
147 restart = run(struct.pack("<I", ids[1]))
148 assert restart.returncode == 0 and restart.stdout != expected[5120:10240]
149 empty = run(b"")
150 assert (empty.returncode, empty.stdout) == (0, b"")
151 for invalid in (b"\x01", struct.pack("<I", cfg.vocab_size)):
152 bad = run(invalid)
153 assert (bad.returncode, bad.stdout) == (3, b"")
154 with tempfile.TemporaryDirectory() as scratch:
155 root = Path(scratch)
156 assert run(data, root).returncode == 2
157 for shard in model.glob("model-*.safetensors"):
158 (root / shard.name).symlink_to(shard)
159 name = "model-00006-of-00131.safetensors"
160 corrupt = root / name
161 corrupt.unlink()
162 with (model / name).open("rb") as src:
163 n, = struct.unpack("<Q", src.read(8))
164 header = json.loads(src.read(n))
165 key = PREFIX + "ngram_embedding.shard_2.weight"
166 header[key]["shape"][1] -= 1
167 raw = json.dumps(header).encode()
168 with corrupt.open("wb") as out:
169 out.write(struct.pack("<Q", len(raw)) + raw)
170 out.truncate((model / name).stat().st_size)
171 bad = run(data, root)
172 assert (bad.returncode, bad.stdout) == (2, b"")
173 print(f"PASS {len(ids)} tokens, {len(table.used)} shards, {len(expected)} identical BF16 bytes")
174 print("vector_sha256", hashlib.sha256(expected).hexdigest())
175 print("PASS history, empty input, invalid token, short input, missing and malformed shard controls")
176
177
178if __name__ == "__main__":
179 if not __debug__:
180 raise RuntimeError("Run the comparison with assertions enabled")
181 parser = argparse.ArgumentParser()
182 parser.add_argument("executable", type=Path)
183 parser.add_argument("checkpoint", type=Path)
184 args = parser.parse_args()
185 torch.set_num_threads(1)
186 check(args.executable.resolve(), args.checkpoint.resolve())