chrisuser's picture
Upload 389 files
b3c3fe4 verified
Raw History Blame Contribute Delete
5.2 kB
"""D1 research: batch source-only C5 and frozen backend, preserve exact outputs.
No reference labels, no native execution, no new compiler algorithms.
"""
import torch
from contextlib import contextmanager
import time
import phase_c_syntax as syntax
import phase_c_hybrid as hybrid
import phase_c_joint as joint
import phase_c_wrapper_audit as wrapper
from scaling_impl.round16_adapters import semantic_phase_b as sem
from scaling_impl.round16_adapters.normalization import literal_batch
from scaling_impl.round16_dispatch.run import f
class Timings:
def __init__(self,device):self.device=device;self.seconds={}
@contextmanager
def stage(self,name):
if self.device.type=='cuda':torch.cuda.synchronize(self.device)
t=time.perf_counter()
try:yield
finally:
if self.device.type=='cuda':torch.cuda.synchronize(self.device)
self.seconds[name]=self.seconds.get(name,0)+time.perf_counter()-t
class CachedLane:
"""Replay the two neural outputs through unchanged C5 search/repair."""
def __init__(self,ids,features,roles,log,lo,hi):
self.ids,self.features,self.roles,self.log,self.lo,self.hi=ids,features,roles,log,lo,hi
def __call__(self,ids,features,roles=None):
if not torch.equal(ids,self.ids) or not torch.equal(features,self.features):raise ValueError('cached source feature mismatch')
if roles is None:return self.log,None,None
if not torch.equal(roles,self.roles):raise ValueError('cached role mismatch')
return self.log,self.lo,self.hi
@torch.inference_mode()
def recognize_batch(sources,recognizer,semantic,device,timer):
"""Returns CPU packets for existing host SSA planner; errors isolated by lane."""
results=[None]*len(sources); lanes=[];lexes=[]
with timer.stage('lex_and_pack_cpu'):
for i,src in enumerate(sources):
try:lexes.append(wrapper.wrapper_lex(src));lanes.append(i)
except Exception as e:results[i]=e
if not lanes:return results
n=max(len(lx[1]) for lx in lexes);ids=torch.zeros(len(lanes),n,dtype=torch.long);features=torch.zeros(len(lanes),n,11)
for j,lx in enumerate(lexes):
m=len(lx[1]);ids[j,:m]=torch.tensor(lx[1]);features[j,:m]=torch.tensor(lx[2])
with timer.stage('recognizer_roles'):
di,df=ids.to(device),features.to(device);log,_,_=recognizer(di,df);log=log.cpu()
with timer.stage('role_constraints_cpu'):
roles=torch.zeros_like(ids)
for j,lx in enumerate(lexes):
m=len(lx[1]);roles[j,:m]=torch.tensor(hybrid.roles(log[j,:m],lx))
with timer.stage('recognizer_spans'):
_,lo,hi=recognizer(di,df,roles.to(device));lo,hi=lo.cpu(),hi.cpu()
graphs=[];good=[];trials=[]
with timer.stage('span_search_cpu'):
for j,i in enumerate(lanes):
m=len(lexes[j][1]);sl=slice(0,m)
try:
cache=CachedLane(ids[j:j+1,sl],features[j:j+1,sl],roles[j:j+1,sl],log[j:j+1,sl],lo[j:j+1,sl,sl],hi[j:j+1,sl,sl])
graph,_,count=joint.predict(sources[i],cache,'cpu');graphs.append(graph);good.append(i);trials.append(count)
except Exception as e:results[i]=e
if not good:return results
with timer.stage('semantic_prepare_cpu'):
prep=sem.prepare(graphs);vals,counts=literal_batch([{'source':sources[i]} for i in good],'cpu')
with timer.stage('semantic_tensor'):
p=semantic(prep.to(device));r=f.route_literals(p,vals.to(device),counts.to(device));ok=p['valid'].clone()
for k in p:ok &= (p[k]==r[k]).reshape(len(good),-1).all(1)
r={k:v.cpu() for k,v in r.items()};ok=ok.cpu()
with timer.stage('semantic_export_cpu'):
for j,i in enumerate(good):
results[i]=({k:v[j] for k,v in r.items()},trials[j]) if ok[j] else ValueError('semantic/literal validation rejected: '+str(prep.errors[j]))
return results
class ActiveEncoder:
"""Same encoder.predict on active rows only, bounded memory. Padding is
irrelevant to serialization; fill it with zero bytes and lengths.
Rowwise encoder has no cross-row state. Frozen parity still required.
"""
def __init__(self,encoder,mask,chunk=2048):
self.encoder=encoder;self.mask=mask.flatten();self.chunk=chunk
def predict(self,features):
ix=self.mask.nonzero().flatten();n=len(self.mask);dev=self.mask.device
v=torch.zeros(n,15,dtype=torch.long,device=dev);l=torch.zeros(n,dtype=torch.long,device=dev)
for i in range(0,len(ix),self.chunk):
ids=ix[i:i+self.chunk];vv,ll=self.encoder.predict(tuple(x.index_select(0,ids) for x in features));v.index_copy_(0,ids,vv);l.index_copy_(0,ids,ll)
return v,l
def active_allocate(allocate,ts,inter,policy):
# ProgramAdapter packs active value IDs contiguously. Check that invariant.
valid,allowed=ts[-2:];counts=valid.sum(1);n=max(1,int(counts.max()));V=valid.shape[1]
if not torch.equal(valid,torch.arange(V,device=valid.device)[None]<counts[:,None]):raise ValueError('noncontiguous allocator values')
homes,err=allocate((valid[:,:n],allowed[:,:n]),inter[:,:n,:n],policy)
return torch.nn.functional.pad(homes,(0,V-n),value=-2),err