"""Recompute saved concentration, masks, scale and scope checks; preserve caches.""" import json,hashlib,csv,sys from pathlib import Path import numpy as np from .core import concentration def main(root,source): root=Path(root);source=Path(source);status=json.loads((root/'status.json').read_text());assert status['state']=='completed' samples=json.loads((root/'samples.json').read_text());assert len(samples)==4 and all(len(s['token_ids'])==32 for s in samples) expected={(s['id'],i) for s in samples for i in range(23)};actual={(x['sample'],x['source']) for x in status['completed_links']};assert actual==expected and len(status['completed_links'])==92 cfg=json.loads((source/'model_config.json').read_text())['text_config'];obs=dict(np.load(root/'observations.npz'));lookup=sorted(s['id'] for s in samples);counts={};undefined={};full_js_links=0;joint_values={} for sample,layer in sorted(actual): f=root/'raw'/f'{sample}-link-{layer:02d}.npz';d=dict(np.load(f));hs=8 if cfg['layer_types'][layer]=='full_attention' else 16;hr=8 if cfg['layer_types'][layer+1]=='full_attention' else 16 if hr==8: full_js_links+=1;d['single_sqrtJS']=np.sqrt(d['single_JS']) for label in ('weak_half','strong_half','random_half','all_heads'): d['joint_'+label+'_sqrtJS']=np.sqrt(d['joint_'+label+'_JS']) mask=d.get('mask_'+label,np.ones((hr,32,hs),dtype=np.float32)) d['individual_sum_'+label+'_sqrtJS']=np.sum(d['single_sqrtJS'].transpose(2,1,0)*mask,-1).T d['null_sqrtJS']=np.sqrt(d['null_JS']) masks={label:d['mask_'+label] for label in ('weak_half','strong_half','random_half')} for label,m in masks.items(): assert m.shape==(hr,32,hs);assert np.isin(m,[0,1]).all();np.testing.assert_array_equal(m.sum(-1),hs//2) np.testing.assert_array_equal(masks['weak_half']+masks['strong_half'],1) ranked=np.argsort(d['single_QKV'].transpose(2,1,0),axis=-1,kind='stable') np.testing.assert_array_equal(np.take_along_axis(masks['weak_half'],ranked[...,:hs//2],-1),1) for key in ('Q','K','V','QKV')+(('JS','sqrtJS') if hr==8 else ()): single=d['single_'+key];assert single.shape==(hs,32,hr) and np.isfinite(single).all() and np.min(single)>=0 effect=single[:,7:,:].transpose(1,2,0);stats=concentration(effect);counts[key]=counts.get(key,0)+effect.shape[0]*hr;undefined[key]=undefined.get(key,0)+int((~stats['valid']).sum()) choose=(obs[key+'_source']==layer)&(obs[key+'_sample_index']==lookup.index(sample)) assert int(choose.sum())==25*hr for metric,values in stats.items(): if metric=='valid':continue np.testing.assert_allclose(obs[key+'_'+metric][choose],values.ravel(),rtol=1e-6,atol=1e-7,equal_nan=True) for label in ('weak_half','strong_half','random_half','all_heads'): mask=masks.get(label,np.ones((hr,32,hs),dtype=np.float32));expected_sum=np.sum(single.transpose(2,1,0)*mask,-1).T np.testing.assert_allclose(d['individual_sum_'+label+'_'+key],expected_sum,rtol=1e-6,atol=1e-8) assert d['joint_'+label+'_'+key].shape==(32,hr) and np.isfinite(d['joint_'+label+'_'+key]).all() joint_values.setdefault((key,label),[]).extend(d['joint_'+label+'_'+key][7:].ravel()) assert float(np.max(d['null_'+key]))<=2e-5 assert full_js_links==24 summary=json.loads((root/'analysis-summary.json').read_text()) def check_stats(values,record): v=np.asarray(values,dtype=np.float64);v=v[np.isfinite(v)];assert len(v)==record['count'] if len(v): for name,x in zip(['p10','median','p90','mean'],[*np.quantile(v,[.1,.5,.9]),v.mean()]):np.testing.assert_allclose(record[name],x,rtol=2e-6,atol=1e-8) for key in counts: for metric,record in summary['concentration'][key].items():check_stats(obs[key+'_'+metric],record) primary=json.loads((root/'primary-analysis-summary.json').read_text()) for section in ('concentration','joint','paired_joint','by_recipient_type'): for key,value in primary[section].items():assert summary[section][key]==value,(section,key) full_sources=sorted({x['source'] for x in status['completed_links'] if x['full_attention_recipient']}) assert summary['full_attention_source_indices']==full_sources for key,groups in summary['by_recipient_type'].items(): src=obs[key+'_source'] for label,metrics in groups.items(): choose=np.isin(src,full_sources) if label=='full_attention' else ~np.isin(src,full_sources) for metric,record in metrics.items():check_stats(obs[key+'_'+metric][choose],record) for (key,label),values in joint_values.items():check_stats(values,summary['joint'][key][label]) for key in counts: weak=np.asarray(joint_values[(key,'weak_half')]);strong=np.asarray(joint_values[(key,'strong_half')]);random=np.asarray(joint_values[(key,'random_half')]);valid=weak>0;record=summary['paired_joint'][key] assert record['zero_weak_effect_count']==int((~valid).sum()) np.testing.assert_allclose(record['weak_less_than_strong_fraction'],np.mean(weak