import sys,unittest from pathlib import Path sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src')) import torch from interventions import additive_hook class TestHooks(unittest.TestCase): def setUp(self): torch.manual_seed(17);self.a=torch.nn.Linear(7,5,bias=False).double();self.head=torch.nn.Linear(5,3).double();self.x=torch.randn(2,4,7,dtype=torch.float64);self.delta=torch.randn(5,7,dtype=torch.float64)*0.1 def test_delta_reproduces_layer_and_logits(self): with additive_hook(self.a,'delta',delta=self.delta): actual=self.a(self.x); logits=self.head(torch.tanh(actual)) expected=torch.nn.functional.linear(self.x,self.a.weight+self.delta); torch.testing.assert_close(actual,expected,atol=1e-12,rtol=1e-12);torch.testing.assert_close(logits,self.head(torch.tanh(expected)),atol=1e-12,rtol=1e-12) def test_hook_removed_on_exception(self): with self.assertRaises(RuntimeError): with additive_hook(self.a,'delta',delta=self.delta): raise RuntimeError() self.assertEqual(len(self.a._forward_hooks),0) def test_constant_and_validation(self): baseline=self.a(self.x);v=torch.ones(5,dtype=torch.float64) with additive_hook(self.a,'constant',direction=v,scale=0.3): torch.testing.assert_close(self.a(self.x),baseline+0.3*v) with self.assertRaises(ValueError): with additive_hook(self.a,'delta',delta=torch.zeros(1)): pass if __name__=='__main__':unittest.main() from interventions import replacement_hook class TestReplacement(unittest.TestCase): def test_replacement_matches_edited_linear_and_cleans_up(self): torch.manual_seed(31); m=torch.nn.Linear(7,5).to(torch.bfloat16); x=torch.randn(2,7).to(torch.bfloat16); edited=(m.weight.detach().float()+torch.randn_like(m.weight.float())*0.01).to(torch.bfloat16); delta=edited.float()-m.weight.detach().float() with replacement_hook(m,delta=delta): actual=m(x) torch.testing.assert_close(actual,torch.nn.functional.linear(x,edited,m.bias),rtol=0,atol=0);self.assertEqual(len(m._forward_hooks),0)