junidude14 commited on
Commit
294e683
·
verified ·
1 Parent(s): 304d93e

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/prepare_legacy.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support/validation-only expression view; preserve original cell-row RNG semantics."""
2
+ from pathlib import Path
3
+ import sys,json,shutil
4
+ import numpy as np
5
+ import pandas as pd
6
+ P=Path(__file__).resolve().parents[1];M=P.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';S=M/'plans/paper_figures_strictpairs_20261012'
7
+ sys.path.insert(0,str(S/'tools'));from support_input_isolation import isolated_arrays,sha
8
+ j=next(j for j in json.loads((P/'MATRIX.json').read_text())['paired_jobs'] if j['id']==sys.argv[1]);out=Path(j['output'])/'input'/j['cohort'];out.mkdir(parents=True,exist_ok=True)
9
+ source=F/f"data/{j['cohort']}";folds=pd.read_csv(source/'folds.csv');allowed=set(j['train_samples']+j['validation_samples']);rows=folds.index[folds.sample_id.isin(allowed)].to_numpy()
10
+ assert set(folds.loc[rows,'sample_id'])==allowed and not allowed&set(j['test_samples'])
11
+ arrays,audit=isolated_arrays(source/'cells_panel6k.npz',rows)
12
+ np.savez_compressed(out/'cells_panel6k.npz',**arrays);shutil.copy2(source/'folds.csv',out/'folds.csv')
13
+ if j['family']=='legacy5':(out/'train_donors.txt').write_text('\n'.join(j['train_donors'])+'\n')
14
+ (out/'ISOLATION.json').write_text(json.dumps({'job':j['id'],'allowed_samples':sorted(allowed),'source_sha256':sha(source/'cells_panel6k.npz'),'output_sha256':sha(out/'cells_panel6k.npz'),'audit':audit},indent=2)+'\n')
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/pretrain.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact f01-panel profile + full pretraining. Call only through ml-run."""
2
+ from pathlib import Path
3
+ from datetime import datetime,timezone
4
+ import os,sys,json,subprocess,hashlib
5
+ P=Path(__file__).resolve().parents[1];M=P.parents[1]
6
+ def sha(p):
7
+ with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
8
+ def state(phase,**kw):
9
+ j={'phase':phase,'at':datetime.now(timezone.utc).isoformat(),**kw};p=P/'PRETRAIN_STATUS.tmp';p.write_text(json.dumps(j,indent=2)+'\n');p.replace(P/'PRETRAIN_STATUS.json');print(json.dumps(j),flush=True)
10
+ def verify_inputs():
11
+ c=json.loads((P/'CONTRACT.json').read_text())
12
+ for p,h in {**c['sources'],**c['configs']}.items():assert sha(p)==h,p
13
+ assert os.path.ismount(P/'payload'),'NAS mount missing; refuse fallback onto local disk'
14
+ storage=json.loads((P/'STORAGE_VERIFIED.json').read_text());assert sha(P/'payload/STORAGE_PROBE.bin')==storage['probe_sha256']
15
+ v=os.statvfs(P/'payload');assert v.f_bavail*v.f_frsize>120*2**30,'NAS insufficient space'
16
+ return c
17
+
18
+ def main():
19
+ groups=Path('/proc/self/cgroup').read_text();assert 'ml.slice' in groups
20
+ unit=[x for x in groups.strip().split('/') if x.endswith('.service')][-1]
21
+ subprocess.run(['systemctl','--user','set-property','--runtime',unit,'MemoryHigh=64G','MemoryMax=72G','MemorySwapMax=0'],check=True)
22
+ assert subprocess.check_output(['systemctl','--user','show',unit,'-p','OOMPolicy','--value'],text=True).strip()=='kill'
23
+ subprocess.run(['systemctl','--user','is-active','--quiet','ml-memory-guard.service'],check=True)
24
+ subprocess.run(['/home/sj_server_1/.local/libexec/ml-memory-guard','--check'],check=True)
25
+ assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader'],text=True).strip()
26
+ assert int(Path('/proc/meminfo').read_text().split('MemAvailable:')[1].split()[0])>64*1048576
27
+ c=verify_inputs();py='/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python'
28
+ for stage in ['profile','train']:
29
+ cfg=P/f'configs/{stage}.json';settings=json.loads(cfg.read_text());out=Path(settings['paths']['output_dir'])
30
+ if out.exists():raise RuntimeError('Existing run requires inspection; no implicit resume: '+str(out))
31
+ state('profiling' if stage=='profile' else 'pretraining',output=str(out))
32
+ with (P/f'{stage}.log').open('x') as log:
33
+ subprocess.run([py,'-u',str(M/'scripts/train_allcell_sdd.py'),'--config',str(cfg),'--expected-config-sha256',sha(cfg)],stdout=log,stderr=subprocess.STDOUT,check=True)
34
+ if stage=='profile':
35
+ prof=json.loads((out/'ALLCELL_PROFILE.json').read_text());assert prof['status']=='COMPLETED'
36
+ state('profile_passed',profile=str(out/'ALLCELL_PROFILE.json'))
37
+ verify_inputs()
38
+ new=Path(c['pretrain_output']);a=json.loads((new/'data_audit.json').read_text());b=json.loads((M/'runs/f01_6k_1x_seed20260627/data_audit.json').read_text());assert a['gene_ids']==b['gene_ids'];assert a['gene_positions']==b['gene_positions']
39
+ contract=json.loads((new/'ALLCELL_DATA_CONTRACT.json').read_text());base=json.loads((M/'runs/f01_6k_1x_seed20260627/ALLCELL_DATA_CONTRACT.json').read_text())
40
+ assert contract['status']=='COMPLETED' and contract['total_target_cells']==base['total_target_cells']
41
+ for k in ['source_corpus_fingerprint','source_recipe_sha256','source_pool_sha256','pool_order_sha256','recipe_schedule_sha256','emitted_target_order_sha256']:
42
+ assert contract['pairing'][k]==base['pairing'][k],k
43
+ cp=new/'checkpoint_epoch_016.pt';receipt={'checkpoint':str(cp),'checkpoint_sha256':sha(cp),'gene_ids_exact':True,'gene_positions_exact':True,'stream_order_exact':True,'target_occurrences':contract['total_target_cells'],'selected_epoch':16,'selection':'fixed E16 EMA, no downstream outcome selection'}
44
+ (P/'PRETRAIN_VERIFIED.json').write_text(json.dumps(receipt,indent=2)+'\n');state('completed',**receipt)
45
+ if __name__=='__main__':
46
+ try:main()
47
+ except BaseException as e:state('stopped_needs_inspection',error=str(e));raise
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/run_campaign.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable controller. GPU pretraining queues under ml-run; downstream follows verification."""
2
+ from pathlib import Path
3
+ from datetime import datetime,timezone
4
+ import os,sys,json,subprocess
5
+ P=Path(__file__).resolve().parents[1]
6
+ def state(phase,**kw):
7
+ j={'phase':phase,'host':'server_1','at':datetime.now(timezone.utc).isoformat(),**kw};t=P/'STATUS.tmp';t.write_text(json.dumps(j,indent=2)+'\n');t.replace(P/'STATUS.json');print(json.dumps(j),flush=True)
8
+ def main():
9
+ state('queued_pretraining',reason='server_2 busy; server_1 selected per user fallback; shared GPU lock must be acquired')
10
+ env=dict(os.environ,PBISC_ALLCELL_MANAGED='1',PBISC_SDD_FAST_ROWS='4',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',PYTHONDONTWRITEBYTECODE='1',PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True',CUDA_VISIBLE_DEVICES='0')
11
+ subprocess.run(['/home/sj_server_1/.local/bin/ml-run','/usr/bin/env',*[f'{k}={env[k]}' for k in ['PBISC_ALLCELL_MANAGED','PBISC_SDD_FAST_ROWS','OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS','PYTHONDONTWRITEBYTECODE','PYTORCH_CUDA_ALLOC_CONF','CUDA_VISIBLE_DEVICES']],sys.executable,'-u',str(P/'tools/pretrain.py')],env=env,check=True)
12
+ assert (P/'PRETRAIN_VERIFIED.json').exists()
13
+ state('downstream')
14
+ env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='4',MKL_NUM_THREADS='4')
15
+ subprocess.run(['/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python','-u',str(P/'tools/downstream.py')],env=env,check=True)
16
+ status=json.loads((P/'DOWNSTREAM_STATUS.json').read_text())
17
+ state(status['phase'],downstream=str(P/'DOWNSTREAM_STATUS.json'))
18
+ if __name__=='__main__':
19
+ try:main()
20
+ except BaseException as e:state('stopped_needs_inspection',error=str(e));raise
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/score_paired.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """New-parent validation followed by unchanged benchmark metrics and donor statistics."""
2
+ from pathlib import Path
3
+ import sys,os,json,argparse
4
+ from types import SimpleNamespace
5
+ import numpy as np
6
+ assert os.environ.get('CUDA_VISIBLE_DEVICES')==''
7
+ P=Path(__file__).resolve().parents[1];M=P.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';S=M/'plans/paper_figures_strictpairs_20261012'
8
+ sys.path[:0]=[str(S/'tools'),str(F/'tools')]
9
+ import score_ft as FT
10
+ import score_strict as ST
11
+ from runtime import sha256
12
+ j=next(j for j in json.loads((P/'MATRIX.json').read_text())['paired_jobs'] if j['id']==sys.argv[1]);out=Path(j['output'])/'evaluation';out.mkdir(parents=True,exist_ok=True)
13
+ gen=Path(j['output'])/'generated.npz';rec=json.loads(gen.with_suffix('.log').read_text());assert rec['output_sha256']==sha256(gen)
14
+ parent=json.loads((P/'PRETRAIN_VERIFIED.json').read_text());train=Path(j['output'])/'run/RUN.json'
15
+ if j.get('adapter_alias'):
16
+ alias=next(x for x in json.loads((P/'MATRIX.json').read_text())['paired_jobs'] if x['id']==j['adapter_alias']);train=Path(alias['output'])/'run/RUN.json'
17
+ r=json.loads(train.read_text());assert r['source_checkpoint_sha256']==parent['checkpoint_sha256'];assert rec['checkpoint_sha256']==r['checkpoint_sha256'];assert set(r['train_rows'])==set(j['train_samples']);assert set(r['inner_val_rows'])==set(j['validation_samples']);assert set(r['test_rows_never_loaded_for_training'])==set(j['test_samples'])
18
+ with np.load(gen) as z:
19
+ assert z['gene_ids'].astype(str).tolist()==json.loads((M/'runs/f01_6k_1x_seed20260627/data_audit.json').read_text())['gene_ids'];assert set(z['sample_ids'].astype(str))==set(j['test_samples'])
20
+ ids=out/'test_samples.txt';ids.write_text('\n'.join(j['test_samples'])+'\n')
21
+ argv=['--dataset',j['cohort'],'--out',str(out/'score'),'--arm',f'trunk4x={gen}','--condition',f"trunk4x={j['test_condition']}",'--donors',str(ids),'--threads','4']
22
+ groups={'ye2026_sepsis':('adult_sepsis,ped_sepsis','adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl'),'imperial_eskd':('covid_positive','covid_negative'),'giroux2022':('severe','mild'),'ji2025_chili':('TOL,FU1','BC,AC')}
23
+ if j['cohort'] in groups:argv+=['--case-groups',groups[j['cohort']][0],'--control-groups',groups[j['cohort']][1]]
24
+ else:argv+=['--no-contrast','--no-deg']
25
+ if j['family']=='strict' and j['cohort']=='giroux2022':argv+=['--exclude-genes',str(F/'data/sex_linked_genes/sex_linked_genes_exclude.csv')]
26
+ newarms={'trunk4x':gen}
27
+ if j['family']=='strict':
28
+ for name,path,cond in [('raw',P/f"payload/global/{j['cohort']}/raw.npz",S/f"data/external_refcal/{j['cohort']}/conditions_raw.npz"),('refcal',P/f"payload/global/{j['cohort']}/refcal.npz",S/f"data/external_refcal/{j['cohort']}/conditions_refcal.npz"),('pairedcal',Path(j['output'])/'pairedcal.npz',Path(j['cal_condition']))]:
29
+ rr=json.loads(path.with_suffix('.log').read_text());assert rr['output_sha256']==sha256(path) and rr['checkpoint_sha256']==parent['checkpoint_sha256']
30
+ newarms[name]=path;argv+=['--arm',f'{name}={path}','--condition',f'{name}={cond}']
31
+ FT.main(argv)
32
+ if j['family']=='strict':
33
+ support=ST.read_support(Path(j['support_path']));binding={'schema':'pbisc.paper.strict-score-binding.v1','support_sha256':support['sha256'],'cohort':j['cohort'],'unit':support['unit'],'test_sample_ids':support['test_sample_ids'],'test_donor_ids':support['test_donor_ids'],'arm_bindings':{'trunk4x':{'npz':str(gen),'npz_sha256':rec['output_sha256'],'checkpoint_sha256':r['checkpoint_sha256'],'new_parent_sha256':parent['checkpoint_sha256']}}}
34
+ binding['arm_bindings']={name:{'npz':str(path),'npz_sha256':sha256(path),'new_parent_sha256':parent['checkpoint_sha256']} for name,path in newarms.items()}
35
+ (out/'scoring_support.json').write_text(json.dumps(binding,indent=2)+'\n')
36
+ arms=[f'{name}={path}' for name,path in newarms.items()];args=SimpleNamespace(draw_long=[],baseline='raw',pseudobulk_table=None,threads=4)
37
+ for kind in ['extras','contrast']:ST._call_extra(kind,support,out,arms,4)
38
+ ST._call_stats(support,out,arms,args)
39
+ if j['cohort']!='immicro':
40
+ import rare_cache_builder as RC
41
+ RC.build(Path(j['support_path']),out/'score',newarms,out/'rare_cache',cell_budget=1500,depth_target=1000.)
42
+ (out/'DONE.json').write_text(json.dumps({'job':j['id'],'new_base_sha256':parent['checkpoint_sha256'],'generation_sha256':rec['output_sha256'],'gene_context_exact':True,'baseline_results_reused_by_reference':j.get('baseline_score'),'rare_identity':'diagnostic only; original-paper fine-label gate remains'},indent=2)+'\n')