File size: 5,251 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
import subprocess
import time
from dataclasses import dataclass
from pathlib import Path
from typing import TextIO

from packages.core.file_lock import lock_file

NVIDIA_SMI_QUERY = "index,name,memory.total,memory.used,memory.free,utilization.gpu"


@dataclass(frozen=True, slots=True)
class GpuInfo:
    index: int
    name: str
    memory_total_mb: int
    memory_used_mb: int
    memory_free_mb: int
    utilization_percent: int


def parse_nvidia_smi(output: str) -> list[GpuInfo]:
    gpus: list[GpuInfo] = []
    for line_number, raw_line in enumerate(output.splitlines(), start=1):
        line = raw_line.strip()
        if not line:
            continue
        parts = [part.strip() for part in line.split(",")]
        if len(parts) != 6:
            raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}")
        try:
            gpus.append(
                GpuInfo(
                    index=int(parts[0]),
                    name=parts[1],
                    memory_total_mb=int(parts[2]),
                    memory_used_mb=int(parts[3]),
                    memory_free_mb=int(parts[4]),
                    utilization_percent=int(parts[5]),
                )
            )
        except ValueError as exc:
            raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}") from exc
    return gpus


def select_gpus(
    gpus: list[GpuInfo],
    *,
    allowed_ids: set[int] | None,
    max_gpus: int,
    min_free_vram_mb: int,
    max_used_vram_mb: int,
    max_utilization_percent: int,
) -> list[GpuInfo]:
    if max_gpus < 0:
        raise ValueError("max_gpus must be non-negative (0 means all eligible GPUs)")
    candidates = [
        gpu
        for gpu in gpus
        if (allowed_ids is None or gpu.index in allowed_ids)
        and gpu.memory_free_mb >= min_free_vram_mb
        and gpu.memory_used_mb <= max_used_vram_mb
        and gpu.utilization_percent <= max_utilization_percent
    ]
    candidates.sort(key=lambda gpu: (gpu.utilization_percent, -gpu.memory_free_mb, gpu.index))
    return candidates if max_gpus == 0 else candidates[:max_gpus]


def probe_gpus() -> list[GpuInfo]:
    completed = subprocess.run(
        [
            "nvidia-smi",
            f"--query-gpu={NVIDIA_SMI_QUERY}",
            "--format=csv,noheader,nounits",
        ],
        check=True,
        capture_output=True,
        text=True,
    )
    return parse_nvidia_smi(completed.stdout)


@dataclass(slots=True)
class GpuLease:
    gpu: GpuInfo
    handle: TextIO

    def close(self) -> None:
        if not self.handle.closed:
            self.handle.close()

    def __enter__(self) -> GpuLease:
        return self

    def __exit__(self, *_: object) -> None:
        self.close()


class DynamicGpuPool:
    """Cross-process GPU leasing with a fresh memory check before every lease."""

    def __init__(
        self,
        lock_root: Path,
        *,
        allowed_ids: set[int] | None = None,
        min_free_vram_mb: int = 8192,
        max_used_vram_mb: int = 1 << 30,
        max_utilization_percent: int = 100,
    ) -> None:
        self.lock_root = lock_root
        self.allowed_ids = allowed_ids
        self.min_free_vram_mb = min_free_vram_mb
        self.max_used_vram_mb = max_used_vram_mb
        self.max_utilization_percent = max_utilization_percent
        self.lock_root.mkdir(parents=True, exist_ok=True)

    def try_acquire(self, *, excluded_ids: set[int] | None = None) -> GpuLease | None:
        excluded_ids = excluded_ids or set()
        candidates = select_gpus(
            probe_gpus(),
            allowed_ids=(
                None
                if self.allowed_ids is None
                else self.allowed_ids - excluded_ids
            ),
            max_gpus=0,
            min_free_vram_mb=self.min_free_vram_mb,
            max_used_vram_mb=self.max_used_vram_mb,
            max_utilization_percent=self.max_utilization_percent,
        )
        if self.allowed_ids is None:
            candidates = [gpu for gpu in candidates if gpu.index not in excluded_ids]
        for gpu in candidates:
            path = self.lock_root / f"gpu-{gpu.index}.lock"
            handle = path.open("a+", encoding="utf-8")
            if not lock_file(handle, blocking=False):
                handle.close()
                continue
            handle.seek(0)
            handle.truncate()
            handle.write(
                f"pid={os.getpid()} gpu={gpu.index} acquired_unix={time.time():.3f}\n"
            )
            handle.flush()
            return GpuLease(gpu=gpu, handle=handle)
        return None

    def acquire(
        self,
        *,
        timeout_s: float,
        poll_interval_s: float = 5.0,
        excluded_ids: set[int] | None = None,
    ) -> GpuLease:
        deadline = time.monotonic() + timeout_s
        while True:
            lease = self.try_acquire(excluded_ids=excluded_ids)
            if lease is not None:
                return lease
            if time.monotonic() >= deadline:
                raise TimeoutError("no GPU satisfied the lease requirements before timeout")
            time.sleep(min(poll_interval_s, max(0.0, deadline - time.monotonic())))