File size: 10,271 Bytes
f947839
 
 
 
 
 
61b4734
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61b4734
 
 
 
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61b4734
 
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61b4734
 
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""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()