NeuroCC_0.4.0 / neuro_compiler /runtime /phase_c_syntax.py
chrisuser's picture
Upload 389 files
b3c3fe4 verified
Raw History Blame Contribute Delete
14.3 kB
"""Phase C1 source-only token anchor + span learning. No compiler at inference.
Clang labels are used only by offline training/evaluation. Graph assembly is bounded
span containment, not a recursive grammar parser. Not release-qualified.
"""
import torch, re, json, math, collections, random, time, argparse
from torch import nn
from pathlib import Path
from scaling_impl.round16_adapters.normalization import tokens,normalize_source
from scaling_impl.round16_adapters import semantic_phase_b as sem
import phase_b_replay as replay
import ast_s11b_cpu as b
KIND=['none','FunctionDecl','ParmVarDecl','CompoundStmt','DeclStmt','VarDecl','DeclRefExpr','IntegerLiteral','BinaryOperator','CompoundAssignOperator','UnaryOperator','ParenExpr','ArraySubscriptExpr','ForStmt','IfStmt','ReturnStmt','CXXFunctionalCastExpr','ConditionalOperator','NoInlineAttr']
OPS={'++','--','+=','-=','^=','<=','>=','==','!=','&&','<<','>>','+','-','*','%','&','^','<','>','=','!'}
KEYS='extern "C" __attribute__ noinline using static_assert sizeof const constexpr unsigned int long bool void __restrict kernel for if else return ( ) [ ] { } ; , ? :'.split()
WORDS=['PAD','ID','NUM','TYPE','OTHER']+KEYS+sorted(OPS)
W={k:i for i,k in enumerate(WORDS)}; C={k:i for i,k in enumerate(KIND)}
L=384
def lex(src):
norm=normalize_source(src); raw=tokens(src);ts=[];i=0
while i<len(raw):
t=raw[i]
if i+1<len(raw) and t[2]==raw[i+1][1] and t[0]+raw[i+1][0] in OPS:
t=(t[0]+raw[i+1][0],t[1],raw[i+1][2],'other');i+=1
ts.append(t);i+=1
if len(ts)>L:raise ValueError('token capacity')
text=[x[0] for x in ts]; stack=[];match={};depth=[]
for i,t in enumerate(text):
depth.append([sum(text[j]==o for j in stack) for o in ('{','(','[')])
if t in ('{','(','['):stack.append(i)
elif t in ('}',')',']'):
if not stack or text[stack[-1]]!={'}':'{',')':'(',']':'['}[t]:raise ValueError('delimiter mismatch')
j=stack.pop();match[i]=j;match[j]=i
if stack:raise ValueError('delimiter mismatch')
ids=[W.get(t,W['TYPE'] if t in norm['aliases'] else W['ID'] if k=='id' else W['NUM'] if re.fullmatch(r'[0-9]+[uUlL]*',t) else W['OTHER']) for t,_,_,k in ts]
# literals may be lexed as num; explicit regex ensures no spelling leakage.
name=text.index('kernel'); body=next(i for i in range(name,len(text)) if text[i]=='{');head=name+1
feats=[]
for i,(t,_,_,_) in enumerate(ts):
d=depth[i];m=match.get(i,i);feats.append([min(x,16)/8 for x in d]+[float(i<body),float(i<name),float(name<i<body),float(i==name),float(i==body),min(abs(m-i),128)/32,float(i in match),i/max(1,len(ts)-1)])
return ts,ids,feats,match,body
def labels(row, lx):
ts,_,_,_,_=lx; starts={x[1]:i for i,x in enumerate(ts)};ends={x[2]:i for i,x in enumerate(ts)};ns=row['nodes'];out=[]; gold=replay.stripped(row)
def explicit(i):
while ns[i]['kind']=='ImplicitCastExpr':i=ns[i]['children'][0]
return ns[i]
for n in ns:
k=n['kind'];f=n['fields']
if k in ('ImplicitCastExpr','Unknown'):continue
s=starts[n['start']];e=ends[n['end']];a=starts[n['pos']];ch=[explicit(j) for j in n['children']]
if k in ('BinaryOperator','CompoundAssignOperator','ConditionalOperator','ArraySubscriptExpr'):
lo=ch[0]['end'];hi=ch[1]['start'];op='?' if k=='ConditionalOperator' else '[' if k=='ArraySubscriptExpr' else f['opcode']; cand=[j for j,t in enumerate(ts) if lo<=t[1]<hi and t[0]==op]
if len(cand)!=1:raise ValueError(('operator anchor',row['id'],k,op,cand,lo,hi))
a=cand[0]
elif k=='UnaryOperator' and f['postfix']=='True':a=e
out.append((a,C[k],s,e))
if len({a for a,k,s,e in out})!=len(out):raise ValueError(('anchor collision',row['id'],[x for x,n in collections.Counter(a for a,*_ in out).items() if n>1]))
return out,gold
class Model(nn.Module):
def __init__(self,context=True):
super().__init__();self.context=context;self.emb=nn.Embedding(len(W),32,padding_idx=0);self.inp=nn.Linear(43,64);self.conv=nn.ModuleList(nn.Conv1d(64,64,5,padding=2*d,dilation=d) for d in (1,2,4));self.norm=nn.ModuleList(nn.LayerNorm(64) for _ in self.conv);self.role=nn.Linear(64,len(KIND));self.kind=nn.Embedding(len(KIND),16);self.left=nn.Linear(80,64);self.right=nn.Linear(80,64);self.key=nn.Linear(64,64);self.dist=nn.Embedding(2*L+1,2)
def forward(self,ids,features,roles=None):
h=self.inp(torch.cat((self.emb(ids),features),-1));mask=ids.ne(0);h=h*mask[...,None]
if self.context:
for c,n in zip(self.conv,self.norm):h=n(h+torch.nn.functional.gelu(c(h.transpose(1,2)).transpose(1,2)))*mask[...,None]
logits=self.role(h);r=logits.argmax(-1) if roles is None else roles;z=torch.cat((h,self.kind(r)),dim=-1);key=self.key(h);n=ids.shape[1];p=torch.arange(n,device=ids.device);dist=p[None,:]-p[:,None];bias=self.dist(dist+L);left=(self.left(z)@key.transpose(1,2))/8+bias[:,:,0];right=(self.right(z)@key.transpose(1,2))/8+bias[:,:,1];left=left.masked_fill((dist>0)[None]|~mask[:,None,:],-1e4);right=right.masked_fill((dist<0)[None]|~mask[:,None,:],-1e4);return logits,left,right
def pack(rows):
data=[]
for row in rows:
lx=lex(row['source']);y,g=labels(row,lx);n=len(lx[0]);r=torch.zeros(n,dtype=torch.long);s=torch.full((n,),-100,dtype=torch.long);e=s.clone()
for a,k,lo,hi in y:r[a]=k;s[a]=lo;e[a]=hi
data.append((row,lx,y,g,torch.tensor(lx[1]),torch.tensor(lx[2]),r,s,e))
return data
def batch(ds,device='cpu'):
n=max(len(x[4]) for x in ds);ids=torch.zeros(len(ds),n,dtype=torch.long);f=torch.zeros(len(ds),n,11);r=ids.clone();s=torch.full_like(ids,-100);e=s.clone()
for j,x in enumerate(ds):m=len(x[4]);ids[j,:m]=x[4];f[j,:m]=x[5];r[j,:m]=x[6];s[j,:m]=x[7];e[j,:m]=x[8]
return tuple(t.to(device) for t in (ids,f,r,s,e))
def constrain(nodes,lx):
ts,_,_,match,body=lx;out=[]
for a,k,s,e in nodes:
name=KIND[k];t=ts[a][0]
if name in ('DeclRefExpr','IntegerLiteral','NoInlineAttr'):s=e=a
elif name in ('CompoundStmt','ParenExpr') and a in match and match[a]>a:s,e=a,match[a]
elif name=='CXXFunctionalCastExpr' and a+1 in match and ts[a+1][0]=='(':s,e=a,match[a+1]
elif name=='ArraySubscriptExpr' and a in match and t=='[':e=match[a]
elif name=='FunctionDecl':s=a;e=len(ts)-1
out.append((a,k,s,e))
return out
def assemble(src,lx,nodes):
ts,_,_,_,_=lx;ns=sorted(nodes,key=lambda x:(x[2],-x[3],x[0]));roots=[i for i,n in enumerate(ns) if KIND[n[1]]=='FunctionDecl'];
if len(roots)!=1:raise ValueError('root count')
root=roots[0];ch=[[] for _ in ns];par={};
for j,(a,k,s,e) in enumerate(ns):
if j==root:continue
kind=KIND[k]
if kind in ('ParmVarDecl','NoInlineAttr'):p=root
else:
choices=[]
for i,(aa,kk,ss,ee) in enumerate(ns):
if i==j or KIND[kk] in ('DeclRefExpr','IntegerLiteral','NoInlineAttr','ParmVarDecl'):continue
if KIND[kk]=='VarDecl' and kind=='VarDecl':continue
if ss<=s and e<=ee and (ss<s or e<ee):choices.append((ee-ss,-ss,i))
if not choices:raise ValueError('missing parent')
p=min(choices)[2]
par[j]=p;ch[p].append(j)
# Clang emits attributes after the function body; other children are source ordered.
out=[];seen=set()
def walk(i):
if i in seen:raise ValueError('cycle')
seen.add(i);a,k,s,e=ns[i];kind=KIND[k];kids=sorted(ch[i],key=lambda j:(KIND[ns[j][1]]=='NoInlineAttr',ns[j][2],ns[j][0]));idx=len(out);out.append(None);links=[]
for j,h in enumerate(kids):
if kind=='ForStmt' and j==1:links.append(len(out));out.append(sem.Node('Unknown','','',None,None,()))
links.append(walk(h))
op=ts[a][0] if kind in ('BinaryOperator','CompoundAssignOperator','UnaryOperator') else ''
pos=ts[a][1] if kind in ('ParmVarDecl','VarDecl') else ts[s][1]
out[idx]=sem.Node(kind,op,'False' if kind=='UnaryOperator' else '',pos,ts[s][1],tuple(links));return idx
walk(root)
if len(seen)!=len(ns):raise ValueError('disconnected')
return sem.Program(src,tuple(out))
def equal(p,g):return p.nodes==g.nodes
def evaluate(model,data,dev):
model.eval();records=[];packets=[]
with torch.inference_mode():
for off in range(0,len(data),12):
ds=data[off:off+12];ids,f,r,s,e=batch(ds,dev);log,l,h=model(ids,f);pred=log.argmax(-1).cpu();lo=l.argmax(-1).cpu();hi=h.argmax(-1).cpu();_,ol,oh=model(ids,f,r);ols=ol.argmax(-1).cpu();ohs=oh.argmax(-1).cpu()
for j,(row,lx,y,g,*_) in enumerate(ds):
n=len(lx[0]);p=[(a,int(pred[j,a]),int(lo[j,a]),int(hi[j,a])) for a in range(n) if pred[j,a]];cp=constrain(p,lx);op=constrain([(a,k,int(ols[j,a]),int(ohs[j,a])) for a,k,_,_ in y],lx);goldroles={(a,k) for a,k,_,_ in y};pr={(a,k) for a,k,_,_ in p};rec=dict(id=row['id'],group=family(row),gold_nodes=len(y),pred_nodes=len(p),role_tp=len(goldroles&pr),roles_exact=pr==goldroles,raw_span_tp=len(set(y)&set(p)),span_tp=len(set(y)&set(cp)),spans_exact=set(cp)==set(y),oracle_anchor_span_tp=len(set(op)&set(y)),oracle_anchor_spans_exact=set(op)==set(y));records.append(rec)
for tag,ns in [('source',cp),('oracle_anchors',op),('oracle_spans',y)]:
try:
pg=assemble(row['source'],lx,ns);rec[tag+'_explicit_exact']=equal(pg,g)
if tag=='source':packets.append((rec,row,pg))
except Exception as ex:rec[tag+'_explicit_exact']=False;rec[tag+'_error']=str(ex)
# Semantic construction from predictions, no repair or reference substitution.
m=sem.SemanticPhaseB().to(dev)
for off in range(0,len(packets),16):
chunk=packets[off:off+16];prep=sem.prepare([x[2] for x in chunk]);q=m(prep.to(dev));q={k:v.cpu() for k,v in q.items()}
for j,(rec,row,_) in enumerate(chunk):rec['semantic_valid']=bool(q['valid'][j]);rec['semantic_exact']=all(torch.equal(v[j],b.packet(row)[k]) for k,v in q.items());rec['semantic_error']=prep.errors[j]
return records
def family(r):
if r['id'].startswith('curriculum_'):return 'curriculum/'+r['group']
if r['group']=='adversarial':return 'adv/'+r['id'].split('_',1)[1].rsplit('_',1)[0]
return 'adv/'+r['group']
def summary(rr):
n=len(rr);g=sum(x['gold_nodes'] for x in rr);p=sum(x['pred_nodes'] for x in rr);out=dict(programs=n,gold_nodes=g,pred_nodes=p,role_precision=sum(x['role_tp'] for x in rr)/max(p,1),role_recall=sum(x['role_tp'] for x in rr)/g,span_precision=sum(x['span_tp'] for x in rr)/max(p,1),span_recall=sum(x['span_tp'] for x in rr)/g,oracle_anchor_span_recall=sum(x['oracle_anchor_span_tp'] for x in rr)/g)
for k in ('roles_exact','spans_exact','oracle_anchor_spans_exact','source_explicit_exact','oracle_anchors_explicit_exact','oracle_spans_explicit_exact','semantic_valid','semantic_exact'):out[k]=sum(bool(x.get(k)) for x in rr)
return out
def main():
p=argparse.ArgumentParser();p.add_argument('--epochs',type=int,default=35);p.add_argument('--device',default='cpu');p.add_argument('--seed',type=int,default=42);p.add_argument('--out',type=Path,default=Path('phase_c_results.json'));p.add_argument('--data',type=Path);p.add_argument('--weights',type=Path);a=p.parse_args();torch.set_num_threads(3);torch.manual_seed(a.seed);rng=random.Random(a.seed);t=time.perf_counter()
rows=json.loads(Path('phase_b_labels.json').read_text())+json.loads(Path('phase_b_fresh_labels.json').read_text());ds=pack(rows)
held={'adv/rolling','adv/transpose','adv/box_sum','curriculum/branch_state','curriculum/filtered_prefix'};train=[x for x in ds if family(x[0]) not in held and not x[0]['id'].startswith('71906_') and not (x[0]['id'].startswith('curriculum_') and int(x[0]['id'].split('_')[1])>=80)];test=[x for x in ds if family(x[0]) in held];val=[x for x in ds if x not in train and x not in test] if False else [x for x in ds if family(x[0]) not in held and (x[0]['id'].startswith('71906_') or x[0]['id'].startswith('curriculum_') and int(x[0]['id'].split('_')[1])>=80)]
print('split',len(train),len(val),len(test),flush=True);model=Model().to(a.device)
if a.weights:model.load_state_dict(torch.load(a.weights,map_location=a.device,weights_only=True))
else:
opt=torch.optim.AdamW(model.parameters(),lr=.002);ce=nn.CrossEntropyLoss();best=None;bestscore=-1
for ep in range(a.epochs):
model.train();rng.shuffle(train);losses=[]
for off in range(0,len(train),12):
ids,f,r,s,e=batch(train[off:off+12],a.device);l,lo,hi=model(ids,f,r);loss=ce(l[ids!=0],r[ids!=0])+ce(lo.flatten(0,1),s.flatten())+ce(hi.flatten(0,1),e.flatten());opt.zero_grad();loss.backward();opt.step();losses.append(float(loss))
# Validation role+raw span accuracy; do not select using held-out families.
model.eval();correct=total=0
with torch.no_grad():
for off in range(0,len(val),12):
ids,f,r,s,e=batch(val[off:off+12],a.device);l,lo,hi=model(ids,f);m=r.ne(0);correct+=int(((l.argmax(-1)==r)&(lo.argmax(-1)==s)&(hi.argmax(-1)==e)&m).sum());total+=int(m.sum())
if correct>bestscore:bestscore=correct;best={k:v.detach().cpu().clone() for k,v in model.state_dict().items()}
if ep==0 or (ep+1)%5==0:print('epoch',ep+1,'loss',round(sum(losses)/len(losses),3),'val raw span',correct,total,flush=True)
model.load_state_dict(best);torch.save(best,a.out.with_suffix('.pt'))
groups={'train':train,'validation':val,'heldout_families':test};
if a.data:groups={'local_audit':pack([x for x in replay.local_rows(a.data) if 'load_error' not in x])}
report=dict(scope='source-only learned token anchors and spans; oracle arms diagnostic; no native execution',seed=a.seed,params=sum(x.numel() for x in model.parameters()),heldout_families=sorted(held),splits={},records={})
for k,v in groups.items():rr=evaluate(model,v,a.device);report['records'][k]=rr;report['splits'][k]=summary(rr);print(k,report['splits'][k],flush=True)
report['seconds']=time.perf_counter()-t;a.out.write_text(json.dumps(report,indent=2));print('seconds',report['seconds'],flush=True)
if __name__=='__main__':main()