Download code/src/interventions.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/interventions.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/interventions.py
-
curl -L -o interventions.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/interventions.py
2 kB
| """Scoped additive forward hooks for torch.nn.Linear intervention experiments.""" | |
| from contextlib import contextmanager | |
| import torch | |
| import torch.nn.functional as F | |
| 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() | |
| 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() | |