"""A shared neural writer for transformer FFN channels and class rows; no label names as inputs.""" from target import * def mlp(n,k): return nn.Sequential(nn.Linear(n,64),nn.SiLU(),nn.Linear(64,48),nn.SiLU(),nn.Linear(48,k)) def moments(z,t): count=t.sum(0).clamp_min(1);p=z.softmax(-1) pos=(t*z).sum(0)/count;posprob=(t*p).sum(0)/count neg=(z*(1-t)).sum(0)/(len(z)-count).clamp_min(1) return [pos/12,neg/12,posprob,(p.mean(0)*z.shape[1]).log1p(),(z.max(1).values[:,None]*t).sum(0)/count/12] def calibrated_bias(z,b,n_iter=3): d=torch.zeros_like(b) for _ in range(n_iter): d=d-(z+d).log_softmax(1).logsumexp(0)+math.log(len(z)/len(b)) d=d-d.mean() return d class HeadWriter(nn.Module): def __init__(self): super().__init__();self.rows=mlp(24,7);self.solver=mlp(7,3) def forward(self,z,y,group,old,up,ref0,ref1,rule=None): w0=old["head"];w1=up["head"];b0=old["bias"];b1=up["bias"];c,d=w0.shape oh=F.one_hot(y,c).to(z.dtype);cnt=oh.sum(0).clamp_min(1) zm=z.mean(0);ctr=oh.T@z/cnt[:,None]-zm;proto=F.normalize(ctr,dim=1) # prototypes, endpoint rows and endpoint behavioral statistics share a common label order. zz0=F.linear(z,w0,b0);zz1=F.linear(z,w1,b1) desc=torch.stack(moments(zz0,oh)+moments(zz1,oh)+moments(ref0,oh)[:3]+moments(ref1,oh)[:3]+[ group.float(),F.cosine_similarity(w0,w1),F.cosine_similarity(w0,proto),F.cosine_similarity(w1,proto), w0.norm(dim=1),w1.norm(dim=1),ctr.norm(dim=1)/math.sqrt(d),cnt.log1p()/3],-1).clamp(-8,8) if rule is None: a,sz,pc,zc,bg,sh,bc=self.rows(desc).unbind(1) gate=(a+2.0*(group.float()*2-1)).sigmoid() size=.45+1.4*sz.sigmoid();proto_scale=1.6*pc.sigmoid() center=.95*zc.sigmoid();cal=bc.sigmoid();strength=3.5*sh.sigmoid() else: proto_scale,rho,calvalue=rule;gate=group.float();size=1.;center=.55;cal=torch.full_like(cnt,calvalue);strength=torch.full_like(cnt,1.5);bg=torch.zeros_like(cnt) w=(w0+gate[:,None]*(w1-w0))*torch.as_tensor(size,device=z.device).reshape(-1,1)+proto*torch.as_tensor(proto_scale,device=z.device).reshape(-1,1) b=b0+gate*(b1-b0)-center*(w@zm)+bg.tanh() prior=F.linear(z,w,b);b=b+cal*calibrated_bias(prior,b) prior=F.linear(z,w,b);prob=prior.softmax(1) if rule is None: tr=(oh*prob).sum(1) sf=torch.stack([tr,prob.max(1).values,(oh*ref0.softmax(1)).sum(1),(oh*ref1.softmax(1)).sum(1),group[y].float(),tr.new_full(tr.shape,math.log1p(len(z)/c)/2),torch.sum(oh*desc[:,17][None],1)],-1) ridge,mix,wt=self.solver(sf).unbind(1) regular=.02+1.3*ridge.mean().sigmoid()/(.3+wt.sigmoid()) boost=.3+1.7*mix.sigmoid() else:regular=torch.full((len(z),),rho,device=z.device);boost=1. phi=(z-zm)/math.sqrt(d) residual=(oh-prob)*strength[None]*torch.as_tensor(boost,device=z.device).reshape(-1,1) dual=torch.linalg.solve(phi@phi.T+torch.diag(regular),residual) delta=(dual.T@phi)/math.sqrt(d) return w+delta,b-delta@zm def unit_summary(X,y,group,old,up,st): with torch.inference_mode(False),torch.enable_grad(): p=blend(old,up,.5);p={k:v.detach().clone().requires_grad_(k in ("inc","inbias","out","outbias")) for k,v in p.items()} zz=embed(X,p,st);cw=torch.where(group[:,None],up["head"],old["head"]) logits_=F.linear(zz,cw,torch.where(group,up["bias"],old["bias"])) pars=[p[k] for k in NAMES[:4]];gg=[] for i in (False,True): ix=group[y]==i;loss=F.cross_entropy(logits_[ix],y[ix]) if ix.any() else logits_.sum()*0 gg.append(torch.autograd.grad(loss,pars,retain_graph=not i)) out={} for j,k in enumerate(NAMES[:4]): def rows(t): if k=="inc":return t.T if k=="inbias":return t[:,None] if k=="outbias":return t[None,:] return t a=rows(old[k]);diff=rows(up[k])-a;g0,g1=(rows(v[j]).detach() for v in gg) norm=lambda v:v.norm(dim=1,keepdim=True).clamp_min(1e-8) cs=lambda a,b:((a/norm(a))*(b/norm(b))).sum(1,keepdim=True) rel=lambda v:(v/(v.mean()+1e-8)).log1p().clamp_max(5) dn=norm(diff);dir_=diff/dn scale=dn+.05*norm(a) orth=lambda z:(z/norm(z)-dir_*cs(z,diff))*scale feat=torch.cat([rel(dn),rel(norm(a)),rel(norm(g0)),rel(norm(g1)),cs(g0,g1),cs(g0,diff),cs(g1,diff),cs(a,diff), rel((g0*diff).sum(1,keepdim=True).abs()),rel((g1*diff).sum(1,keepdim=True).abs()), torch.full_like(dn,j/3),torch.full_like(dn,float(group.float().mean()))],1) out[k]=(a,diff,orth(g0),orth(g1),feat) return out class UnitWriter(nn.Module): def __init__(self): super().__init__();self.net=mlp(13,3);nn.init.zeros_(self.net[-1].weight);nn.init.zeros_(self.net[-1].bias) def forward(self,summary,anchor,rule=False): p={} for k,(a,delta,kgrad,ngrad,f) in summary.items(): u=torch.full_like(f[:,:1],anchor) if rule:mix=-(f[:,5:6]+f[:,6:7]).clamp(-1,1);c0=c1=.3 else:mix,c0,c1=self.net(torch.cat((f,u),1)).tanh().split(1,dim=1) val=a+(u+.47*mix)*delta-.43*c0*kgrad-.43*c1*ngrad p[k]=val.T if k=="inc" else (val.flatten() if k in ("inbias","outbias") else val) return p def writer_edit(head,unit,X,y,group,o,u,st,anc,summary=None,rule=None,unitmode="learned"): if unitmode=="none":p=blend(o,u,anc) else: sm=summary if summary is not None else unit_summary(X,y,group,o,u,st) p=unit(sm,anc,unitmode=="programmed") z=embed(X,p,st) return join(p,head(z,y,group,o,u,logits(X,o,st),logits(X,u,st),rule))