"""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 iL: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(i1])) 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=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()