interplane.Get Omega
Read in your language

aien-train

AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.

Brought by drakestapleton

branch main Branches Tags History

aien-train / tests / omegallm / bf16-inference.py

102 lines · 5382 bytes Raw Blame History
1#!/usr/bin/env python3
2"""External BF16 decode oracle. Requires an already authorized GPU window."""
3import argparse
4import hashlib
5import json
6import os
7from pathlib import Path
8import re
9import struct
10import subprocess
11
12p = argparse.ArgumentParser(description=__doc__)
13p.add_argument('--candidate', type=Path, required=True)
14p.add_argument('--baseline', type=Path, required=True)
15p.add_argument('--compiler', type=Path, required=True)
16p.add_argument('--source', type=Path, required=True, help='candidate concatenated build source')
17p.add_argument('--checkpoint', type=Path, action='append', required=True)
18p.add_argument('--merges', type=Path, required=True)
19p.add_argument('--output', type=Path, required=True)
20a = p.parse_args()
21a.output.mkdir(parents=True, exist_ok=False)
22assert os.environ.get('SPARK_WINDOW'), 'authorized SPARK_WINDOW required'
23sha = lambda x: hashlib.sha256(x.read_bytes()).hexdigest()
24inputs = [a.candidate, a.baseline, a.compiler, a.source, a.merges] + a.checkpoint
25report = {'window': os.environ['SPARK_WINDOW'], 'verdict': 'RUNNING',
26 'inputs': {str(x.resolve()): sha(x) for x in inputs}, 'checks': []}
27def save():
28 (a.output/'result.json').write_text(json.dumps(report, indent=2)+'\n')
29save()
30def run(tag, binary, args, expected=0, data=None):
31 cmd = [str(binary.resolve()), *map(str,args)]
32 r = subprocess.run(cmd, input=data, capture_output=True, timeout=300)
33 (a.output/(tag+'.stdout')).write_bytes(r.stdout)
34 (a.output/(tag+'.stderr')).write_bytes(r.stderr)
35 report['checks'].append({'tag': tag, 'argv': cmd, 'exit': r.returncode,
36 'stdout_sha256': hashlib.sha256(r.stdout).hexdigest(),
37 'stderr_sha256': hashlib.sha256(r.stderr).hexdigest()})
38 save()
39 assert r.returncode in (expected if isinstance(expected, tuple) else (expected,)), (tag, r.returncode, expected)
40 return r.stdout
41def compare(tag, ck, prompt, mode, binary=None, expected=0):
42 out = run(tag, binary or a.candidate, ['gdbench',ck,250,prompt,a.merges,mode],expected)
43 lines = out.decode().splitlines()
44 points = [list(map(int,x.split()[1:])) for x in lines if x.startswith('GQ ')]
45 total = [list(map(int,x.split()[1:])) for x in lines if x.startswith('GDQ ')]
46 assert len(points) == 250 and len(total) == 1, ('incomplete-comparison',tag)
47 assert [x[0] for x in points] == list(range(250)), ('step-sequence',tag)
48 assert total[0][0] == 250
49 assert total[0][1] == sum(x[4] for x in points), ('difference-count',tag)
50 assert total[0][2] == max(x[5] for x in points), ('maximum-error',tag)
51 assert total[0][3] == sum(x[2]!=x[3] and x[6]>500000000 for x in points), ('divergence-count',tag)
52 if mode == 8:
53 assert total[0][2] <= 250000000 and total[0][3] == 0, ('BF16-accuracy',tag)
54 if mode == 2:
55 assert total[0][1:] == [0,0,0], ('f32-regression',tag)
56 return out
57def profile(tag, binary, ck):
58 out = run(tag,binary,['gdbench',ck,1,'Once upon a time',a.merges,7])
59 ids = [int(x.split()[1]) for x in out.decode().splitlines() if x.startswith('GP ')]
60 assert ids, ('missing-profile',tag)
61 return sum(27 <= i <= 36 for i in ids)
62try:
63 prompts = ['The Omega compiler reads a program and',
64 'Once upon a time, a small fox found a red ball.',
65 '1 2 3 4 5. The answer is',
66 'fn main to int ret 0 end. '+('The moon and stars were bright. '*45)]
67 for i,ck in enumerate(a.checkpoint):
68 for j,prompt in enumerate(prompts):
69 compare(f'bf16-{i}-{j}',ck,prompt,8)
70 compare(f'f32-{i}',ck,prompts[0],2)
71 layers = struct.unpack_from('<Q',ck.read_bytes()[:64],48)[0]
72 assert profile(f'profile-{i}',a.candidate,ck) == 3*layers, 'BF16-dispatch-coverage'
73 # Preserve pre-existing full-BF16 comparison and its failed tolerance outcome.
74 old = compare(f'old-baseline-{i}',ck,prompts[0],4,a.baseline,(0,42))
75 old_rc = report['checks'][-1]['exit']
76 now = compare(f'old-candidate-{i}',ck,prompts[0],4,a.candidate,old_rc)
77 assert old == now, 'legacy-mode-regression'
78 for binary,label in [(a.baseline,'base'),(a.candidate,'candidate')]:
79 run(f'empty-{i}-{label}',binary,['gdbench',ck,250,'',a.merges,2],2)
80 args = ['gsampb',ck,0,64,0,prompts[1],a.merges]
81 sample = run(f'sample-{i}-1',a.candidate,args)
82 assert sample and sample == run(f'sample-{i}-2',a.candidate,args), 'sample-repeatability'
83 # Disable every new BF16 selector in the actual compiled source. The profile
84 # oracle must detect the no-op implementation even though f32 meets tolerance.
85 source = a.source.read_bytes()
86 needle = b'put bfdec 0 1\n'
87 assert source.count(needle) == 3, 'mutant-selector-count'
88 mutant = source.replace(needle,b'put bfdec 0 0\n')
89 image = run('mutant-build',a.compiler,[],data=mutant)
90 path = a.output/'no-bf16'
91 path.write_bytes(image); path.chmod(0o700)
92 assert profile('mutant-profile',path,a.checkpoint[0]) == 0, 'no-op-control-not-exercised'
93 for x in inputs:
94 assert sha(x) == report['inputs'][str(x.resolve())], ('input-changed',str(x))
95 report['verdict']='PASS'
96 print('BF16_INFERENCE PASS',len(report['checks']),'checks',flush=True)
97except BaseException as e:
98 report['verdict']='FAIL'
99 report['error']=repr(e)
100 raise
101finally:
102 save()