File size: 1,494 Bytes
1fa5a85 | 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 | """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'))
|