Skip to content

Commit 35d2a94

Browse files
authored
Merge pull request #267 from HPC-SimTools/265-add-support-for-cores-per-task-when-using-prun
265 add support for cores per task when using prun
2 parents d1f7aed + 94c6cdb commit 35d2a94

10 files changed

Lines changed: 1191 additions & 114 deletions

File tree

‎doc/user_guides/ensembles.rst‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,10 +438,47 @@ not necessarily the time it occurred. A running process does not establish
438438
DVM responsiveness. Abrupt worker or node loss may leave no final record.
439439
Components must still check ``wait_task()`` results and propagate failures.
440440

441+
CPU budgets and rank limits
442+
---------------------------
443+
444+
``cores_per_instance`` is the CPU budget available to each subordinate IPS
445+
instance, not a request for that many MPI ranks. It defaults to one and must
446+
be a positive integer. A task launched with ``nproc=2, task_cpp=4`` requires
447+
eight processing elements from this budget.
448+
449+
The generated single-node platform sets both ``CORES_PER_NODE`` and
450+
``PROCS_PER_NODE`` to the instance budget by default. These settings remain
451+
independent: an explicitly configured DVM instance with eight cores and a
452+
two-process limit can run two four-core ranks. Lowering the process limit
453+
does not discard CPU capacity. CPU reservations and concurrent rank occupancy
454+
are tracked and released separately. ``TOTAL_PROCS``, when set, also limits
455+
concurrent ranks across the instance's nodes.
456+
457+
Parent scheduling allows ``allocated CPU capacity // cores_per_instance``
458+
instances concurrently per worker. A 128-core node can therefore run sixteen
459+
eight-core instances at once. All workers use the concurrency supported by
460+
the smallest allocated node budget. An instance budget exceeding that capacity
461+
is rejected before workers are launched. Generic non-ensemble Dask task pools
462+
retain their existing ``dask_ppw`` behavior.
463+
464+
In core mode, budgets count physical cores. With ``hwthreads=True``, budgets
465+
count hardware threads. Manual platforms must declare ``CORES_PER_NODE`` in
466+
the selected unit; generated instance platforms do this automatically.
467+
For Slurm platforms, ``CORES_PER_NODE`` describes physical capacity and IPS
468+
uses ``SLURM_JOB_CPUS_PER_NODE`` plus ``scontrol show node`` topology to bound
469+
and convert the allocation. IPS does not inspect the login host's or macOS
470+
host's topology to infer compute-node capacity. Partial allocations are
471+
conservatively rounded down in physical-core mode. Missing scheduler topology
472+
is an error, rather than permission to use an entire machine.
473+
474+
This CPU-budget discovery path currently supports ``NODE_DETECTION=manual``
475+
and ``slurm_env``. Other launchers retain their existing resource-discovery
476+
behavior. Instances remain on a single node, and the DVM controls actual
477+
binding; the instance configuration describes a budget rather than CPU IDs.
478+
441479
Limitations
442480
-----------
443481

444-
- The method signature indicates `cores_per_instance` is not yet fully implemented
445482
- Parameter substitution is limited to simple string replacement
446483

447484
See Also
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
"""CPU budgets independent of MPI rank limits and local machine topology."""
2+
3+
import os
4+
import re
5+
import subprocess
6+
from collections.abc import Callable
7+
from typing import Any
8+
9+
10+
def _expand_slurm_counts(value: str) -> list[int]:
11+
"""Expand Slurm's per-node CPU counts.
12+
13+
:param value: A count expression such as ``256(x2),128``.
14+
:returns: One positive CPU count per allocated node.
15+
:raises ValueError: If the expression is malformed.
16+
"""
17+
counts = []
18+
for group in value.split(','):
19+
match = re.fullmatch(r'([1-9][0-9]*)(?:\(x([1-9][0-9]*)\))?', group.strip())
20+
if match is None:
21+
raise ValueError(f'Invalid SLURM_JOB_CPUS_PER_NODE: {value!r}')
22+
counts.extend([int(match[1])] * int(match[2] or 1))
23+
return counts
24+
25+
26+
def _get_cpu_nodes(
27+
get_parameter: Callable[..., Any], hwthreads: bool = False
28+
) -> list[tuple[str, int]]:
29+
"""Read allocated CPU budgets without using process-slot counts as capacity.
30+
31+
Manual configurations declare budgets in the selected processing-element
32+
unit. Slurm CPU counts are converted using the compute nodes' scheduler
33+
topology, never the topology of the host running IPS. For partial Slurm
34+
allocations, core-mode capacity is conservatively rounded down.
35+
36+
:param get_parameter: Configuration lookup accepting ``silent=True``.
37+
:param hwthreads: Whether the allocation unit is a hardware thread.
38+
:returns: Node names and allocatable processing-element counts.
39+
:raises ValueError: If capacity or scheduler topology cannot be established.
40+
"""
41+
detection = get_parameter('NODE_DETECTION', silent=True)
42+
configured = int(get_parameter('CORES_PER_NODE', silent=True) or 0)
43+
if configured < 1:
44+
raise ValueError('CPU budgeting requires a positive CORES_PER_NODE')
45+
if detection == 'manual':
46+
nodes = int(get_parameter('NODES', silent=True) or 1)
47+
if nodes < 1:
48+
raise ValueError('NODES must be positive')
49+
return [(f'dummynode{i}', configured) for i in range(nodes)]
50+
if detection != 'slurm_env':
51+
raise ValueError('CPU budgeting currently requires manual or slurm_env node detection')
52+
53+
nodelist = os.environ.get('SLURM_JOB_NODELIST') or os.environ.get('SLURM_NODELIST')
54+
counts = os.environ.get('SLURM_JOB_CPUS_PER_NODE')
55+
if not nodelist or not counts:
56+
raise ValueError('Slurm CPU budgeting requires the job node list and CPUs per node')
57+
names = subprocess.check_output(
58+
['scontrol', 'show', 'hostnames', nodelist], encoding='UTF-8'
59+
).split()
60+
allocated = _expand_slurm_counts(counts)
61+
if len(names) != len(allocated):
62+
raise ValueError('Slurm node list and CPU counts have different lengths')
63+
topology = subprocess.check_output(
64+
['scontrol', 'show', 'node', nodelist, '--oneliner'], encoding='UTF-8'
65+
)
66+
topologies = {}
67+
for line in topology.splitlines():
68+
fields = dict(part.split('=', 1) for part in line.split() if '=' in part)
69+
if 'NodeName' in fields:
70+
topologies[fields['NodeName']] = fields
71+
result = []
72+
for name, granted in zip(names, allocated, strict=True):
73+
fields = topologies.get(name, {})
74+
try:
75+
tpc = int(fields['ThreadsPerCore'])
76+
physical = int(fields['Sockets']) * int(fields['CoresPerSocket'])
77+
scheduled = int(fields['CPUTot'])
78+
except (KeyError, ValueError) as exc:
79+
raise ValueError(f'Missing Slurm CPU topology for {name}') from exc
80+
if min(tpc, physical, scheduled) < 1 or scheduled not in (physical, physical * tpc):
81+
raise ValueError(f'Inconsistent Slurm CPU topology for {name}')
82+
# Slurm may count schedulable CPUs as cores or hardware threads.
83+
scheduled_per_core = scheduled // physical
84+
if hwthreads:
85+
capacity = min(configured, physical) * tpc
86+
capacity = min(capacity, granted * tpc // scheduled_per_core)
87+
else:
88+
capacity = min(configured, physical, granted // scheduled_per_core)
89+
if capacity < 1:
90+
raise ValueError(f'No complete processing element available on {name}')
91+
result.append((name, capacity))
92+
return result
93+
94+
95+
def _ensemble_worker_threads(capacities: list[int], budget: int) -> int:
96+
"""Compute a safe uniform concurrency for one Dask worker per node.
97+
98+
:param capacities: Allocated CPU budgets of the worker nodes.
99+
:param budget: Processing elements reserved for each ensemble instance.
100+
:returns: Instances allowed concurrently on each worker.
101+
:raises ValueError: If the budget is invalid or cannot fit every worker.
102+
"""
103+
if isinstance(budget, bool) or not isinstance(budget, int) or budget < 1:
104+
raise ValueError('cores_per_instance must be a positive integer')
105+
if not capacities or min(capacities) < budget:
106+
raise ValueError('cores_per_instance exceeds the allocated CPU capacity of a worker node')
107+
return min(capacities) // budget

‎ipsframework/resource_manager.py‎

Lines changed: 146 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from collections import namedtuple
99
from math import ceil
1010

11+
from ._internal.cpu_resources import _get_cpu_nodes
1112
from .ips_es_spec import EventManager
1213
from .ips_exceptions import (
1314
BadResourceRequestError,
@@ -108,6 +109,15 @@ def initialize(self, data_mngr, task_mngr, config_mngr, cmd_nodes=0, cmd_ppn=0):
108109
self.TM = task_mngr
109110
self.CM = config_mngr
110111
self.node_alloc_mode = self.CM.get_platform_parameter('NODE_ALLOCATION_MODE')
112+
self._dvm = (
113+
str(self.CM.get_platform_parameter('MPIRUN_VERSION', silent=True)).upper()
114+
== 'OPENMPI-DVM'
115+
)
116+
117+
self._dvm_rank_allocations: dict[int, dict[str, int]] = {}
118+
self._dvm_total_ranks = (
119+
int(self.CM.get_platform_parameter('TOTAL_PROCS', silent=True) or 0) if self._dvm else 0
120+
)
111121

112122
rfile_name = os.path.join(self.CM.sim_map[self.CM.fwk_sim_name].sim_root, 'resource_usage')
113123
# SIMYAN: try to safely make the directory...
@@ -137,13 +147,31 @@ def initialize(self, data_mngr, task_mngr, config_mngr, cmd_nodes=0, cmd_ppn=0):
137147
self.host = self.CM.get_platform_parameter('HOST')
138148
self.fwk.debug('RM: Host = %s', self.host)
139149
try:
140-
(
141-
list_of_nodes,
142-
self.cores_per_node,
143-
self.sockets_per_node,
144-
self.max_ppn,
145-
self.accurate_nodes,
146-
) = get_resource_list(self.CM, self.host)
150+
if self._dvm:
151+
list_of_nodes = _get_cpu_nodes(
152+
self.CM.get_platform_parameter,
153+
str(self.CM.get_platform_parameter('DVM_HWTHREADS', silent=True)).lower()
154+
== 'true',
155+
)
156+
# Process limits restrict ranks, never the CPU inventory.
157+
self.max_ppn = int(self.CM.get_platform_parameter('PROCS_PER_NODE'))
158+
if self.max_ppn <= 0:
159+
self.max_ppn = max(count for _, count in list_of_nodes)
160+
self.cores_per_node = max(count for _, count in list_of_nodes)
161+
self.sockets_per_node = int(
162+
self.CM.get_platform_parameter('SOCKETS_PER_NODE') or 1
163+
)
164+
self.accurate_nodes = (
165+
self.CM.get_platform_parameter('NODE_DETECTION') != 'manual'
166+
)
167+
else:
168+
(
169+
list_of_nodes,
170+
self.cores_per_node,
171+
self.sockets_per_node,
172+
self.max_ppn,
173+
self.accurate_nodes,
174+
) = get_resource_list(self.CM, self.host)
147175
self.fwk.warning('RM: list_of_nodes = %s', str(list_of_nodes))
148176
self.fwk.warning('RM: max_ppn = %d ', int(self.max_ppn))
149177
if self.accurate_nodes is True and not self.CM.get_platform_parameter(
@@ -167,7 +195,7 @@ def initialize(self, data_mngr, task_mngr, config_mngr, cmd_nodes=0, cmd_ppn=0):
167195
if user_ppn <= self.max_ppn:
168196
self.ppn = user_ppn
169197
for i, (node, count) in enumerate(list_of_nodes):
170-
if count > self.ppn:
198+
if not self._dvm and count > self.ppn:
171199
list_of_nodes[i] = (node, self.ppn)
172200
self.fwk.warning('Using user set procs per node: %d', user_ppn)
173201
else:
@@ -182,7 +210,7 @@ def initialize(self, data_mngr, task_mngr, config_mngr, cmd_nodes=0, cmd_ppn=0):
182210
if user_ppn <= self.max_ppn:
183211
self.ppn = user_ppn
184212
for i, (node, count) in enumerate(list_of_nodes):
185-
if count > self.ppn:
213+
if not self._dvm and count > self.ppn:
186214
list_of_nodes[i] = (node, self.ppn)
187215
else:
188216
self.fwk.warning(
@@ -371,6 +399,14 @@ def get_allocation(
371399
whole_nodes = True
372400
whole_socks = True
373401

402+
if (
403+
str(self.CM.get_platform_parameter('MPIRUN_VERSION', silent=True)).upper()
404+
== 'OPENMPI-DVM'
405+
):
406+
return self._get_dvm_allocation(
407+
comp_id, nproc, task_id, whole_nodes, whole_socks, ppn, task_cpp, task_gpp
408+
)
409+
374410
# Are there enough cores to satisfy the request?
375411
# Returns the list of nodes that fit the bill
376412
allocation_possible = False
@@ -525,6 +561,106 @@ def get_allocation(
525561
cores_allocated=cores_allocated,
526562
)
527563

564+
def _get_dvm_allocation(
565+
self,
566+
comp_id: str,
567+
nproc: int,
568+
task_id: int,
569+
whole_nodes: bool,
570+
whole_socks: bool,
571+
ppn: int,
572+
task_cpp: int,
573+
task_gpp: int,
574+
) -> Allocation:
575+
"""Reserve complete ranks for a DVM launch without reducing their core count.
576+
577+
:param comp_id: Identifier of the requesting component.
578+
:param nproc: Number of MPI ranks requested.
579+
:param task_id: Identifier used to track and release the allocation.
580+
:param whole_nodes: Whether to reserve entire nodes.
581+
:param whole_socks: Whether to reserve entire sockets.
582+
:param ppn: Maximum ranks per node requested by the caller.
583+
:param task_cpp: Processing elements per rank in the configured CPU mode;
584+
zero retains launcher defaults.
585+
:param task_gpp: GPUs per rank.
586+
:returns: Allocation containing rank counts and reserved physical cores.
587+
:raises ValueError: If the rank or core count is invalid.
588+
:raises BadResourceRequestError: If the request exceeds total capacity.
589+
:raises InsufficientResourcesError: If capacity is temporarily occupied.
590+
"""
591+
if nproc < 1 or not isinstance(task_cpp, int) or task_cpp < 0:
592+
raise ValueError('DVM tasks require positive nproc and nonnegative integer task_cpp')
593+
cpp = task_cpp or 1
594+
ppn = min(ppn, self.cores_per_node // cpp)
595+
total_capacity = sum(min(ppn, node.total_cores // cpp) for node in self.nodes.values())
596+
if self._dvm_total_ranks > 0:
597+
total_capacity = min(total_capacity, self._dvm_total_ranks)
598+
requested_nodes = ceil(nproc / max(ppn, 1))
599+
if nproc > total_capacity:
600+
raise BadResourceRequestError(
601+
comp_id, task_id, requested_nodes, max(1, requested_nodes - len(self.nodes))
602+
)
603+
if not self.check_gpus(ppn, task_gpp):
604+
raise GpuResourceRequestMismatchError(comp_id, task_id, ppn, task_gpp, self.gpn)
605+
606+
# Plan first so a failed request never consumes a partial allocation.
607+
plan = []
608+
remaining = nproc
609+
for name in self.avail_nodes:
610+
node = self.nodes[name]
611+
available = node.avail_cores
612+
if whole_nodes:
613+
available = available if available == node.total_cores else 0
614+
elif whole_socks:
615+
available = sum(
616+
sock.avail_cores
617+
for sock in node.sockets
618+
if sock.avail_cores == sock.total_cores
619+
)
620+
ranks_in_use = sum(
621+
allocation.get(name, 0) for allocation in self._dvm_rank_allocations.values()
622+
)
623+
ranks = min(ppn, available // cpp, remaining, max(0, self.max_ppn - ranks_in_use))
624+
if ranks:
625+
plan.append((name, ranks))
626+
remaining -= ranks
627+
if not remaining:
628+
break
629+
if self._dvm_total_ranks > 0:
630+
remaining = max(remaining, nproc - max(0, self._dvm_total_ranks - self.processes))
631+
if remaining:
632+
raise InsufficientResourcesError(
633+
comp_id, task_id, requested_nodes, ceil(remaining / ppn)
634+
)
635+
636+
entries = []
637+
cores_allocated = 0
638+
for name, ranks in plan:
639+
node = self.nodes[name]
640+
count, cores = node.allocate(whole_nodes, whole_socks, task_id, comp_id, ranks * cpp)
641+
entries.append((name, cores))
642+
cores_allocated += count
643+
if name not in self.alloc_nodes:
644+
self.alloc_nodes.append(name)
645+
if not node.avail_cores:
646+
self.avail_nodes.remove(name)
647+
self.processes += nproc
648+
self.alloc_cores += cores_allocated
649+
self.avail_cores -= cores_allocated
650+
self.active_tasks[task_id] = (comp_id, nproc, cores_allocated)
651+
self._dvm_rank_allocations[task_id] = dict(plan)
652+
self.report_rm_status('allocation for DVM task %d' % task_id)
653+
return Allocation(
654+
partial_node=not whole_nodes,
655+
nodelist=[name for name, _ in plan],
656+
corelist=None if whole_nodes else entries,
657+
ppn=ppn,
658+
max_ppn=self.max_ppn,
659+
cpp=task_cpp,
660+
accurate_nodes=self.accurate_nodes,
661+
cores_allocated=cores_allocated,
662+
)
663+
528664
def check_whole_node_cap(self, nproc, ppn):
529665
"""
530666
Determine if it is currently possible to allocate *nproc* processes
@@ -678,6 +814,7 @@ def release_allocation(self, task_id, status):
678814
self.avail_cores += num_cores
679815
self.alloc_cores -= num_cores
680816
self.processes -= nproc
817+
self._dvm_rank_allocations.pop(task_id, None)
681818

682819
self.report_rm_status('released nodes for task %d' % task_id)
683820

0 commit comments

Comments
 (0)