Download code/controller.py from yang29/afd-causal-forcing-baselines-vbench: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/yang29/afd-causal-forcing-baselines-vbench/resolve/main/code/controller.py
- Command line
-
hf download hf://datasets/yang29/afd-causal-forcing-baselines-vbench/code/controller.py
-
curl -L -o controller.py https://huggingface.co/datasets/yang29/afd-causal-forcing-baselines-vbench/resolve/main/code/controller.py
10.3 kB
| """Detached PBS supervision: CF GPU tests, training, and every-40 evaluation.""" | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import shutil | |
| import subprocess | |
| import time | |
| from scripts.causal_baselines_b200.common import REPO, ROOT, CAMPAIGN, METHODS, STEPS, read, write | |
| from scripts.long_baselines_b200 import campaign as scheduler | |
| from scripts.long_vbench_b200.watch import host as evaluation_host | |
| scheduler.HEALTHY_HOSTS = {f'borealis-{n}' for n in (38,39,42,43,44,45)} | |
| ASTRO_PY='/hpctmp/e0833524/afd_astrolabe_b200/venv/bin/python' | |
| def call(*args,timeout=180): | |
| return scheduler.run(*args,timeout=timeout) | |
| def metrics(directory,method): | |
| files=list((Path(directory)/'logs').rglob('metrics.jsonl')) if method=='astrolabe' else [Path(directory)/'metrics.jsonl'] | |
| rows=[] | |
| for p in files: | |
| if p.exists(): | |
| for line in p.read_text().splitlines(): | |
| try: | |
| rows.append(json.loads(line)) | |
| except ValueError: | |
| pass | |
| return max(rows,key=lambda r:r['step']) if rows else None | |
| def reconcile(item): | |
| """A lost qsub response is not evidence that the job was not accepted.""" | |
| output=call('qstat','-u','e0833524','-f',timeout=20) | |
| for block in output.split('Job Id: ')[1:]: | |
| if re.search(r'^\s*Job_Name = '+re.escape(item['job_name'])+r'\s*$',block,re.M): | |
| item.update(job_id=block.splitlines()[0].strip(),stage='running') | |
| return | |
| if time.time()-item.get('submission_started',0)>120: | |
| item['stage']='pending' | |
| def submit(item,method,directory,smoke=False,plan=None): | |
| if plan and shutil.disk_usage(ROOT).free < 80 * 1024**3: | |
| item['storage_wait']='Waiting for 80 GiB free, including reserve for active training checkpoints' | |
| return False | |
| item.pop('storage_wait',None) | |
| selected=evaluation_host() if plan else scheduler.available_host() | |
| if selected is None: | |
| return False | |
| name=(f'cf-e-{method[:3]}-{read(plan)["checkpoint_step"]}' if plan else | |
| f'cf-{"s" if smoke else "t"}-{method[:3]}-{item.get("attempt",1)}') | |
| item.update(stage='submitting',job_name=name,submission_started=time.time()) | |
| write(CAMPAIGN/'status.json',STATE) | |
| if plan: | |
| variables=f'CF_EVAL_PLAN={plan}' | |
| resources=f'select=1:host={selected}:ngpus=1:ncpus=12:mem=100GB' | |
| else: | |
| skip=smoke and (directory/'training_verified.json').exists() | |
| variables=f'CF_METHOD={method},CF_RUN_DIR={directory},CF_SMOKE={int(smoke)},CF_SKIP_TRAIN={int(skip)}' | |
| resources=f'select=1:host={selected}:ngpus=2:ncpus=24:mem=200GB' | |
| try: | |
| response=call('qsub','-N',name,'-l',resources,'-v',variables,'-o',directory/'pbs.log', | |
| 'scripts/causal_baselines_b200/eval.pbs' if plan else 'scripts/causal_baselines_b200/train.pbs',timeout=45) | |
| job=re.search(r'\b\d+\.vip-ha-pbs\b',response) | |
| if job is None: | |
| raise ValueError(f'No job ID in response: {response}') | |
| item.update(stage='running',job_id=job.group(0),host=selected) | |
| item.pop('error',None) | |
| except Exception as exc: | |
| item.update(stage='submission_unknown',error=f'{type(exc).__name__}: {exc}') | |
| write(CAMPAIGN/'status.json',STATE) | |
| return True | |
| def live(item): | |
| if item.get('stage') in ('submitting','submission_unknown'): | |
| reconcile(item) | |
| return True | |
| if not item.get('job_id'): | |
| return False | |
| status=scheduler.job_status(item['job_id']) | |
| item['pbs']=status | |
| if status.get('job_state') not in ('E','F') or 'Exit_status' not in status: | |
| return True | |
| item.setdefault('previous_jobs',[]).append(dict(job_id=item.pop('job_id'),pbs=status)) | |
| if status.get('Exit_status') != '0' and item.get('host'): | |
| STATE.setdefault('node_cooldowns',{})[item['host']]=time.time()+3600 | |
| item.update(stage='retry_pending',retry_after=time.time()+30) | |
| return False | |
| def ensure_run(item,method,smoke): | |
| if item.get('run_dir'): | |
| directory=Path(item['run_dir']) | |
| if (directory/'manifest.json').exists(): | |
| return directory | |
| attempt=item.get('attempt',0)+1 | |
| directory=CAMPAIGN/('checks' if smoke else 'runs')/method/f'attempt-{attempt:03d}' | |
| # An interrupted prepare never overwrites an existing run. | |
| while directory.exists(): | |
| attempt+=1 | |
| directory=directory.with_name(f'attempt-{attempt:03d}') | |
| command=['bash','scripts/causal_baselines_b200/container.sh',ASTRO_PY,'-m', | |
| 'scripts.causal_baselines_b200.prepare','--method',method,'--run-dir',str(directory)] | |
| if smoke: | |
| command.append('--smoke') | |
| print(call(*command),flush=True) | |
| item.update(run_dir=str(directory),attempt=attempt,stage='pending') | |
| write(CAMPAIGN/'status.json',STATE) | |
| return directory | |
| def tick_method(method,item): | |
| check=item.setdefault('check',{}) | |
| directory=ensure_run(check,method,True) | |
| passed=directory/'gpu_test_passed.json' | |
| if passed.exists() and read(passed)['passed']: | |
| check['stage']='complete' | |
| elif live(check): | |
| return | |
| elif time.time()>=check.get('retry_after',0): | |
| if not (directory/'training_verified.json').exists() and metrics(directory,method): | |
| check.setdefault('failed_runs',[]).append(check.pop('run_dir')) | |
| directory=ensure_run(check,method,True) | |
| submit(check,method,directory,smoke=True) | |
| return | |
| else: | |
| return | |
| training=item.setdefault('training',{}) | |
| directory=ensure_run(training,method,False) | |
| row=metrics(directory,method) | |
| if row: | |
| training['latest_metrics']=row | |
| done=directory/'training_complete.json' | |
| if done.exists() and read(done)['passed']: | |
| training['stage']='complete' | |
| elif not live(training) and time.time()>=training.get('retry_after',0): | |
| if row: | |
| training.setdefault('failed_runs',[]).append(training.pop('run_dir')) | |
| directory=ensure_run(training,method,False) | |
| submit(training,method,directory) | |
| discover(method,directory) | |
| def discover(method,directory): | |
| from scripts.causal_baselines_b200.plan import prepare | |
| from scripts.causal_baselines_b200.eval_common import checkpoint_path | |
| for step in STEPS: | |
| key=f'{method}:{step}' | |
| if key in STATE['evaluations']: | |
| continue | |
| try: | |
| cp=checkpoint_path(dict(method=method,checkpoint_run_dir=str(directory),checkpoint_step=step)) | |
| if method=='astrolabe' and not (cp.parent.parent/'ready.json').exists(): | |
| continue | |
| if time.time()-cp.stat().st_mtime<30: | |
| continue | |
| output=CAMPAIGN/'evaluations'/f'step-{step:03d}'/method | |
| plan=prepare(method,directory,step,output) | |
| STATE['evaluations'][key]=dict(method=method,step=step,plan=str(plan),stage='pending') | |
| write(CAMPAIGN/'status.json',STATE) | |
| except FileNotFoundError: | |
| continue | |
| def evaluations(): | |
| uploaded=read(CAMPAIGN/'upload/status.json') if (CAMPAIGN/'upload/status.json').exists() else {'groups':{}} | |
| for method in METHODS: | |
| tasks=sorted([v for v in STATE['evaluations'].values() if v['method']==method],key=lambda v:v['step']) | |
| for item in tasks: | |
| output=Path(item['plan']).parent | |
| summary=output/'results/summary.json' | |
| key=f"step-{item['step']:03d}/{method}" | |
| if summary.exists(): | |
| result=read(summary) | |
| assert result['checkpoint_step']==item['step'] and result['generator_family']=='causal_forcing' | |
| assert not result['smoke'] and len(result['dimensions'])==16 | |
| item['stage']='complete' | |
| item['weighted_total_percent']=result['total_score_percent'] | |
| item['upload']=uploaded['groups'].get(key,{}).get('stage','pending') | |
| # At most one unarchived 4720-video group per method. Every new | |
| # checkpoint is pinned immediately; later groups wait for space. | |
| if item['upload']!='retired': | |
| break | |
| continue | |
| if live(item): | |
| break | |
| if time.time()>=item.get('retry_after',0): | |
| submit(item,method,output,plan=item['plan']) | |
| break | |
| def main(): | |
| global STATE | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--once',action='store_true') | |
| args=parser.parse_args() | |
| STATE=read(CAMPAIGN/'status.json') if (CAMPAIGN/'status.json').exists() else dict( | |
| methods={m:{} for m in METHODS},evaluations={},target_steps=160,checkpoint_interval=40) | |
| write(CAMPAIGN/'controller.json',dict(pid=os.getpid(),started=time.time())) | |
| while True: | |
| blocked={h for h,t in STATE.get('node_cooldowns',{}).items() if t>time.time()} | |
| scheduler.HEALTHY_HOSTS={f'borealis-{n}' for n in (38,39,42,43,44,45)}-blocked | |
| if not (ROOT/'assets/causal_forcing.json').exists(): | |
| STATE['stage']='waiting_for_official_checkpoint' | |
| else: | |
| STATE['stage']='active' | |
| for method,item in STATE['methods'].items(): | |
| try: | |
| tick_method(method,item) | |
| item.pop('controller_error',None) | |
| except Exception as exc: | |
| item['controller_error']=f'{type(exc).__name__}: {exc}' | |
| print(method,item['controller_error'],flush=True) | |
| try: | |
| evaluations() | |
| STATE.pop('evaluation_controller_error',None) | |
| except Exception as exc: | |
| STATE['evaluation_controller_error']=f'{type(exc).__name__}: {exc}' | |
| print(STATE['evaluation_controller_error'],flush=True) | |
| STATE['updated_utc']=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) | |
| write(CAMPAIGN/'status.json',STATE) | |
| print(json.dumps(dict(stage=STATE['stage'],methods={m:{k:v.get('stage') for k,v in i.items() if isinstance(v,dict)} | |
| for m,i in STATE['methods'].items()},evaluations={k:v['stage'] for k,v in STATE['evaluations'].items()})),flush=True) | |
| if args.once: | |
| return | |
| time.sleep(30) | |
| if __name__=='__main__': | |
| main() | |