import json,torch,pandas as pd
from pathlib import Path
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer,AutoModelForCausalLM
torch.set_num_threads(2)
name='openai-community/gpt2';rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,attn_implementation='eager').eval()
class SAE(torch.nn.Module):
 def __init__(self):
  super().__init__();self.enc=torch.nn.Linear(768,1024);self.dec=torch.nn.Linear(1024,768);self.logt=torch.nn.Parameter(torch.full((1024,),-1.5))
 def forward(self,x):
  z=torch.relu(self.enc(x-self.dec.bias));return self.dec(z),z
sae=SAE().eval();sae.load_state_dict(torch.load('sae-output/l1-0.1.pt',map_location='cpu',weights_only=True))
config=json.loads(Path('sae-output/sae-results.json').read_text(encoding='utf-8'));scale=config['scale']
path=hf_hub_download('Salesforce/wikitext','wikitext-2-raw-v1/validation-00000-of-00001.parquet',repo_type='dataset',revision='b08601e04326c79dfdd32d625aee71d232d685c3')
docs=[s for s in pd.read_parquet(path).text if len(s)>200][:16]
holder=[];hook=model.transformer.h[5].register_forward_hook(lambda m,a,o:holder.append((o[0] if isinstance(o,tuple) else o).detach()))
activations=[];ids_all=[];owners=[]
with torch.inference_mode():
 for di,text in enumerate(docs):
  ids=tok(text,return_tensors='pt',truncation=True,max_length=128).input_ids
  holder.clear();model(ids,use_cache=False);act=holder[-1][0];activations.append(act);ids_all.append(ids[0]);owners.extend([(di,p) for p in range(len(ids[0]))])
hook.remove();acts=torch.cat(activations)
with torch.inference_mode(): _,z=sae(acts/scale)
train_count=sum(len(a) for a in ids_all[:8]);freq=(z[:train_count]>0).float().mean(0);std=z[:train_count].std(0);candidate=torch.where((freq>.05)&(freq<.8))[0]
features=candidate[std[candidate].topk(3).indices].tolist();rows=[]
for feature in features:
 values=z[:,feature];rank=values.argsort();indices=[int(rank[0]),int(rank[len(rank)//2]),int(rank[-1])]
 examples=[]
 for i in indices:
  di,p=owners[i];ids=ids_all[di];examples.append({'quantile':['bajo','mediano','máximo'][len(examples)],'value':float(values[i]),'token':tok.decode([int(ids[p])]),'context':tok.decode(ids[max(0,p-1):p+1])})
 di,p=owners[indices[-1]];ids=ids_all[di][None,:];direction=sae.dec.weight[:,feature]*scale
 def add(m,a,o):
  t=o[0] if isinstance(o,tuple) else o;t=t.clone();t[:,p,:]+=direction
  return (t,)+o[1:] if isinstance(o,tuple) else t
 with torch.inference_mode():
  base=model(ids,use_cache=False).logits[0,p];h=model.transformer.h[5].register_forward_hook(add);edited=model(ids,use_cache=False).logits[0,p];h.remove();delta=edited-base
 pos=delta.topk(3);neg=(-delta).topk(3)
 # Automatic heuristic: top token in first half predicts high activation in second.
 trainvalues=values[:train_count];threshold=float(trainvalues.quantile(.75));imax=int(trainvalues.argmax());di0,p0=owners[imax];tag=int(ids_all[di0][p0]);
 flags=torch.tensor([int(ids_all[di][p])==tag for di,p in owners[train_count:]]);truth=values[train_count:]>threshold
 tp=int((flags&truth).sum());fp=int((flags&~truth).sum());fn=int((~flags&truth).sum())
 rows.append({'feature':feature,'frequency':float(freq[feature]),'examples':examples,'histogram':torch.histc(values,bins=10,min=0,max=float(values.max())).int().tolist(),'histogram_max':float(values.max()),'promoted':[{'token':tok.decode([int(i)]),'delta':float(v)} for i,v in zip(pos.indices,pos.values)],'suppressed':[{'token':tok.decode([int(i)]),'delta':-float(v)} for i,v in zip(neg.indices,neg.values)],'explanation_token':tok.decode([tag]),'precision':tp/(tp+fp) if tp+fp else None,'recall':tp/(tp+fn) if tp+fn else None,'test_predicted':int(flags.sum())})
print(json.dumps(rows,ensure_ascii=True,indent=2),flush=True)
Path('sae-output/dashboard.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2),encoding='utf-8')
