Repository navigation
Expand file tree
/
Copy pathgpu_memory.py
More file actions
97 lines (85 loc) · 3.75 KB
/
Copy pathgpu_memory.py
File metadata and controls
97 lines (85 loc) · 3.75 KB
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
"""Optional NVIDIA per-process GPU-memory sampling via NVML."""
from __future__ import annotations
import logging
log = logging.getLogger(__name__)
class NvidiaGpuMemorySampler:
"""Return framebuffer memory attributed to each PID across all GPUs.
NVML is optional: systems without the Python binding, an NVIDIA GPU, or
permission to query accounting simply return an empty sample.
"""
def __init__(self):
self._nvml = None
self._initialized = False
self._last_utilization_timestamp: dict[int, int] = {}
try:
import pynvml
pynvml.nvmlInit()
self._nvml = pynvml
self._initialized = True
except Exception as exc:
log.debug("NVIDIA GPU memory monitoring unavailable: %s", exc)
def sample(self) -> tuple[dict[int, float], dict[int, int]]:
if not self._initialized or self._nvml is None:
return {}, {}
nvml = self._nvml
per_device_pid: dict[tuple[int, int], int] = {}
utilization: dict[int, float] = {}
try:
for device_index in range(nvml.nvmlDeviceGetCount()):
handle = nvml.nvmlDeviceGetHandleByIndex(device_index)
utilization_getter = getattr(
nvml, "nvmlDeviceGetProcessUtilization", None
)
if utilization_getter is not None:
try:
samples = utilization_getter(
handle,
self._last_utilization_timestamp.get(device_index, 0),
)
if samples:
self._last_utilization_timestamp[device_index] = max(
int(sample.timeStamp) for sample in samples
)
for sample in samples:
pid = int(sample.pid)
# Sum work across GPUs, capped at a familiar percent.
utilization[pid] = min(
100.0,
utilization.get(pid, 0.0) + float(sample.smUtil),
)
except Exception:
pass
processes = []
for getter_name in (
"nvmlDeviceGetComputeRunningProcesses",
"nvmlDeviceGetGraphicsRunningProcesses",
):
getter = getattr(nvml, getter_name, None)
if getter is None:
continue
try:
processes.extend(getter(handle))
except Exception:
# Some driver/device combinations expose only one list.
continue
for process in processes:
used = getattr(process, "usedGpuMemory", 0)
if not isinstance(used, int) or used <= 0:
continue
key = (device_index, int(process.pid))
# A C+G process appears in both NVML lists for one device.
per_device_pid[key] = max(per_device_pid.get(key, 0), used)
except Exception as exc:
log.debug("Could not sample NVIDIA GPU memory: %s", exc)
return {}, {}
totals: dict[int, int] = {}
for (_device_index, pid), used in per_device_pid.items():
totals[pid] = totals.get(pid, 0) + used
return utilization, totals
def close(self):
if self._initialized and self._nvml is not None:
try:
self._nvml.nvmlShutdown()
except Exception:
pass
self._initialized = False