junidude14 commited on
Commit
5e33d7b
·
verified ·
1 Parent(s): c0b605a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T223459Z-f01-two-host-dispatch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/downstream.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute the sealed same-gene-context matrix. No unchanged baseline training."""
2
+ from pathlib import Path
3
+ from datetime import datetime,timezone
4
+ import json,os,sys,shutil,subprocess
5
+ P=Path(__file__).resolve().parents[1];M=P.parents[1];S=M/'plans/paper_figures_strictpairs_20261012';F=M/'plans/paired_finetune_intradataset_20260927'
6
+ sys.path.insert(0,str(S/'tools'))
7
+ from runtime import Runtime,sha256,atomic_json
8
+ from dual_runtime import RemoteRuntime,LOCAL,CPU_LOCK,STATUS_LOCK,parallel_lanes,singleton
9
+ PY='/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python';CPU='/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python'
10
+ def status(phase,**kw):
11
+ with STATUS_LOCK:
12
+ host=getattr(LOCAL,'host','server_1');record={'phase':phase,'host':host,'at':datetime.now(timezone.utc).isoformat(),**kw}
13
+ atomic_json(P/f'DOWNSTREAM_{host}.json',record);atomic_json(P/'DOWNSTREAM_STATUS.json',record)
14
+ def safe_storage():
15
+ contract=json.loads((P/'CONTRACT.json').read_text())
16
+ for source,digest in {**contract['sources'],**contract['configs']}.items():assert sha256(Path(source))==digest,source
17
+ for source,digest in json.loads((P/'WORKFLOW_SEAL.json').read_text())['files'].items():assert sha256(Path(source))==digest,source
18
+ assert os.path.ismount(P/'payload'),'NAS unmounted; stop before falling back to local storage'
19
+ v=os.statvfs(P/'payload');assert v.f_bavail*v.f_frsize>120*2**30,'NAS free space below reserve'
20
+ def main():
21
+ matrix=json.loads((P/'MATRIX.json').read_text());verified=json.loads((P/'PRETRAIN_VERIFIED.json').read_text());safe_storage()
22
+ base=Path(verified['checkpoint']);assert sha256(base)==verified['checkpoint_sha256']
23
+ cache=P/'base_cache';cache.mkdir(exist_ok=True);local=cache/'checkpoint_epoch_016.pt'
24
+ if not local.exists():shutil.copyfile(base,local)
25
+ assert sha256(local)==verified['checkpoint_sha256'];base=local
26
+ rt=Runtime(P/'payload/runtime');remote=RemoteRuntime(P/'payload/runtime');parent_sha=verified['checkpoint_sha256']
27
+ ownership=json.loads((P/'TWO_HOST_PLAN.json').read_text())['owners']
28
+ def execute(tag,args,resource='cpu',inputs=(),outputs=(),mem=32):
29
+ safe_storage()
30
+ runner=remote if resource=='gpu' and getattr(LOCAL,'host','server_1')=='server_2' else rt
31
+ if resource=='cpu':
32
+ with CPU_LOCK:runner.execute(tag,args,resource=resource,memory_gib=mem,threads=4,inputs=list(inputs),outputs=list(outputs))
33
+ else:runner.execute(tag,args,resource=resource,memory_gib=mem,threads=4,inputs=list(inputs),outputs=list(outputs))
34
+ def sample(tag,cp,condition,out,seed):
35
+ out.parent.mkdir(parents=True,exist_ok=True)
36
+ execute(tag,[PY,'-u',str(S/'tools/sample_one.py'),'--checkpoint',str(cp),'--checkpoint-sha',sha256(cp),'--condition',str(condition),'--output',str(out),'--seed',str(seed)],'gpu',[cp,condition,S/'tools/sample_one.py'],[out,out.with_suffix('.log')],48)
37
+ execute('hf-pretrain-backup',['/home/sj_server_1/miniforge3/bin/python',str(P/'tools/publish_core.py'),'--pretrain'],inputs=[P/'PRETRAIN_VERIFIED.json',P/'tools/publish_core.py'],outputs=[P/'HF_PRETRAIN_VERIFIED.json'],mem=4)
38
+ # Final E16 fixed before downstream outcomes. The SLE builder uses a namespace-local compatibility tag.
39
+ def sle(row):
40
+ folder=P/f"payload/sle/seed{row['seed_index']}";g=folder/'generated_f016k_e16.npz';status('sle',seed=row['seed'])
41
+ sample('sle-'+str(row['seed_index']),base,M/'artifacts/gse135779_scsemi_split_target42_20260913/donor_conditions.npz',g,row['seed'])
42
+ execute('sle-score-'+str(row['seed_index']),[CPU,str(P/'tools/score_sle.py'),str(row['seed_index'])],inputs=[g,P/'tools/score_sle.py'],outputs=[folder/'DONE.json'])
43
+ parallel_lanes(matrix['sle'],sle,lambda row:['server_1','server_2'][row['seed_index']%2])
44
+ # Unadapted/reference-calibrated outputs depend on the new pretrained checkpoint, so cannot reuse x1 cells.
45
+ def global_sample(item):
46
+ cohort,arm=item
47
+ c=S/f'data/external_refcal/{cohort}/conditions_{arm}.npz';g=P/f'payload/global/{cohort}/{arm}.npz'
48
+ status('global_generation',cohort=cohort,arm=arm);sample('global-'+cohort+'-'+arm,base,c,g,20260928)
49
+ global_items=[(c,a) for c in matrix['global_cohorts'] for a in ['raw','refcal']]
50
+ parallel_lanes(global_items,global_sample,lambda item:['server_1','server_2'][global_items.index(item)%2])
51
+ jobs=matrix['paired_jobs'];byid={j['id']:j for j in jobs}
52
+ # Canonical strict40 first, then historical full/rank CV, then additional legacy-donor supports.
53
+ def paired(item):
54
+ index,j=item
55
+ tag=j['id'].replace('/','-');out=Path(j['output']);out.mkdir(parents=True,exist_ok=True);status('paired',job=j['id'],index=index,total=len(jobs))
56
+ if j.get('adapter_alias'):
57
+ alias=byid[j['adapter_alias']];run=Path(alias['output'])/'run'
58
+ r=json.loads((run/'RUN.json').read_text());assert set(r['train_rows'])==set(j['train_samples']) and set(r['test_rows_never_loaded_for_training'])==set(j['test_samples'])
59
+ atomic_json(out/'ADAPTER_ALIAS.json',{'source_run':str(run),'checkpoint_sha256':r['checkpoint_sha256'],'reason':'identical support/test, seed, fixed3000 schedule and exact same f01x4 parent; do not train twice'})
60
+ else:
61
+ run=out/'run';ds=F/f"data/{j['cohort']}"
62
+ if j['family']!='strict':
63
+ execute(tag+'-isolate',[CPU,str(P/'tools/prepare_legacy.py'),j['id']],inputs=[P/'MATRIX.json',ds/'cells_panel6k.npz',ds/'folds.csv',P/'tools/prepare_legacy.py'],outputs=[out/'input'/j['cohort']/'ISOLATION.json'])
64
+ ds=out/'input'/j['cohort']
65
+ cmd=[PY,'-u',str(F/'tools/ft_sdd.py'),'--checkpoint',str(base),'--checkpoint-sha',parent_sha,'--dataset-dir',str(ds),'--condition-npz',j['condition'],'--fold',str(j.get('fold',0)),'--mode',j['mode'],'--lora-rank',str(j['rank']),'--lora-alpha',str(j['alpha']),'--lr',str(j['lr']),'--warmup',str(j['warmup']),'--batch-size',str(j['batch_size']),'--ema-decay',str(j['ema_decay']),'--seed',str(j['seed']),'--max-cuda-gib','24','--min-system-gib','32','--out-dir',str(run)]
66
+ if j['fixed_steps']:cmd+=['--fixed-steps',str(j['fixed_steps'])]
67
+ if j['family']=='strict':cmd+=['--support-manifest',j['support_path']]
68
+ elif j['family']=='legacy5':cmd+=['--train-donors-file',str(ds/'train_donors.txt')]
69
+ else:cmd+=['--max-steps',str(j['max_steps']),'--eval-every',str(j['eval_every']),'--patience',str(j['patience'])]
70
+ execute(tag+'-train',cmd,'gpu',[base,P/'MATRIX.json',Path(j['condition']),ds/'cells_panel6k.npz',F/'tools/ft_sdd.py'],[run/'RUN.json',run/'checkpoint_ft.pt'],64)
71
+ r=json.loads((run/'RUN.json').read_text());assert r['source_checkpoint_sha256']==parent_sha;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'])
72
+ if j.get('generation_alias'):
73
+ alias=byid[j['generation_alias']]
74
+ for ext in ['.npz','.log']:
75
+ dst=out/('generated'+ext)
76
+ if not dst.exists():dst.symlink_to(Path(alias['output'])/('generated'+ext))
77
+ atomic_json(out/'GENERATION_ALIAS.json',{'source':alias['output'],'proof':str(P/'GENERATION_REUSE_PROOF.json')})
78
+ else:sample(tag+'-generate',run/'checkpoint_ft.pt',Path(j['test_condition']),out/'generated.npz',j['sampling_seed'])
79
+ if j['family']=='strict':sample(tag+'-pairedcal',base,Path(j['cal_condition']),out/'pairedcal.npz',20260928)
80
+ if j.get('generation_alias'):
81
+ dest=out/'evaluation'
82
+ if not dest.exists():dest.symlink_to(Path(byid[j['generation_alias']]['output'])/'evaluation',target_is_directory=True)
83
+ atomic_json(out/'EVALUATION_ALIAS.json',{'source':str(dest.resolve()),'reason':'Same generated cells, test donors and scoring contract; reuse exact strict Sepsis metrics.'})
84
+ else:execute(tag+'-score',[CPU,str(P/'tools/score_paired.py'),j['id']],inputs=[out/'generated.npz',P/'MATRIX.json',P/'tools/score_paired.py'],outputs=[out/'evaluation/DONE.json'])
85
+ parallel_lanes(list(enumerate(jobs)),paired,lambda item:ownership[item[1]['id']])
86
+ # CV metrics must be scored on the same pooled held-out donors, not averaged fold P/C.
87
+ execute('pool-cv-and-score',[CPU,str(P/'tools/pool_cv.py')],inputs=[P/'MATRIX.json',P/'tools/pool_cv.py'],outputs=[P/'payload/pooled/DONE.json'])
88
+ # Published bulk-only condition files are reused; matching legacy-donor adaptation is explicit.
89
+ bulk_items=[]
90
+ for cohort in matrix['bulkonly_cohorts']:
91
+ B=M/'plans/bulkonly_lora5_20261006/data'/cohort
92
+ conditions=sorted(B.glob('bulkonly_raw_part*.npz')) or [B/'bulkonly_raw.npz']
93
+ bulk_items.extend((cohort,draw,part,condition) for draw in range(5) for part,condition in enumerate(conditions))
94
+ def bulk(item):
95
+ cohort,draw,part,condition=item
96
+ j=byid[f'legacy5/{cohort}/draw{draw}'];source=byid[j['adapter_alias']] if j.get('adapter_alias') else j;cp=Path(source['output'])/'run/checkpoint_ft.pt'
97
+ dest=P/f'payload/bulkonly/{cohort}/draw{draw}/part{part}/generated.npz';status('bulkonly',cohort=cohort,draw=draw,part=part)
98
+ sample(f'bulk-{cohort}-{draw}-{part}',cp,condition,dest,20260927)
99
+ execute(f'bulk-compact-{cohort}-{draw}-{part}',[CPU,str(P/'tools/bulk_compact.py'),cohort,str(draw),str(part)],inputs=[dest,P/'tools/bulk_compact.py'],outputs=[dest.parent/'COMPACT.json'])
100
+ parallel_lanes(bulk_items,bulk,lambda item:ownership[f'legacy5/{item[0]}/draw{item[1]}'])
101
+ execute('assemble-comparisons',[CPU,str(P/'tools/finalize.py')],inputs=[P/'MATRIX.json',P/'tools/finalize.py'],outputs=[P/'RESULTS_STATUS.json'])
102
+ result=json.loads((P/'RESULTS_STATUS.json').read_text());status(result['phase'],result=str(P/'RESULTS_STATUS.json'))
103
+ execute('hf-core-backup',['/home/sj_server_1/miniforge3/bin/python',str(P/'tools/publish_core.py')],inputs=[P/'RESULTS_STATUS.json',P/'tools/publish_core.py'],outputs=[P/'HF_CORE_VERIFIED.json'],mem=4)
104
+ try:
105
+ execute('archive-completed',["/home/sj_server_1/miniforge3/bin/python",str(P/'tools/archive_completed.py')],inputs=[P/'RESULTS_STATUS.json',P/'tools/archive_completed.py'],outputs=[P/'FINAL_ARCHIVE.json'],mem=4)
106
+ except Exception as e:
107
+ status('data_complete_archive_pending',result=str(P/'RESULTS_STATUS.json'),error=str(e))
108
+ if __name__=='__main__':
109
+ try:
110
+ with singleton():main()
111
+ except BaseException as e:status('stopped_needs_inspection',error=str(e));raise
paper-releases/pbisc-diffusion/updates/20261013T223459Z-f01-two-host-dispatch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/dual_runtime.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two fixed GPU lanes; canonical receipts stay on server_1, outputs on shared NAS."""
2
+ from pathlib import Path
3
+ import fcntl,json,os,shlex,subprocess,threading
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from contextlib import contextmanager
6
+ from runtime import Runtime,atomic_json,sha256
7
+ P=Path(__file__).resolve().parents[1]
8
+ REMOTE_PY='/home/sj_server_2/miniforge3/envs/b2sc-infer/bin/python'
9
+ LOCAL=threading.local()
10
+ CPU_LOCK=threading.Lock()
11
+ STATUS_LOCK=threading.Lock()
12
+
13
+ def ssh(argv,**kwargs):
14
+ return subprocess.run(['ssh','-o','BatchMode=yes','spark-0110',shlex.join(argv)],check=True,**kwargs)
15
+
16
+ def parallel_lanes(items,fn,owners):
17
+ """Each item has exactly one immutable owner; failures never reassign or retry."""
18
+ stop=threading.Event()
19
+ def lane(host):
20
+ LOCAL.host=host
21
+ for item in items:
22
+ if stop.is_set():return
23
+ if owners(item)!=host:continue
24
+ try:fn(item)
25
+ except BaseException:
26
+ stop.set();raise
27
+ with ThreadPoolExecutor(max_workers=2) as pool:
28
+ futures=[pool.submit(lane,h) for h in ['server_1','server_2']]
29
+ for future in futures:future.result()
30
+ LOCAL.host='server_1'
31
+
32
+ @contextmanager
33
+ def singleton():
34
+ with (P/'ops/downstream.lock').open('a') as f:
35
+ fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB)
36
+ yield
37
+
38
+ class RemoteRuntime(Runtime):
39
+ def preflight(self,resource,memory_gib):
40
+ if resource!='gpu':return super().preflight(resource,memory_gib)
41
+ result=subprocess.run(['ssh','-o','BatchMode=yes','spark-0110',shlex.join([REMOTE_PY,str(P/'tools/remote_gpu.py'),'--check'])],capture_output=True,text=True)
42
+ if result.returncode==75:raise BlockingIOError(result.stdout+result.stderr)
43
+ if result.returncode:raise RuntimeError(result.stdout+result.stderr)
44
+ def wrapped_command(self,name,argv,resource,memory_gib,threads):
45
+ assert resource=='gpu'
46
+ request=P/f'payload/dispatch/{name}.json';request.parent.mkdir(parents=True,exist_ok=True)
47
+ atomic_json(request,{'argv':argv,'threads':threads,'name':name})
48
+ return ['ssh','-o','BatchMode=yes','spark-0110',shlex.join([REMOTE_PY,str(P/'tools/remote_gpu.py'),str(request)])]
49
+ def execution_metadata(self,argv=None,command=None):
50
+ d=super().execution_metadata(argv,command);d.update(host='spark-0110',coordinator='server_1',remote_python=REMOTE_PY);return d
51
+ def execute(self,name,argv,**kwargs):
52
+ bindings=json.loads((P/'REMOTE_CODE_VERIFIED.json').read_text())['files']
53
+ verify='import json,pathlib,hashlib,sys; b=json.load(sys.stdin); assert all(hashlib.file_digest(pathlib.Path(p).open("rb"),"sha256").hexdigest()==h for p,h in b.items()), "remote code changed"'
54
+ ssh(['python3','-c',verify],input=json.dumps(bindings),text=True)
55
+ # Inputs in payload are already visible through the shared NAS. Stage only immutable external inputs.
56
+ files=set(Path(x) for x in kwargs.get('inputs',[]) if Path(x).is_file())
57
+ for flag in ['--condition','--condition-npz','--support-manifest','--train-donors-file']:
58
+ if flag in argv:files.add(Path(argv[argv.index(flag)+1]))
59
+ if '--dataset-dir' in argv:
60
+ ds=Path(argv[argv.index('--dataset-dir')+1]);files.update([ds/'cells_panel6k.npz',ds/'folds.csv'])
61
+ for f in sorted(files):
62
+ if f.is_relative_to(P/'payload'):continue
63
+ digest=sha256(f)
64
+ code='import pathlib,hashlib,sys; p=pathlib.Path(sys.argv[1]); print(hashlib.file_digest(p.open("rb"),"sha256").hexdigest() if p.is_file() else "MISSING")'
65
+ got=ssh(['python3','-c',code,str(f)],capture_output=True,text=True).stdout.strip()
66
+ if got=='MISSING':
67
+ ssh(['mkdir','-p',str(f.parent)])
68
+ subprocess.run(['rsync','-a',str(f),'spark-0110:'+str(f)],check=True)
69
+ got=ssh(['python3','-c',code,str(f)],capture_output=True,text=True).stdout.strip()
70
+ if got!=digest:raise RuntimeError('Remote input differs; preserve and inspect: '+str(f))
71
+ return super().execute(name,argv,**kwargs)
paper-releases/pbisc-diffusion/updates/20261013T223459Z-f01-two-host-dispatch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/publish_core.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verified immutable HF backup independent of the local archive capacity gate.
2
+ Does not advance paper LATEST or claim the independent archive is complete.
3
+ """
4
+ from pathlib import Path
5
+ import fcntl,hashlib,json,os,sys
6
+ os.environ['HF_HUB_DISABLE_XET']='1'
7
+ os.environ['HF_HUB_ENABLE_HF_TRANSFER']='0'
8
+ from huggingface_hub import HfApi,hf_hub_download
9
+ P=Path(__file__).resolve().parents[1];RELEASE=P.parents[3]/'paper-release-20260928'
10
+ PREFIX='campaigns/f01-6k-trunk4x-20261013'
11
+ def digest(p):
12
+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
13
+ def collect(pretrain=False):
14
+ v=json.loads((P/'PRETRAIN_VERIFIED.json').read_text());files=[(Path(v['checkpoint']),'model','pretrain/checkpoint_epoch_016.pt')]
15
+ files += [(P/n,'dataset',n) for n in ['PRETRAIN_VERIFIED.json','MATRIX.json','CONTRACT.json','TWO_HOST_PLAN.json','WORKFLOW_SEAL.json']]
16
+ if not pretrain:
17
+ assert json.loads((P/'RESULTS_STATUS.json').read_text())['phase']=='data_complete_with_review_gates'
18
+ for j in json.loads((P/'MATRIX.json').read_text())['paired_jobs']:
19
+ if j.get('adapter_alias'):continue
20
+ out=Path(j['output']);files += [(out/'run/checkpoint_ft.pt','model',j['id']+'/checkpoint_ft.pt'),(out/'run/RUN.json','dataset',j['id']+'/RUN.json')]
21
+ for f in (out/'evaluation').rglob('*'):
22
+ if f.is_file() and f.suffix in ['.json','.csv'] and f.stat().st_size<4*2**20 and '/labels/' not in str(f):files.append((f,'dataset',str(f.relative_to(P))))
23
+ for root in [P/'comparison',P/'payload/pooled',P/'payload/sle',P/'payload/bulkonly']:
24
+ for f in root.rglob('*'):
25
+ if f.is_file() and f.suffix in ['.json','.csv','.png','.pdf','.svg'] and f.stat().st_size<16*2**20:files.append((f,'dataset',str(f.relative_to(P))))
26
+ files += [(P/n,'dataset',n) for n in ['RESULTS_STATUS.json','PENDING_EVIDENCE.json']]
27
+ return files
28
+
29
+ def main():
30
+ pretrain='--pretrain' in sys.argv;records=[];api=HfApi(token=True)
31
+ with (RELEASE/'maintenance/.writer.lock').open('a') as lock:
32
+ fcntl.flock(lock,fcntl.LOCK_EX)
33
+ for p,kind,relative in collect(pretrain):
34
+ repo='junidude14/PBISC' if kind=='model' else 'junidude14/PBISC-data'
35
+ info=api.repo_info(repo_id=repo,repo_type=kind)
36
+ assert info.private if kind=='dataset' else (not info.private and info.gated in [True,'auto','manual'])
37
+ sha=digest(p);path=f'{PREFIX}/{relative}';head=info.sha
38
+ existing=api.get_paths_info(repo_id=repo,paths=[path],repo_type=kind,revision=head)
39
+ if not existing:
40
+ commit=api.upload_file(path_or_fileobj=str(p),path_in_repo=path,repo_id=repo,repo_type=kind,parent_commit=head,commit_message='Back up completed PBISC same-panel trunk4x evidence')
41
+ head=commit.oid;existing=api.get_paths_info(repo_id=repo,paths=[path],repo_type=kind,revision=head)
42
+ assert len(existing)==1 and existing[0].size==p.stat().st_size
43
+ lfs=existing[0].lfs
44
+ if lfs:assert lfs.sha256==sha,'Immutable HF content conflict'
45
+ else:
46
+ saved=Path(hf_hub_download(repo_id=repo,repo_type=kind,filename=path,revision=head,token=True));assert digest(saved)==sha,'HF readback mismatch'
47
+ records.append({'source':str(p),'repo':repo,'repo_type':kind,'path':path,'revision':head,'sha256':sha,'bytes':p.stat().st_size})
48
+ print(json.dumps(records[-1]),flush=True)
49
+ target=P/('HF_PRETRAIN_VERIFIED.json' if pretrain else 'HF_CORE_VERIFIED.json')
50
+ target.write_text(json.dumps({'state':'verified','assets':records,'independent_archive':'separate maintenance receipt; this backup does not advance LATEST'},indent=2)+'\n')
51
+ if __name__=='__main__':main()
paper-releases/pbisc-diffusion/updates/20261013T223459Z-f01-two-host-dispatch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/remote_gpu.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Remote entrypoint: CPU-only safety checks; CUDA command always inside remote ml-run."""
2
+ from pathlib import Path
3
+ import json,os,subprocess,sys
4
+ os.environ['XDG_RUNTIME_DIR']='/run/user/1000'
5
+ os.environ['DBUS_SESSION_BUS_ADDRESS']='unix:path=/run/user/1000/bus'
6
+ P=Path(__file__).resolve().parents[1]
7
+ NAS=Path('/home/sj_server_2/nas_fast')
8
+ def check():
9
+ if subprocess.run(['systemctl','--user','is-active','--quiet','ml-memory-guard.service']).returncode:
10
+ subprocess.run(['systemctl','--user','restart','ml-memory-guard.service'],check=True)
11
+ subprocess.run(['systemctl','--user','is-active','ml-memory-guard.service'],check=True)
12
+ subprocess.run(['/home/sj_server_2/.local/libexec/ml-memory-guard','--check'],check=True)
13
+ processes=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid,process_name,used_memory','--format=csv,noheader'],text=True)
14
+ if processes.strip():print(processes);raise SystemExit(75)
15
+ if subprocess.run(['flock','-n','/run/user/1000/ml-gpu0.lock','true']).returncode:raise SystemExit(75)
16
+ available=next(int(x.split()[1])/1048576 for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemAvailable:'))
17
+ if available<48:raise SystemExit(75)
18
+ assert os.path.ismount(NAS),'NAS unavailable'
19
+ assert (P/'payload').resolve()==NAS/'PBISC/pbisc-diffusion/f01_trunk4x_complete_20261013'
20
+ v=os.statvfs(P/'payload');assert v.f_bavail*v.f_frsize>120*2**30
21
+ check()
22
+ if sys.argv[1]=='--check':raise SystemExit(0)
23
+ r=json.loads(Path(sys.argv[1]).read_text());argv=r['argv'];argv[0]=sys.executable
24
+ # Kernel and code consistency is validated before enabling the dispatch plan.
25
+ subprocess.run(['/home/sj_server_2/.local/bin/ml-run','/usr/bin/env','CUDA_VISIBLE_DEVICES=0','PYTHONDONTWRITEBYTECODE=1','PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True',*[f'{k}={r["threads"]}' for k in ['OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMBA_NUM_THREADS']],*argv],check=True)