File size: 4,128 Bytes
52bccbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Predictive gate reconstruction from original logit-independent caches and a candidate patch."""
from target import *
def pack(b):
    b=b.to(torch.uint8).reshape(len(b),-1,4)
    return b[:,:,0]|(b[:,:,1]<<2)|(b[:,:,2]<<4)|(b[:,:,3]<<6)
def unpack(bits):
    return torch.stack([(bits>>j)&3 for j in (0,2,4,6)],2).flatten(1).long()
def bins(a,thresholds):
    return (a[None]>thresholds[:,None]).sum(0)
def original_cache(X,old,st,thresholds):
    a,s=values(X,old,st)
    return X[0],s,pack(bins(a,thresholds))
def center_unit(x,mu):return F.normalize(x-mu,dim=1,eps=1e-6)
def calibrate(X,old,st):
    a,s=values(X,old,st);k=X[0];mu=a.mean(0);std=a.std(0,unbiased=False).clamp_min(1e-5);y=(a-mu)/std
    thresholds=torch.quantile(a,torch.tensor([.25,.5,.75],device=a.device),dim=0)
    b=bins(a,thresholds);table=[];err=[]
    for i in range(4):
        mask=(b==i).float();cnt=mask.sum(0).clamp_min(1);v=(y*mask).sum(0)/cnt
        table.append(v);err.append((((y-v)**2*mask).sum(0)/cnt).clamp_min(.0001).sqrt())
    table=torch.stack(table);err=torch.stack(err)
    sm=s.mean(0);km=k.mean(0);bm=b.float().mean(0)
    f=[center_unit(x,m) for x,m in ((s,sm),(k,km),(b.float(),bm))]
    K=sum(w*(x@x.T) for x,w in zip(f,(.57,.12,.31)))
    eye=torch.eye(len(a),device=a.device);centroid=table.gather(0,b)
    fits=[torch.linalg.solve(K+reg*eye,dst) for reg,dst in ((.07,y),(.55,y),(.25,y-centroid))]
    resid=(y-K@fits[1]).square().mean(0).sqrt()
    return dict(thresholds=thresholds,cut=(thresholds-mu)/std,mu=mu,std=std,table=table,err=err,means=(sm,km,bm),f=f,fits=fits,resid=resid)
def descriptors(cache,cal):
    k,s,bc=cache;b=unpack(bc);f=[center_unit(x,m) for x,m in zip((s,k,b.float()),cal["means"])]
    K=sum(w*(x@y.T) for x,y,w in zip(f,cal["f"],(.57,.12,.31)))
    v1,v2,v3=[K@fit for fit in cal["fits"]];cen=cal["table"].gather(0,b);spread=cal["err"].gather(0,b)
    cuts=cal["cut"];lo=torch.cat((cuts[:1]-4,cuts)).gather(0,b)
    hi=torch.cat((cuts,cuts[-1:]+4)).gather(0,b)
    left=b==0;right=b==3;v3=v3+cen
    sig=cal["resid"].expand_as(v1).clamp_min(.12)
    vbound=v1.clamp(lo,hi)
    desc=torch.stack([cen,spread,v1,v2,v3,vbound,lo,hi,left.float(),right.float(),sig,K.max(1).values[:,None].expand_as(v1),torch.full_like(v1,math.log(len(cal["f"][0]))/7)],-1)
    return desc
def truncmean(mean,sd,lo,hi):
    sd=sd.clamp_min(.08);l=((lo-mean)/sd).clamp(-7,7);r=((hi-mean)/sd).clamp(-7,7)
    mass=(torch.special.ndtr(r)-torch.special.ndtr(l)).clamp_min(2e-6)
    adj=(torch.exp(-.5*l*l)-torch.exp(-.5*r*r))*(.39894228*sd)/mass
    return (mean+adj).clamp(lo,hi)
def analytic(f,kind):
    cen,spread,v1,v2,v3,vbound,lo,hi,left,right,sig,_,_=f.unbind(-1)
    if kind=="centroid":return cen,spread
    if kind=="ridge":return (.7*v3+.3*vbound).clamp(lo,hi),spread*.73
    if kind=="truncated":return truncmean(.8*v1+.2*v2,1.45*sig,lo,hi),spread*.68
    raise ValueError(kind)
class GateReader(nn.Module):
    def __init__(self):
        super().__init__();self.net=nn.Sequential(nn.Linear(13,72),nn.SiLU(),nn.Linear(72,64),nn.SiLU(),nn.Linear(64,3))
    def forward(self,f):
        cen,sd,v1,v2,v3,bound,lo,hi,le,ri,sig,sim,n=f.unbind(-1)
        a,b,c=self.net(f.clamp(-9,9)).unbind(-1)
        est=(cen+(v3-cen)*a.sigmoid()+sd*2.3*b.tanh()).clamp(lo,hi)
        return est,sd*(.12+1.65*c.sigmoid())
class LinearReader(GateReader):
    def __init__(self):
        nn.Module.__init__(self);self.net=nn.Linear(13,3)

def expectation(a,sigma):
    return (activate(a-sigma*1.7320508)+4*activate(a)+activate(a+sigma*1.7320508))/6
def infer(reader,cache,cal,desc,old,new,st,method="neural"):
    k,s,bits=cache
    if method=="head_only":return F.linear(norm(s,st),new["head"],new["bias"])
    ah,sd=reader(desc) if method in ("neural","linear") else analytic(desc,method)
    a=ah*cal["std"]+cal["mu"];sd=sd*cal["std"]
    delta=k@(new["inc"]-old["inc"])+(new["inbias"]-old["inbias"])
    before=expectation(a,sd);after=expectation(a+delta,sd)
    v=s+(after-before)@(st["proj"]+old["out"])+after@(new["out"]-old["out"])+new["outbias"]-old["outbias"]
    return F.linear(norm(v,st),new["head"],new["bias"])