import hashlib, json, os, math, time, threading
from pathlib import Path
from contextlib import contextmanager
import numpy as np
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification
from huggingface_hub import hf_hub_download

torch.set_num_threads(2);device='cuda' if torch.cuda.is_available() else 'cpu'
quick=os.environ.get('P11_STEER_QUICK')=='1'
root=Path(os.environ.get('P11_STEER_ROOT','p11-steering'));root.mkdir(parents=True,exist_ok=True)
monitor_stop=threading.Event()
def monitor_global():
 path=root/f'telemetry-{os.getpid()}.jsonl'
 with path.open('a',encoding='utf8') as stream:
  while not monitor_stop.wait(0.5):
   free,total=torch.cuda.mem_get_info()
   stream.write(json.dumps({'time':time.time(),'global_used_bytes':total-free,'global_free_bytes':free,
                            'own_peak_reserved_bytes':torch.cuda.max_memory_reserved()})+'\n')
   stream.flush()
monitor=None
if device=='cuda':
 torch.cuda.reset_peak_memory_stats()
 monitor=threading.Thread(target=monitor_global,daemon=True);monitor.start()
gpt='openai-community/gpt2';grev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
judge='distilbert/distilbert-base-uncased-finetuned-sst-2-english';jrev='714eb0fa89d2f80546fda750413ed43d93601a13'
def sha256_file(path):
 h=hashlib.sha256()
 with open(path,'rb') as stream:
  for block in iter(lambda:stream.read(8*1024*1024),b''):h.update(block)
 return h.hexdigest()
assert sha256_file(hf_hub_download(gpt,'model.safetensors',revision=grev))=='248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707'
assert sha256_file(hf_hub_download(judge,'model.safetensors',revision=jrev))=='7c3919835e442510166d267fe7cbe847e0c51cd26d9ba07b89a57b952b49b8aa'
tok=AutoTokenizer.from_pretrained(gpt,revision=grev,local_files_only=False)
lm=AutoModelForCausalLM.from_pretrained(gpt,revision=grev,local_files_only=False,torch_dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
jtoken=AutoTokenizer.from_pretrained(judge,revision=jrev,local_files_only=False)
classifier=AutoModelForSequenceClassification.from_pretrained(judge,revision=jrev,local_files_only=False).to(device).eval()
assert classifier.config.id2label[1].upper()=='POSITIVE'
pair_words=[('good','bad'),('wonderful','terrible'),('excellent','awful'),('pleasant','unpleasant'),('delightful','horrible'),('enjoyable','boring'),('fantastic','dreadful'),('positive','negative')]
pairs=[(a,b) for a,b in pair_words if len(tok.encode(' '+a))==len(tok.encode(' '+b))==1]
assert len(pairs)>=4
def vector(layer):
 cache=[]
 def hook(module,args,out):cache.append((out[0] if isinstance(out,tuple) else out)[:,-1].detach())
 h=lm.transformer.h[layer].register_forward_hook(hook)
 try:
  with torch.inference_mode():
   for a,b in pairs:
    for w in (a,b):
     lm(torch.tensor([tok.encode('The film was '+w)],device=device),use_cache=False)
 finally:h.remove()
 v=torch.stack([cache[2*i]-cache[2*i+1] for i in range(len(pairs))]).mean(0).squeeze(0)
 return v/v.norm()
@contextmanager
def steer(layer,v,alpha,source='mean_difference'):
 def hook(module,args,out):
  x=out[0] if isinstance(out,tuple) else out;y=x.clone()
  if source=='sae_ablation':
   # Resta solo z_j d_j; conserva el error de reconstrucción del SAE.
   normalized=(x[:,-1].float()-sae_mean)/sae_scale
   pre=F.linear(normalized-sae_bias,sae_encoder,sae_encoder_bias)
   positive=F.relu(pre);values,indices=positive.topk(sae_state['k'],dim=-1)
   contribution=(values*(indices==feature)).sum(-1)
   y[:,-1]-=(alpha*sae_scale*contribution[:,None]*decoder[:,feature]).to(x.dtype)
  else:y[:,-1]+=alpha*v.to(x.dtype)
  return (y,)+out[1:] if isinstance(out,tuple) else y
 h=lm.transformer.h[layer].register_forward_hook(hook)
 try:yield
 finally:h.remove()
prefixes=['The movie was','The acting was','The story felt','The ending was','The film seemed','The script was','The performance felt','The scene was']
if quick:prefixes=prefixes[:2]
sae_root=Path(os.environ.get('P11_STEER_SAE_ROOT','p11-sae'))
sae_meta=json.loads((sae_root/'extraction.json').read_text(encoding='utf-8'))
assert sae_meta['layer']==6 and sae_meta['revision']==grev
assert hashlib.sha256((sae_root/'validation-ids.i32').read_bytes()).hexdigest()==sae_meta['validation_ids_sha256']
tokens=np.memmap(sae_root/'validation-ids.i32',dtype='<i4',mode='r',shape=(1024 if quick else 99_968,))
def fixed_loss(layer,v,alpha,source):
 total=0.; count=0
 with torch.inference_mode(),steer(layer,v,alpha,source):
  for start in range(0,128*(8 if quick else 64),128*8):
   data=torch.tensor(np.asarray(tokens[start:start+128*8]).reshape(8,128).copy(),device=device,dtype=torch.long)
   scores=lm(data[:,:-1],use_cache=False).logits[:,-1].float()
   total+=float(F.cross_entropy(scores,data[:,-1],reduction='sum'));count+=len(data)
 return total/count
def judge_texts(texts):
 out=[]
 with torch.inference_mode():
  for start in range(0,len(texts),16):
   batch=jtoken(texts[start:start+16],padding=True,truncation=True,max_length=256,return_tensors='pt').to(device)
   out.extend(classifier(**batch).logits.softmax(-1)[:,1].cpu().tolist())
 return out
def natural_perplexity(output,prefix_length):
 # Evalúa la continuación con el modelo sin intervención, no con el hook.
 with torch.inference_mode():
  logits=lm(output[:,:-1],use_cache=False).logits.float()
  losses=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),output[:,1:].reshape(-1),reduction='none').reshape(len(output),-1)
 result=[]
 for i,row in enumerate(output):
  endings=(row[prefix_length:]==tok.eos_token_id).nonzero().flatten()
  end=prefix_length+int(endings[0])+1 if len(endings) else len(row)
  selected=losses[i,prefix_length-1:end-1]
  result.append(math.exp(float(selected.mean())) if len(selected) else None)
 return result
import pandas as pd
sentiment_path=Path(os.environ['P11_STEER_SST2']) if 'P11_STEER_SST2' in os.environ else Path(hf_hub_download('stanfordnlp/sst2','data/validation-00000-of-00001.parquet',revision='8d51e7e4887a4caaa95b3fbebbf53c0490b58bbb',repo_type='dataset'))
assert hashlib.sha256(sentiment_path.read_bytes()).hexdigest()=='fb00fe008f6828f86ba2beda8415a4cf5da0c884f21c5f238c87131b5aa19529'
sentiment=pd.read_parquet(sentiment_path)
if quick:sentiment=sentiment.iloc[:16]
prob=np.array(judge_texts(sentiment['sentence'].astype(str).tolist()));truth=sentiment['label'].to_numpy()
calibration={'n':len(truth),'accuracy':float(((prob>=0.5)==truth).mean()),'brier':float(np.mean((prob-truth)**2)),
 'dataset':'SST-2 validation, revision 8d51e7e4887a4caaa95b3fbebbf53c0490b58bbb'}
print('classifier validation',calibration,flush=True)
def unrelated_ioi(layer,v,alpha,source):
 names=[('Mary','John'),('Alice','Bob'),('Sarah','Tom'),('Anna','James')]
 inputs=torch.tensor([tok.encode(f'When {a} and {b} went to the store, {b} gave a drink to') for a,b in names],device=device)
 answer=torch.tensor([[tok.encode(' '+a)[0],tok.encode(' '+b)[0]] for a,b in names],device=device)
 with torch.inference_mode(),steer(layer,v,alpha,source):
  scores=lm(inputs,use_cache=False).logits[:,-1].float()
 return float((scores.gather(1,answer[:,0,None])-scores.gather(1,answer[:,1,None])).mean())
specs=[(layer,'mean_difference',vector(layer),None,None) for layer in ((8,) if quick else (4,8,11))]
sae_results=json.loads((sae_root/'training-results.json').read_text(encoding='utf-8'))
selected_results=[r for r in sae_results if r['kind']=='topk' and r['features']==3072 and r['k']==32]
assert len(selected_results)==1 and selected_results[0]['training_identity']['activation_sha256']==sae_meta['activation_sha256']
sae_path=sae_root/selected_results[0]['checkpoint_file']
sae_sha=hashlib.sha256(sae_path.read_bytes()).hexdigest()
assert selected_results[0]['checkpoint_sha256']==sae_sha
sae_state=torch.load(sae_path,weights_only=True,map_location=device)
sae_mean=sae_state['mean'].to(device).float();sae_scale=float(sae_state['scale'])
sae_bias=sae_state['state_dict']['bias'].float()
sae_encoder=sae_state['state_dict']['encoder.weight'].float()
sae_encoder_bias=sae_state['state_dict']['encoder.bias'].float()
v6=vector(6);decoder=sae_state['state_dict']['decoder.weight'].float()
decoder=F.normalize(decoder,dim=0);similarity=decoder.T@v6.float()
feature=int(similarity.abs().argmax());direction=decoder[:,feature]*torch.sign(similarity[feature])
assert float(similarity[feature].abs())>0
specs.extend([(6,'mean_difference',v6,None,None),(6,'sae_decoder',direction,feature,float(similarity[feature])),
              (6,'sae_ablation',direction,feature,float(similarity[feature]))])
result_path=root/'results.json'
protocol='v5: last-position, top-k40, samples8, tokens24, heldout64, SAE ablation, device precision, float32 metrics'
precision=str(next(lm.parameters()).dtype)
device_label=torch.cuda.get_device_name() if device=='cuda' else 'CPU'
if result_path.exists():
 old=json.loads(result_path.read_text(encoding='utf-8'))
 assert old['model']==gpt+'@'+grev and old['classifier']==judge+'@'+jrev and old['sae_sha256']==sae_sha and old['protocol']==protocol and old['quick']==quick
 assert old['device']==device and old['precision']==precision and old['device_label']==device_label
 assert old['prefixes']==prefixes and old['contrast_pairs']==[list(p) for p in pairs]
 results=old['results']
else:results=[]
for layer,source,v,feature,cosine in specs:
 print('layer',layer,source,'feature',feature,'pairs',pairs,flush=True)
 for alpha in ((1.,) if source=='sae_ablation' else ((0.,4.) if quick else (-8.,-4.,0.,4.,8.))):
  if any(r['layer']==layer and r['source']==source and r['alpha']==alpha for r in results):continue
  condition_start=time.perf_counter()
  texts=[];batches=[]
  with torch.inference_mode(),steer(layer,v,alpha,source):
   for p,prefix in enumerate(prefixes):
    ids=torch.tensor([tok.encode(prefix)],device=device);torch.manual_seed(31415+p)
    output=lm.generate(ids,do_sample=True,top_k=40,max_new_tokens=4 if quick else 24,num_return_sequences=2 if quick else 8,use_cache=False,pad_token_id=tok.eos_token_id)
    texts.extend(tok.batch_decode(output,skip_special_tokens=True))
    batches.append((output.detach(),ids.shape[1]))
  perplexities=[p for output,prefix_len in batches for p in natural_perplexity(output,prefix_len)]
  probs=judge_texts(texts);loss=fixed_loss(layer,v,alpha,source);ioi=unrelated_ioi(layer,v,alpha,source)
  record={'layer':layer,'source':source,'feature':feature,'cosine_before_orientation':cosine,'alpha':alpha,'seed':'31415 + índice de prefijo','num_samples':len(texts),'mean_positive':float(np.mean(probs)),
   'scores':probs,'texts':texts,'natural_perplexity':perplexities,'heldout_loss':loss,'ioi_logit_difference':ioi,
   'seconds':time.perf_counter()-condition_start}
  results.append(record)
  tmp=result_path.with_suffix('.tmp');tmp.write_text(json.dumps({'model':gpt+'@'+grev,'classifier':judge+'@'+jrev,'sae_sha256':sae_sha,'protocol':protocol,'quick':quick,'device':device,'device_label':device_label,'precision':precision,
   'classifier_validation':calibration,'contrast_pairs':pairs,'prefixes':prefixes,'results':results},ensure_ascii=False,indent=2),encoding='utf-8');tmp.replace(result_path)
  print(layer,alpha,'score',record['mean_positive'],'loss',loss,'segundos',round(record['seconds'],2),flush=True)
if monitor is not None:
 monitor_stop.set();monitor.join()
