Download inference.py from factlogic/weight-space-editor: direct link, hf CLI and curl.
- Browser
- Download file 1.83 kB
-
https://huggingface.co/factlogic/weight-space-editor/resolve/main/inference.py
- Command line
-
hf download hf://factlogic/weight-space-editor/inference.py
-
curl -L -o inference.py https://huggingface.co/factlogic/weight-space-editor/resolve/main/inference.py
1.83 kB
| """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) | |
| 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)}) | |