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 / qwen-native / blocks / tests / check.py

198 lines · 9050 bytes Raw Blame History
1"""CPU-only numerical gate. Run with python3 tests/check.py /path/to/seed/out/omc."""
2import hashlib
3from pathlib import Path
4import struct
5import subprocess
6import sys
7import tempfile
8
9import numpy as np
10
11ROOT = Path(__file__).resolve().parents[1]
12PIN = "34d611ca0415eab1728d3234911d90e74af17ba9ab0c581d559f48274d7ca6d3"
13F = np.float32
14TOL = 0.00004
15
16
17def sigmoid(x):
18 return 1 / (1 + np.exp(-x))
19
20
21def bf16(x):
22 raw = x.astype("<f4").view("<u4")
23 return ((raw + 32767 + ((raw >> 16) & 1)) & 0xffff0000).view("<f4")
24
25
26def gdn_ref(model, x, w, hist, state):
27 heads = {27: 48, 35: 32}[model]
28 width = 4096 + heads * 128
29 hist.append(x[:width].astype(float))
30 taps = w[:4 * width].reshape(width, 4)
31 conv = (np.stack(hist[-4:], axis=1) * taps).sum(axis=1)
32 q, k, v = np.split(conv * sigmoid(conv), [2048, 4096])
33 def unit(row):
34 row = row.reshape(16, 128)
35 return np.repeat(row / np.sqrt((row**2).sum(1, keepdims=True) + 1e-6),
36 heads // 16, axis=0)
37 q, k = unit(q) / np.sqrt(128), unit(k)
38 z = x[width:width + heads * 128].astype(float).reshape(heads, 128)
39 a, b = x[width + z.size:width + z.size + heads * 2].reshape(-1, 2).astype(float).T
40 decay = np.exp(-np.exp(w[40960:40960 + heads].astype(float)) *
41 np.logaddexp(0, a + w[41008:41008 + heads]))
42 state *= decay[:, None, None]
43 innovation = (v.reshape(heads, 128) - np.einsum("hk,hkv->hv", k, state)) * sigmoid(b[:, None])
44 state += k[:, :, None] * innovation[:, None, :]
45 out = np.einsum("hk,hkv->hv", q, state)
46 return (out / np.sqrt((out**2).mean(1, keepdims=True) + 1e-6) *
47 w[41056:] * z * sigmoid(z)).ravel()
48
49
50def att_ref(model, pos, x, w, keys, values):
51 nh, nk = {27: (24, 4), 35: (16, 2)}[model]
52 q, gate = x[:nh * 512].reshape(nh, 2, 256).transpose(1, 0, 2)
53 k, v = x[nh * 512:nh * 512 + nk * 512].reshape(2, nk, 256)
54 angles = pos * 10000000.0 ** (-np.arange(32) / 32)
55 def rotate(row, weight):
56 # Preserve sequential f32 sum before the discontinuous BF16 cache rounding.
57 ss = np.cumsum(row * row, axis=1)[:, -1:]
58 row = row * (F(1) / np.sqrt(ss / F(256) + F(1e-6))) * (F(1) + weight)
59 a, b = row[:, :32].copy(), row[:, 32:64].copy()
60 c, s = np.cos(angles).astype(F), np.sin(angles).astype(F)
61 row[:, :32], row[:, 32:64] = a * c - b * s, a * s + b * c
62 return row
63 keys.append(bf16(rotate(k, w[256:])))
64 values.append(bf16(v))
65 query = rotate(q, w[:256]).astype(float)
66 logits = np.einsum("hd,thd->ht", query, np.repeat(keys, nh // nk, axis=1)) / 16
67 probs = np.exp(logits - logits.max(1, keepdims=True))
68 probs /= probs.sum(1, keepdims=True)
69 return (np.einsum("ht,thd->hd", probs, np.repeat(values, nh // nk, axis=1)) *
70 sigmoid(gate.astype(float))).ravel()
71
72
73def att_samples(keys, values):
74 j = np.arange(64)
75 h = j % keys[-1].shape[0]
76 d = (j * 19) % 256
77 return np.r_[keys[-1][h, d], values[-1][h, d]]
78
79
80def fixtures():
81 rng = np.random.default_rng(949)
82 records, expected = [], []
83 for model, last in [(27, 63), (35, 39)]:
84 heads = 48 if model == 27 else 32
85 width = 4096 + heads * 128
86 layers = [0, 3, last - 1, last]
87 weights = {l: rng.normal(0, 0.45, 512 if l % 4 == 3 else 41184).astype(F) for l in layers}
88 for l in layers[::2]:
89 weights[l][41056:] += 1
90 # Restart the same slots at zero with new inputs after the first sequence.
91 for length in (6, 2):
92 states = {l: ([np.zeros(width)] * 3, np.zeros((heads, 128, 128)))
93 if l % 4 != 3 else ([], []) for l in layers}
94 for pos in range(length):
95 for l in layers:
96 attn = l % 4 == 3
97 x = rng.normal(0, 0.7, 14336 if attn else 16480).astype("<f4")
98 w = weights[l]
99 if attn:
100 want = att_ref(model, pos, x, w, *states[l])
101 else:
102 want = gdn_ref(model, x, w, *states[l])
103 records.append(struct.pack("<III", model, l, pos) + x.tobytes() + w.tobytes())
104 if attn:
105 samples = att_samples(*states[l])
106 else:
107 hist, state = states[l]
108 j = np.arange(64)
109 samples = np.r_[state[j % heads, (j * 23) % 128, (j * 37 + 1) % 128],
110 np.array(hist[-3:])[j % 3, (j * 7919) % width]]
111 expected.append((model, l, pos, want, samples))
112 # Fresh layer 59 still has a zero-filled cache. Seed the cursor in the probe to
113 # exercise the last writable row without recomputing an 8191-token prefix.
114 model, l, pos = 27, 59, 8191
115 x = rng.normal(0, 0.7, 14336).astype(F)
116 w = rng.normal(0, 0.45, 512).astype(F)
117 keys, values = [], []
118 att_ref(model, pos, x, w, keys, values)
119 nh = 24
120 qg = x[:nh * 512].reshape(nh, 2, 256)
121 q = qg[:, 0, :].astype(float)
122 q *= (1 + w[:256]) / np.sqrt((q**2).mean(1, keepdims=True) + 1e-6)
123 angle = pos * 1e7 ** (-np.arange(32) / 32)
124 rot = (q[:, :32] + 1j * q[:, 32:64]) * np.exp(1j * angle)
125 q[:, :32], q[:, 32:64] = rot.real, rot.imag
126 score = (q * np.repeat(keys[0], 6, axis=0)).sum(1) / 16
127 prob = (np.exp(score) / (8191 + np.exp(score)))[:, None]
128 want = (prob * np.repeat(values[0], 6, axis=0) * sigmoid(qg[:, 1, :])).ravel()
129 records.append(struct.pack("<III", model, l, pos) + x.tobytes() + w.tobytes())
130 expected.append((model, l, pos, want, att_samples(keys, values)))
131 return struct.pack("<I", len(records)) + b"".join(records), expected
132
133
134def compile_unit(compiler, path, unit):
135 path.write_bytes(subprocess.run([compiler], input=unit.encode(), stdout=subprocess.PIPE,
136 check=True).stdout)
137 path.chmod(0o700)
138
139
140def compare(path, data, expected):
141 raw = subprocess.run([path], input=data, stdout=subprocess.PIPE, check=True).stdout
142 outputs = np.frombuffer(raw, "<f4").reshape(len(expected), 2, 6144)
143 worst = {}
144 for (got, stored), (model, layer, pos, want, samples) in zip(outputs, expected):
145 key = (model, "attention" if layer % 4 == 3 else "delta")
146 if not np.all(np.isfinite(got)) or np.any(got[len(want):] != 0):
147 raise AssertionError((key, layer, pos, "nonfinite or tail write"))
148 err = np.max(np.abs(got[:len(want)] - want))
149 state_err = np.max(np.abs(stored[:128] - samples))
150 if not np.isfinite(state_err):
151 raise AssertionError((key, "nonfinite state"))
152 state_key = (model, key[1] + " state")
153 worst[state_key] = max(worst.get(state_key, 0), state_err)
154 worst[key] = max(worst.get(key, 0), err)
155 return worst
156
157
158def main():
159 compiler = Path(sys.argv[1]).resolve()
160 if hashlib.sha256(compiler.read_bytes()).hexdigest() != PIN:
161 raise ValueError("seed compiler digest differs")
162 unit = "om2\n" + "\n".join((ROOT / name).read_text() for name in
163 ["math.om", "gdn.om", "attention.om", "tests/probe.om"])
164 data, expected = fixtures()
165 with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
166 path = Path(tmp) / "probe"
167 compile_unit(compiler, path, unit)
168 baseline = compare(path, data, expected)
169 print("max absolute error", baseline, flush=True)
170 if max(baseline.values()) >= TOL:
171 raise AssertionError(baseline)
172 for label, old, new in [
173 ("reverse taps", "get w add tap j", "get w add tap sub 3 j"),
174 ("swap a/b", "get x ab rate bias", "get x add ab 1 rate bias"),
175 ("discard prior state", "if not resetting\nsv =", "if false\nsv ="),
176 ("rotate wrong partner", "b = get qa_row add i 32", "b = get qa_row add i 128"),
177 ("truncate BF16", "shr add bits add 32767 and shr bits 16 1 16", "shr bits 16"),
178 ("use SiLU full gate", "mul get qa_row j f32 qb_sig", "mul gate mul get qa_row j f32 qb_sig"),
179 ]:
180 if unit.count(old) != 1:
181 raise AssertionError(label)
182 compile_unit(compiler, path, unit.replace(old, new))
183 error = max(compare(path, data, expected).values())
184 if error <= TOL:
185 raise AssertionError(f"survived: {label}")
186 print("rejected", label, error, flush=True)
187 compile_unit(compiler, path, unit)
188 for m, l, p in [(35, 39, 8192), (27, 64, 0), (35, 40, 0), (27, 0, 1), (38, 3, 0)]:
189 size = (14336 + 512) if l % 4 == 3 else (16480 + 41184)
190 bad = struct.pack("<IIII", 1, m, l, p) + bytes(size * 4)
191 run = subprocess.run([path], input=bad, stdout=subprocess.PIPE)
192 if run.returncode != 105 or run.stdout:
193 raise AssertionError((m, l, p, run.returncode))
194 print("invalid model, layer, sequence and position refused")
195
196
197if __name__ == "__main__":
198 main()