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 / fwdref.py

137 lines · 5470 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Read-only pinned Flint referee for ops.om forward, not a runtime dependency.
3
4Usage: fwdref.py SRC SHARDS OUTPUT
5Header matches opref.py, op 8, T=2, then two token IDs, embeddings,
6for each of 49 layers: input norm, attention output, post-attention norm,
7MLP output, residual output. Finally final norm and all vocabulary logits.
8All tensors are contiguous little-endian f32. Weights stay BF16 on disk;
9reference computation is float32 on CPU. No sampling or generation is claimed.
10"""
11import hashlib
12import json
13import os
14import struct
15import sys
16
17import torch
18from safetensors import safe_open
19from transformers.models.flint import configuration_flint as cf
20from transformers.models.flint import modeling_flint as mf
21
22REF_SHA = "f0540832049f0d67eee9eadd2d8ed42e320388b6b3330e74c8821a5c4eac0c09"
23CFG_SHA = "849eee3068846081077a7568663355802c8c4eec3741d92cd578d222bd144d00"
24for path, pin in ((mf.__file__, REF_SHA), (cf.__file__, CFG_SHA)):
25 if hashlib.sha256(open(path, "rb").read()).hexdigest() != pin:
26 sys.exit("fwdref: reference source pin mismatch: " + path)
27if torch.__version__ != "2.14.0+cu130":
28 sys.exit("fwdref: torch pin mismatch: " + torch.__version__)
29torch.set_num_threads(1)
30torch.set_grad_enabled(False)
31torch.use_deterministic_algorithms(True)
32src, shards, output = sys.argv[1:4]
33cfg = cf.FlintConfig(**json.load(open(os.path.join(src, "config.json"))))
34cfg._attn_implementation = "eager"
35cfg._experts_implementation = "eager"
36wmap = json.load(open(os.path.join(src, "model.safetensors.index.json")))["weight_map"]
37handles = {}
38
39
40def shard(name):
41 f = wmap[name]
42 if f not in handles:
43 handles[f] = safe_open(os.path.join(shards, f), framework="pt")
44 return handles[f]
45
46
47def tensor(name):
48 t = shard(name).get_tensor(name)
49 assert t.dtype == torch.bfloat16, (name, t.dtype)
50 return t.float()
51
52
53def load(module, prefix, rename=None):
54 state = {k: tensor(prefix + (rename or {}).get(k, k)) for k in module.state_dict()}
55 module.load_state_dict(state, strict=True)
56 return module.float().eval()
57
58
59def norm(prefix):
60 return load(mf.FlintRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps), prefix)
61
62
63class Lazy:
64 def __init__(self, prefix, part):
65 self.prefix, self.part = prefix, part
66
67 def __getitem__(self, e):
68 p = self.prefix + "experts.%d." % int(e)
69 if self.part == "gate_up":
70 return torch.cat([tensor(p + "gate_proj.weight"), tensor(p + "up_proj.weight")], dim=0)
71 return tensor(p + "down_proj.weight")
72
73
74def sparse(prefix):
75 c = cf.FlintConfig(**cfg.to_dict())
76 c._experts_implementation = "eager"
77 c.num_experts = 1
78 ex = mf.FlintExperts(c).float()
79 del ex.gate_up_proj, ex.down_proj
80 ex.gate_up_proj, ex.down_proj = Lazy(prefix, "gate_up"), Lazy(prefix, "down")
81 ex.num_experts = cfg.num_experts
82 blk = mf.FlintSparseMoeBlock.__new__(mf.FlintSparseMoeBlock)
83 torch.nn.Module.__init__(blk)
84 blk.gate = load(mf.FlintTopKRouter(cfg), prefix + "gate.")
85 blk.experts = ex
86 blk.shared_expert = load(mf.FlintMLP(cfg, cfg.shared_expert_intermediate_size), prefix + "shared_expert.")
87 return blk
88
89
90def write(f, x):
91 f.write(x.detach().float().contiguous().numpy().astype("<f4").tobytes())
92
93
94ids = [1001, 8920]
95sl = shard("model.embed_tokens.weight").get_slice("model.embed_tokens.weight")
96x = torch.cat([sl[i:i + 1] for i in ids]).float().unsqueeze(0)
97pos = torch.arange(len(ids)).unsqueeze(0)
98rope = mf.FlintRotaryEmbedding(cfg)(x, pos)
99mask = torch.triu(torch.full((len(ids), len(ids)), torch.finfo(torch.float32).min), diagonal=1)[None, None]
100with open(output, "wb") as f:
101 f.write(struct.pack("<8I", 0x504F4C46, 8, 0, len(ids), 0, 0, 21400, 0))
102 f.write(struct.pack("<2I", *ids))
103 write(f, x)
104 for L in range(cfg.num_hidden_layers):
105 p = "model.layers.%d." % L
106 layer = mf.FlintDecoderLayer.__new__(mf.FlintDecoderLayer)
107 torch.nn.Module.__init__(layer)
108 layer.self_attn = load(mf.FlintAttention(cfg, L), p + "self_attn.", {"sinks": "softmax_offset"})
109 layer.input_layernorm = norm(p + "input_layernorm.")
110 layer.post_attention_layernorm = norm(p + "post_attention_layernorm.")
111 layer.mlp = load(mf.FlintMLP(cfg), p + "mlp.") if L < 2 else sparse(p + "mlp.")
112 layer.eval()
113 cap = {}
114
115 def capture(name):
116 def hook(module, args, out):
117 cap[name] = out[0] if isinstance(out, tuple) else out
118 return hook
119
120 for name in ("input_layernorm", "self_attn", "post_attention_layernorm", "mlp"):
121 getattr(layer, name).register_forward_hook(capture(name))
122 x = layer(x, attention_mask=mask, position_ids=pos, position_embeddings=rope, use_cache=False)
123 for name in ("input_layernorm", "self_attn", "post_attention_layernorm", "mlp"):
124 write(f, cap[name])
125 write(f, x)
126 print("fwdref layer", L, flush=True)
127 del layer, cap
128 x = norm("model.norm.")(x)
129 write(f, x)
130 name = "lm_head.weight"
131 sl = shard(name).get_slice(name)
132 # Stream the vocabulary in the same row chunks as Omega, never allocate all weights in f32.
133 for t in range(len(ids)):
134 for first in range(0, cfg.vocab_size, 2048):
135 w = sl[first:first + 2048].float()
136 write(f, torch.nn.functional.linear(x[0, t:t + 1], w))
137print("fwdref complete", hashlib.sha256(open(output, "rb").read()).hexdigest(), flush=True)