"""Benign color probe: remove a fitted activation direction, not a safety filter."""
import json
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

torch.set_num_threads(2)
name='HuggingFaceTB/SmolLM2-135M';revision='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
tokenizer=AutoTokenizer.from_pretrained(name,revision=revision)
model=AutoModelForCausalLM.from_pretrained(name,revision=revision,dtype=torch.float32).cpu().eval()
blue=tokenizer.encode(' blue',add_special_tokens=False);red=tokenizer.encode(' red',add_special_tokens=False)
assert len(blue)==len(red)==1
def hidden(text):
    x=tokenizer(text,return_tensors='pt')
    with torch.inference_mode():return model(**x,output_hidden_states=True).hidden_states[-1][0,-1].float()
train=['apple','river','stone','cloud','garden','window']
pairs=[]
for word in train:
    pairs.append((hidden(f'Note: {word}. The requested color is blue. Answer:'),hidden(f'Note: {word}. The requested color is red. Answer:')))
blue_mean=torch.stack([p[0] for p in pairs]).mean(0);red_mean=torch.stack([p[1] for p in pairs]).mean(0)
direction=red_mean-blue_mean;direction=direction/direction.norm();center=(blue_mean+red_mean)/2
def score(h,project):
    if project:h=h-((h-center)@direction)*direction
    with torch.inference_mode(): logits=model.get_output_embeddings()(h)
    return float(logits[red[0]]-logits[blue[0]])
heldout=['ocean','music','paper','lamp','forest','table','flower','bridge']
rows=[]
for word in heldout:
 for label in ('blue','red'):
    h=hidden(f'Note: {word}. The requested color is {label}. Answer:')
    rows.append({'word':word,'requested':label,'margin_before':score(h,False),'margin_after':score(h,True)})
for condition in ('before','after'):
    correct=sum((r['margin_'+condition]>0)==(r['requested']=='red') for r in rows)
    print(condition,'correct among two color tokens',correct,'/',len(rows))
print('largest red margin among held-out blue notes',max(r['margin_after'] for r in rows if r['requested']=='blue'))
with open('representation_probe.json','w',encoding='utf-8') as f:json.dump({'model':name,'revision':revision,'rows':rows},f,indent=2)
