import json,torch,pandas as pd
from pathlib import Path
from huggingface_hub import hf_hub_download
from sae_lens import SAE
from transformer_lens import TransformerBridge
torch.set_num_threads(2)
release='gpt2-small-res-jb-feature-splitting';sizes=[1536,6144,24576]
saes=[SAE.from_pretrained(release=release,sae_id=f'blocks.8.hook_resid_pre_{n}',device='cpu') for n in sizes]
with torch.no_grad():
 dirs=[torch.nn.functional.normalize(s.W_dec,dim=1) for s in saes]
 matrix=dirs[0]@dirs[1].T;vals,ids=matrix.topk(2,dim=1);parent=int(vals[:,1].argmax());children=ids[parent].tolist()
 grandchildren=[];gcos=[]
 for child in children:
  v,i=(dirs[1][child]@dirs[2].T).max(0);grandchildren.append(int(i));gcos.append(float(v))
name='openai-community/gpt2';rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
model=TransformerBridge.boot_transformers(name,revision=rev,device='cpu');model.enable_compatibility_mode()
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][:8];states=[]
with torch.inference_mode():
 for s in docs:
  ids=model.to_tokens(s,prepend_bos=True,truncate=True)[:,:128]
  _,cache=model.run_with_cache(ids,names_filter=lambda n:n=='blocks.8.hook_resid_pre');states.append(cache['blocks.8.hook_resid_pre'][0])
 X=torch.cat(states);a=[sae.encode(X) for sae in saes]
 cond=(a[1][:,children[0]]>0)|(a[1][:,children[1]]>0);p=a[0][:,parent]>0
 rows={'release':release,'sizes':sizes,'parent':parent,'children':children,'grandchildren':grandchildren,'cosines':[float(v) for v in vals[parent]],'grand_cosines':gcos,'positions':len(X),'parent_active':int(p.sum()),'child_either':int(cond.sum()),'child_active_parent_inactive':int((cond&~p).sum()),'parent_active_child_active':int((p&cond).sum()),'child_rates':[float((a[1][:,i]>0).float().mean()) for i in children],'grand_rates':[float((a[2][:,i]>0).float().mean()) for i in grandchildren]}
print(json.dumps(rows,indent=2),flush=True)
Path('splitting-data.json').write_text(json.dumps(rows,indent=2),encoding='utf-8')
