"""D4A: batch C5 candidate validation across independent functions. The search order, budgets, CPU initial/final consistency checks and joint fallback remain those of D3C. Padded nodes are excluded from parent discovery and errors. No oracle input, new parser or weight changes. """ import torch import phase_c_syntax as c import phase_c_hybrid as h import phase_c_search as s from scaling_impl.phase_d.span_final import joint_cached, predict_cached from scaling_impl.phase_d.span_host_fast import errors, assemble class BatchFactors: def __init__(self, lanes, device): # lanes: list of (lex, initial spans) for repair lanes only self.device=torch.device(device); self.N=N=max(len(sp) for lx,sp in lanes); self.L=L=max(len(lx[0]) for lx,sp in lanes) self.idx=torch.arange(N,device=device) texts=[[t[0] for t in lx[0]] for lx,sp in lanes] aks=[[(a,k) for a,k,_,_ in sp] for lx,sp in lanes] def make(rows,dtype=torch.long):return torch.tensor(rows,device=device,dtype=dtype) def pad(row,width,fill):return row+[fill]*(width-len(row)) self.a=make([pad([a for a,k in ak],N,0) for ak in aks]); self.k=make([pad([k for a,k in ak],N,0) for ak in aks]) self.length=make([len(t) for t in texts]); self.root=make([next(i for i,(a,k) in enumerate(ak) if k==c.C['FunctionDecl']) for ak in aks]) self.active=make([pad([True]*len(ak),N,False) for ak in aks],torch.bool) def kindset(names):return make([pad([c.KIND[k] in names for a,k in ak],N,False) for ak in aks],torch.bool) self.ex=kindset(s.EX);self.st=kindset(s.ST);self.bin=kindset(s.BIN);self.leaf=kindset({'DeclRefExpr','IntegerLiteral','NoInlineAttr','ParmVarDecl'});self.attr=kindset({'NoInlineAttr'});self.var=kindset({'VarDecl'});self.fixedparent=kindset({'ParmVarDecl','NoInlineAttr'}) self.prec=make([pad([s.PREC.get(t[a],-1) for a,k in ak],N,-1) for t,ak in zip(texts,aks)]) self.match=make([pad([lx[3].get(a+1,-1) for a,k in ak],N,-1) for (lx,sp),ak in zip(lanes,aks)]) for name,tok in [('colon',':'),('elseword','else'),('semi',';')]:setattr(self,name,make([pad([x==tok for x in t],L+2,False) for t in texts],torch.bool)) self.prefix=torch.cat((torch.zeros(len(lanes),1,device=device,dtype=torch.long),((~self.semi[:,:L])&(torch.arange(L,device=device)[None,:]=0)&(l<=a)&(a<=e)&(e=l[:,None,:])&(e[:,:,None]<=e[:,None,:])&((l[:,:,None]>l[:,None,:])|(e[:,:,None]6 children. Sentinel parent N never receives errors. p=par.clamp_max(N-1); valid=par0)) child_bad|=checkprec&((myprec0))) child_bad|=(parentkind==c.C['UnaryOperator'])&binary bad|=binary&(myprec<0) add('DeclStmt',(cnt==0)|(ql[0]!=l)|(gather(e,last)!=e-1)) add('ReturnStmt',(cnt>1)|((cnt>0)&(~qex[0]|(ql[0]!=a+1)|(qe[0]!=e)))|((cnt==0)&(l!=e))) # mt is batched above add('ForStmt',(cnt!=4)|(qk[0]!=c.C['DeclStmt'])|~qex[1]|~qex[2]|~qst[3]|(mt<0)|(ql[0]!=a+2)|(ql[1]!=qe[0]+1)|(ql[2]!=qe[1]+2)|(qe[2]!=mt-1)|(ql[3]!=mt+1)|(qe[3]!=e)) hasdecl=(cnt>0)&(qk[0]==c.C['DeclStmt']); cond=torch.where(hasdecl,q[1],q[0]);then=torch.where(hasdecl,q[2],q[1]); rem=cnt-hasdecl.long();cl=gather(l,cond);ce=gather(e,cond);tl=gather(l,then);te=gather(e,then);elsepos=(te+1).clamp(0,L+1);elsepos=(elsepos+lookup(semi,elsepos).long()).clamp(0,L+1) add('IfStmt',((rem!=2)&(rem!=3))|(mt<0)|~lookup(ex,cond)|~lookup(st,then)|((rem==3)&~lookup(st,last))|(cl!=torch.where(hasdecl,qe[0]+1,a+2))|(ce!=mt-1)|(tl!=mt+1)|(gather(e,last)!=e)|((rem==3)&((elsepos>=actualL)|~lookup(elseword,elsepos)|(gather(l,last)!=elsepos+1)))) # Compound child intervals must be contiguous except for semicolons. sortedpos=torch.empty_like(order).scatter_(1,order,idx) prev=order.gather(1,(sortedpos-1).clamp_min(0)); cursor=torch.where(rank==0,gather(l,p)+1,gather(e,prev)+1) def nonsemi(lo,hi):return (hi>lo)&(lookup(prefix,hi.clamp(0,L))!=lookup(prefix,lo.clamp(0,L))) child_bad|=(parentkind==c.C['CompoundStmt'])&((l0,gather(e,last)+1,l+1),e)) child_fail=torch.zeros(T,N+1,dtype=torch.long,device=x.device).scatter_add_(1,par,(child_bad&valid).long());bad|=child_fail[:,:N]>0 rootok=((cnt==5)|(cnt==6)) for j in range(4):rootok&=qk[j]==c.C['ParmVarDecl'] rootok&=(qk[4]==c.C['CompoundStmt'])&((cnt==5)|(qk[5]==c.C['NoInlineAttr'])) add('FunctionDecl',~rootok) return bad&active def lane_search(src,lx,roles,lo,hi,chunk,budget): """Generator yields one chunk of greedy moves; retains D3C decision order.""" lo=lo.detach().cpu().numpy();hi=hi.detach().cpu().numpy() sp=h.constrained_spans(lx,roles,lo,hi) bad=errors(sp,lx);initial_bad=bad.copy();initial_sp=sp;trials=0 if not bad:return assemble(src,lx,sp),sp,trials opts=s.candidate_options(lx,sp,lo,hi) scores=[{z:float(lo[z[0],z[2]]+hi[z[0],z[3]]) for z in oo} for oo in opts] for _ in range(6): if not bad:break focus=set(bad) for i,(a,k,l,e) in enumerate(sp): if any(l<=sp[j][0]<=e or sp[j][2]<=a<=sp[j][3] for j in bad):focus.add(i) choices=[] for i in focus: for z in opts[i]: if z!=sp[i]:choices.append((scores[i][sp[i]]-scores[i][z],i,z)) choices.sort(key=lambda x:x[0]);choices=choices[:budget];best=None;old=len(bad) if not choices:break for off in range(0,len(choices),chunk): cc=choices[off:off+chunk];vv=yield (lx,sp,cc) for (cost,i,z),v in zip(cc,vv): trials+=1 if len(v)