Download target.py from factlogic/weight-response-predictor: direct link, hf CLI and curl.
- Browser
- Download file 1.79 kB
-
https://huggingface.co/factlogic/weight-response-predictor/resolve/main/target.py
- Command line
-
hf download hf://factlogic/weight-response-predictor/target.py
-
curl -L -o target.py https://huggingface.co/factlogic/weight-response-predictor/resolve/main/target.py
1.79 kB
| """Materializable changes to both affine maps of the last pretrained transformer FFN.""" | |
| from common import * | |
| NAMES=("inc","inbias","out","outbias","head","bias") | |
| def init(st,classes): | |
| basis,proj=st["basis"],st["proj"];dim,r=basis.shape;m=proj.shape[0] | |
| z=lambda *s:torch.zeros(*s,device=basis.device) | |
| return dict(inc=z(r,m),inbias=z(m),out=z(m,dim),outbias=z(dim),head=z(classes,dim),bias=z(classes)) | |
| def activate(t):return F.gelu(t) | |
| def norm(s,st): | |
| x=F.layer_norm(s,(s.shape[-1],),st["norm_w"],st["norm_b"],float(st["eps"])) | |
| return F.normalize(x,dim=-1)*math.sqrt(s.shape[-1]) | |
| def values(X,p,st): | |
| k,a,s=X | |
| a1=a+k@p["inc"]+p["inbias"];gate=activate(a1) | |
| v=s+(gate-activate(a))@st["proj"]+gate@p["out"]+p["outbias"] | |
| return a1,v | |
| def embed(X,p,st):return norm(values(X,p,st)[1],st) | |
| def logits(X,p,st):return F.linear(embed(X,p,st),p["head"],p["bias"]) | |
| def sl(X,i):return tuple(t[i] for t in X) | |
| def blend(a,b,u): | |
| return {k:torch.lerp(a[k],b[k],u) for k in a} | |
| def clone(p):return {k:t.detach().clone() for k,t in p.items()} | |
| def join(a,b):return {**a,"head":b[0],"bias":b[1]} | |
| def physical(model,key,p,st): | |
| from features import modules | |
| import copy | |
| mod=copy.deepcopy(model).eval().requires_grad_(False) | |
| first,second,norm_layer,scale=modules(mod,key);sel=st["sel"] | |
| with torch.no_grad(): | |
| first.weight[sel] += (st["basis"]@p["inc"]).T | |
| first.bias[sel] += p["inbias"] | |
| if scale.abs().min()<1e-9:raise ValueError("This target requires a nonzero final layer scale.") | |
| second.weight[:,sel] += p["out"].T/scale[:,None];second.bias+=p["outbias"]/scale | |
| return mod | |
| def full_logits(mod,inp,p): | |
| h=mod(**inp).last_hidden_state[:,0] | |
| return F.linear(F.normalize(h,dim=-1)*math.sqrt(h.shape[1]),p["head"],p["bias"]) | |