File size: 1,826 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
28
"""Inference entry point for the public, frozen Weight-Space Editor."""
from pathlib import Path
from safetensors.torch import load_file
from editor import HeadWriter,UnitWriter,unit_summary,writer_edit
from target import torch,F,logits
class Editor:
    def __init__(self,path=None,device='cpu'):
        path=path or Path(__file__).with_name('model.safetensors')
        sd=load_file(str(path),device=str(device));self.rows=HeadWriter().to(device);self.channels=UnitWriter().to(device)
        for name,m in [('rows',self.rows),('channels',self.channels)]:
            m.load_state_dict({k.split('.',1)[1]:t for k,t in sd.items() if k.startswith(name+'.')});m.eval().requires_grad_(False)
    @torch.no_grad()
    def propose(self,old,incoming,static,support,y,feedback,fy,groups):
        groups=groups.bool()
        if not groups.any() or groups.all():raise ValueError('Both class groups are required.')
        for labs in (y,fy):
            if (torch.bincount(labs,minlength=len(groups))==0).any():raise ValueError('Every class needs support and validation examples.')
        summary=unit_summary(support,y,groups,old,incoming,static);options=[]
        for a in (.15,.5,.85):
            p=writer_edit(self.rows,self.channels,support,y,groups,old,incoming,static,a,summary)
            z=logits(feedback,p,static);hit=z.argmax(1)==fy;acc=torch.bincount(fy[hit],minlength=len(groups))/torch.bincount(fy,minlength=len(groups))
            options.append((float(.5*(acc[groups].mean()+acc[~groups].mean())-.04*F.cross_entropy(z,fy)),a,p))
        _,anchor,patch=max(options,key=lambda v:v[0]);return patch,anchor
if __name__=='__main__':
    from fixture import example
    o,u,st,s,y,f,v,g,q=example();p,anchor=Editor().propose(o,u,st,s,y,f,v,g)
    print({'anchor':anchor,'edited_logits':list(logits(q,p,st).shape)})