Repository navigation
Expand file tree
/
Copy pathmultirun.py
More file actions
executable file
·2350 lines (2094 loc) · 101 KB
/
Copy pathmultirun.py
File metadata and controls
executable file
·2350 lines (2094 loc) · 101 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
import sys
import os
# check that CMSSW_BASE is set
if not 'CMSSW_BASE' in os.environ:
sys.stderr.write('Error: the CMS environment is not set up, please run "cmsenv" or "eval `scram runtime -sh`".\n')
sys.exit(1)
import copy
import glob
import itertools
import math
import psutil
import re
import shutil
import signal
import subprocess
import tempfile
import threading
import time
from collections import defaultdict, namedtuple
from datetime import datetime
from enum import Enum
# silence NumPy warnings about denormals
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import numpy as np
from scipy import stats
warnings.filterwarnings("default", category=UserWarning)
# yappi is an optional dependency, used to profile this script itself
try:
import yappi
yappi.set_clock_type("cpu")
except:
pass
# CMSSW python language
import FWCore.ParameterSet.Config as cms
# local packages
from common import loadModuleFromFile
from options import logdir_placeholders
from cpuinfo import *
from gpuinfo import *
from slot import Slot
from threaded import threaded
cpus = get_cpu_info()
gpus_nv = get_gpu_info_nvidia()
gpus_amd = get_gpu_info_amd()
# Define whether to monitor the host CPU and memory usage of each process, and with how much detail:
# - NONE disables all host process monitoring;
# - BASIC monitors the CPU utilization, virtual memory size (VSS), and resident memory size (RSS);
# - FULL in addition monitors the unique memory size (USS) and the proportional memory size (PSS).
class HostMonitorInfo(Enum):
NONE = 0
BASIC = 1
FULL = 2
monitoring = HostMonitorInfo.BASIC
# Define whether and how much detail to monitor for the GPUs (device-level, via nvidia-smi):
# - NONE disable GPU monitoring;
# - BASIC monitors the device utilization (%) and memory used (MiB);
# - FULL in addition monitors the power draw (W) and temperature (C).
class GpuMonitorInfo(Enum):
NONE = 0
BASIC = 1
FULL = 2
# Configure how to merge different files
# 'inputs' can be
# - 'stdin' to concatenate all inputs and pass them as standard input (NOT IMPLEMENTED), e.g.
# cat in1 in2 in3 ... | command ...
#
# - 'arg' to pass all inputs as arguments, e.g.
# command in1 in2 in3 ...
#
# - 'option' to pass all inputs as arguments after a single option, e.g.
# command -i in1 in2 in3 ...
#
# - 'multi' to pass all inputs as arguments to individual options, e.g.
# command -i in1 -i in2 -i in3 ...
#
# For 'option' and 'multi' the option is given in the "inputs_option" field.
#
# 'output' can be
# - 'stdout' to write the combined output to the standard output of the command, e.g.
# command ... > output
#
# - 'arg' to write the combined output to the (last) argument to the command, e.g.
# command ... output
#
# - 'option' to write the combined output to the argument to the given option, e.g.
# command ... -o output
#
# For 'option' the option is given in the "output_option" field.
auto_merge_map = {
'resources.json': {
'cmd': 'mergeResourcesJson.py',
'args': [],
'inputs': 'args',
'inputs_options': None,
'output': 'stdout',
'output_options': None,
}
}
def fasttimerservice_json(process):
# the name of the JSON file written by the configuration's FastTimerService (e.g. "resources.json"
# or "Phase2Timing_resources.json"), or None if the configuration does not write one
if 'FastTimerService' not in process.__dict__:
return None
service = process.FastTimerService
if not (hasattr(service, 'writeJSONSummary') and service.writeJSONSummary.value()):
return None
return service.jsonFileName.value() if hasattr(service, 'jsonFileName') else 'resources.json'
def auto_merge_entry(tag, resources_json = None):
# return the auto-merge configuration for a --keep entry, or None if it is not supported. The JSON
# file written by the configuration's FastTimerService (resources_json, see fasttimerservice_json)
# has the format of resources.json, so it is merged the same way whatever its name.
if tag in auto_merge_map:
return auto_merge_map[tag]
if resources_json is not None and tag == resources_json:
return auto_merge_map['resources.json']
return None
def runMergeCommand(entry, workdir, inputs, output, verbose):
if entry is None:
return
# do not run the merge command if there are no input files
if not inputs:
return
cmd = entry['cmd']
args = entry['args']
ins = entry['inputs']
out = entry['output']
exec = shutil.which(cmd)
if exec:
command = [ exec ]
else:
raise RuntimeError(f'cannot find command {cmd} .')
if args:
command.extend(args)
stdin = None
if ins == 'stdin':
# FIXME does it make sense to pass multiple inputs as stdin ?
raise NotImplementedError(f'auto merge command {tag} uses input through stdin, which is not supported')
sys.exit(1)
elif ins == 'args':
command.extend(inputs)
elif ins == 'option':
opt = entry['inputs_options']
command.append(opt)
command.extend(inputs)
elif ins == 'multi':
opt = entry['inputs_options']
for i in inputs:
command.extend((opt, i))
else:
raise NotImplementedError(f'auto merge command for {tag} uses an unknown input schema {ins}.')
stdout = None
if out == 'stdout':
stdout = open(output, 'w')
elif out == 'arg':
command.append(output)
elif out == 'option':
opt = entry['output_options']
command.append(opt)
command.append(output)
else:
raise NotImplementedError(f'auto merge command for {tag} uses an unknown output schema {out}.')
cmdline = ' '.join(command)
if verbose:
sys.stdout.write(cmdline + '\n')
sys.stdout.flush()
pipe = subprocess.run(command, stdin = stdin, stdout = stdout, stderr = subprocess.PIPE)
if stdout is not None:
stdout.close()
if pipe.returncode != 0:
raise RuntimeError(f'Exit code {pipe.returncode} while running "' + cmdline + '"\n\n' + pipe.stderr.decode(sys.stdout.encoding))
# ---------------------------------------------------------------------------
# Unified device-level CPU + GPU resource monitoring.
# The GPU sampling is abstracted behind a "backend" (NVIDIA via nvidia-smi or
# AMD via amd-smi), selected automatically; everything else is vendor-neutral.
# ---------------------------------------------------------------------------
def _to_number(value, conv):
# convert a string to int/float, returning 0 on any non-numeric value (e.g. "N/A")
try:
return conv(value)
except Exception:
return conv(0)
def _run_smi(exe_name, args, timeout = 10.):
# run a vendor SMI query (nvidia-smi / amd-smi) and return its standard output, or None on any
# error (tool missing, non-zero exit, timeout, ...)
exe = shutil.which(exe_name)
if not exe:
return None
try:
result = subprocess.run([exe] + args, stdout = subprocess.PIPE, stderr = subprocess.DEVNULL, text = True, timeout = timeout)
except Exception:
return None
if result.returncode != 0:
return None
return result.stdout
def _run_nvidia_smi(args, timeout = 10.):
return _run_smi('nvidia-smi', args, timeout)
def detect_nvidia_monitor_devices():
# return the sorted list of all physical NVIDIA device indices, or [] if nvidia-smi is unavailable
out = _run_nvidia_smi(['--query-gpu=index', '--format=csv,noheader,nounits'])
if out is None:
return []
devices = []
for line in out.splitlines():
line = line.strip()
if line.isdigit():
devices.append(int(line))
return sorted(devices)
_index_uuid_cache = None
def _nvidia_index_uuid():
# return a dict mapping each device index to its UUID. The mapping is fixed for the life of the
# process, so cache it (_nvidia_busy_devices() would otherwise re-query nvidia-smi every tick) -
# but only cache a SUCCESSFUL (non-empty) result, so a transient nvidia-smi failure is retried
# rather than frozen as empty for the whole process.
global _index_uuid_cache
if _index_uuid_cache:
return _index_uuid_cache
out = _run_nvidia_smi(['--query-gpu=index,uuid', '--format=csv,noheader,nounits'])
mapping = {}
if out is None:
return mapping
for line in out.splitlines():
parts = [ p.strip() for p in line.split(',') ]
if len(parts) >= 2 and parts[0].isdigit():
mapping[int(parts[0])] = parts[1]
if mapping:
_index_uuid_cache = mapping
return mapping
def _nvidia_busy_devices(devices):
# return the set of device indices (within `devices`) that currently have a running
# compute process, by intersecting the compute-apps UUIDs with the index->UUID map
out = _run_nvidia_smi(['--query-compute-apps=gpu_uuid', '--format=csv,noheader'])
if out is None:
return set()
busy_uuids = set(line.strip() for line in out.splitlines() if line.strip())
if not busy_uuids:
return set()
index_uuid = _nvidia_index_uuid()
return set(d for d in devices if index_uuid.get(d) in busy_uuids)
def _nvidia_sample(level):
# query all GPUs at once and return a dict mapping device index to (util, mem, power, temp)
query = 'index,utilization.gpu,memory.used'
if level == GpuMonitorInfo.FULL:
query += ',power.draw,temperature.gpu'
out = _run_nvidia_smi(['--query-gpu=' + query, '--format=csv,noheader,nounits'])
sample = {}
if out is None:
return sample
for line in out.splitlines():
parts = [ p.strip() for p in line.split(',') ]
if not parts or not parts[0].isdigit():
continue
idx = int(parts[0])
util = _to_number(parts[1], int) if len(parts) > 1 else 0
mem = _to_number(parts[2], int) if len(parts) > 2 else 0
power = _to_number(parts[3], float) if len(parts) > 3 else 0.
temp = _to_number(parts[4], int) if len(parts) > 4 else 0
sample[idx] = (util, mem, power, temp)
return sample
# --- AMD backend (amd-smi) -------------------------------------------------
def _run_amd_smi(args, timeout = 10.):
return _run_smi('amd-smi', args, timeout)
def _amd_parse_csv(out):
# parse amd-smi --csv output, skipping any banner lines; returns (header, rows) where the
# header is the first comma-separated line that contains a 'gpu' field. Robust to the extra
# columns and the "'CTRL'+'C'..." banner printed by "amd-smi monitor".
if out is None:
return None, []
lines = [ l.strip() for l in out.splitlines() if l.strip() ]
for i, line in enumerate(lines):
fields = [ f.strip() for f in line.split(',') ]
if 'gpu' in fields:
rows = [ [ c.strip() for c in r.split(',') ] for r in lines[i+1:] ]
return fields, rows
return None, []
def detect_amd_monitor_devices():
# return the sorted list of all physical AMD device indices, or [] if amd-smi is unavailable
header, rows = _amd_parse_csv(_run_amd_smi(['list', '--csv']))
if header is None or 'gpu' not in header:
return []
gi = header.index('gpu')
devices = []
for r in rows:
if gi < len(r) and r[gi].isdigit():
devices.append(int(r[gi]))
return sorted(devices)
def _amd_busy_devices(devices):
# return the set of device indices (within `devices`) that currently have a process actually
# using the GPU, parsed from "amd-smi process --csv". A device is considered busy only if a
# process row reports some non-zero GPU usage, to skip the phantom all-zero entry that
# amd-smi lists even on an idle GPU (e.g. "0,N/A,<pid>,0,0,0,0,0,...").
header, rows = _amd_parse_csv(_run_amd_smi(['process', '--csv']))
if header is None or 'gpu' not in header:
return set()
col = { name: i for i, name in enumerate(header) }
gi = col['gpu']
usage_cols = [ col[c] for c in ('vram_mem', 'gtt_mem', 'cpu_mem', 'gfx', 'mem_usage') if c in col ]
busy = set()
for r in rows:
if gi >= len(r) or not r[gi].isdigit():
continue
if 'no running processes' in ','.join(r).lower():
continue
if usage_cols:
# newer format: require some non-zero GPU usage to count the process
if any(ci < len(r) and _to_number(r[ci], float) > 0 for ci in usage_cols):
busy.add(int(r[gi]))
else:
# older format without usage columns: any real process row counts
busy.add(int(r[gi]))
return busy & set(devices)
def _amd_sample(level):
# one "amd-smi monitor" snapshot for all GPUs -> dict mapping index to (util, mem, power, temp)
out = _run_amd_smi(['monitor', '-u', '-v', '-p', '-t', '-w', '1', '-i', '1', '--csv'])
header, rows = _amd_parse_csv(out)
sample = {}
if header is None or 'gpu' not in header:
return sample
col = { name: i for i, name in enumerate(header) }
gi = col.get('gpu')
for r in rows:
if gi is None or gi >= len(r) or not r[gi].isdigit():
continue
idx = int(r[gi])
def field(name, conv):
i = col.get(name)
return _to_number(r[i], conv) if i is not None and i < len(r) else conv(0)
util = field('gfx', int) # graphics utilization (%)
mem = field('vram_used', int) # VRAM used (MB)
power = field('power_usage', float) # power draw (W)
temp = field('hotspot_temperature', int) # hotspot temperature (C)
sample[idx] = (util, mem, power, temp)
return sample
# --- backend selection -----------------------------------------------------
# a GPU monitoring backend bundles the two vendor-specific operations used by monitorResources:
# - sample(level) -> { index: (util, mem, power, temp) }
# - busy(devices) -> set of indices (within devices) currently running a process
GpuBackend = namedtuple('GpuBackend', ['name', 'sample', 'busy'])
_nvidia_backend = GpuBackend('nvidia', _nvidia_sample, _nvidia_busy_devices)
_amd_backend = GpuBackend('amd', _amd_sample, _amd_busy_devices)
# a single monitored GPU: its backend, its (vendor-local) device index, a field-safe column
# name and a human-readable label. On single-vendor machines the name/label are "gpu<d>"/"GPU-<d>";
# on mixed machines they are vendor-qualified ("nvidia0"/"NVIDIA-0") to keep the indices unambiguous.
MonGpu = namedtuple('MonGpu', ['backend', 'index', 'name', 'label'])
_detected_gpus_cache = None
_warned_no_monitor_gpu = False
def detect_gpus():
# return the list of MonGpu for every supported GPU present (NVIDIA and/or AMD). The set of
# physical devices is fixed for the life of the process (nvidia-smi / amd-smi ignore the
# visible-devices restriction), so cache it instead of re-enumerating on every multiCmsRun - but
# only cache a SUCCESSFUL (non-empty) detection, so a transient nvidia-smi/amd-smi failure on the
# first call is retried rather than frozen as "no GPU" for the whole process.
global _detected_gpus_cache
if _detected_gpus_cache:
return _detected_gpus_cache
found = []
nvidia = detect_nvidia_monitor_devices()
if nvidia:
found.append((_nvidia_backend, nvidia))
amd = detect_amd_monitor_devices()
if amd:
found.append((_amd_backend, amd))
multi = len(found) > 1
gpus = []
for backend, devices in found:
for d in devices:
if multi:
gpus.append(MonGpu(backend, d, '%s%d' % (backend.name, d), '%s-%d' % (backend.name.upper(), d)))
else:
gpus.append(MonGpu(backend, d, 'gpu%d' % d, 'GPU-%d' % d))
if gpus:
_detected_gpus_cache = gpus
return gpus
def monitored_gpus():
# the GPUs the monitor should sample and report: every detected device, restricted to the
# CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES selection when set - so --gpus (and any external
# visibility limit) is honored and the CSVs cover exactly the GPUs the jobs can use. nvidia-smi /
# amd-smi ignore those variables, so the filtering has to happen here.
gpus = detect_gpus()
def selected(env, backend = None):
# the physical indices selected by a visible-devices variable, or None if it is not set. An empty
# value ("--gpus none"), a selection matching no GPU, or a value this script cannot map to an
# index (e.g. "-1" or a MIG device) select nothing
val = os.environ.get(env)
if val is None:
return None # not set -> no restriction
try:
indices, uuids = _parse_gpu_device_list(val)
except RuntimeError:
return set()
want = set(indices)
if uuids:
# resolve NVIDIA UUIDs to physical indices; a stray UUID for AMD adds no restriction
if backend is _nvidia_backend:
index_uuid = _nvidia_index_uuid()
uuid_to_index = { uuid: idx for idx, uuid in index_uuid.items() }
for u in uuids:
if u in uuid_to_index:
want.add(uuid_to_index[u])
return want
cuda = selected('CUDA_VISIBLE_DEVICES', _nvidia_backend)
hip = selected('HIP_VISIBLE_DEVICES', _amd_backend)
out = []
for g in gpus:
if g.backend is _nvidia_backend and cuda is not None:
if g.index in cuda:
out.append(g)
elif g.backend is _amd_backend and hip is not None:
if g.index in hip:
out.append(g)
else:
out.append(g)
# if a restriction was requested but matched no device, monitor nothing (the jobs cannot use a GPU
# either); only fall back to all GPUs when no restriction was given at all
if cuda is not None or hip is not None:
return out
return gpus
def assign_gpus(gpus, jobs, gpus_per_job):
# distribute one vendor's GPUs across the jobs: if a job asks for at least as many GPUs as there
# are, every job runs on all of them; otherwise the GPUs are handed out round-robin. Returns one
# comma-separated GPU list per job. Used both for the actual per-job affinity (multiCmsRun) and to
# work out how many jobs share each GPU for the NVIDIA MPS tag (nvidia_mps_tag).
keys = list(gpus.keys())
if gpus_per_job >= len(keys):
return [ ','.join(map(str, keys)) for _ in range(jobs) ]
repeated = list(map(str, itertools.islice(itertools.cycle(keys), jobs * gpus_per_job)))
return [ ','.join(repeated[i*gpus_per_job:(i+1)*gpus_per_job]) for i in range(jobs) ]
def nvidia_mps_tag(nvidia_mps, jobs, gpus_per_job, gpus_nv, slots = None):
# build a short, filename-safe tag for the NVIDIA MPS setting: empty when no NVIDIA GPU is in use,
# "noMPS" when NVIDIA MPS is off, otherwise "MPS<percentage>" or "MPS<low>-<high>" for different
# percentages. Percentages mirror multiCmsRun (nvidia_mps_slot_percentages); uses --slot when given,
# else the automatic round-robin assignment.
if not gpus_nv:
return ''
if not slots:
slots = [ Slot(nvidia_gpus = a) for a in assign_gpus(gpus_nv, jobs, gpus_per_job) ]
else:
# reuse the --slot entries round-robin over the jobs, as multiCmsRun does
slots = list(itertools.islice(itertools.cycle(slots), jobs))
pcts = [ p for p in nvidia_mps_slot_percentages(nvidia_mps, slots, gpus_nv) if p is not None ]
if not pcts:
return 'noMPS'
lo, hi = min(pcts), max(pcts)
return 'MPS%d' % lo if lo == hi else 'MPS%d-%d' % (lo, hi)
def config_accelerators(process):
# the accelerator tokens a configuration allows (process.options.accelerators, e.g. ['cpu'],
# ['gpu-nvidia'], or ['*'] for "everything available"); an empty or missing list is treated as
# ['*']. Lets a CPU-only configuration (accelerators = ['cpu']) drop the %gpus/%mps tags even on a
# GPU node, without needing "-g 0" or "--gpus".
try:
acc = list(process.options.accelerators)
except (AttributeError, TypeError):
acc = []
return acc or ['*']
def gpu_tag(spec):
# build a short, filename-safe tag from a --gpus spec (e.g. "0,1" -> "gpu01", "all" -> "allGPUs");
# "none" returns an empty tag, so the %gpus placeholder drops out of the logdir name.
if not spec or spec == 'all':
return 'allGPUs'
if spec == 'none':
return ''
return 'gpu' + ''.join(c for c in spec if c.isalnum())
def gpu_in_use(gpus_per_job, process = None):
# whether the run actually uses a GPU: each job asks for at least one, at least one GPU (of any
# vendor) is available after the --gpus selection, and -- when a parsed process is given -- its
# configuration is not restricted to the CPU. Used to drop the %gpus tag on CPU-only runs.
if not (gpus_per_job > 0 and (bool(gpus_nv) or bool(gpus_amd))):
return False
if process is None:
return True
return any(a == '*' or a.startswith('gpu') for a in config_accelerators(process))
def nvidia_in_use(gpus_per_job, process = None):
# whether the run uses an NVIDIA GPU (the only vendor NVIDIA MPS applies to), likewise honouring
# the configuration's accelerators when a parsed process is given. Used to drop the %mps tag.
if not (gpus_per_job > 0 and bool(gpus_nv)):
return False
if process is None:
return True
return any(a == '*' or a == 'gpu-nvidia' for a in config_accelerators(process))
def expand_logdir(template, config, jobs, threads, streams, gpus_per_job, gpu_tag, nvidia_mps_tag):
# expand the placeholders in a --logdir template into the per-run directory name, or return None
# if no logs should be stored. The placeholders (their names, descriptions and how each is
# rendered) come from the single registry options.logdir_placeholders.
if not template:
return None
params = { 'config': config, 'jobs': jobs, 'threads': threads, 'streams': streams,
'gpus_per_job': gpus_per_job, 'gpu_tag': gpu_tag, 'nvidia_mps_tag': nvidia_mps_tag }
# an optional tag (%gpus / %mps) renders to '' and is then dropped together with its separator
values = { name: render(params) for name, _desc, render in logdir_placeholders }
# Substitute placeholders in one left-to-right pass (a value that itself contains a "%x" token,
# e.g. a config name, is not re-scanned). Each placeholder may absorb one preceding separator (any
# non-alphanumeric char): when it expands to empty -- an optional tag that does not apply, like
# %gpus with no GPU or %mps with no NVIDIA GPU -- the separator is dropped too, leaving nothing
# dangling. No name is a prefix of another, so the longest-first alternation is unambiguous.
names = sorted(values, key = len, reverse = True)
pattern = r'([^%0-9A-Za-z])?%(' + '|'.join(names) + r')'
def _expand(m):
sep, value = m.group(1) or '', values[m.group(2)]
return sep + value if value else ''
return re.sub(pattern, _expand, template)
# a GPU UUID, as accepted by CUDA_VISIBLE_DEVICES and the --slot "nv=" syntax
_gpu_uuid_re = re.compile(r'^GPU-[0-9a-fA-F]+$')
def _parse_gpu_device_list(devices):
# split a --gpus device list into integer indices and UUID tokens; integer ranges like "0-2" are
# expanded. Returns (indices, uuids) as sets of int / str. An invalid token raises RuntimeError.
indices = set()
uuids = set()
for part in devices.split(','):
part = part.strip()
if not part:
continue
if _gpu_uuid_re.match(part):
uuids.add(part)
elif part.isdigit():
indices.add(int(part))
elif '-' in part:
# an integer range like "0-2": expand it (Slot.parse_int_range raises on a bad range)
try:
for i in Slot.parse_int_range(part):
indices.add(i)
except (ValueError, TypeError):
raise RuntimeError('invalid GPU selector %r in --gpus %r' % (part, devices))
else:
raise RuntimeError('invalid GPU selector %r in --gpus %r (use an index, a range, or a "GPU-..." UUID)' % (part, devices))
return indices, uuids
def _visible_devices_value(devices):
# rewrite a --gpus device list as CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES accept it: integer
# ranges like "0-2" are expanded, since the runtimes only understand indices (and UUIDs for CUDA)
tokens = []
for part in devices.split(','):
part = part.strip()
if not part:
continue
if _gpu_uuid_re.match(part) or part.isdigit():
expanded = [ part ]
else:
expanded = [ str(i) for i in Slot.parse_int_range(part) ]
for token in expanded:
if token not in tokens:
tokens.append(token)
return ','.join(tokens)
def _restrict_gpus(gpus, devices, vendor = None):
# keep the selected physical indices of `gpus`, preserving the device keys so the per-job affinity
# assigns the real GPUs. UUIDs are resolved to NVIDIA indices via nvidia-smi; a UUID in an AMD
# selection is a hard error (HIP_VISIBLE_DEVICES does not accept UUIDs).
indices, uuids = _parse_gpu_device_list(devices)
if uuids and vendor in ('amd', 'rocm', 'hip'):
raise RuntimeError('GPU UUIDs are not supported for AMD (HIP_VISIBLE_DEVICES accepts indices only); '
'use integer indices in --gpus %r' % devices)
want = set(indices)
if uuids:
# resolve NVIDIA UUIDs to physical indices via the (cached) nvidia-smi index->uuid map
index_uuid = _nvidia_index_uuid()
uuid_to_index = { uuid: idx for idx, uuid in index_uuid.items() }
for u in uuids:
if u in uuid_to_index:
want.add(uuid_to_index[u])
else:
print('Warning: --gpus UUID %r did not match any available NVIDIA GPU UUID %s' % (u, sorted(index_uuid.values())))
sys.stdout.flush()
kept = type(gpus)((k, v) for k, v in gpus.items() if k in want)
if gpus and not kept:
print('Warning: --gpus selection %r matched none of the available GPU indices %s' % (devices, sorted(gpus.keys())))
sys.stdout.flush()
return kept
def apply_gpu_selection(spec):
# restrict the GPUs available to the automatic affinity to the --gpus selection, equivalent to
# running under CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES: the visible-devices environment is set
# (so a job the affinity does not pin is still confined to the selection), and the cached GPU
# lists are filtered to the selected physical indices - keeping the physical indices, so the
# per-job affinity still distributes one GPU per job but only across the selected GPUs. spec is:
# 'all' -> no restriction
# 'none' -> disable all GPUs (equivalent to CUDA_VISIBLE_DEVICES="" and
# HIP_VISIBLE_DEVICES="" together)
# 'IDX[,IDX...]' -> restrict the GPUs of whichever vendor(s) are present; UUIDs
# ("GPU-...") are supported for NVIDIA only
# 'VENDOR=IDX[,...]:VENDOR=...' -> restrict the named vendor(s); VENDOR is nvidia or amd
global gpus_nv, gpus_amd
if not spec or spec == 'all':
return
if spec == 'none':
# disable all GPUs of every vendor
os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['HIP_VISIBLE_DEVICES'] = ''
gpus_nv = type(gpus_nv)()
gpus_amd = type(gpus_amd)()
return
if '=' in spec:
for part in spec.split(':'):
if '=' not in part:
raise RuntimeError('invalid --gpus spec %r' % spec)
vendor, devices = part.split('=', 1)
vendor = vendor.strip().lower()
# validate and restrict first, then export the selection in the form the runtime understands
if vendor in ('nvidia', 'nv', 'cuda'):
gpus_nv = _restrict_gpus(gpus_nv, devices, vendor)
os.environ['CUDA_VISIBLE_DEVICES'] = _visible_devices_value(devices)
elif vendor in ('amd', 'rocm', 'hip'):
gpus_amd = _restrict_gpus(gpus_amd, devices, vendor)
os.environ['HIP_VISIBLE_DEVICES'] = _visible_devices_value(devices)
else:
raise RuntimeError('unknown GPU vendor %r in --gpus (use "nvidia" or "amd")' % vendor)
else:
# a plain list: apply it to whichever vendor(s) are present; reject UUIDs when an AMD GPU is
# present (ambiguous which vendor they target), since HIP_VISIBLE_DEVICES does not accept UUIDs
_, uuids = _parse_gpu_device_list(spec)
if uuids and gpus_amd:
raise RuntimeError('GPU UUIDs in --gpus are supported for NVIDIA only, but AMD GPUs are present; '
'use the per-vendor form, e.g. nvidia=GPU-...,amd=0,1')
value = _visible_devices_value(spec)
if gpus_nv:
gpus_nv = _restrict_gpus(gpus_nv, spec, 'nvidia')
os.environ['CUDA_VISIBLE_DEVICES'] = value
if gpus_amd:
gpus_amd = _restrict_gpus(gpus_amd, spec, 'amd')
os.environ['HIP_VISIBLE_DEVICES'] = value
if not gpus_nv and not gpus_amd:
os.environ['CUDA_VISIBLE_DEVICES'] = value
# ---------------------------------------------------------------------------
# NVIDIA MPS (Multi-Process Service) control
# ---------------------------------------------------------------------------
def nvidia_mps_running():
# return True if the NVIDIA MPS control daemon is currently running. Queried via the control
# protocol itself, which is authoritative: a running daemon answers with a number, while a missing
# one prints "Cannot find MPS control daemon process" and exits non-zero. (pgrep is unreliable
# here: the process "comm" is truncated to 15 chars, "nvidia-cuda-mps".)
return get_nvidia_mps_default_percentage() is not None
def ensure_nvidia_mps_off():
# for --no-nvidia-mps: never start NVIDIA MPS, and refuse to run if a control daemon is already
# active, since a pre-existing daemon would silently apply its own active-thread percentage to the jobs.
# Prints a clear, actionable error and exits non-zero.
if nvidia_mps_running():
sys.stderr.write(
'Error: --no-nvidia-mps was given but an NVIDIA MPS control daemon is already running. '
'Stop it (e.g. "echo quit | nvidia-cuda-mps-control") or drop --no-nvidia-mps.\n')
sys.exit(1)
def use_nvidia_mps(nvidia_mps, gpus_per_job, slots = None, no_nvidia_mps = False):
# whether to actually start NVIDIA MPS: it is requested -- either globally with --nvidia-mps, or by
# an "nvidia-mps=" field in at least one --slot entry -- and the jobs will use an NVIDIA GPU.
# --no-nvidia-mps overrides a slot's "nvidia-mps=" field and prevents the daemon from starting.
if no_nvidia_mps and any(slot.nvidia_mps is not None for slot in (slots or [])):
print('Warning: --no-nvidia-mps was given, but a --slot "nvidia-mps=" field requests NVIDIA MPS; '
'not starting the NVIDIA MPS control daemon (the slot setting is ignored).')
sys.stdout.flush()
return False
if nvidia_mps is not None:
requested = '--nvidia-mps'
elif any(slot.nvidia_mps is not None for slot in (slots or [])):
requested = 'an "nvidia-mps=" field in --slot'
else:
return False
if nvidia_in_use(gpus_per_job):
return True
reason = 'no NVIDIA GPU is available' if not gpus_nv else 'the jobs use no GPU (--gpus-per-job 0)'
print('Warning: %s requested but %s; not starting the NVIDIA MPS control daemon.' % (requested, reason))
sys.stdout.flush()
return False
def start_nvidia_mps():
# start the NVIDIA MPS control daemon in the background; return True on success
exe = shutil.which('nvidia-cuda-mps-control')
if not exe:
print('Warning: --nvidia-mps requested but "nvidia-cuda-mps-control" was not found.')
sys.stdout.flush()
return False
result = subprocess.run([exe, '-d'], stdout = subprocess.PIPE, stderr = subprocess.STDOUT, text = True)
if result.returncode != 0:
print('Warning: could not start the NVIDIA MPS control daemon:\n' + (result.stdout or ''))
sys.stdout.flush()
return False
print('Started the NVIDIA MPS control daemon')
sys.stdout.flush()
return True
def stop_nvidia_mps():
# stop the NVIDIA MPS control daemon. The clean "quit" is bounded by a timeout so a wedged
# daemon (e.g. after an interrupted run abruptly killed its clients) cannot hang the cleanup; the
# control daemon is then force-killed so a wedged one never survives. The force-kill matches the
# exact command line we started the daemon with ("nvidia-cuda-mps-control -d"), so it hits only
# that daemon and NOT: the per-user NVIDIA MPS server(s) - whose comm truncates to the same 15 chars
# "nvidia-cuda-mps" and which on a shared node may still be serving a concurrent run's jobs - nor
# any unrelated process that merely mentions "nvidia-cuda-mps-control" in its command line.
# (A control daemon is shared per user, so a concurrent --nvidia-mps run that attached to it will
# still lose it here; its in-flight jobs keep running on the surviving server.)
exe = shutil.which('nvidia-cuda-mps-control')
if exe:
try:
subprocess.run([exe], input = 'quit\n', stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL, text = True, timeout = 10)
except Exception:
pass
try:
subprocess.run(['pkill', '-9', '-u', str(os.getuid()), '-f', 'nvidia-cuda-mps-control -d'],
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL, timeout = 10)
except Exception:
pass
print('Stopped the NVIDIA MPS control daemon')
sys.stdout.flush()
def get_nvidia_mps_default_percentage():
# return the NVIDIA MPS daemon's current default active thread percentage as a float, or None
exe = shutil.which('nvidia-cuda-mps-control')
if not exe:
return None
try:
result = subprocess.run([exe], input = 'get_default_active_thread_percentage\n',
stdout = subprocess.PIPE, stderr = subprocess.STDOUT, text = True, timeout = 10)
except Exception:
return None
if result.returncode != 0:
return None
try:
return float(result.stdout.strip().splitlines()[-1])
except Exception:
return None
def set_nvidia_mps_default_percentage(pct):
# set the NVIDIA MPS daemon's default active thread percentage (applies to servers created afterwards)
exe = shutil.which('nvidia-cuda-mps-control')
if not exe:
return
try:
subprocess.run([exe], input = 'set_default_active_thread_percentage %g\n' % float(pct),
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL, text = True, timeout = 10)
except Exception:
pass
class nvidia_mps_session:
# context manager that, when enabled, starts the NVIDIA MPS control daemon if it is not already
# running. On exit it stops the daemon only if it was started here; if it was already running,
# the daemon is left running and its default active thread percentage is restored to the value
# it had before (multiCmsRun raises that default so the requested --nvidia-mps percentage is honoured
# and not clamped by a lower pre-existing default).
#
# The cleanup also runs on SIGINT (Ctrl+C) and SIGTERM, so an interrupted run does not leave a
# wedged NVIDIA MPS daemon behind; the cleanup is idempotent so it runs at most once.
def __init__(self, enabled):
self.enabled = enabled
self.started = False
self.attached = False
self.saved_default = None
self.cleaned = False
self.prev_handlers = {}
def __enter__(self):
if self.enabled:
if not nvidia_mps_running():
self.started = start_nvidia_mps()
else:
# we are attaching to a pre-existing daemon; remember its default so we can restore it
self.attached = True
self.saved_default = get_nvidia_mps_default_percentage()
# install signal handlers so Ctrl+C / SIGTERM also clean up (signals are only deliverable
# to the main thread; ignore failures if we are not in it)
if self.started or self.attached:
for sig in (signal.SIGINT, signal.SIGTERM):
try:
self.prev_handlers[sig] = signal.getsignal(sig)
signal.signal(sig, self._on_signal)
except (ValueError, OSError):
pass
return self
def _cleanup(self):
if self.cleaned:
return
self.cleaned = True
if self.started:
stop_nvidia_mps()
elif self.attached:
# multiCmsRun raises this daemon's default active thread percentage so the requested --nvidia-mps
# value is not clamped; restore the pre-existing default on exit. If it could not be read,
# fall back to 100 (the NVIDIA MPS factory default) rather than leaving the shared daemon at our
# raised value.
set_nvidia_mps_default_percentage(self.saved_default if self.saved_default is not None else 100.)
def _on_signal(self, signum, frame):
self._cleanup()
# restore handlers and exit with the conventional 128+signal code
self._restore_handlers()
sys.exit(128 + signum)
def _restore_handlers(self):
for sig, handler in self.prev_handlers.items():
try:
signal.signal(sig, handler)
except (ValueError, OSError, TypeError):
pass
self.prev_handlers = {}
def __exit__(self, *exc):
self._restore_handlers()
self._cleanup()
return False
def nvidia_mps_slot_percentages(nvidia_mps, slots, gpus_nv):
# compute the NVIDIA MPS active thread percentage for each job slot, based on how many jobs
# actually land on each NVIDIA GPU (derived from the slots, so it works with --slot as well as with
# the automatic GPU affinity). Returns a list with one entry per slot, using None where NVIDIA MPS
# does not apply (NVIDIA MPS off, no NVIDIA GPU, or a slot that uses no GPU). A positive
# `nvidia_mps` is used verbatim for every GPU-using slot; a non-positive `nvidia_mps` (the
# value-less "--nvidia-mps" passes -1) splits each GPU evenly among the jobs sharing it:
# ceil(100 / (jobs on the busiest GPU the slot uses)).
# An explicit "nvidia-mps=" field in a --slot entry is taken verbatim and wins over the global rule, so a
# single --slot may pin its own percentage while the other slots follow --nvidia-mps (or none).
explicit = [ slot.nvidia_mps for slot in slots ]
if not gpus_nv or (nvidia_mps is None and not any(p is not None for p in explicit)):
return [ None ] * len(slots)
all_gpus = set(str(g) for g in gpus_nv.keys())
# the set of NVIDIA GPUs each slot uses: None means "any/all visible GPUs", a set may be empty
slot_gpus = []
for slot in slots:
if slot.nvidia_gpus is None:
slot_gpus.append(None)
else:
s = set(slot.nvidia_gpus)
slot_gpus.append(s)
all_gpus |= s
# count how many jobs use each GPU; an unconstrained (None) slot counts on every GPU
counts = { g: 0 for g in all_gpus }
for s in slot_gpus:
for g in (all_gpus if s is None else s):
counts[g] += 1
result = []
for s, own in zip(slot_gpus, explicit):
if s is not None and len(s) == 0:
result.append(None) # this slot uses no GPU
elif own is not None:
result.append(own) # explicit "nvidia-mps=" in this --slot
elif nvidia_mps is None:
result.append(None) # only other slots set "nvidia-mps="
elif nvidia_mps > 0:
result.append(nvidia_mps) # explicit percentage
else:
targets = all_gpus if s is None else s
share = max((counts[g] for g in targets), default = 1)
# split the busiest GPU evenly, rounding the share UP (ceil): e.g. 16 jobs on a GPU -> 7% each
# (not the floored 6%), so the jobs are allowed to use the whole GPU rather than leaving it idle
result.append(max(1, -(-100 // max(1, share))))
return result
class _MonitorState:
# shared between the resource monitor thread and multiCmsRun: the accumulated sample rows, the
# numpy dtype, and the detected in-use GPU set. Rows are consumed either by drain() (take + clear:
# per step for an indefinite run so memory stays bounded, else once at the end) or by snapshot()
# (copy without clearing: per step when a shared monitor keeps running across several runs).
def __init__(self):
self.lock = threading.Lock()
self.rows = []
self.dtype = None
self.inuse = None
def drain(self):
# atomically take and clear the accumulated rows
with self.lock:
rows, self.rows = self.rows, []
return rows
def snapshot(self):
# atomically copy the accumulated rows without clearing them, for per-step slicing while a
# shared monitor keeps running across several runs
with self.lock:
return list(self.rows)
@threaded
def monitorResources(stop, gpus, level, state, streamer = None, interval = 1.):
# sample the aggregate host CPU utilization and memory (summed over this process tree) and the
# per-GPU utilization/memory of every monitored GPU (across all vendors) on a single shared
# cadence, so the CPU and GPU timestamps line up. `gpus` is a list of MonGpu; the in-use subset
# is detected at runtime from the GPUs that have a running process. Each sample is appended to
# `state` (a _MonitorState) - which multiCmsRun drains per step (internal / indefinite) or
# snapshots per step (shared monitor) - and, when a `streamer` is given, also written to the
# top-level CSVs as it arrives (line-buffered, so they survive an interruption or crash).
# capture the host monitoring level once, so the structured dtype (built here) and the per-tick
# rows (built in the loop below) always have matching widths even if the global `monitoring` were
# to change under us; a FULL run adds the USS/PSS columns to both.
host_level = monitoring
# build the structured dtype: time + aggregate host + per-GPU columns
fields = [('time', 'datetime64[ms]'),
('cpu_use', 'float'),
('cpu_vms', 'int'),
('cpu_rss', 'int')]
if host_level == HostMonitorInfo.FULL:
fields.append(('cpu_uss', 'int'))
fields.append(('cpu_pss', 'int'))
for g in gpus:
fields.append(('%s_util' % g.name, 'int'))
fields.append(('%s_mem' % g.name, 'int'))
if level == GpuMonitorInfo.FULL: