Download fair-comparison/flow-v1/code/lim/run_sequence.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 8.4 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/run_sequence.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/run_sequence.py
-
curl -L -o run_sequence.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/run_sequence.py
8.4 kB
| """Run a declared finite experiment sequence when its assigned GPU is free.""" | |
| import fcntl | |
| import hashlib | |
| import json | |
| import os | |
| import signal | |
| import subprocess | |
| import time | |
| from pathlib import Path | |
| from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveInt | |
| from pydantic_settings import CliApp | |
| from lim.job import JobConfig, run_job | |
| class SequenceConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| jobs: tuple[Path, ...] | |
| """Ordered immutable JobConfig specifications; any failure stops successors.""" | |
| output_dir: Path | |
| """New sequence state directory; never resume an interrupted sequence implicitly.""" | |
| gpu: NonNegativeInt | |
| """One preselected physical GPU, matching every job's assignment.""" | |
| max_wait_s: PositiveInt = 172800 | |
| """Maximum time waiting for shared GPU availability before stopping.""" | |
| poll_s: PositiveInt = 30 | |
| """Availability interval; no model or renderer is created while waiting.""" | |
| free_memory_mib: PositiveInt = 500 | |
| """Maximum existing GPU allocation permitted before launching a job.""" | |
| required_files: dict[Path, str] = {} | |
| """Exact SHA256 for asynchronously copied inputs; checked before any GPU work.""" | |
| prerequisite_sequence: Path | None = None | |
| """Existing sequence state.json that must complete before taking the GPU lock.""" | |
| class SequenceCLIConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| spec: Path | |
| """Complete JSON SequenceConfig, including input dependencies and assigned GPU.""" | |
| def run(config: SequenceConfig): | |
| jobs = [JobConfig.model_validate_json(p.read_text()) for p in config.jobs] | |
| if not jobs or any(j.gpu != config.gpu for j in jobs): | |
| raise ValueError("Sequence must be nonempty and use exactly its assigned GPU") | |
| config.output_dir.mkdir(parents=True, exist_ok=False) | |
| record = { | |
| "status": "waiting", | |
| "config": config.model_dump(mode="json"), | |
| "jobs": [j.model_dump(mode="json") for j in jobs], | |
| "completed_jobs": [], | |
| "started_epoch": time.time(), | |
| } | |
| path = config.output_dir / "state.json" | |
| def write(): | |
| tmp = path.with_suffix(".tmp") | |
| tmp.write_text(json.dumps(record, indent=2) + "\n") | |
| tmp.replace(path) | |
| def interrupted(signum, frame): | |
| raise KeyboardInterrupt(f"Sequence received signal {signum}") | |
| signal.signal(signal.SIGTERM, interrupted) | |
| write() | |
| remaining_wait = config.max_wait_s | |
| try: | |
| input_wait_started = time.monotonic() | |
| while missing := [str(p) for p in config.required_files if not p.is_file()]: | |
| record.update( | |
| status="waiting_for_inputs", | |
| missing_files=missing, | |
| checked_epoch=time.time(), | |
| ) | |
| write() | |
| if time.monotonic() - input_wait_started >= remaining_wait: | |
| raise TimeoutError("Input transfer did not complete") | |
| time.sleep(config.poll_s) | |
| for p, expected in config.required_files.items(): | |
| with p.open("rb") as stream: | |
| actual = hashlib.file_digest(stream, "sha256").hexdigest() | |
| if actual != expected: | |
| raise ValueError(f"Input digest mismatch: {p}") | |
| remaining_wait -= time.monotonic() - input_wait_started | |
| record.pop("missing_files", None) | |
| record["inputs_verified"] = True | |
| write() | |
| dependency_started = time.monotonic() | |
| if config.prerequisite_sequence is not None: | |
| while True: | |
| dependency = json.loads(config.prerequisite_sequence.read_text()) | |
| status = dependency["status"] | |
| if status == "complete": | |
| record["prerequisite_complete"] = str(config.prerequisite_sequence) | |
| break | |
| if status in ("failed", "interrupted"): | |
| raise RuntimeError( | |
| f"Prerequisite sequence {status}; successors stopped" | |
| ) | |
| record.update( | |
| status="waiting_for_prerequisite", checked_epoch=time.time() | |
| ) | |
| write() | |
| if time.monotonic() - dependency_started >= remaining_wait: | |
| raise TimeoutError("Prerequisite sequence did not complete") | |
| time.sleep(config.poll_s) | |
| remaining_wait -= time.monotonic() - dependency_started | |
| # Cooperating project workers cannot race for the same physical device. | |
| with Path(f"/tmp/lim-gpu-{os.getuid()}-{config.gpu}.lock").open("a") as lock: | |
| lock_started = time.monotonic() | |
| while True: | |
| try: | |
| fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| break | |
| except BlockingIOError: | |
| record.update(status="waiting_for_lock", checked_epoch=time.time()) | |
| write() | |
| if time.monotonic() - lock_started >= remaining_wait: | |
| raise TimeoutError( | |
| "Assigned GPU remained reserved by another sequence" | |
| ) | |
| time.sleep(config.poll_s) | |
| remaining_wait -= time.monotonic() - lock_started | |
| for spec, job in zip(config.jobs, jobs, strict=True): | |
| wait_started = time.monotonic() | |
| deadline = wait_started + remaining_wait | |
| record.update(status="waiting", current_job=str(spec)) | |
| while True: | |
| query = subprocess.run( | |
| [ | |
| "nvidia-smi", | |
| f"--id={config.gpu}", | |
| "--query-gpu=memory.used,utilization.gpu", | |
| "--format=csv,noheader,nounits", | |
| ], | |
| capture_output=True, | |
| text=True, | |
| check=True, | |
| timeout=20, | |
| ) | |
| memory, utilization = [ | |
| int(x.strip()) for x in query.stdout.split(",") | |
| ] | |
| record.update( | |
| gpu_memory_mib=memory, | |
| gpu_utilization_pct=utilization, | |
| checked_epoch=time.time(), | |
| ) | |
| write() | |
| if memory <= config.free_memory_mib and utilization <= 10: | |
| break | |
| if time.monotonic() >= deadline: | |
| raise TimeoutError("Assigned GPU remained occupied") | |
| time.sleep(config.poll_s) | |
| if JobConfig.model_validate_json(spec.read_text()) != job: | |
| raise ValueError("Job specification changed while waiting") | |
| remaining_wait -= time.monotonic() - wait_started | |
| record.update(status="running") | |
| write() | |
| run_job(job) | |
| result = json.loads((job.output_dir / "result.json").read_text()) | |
| if result["status"] != "complete" or result["exit_code"] != 0: | |
| raise RuntimeError("Job did not complete successfully") | |
| record["completed_jobs"].append(str(spec)) | |
| signal.signal(signal.SIGTERM, interrupted) | |
| record.update(status="complete", ended_epoch=time.time()) | |
| except BaseException as error: | |
| current_result = ( | |
| jobs[len(record["completed_jobs"])].output_dir / "result.json" | |
| if len(record["completed_jobs"]) < len(jobs) | |
| else None | |
| ) | |
| child_interrupted = ( | |
| current_result is not None | |
| and current_result.exists() | |
| and json.loads(current_result.read_text()).get("status") == "interrupted" | |
| ) | |
| record.update( | |
| status="interrupted" | |
| if isinstance(error, KeyboardInterrupt) or child_interrupted | |
| else "failed", | |
| error=f"{type(error).__name__}: {error}", | |
| ended_epoch=time.time(), | |
| ) | |
| raise | |
| finally: | |
| write() | |
| if __name__ == "__main__": | |
| cli = CliApp.run(SequenceCLIConfig) | |
| run(SequenceConfig.model_validate_json(cli.spec.read_text())) | |