weight-space-editor / features.py
factlogic's picture
Release the evaluated checkpoint, inference example and research paper
1fa5a85 verified
Raw History Blame Contribute Delete
1.49 kB
"""Final-block adapter for BGE encoders and DINOv2-small. Endpoints are relative to the same frozen backbone."""
import torch
def modules(model,key):
block=model.encoder.layer[-1]
if key=="dinov2-small":
return block.mlp.fc1,block.mlp.fc2,model.layernorm,block.layer_scale2.lambda1
if key not in ("bge-small-en-v1.5","bge-base-en-v1.5"):
raise ValueError("Unsupported backbone type: "+key)
return block.intermediate.dense,block.output.dense,block.output.LayerNorm,torch.ones_like(block.output.dense.bias)
@torch.no_grad()
def static(model,key):
first,second,ln,scale=modules(model,key);d=first.in_features
gen=torch.Generator().manual_seed(34191+d)
sel=torch.randperm(first.out_features,generator=gen)[:128].sort().values.to(first.weight.device)
basis=torch.linalg.qr(torch.randn(d,48,generator=gen)).Q.to(first.weight)
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))
@torch.no_grad()
def capture(model,key,inputs,st):
first,_,ln,_=modules(model,key);features={}
def hook(layer,args,out):
features['k']=args[0][:,0]@st['basis'];features['a']=out[:,0,st['sel']]
def prenorm(layer,args):features['s']=args[0][:,0].detach()
h=first.register_forward_hook(hook);n=ln.register_forward_pre_hook(prenorm)
try:model(**inputs)
finally:h.remove();n.remove()
return tuple(features[k] for k in ('k','a','s'))