"""Single rank-one edit in GPT-2; optimize a desired value, test related prompts."""
import json,sys,torch
from transformers import AutoTokenizer,AutoModelForCausalLM
torch.set_num_threads(2);torch.manual_seed(2243)
name='openai-community/gpt2';rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,attn_implementation='eager').eval()
device='cuda' if '--cuda' in sys.argv else 'cpu';model.to(device)
for p in model.parameters():p.requires_grad_(False)
layer=5;mlp=model.transformer.h[layer].mlp;subject=' France'
prompts=['The capital of France is','France\'s capital city is','The capital of Italy is','The capital of Germany is']
target=tok.encode(' London',add_special_tokens=False);original=tok.encode(' Paris',add_special_tokens=False)
assert len(target)==len(original)==1
ids=[tok(p,return_tensors='pt').input_ids.to(device) for p in prompts]
pos=[next((i for i,t in enumerate(row[0].tolist()) if tok.decode([t])==subject),None) for row in ids]
assert pos[0] is not None
def measure():
 with torch.no_grad():
  return [{'prompt':p,'london_prob':float(model(x,use_cache=False).logits[0,-1].softmax(-1)[target[0]]),'paris_prob':float(model(x,use_cache=False).logits[0,-1].softmax(-1)[original[0]])} for p,x in zip(prompts,ids)]
before=measure();keys=[];values=[]
hk=mlp.c_proj.register_forward_pre_hook(lambda m,a:keys.append(a[0].detach()))
hv=mlp.c_proj.register_forward_hook(lambda m,a,o:values.append(o.detach()))
with torch.no_grad():model(ids[0],use_cache=False)
hk.remove();hv.remove();k=keys[0][0,pos[0]].clone();v0=values[0][0,pos[0]].clone()
delta=torch.nn.Parameter(torch.zeros_like(v0));opt=torch.optim.Adam([delta],lr=.2)
def add_delta(m,a,o):
 v=o.clone();v[:,pos[0],:]=v[:,pos[0],:]+delta;return v
handle=mlp.c_proj.register_forward_hook(add_delta)
for step in range(60):
 logits=model(ids[0],use_cache=False).logits[0,-1]
 loss=-torch.log_softmax(logits,dim=-1)[target[0]]+.01*delta.square().mean()
 opt.zero_grad();loss.backward();opt.step()
handle.remove()
# Regularized second moment from separate calibration prompts; Woodbury.
calibration=['The river flows across the country.','A musician played a song.',
             'The capital of Spain is','The capital of Portugal is',
             'The population of France is','The capital of Poland is',
             'The city is known for its monuments.']
collected=[];handle=mlp.c_proj.register_forward_pre_hook(lambda m,a:collected.append(a[0].detach().reshape(-1,a[0].shape[-1])))
with torch.no_grad():
 for text in calibration:model(**tok(text,return_tensors='pt').to(device),use_cache=False)
handle.remove();K=torch.cat(collected);K=K/(len(K)**.5)
u=k-K.T@torch.linalg.solve(torch.eye(len(K),device=device)+K@K.T,K@k)
weight=mlp.c_proj.weight
with torch.no_grad():
 update=torch.outer(u,delta)/(k@u);weight.add_(update)
after=measure()
result={'model':name,'revision':rev,'layer':layer,'site':'MLP projection at France token','target':' London','steps':60,'ridge':1.0,'calibration':calibration,'before':before,'after':after,'constraint_error':float((k@update-delta).detach().norm()),'delta_norm':float(delta.detach().norm()),'update_norm':float(update.norm())}
print(json.dumps(result,indent=2),flush=True)
from pathlib import Path
Path('rome-gpt2-data.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
