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 / grow-check.py

212 lines · 11055 bytes Raw Blame History
1#!/usr/bin/env python3
2"""External host oracle for ollm grow; Python is never a product dependency.
3
4Usage: python3 tests/omegallm/grow-check.py BUILD_DIR OMC
5Runs product and reduced-bank cases, then requires each compiled mutation to fail.
6"""
7import hashlib
8import json
9import os
10import re
11from pathlib import Path
12import shutil
13import struct
14import subprocess
15import sys
16import tempfile
17
18import oracle as ref
19
20
21def run(binary, *args, expected=0):
22 p = subprocess.run([str(binary), *map(str, args)], capture_output=True, timeout=120)
23 if p.returncode != expected:
24 raise AssertionError((args[0], p.returncode, expected, p.stderr.decode(errors='replace')))
25 return p.stdout
26
27
28def check(binary, root):
29 root.mkdir()
30 train = root / 'train.txt'
31 held = root / 'held.txt'
32 train.write_bytes(b'abc abcd abcde\n' * 64)
33 held.write_bytes(b'bcde abc cab\n' * 32)
34 for fmt in (1, 2):
35 old, new = root / f'old{fmt}.ck', root / f'new{fmt}.ck'
36 # Small enough for a per-weight independent oracle, but crosses the bx banks at L=4.
37 run(binary, 'init', old, 256, 8, 16, 2, 32, 2, 2, 17, 12, 3000,
38 *([] if fmt == 1 else [2]))
39 run(binary, 'train', old, train, 3, 1)
40 src = ref.read_ck1(old)
41 src['params'][0] = -0.0 # exercise bit preservation, not merely float equality
42 old.write_bytes(ref.ck1_bytes(src))
43 before = old.read_bytes()
44 assert any(src['m']) and any(src['v']), 'fixture must have optimizer history'
45 out = run(binary, 'grow', old, new, 4, 12, 3000)
46 dst = ref.read_ck1(new)
47 assert out == f"G 2 4 {dst['P']}\n".encode()
48 assert old.read_bytes() == before, 'separate input modified'
49 assert dst['magic'] == src['magic'] and dst['G'] == src['G']
50 assert dst['c'] == dict(src['c'], L=4)
51 assert dst['seed'] == src['seed'] and dst['step'] == 0
52 assert dst['total'] == 12 and dst['lr'] == 0.003
53 assert not any(dst['m']) and not any(dst['v']), 'optimizer not reset'
54 source_tensors = dict((n, src['params'][o:o+r*c]) for n,o,r,c in ref.tensor_specs(src['c']))
55 initialized = ref.init_params(dst['c'], dst['seed'])
56 for name, off, rows, cols in ref.tensor_specs(dst['c']):
57 actual = dst['params'][off:off+rows*cols]
58 if name in source_tensors:
59 assert struct.pack('<%dd' % len(actual), *actual) == struct.pack('<%dd' % len(actual), *source_tensors[name]), ('learned tensor changed', name)
60 elif name.split('.')[0] in ('wo', 'w2'):
61 assert actual == [0.0] * (rows*cols), ('residual not silent', name)
62 else:
63 assert actual == initialized[off:off+rows*cols], ('initializer mismatch', name)
64 # Check the real binary's predictions, plus the separately implemented forward/gradient.
65 assert run(binary, 'eval', old, held, 4).split()[2:] == run(binary, 'eval', new, held, 4).split()[2:]
66 for seed, temp, prompt in [(1, 0, 'abc'), (7, 800, 'cab'), (11, 400, 'abc cab abc cab')]:
67 assert run(binary, 'sample', old, seed, 16, temp, prompt) == run(binary, 'sample', new, seed, 16, temp, prompt)
68 seqs = [(list(b'abc abcd'), list(b'bc abcde'))]
69 old_loss, _ = ref.loss_and_grad(src['c'], src['params'], seqs)
70 new_loss, grad = ref.loss_and_grad(dst['c'], dst['params'], seqs)
71 assert old_loss == new_loss, 'oracle forward changed'
72 for name, off, rows, cols in ref.tensor_specs(dst['c']):
73 if name in ('wo.2', 'w2.2', 'wo.3', 'w2.3'):
74 assert any(grad[off:off+rows*cols]), ('dead new branch', name)
75 repeat = root / f'repeat{fmt}.ck'
76 run(binary, 'grow', old, repeat, 4, 12, 3000)
77 assert repeat.read_bytes() == new.read_bytes(), 'growth not reproducible'
78 whole, split = root / f'whole{fmt}.ck', root / f'split{fmt}.ck'
79 shutil.copyfile(new, whole)
80 shutil.copyfile(new, split)
81 run(binary, 'train', whole, train, 4, 1)
82 run(binary, 'train', split, train, 2, 1)
83 run(binary, 'train', split, train, 4, 1)
84 assert whole.read_bytes() == split.read_bytes(), 'resume differs'
85 learned = ref.read_ck1(whole)
86 for name, off, rows, cols in ref.tensor_specs(dst['c']):
87 if name in ('wo.2', 'w2.2', 'wo.3', 'w2.3', 'wq.2', 'w1.2'):
88 assert learned['params'][off:off+rows*cols] != dst['params'][off:off+rows*cols], ('no learning', name)
89 # Repeated growth and the current supported depth boundary retain all learned tensors.
90 deep = root / f'deep{fmt}.ck'
91 run(binary, 'grow', whole, deep, 16, 12, 3000)
92 assert run(binary, 'eval', whole, held, 2).split()[2:] == run(binary, 'eval', deep, held, 2).split()[2:]
93 deeper = ref.read_ck1(deep)
94 assert deeper['c']['L'] == 16
95 old_tensors = {n: learned['params'][o:o+r*c] for n,o,r,c in ref.tensor_specs(learned['c'])}
96 for name, off, rows, cols in ref.tensor_specs(deeper['c']):
97 if name in old_tensors:
98 assert struct.pack('<%dd' % (rows*cols), *deeper['params'][off:off+rows*cols]) == struct.pack('<%dd' % (rows*cols), *old_tensors[name]), ('repeat growth lost tensor', name)
99 for index, args in enumerate([(2,12,3000), (1,12,3000), (17,12,3000), (4,0,3000),
100 (4,1000000,3000), (4,12,0)]):
101 bad = root / f'bad{fmt}-{index}.ck'
102 run(binary, 'grow', old, bad, *args, expected=12)
103 assert not bad.exists()
104 missing = root / f'args{fmt}.ck'
105 run(binary, 'grow', old, missing, 18446744073709551615, 12, 3000, expected=2)
106 assert not missing.exists()
107 run(binary, 'grow', old, missing, 4, 12, expected=2)
108 assert not missing.exists()
109 broken = root / f'broken{fmt}.ck'
110 raw = bytearray(before)
111 raw[-1] ^= 1
112 broken.write_bytes(raw)
113 run(binary, 'grow', broken, missing, 4, 12, 3000, expected=14)
114 assert not missing.exists()
115 for nonfinite in (float('inf'), float('-inf'), float('nan')):
116 badsrc = dict(src, params=src['params'].copy())
117 badsrc['params'][0] = nonfinite
118 broken.write_bytes(ref.ck1_bytes(badsrc))
119 run(binary, 'grow', broken, missing, 4, 12, 3000, expected=54)
120 assert not missing.exists()
121 return 'PASS'
122
123
124def check_chunks(binary, root, chunk):
125 root.mkdir()
126 old, new = root / 'old.ck', root / 'grown.ck'
127 run(binary, 'init', old, 4096, 1, 256, 1, 1, 1, 1, 31, 3, 300)
128 before = old.read_bytes()
129 count = struct.unpack_from('<Q', before, 96)[0]
130 width = struct.unpack_from('<Q', before, 24)[0]
131 assert count > chunk + 1, 'fixture must span multiple snapshot chunks'
132 run(binary, 'grow', old, new, 2, 3, 300)
133 after = new.read_bytes()
134 grown = struct.unpack_from('<Q', after, 96)[0]
135 prefix = 8 * (count - width)
136 assert before[112:112+prefix] == after[112:112+prefix], 'multi-chunk learned bytes changed'
137 assert before[112+prefix:112+8*count] == after[112+8*(grown-width):112+8*grown], 'multi-chunk gain changed'
138 assert old.read_bytes() == before
139 for index in (chunk + 1, count - 1):
140 corrupt = bytearray(before)
141 struct.pack_into('<d', corrupt, 112 + 8*index, float('nan'))
142 struct.pack_into('<Q', corrupt, 104, ref.fnv1a64(memoryview(corrupt)[112:]))
143 bad, out = root / 'bad.ck', root / 'refused.ck'
144 bad.write_bytes(corrupt)
145 run(binary, 'grow', bad, out, 2, 3, 300, expected=54)
146 assert not out.exists()
147 return 'PASS'
148
149
150def compile_source(omc, source, out):
151 with out.open('wb') as stream:
152 p = subprocess.run([str(omc)], input=source.encode(), stdout=stream, stderr=subprocess.PIPE, timeout=120)
153 assert p.returncode == 0, p.stderr.decode()
154 out.chmod(0o700)
155
156
157def main():
158 build, omc = map(lambda s: Path(s).resolve(), sys.argv[1:])
159 binary = build / 'ollm'
160 source = (build / 'ollm.om').read_text()
161 results = {'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest()}
162 with tempfile.TemporaryDirectory(prefix='grow-check-') as tmp:
163 root = Path(tmp)
164 results['product'] = check(binary, root / 'product')
165 # Build the existing variant instead of copying its capacities into this test.
166 bank = root / 'bank-build'
167 env = dict(os.environ, TARGET='aarch64', OMC=str(omc), OUT=str(bank),
168 CORE=str(min(os.sched_getaffinity(0))))
169 built = subprocess.run(['sh', str(Path(__file__).with_name('build.sh')),
170 '--variant', 'bx'], env=env, capture_output=True, timeout=120)
171 assert built.returncode == 0, built.stderr.decode(errors='replace')
172 results['cross_bank'] = check(bank / 'ollm-var-bx', root / 'cross-bank')
173 chunk = int(re.search(r'^const OCH ulong (\d+)$', source, re.M).group(1))
174 results['multiple_chunks'] = check_chunks(binary, root / 'chunks', chunk)
175 mutations = {
176 'attention_not_silent': ('oiset opwo l mul get og 2 get og 2 0.0', 'oiset opwo l mul get og 2 get og 2 0.1'),
177 'ffn_not_silent': ('oiset opw2 l mul get og 2 get og 4 0.0', 'oiset opw2 l mul get og 2 get og 4 0.1'),
178 'signed_zero_lost': ('ogrowcopy oldg', 'ogrowcopy oldg\nowp 0 fabs owg 0'),
179 'lost_old_weights': ('ogrowcopy oldg', 'note mutation: omit learned weights'),
180 'lost_final_gain': ('owp add get og 33 j ocsg add oldg j', 'owp add get og 33 j 1.0'),
181 'stale_optimizer': ('ozerom mul 2 p', 'note mutation: omit optimizer reset'),
182 'dead_new_inputs': ('ogrowcopy oldg', 'ogrowcopy oldg\nfor k ulong sub ll oldl\noiset opw1 add oldl k mul get og 2 get og 4 0.0\nend'),
183 }
184 for name, (old, new) in mutations.items():
185 assert source.count(old) == 1, (name, 'mutation count')
186 mutant = root / name
187 compile_source(omc, source.replace(old, new), mutant)
188 try:
189 check(mutant, root / (name + '-work'))
190 except AssertionError as exc:
191 results[name] = 'CAUGHT: ' + str(exc)
192 else:
193 raise AssertionError('surviving mutant: ' + name)
194 start = source.index('fn ogrowsnap ')
195 stop = source.index('fn ogrowcopy ', start)
196 snap = source[start:stop]
197 assert snap.count('for q ulong ocn n') == 1
198 truncated = source[:start] + snap.replace('for q ulong ocn n', 'for q ulong 1') + source[stop:]
199 mutant = root / 'truncated-snapshot'
200 compile_source(omc, truncated, mutant)
201 try:
202 check_chunks(mutant, root / 'truncated-chunks', chunk)
203 except AssertionError as exc:
204 results['truncated_snapshot'] = 'CAUGHT: ' + str(exc)
205 else:
206 raise AssertionError('surviving truncated snapshot mutant')
207 print(json.dumps(results, indent=2))
208 print('GROW_PASS')
209
210
211if __name__ == '__main__':
212 main()