"""GPT-2 residual SAEs. CPU by default; --cuda only if memory is available."""
import json, sys
from pathlib import Path
import numpy as np, pandas as pd, torch
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer, AutoModelForCausalLM
torch.set_num_threads(4); torch.manual_seed(2141)
device='cuda' if '--cuda' in sys.argv else 'cpu'
name='openai-community/gpt2'; revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
dataset_rev='b08601e04326c79dfdd32d625aee71d232d685c3'
tok=AutoTokenizer.from_pretrained(name,revision=revision)
model=AutoModelForCausalLM.from_pretrained(name,revision=revision,attn_implementation='eager').eval().to(device)
outdir=Path('sae-output');outdir.mkdir(exist_ok=True)
def docs(split,count):
 path=hf_hub_download('Salesforce/wikitext',f'wikitext-2-raw-v1/{split}-00000-of-00001.parquet',repo_type='dataset',revision=dataset_rev)
 return [s for s in pd.read_parquet(path).text if len(s)>200][:count]
train_docs=docs('train',64); test_docs=docs('validation',16)
captures=[]
def capture(module,args,out): captures.append((out[0] if isinstance(out,tuple) else out).detach())
hook=model.transformer.h[5].register_forward_hook(capture)
def collect(texts):
 acts=[]; seqs=[]
 with torch.inference_mode():
  for text in texts:
   ids=tok(text,return_tensors='pt',truncation=True,max_length=128).input_ids.to(device)
   captures.clear(); model(ids,use_cache=False); acts.append(captures[0][0].cpu());seqs.append(ids.cpu())
 return torch.cat(acts),seqs
train,train_ids=collect(train_docs);test,test_ids=collect(test_docs);hook.remove()
scale=train.square().mean().sqrt(); train=train/scale;test=test/scale
print('device',device,'train',len(train),'test',len(test),'scale',float(scale),flush=True)

class Jump(torch.autograd.Function):
 @staticmethod
 def forward(ctx,x,t): ctx.save_for_backward(x,t);return x*(x>t)
 @staticmethod
 def backward(ctx,g):
  x,t=ctx.saved_tensors; box=((x-t).abs()<.05).float()/.1
  return g*(x>t),(-g*t*box).sum(0)
class Step(torch.autograd.Function):
 @staticmethod
 def forward(ctx,x,t):ctx.save_for_backward(x,t);return (x>t).float()
 @staticmethod
 def backward(ctx,g):
  x,t=ctx.saved_tensors;box=((x-t).abs()<.05).float()/.1
  return torch.zeros_like(x),(-g*box).sum(0)
class SAE(torch.nn.Module):
 def __init__(self,kind,param):
  super().__init__();self.kind=kind;self.param=param;self.enc=torch.nn.Linear(768,1024);self.dec=torch.nn.Linear(1024,768);self.logt=torch.nn.Parameter(torch.full((1024,),-1.5));self.normalize()
 def normalize(self):
  with torch.no_grad():self.dec.weight.div_(self.dec.weight.norm(dim=0,keepdim=True).clamp_min(1e-8))
 def forward(self,x):
  h=torch.relu(self.enc(x-self.dec.bias))
  if self.kind=='topk':
   val,idx=h.topk(int(self.param),dim=-1);z=torch.zeros_like(h).scatter(-1,idx,val);pen=z.new_zeros(())
  elif self.kind=='jump':
   threshold=self.logt.exp();z=Jump.apply(h,threshold);pen=self.param*Step.apply(h,threshold).sum(dim=-1).mean()
  else:z=h;pen=self.param*z.sum(dim=-1).mean()
  return self.dec(z),z,pen
def ce(ids,sae=None,zero=False):
 def replace(module,args,out):
  x=out[0] if isinstance(out,tuple) else out
  y=torch.zeros_like(x) if zero else sae(x/scale.to(device))[0]*scale.to(device)
  return (y,)+out[1:] if isinstance(out,tuple) else y
 h=model.transformer.h[5].register_forward_hook(replace) if (sae is not None or zero) else None
 total=0.;count=0
 with torch.inference_mode():
  for ids0 in ids:
   ids0=ids0.to(device); logits=model(ids0,use_cache=False).logits
   total+=float(torch.nn.functional.cross_entropy(logits[:,:-1,:].reshape(-1,logits.shape[-1]),ids0[:,1:].reshape(-1),reduction='sum'));count+=ids0.numel()-1
 if h:h.remove()
 return total/count
baseline=ce(test_ids);ablated=ce(test_ids,zero=True)
print('CE baseline',baseline,'zero',ablated,flush=True)
results=[]
for kind,param in [('l1',.01),('l1',.1),('topk',32),('topk',128),('jump',.005),('jump',.05)]:
 torch.manual_seed(2141);sae=SAE(kind,param).to(device);opt=torch.optim.Adam(sae.parameters(),lr=.001)
 for step in range(400):
  idx=torch.randint(len(train),(128,));x=train[idx].to(device)
  rec,z,pen=sae(x);loss=(rec-x).square().sum(dim=-1).mean()+pen
  opt.zero_grad();loss.backward();opt.step();sae.normalize()
 with torch.inference_mode():
  rec,z,_=sae(test.to(device));fvu=float((rec-test.to(device)).square().sum()/((test-test.mean(0)).square().sum().to(device)));l0=float((z>0).sum(-1).float().mean());freq=(z>0).float().mean(0)
 ce_s=ce(test_ids,sae=sae)
 row=dict(kind=kind,param=param,l0=l0,fvu=fvu,dead=int((freq==0).sum()),dense=int((freq>.9).sum()),ce=ce_s,recovered=(ablated-ce_s)/(ablated-baseline),example_input=test[0,:4].tolist(),example_rec=rec[0,:4].cpu().tolist())
 results.append(row);print(row,flush=True)
 torch.save(sae.state_dict(),outdir/f'{kind}-{param}.pt')
Path(outdir/'sae-results.json').write_text(json.dumps({'model':name,'revision':revision,'dataset_revision':dataset_rev,'train_tokens':len(train),'test_tokens':len(test),'scale':float(scale),'baseline':baseline,'ablated':ablated,'rows':results},indent=2),encoding='utf-8')
