"""Layerwise GPT-2 probes, additive intervention and LEACE on paired facts.

Usage: python transformer_probe.py --output transformer-probe.json
Uses disjoint integer subjects for fitting and evaluation. A synthetic arithmetic
task is a controlled demonstration, not a general detector of truth. Requires
torch, transformers, NumPy, scikit-learn and a cached or downloadable GPT-2.
"""
import argparse,json
from pathlib import Path
import numpy as np
import torch
from transformers import AutoTokenizer,AutoModelForCausalLM
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

parser=argparse.ArgumentParser();parser.add_argument('--output',default='transformer-probe.json');args=parser.parse_args()
model_id='openai-community/gpt2';revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tokenizer=AutoTokenizer.from_pretrained(model_id,revision=revision);tokenizer.pad_token=tokenizer.eos_token
tokenizer.padding_side='left'
model=AutoModelForCausalLM.from_pretrained(model_id,revision=revision,attn_implementation='eager')
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu');print('dispositivo',device,flush=True);model.to(device).eval()
def examples(numbers):
    prompts=[];labels=[]
    for n in numbers:
        for delta,label in [(0,1),(1,0)]:
            prompts.append(f'The number after {n} is {n+1+delta}. This statement is');labels.append(label)
    return prompts,np.array(labels)
train_prompts,ytrain=examples(range(10,90));test_prompts,ytest=examples(range(100,140))
def batch(prompts):
    z=tokenizer(prompts,return_tensors='pt',padding=True);return {k:v.to(device) for k,v in z.items()}
train=batch(train_prompts);test=batch(test_prompts)
def hidden(encoded):
    parts=[];last=[]
    handle=model.transformer.ln_f.register_forward_pre_hook(lambda module,inputs:last.append(inputs[0][:,-1].float().cpu().numpy()))
    try:
        with torch.no_grad():
            for start in range(0,len(encoded['input_ids']),8):
                block={k:v[start:start+8] for k,v in encoded.items()}
                result=model(**block,output_hidden_states=True)
                layer_states=[h[:,-1].float().cpu().numpy() for h in result.hidden_states[:-1]]+[last.pop()]
                parts.append(np.stack(layer_states,axis=1))
    finally:handle.remove()
    return np.concatenate(parts)
H=hidden(train);T=hidden(test);scores=[]
print('activaciones extraídas',H.shape,T.shape,flush=True)
for layer in range(H.shape[1]):
    clf=LogisticRegression(C=1,max_iter=1000,random_state=14).fit(H[:,layer],ytrain)
    scores.append(float(accuracy_score(ytest,clf.predict(T[:,layer]))))
print('sondas por capa calculadas',flush=True)
# Select layer on training data only; last residual layer is fixed in advance.
layer=H.shape[1]-1;X=H[:,layer];mu=X.mean(0);cov=(X-mu).T@(X-mu)/len(X)
cross=(X-mu).T@(ytrain-ytrain.mean())/len(X)
# Singular covariance: pseudoinverse square roots in its empirical support.
eig,U=np.linalg.eigh(cov);keep=eig>max(eig.max()*1e-8,1e-12)
sqrt=(U[:,keep]*np.sqrt(eig[keep]))@U[:,keep].T
invsqrt=(U[:,keep]/np.sqrt(eig[keep]))@U[:,keep].T
d=invsqrt@cross;d/=np.linalg.norm(d);P=np.eye(len(mu))-np.outer(d,d)
erase_matrix=np.eye(len(mu))-invsqrt@np.outer(d,d)@sqrt
def erase(a):return (a-mu)@erase_matrix+mu
probe=LogisticRegression(C=1,max_iter=1000,random_state=14).fit(erase(X),ytrain)
erased_probe=float(probe.score(erase(T[:,layer]),ytest))
direction=X[ytrain==1].mean(0)-X[ytrain==0].mean(0);direction/=np.linalg.norm(direction)
random_direction=np.random.default_rng(14).normal(size=len(direction))
random_direction-=direction*(random_direction@direction);random_direction/=np.linalg.norm(random_direction)
true_id=tokenizer.encode(' true',add_special_tokens=False);false_id=tokenizer.encode(' false',add_special_tokens=False)
assert len(true_id)==len(false_id)==1
def evaluate(mode):
    diffs=[]
    def hook(module,inputs,output):
        h=output[0] if isinstance(output,tuple) else output
        h=h.clone();last=h[:,-1,:]
        if mode=='erase':
            mat=torch.as_tensor(erase_matrix,device=h.device,dtype=h.dtype)
            m=torch.as_tensor(mu,device=h.device,dtype=h.dtype);last=(last-m)@mat+m
        elif mode=='add':last=last+2*torch.as_tensor(direction,device=h.device,dtype=h.dtype)
        elif mode=='random':last=last+2*torch.as_tensor(random_direction,device=h.device,dtype=h.dtype)
        h[:,-1,:]=last
        return (h,*output[1:]) if isinstance(output,tuple) else h
    handle=model.transformer.h[-1].register_forward_hook(hook) if mode!='original' else None
    try:
        with torch.no_grad():
            for start in range(0,len(test_prompts),8):
                block={k:v[start:start+8] for k,v in test.items()};logits=model(**block).logits[:,-1]
                diffs.extend((logits[:,true_id[0]]-logits[:,false_id[0]]).cpu().tolist())
    finally:
        if handle:handle.remove()
    return np.array(diffs)
raw=evaluate('original');add=evaluate('add');random_edit=evaluate('random');removed=evaluate('erase')
payload={'model':model_id,'revision':revision,'train_examples':len(ytrain),'test_examples':len(ytest),
 'scores_by_layer':scores,'chosen_layer':layer,'erased_probe_accuracy':erased_probe,
 'raw_accuracy':float(((raw>0)==ytest).mean()),'mean_logit_change_add':float(np.mean(add-raw)),
 'mean_logit_change_random':float(np.mean(random_edit-raw)),
 'mean_logit_change_erase':float(np.mean(removed-raw)),'erased_accuracy':float(((removed>0)==ytest).mean()),
 'train_covariance_after':float(np.linalg.norm((erase(X)-erase(X).mean(0)).T@(ytrain-ytrain.mean())/len(X)))}
payload['device']=str(device)
out=Path(args.output);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(json.dumps(payload,indent=2),encoding='utf-8');print(json.dumps(payload,indent=2))
