interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / om / flint / test / gen.py

238 lines · 8523 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Flint manifest fixture generator. TEST REFEREE ONLY, never an implementation dependency.
3
4Builds a full Flint-shaped checkpoint from config.json alone: every tensor name and shape is derived
5here independently of manifest.om. Shards are sparse: an 8-byte little-endian header length, the
6header JSON, then ftruncate to the data length, so 79.5 GB of apparent size costs about 4 MB of disk.
7
8Usage: gen.py CONFIG OUT MUTANT
9Writes OUT/config.json, OUT/index.json, OUT/shards/*.safetensors and, for MUTANT base, OUT/expected.tsv.
10Every other MUTANT applies exactly one defect; check.sh holds the exit code each one must produce.
11"""
12import json
13import os
14import struct
15import sys
16
17cfg_path, out, mut = sys.argv[1:4]
18raw = open(cfg_path, "rb").read()
19c = json.loads(raw)
20H = c["hidden_size"]
21V = c["vocab_size"]
22HD = c["head_dim"]
23NH = c["num_attention_heads"]
24NKV = c["num_key_value_heads"]
25NE = c["num_experts"]
26MI = c["moe_intermediate_size"]
27SI = c["shared_expert_intermediate_size"]
28DI = c["intermediate_size"]
29NL = c["num_hidden_layers"]
30DENSE = set(c["mlp_only_layers"])
31
32
33def tensors():
34 t = [("model.embed_tokens.weight", [V, H]), ("model.norm.weight", [H]), ("lm_head.weight", [V, H])]
35 for L in range(NL):
36 p = "model.layers.%d." % L
37 t += [
38 (p + "input_layernorm.weight", [H]),
39 (p + "post_attention_layernorm.weight", [H]),
40 (p + "self_attn.q_proj.weight", [NH * HD, H]),
41 (p + "self_attn.k_proj.weight", [NKV * HD, H]),
42 (p + "self_attn.v_proj.weight", [NKV * HD, H]),
43 (p + "self_attn.o_proj.weight", [H, NH * HD]),
44 (p + "self_attn.q_norm.weight", [HD]),
45 (p + "self_attn.k_norm.weight", [HD]),
46 (p + "self_attn.softmax_offset", [NH]),
47 ]
48 if L in DENSE:
49 t += [(p + "mlp.gate_proj.weight", [DI, H]), (p + "mlp.up_proj.weight", [DI, H]),
50 (p + "mlp.down_proj.weight", [H, DI])]
51 continue
52 t += [(p + "mlp.gate.weight", [NE, H]),
53 (p + "mlp.shared_expert.gate_proj.weight", [SI, H]),
54 (p + "mlp.shared_expert.up_proj.weight", [SI, H]),
55 (p + "mlp.shared_expert.down_proj.weight", [H, SI])]
56 for e in range(NE):
57 q = p + "mlp.experts.%d." % e
58 t += [(q + "gate_proj.weight", [MI, H]), (q + "up_proj.weight", [MI, H]),
59 (q + "down_proj.weight", [H, MI])]
60 return t
61
62
63def numel(shape):
64 n = 1
65 for d in shape:
66 n *= d
67 return n
68
69
70NS = 8 if mut == "shard-cap" else 15
71shape_of = dict(tensors())
72names = sorted(shape_of)
73sname = ["model-%05d-of-%05d.safetensors" % (i + 1, NS) for i in range(NS)]
74# shard i: list of [name, dtype, shape, begin, end]; extras: unparsed text spliced into the header
75shards = []
76for i in range(NS):
77 part = names[i * len(names) // NS:(i + 1) * len(names) // NS]
78 shards.append([[n, "BF16", list(shape_of[n]), 0, 0] for n in part])
79wmap = [[n, sname[i]] for i in range(NS) for n in (e[0] for e in shards[i])]
80
81
82def pack(rows):
83 o = 0
84 for r in rows:
85 r[3] = o
86 o += 2 * numel(r[2])
87 r[4] = o
88 return o
89
90
91for rows in shards:
92 pack(rows)
93total = sum(2 * numel(s) for s in shape_of.values())
94
95# ---- one defect per mutant -------------------------------------------------------------------
96s0 = shards[0]
97cfg_text = raw
98idx_tail = ""
99extra_head = "" # text placed before the first entry of shard 0
100extra_entry = "" # extra key inside the first entry of shard 0
101dup_entry = False # repeat the first entry of shard 0 at the end of its header
102size_delta = 0 # bytes added to shard 0's data length
103hl_mode = "le"
104GATE = "model.layers.2.mlp.shared_expert_gate.weight"
105
106if mut == "cfg-json":
107 cfg_text = b"{"
108elif mut == "cfg-field":
109 cfg_text = raw.replace(b'"num_experts": 256', b'"num_experts": 128')
110elif mut == "cfg-unknown":
111 cfg_text = raw.replace(b'"vocab_size": 150144', b'"vocab_size": 150144,\n "foo": 1')
112elif mut == "cfg-dup":
113 cfg_text = raw.replace(b'"vocab_size": 150144', b'"vocab_size": 150144,\n "vocab_size": 150144')
114elif mut == "cfg-missing":
115 cfg_text = raw.replace(b',\n "vocab_size": 150144', b"")
116elif mut == "cfg-softmax":
117 cfg_text = raw.replace(b'"router_score_function": "sigmoid"', b'"router_score_function": "softmax"')
118elif mut == "cfg-window":
119 cfg_text = raw.replace(b'"sliding_window": 513', b'"sliding_window": 4096')
120elif mut == "cfg-tie":
121 cfg_text = raw.replace(b'"tie_word_embeddings": false', b'"tie_word_embeddings": true')
122elif mut == "idx-total":
123 total += 2
124elif mut == "idx-missing":
125 del wmap[5]
126elif mut == "idx-dup":
127 wmap.insert(6, list(wmap[5]))
128elif mut == "idx-unknown":
129 wmap.append([GATE, sname[0]])
130elif mut == "idx-shard-name":
131 wmap[5][1] = "../" + sname[0]
132elif mut == "idx-syntax":
133 idx_tail = "x"
134elif mut == "idx-size":
135 idx_tail = " " * 4194304
136elif mut == "hdr-dtype":
137 s0[0][1] = "F16"
138elif mut == "hdr-shape":
139 r = next(r for r in s0 if r[0].endswith("q_proj.weight"))
140 r[2] = [r[2][1], r[2][0]]
141elif mut == "hdr-rank":
142 r = next(r for r in s0 if r[0].endswith("q_norm.weight"))
143 r[2] = r[2] + [1]
144elif mut == "hdr-off-len":
145 s0[-1][4] += 2
146 size_delta = 2
147elif mut == "hdr-off-overflow":
148 s0[-1][4] = 2 ** 64
149elif mut == "hdr-overlap":
150 a, b = s0[0], s0[1]
151 assert a[4] - a[3] == b[4] - b[3]
152 b[3], b[4] = a[3], a[4]
153elif mut == "hdr-gap":
154 s0[-1][3] += 2
155 s0[-1][4] += 2
156 size_delta = 2
157elif mut == "hdr-trailing":
158 size_delta = 2
159elif mut == "hdr-truncated":
160 size_delta = -2
161elif mut == "hdr-dup":
162 dup_entry = True
163elif mut == "hdr-mismatch":
164 moved = s0.pop()
165 shards[1].append(moved)
166 pack(shards[1])
167elif mut == "hdr-missing":
168 s0.pop()
169elif mut == "hdr-unknown":
170 s0.append([GATE, "BF16", [1, H], 0, 0])
171 pack(s0)
172elif mut == "hdr-meta":
173 extra_head = '"__metadata__":{"format":"pt"},'
174elif mut == "hdr-entry":
175 extra_entry = ',"extra":1'
176elif mut not in ("base", "hdr-json", "hdr-len-be", "hdr-len-big", "shard-short", "shard-absent",
177 "shard-symlink", "shard-dir", "shard-cap"):
178 sys.exit("gen.py: unknown mutant " + mut)
179if cfg_text == raw and mut.startswith("cfg-") and mut != "cfg-json":
180 sys.exit("gen.py: mutant " + mut + " did not change config.json")
181
182# ---- write -------------------------------------------------------------------------------------
183os.makedirs(out + "/shards")
184with open(out + "/config.json", "wb") as f:
185 f.write(cfg_text)
186
187lines = ["{", ' "metadata": {', ' "total_size": %d' % total, " },", ' "weight_map": {']
188lines += [' "%s": "%s"%s' % (n, s, "," if k + 1 < len(wmap) else "") for k, (n, s) in enumerate(wmap)]
189lines += [" }", "}"]
190with open(out + "/index.json", "w") as f:
191 f.write("\n".join(lines) + "\n" + idx_tail)
192
193
194def entry(r, more=""):
195 return '"%s":{"dtype":"%s","shape":[%s],"data_offsets":[%d,%d]%s}' % (
196 r[0], r[1], ",".join(str(d) for d in r[2]), r[3], r[4], more)
197
198
199for i, rows in enumerate(shards):
200 path = out + "/shards/" + sname[i]
201 ents = [entry(r, extra_entry if (i == 0 and k == 0) else "") for k, r in enumerate(rows)]
202 if i == 0 and dup_entry:
203 ents.append(entry(rows[0]))
204 head = "{" + (extra_head if i == 0 else "") + ",".join(ents) + "}"
205 if i == 0 and mut == "hdr-json":
206 head = "{"
207 head = head.encode()
208 head += b" " * (-len(head) % 8)
209 data = max((r[4] for r in rows if r[4] < 2 ** 63), default=0)
210 if i == 0:
211 data += size_delta
212 hl = len(head)
213 if i == 0 and mut == "hdr-len-big":
214 hl = 8 + len(head) + data
215 with open(path, "wb") as f:
216 if i == 0 and mut == "shard-short":
217 f.write(b"\x00" * 4)
218 continue
219 f.write(struct.pack(">Q" if (i == 0 and mut == "hdr-len-be") else "<Q", hl))
220 f.write(head)
221 f.truncate(8 + len(head) + data)
222
223p0 = out + "/shards/" + sname[0]
224if mut == "shard-absent":
225 os.remove(p0)
226elif mut == "shard-symlink":
227 os.rename(p0, p0 + ".real")
228 os.symlink(sname[0] + ".real", p0)
229elif mut == "shard-dir":
230 os.remove(p0)
231 os.mkdir(p0)
232
233if mut == "base":
234 with open(out + "/expected.tsv", "w") as f:
235 f.write("name\tshard\tdtype\tshape\tbegin\tend\n")
236 for i, rows in enumerate(shards):
237 for r in rows:
238 f.write("%s\t%s\t%s\t%s\t%d\t%d\n" % (r[0], sname[i], r[1], "x".join(str(d) for d in r[2]), r[3], r[4]))