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 / deployment / speed / measure.py

84 lines · 5190 bytes Raw Blame History
1import os
2"""External stopwatch; installed and native timed binaries do all inference."""
3from pathlib import Path
4import hashlib,json,os,selectors,struct,subprocess,time,statistics
5R=Path(__file__).resolve().parent
6D=(Path(os.path.expanduser('~')) / '/.local/share/omega-tool-model/round40'.lstrip('/'))
7P=(Path(os.path.expanduser('~')) / '/handoffs/tool-omega-20261104/round40'.lstrip('/'))
8jobs=json.loads((P/'final-selected.json').read_text())
9cases=[dict(name=n,prompt=jobs[0]['turns'][i]['prompt']) for n,i in [('read_request',0),('repair_request',2),('verified_reply',4)]]
10cases.append(dict(name='long_text',prompt='Once upon a time'))
11(R/'workloads.json').write_text(json.dumps(cases,indent=2)+'\n')
12def snapshot():
13 p=subprocess.run(['nvidia-smi','--query-gpu=name,temperature.gpu,utilization.gpu,power.draw,clocks.current.sm','--format=csv,noheader,nounits'],capture_output=True,text=True)
14 return dict(time_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),gpu_csv=p.stdout.strip(),gpu_status=p.returncode,load_average=os.getloadavg(),cpu_affinity=sorted(os.sched_getaffinity(0)))
15(R/'environment-before.json').write_text(json.dumps(snapshot(),indent=2)+'\n')
16def run(cmd,prompt):
17 start=time.perf_counter_ns()
18 p=subprocess.Popen([str(cmd)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize=0)
19 p.stdin.write(prompt.encode());p.stdin.close()
20 streams={1:bytearray(),2:bytearray()}; first=None;chunks=[]
21 sel=selectors.DefaultSelector()
22 sel.register(p.stdout,selectors.EVENT_READ,1);sel.register(p.stderr,selectors.EVENT_READ,2)
23 while sel.get_map():
24 if time.perf_counter_ns()-start>120_000_000_000:
25 p.kill();p.wait();raise RuntimeError('Own benchmark child timed out')
26 for key,_ in sel.select(1):
27 data=os.read(key.fd,4096);now=time.perf_counter_ns()
28 if not data:sel.unregister(key.fileobj);continue
29 streams[key.data].extend(data)
30 if key.data==1:
31 if first is None:first=now
32 chunks.append(dict(time_ns=now-start,bytes=len(data)))
33 rc=p.wait();end=time.perf_counter_ns();sel.close()
34 assert rc==0,(rc,bytes(streams[2])[:200])
35 return dict(command=str(cmd),returncode=rc,elapsed_ns=end-start,first_byte_ns=None if first is None else first-start,stdout=bytes(streams[1]).decode(),stdout_chunks=chunks),bytes(streams[2])
36warm,_=run(D/'omega-tool-model',cases[0]['prompt'])
37(R/'warmup.json').write_text(json.dumps(warm,indent=2)+'\n')
38rows=[]
39for rep in range(5):
40 for case in cases:
41 order=['installed','instrumented'] if rep%2==0 else ['instrumented','installed']
42 pair={}
43 for kind in order:
44 rec,err=run(D/'omega-tool-model' if kind=='installed' else R/'timed',case['prompt'])
45 if kind=='installed':assert not err
46 else:
47 assert len(err)==1440,len(err)
48 marks=list(struct.unpack('<180Q',err));n=marks[8]
49 assert 0<n<=160 and all(b>=a for a,b in zip(marks[:7],marks[1:7]))
50 stamps=marks[10:10+n]
51 assert all(b>a for a,b in zip(stamps,stamps[1:]))
52 assert marks[4]<=stamps[0]<=stamps[-1]<=marks[5]<=marks[6]
53 rec['marks_ns']=marks[:10]+stamps
54 rec['prompt_tokens']=marks[7];rec['output_tokens']=n
55 pair[kind]=rec
56 assert pair['installed']['stdout']==pair['instrumented']['stdout'],case['name']
57 row=dict(repetition=rep,workload=case['name'],parity=True,**pair);rows.append(row)
58 (R/'raw.json').write_text(json.dumps(rows,indent=2)+'\n')
59 print('Measured',rep,case['name'],pair['instrumented']['output_tokens'],'tokens',flush=True)
60(R/'environment-after.json').write_text(json.dumps(snapshot(),indent=2)+'\n')
61pins=json.loads((R/'pins.json').read_text())
62for path,want in pins.items():assert hashlib.sha256(Path(path).read_bytes()).hexdigest()==want,path
63def stats(xs):return dict(median=statistics.median(xs),minimum=min(xs),maximum=max(xs))
64summary=[]
65for case in cases:
66 group=[r for r in rows if r['workload']==case['name']]
67 def vals(fn):return [fn(r['installed'],r['instrumented'],r['instrumented']['marks_ns']) for r in group]
68 result=dict(workload=case['name'],repetitions=len(group),prompt_tokens=sorted(set(r['instrumented']['prompt_tokens'] for r in group)),output_tokens=sorted(set(r['instrumented']['output_tokens'] for r in group)),all_outputs_equal=len(set(r['installed']['stdout'] for r in group))==1)
69 metrics={
70 'visible_first_byte_ms':lambda a,b,t:a['first_byte_ns']/1e6,
71 'total_ms':lambda a,b,t:a['elapsed_ns']/1e6,
72 'internal_first_token_ms':lambda a,b,t:(t[10]-t[0])/1e6,
73 'checkpoint_load_ms':lambda a,b,t:(t[2]-t[1])/1e6,
74 'tokenizer_ms':lambda a,b,t:(t[3]-t[2])/1e6,
75 'device_setup_upload_ms':lambda a,b,t:(t[4]-t[3])/1e6,
76 'first_forward_ms':lambda a,b,t:(t[10]-t[4])/1e6,
77 'decode_tokens_per_second':lambda a,b,t:(b['output_tokens']-1)*1e9/(t[-1]-t[10]),
78 'all_in_tokens_per_second':lambda a,b,t:b['output_tokens']*1e9/a['elapsed_ns'],
79 'instrumented_total_ms':lambda a,b,t:b['elapsed_ns']/1e6,
80 }
81 for key,fn in metrics.items():result[key]=stats(vals(fn))
82 summary.append(result)
83(R/'summary.json').write_text(json.dumps(dict(workloads=summary,parity_pairs=len(rows),unchanged_pins=True,units='ms and output tokens/second; prompt tokens exclude start marker'),indent=2)+'\n')
84print('All measurements complete; parity and original hashes passed.',flush=True)