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 / linear / verify.py

280 lines · 11818 bytes Raw Blame History
1"""External numerical oracle and straight-line warp interpreter for the emitted ISA."""
2import argparse
3import hashlib
4import json
5import os
6import re
7import struct
8import subprocess
9import tempfile
10from pathlib import Path
11
12import numpy as np
13
14ROOT = Path.home() / "work/specialist-transfer-948"
15U = np.uint32
16F = np.float32
17
18
19def digest(data):
20 return hashlib.sha256(data).hexdigest()
21
22
23def decode(byte):
24 sign = -1 if byte & 128 else 1
25 e, f = (byte >> 3) & 15, byte & 7
26 if e == 15 and f == 7:
27 return np.copysign(np.nan, sign)
28 return sign * (f / 512 if e == 0 else (1 + f / 8) * 2 ** (e - 7))
29
30
31def bf(raw):
32 return (np.frombuffer(raw, '<u2').astype(U) << 16).view(F)
33
34
35def unpack_program(binary, mode):
36 raw = subprocess.check_output([binary, mode])
37 with tempfile.NamedTemporaryFile() as f:
38 f.write(raw)
39 f.flush()
40 listing = subprocess.check_output(['nvdisasm', '-b', 'SM121', f.name], text=True)
41 print(mode, 'instruction bytes sha256', digest(raw))
42 program = []
43 for pc, inst in re.findall(r'/\*([0-9a-f]+)\*/\s+([^;]+);', listing):
44 assert int(pc, 16) == len(program) * 16
45 program.append(re.findall(r'@!?P0|[\w.]+', inst))
46 assert len(program) * 16 == len(raw)
47 return program
48
49
50def simulate(program, header, spans, table):
51 """Vectorize across all rows and lanes. Separate allocations have unmapped gaps."""
52 fmt, m, k, _, sc = header[:5]
53 addresses = [0x100000020 + (i << 33) for i in range(5)]
54 output = np.full(m, 0x7fa12345, U)
55 stores = 0
56 memories = dict(zip(addresses, [*spans, output, table]))
57 cb = dict(zip(range(896, 936, 8), addresses))
58 cb.update({936: k, 940: k * (2 - fmt), 944: sc})
59 lanes = np.arange(32, dtype=U)[None, :]
60 rows = np.arange(m, dtype=U)[:, None]
61 regs = {'RZ': U(0)}
62 pc = 0
63
64 def val(token):
65 return regs[token] if token in regs else U(int(token, 0))
66
67 def mem(addr, width):
68 for base, buf in memories.items():
69 if buf is None or not np.all(addr >= base):
70 continue
71 ix = addr - base
72 if np.all(ix + width <= len(memoryview(buf).cast('B'))):
73 assert np.all(ix % width == 0)
74 return np.frombuffer(buf, dtype=f'<u{width}')[(ix // width).astype(int)]
75 raise AssertionError('unmapped device read')
76
77 while True:
78 op, *a = program[pc]
79 pc += 1
80 d = a[0] if a else None
81 if op == 'S2R':
82 regs[d] = {'SR_TID.X': lanes, 'SR_CTAID.X': rows}[a[1]]
83 elif op == 'LDCU.64':
84 assert a == ['UR4', 'c', '0x0', '0x358']
85 elif op.startswith('LDC'):
86 regs[d] = np.uint64(cb[int(a[-1], 0)]) if op == 'LDC.64' else U(cb[int(a[-1], 0)])
87 elif op == 'IMAD.WIDE.U32':
88 regs[d] = np.uint64(val(a[1])) * np.uint64(val(a[2])) + np.uint64(val(a[3]))
89 elif op.startswith('IMAD'):
90 regs[d] = U(val(a[1])) * U(val(a[2])) + U(val(a[3]))
91 elif op == 'SHF.R.U32.HI':
92 assert a[1] == 'RZ'
93 regs[d] = U(val(a[3])) >> val(a[2])
94 elif op == 'MOV':
95 regs[d] = val(a[1])
96 elif op.startswith('LDG.E'):
97 assert a[1:3] == ['desc', 'UR4']
98 width = {'LDG.E': 4, 'LDG.E.U8': 1, 'LDG.E.U16': 2}[op]
99 regs[d] = U(mem(val(a[3].split('.')[0]), width))
100 elif op in ('FFMA', 'FMUL', 'FADD'):
101 lhs, rhs = (val(t).view(F) for t in a[1:3])
102 if op == 'FFMA':
103 result = np.float64(lhs) * np.float64(rhs) + val(a[3]).view(F)
104 else:
105 result = lhs * rhs if op == 'FMUL' else lhs + rhs
106 regs[d] = F(result).view(U)
107 elif op == 'IADD3':
108 regs[d] = sum(U(val(t)) for t in a[-3:]).astype(U)
109 elif op.startswith('ISETP'):
110 lhs, rhs = val(a[2]), val(a[3])
111 pred = lhs < rhs if op == 'ISETP.LT.U32.AND' else lhs >= rhs
112 elif op == '@P0':
113 assert d == 'BRA' and (np.all(pred) or not np.any(pred))
114 if np.all(pred):
115 pc = int(a[1], 16) // 16
116 elif op == 'SHFL.BFLY':
117 assert a[-1] == '0x1f'
118 regs[a[1]] = regs[a[2]][:, np.arange(32) ^ int(a[3], 0)]
119 elif op == '@!P0':
120 assert a[:3] == ['STG.E', 'desc', 'UR4'] and np.array_equal(~pred, lanes == 0)
121 np.testing.assert_array_equal(regs[a[3].split('.')[0]][:, 0], addresses[3] + rows[:, 0] * np.uint64(4))
122 output[:] = regs[a[4]][:, 0]
123 stores += 1
124 elif op == 'EXIT':
125 assert stores == 1
126 return output.view(F)
127 else:
128 raise AssertionError((pc, op, a))
129
130
131def get_tensor(f, start, meta, nrows):
132 rows, k = meta['shape']
133 lo, hi = meta['data_offsets']
134 size = {'BF16': 2, 'F8_E4M3': 1}[meta['dtype']]
135 assert hi - lo == size * rows * k and nrows <= rows
136 f.seek(start + lo)
137 data = f.read(nrows * k * size)
138 assert len(data) == nrows * k * size
139 return data
140
141
142def examples():
143 for name, root, keys in [
144 ('q27', ROOT/'q27', ['linear_attn.in_proj_a', 'linear_attn.in_proj_qkv']),
145 ('q35', Path.home()/'models/qwen3.6-35b-a3b-fp8-95a723d0',
146 ['linear_attn.in_proj_b', 'mlp.shared_expert.up_proj', 'mlp.experts.7.down_proj']),
147 ]:
148 p = root/'layers-0.safetensors'
149 expected = dict(line.split()[::-1] for line in (ROOT/f'{name}-upstream.sha256').read_text().splitlines())
150 with p.open('rb') as f:
151 sha = hashlib.file_digest(f, 'sha256').hexdigest()
152 assert sha == expected[p.name]
153 f.seek(0)
154 start = 8 + struct.unpack('<Q', f.read(8))[0]
155 h = json.loads(f.read(start - 8))
156 print(name, p.name, 'sha256', sha)
157 for key in keys:
158 key = 'model.language_model.layers.0.' + key + '.weight'
159 meta = h[key]
160 rows, k = meta['shape']
161 m = min(129, rows)
162 weights = get_tensor(f, start, meta, m)
163 scale = b''
164 if meta['dtype'] == 'F8_E4M3':
165 sm = h[key+'_scale_inv']
166 assert sm['dtype'] == 'BF16' and sm['shape'] == [(rows+127)//128, (k+127)//128]
167 scale = get_tensor(f, start, sm, (m+127)//128)
168 yield name+' '+key, m, k, weights, scale
169 # Partial column scale block, partial row scale block, subnormals and both max finite values.
170 m, k = 131, 160
171 w = np.resize(np.array([i for i in range(256) if i & 127 != 127], np.uint8), m*k)
172 yield 'finite E4M3FN codes / ragged tiles', m, k, w.tobytes(), struct.pack('<4H', 0x3f80,0x3e80,0x4000,0xbf00)
173
174
175def check_shapes(exe, name, root):
176 hashes = ROOT/'engine/workers'/f'inventory-{name}-headers.sha256'
177 shapes = set()
178 for line in hashes.read_text().splitlines():
179 expected, path = line.split()
180 with (root/path).open('rb') as f:
181 raw = f.read(struct.unpack('<Q', f.read(8))[0])
182 assert digest(raw) == expected
183 tensors = json.loads(raw)
184 for key, t in tensors.items():
185 if not (key.startswith('model.language_model.') or key == 'lm_head.weight'):
186 continue
187 if not key.endswith('.weight') or len(t['shape']) != 2:
188 continue
189 m, k = t['shape']
190 fmt = {'BF16': 0, 'F8_E4M3': 1}[t['dtype']]
191 w0, w1 = t['data_offsets']
192 sr = sc = sb = 0
193 if fmt:
194 sm = tensors[key+'_scale_inv']
195 sr, sc = sm['shape']
196 s0, s1 = sm['data_offsets']
197 sb = s1-s0
198 assert sm['dtype'] == 'BF16'
199 shapes.add((fmt,m,k,sr,sc,w1-w0,sb,k*4,m*4))
200 assert shapes
201 for fields in sorted(shapes):
202 subprocess.run([exe,'s'],input=struct.pack('<9Q',*fields),check=True)
203 print(name, 'distinct admitted header geometries', len(shapes), sorted(x[:3] for x in shapes))
204
205
206def check_grant(expected):
207 root = Path.home()/'yardsticks/windows'
208 if (not expected or Path(expected).name != expected or
209 os.getenv('SPARK_WINDOW') != expected or
210 os.getenv('SPARK_WINDOW_DIR') != str(root/expected) or
211 os.getenv('AIEN_GB10_LOCK_HELD') != '1' or
212 (root/'OPEN').read_text().strip() != expected):
213 raise SystemExit('GPU run requires the owning current spark-window run environment')
214 record = json.loads((root/expected/'open.json').read_text())
215 if record['window_id'] != expected or record['gb10'] not in ('exclusive','shared'):
216 raise SystemExit('FIFO grant does not cover GB10')
217
218
219def main():
220 parser = argparse.ArgumentParser()
221 parser.add_argument('binary', type=Path)
222 parser.add_argument('--gpu', metavar='OWNED_WINDOW_ID', help='run inside the owning FIFO grant')
223 args = parser.parse_args()
224 if args.gpu:
225 check_grant(args.gpu)
226 exe = str(args.binary.resolve())
227 programs = [unpack_program(exe, mode) for mode in 'bf']
228 table = subprocess.check_output([exe, 't'])
229 oracle_table = np.array([decode(i) for i in range(256)], dtype=F)
230 np.testing.assert_array_equal(np.frombuffer(table, '<u4'), oracle_table.view(U))
231 check_shapes(exe, 'q27', ROOT/'q27')
232 check_shapes(exe, 'q35', Path.home()/'models/qwen3.6-35b-a3b-fp8-95a723d0')
233 for name, m, k, weights, scale in examples():
234 fmt = int(bool(scale))
235 x = (((np.arange(k) * 37 + 11) % 127 - 63) / 64).astype('<f4')
236 sr, sc = ((m+127)//128, (k+127)//128) if fmt else (0,0)
237 header = [fmt,m,k,sr,sc,len(weights),len(scale),x.nbytes,m*4]
238 payload = weights + scale + x.tobytes()
239 packet = struct.pack('<9Q', *header) + payload
240 if fmt:
241 grid = bf(scale).reshape(sr, sc)
242 w = oracle_table[np.frombuffer(weights, 'u1')].reshape(m,k)
243 w *= grid[np.arange(m)[:,None]//128, np.arange(k)//128]
244 else:
245 w = bf(weights).reshape(m,k)
246 terms = w.astype('d') * x
247 truth = terms.sum(axis=1)
248 for route in ['reference','ISA'] + (['GPU'] if args.gpu else []):
249 if route == 'ISA':
250 y = simulate(programs[fmt], header, [weights,scale,x], table)
251 else:
252 if route == 'GPU':
253 check_grant(args.gpu)
254 raw = subprocess.check_output([exe, 'r' if route == 'reference' else 'g'], input=packet)
255 y = np.frombuffer(raw, '<f4')
256 assert y.shape == (m,) and np.isfinite(y).all()
257 error = abs(y - truth)
258 bound = (np.finfo(F).eps * (k//32 + 6) * abs(terms).sum(axis=1) + 1e-30)
259 assert np.all(error <= bound)
260 print(name, route, (m,k), 'max_abs', error.max(), 'input',digest(packet),'output',digest(y.tobytes()))
261 if fmt:
262 damaged = bytes(len(scale))
263 y = simulate(programs[fmt], header, [weights,damaged,x], table)
264 assert np.any(abs(y - truth) > bound)
265 if sr != sc:
266 bad = header.copy()
267 bad[3:5] = [sc, sr]
268 assert subprocess.run([exe,'s'],input=struct.pack('<9Q',*bad)).returncode == 2
269 for index in range(9):
270 bad = header.copy()
271 bad[index] += 1 if index else 2
272 rc = subprocess.run([exe, 'r'], input=struct.pack('<9Q', *bad)+payload, stdout=subprocess.DEVNULL).returncode
273 assert rc == 2, (name,index,rc)
274 for bad in [packet[:-1], packet+b'X', packet[:71]]:
275 assert subprocess.run([exe,'r'],input=bad,stdout=subprocess.DEVNULL).returncode == 2
276 print('PASS oracle, instruction simulation, all decode bits, malformed fields, short and trailing input')
277
278
279if __name__ == '__main__':
280 main()