Datasets:
Download codes/reconstruction/experiments/run_queue.py from shuinb/SP-TransientBench: direct link, hf CLI and curl.
- Browser
- Download file 9.8 kB
-
https://huggingface.co/datasets/shuinb/SP-TransientBench/resolve/main/codes/reconstruction/experiments/run_queue.py
- Command line
-
hf download hf://datasets/shuinb/SP-TransientBench/codes/reconstruction/experiments/run_queue.py
-
curl -L -o run_queue.py https://huggingface.co/datasets/shuinb/SP-TransientBench/resolve/main/codes/reconstruction/experiments/run_queue.py
9.8 kB
| 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'])) | |