auto-optimize 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- auto_optimize/__init__.py +3 -0
- auto_optimize/__main__.py +5 -0
- auto_optimize/cli.py +651 -0
- auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
- auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
- auto_optimize/skills/auto-optimize-code/VERSION +1 -0
- auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
- auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
- auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
- auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
- auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
- auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
- auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
- auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
- auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
- auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
- auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
- auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
- auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
- auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
- auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
- auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
- auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
- auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
- auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
- auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
- auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
- auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
- auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
- auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
- auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
- auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
- auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
- auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
- auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
- auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
- auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
- auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
- auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
- auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
- auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
- auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
- auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
- auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
- auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
- auto_optimize-1.0.0.dist-info/METADATA +610 -0
- auto_optimize-1.0.0.dist-info/RECORD +67 -0
- auto_optimize-1.0.0.dist-info/WHEEL +4 -0
- auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
- auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
"""GPUs, host load, GPU lease holders and the processes that belong to a run.
|
|
2
|
+
|
|
3
|
+
The hardware half of a monitor's scanner, with no web dependencies. A
|
|
4
|
+
dashboard's `RunScanner` owns one `Hardware` and calls `resources()` on the
|
|
5
|
+
publisher's fast clock:
|
|
6
|
+
|
|
7
|
+
self.hardware = Hardware(root, classify=my_classify, target=my_target)
|
|
8
|
+
payload = self.hardware.resources() # -> resources.json
|
|
9
|
+
|
|
10
|
+
`classify(cmdline)` names what a process is doing ('training', 'design',
|
|
11
|
+
'scheduler', or 'other') and `target(cmdline, pid)` names the unit of work it
|
|
12
|
+
is on (a model, a design, a task id) or returns None; `pid` lets it read what
|
|
13
|
+
the command line does not show, such as a shell-redirected stdout
|
|
14
|
+
(`stdout_of(pid)`). Both are the only dashboard-specific parts.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import json
|
|
19
|
+
import stat
|
|
20
|
+
import time
|
|
21
|
+
import ctypes
|
|
22
|
+
import shutil
|
|
23
|
+
import socket
|
|
24
|
+
import hashlib
|
|
25
|
+
import tempfile
|
|
26
|
+
import threading
|
|
27
|
+
import subprocess
|
|
28
|
+
|
|
29
|
+
from collections import defaultdict, deque
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
import fcntl
|
|
33
|
+
except ImportError:
|
|
34
|
+
fcntl = None
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
import psutil
|
|
38
|
+
except ImportError:
|
|
39
|
+
psutil = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
SHELLS = ('bash', 'sh', 'zsh', 'dash', 'fish', 'ksh')
|
|
43
|
+
|
|
44
|
+
# The publisher's own processes mention the run directory on their command
|
|
45
|
+
# line, so they would otherwise count as part of the run: the writer, the
|
|
46
|
+
# scanner, and the mount script (`autoopt_monitor.py` here) while `--start`
|
|
47
|
+
# waits for the writer. Keep each entry equal to its script's file name.
|
|
48
|
+
SELF_MARKERS = ('monitor_writer.py', 'scan.py', 'autoopt_monitor.py')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _float(x):
|
|
52
|
+
try:
|
|
53
|
+
x = float(x)
|
|
54
|
+
except (TypeError, ValueError):
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
return None if x != x else x
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _int(x):
|
|
61
|
+
x = _float(x)
|
|
62
|
+
return None if x is None else int(x)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# Seconds one nvidia-smi call may take. Many calls at once on one host take
|
|
66
|
+
# over ten seconds each; a call cut short publishes no reading at all.
|
|
67
|
+
SMI_TIMEOUT = 30
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def nvidia_smi(query, mode='gpu'):
|
|
71
|
+
"""One nvidia-smi CSV query as a list of field lists: [] where there is
|
|
72
|
+
no nvidia-smi, None when the call failed or timed out."""
|
|
73
|
+
|
|
74
|
+
if shutil.which('nvidia-smi') is None:
|
|
75
|
+
return []
|
|
76
|
+
|
|
77
|
+
flag = '--query-gpu' if mode == 'gpu' else '--query-compute-apps'
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
out = subprocess.run(['nvidia-smi', '{}={}'.format(flag, query),
|
|
81
|
+
'--format=csv,noheader,nounits'], capture_output=True, text=True,
|
|
82
|
+
timeout=SMI_TIMEOUT)
|
|
83
|
+
except (subprocess.SubprocessError, OSError):
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
if out.returncode != 0:
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
return [[field.strip() for field in line.split(',')]
|
|
90
|
+
for line in out.stdout.strip().splitlines() if line.strip()]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def concurrently(*calls):
|
|
94
|
+
"""Each zero-argument call on its own thread; their results, in order,
|
|
95
|
+
None for one that raised. Daemon threads, not an executor: interpreter
|
|
96
|
+
exit joins an executor's workers, so a stopping writer would wait out an
|
|
97
|
+
nvidia-smi call it no longer needs."""
|
|
98
|
+
|
|
99
|
+
results = [None] * len(calls)
|
|
100
|
+
|
|
101
|
+
def work(index, call):
|
|
102
|
+
try:
|
|
103
|
+
results[index] = call()
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
threads = [threading.Thread(target=work, args=(index, call), daemon=True)
|
|
108
|
+
for index, call in enumerate(calls)]
|
|
109
|
+
|
|
110
|
+
for thread in threads:
|
|
111
|
+
thread.start()
|
|
112
|
+
for thread in threads:
|
|
113
|
+
thread.join()
|
|
114
|
+
|
|
115
|
+
return results
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def pmon():
|
|
119
|
+
"""Per-process SM and memory utilisation, `{pid: {'sm': %, 'mem': %}}`,
|
|
120
|
+
with the pid as a string so the result survives the shared cache's JSON;
|
|
121
|
+
{} where there is no nvidia-smi, None when the call failed.
|
|
122
|
+
|
|
123
|
+
`nvidia-smi pmon` samples for a full second, so callers hold the result.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
if shutil.which('nvidia-smi') is None:
|
|
127
|
+
return {}
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
out = subprocess.run(['nvidia-smi', 'pmon', '-c', '1'],
|
|
131
|
+
capture_output=True, text=True, timeout=SMI_TIMEOUT)
|
|
132
|
+
except (subprocess.SubprocessError, OSError):
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
if out.returncode != 0:
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
usage = {}
|
|
139
|
+
|
|
140
|
+
for line in out.stdout.splitlines():
|
|
141
|
+
if line.startswith('#') or not line.strip():
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
fields = line.split()
|
|
145
|
+
if len(fields) < 5 or not fields[1].isdigit():
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
usage[fields[1]] = {'sm': _float(fields[3]), 'mem': _float(fields[4])}
|
|
149
|
+
|
|
150
|
+
return usage
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# Each new nvidia-smi process stalls cudaMalloc in every CUDA process on the
|
|
154
|
+
# host while it starts, so the GPUs are read through one NVML session held for
|
|
155
|
+
# the publisher's life. nvidia-smi is the fallback where the library will not
|
|
156
|
+
# load; GPU_SCAN_NVML names another library file (a test's).
|
|
157
|
+
NVML_LIBRARY = 'libnvidia-ml.so.1'
|
|
158
|
+
|
|
159
|
+
# pmon's window: a process's utilisation is its latest sample in the last
|
|
160
|
+
# second.
|
|
161
|
+
PMON_WINDOW = 1.0
|
|
162
|
+
|
|
163
|
+
_OK, _NOT_FOUND, _TOO_SMALL = 0, 6, 7
|
|
164
|
+
_NOT_AVAILABLE = 2 ** 64 - 1
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _mib(size):
|
|
168
|
+
"""Bytes as MiB rounded up, as nvidia-smi rounds them."""
|
|
169
|
+
|
|
170
|
+
return -(-size // 2 ** 20)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class _Utilization(ctypes.Structure):
|
|
174
|
+
_fields_ = [('gpu', ctypes.c_uint), ('memory', ctypes.c_uint)]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _Memory(ctypes.Structure):
|
|
178
|
+
# nvmlMemory_v2_t: `used` leaves out what the driver reserves, as
|
|
179
|
+
# nvidia-smi's memory.used does.
|
|
180
|
+
_fields_ = [('version', ctypes.c_uint), ('total', ctypes.c_ulonglong),
|
|
181
|
+
('reserved', ctypes.c_ulonglong), ('free', ctypes.c_ulonglong),
|
|
182
|
+
('used', ctypes.c_ulonglong)]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class _Process(ctypes.Structure):
|
|
186
|
+
_fields_ = [('pid', ctypes.c_uint), ('used', ctypes.c_ulonglong),
|
|
187
|
+
('gpu_instance', ctypes.c_uint), ('compute_instance', ctypes.c_uint)]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class _Sample(ctypes.Structure):
|
|
191
|
+
_fields_ = [('pid', ctypes.c_uint), ('time', ctypes.c_ulonglong),
|
|
192
|
+
('sm', ctypes.c_uint), ('memory', ctypes.c_uint),
|
|
193
|
+
('encoder', ctypes.c_uint), ('decoder', ctypes.c_uint)]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class NVML:
|
|
197
|
+
"""The scanner's three GPU queries, answered by one NVML session.
|
|
198
|
+
|
|
199
|
+
Each returns what its nvidia-smi counterpart returns: rows, [] where
|
|
200
|
+
there are no GPUs, None when the library did not answer. A field a GPU
|
|
201
|
+
does not report is None, where nvidia-smi prints [N/A].
|
|
202
|
+
|
|
203
|
+
Reading the power limit holds every other process's cudaMalloc while it
|
|
204
|
+
runs, so it is read once per session.
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
SYMBOLS = ('nvmlInit_v2', 'nvmlShutdown', 'nvmlDeviceGetCount_v2',
|
|
208
|
+
'nvmlDeviceGetHandleByIndex_v2', 'nvmlDeviceGetUUID',
|
|
209
|
+
'nvmlDeviceGetName', 'nvmlDeviceGetUtilizationRates',
|
|
210
|
+
'nvmlDeviceGetMemoryInfo_v2', 'nvmlDeviceGetTemperature',
|
|
211
|
+
'nvmlDeviceGetPowerUsage', 'nvmlDeviceGetPowerManagementLimit',
|
|
212
|
+
'nvmlDeviceGetComputeRunningProcesses_v3',
|
|
213
|
+
'nvmlDeviceGetProcessUtilization')
|
|
214
|
+
|
|
215
|
+
def __init__(self, path):
|
|
216
|
+
self.lib = ctypes.CDLL(path)
|
|
217
|
+
for name in self.SYMBOLS:
|
|
218
|
+
getattr(self.lib, name)
|
|
219
|
+
|
|
220
|
+
self.lock = threading.Lock()
|
|
221
|
+
self.ready = False
|
|
222
|
+
self.limits = {}
|
|
223
|
+
|
|
224
|
+
def _devices(self):
|
|
225
|
+
"""`[(index, handle, uuid)]`, leaving out a GPU that does not answer;
|
|
226
|
+
None when NVML does not."""
|
|
227
|
+
|
|
228
|
+
lib = self.lib
|
|
229
|
+
|
|
230
|
+
# Opened again at the next sample after a failure: a session from
|
|
231
|
+
# before a driver reload would otherwise fail for the writer's life.
|
|
232
|
+
with self.lock:
|
|
233
|
+
if not self.ready:
|
|
234
|
+
self.ready = lib.nvmlInit_v2() == _OK
|
|
235
|
+
self.limits = {}
|
|
236
|
+
if not self.ready:
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
count = ctypes.c_uint()
|
|
240
|
+
if lib.nvmlDeviceGetCount_v2(ctypes.byref(count)) != _OK:
|
|
241
|
+
with self.lock:
|
|
242
|
+
if self.ready:
|
|
243
|
+
lib.nvmlShutdown()
|
|
244
|
+
self.ready = False
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
devices = []
|
|
248
|
+
|
|
249
|
+
for index in range(count.value):
|
|
250
|
+
handle, uuid = ctypes.c_void_p(), ctypes.create_string_buffer(96)
|
|
251
|
+
|
|
252
|
+
if lib.nvmlDeviceGetHandleByIndex_v2(index, ctypes.byref(handle)) \
|
|
253
|
+
== _OK and lib.nvmlDeviceGetUUID(handle, uuid, 96) == _OK:
|
|
254
|
+
devices.append((index, handle, uuid.value.decode()))
|
|
255
|
+
|
|
256
|
+
return devices
|
|
257
|
+
|
|
258
|
+
def gpus(self):
|
|
259
|
+
"""`--query-gpu` of index, uuid, name, utilization.gpu,
|
|
260
|
+
utilization.memory, memory.used, memory.total (MiB), temperature.gpu,
|
|
261
|
+
power.draw and power.limit (W)."""
|
|
262
|
+
|
|
263
|
+
devices = self._devices()
|
|
264
|
+
if devices is None:
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
lib, rows = self.lib, []
|
|
268
|
+
|
|
269
|
+
def read(call, *args):
|
|
270
|
+
return call(*args) == _OK
|
|
271
|
+
|
|
272
|
+
for index, handle, uuid in devices:
|
|
273
|
+
name = ctypes.create_string_buffer(96)
|
|
274
|
+
use = _Utilization()
|
|
275
|
+
memory = _Memory(version=ctypes.sizeof(_Memory) | 2 << 24)
|
|
276
|
+
temperature, power, limit = (ctypes.c_uint() for _ in range(3))
|
|
277
|
+
|
|
278
|
+
if uuid not in self.limits:
|
|
279
|
+
self.limits[uuid] = round(limit.value / 1000, 2) if read(
|
|
280
|
+
lib.nvmlDeviceGetPowerManagementLimit, handle,
|
|
281
|
+
ctypes.byref(limit)) else None
|
|
282
|
+
|
|
283
|
+
has_use = read(lib.nvmlDeviceGetUtilizationRates, handle,
|
|
284
|
+
ctypes.byref(use))
|
|
285
|
+
has_memory = read(lib.nvmlDeviceGetMemoryInfo_v2, handle,
|
|
286
|
+
ctypes.byref(memory))
|
|
287
|
+
|
|
288
|
+
rows.append([index, uuid,
|
|
289
|
+
name.value.decode() if read(lib.nvmlDeviceGetName, handle, name,
|
|
290
|
+
96) else None,
|
|
291
|
+
use.gpu if has_use else None,
|
|
292
|
+
use.memory if has_use else None,
|
|
293
|
+
_mib(memory.used) if has_memory else None,
|
|
294
|
+
_mib(memory.total) if has_memory else None,
|
|
295
|
+
temperature.value if read(lib.nvmlDeviceGetTemperature, handle, 0,
|
|
296
|
+
ctypes.byref(temperature)) else None,
|
|
297
|
+
round(power.value / 1000, 2) if read(lib.nvmlDeviceGetPowerUsage,
|
|
298
|
+
handle, ctypes.byref(power)) else None,
|
|
299
|
+
self.limits[uuid]])
|
|
300
|
+
|
|
301
|
+
return rows
|
|
302
|
+
|
|
303
|
+
def apps(self):
|
|
304
|
+
"""`--query-compute-apps` of gpu_uuid, pid and used_memory (MiB)."""
|
|
305
|
+
|
|
306
|
+
devices = self._devices()
|
|
307
|
+
if devices is None:
|
|
308
|
+
return None
|
|
309
|
+
|
|
310
|
+
rows = []
|
|
311
|
+
|
|
312
|
+
for index, handle, uuid in devices:
|
|
313
|
+
size = 64
|
|
314
|
+
|
|
315
|
+
while True:
|
|
316
|
+
count, found = ctypes.c_uint(size), (_Process * size)()
|
|
317
|
+
code = self.lib.nvmlDeviceGetComputeRunningProcesses_v3(handle,
|
|
318
|
+
ctypes.byref(count), found)
|
|
319
|
+
|
|
320
|
+
if code != _TOO_SMALL or size >= 4096:
|
|
321
|
+
break
|
|
322
|
+
size *= 4
|
|
323
|
+
|
|
324
|
+
if code != _OK:
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
rows.extend([uuid, process.pid, None if process.used == _NOT_AVAILABLE
|
|
328
|
+
else _mib(process.used)] for process in found[:count.value])
|
|
329
|
+
|
|
330
|
+
return rows
|
|
331
|
+
|
|
332
|
+
def usage(self):
|
|
333
|
+
"""`pmon`'s per-process SM and memory utilisation, `{pid: {'sm': %,
|
|
334
|
+
'mem': %}}`, from each process's latest sample in the last
|
|
335
|
+
PMON_WINDOW seconds."""
|
|
336
|
+
|
|
337
|
+
devices = self._devices()
|
|
338
|
+
if devices is None:
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
since = ctypes.c_ulonglong(int((time.time() - PMON_WINDOW) * 1e6))
|
|
342
|
+
latest = {}
|
|
343
|
+
|
|
344
|
+
for index, handle, uuid in devices:
|
|
345
|
+
count = ctypes.c_uint(0)
|
|
346
|
+
code = self.lib.nvmlDeviceGetProcessUtilization(handle, None,
|
|
347
|
+
ctypes.byref(count), since)
|
|
348
|
+
|
|
349
|
+
# NOT_FOUND: no sample in the window. Anything else: not supported.
|
|
350
|
+
if code not in (_OK, _TOO_SMALL) or count.value == 0:
|
|
351
|
+
continue
|
|
352
|
+
|
|
353
|
+
count = ctypes.c_uint(count.value + 16)
|
|
354
|
+
samples = (_Sample * count.value)()
|
|
355
|
+
if self.lib.nvmlDeviceGetProcessUtilization(handle, samples,
|
|
356
|
+
ctypes.byref(count), since) != _OK:
|
|
357
|
+
continue
|
|
358
|
+
|
|
359
|
+
for sample in samples[:count.value]:
|
|
360
|
+
key = str(sample.pid)
|
|
361
|
+
if key not in latest or sample.time > latest[key][0]:
|
|
362
|
+
latest[key] = (sample.time, {'sm': float(sample.sm),
|
|
363
|
+
'mem': float(sample.memory)})
|
|
364
|
+
|
|
365
|
+
return {pid: value for pid, (_, value) in latest.items()}
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
_nvml, _nvml_lock = None, threading.Lock()
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def nvml():
|
|
372
|
+
"""This process's NVML session, None where the library will not load."""
|
|
373
|
+
|
|
374
|
+
global _nvml
|
|
375
|
+
|
|
376
|
+
with _nvml_lock:
|
|
377
|
+
if _nvml is None:
|
|
378
|
+
try:
|
|
379
|
+
_nvml = NVML(os.environ.get('GPU_SCAN_NVML') or NVML_LIBRARY)
|
|
380
|
+
except (OSError, AttributeError):
|
|
381
|
+
_nvml = False
|
|
382
|
+
|
|
383
|
+
return _nvml or None
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
GPU_QUERY = ('index,uuid,name,utilization.gpu,utilization.memory,memory.used,'
|
|
387
|
+
'memory.total,temperature.gpu,power.draw,power.limit')
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def gpu_rows():
|
|
391
|
+
"""`--query-gpu` of GPU_QUERY's fields, one list per GPU."""
|
|
392
|
+
|
|
393
|
+
session = nvml()
|
|
394
|
+
return session.gpus() if session else nvidia_smi(GPU_QUERY)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def app_rows():
|
|
398
|
+
"""`--query-compute-apps` of gpu_uuid, pid and used_memory."""
|
|
399
|
+
|
|
400
|
+
session = nvml()
|
|
401
|
+
return session.apps() if session else nvidia_smi(
|
|
402
|
+
'gpu_uuid,pid,used_memory', mode='apps')
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
# Reading per-process utilisation holds every other process's cudaMalloc for
|
|
406
|
+
# as long as it runs, a few milliseconds per GPU, so all publishers together
|
|
407
|
+
# read it once a minute and show the last answer between.
|
|
408
|
+
USAGE_SECONDS = 60
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def process_usage():
|
|
412
|
+
"""`pmon`'s per-process utilisation, `{pid: {'sm': %, 'mem': %}}`."""
|
|
413
|
+
|
|
414
|
+
session = nvml()
|
|
415
|
+
return session.usage() if session else pmon()
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# How old a shared GPU answer may be before a publisher asks again; under the
|
|
419
|
+
# 3 s hardware clock, so each poll sees a new sample. An answer is dated when
|
|
420
|
+
# its call started, so a slow call does not look fresh at the next tick.
|
|
421
|
+
SHARED_SECONDS = 2.5
|
|
422
|
+
# How long a publisher waits for another's call before showing the last
|
|
423
|
+
# answer: long enough for a normal call, short of a stalled one.
|
|
424
|
+
SHARED_WAIT = 1.5
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def shared_dir():
|
|
428
|
+
"""This user's directory for what every publisher on the host shares:
|
|
429
|
+
/dev/shm where there is one, since locks on a network filesystem stall.
|
|
430
|
+
|
|
431
|
+
The name is predictable, so another user of the host can make it first
|
|
432
|
+
and plant symlinks that redirect these writes. A directory of that name
|
|
433
|
+
this user does not own, or that others may write to, is passed over for
|
|
434
|
+
one under ~/.cache."""
|
|
435
|
+
|
|
436
|
+
base = '/dev/shm' if os.access('/dev/shm', os.W_OK) else tempfile.gettempdir()
|
|
437
|
+
name = 'dashboard-monitor-{}'.format(os.getuid())
|
|
438
|
+
|
|
439
|
+
return own_dir([os.path.join(base, name),
|
|
440
|
+
os.path.join(os.path.expanduser('~'), '.cache', name)])
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def own_dir(paths):
|
|
444
|
+
"""The first of `paths`, made if missing, that is a directory (not a
|
|
445
|
+
symlink to one) this user owns and no one else may write to."""
|
|
446
|
+
|
|
447
|
+
for path in paths:
|
|
448
|
+
os.makedirs(path, mode=0o700, exist_ok=True)
|
|
449
|
+
info = os.lstat(path)
|
|
450
|
+
|
|
451
|
+
if (stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid()
|
|
452
|
+
and not info.st_mode & 0o022):
|
|
453
|
+
return path
|
|
454
|
+
|
|
455
|
+
raise OSError('none of {} is a directory this user alone can write '
|
|
456
|
+
'to'.format(', '.join(paths)))
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _read_sample(path):
|
|
460
|
+
try:
|
|
461
|
+
with open(path) as infile:
|
|
462
|
+
sample = json.load(infile)
|
|
463
|
+
except (OSError, ValueError):
|
|
464
|
+
return None
|
|
465
|
+
|
|
466
|
+
return sample if isinstance(sample, dict) and 'at' in sample else None
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def shared_sample(key, seconds, compute):
|
|
470
|
+
"""`(value, sampled_at)` of `compute()`, run at most once per `seconds` by
|
|
471
|
+
all of this user's publishers on the host together, or `(None, None)`
|
|
472
|
+
before any call has succeeded.
|
|
473
|
+
|
|
474
|
+
The GPU queries answer for the whole host, so every dashboard asks the same
|
|
475
|
+
question. Asked separately, a dozen publishers keep forty calls in
|
|
476
|
+
flight and each takes longer than the poll. One publisher refreshes the
|
|
477
|
+
answer under a lock while the rest read the last one. A failed call
|
|
478
|
+
(None) leaves the last good answer in place, so a slow query makes
|
|
479
|
+
the reading older, never absent.
|
|
480
|
+
"""
|
|
481
|
+
|
|
482
|
+
if fcntl is None:
|
|
483
|
+
value = compute()
|
|
484
|
+
return (value, time.time()) if value is not None else (None, None)
|
|
485
|
+
|
|
486
|
+
# Keyed by the executable too: a test's stub on PATH must not hand its
|
|
487
|
+
# made-up GPUs to the real publishers, nor read theirs.
|
|
488
|
+
directory = shared_dir()
|
|
489
|
+
key += '-' + hashlib.sha1(str(shutil.which('nvidia-smi')).encode()).hexdigest()[:8]
|
|
490
|
+
path = os.path.join(directory, key + '.json')
|
|
491
|
+
sample = _read_sample(path)
|
|
492
|
+
|
|
493
|
+
if sample is not None and time.time() - sample['at'] < seconds:
|
|
494
|
+
return sample['value'], sample['at']
|
|
495
|
+
|
|
496
|
+
with open(os.path.join(directory, key + '.lock'), 'a') as lock:
|
|
497
|
+
# Someone else is asking: their answer if it lands within
|
|
498
|
+
# SHARED_WAIT, the last one otherwise. With no answer yet there is
|
|
499
|
+
# nothing to show, so wait for it.
|
|
500
|
+
taken = _take(lock, SHARED_WAIT if sample else None)
|
|
501
|
+
latest = _read_sample(path) or sample
|
|
502
|
+
|
|
503
|
+
# An answer that landed while this one waited is used whatever its
|
|
504
|
+
# age: a call slower than `seconds` would otherwise be repeated by
|
|
505
|
+
# every publisher that waited on it.
|
|
506
|
+
if not taken or (latest is not None and (time.time() - latest['at']
|
|
507
|
+
< seconds or sample is None or latest['at'] != sample['at'])):
|
|
508
|
+
return latest['value'], latest['at']
|
|
509
|
+
|
|
510
|
+
sample = latest
|
|
511
|
+
|
|
512
|
+
at = time.time()
|
|
513
|
+
value = compute()
|
|
514
|
+
|
|
515
|
+
if value is None:
|
|
516
|
+
return (sample['value'], sample['at']) if sample else (None, None)
|
|
517
|
+
|
|
518
|
+
tmp = '{}.{}-{}.tmp'.format(path, os.getpid(), threading.get_ident())
|
|
519
|
+
with open(tmp, 'w') as out:
|
|
520
|
+
json.dump({'at': at, 'value': value}, out)
|
|
521
|
+
os.replace(tmp, path)
|
|
522
|
+
|
|
523
|
+
return value, at
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _take(lock, timeout):
|
|
527
|
+
"""Lock `lock`, waiting at most `timeout` seconds (None: as long as it
|
|
528
|
+
takes). Whether it was taken."""
|
|
529
|
+
|
|
530
|
+
if timeout is None:
|
|
531
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
532
|
+
return True
|
|
533
|
+
|
|
534
|
+
deadline = time.time() + timeout
|
|
535
|
+
|
|
536
|
+
while True:
|
|
537
|
+
try:
|
|
538
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
539
|
+
return True
|
|
540
|
+
except BlockingIOError:
|
|
541
|
+
if time.time() >= deadline:
|
|
542
|
+
return False
|
|
543
|
+
time.sleep(0.05)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def leases(directory=None):
|
|
547
|
+
"""Live GPU lease holders, `{index: {user, note, pid, acquired_at}}`.
|
|
548
|
+
|
|
549
|
+
Optional: read only when `GPU_LEASE_DIR` (or `directory`) names a
|
|
550
|
+
directory written by a lease tool, one `gpu<index>.json` per held GPU
|
|
551
|
+
with any of `gpu`, `user`, `note` (or `cmd`), `pid`, `acquired_at` and
|
|
552
|
+
`expires_at` (epoch seconds). A lease counts while its pid is alive and
|
|
553
|
+
its expiry has not passed. The files are read, never reaped. No
|
|
554
|
+
directory means no information, not an error.
|
|
555
|
+
"""
|
|
556
|
+
|
|
557
|
+
directory = directory or os.environ.get('GPU_LEASE_DIR')
|
|
558
|
+
if not directory:
|
|
559
|
+
return {}
|
|
560
|
+
directory = os.path.expanduser(directory)
|
|
561
|
+
out = {}
|
|
562
|
+
|
|
563
|
+
try:
|
|
564
|
+
names = os.listdir(directory)
|
|
565
|
+
except OSError:
|
|
566
|
+
return out
|
|
567
|
+
|
|
568
|
+
for name in names:
|
|
569
|
+
if not (name.startswith('gpu') and name.endswith('.json')):
|
|
570
|
+
continue
|
|
571
|
+
|
|
572
|
+
try:
|
|
573
|
+
with open(os.path.join(directory, name)) as infile:
|
|
574
|
+
lease = json.load(infile)
|
|
575
|
+
except (OSError, ValueError):
|
|
576
|
+
continue
|
|
577
|
+
|
|
578
|
+
# A lease tool's file, not ours: anything of the wrong shape is
|
|
579
|
+
# skipped rather than allowed to stop the hardware sample.
|
|
580
|
+
number = lambda x: isinstance(x, (int, float)) \
|
|
581
|
+
and not isinstance(x, bool)
|
|
582
|
+
|
|
583
|
+
if not isinstance(lease, dict):
|
|
584
|
+
continue
|
|
585
|
+
|
|
586
|
+
pid, expires = lease.get('pid'), lease.get('expires_at')
|
|
587
|
+
index = lease.get('gpu', _int(name[3:-5]))
|
|
588
|
+
|
|
589
|
+
if not (pid is None or (isinstance(pid, int) and pid > 0)) \
|
|
590
|
+
or not (expires is None or number(expires)) \
|
|
591
|
+
or not (isinstance(index, int) and not isinstance(index, bool)):
|
|
592
|
+
continue
|
|
593
|
+
|
|
594
|
+
if expires is not None and time.time() > expires:
|
|
595
|
+
continue
|
|
596
|
+
|
|
597
|
+
if pid is not None:
|
|
598
|
+
try:
|
|
599
|
+
os.kill(pid, 0)
|
|
600
|
+
except ProcessLookupError:
|
|
601
|
+
continue
|
|
602
|
+
except OSError:
|
|
603
|
+
pass
|
|
604
|
+
|
|
605
|
+
out[index] = {'user': lease.get('user'),
|
|
606
|
+
'note': lease.get('note') or lease.get('cmd'),
|
|
607
|
+
'pid': pid, 'acquired_at': lease.get('acquired_at')}
|
|
608
|
+
|
|
609
|
+
return out
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def stdout_of(pid):
|
|
613
|
+
"""Where a process's stdout goes (`/proc/<pid>/fd/1`), or None. A job
|
|
614
|
+
started as `python train.py > logs/m3.log` names its unit of work only
|
|
615
|
+
there."""
|
|
616
|
+
|
|
617
|
+
if pid is None:
|
|
618
|
+
return None
|
|
619
|
+
|
|
620
|
+
try:
|
|
621
|
+
return os.readlink('/proc/{}/fd/1'.format(pid))
|
|
622
|
+
except OSError:
|
|
623
|
+
return None
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def is_job(argv):
|
|
627
|
+
"""True for a command doing work, not an interactive shell.
|
|
628
|
+
|
|
629
|
+
Matching on the working directory alone sweeps up any shell someone has
|
|
630
|
+
cd'd into the run; a shell only counts when it is running a script.
|
|
631
|
+
"""
|
|
632
|
+
|
|
633
|
+
if not argv:
|
|
634
|
+
return False
|
|
635
|
+
|
|
636
|
+
if os.path.basename(argv[0]) not in SHELLS:
|
|
637
|
+
return True
|
|
638
|
+
|
|
639
|
+
return len(argv) > 1 and not argv[1].startswith('-')
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
class Hardware:
|
|
643
|
+
"""GPU, host and process state for one run directory.
|
|
644
|
+
|
|
645
|
+
Parameters
|
|
646
|
+
----------
|
|
647
|
+
root: str
|
|
648
|
+
The run directory. A process belongs to the run when its command line
|
|
649
|
+
names it or its working directory is inside it.
|
|
650
|
+
|
|
651
|
+
classify: callable
|
|
652
|
+
`classify(cmdline) -> str`, what a process is doing. 'scheduler' is
|
|
653
|
+
special: workers are never folded into a scheduler.
|
|
654
|
+
|
|
655
|
+
target: callable
|
|
656
|
+
`target(cmdline, pid) -> str or None`, the unit of work a process
|
|
657
|
+
is on.
|
|
658
|
+
|
|
659
|
+
history: int
|
|
660
|
+
Samples kept for the sparklines.
|
|
661
|
+
"""
|
|
662
|
+
|
|
663
|
+
def __init__(self, root, classify=None, target=None, history=180):
|
|
664
|
+
self.root = os.path.abspath(os.path.expanduser(root))
|
|
665
|
+
self.classify = classify or (lambda cmdline: 'other')
|
|
666
|
+
self.target = target or (lambda cmdline, pid: None)
|
|
667
|
+
self.history = deque(maxlen=history)
|
|
668
|
+
|
|
669
|
+
self.process_cache = {}
|
|
670
|
+
self.process_ttl = 2.0
|
|
671
|
+
self._processes = (0.0, [])
|
|
672
|
+
self._ttl = {}
|
|
673
|
+
self.gpu_sampled_at = None
|
|
674
|
+
self._history_at = None
|
|
675
|
+
self._history_last = 0.0
|
|
676
|
+
|
|
677
|
+
# Set by the writer while a page asks for live cards. NVML answers in
|
|
678
|
+
# about a tenth of a millisecond, so with it a live sample skips the
|
|
679
|
+
# shared cache; without it the shared nvidia-smi cache stays, since
|
|
680
|
+
# every call there costs the host hundreds of milliseconds. Per-process
|
|
681
|
+
# utilisation stays on its own 60 s clock either way.
|
|
682
|
+
self.live = False
|
|
683
|
+
|
|
684
|
+
# The least seconds between history points; the writer sets it just
|
|
685
|
+
# under its own clock, so live samples move the cards and not the
|
|
686
|
+
# sparkline's span.
|
|
687
|
+
self.history_gap = 0.0
|
|
688
|
+
|
|
689
|
+
def _hold(self, key, seconds, compute):
|
|
690
|
+
"""A value recomputed at most every `seconds`, so several callers in one
|
|
691
|
+
poll do not repeat an expensive query."""
|
|
692
|
+
|
|
693
|
+
when, value = self._ttl.get(key, (0.0, None))
|
|
694
|
+
|
|
695
|
+
if time.time() - when < seconds:
|
|
696
|
+
return value
|
|
697
|
+
|
|
698
|
+
value = compute()
|
|
699
|
+
self._ttl[key] = (time.time(), value)
|
|
700
|
+
|
|
701
|
+
return value
|
|
702
|
+
|
|
703
|
+
def processes(self):
|
|
704
|
+
"""Every process whose command line or cwd names the run.
|
|
705
|
+
|
|
706
|
+
Workers are folded into the job that owns them, so the table has one
|
|
707
|
+
row per job rather than one per dataloader: each record carries `tree`
|
|
708
|
+
(summed CPU, RSS and worker count) and `is_root`.
|
|
709
|
+
"""
|
|
710
|
+
|
|
711
|
+
if psutil is None:
|
|
712
|
+
return []
|
|
713
|
+
|
|
714
|
+
when, cached = self._processes
|
|
715
|
+
|
|
716
|
+
if time.time() - when < self.process_ttl:
|
|
717
|
+
return cached
|
|
718
|
+
|
|
719
|
+
fields = ['pid', 'ppid', 'name', 'cmdline', 'create_time',
|
|
720
|
+
'memory_info', 'cwd', 'num_threads', 'status']
|
|
721
|
+
found, seen, mine = {}, set(), {os.getpid()}
|
|
722
|
+
|
|
723
|
+
for proc in psutil.process_iter(fields):
|
|
724
|
+
try:
|
|
725
|
+
info = proc.info
|
|
726
|
+
argv = info.get('cmdline') or []
|
|
727
|
+
cmdline = ' '.join(argv)
|
|
728
|
+
cwd = info.get('cwd') or ''
|
|
729
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
730
|
+
continue
|
|
731
|
+
|
|
732
|
+
if not cmdline:
|
|
733
|
+
continue
|
|
734
|
+
|
|
735
|
+
pid = info['pid']
|
|
736
|
+
|
|
737
|
+
if pid in mine or info.get('ppid') in mine:
|
|
738
|
+
mine.add(pid)
|
|
739
|
+
continue
|
|
740
|
+
|
|
741
|
+
if any(marker in cmdline for marker in SELF_MARKERS):
|
|
742
|
+
continue
|
|
743
|
+
|
|
744
|
+
if not is_job(argv):
|
|
745
|
+
continue
|
|
746
|
+
|
|
747
|
+
if not (self.root in cmdline or cwd == self.root
|
|
748
|
+
or cwd.startswith(self.root + os.sep)):
|
|
749
|
+
continue
|
|
750
|
+
|
|
751
|
+
seen.add(pid)
|
|
752
|
+
|
|
753
|
+
# cpu_percent is measured since the previous call on the same
|
|
754
|
+
# Process object, so the object is kept between scans.
|
|
755
|
+
handle = self.process_cache.get(pid)
|
|
756
|
+
if handle is None:
|
|
757
|
+
handle = self.process_cache[pid] = proc
|
|
758
|
+
|
|
759
|
+
try:
|
|
760
|
+
cpu = handle.cpu_percent()
|
|
761
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
762
|
+
cpu = None
|
|
763
|
+
|
|
764
|
+
memory = info.get('memory_info')
|
|
765
|
+
|
|
766
|
+
found[pid] = {
|
|
767
|
+
'pid': pid, 'ppid': info.get('ppid'),
|
|
768
|
+
'name': info.get('name'), 'cmdline': cmdline,
|
|
769
|
+
'threads': info.get('num_threads'),
|
|
770
|
+
'cpu_percent': cpu, 'rss': getattr(memory, 'rss', None),
|
|
771
|
+
'elapsed': time.time() - (info.get('create_time')
|
|
772
|
+
or time.time()),
|
|
773
|
+
'kind': self.classify(cmdline),
|
|
774
|
+
'target': self.target(cmdline, pid),
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
for pid in [p for p in self.process_cache if p not in seen]:
|
|
778
|
+
del self.process_cache[pid]
|
|
779
|
+
|
|
780
|
+
# Roll workers up into the process that owns the same job. Grouping on
|
|
781
|
+
# the job, not the whole process tree, keeps a scheduler from
|
|
782
|
+
# swallowing every job it launched.
|
|
783
|
+
for record in found.values():
|
|
784
|
+
root, ppid = record['pid'], record['ppid']
|
|
785
|
+
|
|
786
|
+
while ppid in found and found[ppid]['kind'] != 'scheduler':
|
|
787
|
+
parent = found[ppid]
|
|
788
|
+
|
|
789
|
+
if record['target'] is not None \
|
|
790
|
+
and parent['target'] not in (None, record['target']):
|
|
791
|
+
break
|
|
792
|
+
|
|
793
|
+
root, ppid = ppid, parent['ppid']
|
|
794
|
+
|
|
795
|
+
record['root_pid'] = root
|
|
796
|
+
|
|
797
|
+
totals = defaultdict(lambda: {'cpu_percent': 0.0, 'rss': 0,
|
|
798
|
+
'workers': 0})
|
|
799
|
+
kinds, targets = {}, {}
|
|
800
|
+
|
|
801
|
+
for record in found.values():
|
|
802
|
+
total = totals[record['root_pid']]
|
|
803
|
+
total['cpu_percent'] += record['cpu_percent'] or 0.0
|
|
804
|
+
total['rss'] += record['rss'] or 0
|
|
805
|
+
total['workers'] += 1
|
|
806
|
+
|
|
807
|
+
# A wrapper shell says nothing about what it wraps; the work
|
|
808
|
+
# underneath names the group.
|
|
809
|
+
if record['kind'] != 'other':
|
|
810
|
+
kinds.setdefault(record['root_pid'], record['kind'])
|
|
811
|
+
if record['target'] is not None:
|
|
812
|
+
targets.setdefault(record['root_pid'], record['target'])
|
|
813
|
+
|
|
814
|
+
for record in found.values():
|
|
815
|
+
root = record['root_pid']
|
|
816
|
+
record['tree'] = dict(totals[root])
|
|
817
|
+
record['is_root'] = root == record['pid']
|
|
818
|
+
|
|
819
|
+
if record['is_root']:
|
|
820
|
+
record['kind'] = kinds.get(root, record['kind'])
|
|
821
|
+
record['target'] = record['target'] or targets.get(root)
|
|
822
|
+
|
|
823
|
+
records = sorted(found.values(), key=lambda r: r['pid'])
|
|
824
|
+
self._processes = (time.time(), records)
|
|
825
|
+
|
|
826
|
+
return records
|
|
827
|
+
|
|
828
|
+
def gpus(self):
|
|
829
|
+
"""Per-GPU state with this run's processes and any lease attached.
|
|
830
|
+
|
|
831
|
+
`state` is 'ours' when a process of this run is on it, 'leased' when a
|
|
832
|
+
live lease holds it and none of ours is, 'busy' when another job
|
|
833
|
+
is on it, and 'free' otherwise.
|
|
834
|
+
"""
|
|
835
|
+
|
|
836
|
+
# Side by side: through nvidia-smi, on a busy 8-GPU host each query
|
|
837
|
+
# takes seconds, and `pmon` samples for one more.
|
|
838
|
+
if self.live and nvml():
|
|
839
|
+
at = time.time()
|
|
840
|
+
rows, apps, self.gpu_sampled_at = gpu_rows(), app_rows(), at
|
|
841
|
+
usage = shared_sample('pmon', USAGE_SECONDS, process_usage)[0]
|
|
842
|
+
else:
|
|
843
|
+
(rows, self.gpu_sampled_at), (apps, _), (usage, _) = (
|
|
844
|
+
result or (None, None) for result in concurrently(
|
|
845
|
+
lambda: shared_sample('smi', SHARED_SECONDS, gpu_rows),
|
|
846
|
+
lambda: shared_sample('apps', SHARED_SECONDS, app_rows),
|
|
847
|
+
lambda: shared_sample('pmon', USAGE_SECONDS, process_usage)))
|
|
848
|
+
rows, apps, usage = rows or [], apps or [], usage or {}
|
|
849
|
+
|
|
850
|
+
gpus, by_uuid = [], {}
|
|
851
|
+
|
|
852
|
+
for row in rows:
|
|
853
|
+
if len(row) < 10:
|
|
854
|
+
continue
|
|
855
|
+
|
|
856
|
+
gpu = {
|
|
857
|
+
'index': _int(row[0]), 'uuid': row[1], 'name': row[2],
|
|
858
|
+
'utilization': _float(row[3]),
|
|
859
|
+
'memory_utilization': _float(row[4]),
|
|
860
|
+
'memory_used': _float(row[5]), 'memory_total': _float(row[6]),
|
|
861
|
+
'temperature': _float(row[7]), 'power': _float(row[8]),
|
|
862
|
+
'power_limit': _float(row[9]), 'processes': [],
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
gpus.append(gpu)
|
|
866
|
+
by_uuid[row[1]] = gpu
|
|
867
|
+
|
|
868
|
+
ours = {record['pid']: record for record in self.processes()}
|
|
869
|
+
held = self._hold('leases', 2.0, leases)
|
|
870
|
+
|
|
871
|
+
for row in apps:
|
|
872
|
+
if len(row) < 3 or row[0] not in by_uuid:
|
|
873
|
+
continue
|
|
874
|
+
|
|
875
|
+
pid = _int(row[1])
|
|
876
|
+
record = ours.get(pid)
|
|
877
|
+
|
|
878
|
+
by_uuid[row[0]]['processes'].append({
|
|
879
|
+
'pid': pid, 'mine': record is not None,
|
|
880
|
+
'gpu_memory': _float(row[2]),
|
|
881
|
+
'sm': (usage.get(str(pid)) or {}).get('sm'),
|
|
882
|
+
'kind': record['kind'] if record else None,
|
|
883
|
+
'target': record['target'] if record else None,
|
|
884
|
+
'cpu_percent': record['tree']['cpu_percent'] if record else None,
|
|
885
|
+
'rss': record['tree']['rss'] if record else None,
|
|
886
|
+
'workers': record['tree']['workers'] if record else None,
|
|
887
|
+
'elapsed': record['elapsed'] if record else None,
|
|
888
|
+
})
|
|
889
|
+
|
|
890
|
+
for gpu in gpus:
|
|
891
|
+
gpu['mine'] = any(p['mine'] for p in gpu['processes'])
|
|
892
|
+
gpu['lease'] = held.get(gpu['index'])
|
|
893
|
+
gpu['state'] = ('ours' if gpu['mine']
|
|
894
|
+
else 'leased' if gpu['lease']
|
|
895
|
+
else 'busy' if gpu['processes'] else 'free')
|
|
896
|
+
|
|
897
|
+
return gpus
|
|
898
|
+
|
|
899
|
+
def host(self):
|
|
900
|
+
if psutil is None:
|
|
901
|
+
return {}
|
|
902
|
+
|
|
903
|
+
memory = psutil.virtual_memory()
|
|
904
|
+
# The busy share since the last sample, from /proc/stat's idle
|
|
905
|
+
# ticks: what says how much of the machine is free. The load
|
|
906
|
+
# average counts threads another job's CPU quota holds back, and
|
|
907
|
+
# reads in the hundreds on an idle shared machine; it stays in the
|
|
908
|
+
# payload only for pages that still print it.
|
|
909
|
+
busy, count = psutil.cpu_percent(), psutil.cpu_count() or 1
|
|
910
|
+
|
|
911
|
+
return {'cpu_percent': busy, 'cpu_count': count,
|
|
912
|
+
'idle_percent': round(100.0 - busy, 1),
|
|
913
|
+
'cores_free': int(count * (100.0 - busy) / 100.0),
|
|
914
|
+
'load': list(os.getloadavg()),
|
|
915
|
+
'memory_used': memory.used, 'memory_total': memory.total,
|
|
916
|
+
'memory_percent': memory.percent}
|
|
917
|
+
|
|
918
|
+
def resources(self, sample=True):
|
|
919
|
+
"""The `resources.json` payload, appending one history sample.
|
|
920
|
+
|
|
921
|
+
`history` is per-sample records rather than one series per GPU, so a
|
|
922
|
+
memory or host-CPU sparkline can be added without a payload change.
|
|
923
|
+
"""
|
|
924
|
+
|
|
925
|
+
# `psutil` False says why the host summary and the process table
|
|
926
|
+
# are empty, rather than leaving an idle-looking search.
|
|
927
|
+
# `gpu_sampled_at` is when the last GPU query that answered
|
|
928
|
+
# started, which is older than `timestamp` while it is slow or failing.
|
|
929
|
+
state = {'timestamp': time.time(), 'gpus': self.gpus(),
|
|
930
|
+
'gpu_sampled_at': self.gpu_sampled_at,
|
|
931
|
+
'hostname': socket.gethostname(),
|
|
932
|
+
'host': self.host(), 'psutil': psutil is not None,
|
|
933
|
+
'processes': [p for p in self.processes() if p['is_root']]}
|
|
934
|
+
|
|
935
|
+
if sample:
|
|
936
|
+
# A reading already in the history is not repeated, or a stalled
|
|
937
|
+
# query would draw a flat line that looks like a steady GPU.
|
|
938
|
+
now = state['timestamp']
|
|
939
|
+
fresh = state['gpus'] if self.gpu_sampled_at != self._history_at else []
|
|
940
|
+
self._history_at = self.gpu_sampled_at
|
|
941
|
+
|
|
942
|
+
if now - self._history_last >= self.history_gap:
|
|
943
|
+
self._history_last = now
|
|
944
|
+
self.history.append({
|
|
945
|
+
'timestamp': now,
|
|
946
|
+
'gpu': {g['index']: g['utilization'] for g in fresh},
|
|
947
|
+
'gpu_memory': {g['index']: g['memory_used'] for g in fresh},
|
|
948
|
+
'cpu': state['host'].get('cpu_percent'),
|
|
949
|
+
'memory': state['host'].get('memory_percent'),
|
|
950
|
+
})
|
|
951
|
+
|
|
952
|
+
state['history'] = list(self.history)
|
|
953
|
+
|
|
954
|
+
return state
|