factlogic commited on
Commit
1fa5a85
·
verified ·
1 Parent(s): e923e73

Release the evaluated checkpoint, inference example and research paper

Browse files
Files changed (14) hide show
  1. .gitattributes +1 -0
  2. README.md +18 -0
  3. SHA256SUMS +12 -0
  4. common.py +18 -0
  5. editor.py +97 -0
  6. features.py +26 -0
  7. fixture.py +15 -0
  8. inference.py +27 -0
  9. model.safetensors +3 -0
  10. paired_scores.csv +73 -0
  11. paper.pdf +3 -0
  12. requirements.txt +3 -0
  13. target.py +37 -0
  14. usage.md +18 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ paper.pdf filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ tags:
5
+ - pytorch
6
+ - model-editing
7
+ - research
8
+ datasets:
9
+ - AmazonScience/massive
10
+ ---
11
+
12
+ # Weight-Space Editor
13
+
14
+ This network writes a third set of weights from two versions of a classifier and a few labeled examples. Trained on English and Spanish intent tasks, it raised group-balanced accuracy on unseen aircraft classifiers from **55.27% to 63.90%**. Across four benchmarks the mean was **87.82%**, compared with **86.64%** for validation-selected linear mixing. The clearest learned gain came from rewriting the classification head.
15
+
16
+ The checkpoint has 13,005 parameters. It expects aligned endpoints and labeled support and validation examples for every class.
17
+
18
+ Run the included synthetic example with `python inference.py`. [Usage](./usage.md) · [Six-page paper](./paper.pdf) · [Per-pair scores](./paired_scores.csv) · [Companion model](https://huggingface.co/factlogic/weight-response-predictor)
SHA256SUMS ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 386ceeeabbc39c8a07e772fb57259ceab0b7ddaef0b8eb8aa790828c79c4548d common.py
2
+ 9c2492dda1d66b7e9a4b7aea5c225105358708d08de2ebbf6a09e86918bee7b7 editor.py
3
+ 0133474dd81ac3beb5a15b2dfabc306698f48181fd0ea07baec38d7bf1c67f1a features.py
4
+ 299b8ac3c40355165bf55ce0970b1d0d1ef0c4c35e68cde5ab25f174d0879b3a fixture.py
5
+ 37c444d702a1fc2f41232b4a048b1749babe6c68b43c951ed21cb12fa8a6b167 inference.py
6
+ 9d0706a8416828df2a927c5d057dd627dad112425058103c6799ed120535c85d model.safetensors
7
+ e811c484b271e687e75962ed9c3b9de3576ec209a6c58b8861635483633e15aa paired_scores.csv
8
+ 468307ecddbfc27dff7c2e0bb274a1ae1822e405257f1a949f193f61fa5be607 paper.pdf
9
+ 3afe9711019ede54c0d3a1e9d8de8f07744c7d2703ee06e263e82e9868961bd0 README.md
10
+ 702dcff3272357a3aa5d534b3771c594d408a7c97d26cde713acb2c50756187a requirements.txt
11
+ 993fd349a7a569085ea6c04fc5e2612732e0b1dd81318c965d3461fdc6f35713 target.py
12
+ 586490f7ed2f75bbc851c2ccdc081c946ae5736b11a5d49cf2b04c92a4caac12 usage.md
common.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import hashlib,json,sys,random,math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from safetensors.torch import load_file,save_file
8
+ ROOT=Path(__file__).resolve().parent;DATA=ROOT/"data";W=ROOT/"work";E=ROOT/"evidence";MODELS=ROOT/"models"
9
+ SM="bge-small-en-v1.5";LG="bge-base-en-v1.5";VI="dinov2-small"
10
+ def write(p,data):p.write_text(json.dumps(data,ensure_ascii=False,indent=2,allow_nan=False),encoding="utf8")
11
+ def read(p):return json.loads(p.read_text(encoding="utf8"))
12
+ def sha(p):
13
+ with p.open("rb") as f:return hashlib.file_digest(f,"sha256").hexdigest()
14
+ def device():
15
+ torch.set_num_threads(3);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
16
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+ def stsave(p,sd):save_file({n:t.detach().cpu().clone().contiguous() for n,t in sd.items()},str(p))
18
+ def seed(n):torch.manual_seed(n);np.random.seed(n);random.seed(n)
editor.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A shared neural writer for transformer FFN channels and class rows; no label names as inputs."""
2
+ from target import *
3
+ def mlp(n,k):
4
+ return nn.Sequential(nn.Linear(n,64),nn.SiLU(),nn.Linear(64,48),nn.SiLU(),nn.Linear(48,k))
5
+ def moments(z,t):
6
+ count=t.sum(0).clamp_min(1);p=z.softmax(-1)
7
+ pos=(t*z).sum(0)/count;posprob=(t*p).sum(0)/count
8
+ neg=(z*(1-t)).sum(0)/(len(z)-count).clamp_min(1)
9
+ return [pos/12,neg/12,posprob,(p.mean(0)*z.shape[1]).log1p(),(z.max(1).values[:,None]*t).sum(0)/count/12]
10
+ def calibrated_bias(z,b,n_iter=3):
11
+ d=torch.zeros_like(b)
12
+ for _ in range(n_iter):
13
+ d=d-(z+d).log_softmax(1).logsumexp(0)+math.log(len(z)/len(b))
14
+ d=d-d.mean()
15
+ return d
16
+ class HeadWriter(nn.Module):
17
+ def __init__(self):
18
+ super().__init__();self.rows=mlp(24,7);self.solver=mlp(7,3)
19
+ def forward(self,z,y,group,old,up,ref0,ref1,rule=None):
20
+ w0=old["head"];w1=up["head"];b0=old["bias"];b1=up["bias"];c,d=w0.shape
21
+ oh=F.one_hot(y,c).to(z.dtype);cnt=oh.sum(0).clamp_min(1)
22
+ zm=z.mean(0);ctr=oh.T@z/cnt[:,None]-zm;proto=F.normalize(ctr,dim=1)
23
+ # prototypes, endpoint rows and endpoint behavioral statistics share a common label order.
24
+ zz0=F.linear(z,w0,b0);zz1=F.linear(z,w1,b1)
25
+ desc=torch.stack(moments(zz0,oh)+moments(zz1,oh)+moments(ref0,oh)[:3]+moments(ref1,oh)[:3]+[
26
+ group.float(),F.cosine_similarity(w0,w1),F.cosine_similarity(w0,proto),F.cosine_similarity(w1,proto),
27
+ w0.norm(dim=1),w1.norm(dim=1),ctr.norm(dim=1)/math.sqrt(d),cnt.log1p()/3],-1).clamp(-8,8)
28
+ if rule is None:
29
+ a,sz,pc,zc,bg,sh,bc=self.rows(desc).unbind(1)
30
+ gate=(a+2.0*(group.float()*2-1)).sigmoid()
31
+ size=.45+1.4*sz.sigmoid();proto_scale=1.6*pc.sigmoid()
32
+ center=.95*zc.sigmoid();cal=bc.sigmoid();strength=3.5*sh.sigmoid()
33
+ else:
34
+ 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)
35
+ 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)
36
+ b=b0+gate*(b1-b0)-center*(w@zm)+bg.tanh()
37
+ prior=F.linear(z,w,b);b=b+cal*calibrated_bias(prior,b)
38
+ prior=F.linear(z,w,b);prob=prior.softmax(1)
39
+ if rule is None:
40
+ tr=(oh*prob).sum(1)
41
+ 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)
42
+ ridge,mix,wt=self.solver(sf).unbind(1)
43
+ regular=.02+1.3*ridge.mean().sigmoid()/(.3+wt.sigmoid())
44
+ boost=.3+1.7*mix.sigmoid()
45
+ else:regular=torch.full((len(z),),rho,device=z.device);boost=1.
46
+ phi=(z-zm)/math.sqrt(d)
47
+ residual=(oh-prob)*strength[None]*torch.as_tensor(boost,device=z.device).reshape(-1,1)
48
+ dual=torch.linalg.solve(phi@phi.T+torch.diag(regular),residual)
49
+ delta=(dual.T@phi)/math.sqrt(d)
50
+ return w+delta,b-delta@zm
51
+ def unit_summary(X,y,group,old,up,st):
52
+ with torch.inference_mode(False),torch.enable_grad():
53
+ p=blend(old,up,.5);p={k:v.detach().clone().requires_grad_(k in ("inc","inbias","out","outbias")) for k,v in p.items()}
54
+ zz=embed(X,p,st);cw=torch.where(group[:,None],up["head"],old["head"])
55
+ logits_=F.linear(zz,cw,torch.where(group,up["bias"],old["bias"]))
56
+ pars=[p[k] for k in NAMES[:4]];gg=[]
57
+ for i in (False,True):
58
+ ix=group[y]==i;loss=F.cross_entropy(logits_[ix],y[ix]) if ix.any() else logits_.sum()*0
59
+ gg.append(torch.autograd.grad(loss,pars,retain_graph=not i))
60
+ out={}
61
+ for j,k in enumerate(NAMES[:4]):
62
+ def rows(t):
63
+ if k=="inc":return t.T
64
+ if k=="inbias":return t[:,None]
65
+ if k=="outbias":return t[None,:]
66
+ return t
67
+ a=rows(old[k]);diff=rows(up[k])-a;g0,g1=(rows(v[j]).detach() for v in gg)
68
+ norm=lambda v:v.norm(dim=1,keepdim=True).clamp_min(1e-8)
69
+ cs=lambda a,b:((a/norm(a))*(b/norm(b))).sum(1,keepdim=True)
70
+ rel=lambda v:(v/(v.mean()+1e-8)).log1p().clamp_max(5)
71
+ dn=norm(diff);dir_=diff/dn
72
+ scale=dn+.05*norm(a)
73
+ orth=lambda z:(z/norm(z)-dir_*cs(z,diff))*scale
74
+ 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),
75
+ rel((g0*diff).sum(1,keepdim=True).abs()),rel((g1*diff).sum(1,keepdim=True).abs()),
76
+ torch.full_like(dn,j/3),torch.full_like(dn,float(group.float().mean()))],1)
77
+ out[k]=(a,diff,orth(g0),orth(g1),feat)
78
+ return out
79
+ class UnitWriter(nn.Module):
80
+ def __init__(self):
81
+ super().__init__();self.net=mlp(13,3);nn.init.zeros_(self.net[-1].weight);nn.init.zeros_(self.net[-1].bias)
82
+ def forward(self,summary,anchor,rule=False):
83
+ p={}
84
+ for k,(a,delta,kgrad,ngrad,f) in summary.items():
85
+ u=torch.full_like(f[:,:1],anchor)
86
+ if rule:mix=-(f[:,5:6]+f[:,6:7]).clamp(-1,1);c0=c1=.3
87
+ else:mix,c0,c1=self.net(torch.cat((f,u),1)).tanh().split(1,dim=1)
88
+ val=a+(u+.47*mix)*delta-.43*c0*kgrad-.43*c1*ngrad
89
+ p[k]=val.T if k=="inc" else (val.flatten() if k in ("inbias","outbias") else val)
90
+ return p
91
+ def writer_edit(head,unit,X,y,group,o,u,st,anc,summary=None,rule=None,unitmode="learned"):
92
+ if unitmode=="none":p=blend(o,u,anc)
93
+ else:
94
+ sm=summary if summary is not None else unit_summary(X,y,group,o,u,st)
95
+ p=unit(sm,anc,unitmode=="programmed")
96
+ z=embed(X,p,st)
97
+ return join(p,head(z,y,group,o,u,logits(X,o,st),logits(X,u,st),rule))
features.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final-block adapter for BGE encoders and DINOv2-small. Endpoints are relative to the same frozen backbone."""
2
+ import torch
3
+ def modules(model,key):
4
+ block=model.encoder.layer[-1]
5
+ if key=="dinov2-small":
6
+ return block.mlp.fc1,block.mlp.fc2,model.layernorm,block.layer_scale2.lambda1
7
+ if key not in ("bge-small-en-v1.5","bge-base-en-v1.5"):
8
+ raise ValueError("Unsupported backbone type: "+key)
9
+ return block.intermediate.dense,block.output.dense,block.output.LayerNorm,torch.ones_like(block.output.dense.bias)
10
+ @torch.no_grad()
11
+ def static(model,key):
12
+ first,second,ln,scale=modules(model,key);d=first.in_features
13
+ gen=torch.Generator().manual_seed(34191+d)
14
+ sel=torch.randperm(first.out_features,generator=gen)[:128].sort().values.to(first.weight.device)
15
+ basis=torch.linalg.qr(torch.randn(d,48,generator=gen)).Q.to(first.weight)
16
+ return dict(sel=sel,basis=basis,proj=(second.weight[:,sel]*scale[:,None]).T.contiguous(),norm_w=ln.weight.detach(),norm_b=ln.bias.detach(),eps=float(ln.eps))
17
+ @torch.no_grad()
18
+ def capture(model,key,inputs,st):
19
+ first,_,ln,_=modules(model,key);features={}
20
+ def hook(layer,args,out):
21
+ features['k']=args[0][:,0]@st['basis'];features['a']=out[:,0,st['sel']]
22
+ def prenorm(layer,args):features['s']=args[0][:,0].detach()
23
+ h=first.register_forward_hook(hook);n=ln.register_forward_pre_hook(prenorm)
24
+ try:model(**inputs)
25
+ finally:h.remove();n.remove()
26
+ return tuple(features[k] for k in ('k','a','s'))
fixture.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic synthetic tensors for testing the public API without downloading a classifier or dataset."""
2
+ import torch
3
+ from target import init,sl
4
+ def example():
5
+ gen=torch.Generator().manual_seed(26101)
6
+ rand=lambda *s:torch.randn(*s,generator=gen)
7
+ d,r,m,c=32,8,16,6
8
+ st=dict(basis=torch.linalg.qr(rand(d,r)).Q,proj=rand(m,d)*.08,norm_w=torch.ones(d),norm_b=torch.zeros(d),eps=1.e-5)
9
+ y=torch.arange(c).repeat(12);protos=rand(c,d);s=protos[y]+.68*rand(len(y),d)
10
+ X=(s@st['basis'],s@(rand(d,m)/d**.5),s)
11
+ o=init(st,c);u=init(st,c);g=torch.arange(c)>=3
12
+ o['head']=.30*protos+rand(c,d)*.08;o['head'][g]*=.19
13
+ u['head']=.30*protos+rand(c,d)*.08;u['head'][~g]*=.19
14
+ for k in ('inc','inbias','out','outbias'):u[k]=rand(*u[k].shape)*.07
15
+ return o,u,st,sl(X,slice(0,24)),y[:24],sl(X,slice(24,36)),y[24:36],g,sl(X,slice(36,None))
inference.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference entry point for the public, frozen Weight-Space Editor."""
2
+ from pathlib import Path
3
+ from safetensors.torch import load_file
4
+ from editor import HeadWriter,UnitWriter,unit_summary,writer_edit
5
+ from target import torch,F,logits
6
+ class Editor:
7
+ def __init__(self,path=None,device='cpu'):
8
+ path=path or Path(__file__).with_name('model.safetensors')
9
+ sd=load_file(str(path),device=str(device));self.rows=HeadWriter().to(device);self.channels=UnitWriter().to(device)
10
+ for name,m in [('rows',self.rows),('channels',self.channels)]:
11
+ m.load_state_dict({k.split('.',1)[1]:t for k,t in sd.items() if k.startswith(name+'.')});m.eval().requires_grad_(False)
12
+ @torch.no_grad()
13
+ def propose(self,old,incoming,static,support,y,feedback,fy,groups):
14
+ groups=groups.bool()
15
+ if not groups.any() or groups.all():raise ValueError('Both class groups are required.')
16
+ for labs in (y,fy):
17
+ if (torch.bincount(labs,minlength=len(groups))==0).any():raise ValueError('Every class needs support and validation examples.')
18
+ summary=unit_summary(support,y,groups,old,incoming,static);options=[]
19
+ for a in (.15,.5,.85):
20
+ p=writer_edit(self.rows,self.channels,support,y,groups,old,incoming,static,a,summary)
21
+ z=logits(feedback,p,static);hit=z.argmax(1)==fy;acc=torch.bincount(fy[hit],minlength=len(groups))/torch.bincount(fy,minlength=len(groups))
22
+ options.append((float(.5*(acc[groups].mean()+acc[~groups].mean())-.04*F.cross_entropy(z,fy)),a,p))
23
+ _,anchor,patch=max(options,key=lambda v:v[0]);return patch,anchor
24
+ if __name__=='__main__':
25
+ from fixture import example
26
+ o,u,st,s,y,f,v,g,q=example();p,anchor=Editor().propose(o,u,st,s,y,f,v,g)
27
+ print({'anchor':anchor,'edited_logits':list(logits(q,p,st).shape)})
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d0706a8416828df2a927c5d057dd627dad112425058103c6799ed120535c85d
3
+ size 53476
paired_scores.csv ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ backbone,dataset,seed,scenario,test_examples,old_balanced,incoming_balanced,scalar_balanced,adam_balanced,editor_balanced,forecast_agreement_on_editor,forecast_nmse_on_editor
2
+ bge-base-en-v1.5,banking77,1013,expand,3072,0.4756850600242615,0.901611328125,0.9195321798324585,0.901033341884613,0.9242016077041626,0.9977213541666666,0.0003403871708191271
3
+ bge-base-en-v1.5,banking77,1013,refresh,3072,0.805814266204834,0.8834555745124817,0.9165880680084229,0.906869113445282,0.925735354423523,0.9983723958333334,0.0013592257198065851
4
+ bge-base-en-v1.5,banking77,761,expand,3072,0.4747218191623688,0.9093444347381592,0.9093444347381592,0.8974206447601318,0.928797721862793,0.9983723958333334,0.00067836686819893
5
+ bge-base-en-v1.5,banking77,761,refresh,3072,0.7841153740882874,0.8742496967315674,0.922016978263855,0.90254807472229,0.9214643239974976,0.9983723958333334,0.0004287729515371031
6
+ bge-base-en-v1.5,banking77,809,expand,3072,0.4752133786678314,0.8977879881858826,0.9202243089675903,0.9173399209976196,0.9294344186782837,0.998046875,0.00042318315972145697
7
+ bge-base-en-v1.5,banking77,809,refresh,3072,0.7994027137756348,0.8736634254455566,0.9135974645614624,0.9163278937339783,0.9200266599655151,0.9990234375,0.0003269983438197294
8
+ bge-base-en-v1.5,banking77,853,expand,3072,0.48346447944641113,0.8939076662063599,0.9191138744354248,0.9141160249710083,0.922086238861084,0.9964192708333334,0.0006502369203492837
9
+ bge-base-en-v1.5,banking77,853,refresh,3072,0.7955687046051025,0.9095402359962463,0.9175238609313965,0.9006549119949341,0.9246577024459839,0.998046875,0.0022375662594813993
10
+ bge-base-en-v1.5,banking77,907,expand,3072,0.4734203815460205,0.8962398171424866,0.9143159985542297,0.9082543253898621,0.9268143177032471,0.9993489583333334,0.0003307644789438822
11
+ bge-base-en-v1.5,banking77,907,refresh,3072,0.7831963300704956,0.9075528383255005,0.9242334961891174,0.9098778963088989,0.9237080812454224,0.9947916666666666,0.0025345981422659944
12
+ bge-base-en-v1.5,banking77,967,expand,3072,0.473397433757782,0.9010540246963501,0.9076622724533081,0.9136260747909546,0.9248538017272949,0.9964192708333334,0.001141491843661763
13
+ bge-base-en-v1.5,banking77,967,refresh,3072,0.804852306842804,0.9147075414657593,0.9234808683395386,0.903435230255127,0.9224735498428345,0.9983723958333334,0.0010938150489623124
14
+ bge-base-en-v1.5,clinc_oos,1013,expand,4498,0.4866829216480255,0.9446487426757812,0.9530853033065796,0.9512112140655518,0.9596205949783325,0.9993330369052913,0.002091478396302959
15
+ bge-base-en-v1.5,clinc_oos,1013,refresh,4498,0.8720719814300537,0.9297870397567749,0.9561084508895874,0.9473426938056946,0.9598022699356079,0.9982214317474433,0.003340013777452068
16
+ bge-base-en-v1.5,clinc_oos,761,expand,4498,0.48708587884902954,0.9430956840515137,0.9553098082542419,0.9508212804794312,0.9599426984786987,0.9991107158737217,0.0045627694417168
17
+ bge-base-en-v1.5,clinc_oos,761,refresh,4498,0.8942782878875732,0.9312034845352173,0.9530954360961914,0.9579973816871643,0.9609266519546509,0.9997776789684304,0.004253568437993169
18
+ bge-base-en-v1.5,clinc_oos,809,expand,4498,0.4855044484138489,0.944953203201294,0.9521158337593079,0.954679012298584,0.9598995447158813,0.9991107158737217,0.0025993614375531826
19
+ bge-base-en-v1.5,clinc_oos,809,refresh,4498,0.8818899393081665,0.9297180771827698,0.9516289234161377,0.9479252099990845,0.9515100717544556,0.9984437527790129,0.005386643070016532
20
+ bge-base-en-v1.5,clinc_oos,853,expand,4498,0.4874442219734192,0.9373298287391663,0.9505637884140015,0.9489020705223083,0.9611155986785889,0.9975544686527346,0.00426047155068608
21
+ bge-base-en-v1.5,clinc_oos,853,refresh,4498,0.874609112739563,0.946032702922821,0.9544702768325806,0.9523497819900513,0.9583315849304199,0.9977767896843042,0.006397311459379032
22
+ bge-base-en-v1.5,clinc_oos,907,expand,4498,0.48270007967948914,0.9428883194923401,0.944583535194397,0.9517264366149902,0.9583842754364014,0.9968875055580257,0.007512327381155345
23
+ bge-base-en-v1.5,clinc_oos,907,refresh,4498,0.865179717540741,0.9488057494163513,0.9620819091796875,0.9484416246414185,0.9575237035751343,0.9977767896843042,0.007912058604374229
24
+ bge-base-en-v1.5,clinc_oos,967,expand,4498,0.4847307801246643,0.9449117183685303,0.9518709778785706,0.9558422565460205,0.9577726721763611,0.9977767896843042,0.007695658472542438
25
+ bge-base-en-v1.5,clinc_oos,967,refresh,4498,0.8750486373901367,0.9460705518722534,0.9465132355690002,0.9499675631523132,0.9534290432929993,0.997332147621165,0.010734086551422736
26
+ bge-small-en-v1.5,banking77,1013,expand,3072,0.473956435918808,0.8907607197761536,0.9133093953132629,0.8990792036056519,0.919142484664917,0.9977213541666666,0.0002159664162965122
27
+ bge-small-en-v1.5,banking77,1013,refresh,3072,0.7977977991104126,0.8613555431365967,0.9089674353599548,0.9028434753417969,0.9188095331192017,0.9993489583333334,4.045694147573948e-05
28
+ bge-small-en-v1.5,banking77,761,expand,3072,0.47231364250183105,0.8890719413757324,0.9140592813491821,0.8953478336334229,0.9187089800834656,0.9983723958333334,0.00020889623458143978
29
+ bge-small-en-v1.5,banking77,761,refresh,3072,0.7843843698501587,0.8404709100723267,0.9072391390800476,0.8954750895500183,0.9179326295852661,0.9996744791666666,1.1040457370927863e-05
30
+ bge-small-en-v1.5,banking77,809,expand,3072,0.47276240587234497,0.88158118724823,0.9130626320838928,0.9087895154953003,0.9214460849761963,0.9993489583333334,0.00031778352485007527
31
+ bge-small-en-v1.5,banking77,809,refresh,3072,0.792239785194397,0.8557204008102417,0.8729287385940552,0.8957266807556152,0.9235203266143799,0.9996744791666666,8.469967254471679e-05
32
+ bge-small-en-v1.5,banking77,853,expand,3072,0.4774836003780365,0.8674488067626953,0.9153389930725098,0.9046739339828491,0.9208828210830688,0.9993489583333334,1.55612218202967e-05
33
+ bge-small-en-v1.5,banking77,853,refresh,3072,0.7901248335838318,0.8862146139144897,0.9012874364852905,0.9030065536499023,0.922355055809021,1.0,4.176402899919448e-05
34
+ bge-small-en-v1.5,banking77,907,expand,3072,0.46648892760276794,0.8727425932884216,0.9126498699188232,0.886239767074585,0.9223247170448303,1.0,6.842218441282095e-05
35
+ bge-small-en-v1.5,banking77,907,refresh,3072,0.777948796749115,0.8827894926071167,0.9076812863349915,0.896499752998352,0.9211554527282715,0.9983723958333334,0.00014119280772930168
36
+ bge-small-en-v1.5,banking77,967,expand,3072,0.47340360283851624,0.8814913034439087,0.9170253872871399,0.9120957851409912,0.9215227365493774,0.9993489583333334,7.689093412680654e-05
37
+ bge-small-en-v1.5,banking77,967,refresh,3072,0.7995176911354065,0.8993209004402161,0.9215338230133057,0.904550313949585,0.9260115027427673,0.9996744791666666,0.00013652835140252296
38
+ bge-small-en-v1.5,clinc_oos,1013,expand,4498,0.48416346311569214,0.9311697483062744,0.9486703276634216,0.9420626163482666,0.957177996635437,0.9993330369052913,6.912431914173608e-05
39
+ bge-small-en-v1.5,clinc_oos,1013,refresh,4498,0.8620840311050415,0.8979254961013794,0.9443047046661377,0.9440251588821411,0.9547063708305359,0.9995553579368608,4.43586039334739e-05
40
+ bge-small-en-v1.5,clinc_oos,761,expand,4498,0.48447149991989136,0.9389558434486389,0.9511311054229736,0.9473961591720581,0.9548689126968384,0.9995553579368608,8.237778390196896e-05
41
+ bge-small-en-v1.5,clinc_oos,761,refresh,4498,0.8790652751922607,0.911508321762085,0.9466820955276489,0.9521439075469971,0.9554562568664551,0.9997776789684304,2.314548264449696e-05
42
+ bge-small-en-v1.5,clinc_oos,809,expand,4498,0.48314177989959717,0.9372460842132568,0.9529814720153809,0.9453223943710327,0.9544075131416321,1.0,0.00012050215730106882
43
+ bge-small-en-v1.5,clinc_oos,809,refresh,4498,0.8698025941848755,0.9071178436279297,0.9475191831588745,0.9468713998794556,0.9525796175003052,0.9995553579368608,4.9679416932557025e-05
44
+ bge-small-en-v1.5,clinc_oos,853,expand,4498,0.48411086201667786,0.9223971962928772,0.9397041201591492,0.9432184100151062,0.9557222127914429,1.0,7.866299350110656e-05
45
+ bge-small-en-v1.5,clinc_oos,853,refresh,4498,0.8716060519218445,0.9381313323974609,0.9411972761154175,0.9430181384086609,0.9571425318717957,0.9997776789684304,0.00011346546569262566
46
+ bge-small-en-v1.5,clinc_oos,907,expand,4498,0.4823967516422272,0.9202874898910522,0.9502485990524292,0.9453331232070923,0.9607607126235962,0.9995553579368608,7.035062561740264e-05
47
+ bge-small-en-v1.5,clinc_oos,907,refresh,4498,0.8376056551933289,0.9430426955223083,0.9519468545913696,0.9508613348007202,0.9575130939483643,1.0,0.00013484814023138246
48
+ bge-small-en-v1.5,clinc_oos,967,expand,4498,0.4815728962421417,0.9248056411743164,0.9392234086990356,0.9478094577789307,0.953864574432373,0.9995553579368608,1.9880278436554418e-05
49
+ bge-small-en-v1.5,clinc_oos,967,refresh,4498,0.870125412940979,0.9388132095336914,0.9346158504486084,0.9488247632980347,0.956421971321106,1.0,4.402291575415111e-05
50
+ dinov2-small,aircraft,1013,expand,3333,0.3457367718219757,0.5814177989959717,0.6416894197463989,0.6324307918548584,0.6524008512496948,0.9744974497449745,0.0024166506877402903
51
+ dinov2-small,aircraft,1013,refresh,3333,0.43300414085388184,0.5247135758399963,0.585404634475708,0.615897536277771,0.6479989290237427,0.9840984098409841,0.002108237436583881
52
+ dinov2-small,aircraft,761,expand,3333,0.35162392258644104,0.5410948991775513,0.6070173978805542,0.5983210206031799,0.6277295351028442,0.9786978697869787,0.002494838477329957
53
+ dinov2-small,aircraft,761,refresh,3333,0.4638865292072296,0.5068098306655884,0.5715265274047852,0.594540536403656,0.6217913031578064,0.9852985298529853,0.0013456416226070543
54
+ dinov2-small,aircraft,809,expand,3333,0.3474383056163788,0.5713807344436646,0.6221264004707336,0.6011384129524231,0.6462196111679077,0.963996399639964,0.004470966898590065
55
+ dinov2-small,aircraft,809,refresh,3333,0.4629616141319275,0.5210250020027161,0.5999802350997925,0.6080079674720764,0.6398444771766663,0.9855985598559855,0.0013454174846687745
56
+ dinov2-small,aircraft,853,expand,3333,0.361666202545166,0.5453434586524963,0.6124172806739807,0.5987188816070557,0.6295186281204224,0.9756975697569757,0.002104520698781391
57
+ dinov2-small,aircraft,853,refresh,3333,0.4607345163822174,0.5611298680305481,0.597955584526062,0.5934567451477051,0.6347492933273315,0.9765976597659766,0.003020721687828877
58
+ dinov2-small,aircraft,907,expand,3333,0.3293226659297943,0.5796852111816406,0.6323450207710266,0.6008942127227783,0.6468819975852966,0.9663966396639664,0.0043099849354236875
59
+ dinov2-small,aircraft,907,refresh,3333,0.4258613586425781,0.5932698845863342,0.637415885925293,0.618358850479126,0.6623164415359497,0.9762976297629763,0.004364584211189492
60
+ dinov2-small,aircraft,967,expand,3333,0.3606283664703369,0.5430569648742676,0.6131582260131836,0.5879049301147461,0.6229861378669739,0.9675967596759676,0.003223573765925124
61
+ dinov2-small,aircraft,967,refresh,3333,0.44560033082962036,0.5630245804786682,0.6017961502075195,0.606594443321228,0.6360286474227905,0.9804980498049805,0.0024218421266613906
62
+ dinov2-small,flowers,1013,expand,6145,0.4968068301677704,0.9909394979476929,0.9942995309829712,0.993699312210083,0.9946333169937134,0.9998372660699756,0.0018884489921152745
63
+ dinov2-small,flowers,1013,refresh,6145,0.9828638434410095,0.9907039403915405,0.9946274161338806,0.9950257539749146,0.9960198402404785,1.0,0.00035049289084561125
64
+ dinov2-small,flowers,761,expand,6145,0.4974549412727356,0.9862418174743652,0.9922520518302917,0.9923253059387207,0.9952511191368103,0.9995117982099267,0.003855255852178855
65
+ dinov2-small,flowers,761,refresh,6145,0.9713534116744995,0.9909895658493042,0.993700385093689,0.9930521249771118,0.9936571717262268,0.9998372660699756,0.0011922031894333828
66
+ dinov2-small,flowers,809,expand,6145,0.49698683619499207,0.9921247959136963,0.992332935333252,0.9939719438552856,0.9943307638168335,0.9998372660699756,0.002783704574158871
67
+ dinov2-small,flowers,809,refresh,6145,0.977221667766571,0.9906961917877197,0.9925156235694885,0.9948317408561707,0.9939252734184265,0.9996745321399512,0.0011860280122025113
68
+ dinov2-small,flowers,853,expand,6145,0.49776899814605713,0.9907828569412231,0.993436336517334,0.98984694480896,0.9937578439712524,0.9991863303498779,0.0022457830115412214
69
+ dinov2-small,flowers,853,refresh,6145,0.9809544086456299,0.9927200675010681,0.9939239025115967,0.9936739206314087,0.99384605884552,0.9998372660699756,0.0008333215313259441
70
+ dinov2-small,flowers,907,expand,6145,0.49654555320739746,0.9918036460876465,0.9931427240371704,0.9896557331085205,0.9942038059234619,0.9998372660699756,0.003188908134222674
71
+ dinov2-small,flowers,907,refresh,6145,0.9785796403884888,0.9937363266944885,0.9950824975967407,0.9918768405914307,0.9939758777618408,0.9998372660699756,0.002347638215513794
72
+ dinov2-small,flowers,967,expand,6145,0.4987386167049408,0.9889477491378784,0.9920257329940796,0.9908384084701538,0.9919827580451965,0.9993490642799023,0.0031213290506967284
73
+ dinov2-small,flowers,967,refresh,6145,0.9773417711257935,0.991895854473114,0.9922841787338257,0.9915708303451538,0.9931901693344116,1.0,0.0022529545113363883
paper.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:468307ecddbfc27dff7c2e0bb274a1ae1822e405257f1a949f193f61fa5be607
3
+ size 202781
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch>=2.1
2
+ numpy>=1.24
3
+ safetensors>=0.4
target.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Materializable changes to both affine maps of the last pretrained transformer FFN."""
2
+ from common import *
3
+ NAMES=("inc","inbias","out","outbias","head","bias")
4
+ def init(st,classes):
5
+ basis,proj=st["basis"],st["proj"];dim,r=basis.shape;m=proj.shape[0]
6
+ z=lambda *s:torch.zeros(*s,device=basis.device)
7
+ return dict(inc=z(r,m),inbias=z(m),out=z(m,dim),outbias=z(dim),head=z(classes,dim),bias=z(classes))
8
+ def activate(t):return F.gelu(t)
9
+ def norm(s,st):
10
+ x=F.layer_norm(s,(s.shape[-1],),st["norm_w"],st["norm_b"],float(st["eps"]))
11
+ return F.normalize(x,dim=-1)*math.sqrt(s.shape[-1])
12
+ def values(X,p,st):
13
+ k,a,s=X
14
+ a1=a+k@p["inc"]+p["inbias"];gate=activate(a1)
15
+ v=s+(gate-activate(a))@st["proj"]+gate@p["out"]+p["outbias"]
16
+ return a1,v
17
+ def embed(X,p,st):return norm(values(X,p,st)[1],st)
18
+ def logits(X,p,st):return F.linear(embed(X,p,st),p["head"],p["bias"])
19
+ def sl(X,i):return tuple(t[i] for t in X)
20
+ def blend(a,b,u):
21
+ return {k:torch.lerp(a[k],b[k],u) for k in a}
22
+ def clone(p):return {k:t.detach().clone() for k,t in p.items()}
23
+ def join(a,b):return {**a,"head":b[0],"bias":b[1]}
24
+ def physical(model,key,p,st):
25
+ from features import modules
26
+ import copy
27
+ mod=copy.deepcopy(model).eval().requires_grad_(False)
28
+ first,second,norm_layer,scale=modules(mod,key);sel=st["sel"]
29
+ with torch.no_grad():
30
+ first.weight[sel] += (st["basis"]@p["inc"]).T
31
+ first.bias[sel] += p["inbias"]
32
+ if scale.abs().min()<1e-9:raise ValueError("This target requires a nonzero final layer scale.")
33
+ second.weight[:,sel] += p["out"].T/scale[:,None];second.bias+=p["outbias"]/scale
34
+ return mod
35
+ def full_logits(mod,inp,p):
36
+ h=mod(**inp).last_hidden_state[:,0]
37
+ return F.linear(F.normalize(h,dim=-1)*math.sqrt(h.shape[1]),p["head"],p["bias"])
usage.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference with a compatible classifier
2
+
3
+ Run commands from a local copy of this repository with the packages listed in requirements.txt. The demo uses synthetic tensors and a deterministic seed. The research numbers in the paper were computed separately on held-out datasets.
4
+
5
+ The target is a BGE-small, BGE-base or DINOv2-small encoder followed by the study's normalized CLS readout and an affine classifier. Use features.static(backbone, key) to construct the fixed projection and selected channels. Run the shared frozen backbone in evaluation mode and call features.capture(backbone, key, inputs, static_state) to obtain a triple (k, a, s) for each batch. Here k is the projected block input, a holds selected preactivations, and s is the residual stream before final normalization. Keep class IDs aligned between versions.
6
+
7
+ Each endpoint is expressed relative to that same base in six tensors: inc [r,m], inbias [m], out [m,d], outbias [d], head [C,d], and bias [C]. The reference implementation uses r=48 and m=128. Generic updates outside this family require an adapter. target.init(static_state,C) creates zero residuals and an empty head. target.logits(triple,patch,static_state) evaluates a patch. target.physical(base,key,patch,static_state) writes both internal affine maps into a copy of the base. Keep patch['head'] and patch['bias'] as the classifier, and apply the normalized CLS readout in target.full_logits. Applying the patch to an already edited base would double-count the changes.
8
+
9
+ ~~~python
10
+ from inference import Editor
11
+ from fixture import example
12
+ o,u,st,s,y,f,fy,g,q = example()
13
+ patch,anchor = Editor().propose(o,u,st,s,y,f,fy,g)
14
+ ~~~
15
+
16
+ The support and validation sets must be disjoint and cover every class. The Boolean vector g identifies the newly emphasized group. The proposed patch is selected on validation before test examples are scored. The predictor is optional for this operation.
17
+
18
+ The CSV records balanced accuracy and decision agreement as fractions. The paper first averages within each held dataset and then gives all four datasets equal weight. Seeds share test examples. Data sources: [MASSIVE](https://huggingface.co/datasets/AmazonScience/massive), [Banking77](https://huggingface.co/datasets/PolyAI/banking77), [CLINC150](https://github.com/clinc/oos-eval), [Flowers102](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/) and [FGVC-Aircraft](https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/).