"""One process on the video card at a time: the lock the GPU checks of the Pixal3D low-memory work take. A check that runs beside another program on the card measures nothing (a failure under contention is not evidence), so a run that touches CUDA holds the folder code/logs/profiling/gpu.lock for exactly as long as it is on the card. in Python import common (p3d_checks/common.py: common.gpu_lock is this one) with common.gpu_lock("WP1", "check_x sv1024", expected_minutes=4): ... # everything that touches CUDA; take it BEFORE the first # CUDA call of the process who has it python gpu_lock.py status exit code 0 = free, 3 = held How it works: - The folder is made with os.mkdir, which either succeeds or fails as one step, so two runs can never both get it. Inside is owner.json: {"wp", "pid", "started", "heartbeat", "purpose", "expected_minutes"} (ISO times), rewritten every 60 s by a thread of the holder. A waiting run tries every second and prints who holds the lock every 20 s. - Waiting runs queue first come, first served: each writes a ticket (its name orders them by the moment they asked) into gpu.lock.queue/ and only the oldest live ticket tries the mkdir, so a run cannot be starved by others that keep winning the race (round J: an agent waited 73 minutes). A ticket counts while its process is alive and its heartbeat (rewritten every 5 s by the waiting run) is under a minute old; the others are deleted on the way. `status` lists the queue. - A lock is stale, and is then moved aside, deleted and taken, only when its heartbeat is older than 10 minutes AND its process is gone. A lock whose process is alive is never broken, whatever its heartbeat says (a lock folder made by hand has no heartbeat thread at all). A folder without a readable owner file counts as held for 10 minutes after it was made. - With the lock in hand the helper asks nvidia-smi how much video memory is in use. More than 1.5 GiB held by others (a game, a 3D program, a run that did not take the lock) means: wait, and say so. The mirror rule: a process that asks for the lock while it still holds more than 512 MiB of live tensors is refused (HoldingVideoMemory), since every holder would wait for it to leave the card while it waits for the lock (round J's deadlock); free the model and the tables before releasing the lock, or hold it once per script. Others' share is the whole card's use minus what this process holds by PyTorch's count (plus its CUDA context): Windows does count video memory per process (mem_watch.py reads those counters), but the card's total is what also shows the desktop and the programs that never asked for the lock. A holder that is killed (a tool's time limit, Task Manager) cannot clean up: its lock is taken over 10 minutes after its last heartbeat. """ from __future__ import annotations import contextlib import ctypes import datetime import json import os import shutil import sys import threading import time from pathlib import Path from typing import Any, Callable, Iterator HERE = Path(__file__).resolve().parent if str(HERE) not in sys.path: # toolkit.py lies beside this file, which p3d_checks/common.py loads by its path sys.path.append(str(HERE)) import toolkit # noqa: E402 (stdlib only) LOCK = HERE.parents[1] / "logs" / "profiling" / "gpu.lock" OWNER = "owner.json" POLL_SECONDS = 20.0 # a waiting run says who holds the lock this often TRY_SECONDS = 1.0 # and tries to take it this often: a holder that takes it again within # seconds (one capture after another) must not starve the others HEARTBEAT_SECONDS = 60.0 STALE_SECONDS = 600.0 QUEUE_SUFFIX = ".queue" # the folder of the tickets of the runs waiting for the lock (see above) TICKET_BEAT_SECONDS = 5.0 # a waiting run rewrites its ticket's heartbeat this often TICKET_STALE_SECONDS = 60.0 # a ticket without a heartbeat for this long is not waiting any more OTHER_VRAM_MIB = 1536 SELF_VRAM_MIB = 512 # live tensors a process may still hold when it asks for the lock (below) CUDA_CONTEXT_MIB = 350 # what a process holds on the card beside PyTorch's reserve STILL_ACTIVE = 259 ACCESS_DENIED = 5 _depth_guard = threading.Lock() _write_guard = threading.Lock() # the heartbeat thread rewrites the owner record while the block runs _depth: dict[str, int] = {} # lock folder -> how many `with gpu_lock` blocks of this process are open tell = toolkit.teller("gpu-lock") card = toolkit.card class LockTimeout(RuntimeError): """The lock stayed with another run for longer than the caller was willing to wait.""" class CardBusy(RuntimeError): """Other programs kept more video memory than allowed for longer than the caller was willing to wait.""" def iso(when: float | None = None) -> str: stamp = datetime.datetime.fromtimestamp(time.time() if when is None else when).astimezone() return stamp.isoformat(timespec="seconds") def seconds_of(text: Any) -> float | None: """An ISO time as seconds since the epoch; a time without a zone is local time. None when it is not a time.""" try: when = datetime.datetime.fromisoformat(str(text).strip()) except (TypeError, ValueError): return None return when.astimezone().timestamp() def process(pid: int) -> tuple[bool, int | None]: """(is this process running, the moment it was created as the system counts it or None when unknown).""" if pid <= 0: return False, None if os.name != "nt": try: os.kill(pid, 0) except PermissionError: return True, None except OSError: return False, None # Linux: a zombie has ended (a pod whose first process never reaps them keeps its pid for good); the # creation moment is the start time in clock ticks after boot, which tells a reused pid apart try: fields = Path(f"/proc/{pid}/stat").read_text().rpartition(")")[2].split() except OSError: return True, None return fields[0] not in ("Z", "X"), int(fields[19]) from ctypes import wintypes k32 = ctypes.WinDLL("kernel32", use_last_error=True) k32.OpenProcess.restype = wintypes.HANDLE k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) k32.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)) k32.GetProcessTimes.argtypes = (wintypes.HANDLE,) + (ctypes.POINTER(wintypes.FILETIME),) * 4 k32.CloseHandle.argtypes = (wintypes.HANDLE,) handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION if not handle: return ctypes.get_last_error() == ACCESS_DENIED, None # it exists, under another account try: code = wintypes.DWORD() running = bool(k32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == STILL_ACTIVE times = [wintypes.FILETIME() for _ in range(4)] created = None if k32.GetProcessTimes(handle, *[ctypes.byref(t) for t in times]): created = (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime return running, created finally: k32.CloseHandle(handle) def read_owner(lock: Path) -> dict[str, Any] | None: """The lock's owner record, or None when the folder has no readable one (yet).""" for _ in range(3): # a writer may be replacing the file this instant try: record = json.loads((lock / OWNER).read_text(encoding="utf-8")) except FileNotFoundError: return None except (OSError, ValueError): time.sleep(0.05) continue return record if isinstance(record, dict) else None return None def owner_alive(owner: dict[str, Any]) -> bool: """Is the process that took the lock still running. A pid that Windows has given to a newer process does not count: the record carries the moment its own process was created.""" try: pid = int(owner.get("pid", 0)) except (TypeError, ValueError): pid = 0 running, created = process(pid) recorded = owner.get("pid_created") return running and (recorded is None or created is None or int(recorded) == created) def lock_state(lock: Path = LOCK, stale_seconds: float = STALE_SECONDS) -> dict[str, Any]: """The lock as it is now: {"held", "owner", "alive", "heartbeat_age", "stale"}.""" try: made = lock.stat().st_mtime except OSError: return {"held": False, "owner": None, "alive": None, "heartbeat_age": None, "stale": False} owner = read_owner(lock) now = time.time() if owner is None: if not lock.exists(): return {"held": False, "owner": None, "alive": None, "heartbeat_age": None, "stale": False} age = now - made return {"held": True, "owner": None, "alive": None, "heartbeat_age": age, "stale": age > stale_seconds} beat = seconds_of(owner.get("heartbeat")) if beat is None: beat = seconds_of(owner.get("started")) if beat is None: beat = made age = now - beat alive = owner_alive(owner) return {"held": True, "owner": owner, "alive": alive, "heartbeat_age": age, "stale": age > stale_seconds and not alive} def describe(state: dict[str, Any]) -> str: if not state["held"]: return "free" owner = state["owner"] if owner is None: return f"held by a folder without an owner file, made {state['heartbeat_age']:.0f} s ago" text = (f"held by {owner.get('wp') or '?'} (pid {owner.get('pid')}, " f"{'running' if state['alive'] else 'NOT running'}) since {owner.get('started', '?')}, heartbeat " f"{state['heartbeat_age']:.0f} s ago, expected {owner.get('expected_minutes', '?')} min") return text + (f": {owner['purpose']}" if owner.get("purpose") else "") def write_owner(lock: Path, record: dict[str, Any]) -> None: """Replace owner.json in one step: a reader sees the old record or the new one, never half of one.""" part = lock / f"{OWNER}.{os.getpid()}.part" with _write_guard: part.write_text(json.dumps(record), encoding="utf-8") for attempt in range(20): try: os.replace(part, lock / OWNER) return except PermissionError: # another run is reading it this instant (Windows) if attempt == 19: raise time.sleep(0.05) def break_stale(lock: Path, state: dict[str, Any]) -> bool: """Move a stale lock aside (gpu.lock.stale-