Download research_source/worktree/src/diagnose_batch.py from AlephFunk/alg-hodge-27b-01: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/datasets/AlephFunk/alg-hodge-27b-01/resolve/main/research_source/worktree/src/diagnose_batch.py
- Command line
-
hf download hf://datasets/AlephFunk/alg-hodge-27b-01/research_source/worktree/src/diagnose_batch.py
-
curl -L -o diagnose_batch.py https://huggingface.co/datasets/AlephFunk/alg-hodge-27b-01/resolve/main/research_source/worktree/src/diagnose_batch.py
3.92 kB
| """Diagnose single-versus-batch numerical equivalence before accepting capture shards.""" | |
| from __future__ import annotations | |
| import json,os,time | |
| from pathlib import Path | |
| import numpy as np,torch | |
| from transformers import AutoTokenizer,Qwen3_5ForConditionalGeneration | |
| from run import MODEL,REV,LAYERS,D,Scorer,tokenize,json_atomic | |
| from prepare import freeze | |
| OUT=Path(os.environ['SILICO_EXPERIMENT_ARTIFACTS_DIR'])/'alg_hodge_27b_01' | |
| t0=time.monotonic() | |
| families,rows,manifest=freeze() | |
| selected=rows[:24]+[next(r for r in rows if r['id']=='F0256:o12:b01')] | |
| tok=AutoTokenizer.from_pretrained(MODEL,revision=REV) | |
| _,ids,pos=tokenize(tok,selected,'action') | |
| print('DIAGNOSTIC',len(ids),[len(x) for x in ids],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() | |
| modules=[(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(modules)==1 | |
| scorer=Scorer(model,tok,modules[0][1]) | |
| singles=[scorer.run([ids[i]],[pos[i]]) for i in range(len(ids))] | |
| batches={} | |
| for start in range(0,len(ids),8): | |
| result=scorer.run(ids[start:start+8],pos[start:start+8]) | |
| for j,i in enumerate(range(start,min(start+8,len(ids)))): | |
| batches[i]={key:result[key][j] for key in ('prob','mass','acts','evidence')} | |
| records=[] | |
| for i,(r,s) in enumerate(zip(selected,singles)): | |
| single=s['acts'][0].astype('float32');batch=batches[i]['acts'].astype('float32') | |
| ev_single=s['evidence'][0].astype('float32');ev_batch=batches[i]['evidence'].astype('float32') | |
| records.append({'id':r['id'],'n_tokens':len(ids[i]),'single_p_continue':float(s['prob'][0]), | |
| 'batched_p_continue':float(batches[i]['prob']),'absolute_probability_change':abs(float(s['prob'][0])-float(batches[i]['prob'])), | |
| 'single_label_mass':float(s['mass'][0]),'batch_label_mass':float(batches[i]['mass']), | |
| 'activation_relative_l2_by_layer':(np.linalg.norm(single-batch,axis=-1)/np.maximum(np.linalg.norm(single,axis=-1),1e-9)).tolist(), | |
| 'evidence_relative_l2_by_layer':(np.linalg.norm(ev_single-ev_batch,axis=-1)/np.maximum(np.linalg.norm(ev_single,axis=-1),1e-9)).tolist()}) | |
| # Repeat at least one full equal-length subgroup, to distinguish left-padding | |
| # effects from batch-shape effects if the generator happens to provide four. | |
| by_len={} | |
| for i,seq in enumerate(ids):by_len.setdefault(len(seq),[]).append(i) | |
| equal=max(by_len.values(),key=len) | |
| if len(equal)>=2: | |
| chosen=equal[:min(8,len(equal))];same=scorer.run([ids[k] for k in chosen],[pos[k] for k in chosen]); | |
| same_length=[{'id':selected[k]['id'],'n_tokens':len(ids[k]), | |
| 'single_p_continue':float(singles[k]['prob'][0]),'equal_length_batch_p_continue':float(same['prob'][j]), | |
| 'relative_l2_by_layer':(np.linalg.norm(singles[k]['acts'][0].astype('float32')-same['acts'][j].astype('float32'),axis=-1)/np.maximum(np.linalg.norm(singles[k]['acts'][0].astype('float32'),axis=-1),1e-9)).tolist()} | |
| for j,k in enumerate(chosen)] | |
| else:same_length=[] | |
| receipt={'model':MODEL,'revision':REV,'site':modules[0][0],'batch_size':8, | |
| 'n_cases':len(records),'max_abs_probability_change':max(r['absolute_probability_change'] for r in records), | |
| 'max_activation_relative_l2_by_layer':np.max([r['activation_relative_l2_by_layer'] for r in records],axis=0).tolist(), | |
| 'max_evidence_relative_l2_by_layer':np.max([r['evidence_relative_l2_by_layer'] for r in records],axis=0).tolist(), | |
| 'records':records,'equal_length_check':same_length,'duration_seconds':time.monotonic()-t0, | |
| 'peak_gpu_bytes':torch.cuda.max_memory_allocated()} | |
| json_atomic(OUT/'batch_parity_diagnostic.json',receipt) | |
| print('RESULT',json.dumps({'max_p_delta':receipt['max_abs_probability_change'], | |
| 'max_activation_relative_by_layer':receipt['max_activation_relative_l2_by_layer'], | |
| 'equal_length_n':len(same_length),'seconds':receipt['duration_seconds']}),flush=True) | |