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 / fwdref.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Read-only pinned Flint referee for ops.om forward, not a runtime dependency. |
| 3 | |
| 4 | Usage: fwdref.py SRC SHARDS OUTPUT |
| 5 | Header matches opref.py, op 8, T=2, then two token IDs, embeddings, |
| 6 | for each of 49 layers: input norm, attention output, post-attention norm, |
| 7 | MLP output, residual output. Finally final norm and all vocabulary logits. |
| 8 | All tensors are contiguous little-endian f32. Weights stay BF16 on disk; |
| 9 | reference computation is float32 on CPU. No sampling or generation is claimed. |
| 10 | """ |
| 11 | import hashlib |
| 12 | import json |
| 13 | import os |
| 14 | import struct |
| 15 | import sys |
| 16 | |
| 17 | import torch |
| 18 | from safetensors import safe_open |
| 19 | from transformers.models.flint import configuration_flint as cf |
| 20 | from transformers.models.flint import modeling_flint as mf |
| 21 | |
| 22 | REF_SHA = "f0540832049f0d67eee9eadd2d8ed42e320388b6b3330e74c8821a5c4eac0c09" |
| 23 | CFG_SHA = "849eee3068846081077a7568663355802c8c4eec3741d92cd578d222bd144d00" |
| 24 | for 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) |
| 27 | if torch.__version__ != "2.14.0+cu130": |
| 28 | sys.exit("fwdref: torch pin mismatch: " + torch.__version__) |
| 29 | torch.set_num_threads(1) |
| 30 | torch.set_grad_enabled(False) |
| 31 | torch.use_deterministic_algorithms(True) |
| 32 | src, shards, output = sys.argv[1:4] |
| 33 | cfg = cf.FlintConfig(**json.load(open(os.path.join(src, "config.json")))) |
| 34 | cfg._attn_implementation = "eager" |
| 35 | cfg._experts_implementation = "eager" |
| 36 | wmap = json.load(open(os.path.join(src, "model.safetensors.index.json")))["weight_map"] |
| 37 | handles = {} |
| 38 | |
| 39 | |
| 40 | def 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 | |
| 47 | def tensor(name): |
| 48 | t = shard(name).get_tensor(name) |
| 49 | assert t.dtype == torch.bfloat16, (name, t.dtype) |
| 50 | return t.float() |
| 51 | |
| 52 | |
| 53 | def 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 | |
| 59 | def norm(prefix): |
| 60 | return load(mf.FlintRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps), prefix) |
| 61 | |
| 62 | |
| 63 | class 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 | |
| 74 | def 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 | |
| 90 | def write(f, x): |
| 91 | f.write(x.detach().float().contiguous().numpy().astype("<f4").tobytes()) |
| 92 | |
| 93 | |
| 94 | ids = [1001, 8920] |
| 95 | sl = shard("model.embed_tokens.weight").get_slice("model.embed_tokens.weight") |
| 96 | x = torch.cat([sl[i:i + 1] for i in ids]).float().unsqueeze(0) |
| 97 | pos = torch.arange(len(ids)).unsqueeze(0) |
| 98 | rope = mf.FlintRotaryEmbedding(cfg)(x, pos) |
| 99 | mask = torch.triu(torch.full((len(ids), len(ids)), torch.finfo(torch.float32).min), diagonal=1)[None, None] |
| 100 | with 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)) |
| 137 | print("fwdref complete", hashlib.sha256(open(output, "rb").read()).hexdigest(), flush=True) |