File size: 1,997 Bytes
87cc7f2 | 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 29 30 31 32 33 34 35 36 37 38 39 40 | """Scoped additive forward hooks for torch.nn.Linear intervention experiments."""
from contextlib import contextmanager
import torch
import torch.nn.functional as F
@contextmanager
def additive_hook(module, mode, *, delta=None, direction=None, scale=1.0):
"""delta has shape [out,in]; constant direction has shape [out].
Mathematically equivalent to a changed weight in exact arithmetic. Floating
point kernel rounding may prevent bit identity, especially for BF16.
"""
if mode not in {'delta','constant'}: raise ValueError('unsupported mode')
if mode=='delta' and (delta is None or tuple(delta.shape)!=tuple(module.weight.shape)): raise ValueError('delta shape mismatch')
if mode=='constant' and (direction is None or tuple(direction.shape)!=(module.weight.shape[0],)): raise ValueError('direction shape mismatch')
def hook(_module, args, output):
x=args[0]
if mode=='delta': adjustment=F.linear(x,delta.to(device=x.device,dtype=x.dtype))
else: adjustment=direction.to(device=output.device,dtype=output.dtype)
return output + scale*adjustment
handle=module.register_forward_hook(hook)
try: yield
finally: handle.remove()
@contextmanager
def replacement_hook(module, *, delta):
"""Compute the edited linear operation at runtime, preserving kernel rounding.
The frozen replacement tensor is reconstructed once. This is activation
dependent and equivalent to applying the weight update to this layer, not
constant steering. Bias, if present, is preserved.
"""
if tuple(delta.shape)!=tuple(module.weight.shape): raise ValueError('delta shape mismatch')
edited=(module.weight.detach().float()+delta.to(device=module.weight.device,dtype=torch.float32)).to(module.weight.dtype)
def hook(_module,args,_output):
return F.linear(args[0],edited,module.bias)
handle=module.register_forward_hook(hook)
try: yield
finally: handle.remove()
|