interplane.Get Omega
Read in your language

omega-tool-model

First-party Omega tool-use model source, serving harnesses, and verification records

Brought by drakestapleton

branch main Branches Tags History

omega-tool-model / pilot / prepare.py

103 lines · 6493 bytes Raw Blame History
1import os
2"""External curriculum/test instrument. Model operations use native Omega binaries."""
3from pathlib import Path
4import hashlib, json, random, struct, subprocess, os
5
6R=Path(__file__).parent
7CPU=(Path(os.path.expanduser('~')) / '/handoffs/weight-tuning-20261104/build/ollm'.lstrip('/'))
8OMC=(Path(os.path.expanduser('~')) / '/handoffs/omega-llm-20261101/omega-mv/seed/out/omc'.lstrip('/'))
9DATA=(Path(os.path.expanduser('~')) / '/handoffs/omega-llm-20261101/v1-data'.lstrip('/'))
10BASE=Path('/tmp/gk/r10/run/ck60000.bin')
11def run(args, expected=0, **kw):
12 p=subprocess.run([str(x) for x in args],capture_output=True,timeout=120,**kw)
13 assert p.returncode==expected,(args,p.returncode,p.stderr[:300])
14 return p
15def sha(p):
16 with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
17def header(p):
18 with p.open('rb') as f:return struct.unpack('<15Q',f.read(120))
19
20# Independent reset checks, including parameters, moments, metadata, rejected overwrite.
21small=R/'build/small.ck'; out=R/'build/reset-small.ck'
22run([CPU,'init',small,256,8,16,2,32,2,2,1,200,3000,1])
23(R/'build/small.bin').write_bytes(b'abc def ghi\0'*100)
24run([CPU,'train',small,R/'build/small.bin',2,1])
25run([R/'build/reset',small,out,1000,300])
26hb,ho=header(small),header(out); n=hb[12]*8
27bb,bo=small.read_bytes(),out.read_bytes()
28assert bb[120:120+n]==bo[120:120+n]
29assert not any(bo[120+n:]) and any(bb[120+n:])
30assert ho[:9]==hb[:9] and ho[9]==0 and ho[10]==1000
31assert struct.unpack('<d',bo[88:96])[0]==0.0003
32assert ho[12:14]==hb[12:14]
33run([CPU,'eval',out,R/'build/small.bin',1])
34run([R/'build/reset',small,out,1000,300],52)
35run([R/'build/reset',small,R/'build/bad.ck',0,300],51)
36damaged=bytearray(bb); damaged[-1]^=1
37(R/'build/corrupt.ck').write_bytes(damaged)
38run([R/'build/reset',R/'build/corrupt.ck',R/'build/bad.ck',1000,300],14)
39(R/'receipts/reset-check.json').write_text(json.dumps({'weights':'identical','moments':'zero','metadata':'checked','loader_checksum':'pass','overwrite_and_range_and_corruption':'refused'},indent=2))
40
41sets={'train':[],'dev':[],'test':[]}
42def add(split,kind,prompt,answer,**extra):
43 sets[split].append(dict(kind=kind,prompt='Task: '+prompt+'\nAnswer:\n',answer=answer,**extra))
44for split,start,stop in [('train',0,160),('dev',160,180),('test',180,200)]:
45 for i in range(start,stop):
46 path=f'notes/item{i}.txt'; folder=f'folder{i}'; source=f'code/job{i}.om'
47 for verb in ['Read','Open and read']:
48 add(split,'read',f'{verb} {path}. Use a tool.',json.dumps({'tool':'read_file','path':path},separators=(',',':')))
49 add(split,'list',f'List the files in {folder}. Use a tool.',json.dumps({'tool':'list_files','path':folder},separators=(',',':')))
50 add(split,'check',f'Check whether {source} compiles. Use a tool.',json.dumps({'tool':'omega_check','path':source},separators=(',',':')))
51 add(split,'result',f'The read_file tool returned: message{i}. Report its result.',f'The file contains: message{i}.')
52 add(split,'failure',f'The read_file tool returned an error: {path} was not found. Report the result.',f'I could not read {path}: file not found.')
53 # Values stay in the same small domain. Held-out operand pairs are excluded from train.
54 a=i%20; b=i//20
55 code=f'fn main to int\nret add int {a} int {b}\nend'
56 add(split,'add',f'Write Omega that returns {a} plus {b}.',code,expected_exit=a+b)
57 code=f'fn main to int\nif gt int {a} int {b}\nret int {a}\nelse\nret int {b}\nend\nend'
58 add(split,'max',f'Write Omega that returns the larger of {a} and {b}.',code,expected_exit=max(a,b))
59 # Short programs with repeated vocabulary, plus strings unseen during training.
60 msg=f'hello{i}'
61 code=f'text msg "{msg}\\n"\nfn main to int\nn = write int 1 msg ulong 0 len msg\nif ne n long len msg\nret 1\nend\nret 0\nend'
62 add(split,'print',f'Write Omega that prints {msg} followed by a newline.',code,expected_exit=0,expected_stdout=msg+'\n')
63
64# Every target Omega program is actually compiled and executed, including held-out ones.
65checked=[]
66for split,rows in sets.items():
67 for row in rows:
68 if 'expected_exit' not in row:continue
69 p=run([OMC],input=(row['answer']+'\n').encode())
70 exe=R/'build/lesson-check';exe.write_bytes(p.stdout);exe.chmod(0o700)
71 q=run([exe],row['expected_exit'])
72 assert q.stdout.decode()==row.get('expected_stdout','')
73 checked.append({'split':split,'source_sha256':hashlib.sha256(row['answer'].encode()).hexdigest(),'exit':q.returncode})
74
75rng=random.Random(1104)
76for split,rows in sets.items():
77 rng.shuffle(rows)
78 (R/f'data/{split}.json').write_text(json.dumps(rows,indent=2)+'\n')
79 blob=b''.join((x['prompt']+x['answer']+'\nDone.\n').encode()+b'\0' for x in rows)
80 (R/f'data/{split}.bin').write_bytes(blob)
81 run([CPU,'bpeenc',DATA/'merges4096.bin',4096,R/f'data/{split}.bin',R/f'data/{split}.tok'])
82train_answers={x['answer'] for x in sets['train']}
83assert all(x['answer'] not in train_answers for split in ('dev','test') for x in sets[split])
84tokens=(R/'data/train.tok').read_bytes()
85# Fixed interleaving: 9 curriculum blocks then 1 original-story block. Exact sampled bytes saved.
86story=(DATA/'train.tok').open('rb').read(len(tokens)//9)
87story=story[:len(story)//2*2]
88parts=[]
89for i in range(0,len(tokens),4608):
90 parts.append(tokens[i:i+4608]);offset=(i//4608)*512;parts.append(story[offset:offset+512])
91(R/'data/mixed.tok').write_bytes(b''.join(parts))
92(R/'receipts/lesson-checks.json').write_text(json.dumps(checked,indent=2))
93run([R/'build/reset',BASE,R/'checkpoints/start.ck',1000,300])
94# Full-size byte check uses streaming reads, not Python model arithmetic.
95h=header(BASE);n=h[12]*8
96with BASE.open('rb') as f,(R/'checkpoints/start.ck').open('rb') as g:
97 f.seek(120);g.seek(120)
98 while n:
99 k=min(n,1048576);assert f.read(k)==g.read(k);n-=k
100 while block:=g.read(1048576):assert not any(block)
101manifest={'counts':{k:len(v) for k,v in sets.items()},'compiler_checked_programs':len(checked),'source_commit':'56cc88706a9a685ed9c5dae8050e4643cc7f1aae','compiler_commit':'e5b32567a7aff3ce594e3254a622a846a6cd190b','sha256':{str(p):sha(p) for p in [BASE,CPU,OMC,DATA/'merges4096.bin',R/'build/reset',R/'checkpoints/start.ck',R/'data/mixed.tok',R/'data/dev.tok',R/'data/test.tok']}}
102(R/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
103print(json.dumps({k:v for k,v in manifest.items() if k!='sha256'}),flush=True)