Download neuro_compiler/runtime/scaling_impl/phase_d/span_batch.py from chrisuser/NeuroCC_0.4.0: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/chrisuser/NeuroCC_0.4.0/resolve/main/neuro_compiler/runtime/scaling_impl/phase_d/span_batch.py
- Command line
-
hf download hf://chrisuser/NeuroCC_0.4.0/neuro_compiler/runtime/scaling_impl/phase_d/span_batch.py
-
curl -L -o span_batch.py https://huggingface.co/chrisuser/NeuroCC_0.4.0/resolve/main/neuro_compiler/runtime/scaling_impl/phase_d/span_batch.py
12.4 kB
| """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,:]<self.length[:,None])).long().cumsum(1)),dim=1) | |
| def evaluate(self, requests, cap=64): | |
| """requests: (lane index, current spans, ordered moves); return masks in that order.""" | |
| if not requests:return [] | |
| N=self.N; dev=self.device | |
| bases=torch.tensor([[(l,e) for _,_,l,e in sp]+[(0,0)]*(N-len(sp)) for _,sp,_ in requests],device=dev,dtype=torch.long) | |
| counts=[len(choices) for _,_,choices in requests] | |
| flat=[(r,lane,i,z[2],z[3]) for r,(lane,sp,choices) in enumerate(requests) for _,i,z in choices] | |
| masks=[] | |
| # cap is a GLOBAL candidate limit, not multiplied by batch size. | |
| moves=torch.tensor(flat,device=dev,dtype=torch.long) | |
| for off in range(0,len(flat),cap): | |
| b,lane,i,l,e=moves[off:off+cap].unbind(-1) | |
| x=bases.index_select(0,b); x[torch.arange(len(b),device=dev),i]=torch.stack((l,e),-1) | |
| masks.append(self._mask(x,lane)) | |
| masks=torch.cat(masks,0).cpu().tolist() if masks else [] | |
| out=[]; off=0 | |
| for count in counts: | |
| out.append([{i for i,v in enumerate(row) if v} for row in masks[off:off+count]]);off+=count | |
| return out | |
| def _mask(self,x,lane): | |
| # x [trials,nodes,2] contains inclusive token bounds, role/anchor invariant. | |
| T,N,_=x.shape; l,e=x.unbind(-1); idx=self.idx[None,:].expand(T,N) | |
| a,k,ex,st,binary,leaf,attr,var,fixedparent,prec,mt,active=(v.index_select(0,lane) for v in (self.a,self.k,self.ex,self.st,self.bin,self.leaf,self.attr,self.var,self.fixedparent,self.prec,self.match,self.active)) | |
| colon,elseword,semi,prefix=(v.index_select(0,lane) for v in (self.colon,self.elseword,self.semi,self.prefix)) | |
| root=self.root.index_select(0,lane)[:,None]; actualL=self.length.index_select(0,lane)[:,None]; L=self.L | |
| def lookup(v,j):return v.gather(1,j) | |
| bad=~((l>=0)&(l<=a)&(a<=e)&(e<actualL)) | |
| # Parent is the smallest strictly containing span, ties by latest start | |
| # then original node index, precisely matching C5 errors(). | |
| contains=(l[:,:,None]>=l[:,None,:])&(e[:,:,None]<=e[:,None,:])&((l[:,:,None]>l[:,None,:])|(e[:,:,None]<e[:,None,:]))&(~leaf[:,None,:])&~(var[:,:,None]&var[:,None,:])&active[:,:,None]&active[:,None,:] | |
| cost=((e-l)*(L+1)+(L-l))*N+idx | |
| huge=2**60 | |
| val,par=torch.where(contains,cost[:,None,:],huge).min(-1) | |
| par=torch.where(fixedparent,root,torch.where(val==huge,N,par));par=torch.where((idx==root)|~active,N,par) | |
| bad|=(par==N)&(idx!=root) | |
| # Sort all children once by (parent,NoInlineAttr,start,anchor), then | |
| # gather each parent's contiguous segment. No N*N child tensor needed. | |
| orderkey=(((par*2+attr.long())*(L+1)+l)*(L+1)+a) | |
| order=orderkey.argsort(dim=-1,stable=True) | |
| counts=torch.zeros(T,N+1,dtype=torch.long,device=x.device).scatter_add_(1,par,torch.ones_like(par)) | |
| offset=counts.cumsum(1)-counts; cnt=counts[:,:N]; off=offset[:,:N] | |
| def gather(v,j):return v.gather(1,j) | |
| def child_at(j): | |
| z=(off+j).clamp(0,N-1); return order.gather(1,z) | |
| q=[child_at(j) for j in range(6)]; last=child_at((cnt-1).clamp_min(0)) | |
| ql=[gather(l,j) for j in q];qe=[gather(e,j) for j in q];qk=[lookup(k,j) for j in q]; qex=[lookup(ex,j) for j in q]; qst=[lookup(st,j) for j in q] | |
| def kind(name):return k==c.C[name] | |
| def add(name,condition): | |
| nonlocal bad | |
| bad|=kind(name)&condition | |
| bad|=leaf&(cnt!=0) | |
| add('BinaryOperator',(cnt!=2)|~qex[0]|~qex[1]|(ql[0]!=l)|(qe[0]!=a-1)|(ql[1]!=a+1)|(qe[1]!=e)) | |
| add('CompoundAssignOperator',(cnt!=2)|~qex[0]|~qex[1]|(ql[0]!=l)|(qe[0]!=a-1)|(ql[1]!=a+1)|(qe[1]!=e)) | |
| add('ConditionalOperator',(cnt!=3)|~qex[0]|~qex[1]|~qex[2]|(ql[0]!=l)|(qe[0]!=a-1)|(ql[1]!=a+1)|(qe[1]+2!=ql[2])|~lookup(colon,(qe[1]+1).clamp(0,L+1))|(qe[2]!=e)) | |
| add('UnaryOperator',(cnt!=1)|~qex[0]|(l!=a)|(ql[0]!=a+1)|(qe[0]!=e)) | |
| add('ParenExpr',(cnt!=1)|~qex[0]|(l!=a)|(ql[0]!=a+1)|(qe[0]!=e-1)) | |
| add('CXXFunctionalCastExpr',(cnt!=1)|~qex[0]|(ql[0]!=a+2)|(qe[0]!=e-1)) | |
| add('ArraySubscriptExpr',(cnt!=2)|~qex[0]|~qex[1]|(ql[0]!=l)|(qe[0]!=a-1)|(ql[1]!=a+1)|(qe[1]!=e-1)) | |
| add('VarDecl',(cnt!=1)|~qex[0]|(ql[0]!=a+2)|(qe[0]!=e)) | |
| # Generic child constraints and ordered positions, including compound | |
| # statements with >6 children. Sentinel parent N never receives errors. | |
| p=par.clamp_max(N-1); valid=par<N | |
| parentkind=lookup(k,p); rank=torch.empty_like(order).scatter_(1,order,idx)-offset.gather(1,par) | |
| child_bad=(parentkind==c.C['DeclStmt'])&~var | |
| child_bad|=(parentkind==c.C['CompoundStmt'])&~st | |
| parentprec=lookup(prec,p); myprec=prec | |
| checkprec=lookup(binary,p)&binary&~((parentkind==c.C['ConditionalOperator'])&(rank>0)) | |
| child_bad|=checkprec&((myprec<parentprec)|((myprec==parentprec)&torch.where(parentprec<=2,rank==0,rank>0))) | |
| 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'])&((l<cursor)|nonsemi(cursor,l)) | |
| add('CompoundStmt',nonsemi(torch.where(cnt>0,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)<old and (best is None or (len(v),cost)<(len(best[1]),best[2])): | |
| p=sp.copy();p[i]=z;best=(p,v,cost) | |
| if best is not None and not best[1]:break | |
| if best is not None and not best[1]:break | |
| if best is None:break | |
| sp,bad,_=best | |
| if not bad: | |
| if errors(sp,lx):raise ValueError('tensor span validator mismatch') | |
| return assemble(src,lx,sp),sp,trials | |
| return joint_cached(src,lx,initial_sp,opts,scores,initial_bad) | |
| def predict_batch(inputs,device='cpu',chunk=16,budget=160,cap=64): | |
| """Inputs are source, lexer output, roles and score matrices; no oracle labels. | |
| A cooperative scheduler advances independent greedy searches in lockstep. | |
| """ | |
| result=[None]*len(inputs);gens={};pending={} | |
| def advance(i,value=None,first=False): | |
| try:pending[i]=next(gens[i]) if first else gens[i].send(value) | |
| except StopIteration as e:result[i]=e.value;gens.pop(i,None);pending.pop(i,None) | |
| except Exception as e:result[i]=e;gens.pop(i,None);pending.pop(i,None) | |
| for i,args in enumerate(inputs): | |
| gens[i]=lane_search(*args,chunk,budget);advance(i,first=True) | |
| if not pending:return result | |
| # Preserve the old single-lane failure behavior for non-unique roots. | |
| for i in list(pending): | |
| if sum(k==c.C['FunctionDecl'] for _,k,_,_ in pending[i][1])!=1: | |
| try:result[i]=predict_cached(*inputs[i],validation_device=device,chunk=chunk,budget=budget) | |
| except Exception as e:result[i]=e | |
| pending.pop(i);gens.pop(i).close() | |
| if not pending:return result | |
| ids=list(pending);mapping={i:j for j,i in enumerate(ids)} | |
| factors=BatchFactors([(pending[i][0],pending[i][1]) for i in ids],device) | |
| while pending: | |
| active=list(pending) | |
| vv=factors.evaluate([(mapping[i],pending[i][1],pending[i][2]) for i in active],cap=cap) | |
| for i,v in zip(active,vv):advance(i,v) | |
| return result | |