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
aien-sovereign-core-mv / om / flint / test / opref.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Flint forward-operator fixtures. TEST REFEREE ONLY, never an implementation dependency. |
| 3 | |
| 4 | Runs the pinned reference's own modules (transformers models/flint/modeling_flint.py and |
| 5 | configuration_flint.py, the files whose sha256 are REF_SHA and CFG_SHA below) in float32 on small |
| 6 | deterministic inputs drawn from the real BF16 weights of named layers, and writes one binary fixture |
| 7 | per operator for om/flint/ops.om to recompute. Before the q/k/v and attention fixtures it measures |
| 8 | the reference's RoPE powf, cosf and sinf against float64 and exits if any call is off by more than |
| 9 | ops.om's FULP ulps, the libm budget the RoPE bound assumes. |
| 10 | |
| 11 | Usage: opref.py SRC SHARDS OUT |
| 12 | SRC the pinned source tree (config.json, model.safetensors.index.json) |
| 13 | SHARDS the 15 downloaded shards |
| 14 | OUT directory for the fixtures (created) |
| 15 | |
| 16 | Fixture layout, all little-endian: 8 u32 header words, magic 0x504F4C46, op, layer, T, S, aux, |
| 17 | torch version (major * 10000 + minor * 100 + patch, so a torch change moves the fixtures sha256 that |
| 18 | check.sh pins), 0, then the op's arrays (u32 index arrays, f32 everything else) in the order ops.om |
| 19 | reads them: |
| 20 | 1 rmsnorm T rows, aux 0 input_layernorm / 1 post_attention_layernorm: x[T,2048] y[T,2048] |
| 21 | 2 qkv S rows: pos[S] x[S,2048] q[S,32,128] k[S,4,128] v[S,4,128] (after q/k norm and RoPE) |
| 22 | 3 attn S query rows of T keys: pos[S] q[S,4096] k[T,512] v[T,512] o[S,4096] y[S,2048] |
| 23 | 4 router T rows: x[T,2048] logits[T,256] idx[T,6] w[T,6] |
| 24 | 5 shared T rows: x[T,2048] y[T,2048] |
| 25 | 6 expert T rows, aux expert id: x[T,2048] y[T,2048] (routing weight 1) |
| 26 | 7 moe T rows: x[T,2048] y[T,2048] (FlintSparseMoeBlock output) |
| 27 | Inputs are embedding rows of deterministic token ids passed through the named layer's real RMSNorm. |
| 28 | """ |
| 29 | import hashlib |
| 30 | import json |
| 31 | import os |
| 32 | import re |
| 33 | import struct |
| 34 | import sys |
| 35 | |
| 36 | import torch |
| 37 | from safetensors import safe_open |
| 38 | |
| 39 | from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask |
| 40 | from transformers.models.flint import modeling_flint as mf |
| 41 | from transformers.models.flint import configuration_flint as cf |
| 42 | from transformers.models.flint.configuration_flint import FlintConfig |
| 43 | |
| 44 | REF_SHA = "f0540832049f0d67eee9eadd2d8ed42e320388b6b3330e74c8821a5c4eac0c09" # transformers a672eb5f |
| 45 | CFG_SHA = "849eee3068846081077a7568663355802c8c4eec3741d92cd578d222bd144d00" # transformers a672eb5f |
| 46 | MAGIC = 0x504F4C46 |
| 47 | TORCH = [int(v) for v in torch.__version__.split("+")[0].split(".")[:3]] |
| 48 | TORCH_WORD = TORCH[0] * 10000 + TORCH[1] * 100 + TORCH[2] |
| 49 | torch.set_num_threads(1) |
| 50 | torch.use_deterministic_algorithms(True) |
| 51 | torch.set_grad_enabled(False) |
| 52 | |
| 53 | src, shards, out = sys.argv[1:4] |
| 54 | os.makedirs(out, exist_ok=True) |
| 55 | for ref_file, pin in ((mf.__file__, REF_SHA), (cf.__file__, CFG_SHA)): |
| 56 | got = hashlib.sha256(open(ref_file, "rb").read()).hexdigest() |
| 57 | if got != pin: |
| 58 | sys.exit("opref: %s sha256 %s, pinned %s" % (ref_file, got, pin)) |
| 59 | |
| 60 | cfg = FlintConfig(**json.load(open(os.path.join(src, "config.json")))) |
| 61 | cfg._attn_implementation = "eager" |
| 62 | cfg._experts_implementation = "eager" |
| 63 | wmap = json.load(open(os.path.join(src, "model.safetensors.index.json")))["weight_map"] |
| 64 | handles = {} |
| 65 | |
| 66 | |
| 67 | def shard(name): |
| 68 | f = wmap[name] |
| 69 | if f not in handles: |
| 70 | handles[f] = safe_open(os.path.join(shards, f), framework="pt") |
| 71 | return handles[f] |
| 72 | |
| 73 | |
| 74 | def tensor(name): |
| 75 | t = shard(name).get_tensor(name) |
| 76 | assert t.dtype == torch.bfloat16, (name, t.dtype) |
| 77 | return t.float() |
| 78 | |
| 79 | |
| 80 | def load(module, prefix, rename=None): |
| 81 | state = {} |
| 82 | for k in module.state_dict(): |
| 83 | ck = (rename or {}).get(k, k) |
| 84 | state[k] = tensor(prefix + ck) |
| 85 | module.load_state_dict(state, strict=True) |
| 86 | return module.float().eval() |
| 87 | |
| 88 | |
| 89 | def embed_rows(ids): |
| 90 | name = "model.embed_tokens.weight" |
| 91 | sl = shard(name).get_slice(name) |
| 92 | return torch.cat([sl[i:i + 1] for i in ids]).float() |
| 93 | |
| 94 | |
| 95 | def ids(n, salt): |
| 96 | return [1000 + (salt + 7919 * i) % 90000 for i in range(n)] |
| 97 | |
| 98 | |
| 99 | def norm(layer, kind, x): |
| 100 | m = mf.FlintRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) |
| 101 | load(m, "model.layers.%d.%s." % (layer, kind)) |
| 102 | return m(x) |
| 103 | |
| 104 | |
| 105 | def f32(a): |
| 106 | a = a.detach().to(torch.float32).contiguous().reshape(-1) |
| 107 | return a.numpy().astype("<f4").tobytes() |
| 108 | |
| 109 | |
| 110 | def u32(a): |
| 111 | return struct.pack("<%dI" % len(a), *[int(v) for v in a]) |
| 112 | |
| 113 | |
| 114 | def write(fname, op, layer, t, s, aux, *parts): |
| 115 | with open(os.path.join(out, fname), "wb") as f: |
| 116 | f.write(struct.pack("<8I", MAGIC, op, layer, t, s, aux, TORCH_WORD, 0)) |
| 117 | for p in parts: |
| 118 | f.write(p) |
| 119 | |
| 120 | |
| 121 | # 1 RMSNorm, layer 2 input_layernorm, on raw embedding rows |
| 122 | x = embed_rows(ids(16, 1)) |
| 123 | write("rmsnorm.bin", 1, 2, 16, 0, 0, f32(x), f32(norm(2, "input_layernorm", x))) |
| 124 | |
| 125 | # 2/3 attention: layer 2 (sliding window 513, rotary) and layer 5 (full attention, no rotary) |
| 126 | T = 520 |
| 127 | SEL = [0, 1, 2, 255, 511, 512, 513, 519] |
| 128 | pos_ids = torch.arange(T).unsqueeze(0) |
| 129 | cap = {} |
| 130 | orig_eager = mf.eager_attention_forward |
| 131 | |
| 132 | |
| 133 | def capture(module, query, key, value, attention_mask, scaling, **kw): |
| 134 | o, w = orig_eager(module, query, key, value, attention_mask, scaling, **kw) |
| 135 | cap.update(q=query, k=key, v=value, mask=attention_mask, o=o, scaling=scaling) |
| 136 | return o, w |
| 137 | |
| 138 | |
| 139 | mf.eager_attention_forward = capture |
| 140 | rope = mf.FlintRotaryEmbedding(cfg) |
| 141 | |
| 142 | # ops.om bounds RoPE for FULP ulps per powf, cosf and sinf call; measure the reference's own calls |
| 143 | # against float64 and refuse to write fixtures if any exceeds that budget. |
| 144 | FULP = int(re.search(r"^const FULP ulong (\d+)$", |
| 145 | open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "ops.om")).read(), |
| 146 | re.M).group(1)) |
| 147 | |
| 148 | |
| 149 | def ulps(got, exact): |
| 150 | a = got.abs() |
| 151 | ulp = (torch.nextafter(a, torch.full_like(a, float("inf"))) - a).double() |
| 152 | return ((got.double() - exact).abs() / ulp).max().item() |
| 153 | |
| 154 | |
| 155 | theta = cfg.rope_parameters["rope_theta"] |
| 156 | expo = torch.arange(0, cfg.head_dim, 2, dtype=torch.float) / cfg.head_dim |
| 157 | pw = theta ** expo |
| 158 | assert torch.equal(1.0 / pw, rope.inv_freq), "inv_freq is 1 / theta ** (2i / d)" |
| 159 | cos, sin = rope(torch.zeros(1, T, 8), pos_ids) |
| 160 | ang = (pos_ids[..., None].float() * rope.inv_freq)[0] |
| 161 | libm = (ulps(pw, float(theta) ** expo.double()), ulps(cos[0, :, :64], ang.double().cos()), |
| 162 | ulps(sin[0, :, :64], ang.double().sin())) |
| 163 | if max(libm) > FULP: |
| 164 | sys.exit("opref: RoPE libm ulps pow %.3f cos %.3f sin %.3f exceed FULP %d" % (libm + (FULP,))) |
| 165 | |
| 166 | for layer in (2, 5): |
| 167 | kind = cfg.layer_types[layer] |
| 168 | assert kind == ("sliding_attention" if layer == 2 else "full_attention"), (layer, kind) |
| 169 | h = norm(layer, "input_layernorm", embed_rows(ids(T, 100 + layer))).unsqueeze(0) |
| 170 | mk = {"config": cfg, "inputs_embeds": h, "attention_mask": None, "past_key_values": None, |
| 171 | "position_ids": pos_ids} |
| 172 | mask = create_sliding_window_causal_mask(**mk) if layer == 2 else create_causal_mask(**mk) |
| 173 | allowed = torch.tril(torch.ones(T, T, dtype=torch.bool)) |
| 174 | if layer == 2: |
| 175 | allowed &= torch.arange(T)[None, :] > torch.arange(T)[:, None] - cfg.sliding_window |
| 176 | assert mask.shape == (1, 1, T, T) and torch.equal(mask[0, 0] == 0, allowed), "mask semantics" |
| 177 | att = mf.FlintAttention(cfg, layer) |
| 178 | load(att, "model.layers.%d.self_attn." % layer, {"sinks": "softmax_offset"}) |
| 179 | cap.clear() |
| 180 | y, _ = att(h, position_embeddings=rope(h, pos_ids), attention_mask=mask) |
| 181 | assert cap["scaling"] == cfg.head_dim ** -0.5 |
| 182 | q = cap["q"][0].transpose(0, 1) # [T, 32, 128] |
| 183 | k = cap["k"][0].transpose(0, 1) # [T, 4, 128] |
| 184 | v = cap["v"][0].transpose(0, 1) |
| 185 | o = cap["o"][0] # [T, 32, 128] after transpose(1, 2) |
| 186 | sel = torch.tensor(SEL) |
| 187 | write("qkv-%d.bin" % layer, 2, layer, 0, len(SEL), 0, u32(SEL), f32(h[0][sel]), f32(q[sel]), |
| 188 | f32(k[sel]), f32(v[sel])) |
| 189 | write("attn-%d.bin" % layer, 3, layer, T, len(SEL), 0, u32(SEL), f32(q[sel]), f32(k), f32(v), |
| 190 | f32(o[sel]), f32(y[0][sel])) |
| 191 | mf.eager_attention_forward = orig_eager |
| 192 | |
| 193 | # 4 router, layer 24 |
| 194 | L = 24 |
| 195 | pre = "model.layers.%d.mlp." % L |
| 196 | x = norm(L, "post_attention_layernorm", embed_rows(ids(64, 300))) |
| 197 | router = load(mf.FlintTopKRouter(cfg), pre + "gate.") |
| 198 | logits, w, idx = router(x) |
| 199 | write("router.bin", 4, L, 64, 0, 0, f32(x), f32(logits), u32(idx.reshape(-1).tolist()), f32(w)) |
| 200 | |
| 201 | # comparator control: token 0 expects its rank-7 expert in place of its rank-6 one (clear margin) |
| 202 | top7 = torch.topk(logits[0].sigmoid(), 7).indices |
| 203 | bad = idx.clone() |
| 204 | bad[0, 5] = top7[6] |
| 205 | write("router-swap.bin", 4, L, 64, 0, 0, f32(x), f32(logits), u32(bad.reshape(-1).tolist()), f32(w)) |
| 206 | |
| 207 | # near tie: move token 0 along W[b] - W[a] until its rank-6 (a) and rank-7 (b) logits agree |
| 208 | W = router.weight.double() |
| 209 | x0 = x[0].double() |
| 210 | lg = W @ x0 |
| 211 | order = torch.argsort(lg, descending=True) |
| 212 | a, b = order[5], order[6] |
| 213 | d = W[b] - W[a] |
| 214 | xt = (x0 + (lg[a] - lg[b]) / (d @ d) * d).float().unsqueeze(0) |
| 215 | lt, wt, it = router(xt) |
| 216 | write("router-tie.bin", 4, L, 1, 0, 0, f32(xt), f32(lt), u32(it.reshape(-1).tolist()), f32(wt)) |
| 217 | |
| 218 | # 5 shared expert, layer 24 (FlintMLP at shared_expert_intermediate_size) |
| 219 | x4 = x[:4] |
| 220 | sh = load(mf.FlintMLP(cfg, intermediate_size=cfg.shared_expert_intermediate_size), pre + "shared_expert.") |
| 221 | write("shared.bin", 5, L, 4, 0, 0, f32(x4), f32(sh(x4))) |
| 222 | |
| 223 | |
| 224 | class Lazy: |
| 225 | """Expert-indexed view of the checkpoint: experts[e] fuses gate then up, like the conversion map.""" |
| 226 | |
| 227 | def __init__(self, part): |
| 228 | self.part = part |
| 229 | |
| 230 | def __getitem__(self, e): |
| 231 | q = pre + "experts.%d." % int(e) |
| 232 | if self.part == "gate_up": |
| 233 | return torch.cat([tensor(q + "gate_proj.weight"), tensor(q + "up_proj.weight")], dim=0) |
| 234 | return tensor(q + "down_proj.weight") |
| 235 | |
| 236 | |
| 237 | def experts(): |
| 238 | c = FlintConfig(**cfg.to_dict()) |
| 239 | c._experts_implementation = "eager" |
| 240 | c.num_experts = 1 # placeholder parameters; the forward indexes the Lazy views below |
| 241 | ex = mf.FlintExperts(c).float() |
| 242 | del ex.gate_up_proj, ex.down_proj |
| 243 | ex.gate_up_proj, ex.down_proj = Lazy("gate_up"), Lazy("down") |
| 244 | ex.num_experts = cfg.num_experts |
| 245 | return ex |
| 246 | |
| 247 | |
| 248 | # 6 one routed expert MLP: the expert token 0 ranks first, weight 1 |
| 249 | e = int(idx[0, 0]) |
| 250 | ones = torch.ones(4, 1) |
| 251 | ye = experts()(x4, torch.full((4, 1), e, dtype=torch.long), ones) |
| 252 | write("expert.bin", 6, L, 4, 0, e, f32(x4), f32(ye)) |
| 253 | |
| 254 | # 7 the whole sparse MoE block: router, six routed experts, shared expert added without a gate |
| 255 | blk = mf.FlintSparseMoeBlock.__new__(mf.FlintSparseMoeBlock) |
| 256 | torch.nn.Module.__init__(blk) |
| 257 | blk.gate, blk.experts, blk.shared_expert = router, experts(), sh |
| 258 | write("moe.bin", 7, L, 4, 0, 0, f32(x4), f32(blk(x4.unsqueeze(0))[0])) |
| 259 | print("opref ok ref %s cfg %s torch %s expert %d tie %d/%d rope ulps pow %.3f cos %.3f sin %.3f of %d" |
| 260 | % ((REF_SHA[:16], CFG_SHA[:16], torch.__version__, e, int(a), int(b)) + libm + (FULP,))) |