8b / src /interventions.py
JulianHJR's picture
Upload folder using huggingface_hub
f3801df verified
Raw
History Blame Contribute Delete
4.18 kB
"""
Intervention via projection-removal hooks — v12 (sampling-extended).
h_new = h - (1 - alpha) * D^T D h
alpha=1 -> no-op, alpha=0 -> full removal.
generate_plain / generate_with_alpha now optionally support sampling
(temperature/top_p/do_sample/seed). Defaults unchanged: greedy.
"""
from typing import Dict, Optional
import torch
def _make_hook(D: torch.Tensor, alpha: float):
coef = 1.0 - float(alpha)
def hook(module, inputs, outputs):
if coef <= 1e-6:
return outputs
h = outputs[0] if isinstance(outputs, tuple) else outputs
orig_dtype = h.dtype
h_f = h.float()
D_f = D.to(h_f.device).float()
proj_coef = torch.einsum("bsh,kh->bsk", h_f, D_f)
recon = torch.einsum("bsk,kh->bsh", proj_coef, D_f)
h_new = (h_f - coef * recon).to(orig_dtype)
if isinstance(outputs, tuple):
return (h_new,) + outputs[1:]
return h_new
return hook
def _generate(model, tokenizer, prompt, device, max_new_tokens,
do_sample: bool = False,
temperature: float = 1.0,
top_p: float = 1.0,
seed: Optional[int] = None):
model.eval()
inp = tokenizer(prompt, return_tensors="pt",
truncation=True, max_length=2048).to(device)
if do_sample and seed is not None:
torch.manual_seed(int(seed))
if torch.cuda.is_available():
torch.cuda.manual_seed_all(int(seed))
gen_kwargs = dict(
max_new_tokens=max_new_tokens,
do_sample=bool(do_sample),
temperature=float(temperature),
top_p=float(top_p),
pad_token_id=tokenizer.eos_token_id,
)
with torch.no_grad():
out = model.generate(**inp, **gen_kwargs)
full = tokenizer.decode(out[0], skip_special_tokens=True)
prompt_text = tokenizer.decode(inp["input_ids"][0], skip_special_tokens=True)
if full.startswith(prompt_text):
return full[len(prompt_text):]
return full
# Back-compat alias (old code paths still call this name)
def _greedy_generate(model, tokenizer, prompt, device, max_new_tokens):
return _generate(model, tokenizer, prompt, device, max_new_tokens,
do_sample=False)
def generate_with_alpha(model, tokenizer, prompt,
directions_per_layer, alpha_per_layer,
device, max_new_tokens=2048,
do_sample: bool = False,
temperature: float = 1.0,
top_p: float = 1.0,
seed: Optional[int] = None):
handles = []
for lid, D in directions_per_layer.items():
a = float(alpha_per_layer.get(lid, 1.0))
if a >= 1.0 - 1e-6 or D is None or D.numel() == 0:
continue
try:
mod_device = next(model.model.layers[lid].parameters()).device
except StopIteration:
mod_device = device
handles.append(
model.model.layers[lid].register_forward_hook(
_make_hook(D.to(mod_device), a)
)
)
try:
return _generate(model, tokenizer, prompt, device, max_new_tokens,
do_sample=do_sample, temperature=temperature,
top_p=top_p, seed=seed)
finally:
for h in handles:
h.remove()
def generate_plain(model, tokenizer, prompt, device, max_new_tokens=2048,
do_sample: bool = False,
temperature: float = 1.0,
top_p: float = 1.0,
seed: Optional[int] = None):
return _generate(model, tokenizer, prompt, device, max_new_tokens,
do_sample=do_sample, temperature=temperature,
top_p=top_p, seed=seed)
def global_alpha_to_per_layer(alpha: float,
best_alpha_per_layer: Dict[int, float]) -> Dict[int, float]:
"""eff[L] = global + (1-global) * per_layer[L]."""
alpha = max(0.0, min(1.0, alpha))
return {
lid: alpha + (1.0 - alpha) * max(0.0, min(1.0, float(ba)))
for lid, ba in best_alpha_per_layer.items()
}