Datasets:
File size: 9,795 Bytes
df3939b | 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 | import argparse
import concurrent.futures
from datetime import datetime
import json
import os
from pathlib import Path
import subprocess
import threading
import time
from zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parents[1]
RUN = ROOT / 'experiments/run_20261025'
LOCK = threading.Lock()
STOP = threading.Event()
STAGES = ['train', 'test_100000', 'test_150000']
def now():
return datetime.now(ZoneInfo('America/New_York')).isoformat(timespec='seconds')
def write_state(state):
temporary = RUN / 'state.tmp'
temporary.write_text(json.dumps(state, indent=2) + '\n')
temporary.replace(RUN / 'state.json')
def free_memory(gpu):
output = subprocess.check_output(['nvidia-smi', f'--id={gpu}', '--query-gpu=memory.free',
'--format=csv,noheader,nounits'], text=True)
return int(output.strip())
def required_memory(job, stage=None):
if job['method'] == 'trnerf':
return 4096
if job['method'] == 'transientangelo' and (stage or job.get('resume_stage', 'train')).startswith('test_'):
return 8192
return 9216
def retry_failed_test(state, job_id):
failed = [job for job in state['jobs'] if job['status'] == 'failed']
if len(failed) != 1 or failed[0]['id'] != job_id:
raise SystemExit('Inspect failures first; --retry-failed must name the only failed job.')
if any(job['status'] == 'running' for job in state['jobs']):
raise SystemExit('Do not retry while another queue job is still running.')
job = failed[0]
stage = job.get('stage')
if stage not in STAGES[1:]:
raise SystemExit('Only failed evaluations can be retried without retraining.')
for step in (100000, 150000):
filenames = ([f'step{step}.ckpt'] if job['method'] == 'transientangelo'
else [f'radiance_field_{step:04d}.pth', f'occupancy_grid_{step:04d}.pth'])
for filename in filenames:
if not (Path(job['checkpoint']) / filename).is_file():
raise SystemExit(f'Missing completed training checkpoint: {filename}')
output = Path(job['work']) / stage
if (output / 'unified_metrics/metrics_aggregate.json').exists():
raise SystemExit('The failed stage has an aggregate result; inspect it rather than overwrite it.')
archive = None
if output.exists():
timestamp = datetime.now(ZoneInfo('America/New_York')).strftime('%Y%m%dT%H%M%S%f%z')
archive = output.with_name(f'{stage}_failed_{timestamp}')
output.rename(archive)
job.setdefault('retry_history', []).append(dict(stage=stage, returncode=job.get('returncode'),
failed_at=job.get('finished'), retried_at=now(), archived_output=str(archive) if archive else None))
job.update(status='pending', resume_stage=stage)
job.pop('returncode', None)
job.pop('finished', None)
print(f'{now()} Retrying {job_id} from {stage}; training and completed results are retained.', flush=True)
def execute(command, job, gpu, stage):
command = [argument.replace('{gpu}', str(gpu)).replace('{step}', stage.removeprefix('test_')) for argument in command]
environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu), CUDA_DEVICE_ORDER='PCI_BUS_ID',
CUDA_HOME='/home/donghongzhou/cuda-12.8', TORCH_CUDA_ARCH_LIST='12.0',
STB_METRICS_PYTHON=str(ROOT / 'experiments/.venv/bin/python'),
STB_METRICS_DEVICE='cpu',
OMP_NUM_THREADS='4', OPENBLAS_NUM_THREADS='2', MPLBACKEND='Agg',
PYTHONUNBUFFERED='1', PYTORCH_ALLOC_CONF='expandable_segments:True',
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True')
environment['TQDM_MININTERVAL'] = '60'
if job['method'] == 'transientangelo':
environment['PYTHONPATH'] = str(ROOT / 'experiments/ta_deps') + os.pathsep + environment.get('PYTHONPATH', '')
environment['TORCH_EXTENSIONS_DIR'] = str(ROOT / 'experiments/torch_extensions/ta')
environment['MAX_JOBS'] = '4'
environment['CC'] = '/usr/bin/gcc'
environment['CXX'] = '/usr/bin/g++'
environment['PATH'] = '/home/donghongzhou/cuda-12.8/bin:' + str(ROOT / 'experiments/.venv/bin') + ':' + environment['PATH']
logfile = Path(job['work']) / f'{stage}.log'
with logfile.open('a') as output:
output.write(f'\n[{now()}] {command}\n')
output.flush()
process = subprocess.Popen(command, cwd=job['cwd'], env=environment, stdout=output, stderr=subprocess.STDOUT)
print(f'{now()} GPU {gpu}: {job["id"]} {stage}, PID {process.pid}', flush=True)
return process.wait()
def worker(gpu, state):
while not STOP.is_set():
with LOCK:
if not any(job['status'] == 'pending' for job in state['jobs']):
return
available_memory = free_memory(gpu)
with LOCK:
if STOP.is_set():
return
job = next((job for job in state['jobs'] if job['status'] == 'pending'
and available_memory >= required_memory(job)), None)
if job is None:
state['workers'][str(gpu)] = dict(status='waiting_for_memory', memory_free_mib=available_memory, updated=now())
else:
job.update(status='running', gpu=gpu, started=now())
state['workers'][str(gpu)] = dict(status='running', job=job['id'], updated=now())
write_state(state)
if job is None:
time.sleep(30)
continue
for stage in STAGES[STAGES.index(job.get('resume_stage', 'train')):]:
if (job.get('preserve_completed_tests') and stage.startswith('test_')
and (Path(job['work']) / stage / 'unified_metrics/metrics_aggregate.json').is_file()):
print(f'{now()} Preserving completed {job["id"]} {stage}', flush=True)
continue
with LOCK:
job['stage'] = stage
write_state(state)
if job['method'] == 'transientangelo' and stage.startswith('test_'):
available_memory = free_memory(gpu)
while available_memory < required_memory(job, stage):
with LOCK:
state['workers'][str(gpu)] = dict(status='waiting_for_memory', job=job['id'],
stage=stage, memory_free_mib=available_memory, updated=now())
write_state(state)
if STOP.wait(30):
with LOCK:
job.update(status='pending', resume_stage=stage)
state['workers'][str(gpu)] = dict(status='idle', updated=now())
write_state(state)
return
available_memory = free_memory(gpu)
with LOCK:
state['workers'][str(gpu)] = dict(status='running', job=job['id'], updated=now())
write_state(state)
command = job['train'] if stage == 'train' else job['eval']
result = execute(command, job, gpu, stage)
if result == 0 and stage.startswith('test_'):
result = 0 if (Path(job['work']) / stage / 'unified_metrics/metrics_aggregate.json').is_file() else 1
if result:
with LOCK:
job.update(status='failed', returncode=result, finished=now())
state['workers'][str(gpu)] = dict(status='stopped_on_error', job=job['id'], stage=stage)
write_state(state)
STOP.set()
print(f'{now()} ERROR: {job["id"]} {stage} failed; no further jobs will launch.', flush=True)
return
with LOCK:
job.update(status='completed', finished=now())
job.pop('resume_stage', None)
job.pop('preserve_completed_tests', None)
state['workers'][str(gpu)] = dict(status='idle', updated=now())
write_state(state)
print(f'{now()} Completed {job["id"]}', flush=True)
time.sleep(5)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--resume', action='store_true')
parser.add_argument('--run-dir', type=Path, default=RUN)
parser.add_argument('--retry-failed', metavar='JOB_ID')
args = parser.parse_args()
RUN = args.run_dir.resolve()
if args.retry_failed and not args.resume:
parser.error('--retry-failed requires --resume')
if (RUN / 'state.json').exists() and not args.resume:
raise SystemExit('State already exists. Use --resume to continue the existing queue.')
state = json.loads((RUN / ('state.json' if args.resume else 'manifest.json')).read_text())
previous_pid = state.get('scheduler_pid')
if previous_pid:
try:
os.kill(previous_pid, 0)
except ProcessLookupError:
pass
else:
raise SystemExit(f'Queue scheduler {previous_pid} is already running.')
if args.retry_failed:
retry_failed_test(state, args.retry_failed)
if any(job['status'] in ('running', 'failed') for job in state['jobs']):
raise SystemExit('Inspect running/failed jobs before resuming; they are not automatically overwritten.')
state['workers'] = {}
state['scheduler_pid'] = os.getpid()
state['scheduler_started'] = now()
with LOCK:
write_state(state)
print(f'{now()} Queue started: {len(state["jobs"])} jobs on GPUs {state["gpus"]}; shares remaining memory with existing workloads.', flush=True)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
list(executor.map(lambda gpu: worker(gpu, state), state['gpus']))
|