File size: 15,432 Bytes
b3c3fe4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | #!/usr/bin/env python3
"""NeuroCC 0.4.0 runtime comparison; Linux/WSL x86-64; no learned bytes executed directly."""
import argparse, collections, csv, hashlib, json, math, os, platform, re, shutil, statistics, subprocess, sys, time
from pathlib import Path
MODES = {'llvm_algorithm': ('A','B'), 'same_source_baseline': ('A','C'),
'same_source_target': ('B','D'), 'transformed_vs_llvm_original': ('A','D'),
'neurocc_algorithm': ('C','D')}
def need(ok, message):
if not ok: raise ValueError(message)
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
def read(p): return json.loads(p.read_text(encoding='utf-8'))
def index_jsonl(p):
rows=[json.loads(s) for s in p.read_text(encoding='utf-8').splitlines() if s.strip()]
out={r['id']:r for r in rows}; need(len(out)==len(rows),'duplicate IDs: '+str(p)); return out
def write(p, x):
temp=p.with_suffix(p.suffix+'.tmp'); temp.write_text(json.dumps(x,indent=2,allow_nan=False)+'\n',encoding='utf-8'); temp.replace(p)
def cmd(args, cwd, timeout):
p=subprocess.run([str(x) for x in args], cwd=str(cwd), capture_output=True,text=True,timeout=timeout,env=dict(os.environ,LC_ALL="C"))
if p.returncode: raise RuntimeError('exit {}: {}\n{}\n{}'.format(p.returncode,' '.join(map(str,args)),p.stderr[-1800:],p.stdout[-500:]))
return p.stdout
def symbol(obj, name, cwd, timeout):
lines=cmd(['nm','-S','--defined-only',obj],cwd,timeout).splitlines()
rows=[s.split() for s in lines if s.split() and s.split()[-1]==name]
need(len(rows)==1 and len(rows[0])==4 and rows[0][2].lower()=='t','missing/invalid text symbol '+name)
addr,n=(int(v,16) for v in rows[0][:2]); need(n>0,'empty symbol'); return addr,n
def function_bytes(obj, name, cwd, timeout):
addr,n=symbol(obj,name,cwd,timeout)
# Candidate functions are deliberately assembled into .text. In linked ELF,
# nm gives virtual address, while objcopy emits the section starting at its VMA.
sections=cmd(['objdump','-h',obj],cwd,timeout)
m=re.search(r'^\s*\d+\s+\.text\s+([0-9a-fA-F]+)\s+([0-9a-fA-F]+)\s',sections,re.M)
need(m is not None,'missing .text section'); size,vma=(int(v,16) for v in m.groups())
offset=addr-vma; need(0<=offset and offset+n<=size,'symbol outside .text')
raw=cwd/'text_extract.bin'; cmd(['objcopy','-O','binary','--only-section=.text',obj,raw],cwd,timeout)
b=raw.read_bytes(); raw.unlink(); need(offset+n<=len(b),'truncated .text'); return b[offset:offset+n]
def candidate(plan, expected, path, timeout):
# Only independent, provenance-bound assembly is accepted. Never inject raw predictions.
need(plan.get('stage')=='isel' and plan.get('origin')=='source_c5_candidate_physical','not a C5 physical plan')
asm=plan['assembly']; need(asm.startswith(('.text\n.globl neurocc_fn\nneurocc_fn:\n','.intel_syntax noprefix\n.text\n.globl neurocc_fn\nneurocc_fn:\n')),'unexpected assembly header')
src=path.with_suffix('.s'); src.write_text(asm,encoding='utf-8')
cmd(['as','--64',src,'-o',path],path.parent,timeout)
rel=cmd(['readelf','-rW',path],path.parent,timeout); need('There are no relocations' in rel,'candidate object has relocations')
need(function_bytes(path,'neurocc_fn',path.parent,timeout)==expected,'independent assembler byte mismatch')
def parse(output, sizes, samples):
lines=output.strip().splitlines(); need(len(lines)==3 and lines[0]=='CHECKS 87','oracle checks missing or unexpected output')
result=[]
for n,line in zip(sizes,lines[1:]):
p=line.split(); need(len(p)==8+samples and p[0]=='BENCH' and int(p[1])==n,'unexpected BENCH record')
l,r,ratio,w=map(float,p[2:6]); lr,rr=map(int,p[6:8]); raw=[list(map(float,x.split(','))) for x in p[8:]]
need(all(len(x)==2 and all(math.isfinite(v) and v>0 for v in x) for x in raw),'bad timing samples')
need(all(math.isfinite(v) and v>0 for v in (l,r,ratio)) and 0<=w<=1 and lr>0 and rr>0,'invalid timing summary')
# Compute paired ratios directly from the raw samples (avoid ratios of separate medians).
ratios=[x/y for x,y in raw]; q=statistics.median(ratios)
need(math.isclose(q,ratio,rel_tol=1e-7),'harness ratio mismatch')
result.append(dict(n=n,left_ns=l,right_ns=r,speedup=q,right_win_fraction=sum(v>1 for v in ratios)/len(ratios),left_reps=lr,right_reps=rr,raw_pairs_ns=raw))
return result
def evaluate_mode(d, mode, objs, names, expected, harness, oracle, a, info):
left,right=MODES[mode]; parts=[]
for label,side in ((left,'baseline'),(right,'target')):
name=side+'_kernel'; dst=d/(mode+'_'+side+'.o')
cmd(['objcopy','--redefine-sym',names[label]+'='+name,objs[label],dst],d,a.timeout); parts.append(dst)
exe=d/mode
cmd([a.clang,'-fno-lto','-Wl,--no-relax',harness,oracle,*parts,'-o',exe],d,a.timeout)
for label,side in ((left,'baseline'),(right,'target')):
if label in expected:
need(function_bytes(exe,side+'_kernel',d,a.timeout)==expected[label],'linked candidate bytes changed')
timings=[]
for j in range(a.repeats):
# Fresh process each repeat. Same input seed for each comparison in a repeat.
seed=(int(info.get('seed',12345))+j)&0xffffffff
output=cmd([exe,info['layout'],*info['sizes'],seed,a.samples,a.sample_ms,0],d,a.timeout)
(d/(mode+'.'+str(j)+'.log')).write_text(output,encoding='utf-8')
timings.append(parse(output,info['sizes'],a.samples))
per=[]
for k,n in enumerate(info['sizes']):
r=[t[k] for t in timings]; speeds=[b['speedup'] for b in r]
# Conservative repeat-consistency rule; not a statistical confidence interval.
if all(b['speedup']>1.05 and b['right_win_fraction']>=.8 for b in r): status='right_faster'
elif all(b['speedup']<1/1.05 and b['right_win_fraction']<=.2 for b in r): status='left_faster'
else: status='inconclusive'
per.append(dict(n=n,speedup=statistics.median(speeds),status=status,repeat_results=r))
return dict(status='passed',left=left,right=right,checks=87*a.repeats,benchmarks=per)
def summarize(records, selected):
out={}
for mode in MODES:
passed=[r['modes'][mode] for r in records if r.get('modes',{}).get(mode,{}).get('status')=='passed']
values=[b for r in passed for b in r['benchmarks']]
ratios=[b['speedup'] for b in values]
out[mode]=dict(pairs_selected=selected,pairs_passed=len(passed),pairs_missing_or_failed=selected-len(passed),size_cases=len(values),geomean_speedup=math.exp(statistics.mean(map(math.log,ratios))) if ratios else None,median_speedup=statistics.median(ratios) if ratios else None,by_size_status=dict(collections.Counter(b['status'] for b in values)),right_faster_both_sizes=sum(all(b['status']=='right_faster' for b in r['benchmarks']) for r in passed),left_faster_both_sizes=sum(all(b['status']=='left_faster' for b in r['benchmarks']) for r in passed))
return out
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--data',type=Path,required=True);p.add_argument('--run',type=Path,required=True,help='qualified D5A function-only run');p.add_argument('--baseline',type=Path,required=True,help='qualified C5 audited run');p.add_argument('--out',type=Path,required=True);p.add_argument('--clang',default='clang++');p.add_argument('--march',choices=['x86-64','x86-64-v2','x86-64-v3','native'],default='x86-64');p.add_argument('--limit',type=int,default=0);p.add_argument('--repeats',type=int,default=2);p.add_argument('--samples',type=int,default=7);p.add_argument('--sample-ms',type=float,default=3);p.add_argument('--timeout',type=int,default=180);p.add_argument('--cpu',type=int,help='optional Linux logical CPU affinity');a=p.parse_args()
need(sys.platform.startswith('linux') and platform.machine()=='x86_64','run in x86-64 Linux/WSL, not Windows Python');need(a.limit>=0 and a.repeats>=1 and a.samples>=3 and a.sample_ms>0 and math.isfinite(a.sample_ms) and a.timeout>0,'invalid options')
for tool in (a.clang,'as','nm','objcopy','objdump','readelf'):need(shutil.which(tool),'missing tool '+tool)
if a.cpu is not None:os.sched_setaffinity(0,{a.cpu})
for name in ('data','run','baseline','out'):setattr(a,name,getattr(a,name).resolve())
version=cmd([a.clang,'--version'],a.data,a.timeout);need('clang' in version.lower(),'LLVM Clang required')
# Re-run the established frozen gate, rather than trust a copied JSON success flag.
import phase_d3b_function_gate as gate
need(gate.compare(a.run,a.baseline)==0,'frozen function-byte gate failed')
funcs=index_jsonl(a.run/'functions.jsonl'); plans=index_jsonl(a.baseline/'plans.jsonl')
samples=index_jsonl(a.data/'samples.jsonl'); manifest=read(a.data/'manifest.json'); bundle=a.data/'wsl_pending'; bm=read(bundle/'manifest.json')
need(manifest.get('schema')=='neurocc.round16b.reference.v1' and manifest.get('samples')==len(samples)==598 and bm.get('abi')=='sysv','unexpected corpus/ABI')
need(set(samples)==set(funcs)==set(plans),'dataset ID mismatch')
records0={r['id']:r for r in read(a.baseline/'summary.json')['records']}
pairs={}
for sid,s in samples.items():
need(s['source_sha256']==records0[sid]['source_sha256'],'source identity mismatch: '+sid)
if s['role'] in ('baseline','target'):
cid=s['pair_id'];need(re.fullmatch(r'[A-Za-z0-9_-]+',cid) is not None,'invalid pair ID')
q=pairs.setdefault(cid,{});need(s['role'] not in q,'duplicate role');q[s['role']]=s
need(len(pairs)==249 and all(set(q)=={'baseline','target'} for q in pairs.values()),'incomplete adversarial corpus')
need(all(cid in bm['adversarial'] for cid in pairs),'pair not in bundle')
selected=sorted(pairs)[:a.limit or None]; a.out.mkdir(parents=True,exist_ok=False)
flags=['-std=c++17','-O3','-march='+a.march,'-fno-lto']; common=['-std=c++17','-O2','-march='+a.march,'-fno-lto']
harness=a.out/'harness.o';cmd([a.clang,*common,'-c',bundle/'adversarial_harness.cpp','-o',harness],a.out,a.timeout)
meta=dict(schema='neurocc.0.4.0.runtime.v1',scope='Warm CPU kernel runtime, independently assembled NeuroCC instructions verified byte-identical to frozen learned output before and after link. No raw learned code execution. Preselected development pairs, not generalization or learned hyperoptimization.',labels={'A':'LLVM -O3 original source','B':'LLVM -O3 transformed source','C':'NeuroCC original source','D':'NeuroCC transformed source'},speedup_definition='left time / right time; >1 means right faster',win_rule='every repeat median paired ratio >1.05 and >=80% raw wins; inverse for left faster; otherwise inconclusive',compiler_version=version,llvm_flags=flags,harness_flags=common,host=platform.uname()._asdict(),cpu_model=next((l.split(':',1)[1].strip() for l in Path('/proc/cpuinfo').read_text().splitlines() if l.startswith('model name')),None),affinity=sorted(os.sched_getaffinity(0)),samples=a.samples,repeats=a.repeats,sample_ms=a.sample_ms,total_pairs=249,selected_pairs=len(selected),selected_ids=selected,provenance={'functions_sha256':sha(a.run/'functions.jsonl'),'c5_plans_sha256':sha(a.baseline/'plans.jsonl'),'dataset_sha256':sha(a.data/'samples.jsonl'),'harness_sha256':sha(bundle/'adversarial_harness.cpp'),'frozen_gate_sha256':sha(a.run/'phase_d3b_function_parity.json')})
results=[]; started=time.perf_counter()
families={cid:pairs[cid]['baseline']['family'] for cid in selected}
def size_summary():
rr=[r['symbol_bytes'] for r in results if set(r.get('symbol_bytes',{}))==set('ABCD')]
return {mode:dict(pairs=len(rr),left_total_bytes=sum(r[l] for r in rr),right_total_bytes=sum(r[t] for r in rr),geomean_left_over_right=math.exp(statistics.mean(math.log(r[l]/r[t]) for r in rr)) if rr else None) for mode,(l,t) in MODES.items()}
def report():
s=dict(meta,processed_pairs=len(results),seconds=time.perf_counter()-started,comparisons=summarize(results,len(selected)),complete=len(results)==len(selected),all_comparisons_passed=len(results)==len(selected) and all(len(r.get('modes',{}))==len(MODES) and all(x['status']=='passed' for x in r['modes'].values()) for r in results));write(a.out/'runtime_summary.json',s);write(a.out/'runtime_details.json',results);return s
for i,cid in enumerate(selected,1):
q=pairs[cid];case=bundle/'cases'/cid;d=a.out/cid;d.mkdir();r=dict(pair_id=cid,family=q['baseline']['family'],modes={}); objs={};names={};expected={};sizes={}
try:
info=read(case/'pair.json');need(len(info['sizes'])==2 and all(isinstance(n,int) and n>0 for n in info['sizes']),'bad sizes');r['sizes']=info['sizes'];r['layout']=info['layout'];r['pair_manifest_sha256']=sha(case/'pair.json');r['oracle_sha256']=sha(case/'oracle.cpp')
oracle=d/'oracle.o';cmd([a.clang,*common,'-c',case/'oracle.cpp','-o',oracle],d,a.timeout)
for role,llvm,ncc in (('baseline','A','C'),('target','B','D')):
s=q[role];sid=s['id'];src=case/role/'kernel.cpp';need(sha(src)==s['source_sha256'],'kernel source hash mismatch');need(sha(case/role/'kernel.bin')==s['binary_sha256'],'reference binary hash mismatch')
f=funcs[sid];need(f['abi']=='sysv' and f['architecture']=='x86_64' and f['relocations']==[],'unsupported function ABI/relocations');raw=bytes.fromhex(f['code_hex']);need(len(raw)==f['size'] and hashlib.sha256(raw).hexdigest()==f['sha256'],'function packet hash mismatch')
objs[llvm]=d/(llvm+'.o');names[llvm]='kernel';cmd([a.clang,*flags,'-c',src,'-o',objs[llvm]],d,a.timeout);sizes[llvm]=symbol(objs[llvm],names[llvm],d,a.timeout)[1]
objs[ncc]=d/(ncc+'.o');names[ncc]='neurocc_fn';expected[ncc]=raw;candidate(plans[sid],raw,objs[ncc],a.timeout);sizes[ncc]=len(raw)
r['symbol_bytes']=sizes
for mode in MODES:
try:r['modes'][mode]=evaluate_mode(d,mode,objs,names,expected,harness,oracle,a,info)
except Exception as e:r['modes'][mode]=dict(status='failed',error=str(e))
except Exception as e:r['error']=str(e)
results.append(r);report();print('{}/{} {} {}'.format(i,len(selected),cid,{m:v['status'] for m,v in r['modes'].items()} if 'error' not in r else r['error']),flush=True)
s=report()
s['by_family']={family:summarize([r for r in results if r['family']==family],sum(v==family for v in families.values())) for family in sorted(set(families.values()))}
s['symbol_size_comparisons']=size_summary()
need(sha(a.run/'functions.jsonl')==meta['provenance']['functions_sha256'] and sha(a.baseline/'plans.jsonl')==meta['provenance']['c5_plans_sha256'] and sha(a.data/'samples.jsonl')==meta['provenance']['dataset_sha256'],'input provenance changed during run')
write(a.out/'runtime_summary.json',s)
with (a.out/'runtime_cases.csv').open('w',newline='',encoding='utf-8') as f:
w=csv.writer(f);w.writerow(['pair_id','family','comparison','n','speedup_left_over_right','classification','A_bytes','B_bytes','C_bytes','D_bytes'])
for r in results:
for mode,v in r['modes'].items():
for b in v.get('benchmarks',[]):w.writerow([r['pair_id'],r['family'],mode,b['n'],b['speedup'],b['status'],*[r.get('symbol_bytes',{}).get(k) for k in 'ABCD']])
print(json.dumps(s,indent=2));return int(not s['all_comparisons_passed'])
if __name__=='__main__':raise SystemExit(main())
|