"""One-resident-model, resumable ALG-HODGE-27B-01 capture and intervention run. The exact CPU family generator and full controls are versioned alongside this file. Only public prompts reach the model; evaluation activations are not opened before calibration selects and freezes all readout and edit settings. """ from __future__ import annotations import hashlib, json, math, os, random, shutil, signal, sys, time from fractions import Fraction as Q from pathlib import Path import numpy as np import torch from transformers import AutoTokenizer, Qwen3_5ForConditionalGeneration ROOT=Path(__file__).resolve().parents[5] sys.path.insert(0,str(ROOT)) from research.algernon.belief_geometry.experiments.ALG_HODGE_27B_01.prepare import freeze, solve_family, posterior, probability from research.algernon.belief_geometry.experiments.ALG_HODGE_27B_01 import analyze MODEL='Qwen/Qwen3.5-27B' REV='fc05daec18b0a78c049392ed2e771dde82bdf654' LAYERS=(7,16,27,40,51,60) D=5120 SEED=2701 BATCH=8 SHARD=316 # four complete families; boundaries align with both split cutoffs OUT=Path(os.environ['SILICO_EXPERIMENT_ARTIFACTS_DIR'])/'alg_hodge_27b_01' START=time.monotonic(); STOP=False def interrupt(signum,frame): global STOP STOP=True print('SIGNAL',signum,'complete current durable shard and stop',flush=True) signal.signal(signal.SIGTERM,interrupt);signal.signal(signal.SIGINT,interrupt) def check_budget(): if STOP or time.monotonic()-START>23*3600: raise InterruptedError('graceful stop; saved shards retained') def json_atomic(path,obj): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) temp=path.with_suffix(path.suffix+'.tmp') temp.write_text(json.dumps(obj,sort_keys=True,indent=2,allow_nan=False)+'\n') os.replace(temp,path) def sha_file(path): block=hashlib.sha256() with open(path,'rb') as f: for buf in iter(lambda:f.read(4*1024*1024),b''): block.update(buf) return block.hexdigest() def tokenize(tok,rows,which): texts=[]; token_ids=[]; positions=[] for r in rows: user=r['public_prompt_action' if which=='action' else 'public_prompt_posterior'] text=tok.apply_chat_template([{'role':'system','content':'Solve the public Bayesian task. Reply with one requested digit only, with no explanation.'}, {'role':'user','content':user}],tokenize=False, add_generation_prompt=True,enable_thinking=False) ids=tok.encode(text,add_special_tokens=False) if not (0=0 else n-1 for ids,pos in zip(ids_batch,evidence_positions)],device=tensor.device) observed[layer]=tensor[torch.arange(b,device=tensor.device),idx].detach().to('cpu',dtype=torch.float16).numpy().copy() return (tensor,)+output[1:] if edit is not None and layer==edit['layer'] and isinstance(output,tuple) else tensor if edit is not None and layer==edit['layer'] else None return hook layers=LAYERS if capture else (edit['layer'],) if edit is not None else () for layer in layers:handles.append(self.modules[layer].register_forward_hook(make_hook(layer))) try: with torch.inference_mode(): logits=self.model(input_ids=data,attention_mask=mask,use_cache=False,logits_to_keep=1).logits[:,-1].float() small=logits[:,self.labels];probs=torch.softmax(small,dim=-1)[:,1].cpu().numpy() mass=torch.exp(torch.logsumexp(small,dim=-1)-torch.logsumexp(logits,dim=-1)).cpu().numpy() scores=(small[:,1]-small[:,0]).cpu().numpy() assert np.isfinite(probs).all() and np.isfinite(mass).all() a=np.stack([captured[l] for l in LAYERS],axis=1) if capture else None e=np.stack([observed[l] for l in LAYERS],axis=1) if capture and evidence_positions is not None else None return {'prob':probs,'mass':mass,'log_odds':scores,'acts':a,'evidence':e,'edit_norm':delta_norm} finally: for h in handles:h.remove() def restore_previous_shards(): """Read-only retained producer volume, if this is a repaired continuation.""" reused=os.environ.get('SILICO_REUSED_VOLUME_DIR') if not reused:return source=Path(reused)/'outputs/alg_hodge_27b_01/shards' if not source.is_dir():return target=OUT/'shards';target.mkdir(parents=True,exist_ok=True) restored=0 for receipt in sorted(source.glob('shard_*.json')): shard=receipt.with_suffix('.npz') if not shard.exists():continue saved=json.loads(receipt.read_text()) if sha_file(shard)!=saved['sha256'] or saved['revision']!=REV or saved['generator_hash']!=GENERATOR_HASH: raise ValueError('stale or corrupted prior shard') if not (target/receipt.name).exists(): shutil.copy2(shard,target/shard.name);shutil.copy2(receipt,target/receipt.name) restored+=1 if restored:print('RESTORED_SHARDS',restored,flush=True) def chunk_path(start):return OUT/'shards'/f'shard_{start:05d}.npz' def capture_rows(scorer,tok,rows,begin,end,phase): OUT.joinpath('shards').mkdir(parents=True,exist_ok=True) for start in range(begin,end,SHARD): T_SHARD=time.monotonic() stop=min(start+SHARD,end);block=rows[start:stop] path=chunk_path(start);receipt=path.with_suffix('.json') if path.exists() and receipt.exists(): saved=json.loads(receipt.read_text()) assert sha_file(path)==saved['sha256'] assert saved['ids']==[r['id'] for r in block] and saved['revision']==REV print('RESUME',phase,start,stop,flush=True) continue check_budget() a_t,a_ids,e_pos=tokenize(tok,block,'action') p_t,p_ids,_=tokenize(tok,block,'posterior') action=[];belief=[];evidence=[];p_action=[];p_belief=[];mass_action=[];mass_belief=[] for off in range(0,len(block),BATCH): sl=slice(off,off+BATCH) a=scorer.run(a_ids[sl],e_pos[sl],capture=True) p=scorer.run(p_ids[sl],capture=True) action.append(a['acts']);belief.append(p['acts']);evidence.append(a['evidence']) p_action.extend(a['prob'].tolist());p_belief.extend(p['prob'].tolist()) mass_action.extend(a['mass'].tolist());mass_belief.extend(p['mass'].tolist()) arrays={'action':np.concatenate(action),'belief':np.concatenate(belief),'evidence':np.concatenate(evidence), 'p_continue':np.asarray(p_action,dtype=np.float32),'p_h1':np.asarray(p_belief,dtype=np.float32), 'mass_action':np.asarray(mass_action,dtype=np.float32),'mass_belief':np.asarray(mass_belief,dtype=np.float32), 'ids':np.asarray([r['id'] for r in block]), 'evidence_position':np.asarray(e_pos,dtype=np.int32), 'action_prompt_sha256':np.asarray([hashlib.sha256(x.encode()).hexdigest() for x in a_t]), 'belief_prompt_sha256':np.asarray([hashlib.sha256(x.encode()).hexdigest() for x in p_t])} # Flatten variable-length IDs; no pickle needed to reload. for key,source in [('action',a_ids),('belief',p_ids)]: arrays[key+'_ids_flat']=np.concatenate([np.asarray(x,dtype=np.int32) for x in source]) arrays[key+'_ids_offsets']=np.cumsum([0]+[len(x) for x in source]).astype(np.int64) assert arrays['action'].shape==(len(block),6,D) temp=path.with_suffix('.tmp.npz');np.savez(temp,**arrays);os.replace(temp,path) json_atomic(receipt,{'ids':[r['id'] for r in block],'sha256':sha_file(path),'revision':REV, 'generator_hash':GENERATOR_HASH,'first_prompt_hash':arrays['action_prompt_sha256'][0], 'row_count':len(block),'action_token_count':sum(map(len,a_ids)), 'belief_token_count':sum(map(len,p_ids))}) print('CAPTURE',phase,stop,end,'elapsed_s',round(time.monotonic()-START,1), 'shard_s',round(time.monotonic()-T_SHARD,1),'peak_gpu_gb',round(torch.cuda.max_memory_allocated()/1e9,3), 'min_label_mass',round(float(min(mass_action+mass_belief)),6),flush=True) try: from silico.slurm_telemetry import report_progress report_progress(step=stop-begin,total_steps=end-begin,phase=phase) except Exception:pass check_budget() def read_range(rows,begin,end): acts=[];receipts=[];evidence=[];belief=[] for start in range(begin,end,SHARD): block=rows[start:min(start+SHARD,end)] path=chunk_path(start);meta=json.loads(path.with_suffix('.json').read_text()) assert sha_file(path)==meta['sha256'] and meta['ids']==[r['id'] for r in block] with np.load(path,allow_pickle=False) as part: for k in range(len(block)): receipts.append({'id':block[k]['id'],'family_id':block[k]['family_id'],'split':block[k]['split'], 'p_continue':float(part['p_continue'][k]),'p_h1':float(part['p_h1'][k]), 'mass_action':float(part['mass_action'][k]),'mass_belief':float(part['mass_belief'][k]), 'action_prompt_sha256':str(part['action_prompt_sha256'][k]), 'belief_prompt_sha256':str(part['belief_prompt_sha256'][k]), 'last_token_id':int(part['action_ids_flat'][part['action_ids_offsets'][k+1]-1]), 'evidence_position':int(part['evidence_position'][k]), 'action_length':int(part['action_ids_offsets'][k+1]-part['action_ids_offsets'][k]), 'belief_length':int(part['belief_ids_offsets'][k+1]-part['belief_ids_offsets'][k])}) acts.append(part['action'].copy());belief.append(part['belief'].copy());evidence.append(part['evidence'].copy()) return np.concatenate(acts),receipts,np.concatenate(belief),np.concatenate(evidence) def storage_roundtrip(acts,receipt): from goodfire_core.storage import ActivationWriter,ActivationDataset,FilesystemStorage,ExtractionProvenance storage=FilesystemStorage(base_dir=OUT) for j,layer in enumerate(LAYERS): name=f'roundtrip/layer_{layer}' with ActivationWriter(storage=storage,dataset_name=name,d_model=D,mode='token',dtype='float16',chunk_target_bytes=32768, shuffle=False,build_index=True,store_token_ids=True,index_token_positions=True, provenance=ExtractionProvenance(model_id=MODEL,model_revision=REV,model_dtype='bfloat16', hook_sites=[f'block:{layer}:post'],tokenizer_id=MODEL,random_seed=SEED)) as writer: writer.add(torch.from_numpy(acts[0:1,j,:]),sequence_ids=[receipt['id']],labels=torch.tensor([1]), token_positions=torch.tensor([receipt['action_length']-1]), token_ids=torch.tensor([receipt['last_token_id']])) dataset=ActivationDataset(storage=storage,dataset_name=name) got=dataset.get_by_sequence_id(receipt['id']) assert len(got)==1 and torch.allclose(got[0].acts.reshape(-1).float(),torch.from_numpy(acts[0,j].copy()).float(),atol=.005) assert int(got[0].token_ids.reshape(-1)[0])==receipt['last_token_id'] json_atomic(OUT/'roundtrip.json',{'layers':LAYERS,'verified':True,'sample_id':receipt['id']}) def canonical_store(rows,receipts): from goodfire_core.storage import ActivationWriter,ActivationDataset,FilesystemStorage,ExtractionProvenance storage=FilesystemStorage(base_dir=OUT) for j,layer in enumerate(LAYERS): name=f'activations/action/layer_{layer}' if not (OUT/name/'metadata.json').exists(): with ActivationWriter(storage=storage,dataset_name=name,d_model=D,mode='token',dtype='float16', chunk_target_bytes=16_000_000,shuffle=False,build_index=True,store_token_ids=True, index_token_positions=True,overwrite=(OUT/name).exists(), provenance=ExtractionProvenance(model_id=MODEL,model_revision=REV,model_dtype='bfloat16', extraction_dtype='float16',hook_sites=[f'block:{layer}:output'],max_seq_length=512, total_sequences_processed=len(rows),tokenizer_id=MODEL,source_dataset='frozen_cases',random_seed=SEED)) as writer: for start in range(0,len(rows),SHARD): block=rows[start:start+SHARD];rs=receipts[start:start+SHARD] with np.load(chunk_path(start),allow_pickle=False) as shard: a=shard['action'][:,j,:].copy() writer.add(torch.from_numpy(a),sequence_ids=[r['id'] for r in rs], labels=torch.tensor([int(r['targets']['optimal_action']=='CONTINUE') for r in block]), token_positions=torch.tensor([r['action_length']-1 for r in rs]), token_ids=torch.tensor([r['last_token_id'] for r in rs])) writer.import_sequence_metadata([r['id'] for r in rs], labels=[int(r['targets']['optimal_action']=='CONTINUE') for r in block], sources=['generated:'+r['split'] for r in block], metadata_jsons=[json.dumps({'family':r['family_id'],'split':r['split'], 'prompt_sha256':r['action_prompt_sha256'],'ordered_prefix':r0['ordered_prefix']}) for r,r0 in zip(rs,block)]) ds=ActivationDataset(storage=storage,dataset_name=name) assert len(ds)==len(rows) and ds.metadata.provenance.model_revision==REV for k in (0,20223,20224,30335,30336,40447): sample=ds.get_by_sequence_id(rows[k]['id']) assert len(sample)==1 and int(sample[0].token_ids.reshape(-1)[0])==receipts[k]['last_token_id'] print('STORE VERIFIED',layer,len(ds),flush=True) json_atomic(OUT/'activation_store.json',{'layers':LAYERS,'count_per_layer':len(rows), 'sample_id_and_last_token_roundtrip':True}) def normalize(x): v=x.astype('float64');return v / np.maximum(np.linalg.norm(v,axis=-1,keepdims=True),1e-12)*math.sqrt(D) def _state_utility(row,family): """One conditional world per row, common across edit conditions and actions.""" p=Q(row['targets']['posterior_h1']); assignment=tuple(row['partial_assignment']) solve=solve_family(family) gen=random.Random(int(hashlib.sha256(('world:'+row['id']).encode()).hexdigest()[:16],16)) truth=int(gen.random()Q(1,2))==truth) costs=Q(0);state=assignment;history=[] for step in range(3): solution=solve(state) if step>0 and solution['action']=='STOP':break if not solution['branches']:break best=min(k for k,v in solution['branches'].items() if v==max(solution['branches'].values())) i=int(best[1:])-1 outcome=int(uniform[i]Q(1,2))==truth)-costs) return {'stop_realized':float(stop_real),'continue_realized':cont_real, 'stop_expected':float(Q(row['targets']['stop_value'])), 'continue_expected':float(Q(row['targets']['continue_value'])), 'continue_probe_cost':float(costs),'truth':truth,'future_outcomes':history} def patch_eval(scorer,tok,rows,acts,receipts,freeze_record,pairs,cal=False,families=None): layer=freeze_record['selected_layer'];j=LAYERS.index(layer) direction=np.asarray(freeze_record['direction'],dtype='float32') sd=freeze_record['train_projection_sd'];scale=freeze_record['scale'];unit=direction/np.linalg.norm(direction) rng=np.random.default_rng(SEED+39) random_dir=rng.normal(size=D);random_dir-=unit*(random_dir@unit);random_dir/=np.linalg.norm(random_dir) shuffled_dir=rng.permutation(unit);shuffled_dir/=np.linalg.norm(shuffled_dir) lookup={r['id']:i for i,r in enumerate(rows)} pair_entries=[(pair['stop_row_id'],pair['continue_row_id']) for pair in pairs] pair_index={r:idx for idx,entry in enumerate(pair_entries) for r in entry} if not cal: family_map={family['id']:family['public'] for family in families} with np.load(freeze_record['weights_path'],allow_pickle=False) as selected_file: posterior_fit=analyze._load_fit(selected_file,'posterior') posterior_layer=LAYERS.index(freeze_record['selected']['posterior']['layer']) if cal: # Predeclared balanced canonical calibration sample; no evaluation outputs. useful=[r for r in rows if r['split']=='calibration' and r['ordered_prefix']==r['canonical_prefix'] and r['targets']['continue_value'] is not None] cand={label:[r['id'] for r in useful if r['targets']['optimal_action']==label] for label in ('STOP','CONTINUE')} pair_entries=[(id0,id1) for id0,id1 in zip(cand['STOP'][:32],cand['CONTINUE'][:32])] donors={a:b for a,b in pair_entries}|{b:a for a,b in pair_entries} shuffle_map={} for sid in donors: want='CONTINUE' if rows[lookup[sid]]['targets']['optimal_action']=='STOP' else 'STOP' pool=sorted(k for k in donors if k!=sid and k!=donors[sid] and rows[lookup[k]]['targets']['optimal_action']==want) assert pool shuffle_map[sid]=pool[int(hashlib.sha256(sid.encode()).hexdigest()[:8],16)%len(pool)] mean=freeze_record.get('train_activation_mean',None) if mean is None:mean=np.zeros(D) outputs=[] for count,sid in enumerate(sorted(donors)): check_budget() i=lookup[sid];recipient=rows[i];sender=donors[sid];current=acts[i,j].astype('float32') donor=acts[lookup[sender],j].astype('float32');sign=1 if recipient['targets']['optimal_action']=='CONTINUE' else -1 shift=sign*scale*sd*unit ablated=current-((current-np.asarray(mean))@unit)*unit other=acts[lookup[shuffle_map[sid]],j].astype('float32') conditions={'swap':('replace',donor),'ablation':('replace',ablated), 'direction':('add',shift),'random':('add',sign*scale*sd*random_dir), 'shuffled':('add',sign*scale*sd*shuffled_dir), 'norm_matched':('add',sign*np.linalg.norm(donor-current)*random_dir), 'shuffled_pair':('replace',other),'sham':('add',np.zeros(D,dtype='float32'))} if cal: conditions={k:conditions[k] for k in ('direction','sham')} _,ids,_=tokenize(tok,[recipient],'action') if not cal: utility=_state_utility(recipient,family_map[recipient['family_id']]) def with_utility(condition,prob,edit_norm,posterior_est,vec): decision='CONTINUE' if prob>=.5 else 'STOP' suffix='continue' if decision=='CONTINUE' else 'stop' return {'id':sid,'donor_id':sender,'family_id':recipient['family_id'], 'pair_id':pair_index[sid],'condition':condition,'p_continue':prob, 'edit_norm':float(edit_norm),'baseline_p_continue':receipts[i]['p_continue'], 'source_action':recipient['targets']['optimal_action'], 'expected_utility':utility[suffix+'_expected'], 'realized_utility':utility[suffix+'_realized'], 'probe_cost':utility['continue_probe_cost'] if decision=='CONTINUE' else 0., 'terminal_accuracy':int(utility[suffix+'_realized']+( utility['continue_probe_cost'] if decision=='CONTINUE' else 0.)>0.5), 'decoded_posterior_after_edit':float(posterior_est), 'post_edit_decoded_activation':vec.astype(np.float16).tolist()} baseline=float(receipts[i]['p_continue']) base_posterior=float(analyze._predict(acts[i:i+1,posterior_layer,:],posterior_fit)[0]) outputs.append(with_utility('baseline',baseline,0,base_posterior,current)) for name,(mode,vector) in conditions.items(): edit={'layer':layer,'mode':mode,'vectors':torch.tensor(np.asarray(vector,dtype='float32')[None,:],device='cuda')} scored=scorer.run(ids,edit=edit,capture=True) measured=scored['edit_norm'][0] if name!='sham' and measured<=0:raise ValueError(('edit_not_applied',sid,name)) if name=='sham' and abs(float(scored['prob'][0])-receipts[i]['p_continue'])>3e-4: raise ValueError(('sham_not_identity',sid,scored['prob'][0],receipts[i]['p_continue'])) if cal: outputs.append({'id':sid,'condition':name,'source_action':recipient['targets']['optimal_action'], 'p_continue':float(scored['prob'][0]),'baseline_p_continue':receipts[i]['p_continue'], 'edit_norm':float(measured)}) else: estimate=float(analyze._predict(scored['acts'][0:1,posterior_layer,:],posterior_fit)[0]) result=with_utility(name,float(scored['prob'][0]),measured,estimate,scored['acts'][0,j]) result['label_mass']=float(scored['mass'][0]);outputs.append(result) if (count+1)%32==0:print('EDIT',('cal' if cal else 'eval'),count+1,len(donors),flush=True) return outputs def main(): global GENERATOR_HASH,T_SHARD OUT.mkdir(parents=True,exist_ok=True) print('VERSIONS',torch.__version__,__import__('transformers').__version__,np.__version__,flush=True) assert torch.cuda.is_available() and torch.cuda.device_count()==1 print('GPU',torch.cuda.get_device_name(0),torch.cuda.get_device_properties(0).total_memory,flush=True) print('RUN_CONFIG',json.dumps({'model':MODEL,'revision':REV,'dtype':'bf16','layers':LAYERS, 'seed':SEED,'batch':BATCH,'shard':SHARD,'deadline_guard_s':23*3600}),flush=True) random.seed(SEED);np.random.seed(SEED);torch.manual_seed(SEED) families,rows,manifest=freeze(SEED) GENERATOR_HASH=manifest['content_sha256'] assert len(rows)==40448 and len(families)==512 and len(manifest['opposite_decision_pairs'])==128 json_atomic(OUT/'dataset_manifest.json',manifest) json_atomic(OUT/'families.json',families) case_path=OUT/'frozen_cases.jsonl' if not case_path.exists(): with case_path.open('w') as f: for row in rows:f.write(json.dumps(row,sort_keys=True,separators=(',',':'))+'\n') print('DATASET',GENERATOR_HASH,sha_file(case_path),len(rows),len(families),flush=True) restore_previous_shards() tok=AutoTokenizer.from_pretrained(MODEL,revision=REV) print('TOKENIZER',type(tok).__name__,'id0/id1',tok.encode('0',add_special_tokens=False),tok.encode('1',add_special_tokens=False),flush=True) model=Qwen3_5ForConditionalGeneration.from_pretrained(MODEL,revision=REV,dtype=torch.bfloat16, device_map='cuda:0',low_cpu_mem_usage=True,attn_implementation='sdpa').eval() candidates=[(n,m) for n,m in model.named_modules() if n.endswith(('language_model.layers','model.layers')) and hasattr(m,'__len__') and len(m)==64] assert len(candidates)==1 site,modules=candidates[0];assert all(next(modules[k].parameters()).device.type=='cuda' for k in LAYERS) scorer=Scorer(model,tok,modules) json_atomic(OUT/'startup.json',{'model':MODEL,'revision':REV,'dtype':str(model.dtype),'site':site, 'num_layers':len(modules),'selected_layers':LAYERS,'gpu_weight_bytes':torch.cuda.memory_allocated(), 'tokenizer_class':type(tok).__name__,'label_ids':scorer.labels,'generator_hash':GENERATOR_HASH}) # Instrument checks on actual prompts, including batch-vs-single consistency. _,check_ids,pos=tokenize(tok,rows[:2],'action') first=scorer.run(check_ids[:1],pos[:1]);batched=scorer.run(check_ids,pos) if abs(float(first['prob'][0])-float(batched['prob'][0]))>0.02: raise ValueError(('batched_padding_parity',first['prob'][0],batched['prob'][0])) assert batched['acts'].shape==(2,6,D) storage_roundtrip(batched['acts'],{'id':rows[0]['id'],'action_length':len(check_ids[0]),'last_token_id':check_ids[0][-1]}) json_atomic(OUT/'instrument.json',{'batch_single_p_difference':abs(float(first['prob'][0])-float(batched['prob'][0])), 'first_label_mass':float(first['mass'][0]),'first_probability':float(first['prob'][0]), 'roundtrip':True,'evidence_position':pos[1],'first_prompt_length':len(check_ids[0])}) if os.environ.get('ALG_SMOKE_ONLY')=='1': subset=rows[:16] start_benchmark=time.monotonic() _,action_ids,evidence_pos=tokenize(tok,subset,'action') _,belief_ids,_=tokenize(tok,subset,'posterior') for ix in range(0,16,BATCH): scorer.run(action_ids[ix:ix+BATCH],evidence_pos[ix:ix+BATCH]);scorer.run(belief_ids[ix:ix+BATCH]) json_atomic(OUT/'actual_preflight.json',{'contexts':16,'forward_passes':4, 'input_tokens':sum(map(len,action_ids))+sum(map(len,belief_ids)), 'elapsed_seconds':time.monotonic()-start_benchmark,'peak_gpu_bytes':torch.cuda.max_memory_allocated()}) print('ACTUAL_PREFLIGHT', (OUT/'actual_preflight.json').read_text(),flush=True) return cal_end=384*79;assert cal_end==30336 T_SHARD=time.monotonic() capture_rows(scorer,tok,rows,0,cal_end,'train_cal_capture') selected_acts,selected_receipts,_,_=read_range(rows,0,cal_end) selection=analyze.select(selected_acts,rows[:cal_end],selected_receipts,OUT) # Freeze choices on calibration only. Never gate evaluation on an agent-invented quality threshold. layer=selection['G_intervention_layer']; j=LAYERS.index(layer) with np.load(selection['weights_path'],allow_pickle=False) as selected_file: unit=np.asarray(selected_file['G_direction_unit'],dtype='float32') unit/=np.linalg.norm(unit) train=selected_acts[:256*79,j,:].astype('float32') selection['train_projection_sd']=float(np.std(train@unit,ddof=1)) selection['train_activation_mean']=train.mean(axis=0).tolist() selection['selected_layer']=layer selection['direction']=unit.tolist() if selection['train_projection_sd']<=0:raise ValueError('collapsed intervention direction') cal_trials=[] for scale in (0.5,1.,2.): frozen=dict(selection,scale=scale) trial=patch_eval(scorer,tok,rows[:cal_end],selected_acts,selected_receipts,frozen,[],cal=True) directional=[(1 if r['source_action']=='CONTINUE' else -1)*(r['p_continue']-r['baseline_p_continue']) for r in trial if r['condition']=='direction'] cal_trials.append({'scale':scale,'n':len(directional),'mean_directional_p_change':float(np.mean(directional))}) choice=max(cal_trials,key=lambda t:(t['mean_directional_p_change'],-t['scale'])) selection['scale']=choice['scale'];selection['calibration_trials']=cal_trials # In file freeze do not duplicate the large train mean: keep a hash and weight file reference. numpy_path=OUT/'selected_weights.npz' with np.load(numpy_path,allow_pickle=False) as saved: payload={k:saved[k] for k in saved.files} payload['train_activation_mean']=np.asarray(selection['train_activation_mean'],dtype='float32') np.savez(numpy_path,**payload) json_atomic(OUT/'intervention_freeze.json',{k:v for k,v in selection.items() if k not in ('train_activation_mean','direction')} |{'direction_sha256':hashlib.sha256(unit.tobytes()).hexdigest(),'weights_file':'selected_weights.npz'}) print('FROZEN',layer,choice,'cal_trials',cal_trials,flush=True) check_budget() T_SHARD=time.monotonic() capture_rows(scorer,tok,rows,cal_end,len(rows),'eval_capture') all_acts,receipts,belief_acts,evidence_acts=read_range(rows,0,len(rows)) json_atomic(OUT/'activation_manifest.json',{'model':MODEL,'revision':REV,'layers':LAYERS,'site':site, 'dtype':'float16','row_count':len(rows),'shape':list(all_acts.shape), 'prompt_policies':['decision final token','posterior final token','last evidence token or root final'], 'tokenizer':type(tok).__name__,'generator_hash':GENERATOR_HASH, 'shards':{chunk_path(i).name:sha_file(chunk_path(i)) for i in range(0,len(rows),SHARD)}, 'token_positions_and_full_token_ids':'in each shard under evidence_position, action/belief_ids_flat and *_ids_offsets'}) canonical_store(rows,receipts) interventions=patch_eval(scorer,tok,rows,all_acts,receipts,selection,manifest['opposite_decision_pairs'],families=families) # Store the large post-edit vectors apart from lightweight per-row receipts. modified=np.asarray([r.pop('post_edit_decoded_activation') for r in interventions],dtype=np.float16) np.savez(OUT/'intervention_activations.npz',vectors=modified,ids=np.asarray([r['id'] for r in interventions]), conditions=np.asarray([r['condition'] for r in interventions])) json_atomic(OUT/'intervention_rows.json',interventions) results=analyze.evaluate(all_acts,rows,receipts,selection,interventions,OUT) json_atomic(OUT/'runtime_end.json',{'completed':True,'process_seconds':time.monotonic()-START, 'peak_gpu_allocated_bytes':torch.cuda.max_memory_allocated(),'selected_activation_bytes':all_acts.nbytes, 'capture_rows':len(rows),'total_input_token_positions':sum(r['action_length']+r['belief_length'] for r in receipts), 'intervention_forward_calls':len(interventions),'rudimentary_RU_meter':None}) print('COMPLETE',time.monotonic()-START,'n_eval',results['probe']['evaluation_rows'],flush=True) if __name__=='__main__': try: main() except BaseException as exc: OUT.mkdir(parents=True,exist_ok=True) json_atomic(OUT/'failure.json',{'type':type(exc).__name__,'message':str(exc), 'elapsed_process_seconds':time.monotonic()-START}) raise