File size: 3,113 Bytes
5024339
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Wait for the existing GPU-2 LiveWorld job, then run three PanoData samples."""
from pathlib import Path
import fcntl
import json
import os
import subprocess
import sys
import time

ROOT = Path(__file__).resolve().parents[1]
LOGS = ROOT / 'logs'
LOGS.mkdir(exist_ok=True)
STATUS = LOGS / 'panodata_queue_status.json'


def identity(pid):
    try:
        fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
        return None if fields[0] == 'Z' else fields[19]
    except (FileNotFoundError, ProcessLookupError):
        return None


def write_status(state, **kwargs):
    payload = {'state': state, 'updated_at': time.strftime('%Y-%m-%d %H:%M:%S %z'), **kwargs}
    temporary = STATUS.with_suffix('.tmp')
    temporary.write_text(json.dumps(payload, indent=2))
    temporary.replace(STATUS)
    print(json.dumps(payload), flush=True)


def main():
    lock = (LOGS / 'panodata_queue.lock').open('w')
    fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    request = json.loads((LOGS / 'panodata_queue_request.json').read_text())
    pid, start = request['wait_pid'], request['wait_start_ticks']
    write_status('waiting_for_current_job', wait_pid=pid, samples=3, gpu=2)
    while start is not None and identity(pid) == start:
        time.sleep(30)
    # The prior process has released CUDA, but allow for other jobs sharing GPU 2.
    write_status('waiting_for_gpu_memory', gpu=2, minimum_free_mib=70000)
    while True:
        result = subprocess.run(['nvidia-smi', '-i', '2', '--query-gpu=memory.free',
                                 '--format=csv,noheader,nounits'], capture_output=True, text=True)
        if result.returncode:
            raise RuntimeError(result.stderr)
        if int(result.stdout.strip()) >= 70000:
            break
        time.sleep(30)
    env = os.environ.copy()
    env['CUDA_VISIBLE_DEVICES'] = '2'
    env.setdefault('OMP_NUM_THREADS', '8')
    env.setdefault('PYTORCH_CUDA_ALLOC_CONF', 'expandable_segments:True')
    command = [sys.executable, '-u', str(ROOT / 'scripts/infer_panodata.py'),
               '--max_samples', '3', '--perspective_num_frames', '1', '--num_frames', '81',
               '--skip_existing', '--device', 'cuda:0']
    logfile = LOGS / 'infer_panodata_first3.log'
    with logfile.open('ab', buffering=0) as output:
        child = subprocess.Popen(command, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
                                 stdout=output, stderr=subprocess.STDOUT)
        write_status('running', pid=child.pid, gpu=2, samples=3, command=command,
                     log=str(logfile), previous_job_final_video_exists=(
                         ROOT / 'outputs_local/kid_coffee/traj_f/final_video.mp4').is_file())
        code = child.wait()
    write_status('complete' if code == 0 else 'failed', returncode=code, gpu=2,
                 samples=3, log=str(logfile), output=str(ROOT / 'outputs_panodata/LiveWorld-K1'))
    if code:
        raise SystemExit(code)


if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        write_status('failed', error=str(exc))
        raise