cmvr-visual/inference/llm_services/gpu_policy.py

242 lines
12 KiB
Python

"""Read-only GPU admission/preemption policy backed by a host monitor snapshot.
This module never imports CUDA/NVML or inspects host /proc. It grants no lock:
the serial worker owns execution, and must stop its whole job process group
before requeueing when should_yield() reports an external user or bad snapshot.
"""
from __future__ import annotations
import json
import math
import os
import re
import time
from pathlib import Path
from typing import Any, Callable
MAX_SNAPSHOT_AGE_SECONDS = 5.0
MAX_FUTURE_SECONDS = 1.0
MAX_SNAPSHOT_BYTES = 1024 * 1024
_GPU_UUID = re.compile(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z")
_CONTAINER_ID = re.compile(r"[0-9a-fA-F]{64}\Z")
_SNAPSHOT_KEYS = {"schema_version", "generated_at", "error", "container_id", "gpus"}
_GPU_KEYS = {"index", "uuid", "total_gib", "free_gib", "idle_since", "external_pids", "own_pids"}
def _number(value: Any, name: str, *, minimum: float = 0) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{name} must be a finite number")
try:
normalized = float(value)
except (ValueError, OverflowError) as exc:
raise ValueError(f"{name} must be a finite number") from exc
if not math.isfinite(normalized) or normalized < minimum:
raise ValueError(f"{name} must be finite and at least {minimum:g}")
return normalized
def _keys(value: Any, required: set[str], name: str, *, optional: set[str] | None = None) -> None:
if (not isinstance(value, dict) or not required.issubset(value)
or set(value) - required - (optional or set())):
raise ValueError(f"{name} has missing or unknown fields")
def _index(value: Any) -> int:
if type(value) is not int or value < 0:
raise ValueError("GPU index must be a nonnegative integer")
return value
def _uuid(value: Any) -> str:
if not isinstance(value, str) or _GPU_UUID.fullmatch(value) is None:
raise ValueError("GPU uuid is malformed")
return value
def _pids(value: Any, name: str) -> list[int]:
if not isinstance(value, list) or any(type(pid) is not int or pid <= 0 for pid in value):
raise ValueError(f"{name} must be a list of positive integer PIDs")
if len(value) != len(set(value)):
raise ValueError(f"{name} contains duplicate PIDs")
return list(value)
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise ValueError("Snapshot contains a duplicate JSON key")
result[key] = value
return result
def _lease(value: Any) -> dict[str, Any]:
# The worker receives uuid+index from choose(); an already spawned model
# stage only needs the UUID inherited through LLM_GPU_UUID.
if not isinstance(value, dict) or "uuid" not in value or set(value) - {"uuid", "index"}:
raise ValueError("GPU lease requires uuid and optionally index")
result = {"uuid": _uuid(value["uuid"])}
if "index" in value:
result["index"] = _index(value["index"])
return result
class GpuPolicy:
def __init__(self, status_path: str | Path, *, budget_gib: Any = 68,
reserve_gib: Any = 8, idle_seconds: Any = 15,
now: Callable[[], float] = time.time):
self.path = Path(status_path)
self._now = now
self._configuration_error: str | None = None
self.budget_gib = self.reserve_gib = self.idle_seconds = None
try:
if not self.path.is_absolute():
raise ValueError("LLM_GPU_STATUS_PATH must be an absolute file path")
values = []
for name, value, minimum, maximum in (
("LLM_GPU_BUDGET_GIB", budget_gib, 1, 72),
("LLM_GPU_RESERVE_GIB", reserve_gib, 1, 16),
("LLM_GPU_IDLE_SECONDS", idle_seconds, 0, 86400),
):
if isinstance(value, bool):
raise ValueError(f"{name} must be a finite number")
try:
number = float(value)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"{name} must be a finite number") from exc
if not math.isfinite(number) or not minimum <= number <= maximum:
raise ValueError(f"{name} must be between {minimum} and {maximum}")
values.append(number)
self.budget_gib, self.reserve_gib, self.idle_seconds = values
except ValueError as exc:
self._configuration_error = f"GPU policy configuration error: {exc}"
@classmethod
def from_env(cls) -> GpuPolicy | None:
if "LLM_GPU_STATUS_PATH" not in os.environ:
return None
return cls(os.environ["LLM_GPU_STATUS_PATH"],
budget_gib=os.environ.get("LLM_GPU_BUDGET_GIB", "68"),
reserve_gib=os.environ.get("LLM_GPU_RESERVE_GIB", "8"),
idle_seconds=os.environ.get("LLM_GPU_IDLE_SECONDS", "15"))
def _read(self) -> tuple[dict[str, Any] | None, str | None, float | None]:
if self._configuration_error is not None:
return None, self._configuration_error, None
try:
now = _number(self._now(), "current time")
with self.path.open("rb") as handle:
raw = handle.read(MAX_SNAPSHOT_BYTES + 1)
if len(raw) > MAX_SNAPSHOT_BYTES:
raise ValueError("Snapshot exceeds the size limit")
data = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
_keys(data, _SNAPSHOT_KEYS, "Snapshot")
if type(data["schema_version"]) is not int or data["schema_version"] != 1:
raise ValueError("Unsupported GPU snapshot schema_version")
generated_at = _number(data["generated_at"], "generated_at")
if generated_at > now + MAX_FUTURE_SECONDS:
raise ValueError("GPU snapshot timestamp is in the future")
if now - generated_at > MAX_SNAPSHOT_AGE_SECONDS:
raise ValueError("GPU snapshot is stale")
if not isinstance(data["container_id"], str) or _CONTAINER_ID.fullmatch(data["container_id"]) is None:
raise ValueError("Snapshot container_id must be a full 64-hex container ID")
if data["error"] is not None and not isinstance(data["error"], str):
raise ValueError("Snapshot error must be null or a string")
if not isinstance(data["gpus"], list):
raise ValueError("Snapshot gpus must be a list")
indexes, uuids = set(), set()
gpus = []
for gpu in data["gpus"]:
# Only the root monitor may attest baseline processes (e.g. its
# exact PID/birth/executable/type/memory Xorg allowlist). The
# container policy does not inspect or infer host exemptions.
_keys(gpu, _GPU_KEYS, "GPU entry", optional={"baseline_pids"})
index, uuid = _index(gpu["index"]), _uuid(gpu["uuid"])
if index in indexes or uuid.lower() in uuids:
raise ValueError("Snapshot contains duplicate GPU index or UUID")
indexes.add(index)
uuids.add(uuid.lower())
total = _number(gpu["total_gib"], "total_gib")
free = _number(gpu["free_gib"], "free_gib")
if total <= 0 or free > total:
raise ValueError("GPU memory must satisfy 0 <= free_gib <= total_gib and total_gib > 0")
idle_since = gpu["idle_since"]
if idle_since is not None:
idle_since = _number(idle_since, "idle_since")
if idle_since > now + MAX_FUTURE_SECONDS or idle_since > generated_at + MAX_FUTURE_SECONDS:
raise ValueError("GPU idle_since timestamp is in the future")
external = _pids(gpu["external_pids"], "external_pids")
own = _pids(gpu["own_pids"], "own_pids")
baseline = _pids(gpu.get("baseline_pids", []), "baseline_pids")
if set(external) & set(own) or set(baseline) & (set(external) | set(own)):
raise ValueError("GPU process ownership lists must not overlap")
gpus.append({"index": index, "uuid": uuid, "total_gib": total, "free_gib": free,
"idle_since": idle_since, "external_pids": external, "own_pids": own,
"baseline_pids": baseline})
if data["error"] is not None:
return None, f"GPU monitor error: {data['error']}", now
return {"generated_at": generated_at, "container_id": data["container_id"], "gpus": gpus}, None, now
except (OSError, ValueError, TypeError, OverflowError, RecursionError) as exc:
return None, f"GPU snapshot unavailable: {exc}", None
def _eligible(self, data: dict[str, Any], now: float) -> list[dict[str, Any]]:
candidates = [gpu for gpu in data["gpus"]
if not gpu["external_pids"] and not gpu["own_pids"]
and gpu["idle_since"] is not None
and now - gpu["idle_since"] >= self.idle_seconds
and gpu["free_gib"] >= self.budget_gib + self.reserve_gib]
return sorted(candidates, key=lambda gpu: (-gpu["free_gib"], gpu["index"]))
def choose(self) -> dict[str, Any] | None:
data, reason, now = self._read()
if reason is not None:
return None
eligible = self._eligible(data, now)
return {"uuid": eligible[0]["uuid"], "index": eligible[0]["index"]} if eligible else None
def should_yield(self, lease: Any) -> str | None:
try:
lease = _lease(lease)
except (ValueError, TypeError) as exc:
return f"Invalid GPU lease: {exc}"
data, reason, _ = self._read()
if reason is not None:
return reason
chosen = next((gpu for gpu in data["gpus"] if gpu["uuid"].lower() == lease["uuid"].lower()), None)
if chosen is None:
return "Leased GPU is missing from the monitor snapshot"
if "index" in lease and chosen["index"] != lease["index"]:
return "Leased GPU index changed in the monitor snapshot"
if chosen["external_pids"]:
return "External GPU user detected on leased GPU; stop and requeue this job"
# Our own process and allocator consumption are expected while running.
return None
def environment(self, lease: Any) -> dict[str, str]:
lease = _lease(lease)
if self._configuration_error is not None:
raise ValueError(self._configuration_error)
return {"CUDA_VISIBLE_DEVICES": lease["uuid"], "LLM_GPU_UUID": lease["uuid"]}
def describe(self) -> dict[str, Any]:
data, reason, now = self._read()
description = {"enabled": True, "status": "unavailable", "reason": reason,
"status_path": str(self.path), "budget_gib": self.budget_gib,
"reserve_gib": self.reserve_gib, "idle_seconds": self.idle_seconds,
"max_snapshot_age_seconds": MAX_SNAPSHOT_AGE_SECONDS,
"generated_at": None, "age_seconds": None, "selected": None,
"eligible_gpus": [], "gpus": []}
if reason is not None:
return description
eligible = self._eligible(data, now)
description.update(status="ready" if eligible else "waiting", reason=None if eligible else "No eligible GPU",
generated_at=data["generated_at"], age_seconds=max(0, now - data["generated_at"]),
eligible_gpus=[{"uuid": gpu["uuid"], "index": gpu["index"]} for gpu in eligible])
description["selected"] = description["eligible_gpus"][0] if eligible else None
description["gpus"] = [{"index": gpu["index"], "uuid": gpu["uuid"], "total_gib": gpu["total_gib"],
"free_gib": gpu["free_gib"], "idle_since": gpu["idle_since"],
"external_processes": len(gpu["external_pids"]), "own_processes": len(gpu["own_pids"]),
"baseline_processes": len(gpu["baseline_pids"])}
for gpu in sorted(data["gpus"], key=lambda gpu: gpu["index"])]
return description