Skip to content

Commit d795364

Browse files
committed
feat: improve support for cores per task in DVM, enhancing CPU budget management
1 parent cd42e17 commit d795364

7 files changed

Lines changed: 361 additions & 32 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

‎ipsframework/resource_manager.py‎

Lines changed: 49 additions & 11 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(
@@ -552,7 +580,8 @@ def _get_dvm_allocation(
552580
:param whole_nodes: Whether to reserve entire nodes.
553581
:param whole_socks: Whether to reserve entire sockets.
554582
:param ppn: Maximum ranks per node requested by the caller.
555-
:param task_cpp: Physical cores per rank; zero retains launcher defaults.
583+
:param task_cpp: Processing elements per rank in the configured CPU mode;
584+
zero retains launcher defaults.
556585
:param task_gpp: GPUs per rank.
557586
:returns: Allocation containing rank counts and reserved physical cores.
558587
:raises ValueError: If the rank or core count is invalid.
@@ -564,6 +593,8 @@ def _get_dvm_allocation(
564593
cpp = task_cpp or 1
565594
ppn = min(ppn, self.cores_per_node // cpp)
566595
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)
567598
requested_nodes = ceil(nproc / max(ppn, 1))
568599
if nproc > total_capacity:
569600
raise BadResourceRequestError(
@@ -586,12 +617,17 @@ def _get_dvm_allocation(
586617
for sock in node.sockets
587618
if sock.avail_cores == sock.total_cores
588619
)
589-
ranks = min(ppn, available // cpp, remaining)
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))
590624
if ranks:
591625
plan.append((name, ranks))
592626
remaining -= ranks
593627
if not remaining:
594628
break
629+
if self._dvm_total_ranks > 0:
630+
remaining = max(remaining, nproc - max(0, self._dvm_total_ranks - self.processes))
595631
if remaining:
596632
raise InsufficientResourcesError(
597633
comp_id, task_id, requested_nodes, ceil(remaining / ppn)
@@ -612,6 +648,7 @@ def _get_dvm_allocation(
612648
self.alloc_cores += cores_allocated
613649
self.avail_cores -= cores_allocated
614650
self.active_tasks[task_id] = (comp_id, nproc, cores_allocated)
651+
self._dvm_rank_allocations[task_id] = dict(plan)
615652
self.report_rm_status('allocation for DVM task %d' % task_id)
616653
return Allocation(
617654
partial_node=not whole_nodes,
@@ -777,6 +814,7 @@ def release_allocation(self, task_id, status):
777814
self.avail_cores += num_cores
778815
self.alloc_cores -= num_cores
779816
self.processes -= nproc
817+
self._dvm_rank_allocations.pop(task_id, None)
780818

781819
self.report_rm_status('released nodes for task %d' % task_id)
782820

‎ipsframework/services.py‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from rich.console import Console
3838

3939
from ipsframework import ipsutil, messages
40+
from ipsframework._internal.cpu_resources import _ensemble_worker_threads, _get_cpu_nodes
4041
from ipsframework._internal.definitions import IPS_EVENT_TYPE
4142
from ipsframework.cca_es_spec import initialize_event_service
4243
from ipsframework.component_registry import ComponentID
@@ -2905,14 +2906,16 @@ def run_ensemble(
29052906
`logfile` and `errfile` will write to the working directory local
29062907
to the ensemble instance.
29072908
2908-
TODO be able to specify the number of cores per instance
2909-
29102909
:param template: configuration template file
29112910
:param variables: a dict of variables to pass to the ensemble runs
29122911
:param run_dir: in which to run the ensembles
29132912
:param name: ensemble name, or string to prepend to generated instance
29142913
directory and file names
2915-
:param cores_per_instance: How many cores per ensemble instances?
2914+
:param cores_per_instance: Positive CPU budget per instance, default one.
2915+
Counts physical cores, or hardware threads when ``hwthreads=True``.
2916+
Concurrent tasks inside an instance share this budget. Parent
2917+
concurrency uses allocated CPU capacity, independently of rank limits.
2918+
Manual platform CPU capacities must use the same unit.
29162919
:param num_nodes: Total number of nodes to allocate for the ensemble
29172920
runs. There will be one Dask worker assigned to each of these
29182921
nodes. If none specified, then assign a worker to each allocated
@@ -2928,6 +2931,13 @@ def run_ensemble(
29282931
# This should be a unique variable across all ensembles we keep track
29292932
# of in the portal This ID should only be shared by runs within an
29302933
# ensemble
2934+
cores_per_instance = 1 if cores_per_instance is None else cores_per_instance
2935+
if (
2936+
isinstance(cores_per_instance, bool)
2937+
or not isinstance(cores_per_instance, int)
2938+
or cores_per_instance < 1
2939+
):
2940+
raise ValueError('cores_per_instance must be a positive integer')
29312941
portal_ensemble_id = str(uuid.uuid4())
29322942

29332943
use_portal = self._should_use_portal()
@@ -3057,15 +3067,12 @@ def create_platform_config_file(prefix, working_dir, cores_per_instance, **kwarg
30573067
# `prun` *should* use the environment variables set by the plugin
30583068
# to find the DVM.
30593069
platform_config['MPIRUN_VERSION'] = 'OPENMPI-DVM'
3070+
platform_config['DVM_HWTHREADS'] = hwthreads
30603071

3061-
# Set the budget of cores per instance. By default, we will give
3062-
# a single core per instance.
3063-
if cores_per_instance is not None:
3064-
platform_config['CORES_PER_NODE'] = cores_per_instance
3065-
platform_config['PROCS_PER_NODE'] = cores_per_instance
3066-
else:
3067-
platform_config['CORES_PER_NODE'] = 1
3068-
platform_config['PROCS_PER_NODE'] = 1
3072+
# This virtual node contains the instance's CPU budget. Rank limits
3073+
# remain separate even when their default equals that budget.
3074+
platform_config['CORES_PER_NODE'] = cores_per_instance
3075+
platform_config['PROCS_PER_NODE'] = cores_per_instance
30693076

30703077
# for now each instance will always run on just one node
30713078
platform_config['NODES'] = 1
@@ -3240,6 +3247,7 @@ def send_ensemble_instance_to_portal(ensemble_name: str, data_path: Path) -> Non
32403247
try:
32413248
# Note that we *always* use Dask to run the ensemble tasks
32423249
self.logger.debug(f'Submitting {len(instances)} ensemble tasks')
3250+
self.task_pools[task_pool_name]._ensemble_budget = cores_per_instance
32433251
num_submitted = self.submit_tasks(
32443252
task_pool_name,
32453253
block=True,
@@ -3260,6 +3268,7 @@ def send_ensemble_instance_to_portal(ensemble_name: str, data_path: Path) -> Non
32603268
except Exception as e:
32613269
self.critical(f'Got an exception running ensemble: {e!s}')
32623270
traceback.print_exc()
3271+
raise
32633272
finally:
32643273
# self.debug('Getting finished tasks')
32653274
# exit_status = self.get_finished_tasks(task_pool_name)
@@ -3523,6 +3532,7 @@ def __init__(self, name: str, services: ServicesProxy):
35233532
self.dask_scheduler_file = None
35243533
self.dask_client = None
35253534
self.worker_event_logfile = None
3535+
self._ensemble_budget: int | None = None
35263536

35273537
def _wait_any_task(self, block=True):
35283538
"""
@@ -3728,6 +3738,14 @@ def _make_worker_args(
37283738
return base_args
37293739

37303740
services: ServicesProxy = self.services
3741+
ensemble_threads = None
3742+
if self._ensemble_budget is not None:
3743+
if dask_worker_per_gpu:
3744+
raise ValueError('Ensemble CPU budgets require one Dask worker per node')
3745+
cpu_nodes = _get_cpu_nodes(services.get_config_param, hwthreads)
3746+
ensemble_threads = _ensemble_worker_threads(
3747+
[capacity for _, capacity in cpu_nodes], self._ensemble_budget
3748+
)
37313749

37323750
# Note that we use the absolute path since at some point we may
37333751
# be in a different directory, which means that we otherwise would
@@ -3824,6 +3842,10 @@ def _make_worker_args(
38243842
nthreads = dask_ppw if dask_ppw else services.get_config_param('PROCS_PER_NODE') // gpn
38253843
task_ppn = gpn
38263844
task_gpp = 1
3845+
elif ensemble_threads is not None:
3846+
nthreads = ensemble_threads
3847+
task_ppn = 1
3848+
task_gpp = 0
38273849
else:
38283850
# The number of threads per Dask worker is the number of processors
38293851
# on that node divided by the cores per instance, which we're

‎tests/new/test_dvm_plugin.py‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""DVM diagnostics and cleanup without requiring PRTE or Slurm."""
2+
23
import json
34
import logging
45
import subprocess
6+
from pathlib import Path
57
from types import SimpleNamespace
68
from unittest.mock import Mock
79

@@ -23,7 +25,6 @@ def running(tmp_path, monkeypatch):
2325
proc.poll.side_effect = lambda: proc.returncode
2426

2527
def popen(command, **kwargs):
26-
from pathlib import Path
2728
Path(command[-1]).write_text('test-uri\n')
2829
return proc
2930

@@ -47,8 +48,14 @@ def stop(*args, **kwargs):
4748
plugin.teardown(worker)
4849
events = records(worker)
4950
assert [r['event'] for r in events] == [
50-
'launch_requested', 'launched', 'ready', 'shutdown_begin',
51-
'shutdown_command', 'exit_observed', 'shutdown_command_end', 'shutdown_complete',
51+
'launch_requested',
52+
'launched',
53+
'ready',
54+
'shutdown_begin',
55+
'shutdown_command',
56+
'exit_observed',
57+
'shutdown_command_end',
58+
'shutdown_complete',
5259
]
5360
assert events[0]['environment']['PRTE_MCA_ras_slurm_use_entire_allocation'] == '1'
5461
assert events[2]['uri'] == 'test-uri'
@@ -61,7 +68,9 @@ def stop(*args, **kwargs):
6168

6269
def test_shutdown_timeout_escalates_and_reaps(running, monkeypatch):
6370
plugin, worker, proc = running
64-
monkeypatch.setattr(services.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired('pterm', 10)))
71+
monkeypatch.setattr(
72+
services.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired('pterm', 10))
73+
)
6574
calls = []
6675

6776
def wait(timeout):
@@ -77,7 +86,9 @@ def wait(timeout):
7786
proc.terminate.assert_called_once()
7887
proc.kill.assert_called_once()
7988
events = records(worker)
80-
assert {'shutdown_command_failed', 'terminate_requested', 'kill_requested'} <= {e['event'] for e in events}
89+
assert {'shutdown_command_failed', 'terminate_requested', 'kill_requested'} <= {
90+
e['event'] for e in events
91+
}
8192
assert events[-1]['signal'] == 9
8293
assert events[-1]['dvm_return_code'] == -9
8394

@@ -111,7 +122,9 @@ def test_child_failure_references_dvm(tmp_path, monkeypatch):
111122
monkeypatch.setenv('IPS_DVM_INSTANCE', 'INSTANCE_3')
112123
proxy = Mock()
113124
proxy.get_working_dir.return_value = str(tmp_path)
114-
task = Mock(start_time=0, nproc=1, cores_allocated=1, binary='prun', args=(), command='prun test')
125+
task = Mock(
126+
start_time=0, nproc=1, cores_allocated=1, binary='prun', args=(), command='prun test'
127+
)
115128
task.process.wait.return_value = 195
116129
proxy.task_map = {7: task}
117130
assert services.ServicesProxy.wait_task(proxy, 7) == 195

0 commit comments

Comments
 (0)