From 1b10e509b799cc8a79fd80b2b30229bc9e0cac4f Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 03:34:40 -0600 Subject: [PATCH 01/11] arch: Respect cgroup and Slurm host memory budgets --- devito/arch/limits.py | 114 ++++++++++++++++++++++++++++++++++ devito/operator/operator.py | 3 +- tests/test_limits.py | 120 ++++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 devito/arch/limits.py create mode 100644 tests/test_limits.py diff --git a/devito/arch/limits.py b/devito/arch/limits.py new file mode 100644 index 0000000000..b73a27fcd3 --- /dev/null +++ b/devito/arch/limits.py @@ -0,0 +1,114 @@ +"""Operating-system and scheduler limits for host resources.""" + +import os +import re +from contextlib import suppress +from pathlib import Path + +__all__ = ['host_memory_available'] + +_PROC_SELF = Path('/proc/self') + + +def _mount_path(value): + # mountinfo escapes whitespace and backslashes as octal sequences. + return Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)) + + +def _cgroup_memory_headroom(): + try: + groups = (_PROC_SELF / 'cgroup').read_text(errors='surrogateescape') + mounts = (_PROC_SELF / 'mountinfo').read_text(errors='surrogateescape') + except OSError: + return None + + memberships = {} + for line in groups.split('\n'): + fields = line.split(':', 2) + if len(fields) != 3: + continue + hierarchy, controllers, group = fields + if 'memory' in controllers.split(','): + memberships['cgroup'] = Path(group) + elif hierarchy == '0' and not controllers: + memberships['cgroup2'] = Path(group) + + # On a hybrid system, the memory controller belongs to a single + # hierarchy. A v1 memory membership takes precedence. + v1 = 'cgroup' in memberships + fs = 'cgroup' if v1 else 'cgroup2' + group = memberships.get(fs) + if group is None or not group.is_absolute() or '..' in group.parts: + return None + limit_name, usage_name = (('memory.limit_in_bytes', 'memory.usage_in_bytes') + if v1 else ('memory.max', 'memory.current')) + + headrooms = [] + for line in mounts.split('\n'): + mount, _, superblock = line.partition(' - ') + fields = mount.split(' ') + details = superblock.split() + if len(fields) < 5 or len(details) < 3 or details[0] != fs: + continue + if v1 and 'memory' not in details[2].split(','): + continue + root, mountpoint = map(_mount_path, fields[3:5]) + try: + directory = mountpoint / group.relative_to(root) + except ValueError: + # A container can see a bind mount of its cgroup subtree while + # reporting its membership relative to a private cgroup root. + directory = mountpoint / group.relative_to('/') + try: + processes = (directory / 'cgroup.procs').read_text().split() + except OSError: + continue + if str(os.getpid()) not in processes: + continue + + # A parent can have less headroom than the process's own group, + # since its usage also includes sibling processes and cgroups. + for path in (directory, *directory.parents): + with suppress(OSError, ValueError): + limit = int((path / limit_name).read_text()) + usage = int((path / usage_name).read_text()) + if limit >= 0 and usage >= 0: + headrooms.append(max(0, limit - usage)) + if path == mountpoint: + break + + return min(headrooms, default=None) + + +def _slurm_integer(env, name): + try: + return max(0, int(env.get(name, '0'))) + except ValueError: + return 0 + + +def _slurm_memory_limit(env): + if not (env.get('SLURM_JOB_ID') or env.get('SLURM_JOBID')): + return None + + if 'SLURM_MEM_PER_NODE' in env: + budget = _slurm_integer(env, 'SLURM_MEM_PER_NODE') + elif 'SLURM_MEM_PER_CPU' in env: + budget = (_slurm_integer(env, 'SLURM_MEM_PER_CPU') * + _slurm_integer(env, 'SLURM_CPUS_ON_NODE')) + else: + gpus = (_slurm_integer(env, 'SLURM_GPUS_ON_NODE') or + _slurm_integer(env, 'SLURM_GPUS_PER_NODE')) + budget = _slurm_integer(env, 'SLURM_MEM_PER_GPU') * gpus + + return budget * 2**20 if budget else None + + +def host_memory_available(node_available): + """ + Clamp available node RAM to visible cgroup headroom and the local Slurm + allocation, in bytes. Slurm's environment describes a capacity budget. + Current usage is available through the memory controller. + """ + limits = (node_available, _cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) + return min(limit for limit in limits if limit is not None) diff --git a/devito/operator/operator.py b/devito/operator/operator.py index 70d700cba3..247ac383e7 100644 --- a/devito/operator/operator.py +++ b/devito/operator/operator.py @@ -14,6 +14,7 @@ from devito.arch import ( ANYCPU, Device, compiler_registry, get_visible_devices, platform_registry ) +from devito.arch.limits import host_memory_available from devito.data import default_allocator from devito.exceptions import ( CompilationError, ExecutionError, InvalidArgument, InvalidOperator @@ -1516,7 +1517,7 @@ def nbytes_avail_mapper(self): nproc = self.grid.distributor.nprocs_local except AttributeError: nproc = 1 - mapper[host_layer] = int(ANYCPU.memavail() / nproc) + mapper[host_layer] = host_memory_available(ANYCPU.memavail()) // nproc for layer in (host_layer, device_layer): if mapper.get(layer) is not None: diff --git a/tests/test_limits.py b/tests/test_limits.py new file mode 100644 index 0000000000..9aa679dedc --- /dev/null +++ b/tests/test_limits.py @@ -0,0 +1,120 @@ +import os + +import pytest + +from devito import Eq, Function, Grid, Operator +from devito.arch import ANYCPU, limits +from devito.types import host_layer + +MIB = 2**20 + + +@pytest.fixture +def proc_self(tmp_path, monkeypatch): + proc = tmp_path / 'proc' / 'self' + proc.mkdir(parents=True) + monkeypatch.setattr(limits, '_PROC_SELF', proc) + monkeypatch.delenv('SLURM_JOB_ID', raising=False) + monkeypatch.delenv('SLURM_JOBID', raising=False) + return proc + + +def write_memory(group, limit, usage, *, v1=False): + group.mkdir(parents=True, exist_ok=True) + if v1: + (group / 'memory.limit_in_bytes').write_text(str(limit)) + (group / 'memory.usage_in_bytes').write_text(str(usage)) + else: + (group / 'memory.max').write_text(str(limit)) + (group / 'memory.current').write_text(str(usage)) + + +def test_cgroup2_parent_headroom(proc_self, tmp_path): + mount = tmp_path / 'memory with spaces' + escaped_mount = str(mount).replace(' ', r'\040') + (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {escaped_mount} rw - ' + 'cgroup2 cgroup rw\n') + (proc_self / 'cgroup').write_text('0::/slurm/job_42/step\n') + job = mount / 'slurm' / 'job_42' + write_memory(job / 'step', 800, 500) + write_memory(job, 1000, 900) + assert limits.host_memory_available(2000) == 100 + assert limits.host_memory_available(50) == 50 + + write_memory(job, 1000, 1100) + assert limits.host_memory_available(2000) == 0 + + +def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): + v1, v2 = tmp_path / 'memory', tmp_path / 'unified' + (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' + f'3 2 0:45 /slurm {v1} rw - cgroup cgroup ' + 'rw,memory\n') + (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') + write_memory(v2 / 'job_42', 60, 10) + write_memory(v1 / 'job_42', 500, 375, v1=True) + write_memory(v1 / 'job_42' / 'task', 9223372036854771712, 300, v1=True) + assert limits.host_memory_available(2000) == 125 + + +def test_cgroup2_private_namespace(proc_self, tmp_path): + mount = tmp_path / 'memory' + (proc_self / 'mountinfo').write_text(f'1 2 0:44 /containers/123 {mount} rw - ' + 'cgroup2 cgroup rw\n') + (proc_self / 'cgroup').write_text('0::/\n') + write_memory(mount, 400, 168) + (mount / 'cgroup.procs').write_text(f'{os.getpid()}\n') + assert limits.host_memory_available(500) == 232 + + (mount / 'cgroup.procs').write_text('') + assert limits.host_memory_available(500) == 500 + + +@pytest.mark.parametrize('env, mib', [ + ({}, None), + ({'SLURM_MEM_PER_NODE': '0'}, None), + ({'SLURM_MEM_PER_NODE': 'unavailable'}, None), + ({'SLURM_MEM_PER_NODE': '640'}, 640), + ({'SLURM_MEM_PER_CPU': '100', 'SLURM_CPUS_ON_NODE': '4', + 'SLURM_JOB_CPUS_PER_NODE': '72(x2),36', 'SLURM_NODEID': '0'}, 400), + ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_ON_NODE': '2', 'SLURM_GPUS': '8'}, 400), + ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_PER_NODE': '3'}, 600), + ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS': '8'}, None), +]) +def test_slurm_allocation_budget(proc_self, monkeypatch, env, mib): + for key in ('SLURM_MEM_PER_NODE', 'SLURM_MEM_PER_CPU', 'SLURM_MEM_PER_GPU', + 'SLURM_CPUS_ON_NODE', 'SLURM_GPUS_ON_NODE', 'SLURM_GPUS_PER_NODE'): + monkeypatch.delenv(key, raising=False) + for key, value in env.items(): + monkeypatch.setenv(key, value) + + # A launcher may leave scheduler variables behind outside a job. + assert limits.host_memory_available(1024 * MIB) == 1024 * MIB + monkeypatch.setenv('SLURM_JOB_ID', '42') + assert limits.host_memory_available(1024 * MIB) == (mib or 1024) * MIB + + +def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch): + mount = tmp_path / 'memory' + (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') + (proc_self / 'cgroup').write_text('0::/job_42\n') + monkeypatch.setenv('SLURM_JOB_ID', '42') + monkeypatch.setenv('SLURM_MEM_PER_NODE', '16') + + write_memory(mount / 'job_42', 'max', 24 * MIB) + assert limits.host_memory_available(1024 * MIB) == 16 * MIB + write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) + assert limits.host_memory_available(1024 * MIB) == 8 * MIB + + +def test_operator_uses_local_host_budget(proc_self, monkeypatch): + grid = Grid(shape=(8, 8)) + field = Function(name='field', grid=grid) + args = Operator(Eq(field, 1)).arguments() + monkeypatch.setattr(ANYCPU, 'memavail', lambda: 1024 * MIB) + monkeypatch.setattr(type(args.grid.distributor), 'nprocs_local', 4) + monkeypatch.setenv('SLURM_JOB_ID', '42') + monkeypatch.setenv('SLURM_MEM_PER_NODE', '64') + + consumed = args.nbytes_consumed_operator[host_layer] + assert args.nbytes_avail_mapper[host_layer] == 16 * MIB - consumed From b1cfcce67c5946c136b9b50c1490293aba0de6a1 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 05:11:17 -0600 Subject: [PATCH 02/11] arch: Export host memory availability --- devito/arch/__init__.py | 1 + devito/arch/limits.py | 18 +++++++++++++++--- devito/operator/operator.py | 4 ++-- tests/test_limits.py | 25 ++++++++++++++----------- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/devito/arch/__init__.py b/devito/arch/__init__.py index 264b63ae65..033ac0eec7 100644 --- a/devito/arch/__init__.py +++ b/devito/arch/__init__.py @@ -1,2 +1,3 @@ from .archinfo import * # noqa from .compiler import * # noqa +from .limits import * # noqa diff --git a/devito/arch/limits.py b/devito/arch/limits.py index b73a27fcd3..2f8d2138f2 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -16,6 +16,11 @@ def _mount_path(value): def _cgroup_memory_headroom(): + """Return the tightest visible cgroup memory headroom in bytes. + + Account for usage in the current group and each visible ancestor. Return + None when no memory limit and usage can be read together. + """ try: groups = (_PROC_SELF / 'cgroup').read_text(errors='surrogateescape') mounts = (_PROC_SELF / 'mountinfo').read_text(errors='surrogateescape') @@ -81,6 +86,11 @@ def _cgroup_memory_headroom(): def _slurm_integer(env, name): + """Read a nonnegative Slurm memory size or resource count. + + Zero represents an unset, invalid, or negative field. Callers treat zero + as an unspecified budget or count. + """ try: return max(0, int(env.get(name, '0'))) except ValueError: @@ -106,9 +116,11 @@ def _slurm_memory_limit(env): def host_memory_available(node_available): """ - Clamp available node RAM to visible cgroup headroom and the local Slurm - allocation, in bytes. Slurm's environment describes a capacity budget. - Current usage is available through the memory controller. + Return available host memory in bytes. + + Cgroups provide the remaining bytes under the kernel's limit. Slurm + environment variables provide an allocation budget, which can apply + independently of a visible cgroup limit. """ limits = (node_available, _cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) return min(limit for limit in limits if limit is not None) diff --git a/devito/operator/operator.py b/devito/operator/operator.py index 247ac383e7..0799c3aac9 100644 --- a/devito/operator/operator.py +++ b/devito/operator/operator.py @@ -12,9 +12,9 @@ from sympy import sympify from devito.arch import ( - ANYCPU, Device, compiler_registry, get_visible_devices, platform_registry + ANYCPU, Device, compiler_registry, get_visible_devices, host_memory_available, + platform_registry ) -from devito.arch.limits import host_memory_available from devito.data import default_allocator from devito.exceptions import ( CompilationError, ExecutionError, InvalidArgument, InvalidOperator diff --git a/tests/test_limits.py b/tests/test_limits.py index 9aa679dedc..fcc1229627 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -3,7 +3,7 @@ import pytest from devito import Eq, Function, Grid, Operator -from devito.arch import ANYCPU, limits +from devito.arch import ANYCPU, host_memory_available, limits from devito.types import host_layer MIB = 2**20 @@ -38,11 +38,11 @@ def test_cgroup2_parent_headroom(proc_self, tmp_path): job = mount / 'slurm' / 'job_42' write_memory(job / 'step', 800, 500) write_memory(job, 1000, 900) - assert limits.host_memory_available(2000) == 100 - assert limits.host_memory_available(50) == 50 + assert host_memory_available(2000) == 100 + assert host_memory_available(50) == 50 write_memory(job, 1000, 1100) - assert limits.host_memory_available(2000) == 0 + assert host_memory_available(2000) == 0 def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): @@ -54,7 +54,7 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): write_memory(v2 / 'job_42', 60, 10) write_memory(v1 / 'job_42', 500, 375, v1=True) write_memory(v1 / 'job_42' / 'task', 9223372036854771712, 300, v1=True) - assert limits.host_memory_available(2000) == 125 + assert host_memory_available(2000) == 125 def test_cgroup2_private_namespace(proc_self, tmp_path): @@ -64,15 +64,16 @@ def test_cgroup2_private_namespace(proc_self, tmp_path): (proc_self / 'cgroup').write_text('0::/\n') write_memory(mount, 400, 168) (mount / 'cgroup.procs').write_text(f'{os.getpid()}\n') - assert limits.host_memory_available(500) == 232 + assert host_memory_available(500) == 232 (mount / 'cgroup.procs').write_text('') - assert limits.host_memory_available(500) == 500 + assert host_memory_available(500) == 500 @pytest.mark.parametrize('env, mib', [ ({}, None), ({'SLURM_MEM_PER_NODE': '0'}, None), + ({'SLURM_MEM_PER_NODE': '-1'}, None), ({'SLURM_MEM_PER_NODE': 'unavailable'}, None), ({'SLURM_MEM_PER_NODE': '640'}, 640), ({'SLURM_MEM_PER_CPU': '100', 'SLURM_CPUS_ON_NODE': '4', @@ -89,9 +90,9 @@ def test_slurm_allocation_budget(proc_self, monkeypatch, env, mib): monkeypatch.setenv(key, value) # A launcher may leave scheduler variables behind outside a job. - assert limits.host_memory_available(1024 * MIB) == 1024 * MIB + assert host_memory_available(1024 * MIB) == 1024 * MIB monkeypatch.setenv('SLURM_JOB_ID', '42') - assert limits.host_memory_available(1024 * MIB) == (mib or 1024) * MIB + assert host_memory_available(1024 * MIB) == (mib or 1024) * MIB def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch): @@ -102,9 +103,11 @@ def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch): monkeypatch.setenv('SLURM_MEM_PER_NODE', '16') write_memory(mount / 'job_42', 'max', 24 * MIB) - assert limits.host_memory_available(1024 * MIB) == 16 * MIB + assert host_memory_available(1024 * MIB) == 16 * MIB + write_memory(mount / 'job_42', 48 * MIB, 24 * MIB) + assert host_memory_available(1024 * MIB) == 16 * MIB write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) - assert limits.host_memory_available(1024 * MIB) == 8 * MIB + assert host_memory_available(1024 * MIB) == 8 * MIB def test_operator_uses_local_host_budget(proc_self, monkeypatch): From 318a300bb41e5ade797fb90d248b1551c1c75d66 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 07:29:18 -0600 Subject: [PATCH 03/11] arch: Explain Slurm and cgroup memory limits --- devito/arch/limits.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 2f8d2138f2..09677c48ff 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -118,9 +118,14 @@ def host_memory_available(node_available): """ Return available host memory in bytes. - Cgroups provide the remaining bytes under the kernel's limit. Slurm - environment variables provide an allocation budget, which can apply - independently of a visible cgroup limit. + Cgroup headroom accounts for usage in the process's group and its + visible ancestors. Slurm's `task/cgroup` plugin applies the job's RAM + limit through cgroups when `ConstrainRAMSpace` is enabled. + + Slurm can also enforce an allocation through job accounting + (`OverMemoryKill`). A visible cgroup cap can come from a container or + systemd scope, so also apply any local allocation reported in the + Slurm environment. """ limits = (node_available, _cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) return min(limit for limit in limits if limit is not None) From 7789774636227d2db9cc3214cfa31c774f68cd4f Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 08:14:11 -0600 Subject: [PATCH 04/11] arch: Report effective host memory budgets --- devito/arch/limits.py | 94 ++++++++++++++++++++++++++++++------------- tests/test_limits.py | 23 ++++++++--- 2 files changed, 84 insertions(+), 33 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 09677c48ff..a7f76346fe 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -3,11 +3,18 @@ import os import re from contextlib import suppress +from functools import lru_cache +from mmap import PAGESIZE from pathlib import Path +from devito.logger import is_log_enabled_for, perf +from devito.tools import humanbytes + __all__ = ['host_memory_available'] _PROC_SELF = Path('/proc/self') +# The 64-bit v1 controller uses page-aligned LONG_MAX for an unlimited cap. +_CGROUP_V1_UNLIMITED = (2**63 - 1) // PAGESIZE * PAGESIZE def _mount_path(value): @@ -15,15 +22,32 @@ def _mount_path(value): return Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)) +@lru_cache(maxsize=1) +def _cgroup_memory_mounts(mountinfo, fs): + """Resolve the memory controller mounts described by mountinfo.""" + mounts = [] + for line in mountinfo.split('\n'): + mount, _, superblock = line.partition(' - ') + fields = mount.split(' ') + details = superblock.split() + if len(fields) < 5 or len(details) < 3 or details[0] != fs: + continue + if fs == 'cgroup' and 'memory' not in details[2].split(','): + continue + mounts.append(tuple(map(_mount_path, fields[3:5]))) + + return tuple(mounts) + + def _cgroup_memory_headroom(): """Return the tightest visible cgroup memory headroom in bytes. - Account for usage in the current group and each visible ancestor. Return - None when no memory limit and usage can be read together. + Read the current limit and usage of the group and each visible ancestor. + Return None when no memory limit and usage can be read together. """ try: groups = (_PROC_SELF / 'cgroup').read_text(errors='surrogateescape') - mounts = (_PROC_SELF / 'mountinfo').read_text(errors='surrogateescape') + mountinfo = (_PROC_SELF / 'mountinfo').read_text(errors='surrogateescape') except OSError: return None @@ -49,15 +73,7 @@ def _cgroup_memory_headroom(): if v1 else ('memory.max', 'memory.current')) headrooms = [] - for line in mounts.split('\n'): - mount, _, superblock = line.partition(' - ') - fields = mount.split(' ') - details = superblock.split() - if len(fields) < 5 or len(details) < 3 or details[0] != fs: - continue - if v1 and 'memory' not in details[2].split(','): - continue - root, mountpoint = map(_mount_path, fields[3:5]) + for root, mountpoint in _cgroup_memory_mounts(mountinfo, fs): try: directory = mountpoint / group.relative_to(root) except ValueError: @@ -76,42 +92,51 @@ def _cgroup_memory_headroom(): for path in (directory, *directory.parents): with suppress(OSError, ValueError): limit = int((path / limit_name).read_text()) - usage = int((path / usage_name).read_text()) - if limit >= 0 and usage >= 0: - headrooms.append(max(0, limit - usage)) + if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED): + usage = int((path / usage_name).read_text()) + if usage >= 0: + headrooms.append(max(0, limit - usage)) if path == mountpoint: break return min(headrooms, default=None) -def _slurm_integer(env, name): +def _slurm_integer(value): """Read a nonnegative Slurm memory size or resource count. Zero represents an unset, invalid, or negative field. Callers treat zero as an unspecified budget or count. """ try: - return max(0, int(env.get(name, '0'))) + return max(0, int(value or '0')) except ValueError: return 0 +@lru_cache(maxsize=1) +def _slurm_memory_bytes(memory, count='1', fallback_count=None): + """Convert the selected Slurm memory request and local count to bytes.""" + units = _slurm_integer(count) or _slurm_integer(fallback_count) + budget = _slurm_integer(memory) * units + return budget * 2**20 if budget else None + + def _slurm_memory_limit(env): if not (env.get('SLURM_JOB_ID') or env.get('SLURM_JOBID')): return None if 'SLURM_MEM_PER_NODE' in env: - budget = _slurm_integer(env, 'SLURM_MEM_PER_NODE') - elif 'SLURM_MEM_PER_CPU' in env: - budget = (_slurm_integer(env, 'SLURM_MEM_PER_CPU') * - _slurm_integer(env, 'SLURM_CPUS_ON_NODE')) - else: - gpus = (_slurm_integer(env, 'SLURM_GPUS_ON_NODE') or - _slurm_integer(env, 'SLURM_GPUS_PER_NODE')) - budget = _slurm_integer(env, 'SLURM_MEM_PER_GPU') * gpus + return _slurm_memory_bytes(env['SLURM_MEM_PER_NODE']) + if 'SLURM_MEM_PER_CPU' in env: + return _slurm_memory_bytes( + env['SLURM_MEM_PER_CPU'], env.get('SLURM_CPUS_ON_NODE') + ) - return budget * 2**20 if budget else None + return _slurm_memory_bytes( + env.get('SLURM_MEM_PER_GPU'), env.get('SLURM_GPUS_ON_NODE'), + env.get('SLURM_GPUS_PER_NODE') + ) def host_memory_available(node_available): @@ -127,5 +152,18 @@ def host_memory_available(node_available): systemd scope, so also apply any local allocation reported in the Slurm environment. """ - limits = (node_available, _cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) - return min(limit for limit in limits if limit is not None) + limits = { + source: limit for source, limit in ( + ('cgroup headroom', _cgroup_memory_headroom()), + ('Slurm allocation', _slurm_memory_limit(os.environ)), + ) + if limit is not None + } + available = min((node_available, *limits.values())) + if limits and is_log_enabled_for('PERF'): + details = ', '.join(f'{source} {humanbytes(limit)}' + for source, limit in limits.items()) + perf(f'Host memory budget {humanbytes(available)} ' + f'(node available {humanbytes(node_available)}, {details})') + + return available diff --git a/tests/test_limits.py b/tests/test_limits.py index fcc1229627..cad13a9731 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -4,6 +4,7 @@ from devito import Eq, Function, Grid, Operator from devito.arch import ANYCPU, host_memory_available, limits +from devito.logger import PERF from devito.types import host_layer MIB = 2**20 @@ -45,16 +46,21 @@ def test_cgroup2_parent_headroom(proc_self, tmp_path): assert host_memory_available(2000) == 0 -def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): +def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): v1, v2 = tmp_path / 'memory', tmp_path / 'unified' (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' f'3 2 0:45 /slurm {v1} rw - cgroup cgroup ' 'rw,memory\n') (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') write_memory(v2 / 'job_42', 60, 10) - write_memory(v1 / 'job_42', 500, 375, v1=True) write_memory(v1 / 'job_42' / 'task', 9223372036854771712, 300, v1=True) - assert host_memory_available(2000) == 125 + with caplog.at_level(PERF, logger='Devito'): + assert host_memory_available(2000) == 2000 + assert 'Host memory budget' not in caplog.text + + write_memory(v1 / 'job_42', 500, 375, v1=True) + assert host_memory_available(2000) == 125 + assert 'cgroup headroom 125 B' in caplog.text def test_cgroup2_private_namespace(proc_self, tmp_path): @@ -95,7 +101,7 @@ def test_slurm_allocation_budget(proc_self, monkeypatch, env, mib): assert host_memory_available(1024 * MIB) == (mib or 1024) * MIB -def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch): +def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch, caplog): mount = tmp_path / 'memory' (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') (proc_self / 'cgroup').write_text('0::/job_42\n') @@ -107,7 +113,14 @@ def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch): write_memory(mount / 'job_42', 48 * MIB, 24 * MIB) assert host_memory_available(1024 * MIB) == 16 * MIB write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) - assert host_memory_available(1024 * MIB) == 8 * MIB + with caplog.at_level(PERF, logger='Devito'): + assert host_memory_available(1024 * MIB) == 8 * MIB + assert 'Host memory budget 8 MB' in caplog.text + assert 'cgroup headroom 8 MB, Slurm allocation 16 MB' in caplog.text + + monkeypatch.setenv('SLURM_MEM_PER_NODE', '4') + assert host_memory_available(1024 * MIB) == 4 * MIB + assert 'Host memory budget 4 MB' in caplog.text def test_operator_uses_local_host_budget(proc_self, monkeypatch): From 068d17a9765249ecc15b6fb39b56632d4eabb1c5 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 08:35:59 -0600 Subject: [PATCH 05/11] arch: Use Devito memoization for host memory metadata --- devito/arch/limits.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index a7f76346fe..50038cf86c 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -3,12 +3,11 @@ import os import re from contextlib import suppress -from functools import lru_cache from mmap import PAGESIZE from pathlib import Path from devito.logger import is_log_enabled_for, perf -from devito.tools import humanbytes +from devito.tools import humanbytes, memoized_func __all__ = ['host_memory_available'] @@ -22,7 +21,7 @@ def _mount_path(value): return Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)) -@lru_cache(maxsize=1) +@memoized_func def _cgroup_memory_mounts(mountinfo, fs): """Resolve the memory controller mounts described by mountinfo.""" mounts = [] @@ -114,7 +113,7 @@ def _slurm_integer(value): return 0 -@lru_cache(maxsize=1) +@memoized_func def _slurm_memory_bytes(memory, count='1', fallback_count=None): """Convert the selected Slurm memory request and local count to bytes.""" units = _slurm_integer(count) or _slurm_integer(fallback_count) From 410a007db966c3e54229f0838a25ef8a8aa898c0 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 08:38:50 -0600 Subject: [PATCH 06/11] arch: Clarify and report the effective host memory cap --- devito/arch/limits.py | 25 ++++++++++--------------- tests/test_limits.py | 10 +++++----- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 50038cf86c..3c67119f6e 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -12,8 +12,11 @@ __all__ = ['host_memory_available'] _PROC_SELF = Path('/proc/self') -# The 64-bit v1 controller uses page-aligned LONG_MAX for an unlimited cap. -_CGROUP_V1_UNLIMITED = (2**63 - 1) // PAGESIZE * PAGESIZE +# On 64-bit Linux, cgroup v1 uses the number of whole pages that fit +# in LONG_MAX (2**63 - 1) bytes to represent an unlimited cap. +# The memory.limit_in_bytes file reports the size of those pages in bytes. +_CGROUP_V1_UNLIMITED_PAGES = (2**63 - 1) // PAGESIZE +_CGROUP_V1_UNLIMITED_BYTES = _CGROUP_V1_UNLIMITED_PAGES * PAGESIZE def _mount_path(value): @@ -91,7 +94,7 @@ def _cgroup_memory_headroom(): for path in (directory, *directory.parents): with suppress(OSError, ValueError): limit = int((path / limit_name).read_text()) - if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED): + if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED_BYTES): usage = int((path / usage_name).read_text()) if usage >= 0: headrooms.append(max(0, limit - usage)) @@ -151,18 +154,10 @@ def host_memory_available(node_available): systemd scope, so also apply any local allocation reported in the Slurm environment. """ - limits = { - source: limit for source, limit in ( - ('cgroup headroom', _cgroup_memory_headroom()), - ('Slurm allocation', _slurm_memory_limit(os.environ)), - ) - if limit is not None - } - available = min((node_available, *limits.values())) + limits = (_cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) + limits = tuple(limit for limit in limits if limit is not None) + available = min((node_available, *limits)) if limits and is_log_enabled_for('PERF'): - details = ', '.join(f'{source} {humanbytes(limit)}' - for source, limit in limits.items()) - perf(f'Host memory budget {humanbytes(available)} ' - f'(node available {humanbytes(node_available)}, {details})') + perf(f'Host memory budget {humanbytes(available)}') return available diff --git a/tests/test_limits.py b/tests/test_limits.py index cad13a9731..d9c09760c8 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -1,4 +1,5 @@ import os +from mmap import PAGESIZE import pytest @@ -53,14 +54,14 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): 'rw,memory\n') (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') write_memory(v2 / 'job_42', 60, 10) - write_memory(v1 / 'job_42' / 'task', 9223372036854771712, 300, v1=True) + write_memory(v1 / 'job_42' / 'task', 2**63 - PAGESIZE, 300, v1=True) with caplog.at_level(PERF, logger='Devito'): assert host_memory_available(2000) == 2000 assert 'Host memory budget' not in caplog.text write_memory(v1 / 'job_42', 500, 375, v1=True) assert host_memory_available(2000) == 125 - assert 'cgroup headroom 125 B' in caplog.text + assert caplog.messages[-1] == 'Host memory budget 125 B' def test_cgroup2_private_namespace(proc_self, tmp_path): @@ -115,12 +116,11 @@ def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch, caplog): write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) with caplog.at_level(PERF, logger='Devito'): assert host_memory_available(1024 * MIB) == 8 * MIB - assert 'Host memory budget 8 MB' in caplog.text - assert 'cgroup headroom 8 MB, Slurm allocation 16 MB' in caplog.text + assert caplog.messages[-1] == 'Host memory budget 8 MB' monkeypatch.setenv('SLURM_MEM_PER_NODE', '4') assert host_memory_available(1024 * MIB) == 4 * MIB - assert 'Host memory budget 4 MB' in caplog.text + assert caplog.messages[-1] == 'Host memory budget 4 MB' def test_operator_uses_local_host_budget(proc_self, monkeypatch): From efe880c2a49339d552eb82f10ccefa079c332621 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 09:02:44 -0600 Subject: [PATCH 07/11] tests: Align cgroup mountinfo fixture continuations --- tests/test_limits.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/tests/test_limits.py b/tests/test_limits.py index d9c09760c8..49987e8799 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -34,8 +34,9 @@ def write_memory(group, limit, usage, *, v1=False): def test_cgroup2_parent_headroom(proc_self, tmp_path): mount = tmp_path / 'memory with spaces' escaped_mount = str(mount).replace(' ', r'\040') - (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {escaped_mount} rw - ' - 'cgroup2 cgroup rw\n') + (proc_self / 'mountinfo').write_text( + f'1 2 0:44 / {escaped_mount} rw - cgroup2 cgroup rw\n' + ) (proc_self / 'cgroup').write_text('0::/slurm/job_42/step\n') job = mount / 'slurm' / 'job_42' write_memory(job / 'step', 800, 500) @@ -49,9 +50,10 @@ def test_cgroup2_parent_headroom(proc_self, tmp_path): def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): v1, v2 = tmp_path / 'memory', tmp_path / 'unified' - (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' - f'3 2 0:45 /slurm {v1} rw - cgroup cgroup ' - 'rw,memory\n') + (proc_self / 'mountinfo').write_text( + f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' + f'3 2 0:45 /slurm {v1} rw - cgroup cgroup rw,memory\n' + ) (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') write_memory(v2 / 'job_42', 60, 10) write_memory(v1 / 'job_42' / 'task', 2**63 - PAGESIZE, 300, v1=True) @@ -66,8 +68,9 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): def test_cgroup2_private_namespace(proc_self, tmp_path): mount = tmp_path / 'memory' - (proc_self / 'mountinfo').write_text(f'1 2 0:44 /containers/123 {mount} rw - ' - 'cgroup2 cgroup rw\n') + (proc_self / 'mountinfo').write_text( + f'1 2 0:44 /containers/123 {mount} rw - cgroup2 cgroup rw\n' + ) (proc_self / 'cgroup').write_text('0::/\n') write_memory(mount, 400, 168) (mount / 'cgroup.procs').write_text(f'{os.getpid()}\n') From c8d9b26db406bc28e69cd18b93c6c41239bf3aef Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 09:08:55 -0600 Subject: [PATCH 08/11] arch: Simplify memory mount parsing and label host budgets --- devito/arch/limits.py | 47 ++++++++++++++++++++++++++++--------------- tests/test_limits.py | 9 ++++++--- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 3c67119f6e..92ff477595 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -19,24 +19,32 @@ _CGROUP_V1_UNLIMITED_BYTES = _CGROUP_V1_UNLIMITED_PAGES * PAGESIZE -def _mount_path(value): - # mountinfo escapes whitespace and backslashes as octal sequences. - return Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)) - - @memoized_func def _cgroup_memory_mounts(mountinfo, fs): - """Resolve the memory controller mounts described by mountinfo.""" + """ + Return the root and mount point of each visible memory controller mount. + + In `/proc/self/mountinfo`, the root is the part of the cgroup hierarchy + exposed at the mount point. A mount may expose only a subtree. In v1, + the `memory` superblock option identifies the memory controller. + """ mounts = [] for line in mountinfo.split('\n'): - mount, _, superblock = line.partition(' - ') - fields = mount.split(' ') - details = superblock.split() - if len(fields) < 5 or len(details) < 3 or details[0] != fs: + location, _, superblock = line.partition(' - ') + try: + kind, _, options = superblock.split()[:3] + except ValueError: continue - if fs == 'cgroup' and 'memory' not in details[2].split(','): + if kind != fs or (kind == 'cgroup' and 'memory' not in options.split(',')): continue - mounts.append(tuple(map(_mount_path, fields[3:5]))) + + paths = location.split(' ', 5)[3:5] + if len(paths) == 2: + # Mountinfo escapes whitespace and backslashes as octal sequences. + mounts.append(tuple( + Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), path)) + for path in paths + )) return tuple(mounts) @@ -53,6 +61,8 @@ def _cgroup_memory_headroom(): except OSError: return None + # Each /proc/self/cgroup entry gives a hierarchy ID, a list of controllers, + # and the process's group path. An empty list on hierarchy 0 denotes v2. memberships = {} for line in groups.split('\n'): fields = line.split(':', 2) @@ -154,10 +164,15 @@ def host_memory_available(node_available): systemd scope, so also apply any local allocation reported in the Slurm environment. """ - limits = (_cgroup_memory_headroom(), _slurm_memory_limit(os.environ)) - limits = tuple(limit for limit in limits if limit is not None) - available = min((node_available, *limits)) + limits = ( + (_cgroup_memory_headroom(), 'cgroup'), + (_slurm_memory_limit(os.environ), 'slurm'), + ) + limits = tuple((limit, reason) for limit, reason in limits if limit is not None) + available, reason = min( + (*limits, (node_available, 'node')), key=lambda entry: entry[0] + ) if limits and is_log_enabled_for('PERF'): - perf(f'Host memory budget {humanbytes(available)}') + perf(f'Host memory budget {humanbytes(available)} [{reason}]') return available diff --git a/tests/test_limits.py b/tests/test_limits.py index 49987e8799..55ce1caeeb 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -63,7 +63,7 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): write_memory(v1 / 'job_42', 500, 375, v1=True) assert host_memory_available(2000) == 125 - assert caplog.messages[-1] == 'Host memory budget 125 B' + assert caplog.messages[-1] == 'Host memory budget 125 B [cgroup]' def test_cgroup2_private_namespace(proc_self, tmp_path): @@ -119,11 +119,14 @@ def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch, caplog): write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) with caplog.at_level(PERF, logger='Devito'): assert host_memory_available(1024 * MIB) == 8 * MIB - assert caplog.messages[-1] == 'Host memory budget 8 MB' + assert caplog.messages[-1] == 'Host memory budget 8 MB [cgroup]' monkeypatch.setenv('SLURM_MEM_PER_NODE', '4') assert host_memory_available(1024 * MIB) == 4 * MIB - assert caplog.messages[-1] == 'Host memory budget 4 MB' + assert caplog.messages[-1] == 'Host memory budget 4 MB [slurm]' + + assert host_memory_available(2 * MIB) == 2 * MIB + assert caplog.messages[-1] == 'Host memory budget 2 MB [node]' def test_operator_uses_local_host_budget(proc_self, monkeypatch): From da138c80285c0264f6a2cfaf1b7ac981e3c57b81 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 09:38:56 -0600 Subject: [PATCH 09/11] arch: Share cgroup memory limits and test with explicit inputs --- devito/arch/limits.py | 71 +++++++++------- tests/test_limits.py | 184 +++++++++++++++++++++++++----------------- 2 files changed, 153 insertions(+), 102 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 92ff477595..0e4486c4e6 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -9,7 +9,7 @@ from devito.logger import is_log_enabled_for, perf from devito.tools import humanbytes, memoized_func -__all__ = ['host_memory_available'] +__all__ = ['cgroup_memory_limit', 'host_memory_available'] _PROC_SELF = Path('/proc/self') # On 64-bit Linux, cgroup v1 uses the number of whole pages that fit @@ -49,17 +49,13 @@ def _cgroup_memory_mounts(mountinfo, fs): return tuple(mounts) -def _cgroup_memory_headroom(): - """Return the tightest visible cgroup memory headroom in bytes. - - Read the current limit and usage of the group and each visible ancestor. - Return None when no memory limit and usage can be read together. - """ +def _cgroup_memory_limits(proc_self): + """Yield each finite memory ceiling and its usage file up to the mount root.""" try: - groups = (_PROC_SELF / 'cgroup').read_text(errors='surrogateescape') - mountinfo = (_PROC_SELF / 'mountinfo').read_text(errors='surrogateescape') + groups = (proc_self / 'cgroup').read_text(errors='surrogateescape') + mountinfo = (proc_self / 'mountinfo').read_text(errors='surrogateescape') except OSError: - return None + return # Each /proc/self/cgroup entry gives a hierarchy ID, a list of controllers, # and the process's group path. An empty list on hierarchy 0 denotes v2. @@ -80,11 +76,10 @@ def _cgroup_memory_headroom(): fs = 'cgroup' if v1 else 'cgroup2' group = memberships.get(fs) if group is None or not group.is_absolute() or '..' in group.parts: - return None + return limit_name, usage_name = (('memory.limit_in_bytes', 'memory.usage_in_bytes') if v1 else ('memory.max', 'memory.current')) - headrooms = [] for root, mountpoint in _cgroup_memory_mounts(mountinfo, fs): try: directory = mountpoint / group.relative_to(root) @@ -99,21 +94,37 @@ def _cgroup_memory_headroom(): if str(os.getpid()) not in processes: continue - # A parent can have less headroom than the process's own group, - # since its usage also includes sibling processes and cgroups. for path in (directory, *directory.parents): with suppress(OSError, ValueError): limit = int((path / limit_name).read_text()) if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED_BYTES): - usage = int((path / usage_name).read_text()) - if usage >= 0: - headrooms.append(max(0, limit - usage)) + yield limit, path / usage_name if path == mountpoint: break + +def _cgroup_memory_headroom(proc_self): + """Return the tightest visible cgroup memory headroom in bytes. + + Read the current limit and usage of the group and each visible ancestor. + A parent's usage also includes sibling processes and cgroups. + Return None when no memory limit and usage can be read together. + """ + headrooms = [] + for limit, usage_file in _cgroup_memory_limits(proc_self): + with suppress(OSError, ValueError): + usage = int(usage_file.read_text()) + if usage >= 0: + headrooms.append(max(0, limit - usage)) + return min(headrooms, default=None) +def cgroup_memory_limit(): + """Return the tightest visible cgroup memory ceiling in bytes, or None.""" + return min((limit for limit, _ in _cgroup_memory_limits(_PROC_SELF)), default=None) + + def _slurm_integer(value): """Read a nonnegative Slurm memory size or resource count. @@ -151,6 +162,18 @@ def _slurm_memory_limit(env): ) +def _host_memory_budget(node_available, cgroup, slurm): + limits = ((cgroup, 'cgroup'), (slurm, 'slurm')) + limits = tuple((limit, reason) for limit, reason in limits if limit is not None) + available, reason = min( + (*limits, (node_available, 'node')), key=lambda entry: entry[0] + ) + if limits and is_log_enabled_for('PERF'): + perf(f'Host memory budget {humanbytes(available)} [{reason}]') + + return available + + def host_memory_available(node_available): """ Return available host memory in bytes. @@ -164,15 +187,7 @@ def host_memory_available(node_available): systemd scope, so also apply any local allocation reported in the Slurm environment. """ - limits = ( - (_cgroup_memory_headroom(), 'cgroup'), - (_slurm_memory_limit(os.environ), 'slurm'), - ) - limits = tuple((limit, reason) for limit, reason in limits if limit is not None) - available, reason = min( - (*limits, (node_available, 'node')), key=lambda entry: entry[0] + return _host_memory_budget( + node_available, _cgroup_memory_headroom(_PROC_SELF), + _slurm_memory_limit(os.environ) ) - if limits and is_log_enabled_for('PERF'): - perf(f'Host memory budget {humanbytes(available)} [{reason}]') - - return available diff --git a/tests/test_limits.py b/tests/test_limits.py index 55ce1caeeb..e277d5740c 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -1,23 +1,22 @@ import os +import sys from mmap import PAGESIZE +from pathlib import Path +from subprocess import run +from textwrap import dedent import pytest -from devito import Eq, Function, Grid, Operator -from devito.arch import ANYCPU, host_memory_available, limits +from devito.arch import limits from devito.logger import PERF -from devito.types import host_layer MIB = 2**20 @pytest.fixture -def proc_self(tmp_path, monkeypatch): +def proc_self(tmp_path): proc = tmp_path / 'proc' / 'self' proc.mkdir(parents=True) - monkeypatch.setattr(limits, '_PROC_SELF', proc) - monkeypatch.delenv('SLURM_JOB_ID', raising=False) - monkeypatch.delenv('SLURM_JOBID', raising=False) return proc @@ -31,24 +30,29 @@ def write_memory(group, limit, usage, *, v1=False): (group / 'memory.current').write_text(str(usage)) -def test_cgroup2_parent_headroom(proc_self, tmp_path): +@pytest.mark.parametrize('root', ['/', '/slurm']) +@pytest.mark.parametrize('v1', [False, True]) +def test_cgroup_parent_headroom(proc_self, tmp_path, root, v1): mount = tmp_path / 'memory with spaces' escaped_mount = str(mount).replace(' ', r'\040') + membership = '7:memory:' if v1 else '0::' + filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' (proc_self / 'mountinfo').write_text( - f'1 2 0:44 / {escaped_mount} rw - cgroup2 cgroup rw\n' + f'1 2 0:44 {root} {escaped_mount} rw - {filesystem}\n' ) - (proc_self / 'cgroup').write_text('0::/slurm/job_42/step\n') - job = mount / 'slurm' / 'job_42' - write_memory(job / 'step', 800, 500) - write_memory(job, 1000, 900) - assert host_memory_available(2000) == 100 - assert host_memory_available(50) == 50 + (proc_self / 'cgroup').write_text(f'{membership}/slurm/job_42/step\n') + job = mount / Path('/slurm/job_42').relative_to(root) + write_memory(job / 'step', 800, 500, v1=v1) + write_memory(job, 1000, 900, v1=v1) - write_memory(job, 1000, 1100) - assert host_memory_available(2000) == 0 + assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == [800, 1000] + assert limits._cgroup_memory_headroom(proc_self) == 100 + write_memory(job, 1000, 1100, v1=v1) + assert limits._cgroup_memory_headroom(proc_self) == 0 -def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): + +def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): v1, v2 = tmp_path / 'memory', tmp_path / 'unified' (proc_self / 'mountinfo').write_text( f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' @@ -57,27 +61,62 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path, caplog): (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') write_memory(v2 / 'job_42', 60, 10) write_memory(v1 / 'job_42' / 'task', 2**63 - PAGESIZE, 300, v1=True) - with caplog.at_level(PERF, logger='Devito'): - assert host_memory_available(2000) == 2000 - assert 'Host memory budget' not in caplog.text + assert not list(limits._cgroup_memory_limits(proc_self)) + assert limits._cgroup_memory_headroom(proc_self) is None - write_memory(v1 / 'job_42', 500, 375, v1=True) - assert host_memory_available(2000) == 125 - assert caplog.messages[-1] == 'Host memory budget 125 B [cgroup]' + write_memory(v1 / 'job_42', 500, 375, v1=True) + assert limits._cgroup_memory_headroom(proc_self) == 125 -def test_cgroup2_private_namespace(proc_self, tmp_path): +@pytest.mark.parametrize('v1', [False, True]) +def test_cgroup_private_namespace(proc_self, tmp_path, v1): mount = tmp_path / 'memory' + filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' (proc_self / 'mountinfo').write_text( - f'1 2 0:44 /containers/123 {mount} rw - cgroup2 cgroup rw\n' + f'1 2 0:44 /containers/123 {mount} rw - {filesystem}\n' ) - (proc_self / 'cgroup').write_text('0::/\n') - write_memory(mount, 400, 168) + (proc_self / 'cgroup').write_text('7:memory:/\n' if v1 else '0::/\n') + write_memory(mount, 400, 168, v1=v1) (mount / 'cgroup.procs').write_text(f'{os.getpid()}\n') - assert host_memory_available(500) == 232 + assert limits._cgroup_memory_headroom(proc_self) == 232 (mount / 'cgroup.procs').write_text('') - assert host_memory_available(500) == 500 + assert limits._cgroup_memory_headroom(proc_self) is None + + +@pytest.mark.parametrize('value, caps', [ + (None, []), + ('max', []), + ('-1', []), + ('malformed', []), + ('0', [0]), + ('2048', [2048]), +]) +def test_cgroup_ceiling_without_usage(proc_self, tmp_path, value, caps): + mount = tmp_path / 'memory' + mount.mkdir() + (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') + (proc_self / 'cgroup').write_text('0::/\n') + if value is not None: + (mount / 'memory.max').write_text(value) + + assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == caps + assert limits._cgroup_memory_headroom(proc_self) is None + + +@pytest.mark.parametrize('membership, root, filesystem', [ + ('malformed', '/', 'cgroup2 cgroup rw'), + ('0::/job', '/', ''), + ('0::/job', '/elsewhere', 'cgroup2 cgroup rw'), + ('5:cpu:/job', '/', 'cgroup cgroup rw,cpu'), + ('0::/../job', '/', 'cgroup2 cgroup rw'), +]) +def test_invalid_cgroup_metadata(proc_self, tmp_path, membership, root, filesystem): + mount = tmp_path / 'memory' + write_memory(mount, 0, 0) + (proc_self / 'cgroup').write_text(membership) + (proc_self / 'mountinfo').write_text(f'1 2 0:44 {root} {mount} rw - {filesystem}') + assert not list(limits._cgroup_memory_limits(proc_self)) @pytest.mark.parametrize('env, mib', [ @@ -92,51 +131,48 @@ def test_cgroup2_private_namespace(proc_self, tmp_path): ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_PER_NODE': '3'}, 600), ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS': '8'}, None), ]) -def test_slurm_allocation_budget(proc_self, monkeypatch, env, mib): - for key in ('SLURM_MEM_PER_NODE', 'SLURM_MEM_PER_CPU', 'SLURM_MEM_PER_GPU', - 'SLURM_CPUS_ON_NODE', 'SLURM_GPUS_ON_NODE', 'SLURM_GPUS_PER_NODE'): - monkeypatch.delenv(key, raising=False) - for key, value in env.items(): - monkeypatch.setenv(key, value) - +def test_slurm_allocation_budget(env, mib): # A launcher may leave scheduler variables behind outside a job. - assert host_memory_available(1024 * MIB) == 1024 * MIB - monkeypatch.setenv('SLURM_JOB_ID', '42') - assert host_memory_available(1024 * MIB) == (mib or 1024) * MIB + assert limits._slurm_memory_limit(env) is None + expected = mib * MIB if mib is not None else None + assert limits._slurm_memory_limit(dict(env, SLURM_JOB_ID='42')) == expected -def test_cgroup_and_slurm(proc_self, tmp_path, monkeypatch, caplog): - mount = tmp_path / 'memory' - (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') - (proc_self / 'cgroup').write_text('0::/job_42\n') - monkeypatch.setenv('SLURM_JOB_ID', '42') - monkeypatch.setenv('SLURM_MEM_PER_NODE', '16') - - write_memory(mount / 'job_42', 'max', 24 * MIB) - assert host_memory_available(1024 * MIB) == 16 * MIB - write_memory(mount / 'job_42', 48 * MIB, 24 * MIB) - assert host_memory_available(1024 * MIB) == 16 * MIB - write_memory(mount / 'job_42', 32 * MIB, 24 * MIB) +@pytest.mark.parametrize('node, cgroup, slurm, budget, reason', [ + (100, None, None, 100, None), + (100, None, 16, 16, 'slurm'), + (100, 24, 16, 16, 'slurm'), + (100, 8, 16, 8, 'cgroup'), + (2, 8, 4, 2, 'node'), +]) +def test_host_memory_budget(caplog, node, cgroup, slurm, budget, reason): with caplog.at_level(PERF, logger='Devito'): - assert host_memory_available(1024 * MIB) == 8 * MIB - assert caplog.messages[-1] == 'Host memory budget 8 MB [cgroup]' - - monkeypatch.setenv('SLURM_MEM_PER_NODE', '4') - assert host_memory_available(1024 * MIB) == 4 * MIB - assert caplog.messages[-1] == 'Host memory budget 4 MB [slurm]' - - assert host_memory_available(2 * MIB) == 2 * MIB - assert caplog.messages[-1] == 'Host memory budget 2 MB [node]' - - -def test_operator_uses_local_host_budget(proc_self, monkeypatch): - grid = Grid(shape=(8, 8)) - field = Function(name='field', grid=grid) - args = Operator(Eq(field, 1)).arguments() - monkeypatch.setattr(ANYCPU, 'memavail', lambda: 1024 * MIB) - monkeypatch.setattr(type(args.grid.distributor), 'nprocs_local', 4) - monkeypatch.setenv('SLURM_JOB_ID', '42') - monkeypatch.setenv('SLURM_MEM_PER_NODE', '64') - - consumed = args.nbytes_consumed_operator[host_layer] - assert args.nbytes_avail_mapper[host_layer] == 16 * MIB - consumed + assert limits._host_memory_budget(node, cgroup, slurm) == budget + if reason is None: + assert not caplog.messages + else: + assert caplog.messages == [f'Host memory budget {budget} B [{reason}]'] + + +def test_operator_host_budget(): + script = dedent(''' + from types import SimpleNamespace + + from devito import Eq, Function, Grid, Operator + from devito.operator.operator import ArgumentsMap + from devito.types import host_layer + + field = Function(name='field', grid=Grid(shape=(8, 8))) + op = Operator(Eq(field, 1)) + args = op.arguments() + grid = SimpleNamespace(comm=args.comm, + distributor=SimpleNamespace(nprocs_local=4)) + local = ArgumentsMap(args, grid, op) + consumed = local.nbytes_consumed_operator[host_layer] + assert local.nbytes_avail_mapper[host_layer] == 2**20 - consumed + ''') + env = dict(os.environ, SLURM_JOB_ID='42', SLURM_MEM_PER_NODE='4', DEVITO_MPI='0') + run( + [sys.executable, '-c', script], cwd=Path(__file__).resolve().parents[1], + env=env, check=True, timeout=60 + ) From 2c91d72648d52b16446b4596132782a9f8e728c4 Mon Sep 17 00:00:00 2001 From: Fabio Luporini Date: Thu, 3 Dec 2026 11:56:10 -0600 Subject: [PATCH 10/11] arch: Adopt PRO cgroup mount resolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use Jack’s namespace-root and mount-relative ancestor handling. Apply the known ceiling when current usage is unavailable. --- devito/arch/limits.py | 50 ++++++++++++++++++++++--------------------- tests/test_limits.py | 45 +++++++++++++++++++++++++++----------- 2 files changed, 59 insertions(+), 36 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 0e4486c4e6..5c3b15bbce 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -29,22 +29,20 @@ def _cgroup_memory_mounts(mountinfo, fs): the `memory` superblock option identifies the memory controller. """ mounts = [] - for line in mountinfo.split('\n'): - location, _, superblock = line.partition(' - ') - try: - kind, _, options = superblock.split()[:3] - except ValueError: + for line in mountinfo.splitlines(): + location, _, filesystem = line.partition(' - ') + location, filesystem = location.split(), filesystem.split() + if len(location) < 5 or len(filesystem) < 3: continue + kind, _, options = filesystem[:3] if kind != fs or (kind == 'cgroup' and 'memory' not in options.split(',')): continue - paths = location.split(' ', 5)[3:5] - if len(paths) == 2: - # Mountinfo escapes whitespace and backslashes as octal sequences. - mounts.append(tuple( - Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), path)) - for path in paths - )) + # Mountinfo escapes whitespace and backslashes as octal sequences. + mounts.append(tuple( + Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), path)) + for path in location[3:5] + )) return tuple(mounts) @@ -81,26 +79,29 @@ def _cgroup_memory_limits(proc_self): if v1 else ('memory.max', 'memory.current')) for root, mountpoint in _cgroup_memory_mounts(mountinfo, fs): - try: - directory = mountpoint / group.relative_to(root) - except ValueError: + if group == Path('/'): + # A private cgroup namespace reports its root as '/' even when + # mountinfo identifies the mount root by its host path. + relative = Path('.') + elif group.is_relative_to(root): + relative = group.relative_to(root) + else: # A container can see a bind mount of its cgroup subtree while # reporting its membership relative to a private cgroup root. - directory = mountpoint / group.relative_to('/') + relative = group.relative_to('/') try: - processes = (directory / 'cgroup.procs').read_text().split() + processes = (mountpoint / relative / 'cgroup.procs').read_text().split() except OSError: continue if str(os.getpid()) not in processes: continue - for path in (directory, *directory.parents): + for parent in (relative, *relative.parents): + path = mountpoint / parent with suppress(OSError, ValueError): limit = int((path / limit_name).read_text()) if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED_BYTES): yield limit, path / usage_name - if path == mountpoint: - break def _cgroup_memory_headroom(proc_self): @@ -108,14 +109,15 @@ def _cgroup_memory_headroom(proc_self): Read the current limit and usage of the group and each visible ancestor. A parent's usage also includes sibling processes and cgroups. - Return None when no memory limit and usage can be read together. + Use the ceiling as an upper bound when usage is unavailable. + Return None when no finite ceiling is visible. """ headrooms = [] for limit, usage_file in _cgroup_memory_limits(proc_self): + headroom = limit with suppress(OSError, ValueError): - usage = int(usage_file.read_text()) - if usage >= 0: - headrooms.append(max(0, limit - usage)) + headroom -= max(0, int(usage_file.read_text())) + headrooms.append(max(0, headroom)) return min(headrooms, default=None) diff --git a/tests/test_limits.py b/tests/test_limits.py index e277d5740c..989aa84207 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -69,7 +69,7 @@ def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): @pytest.mark.parametrize('v1', [False, True]) -def test_cgroup_private_namespace(proc_self, tmp_path, v1): +def test_cgroup_namespace_root(proc_self, tmp_path, v1): mount = tmp_path / 'memory' filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' (proc_self / 'mountinfo').write_text( @@ -77,31 +77,52 @@ def test_cgroup_private_namespace(proc_self, tmp_path, v1): ) (proc_self / 'cgroup').write_text('7:memory:/\n' if v1 else '0::/\n') write_memory(mount, 400, 168, v1=v1) - (mount / 'cgroup.procs').write_text(f'{os.getpid()}\n') + + # The bind mount exposes the namespace root even without cgroup.procs. + assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == [400] + assert limits._cgroup_memory_headroom(proc_self) == 232 + + +@pytest.mark.parametrize('v1', [False, True]) +def test_cgroup_nested_namespace(proc_self, tmp_path, v1): + mount = tmp_path / 'memory' + filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' + (proc_self / 'mountinfo').write_text( + f'1 2 0:44 /containers/123 {mount} rw - {filesystem}\n' + ) + (proc_self / 'cgroup').write_text('7:memory:/step\n' if v1 else '0::/step\n') + write_memory(mount, 400, 168, v1=v1) + step = mount / 'step' + step.mkdir() + (step / 'cgroup.procs').write_text(f'{os.getpid()}\n') assert limits._cgroup_memory_headroom(proc_self) == 232 - (mount / 'cgroup.procs').write_text('') + (step / 'cgroup.procs').write_text('') assert limits._cgroup_memory_headroom(proc_self) is None -@pytest.mark.parametrize('value, caps', [ - (None, []), - ('max', []), - ('-1', []), - ('malformed', []), - ('0', [0]), - ('2048', [2048]), +@pytest.mark.parametrize('value, usage, caps', [ + (None, None, []), + ('max', None, []), + ('-1', None, []), + ('malformed', None, []), + ('0', None, [0]), + ('2048', None, [2048]), + ('2048', 'malformed', [2048]), + ('2048', '-1', [2048]), ]) -def test_cgroup_ceiling_without_usage(proc_self, tmp_path, value, caps): +def test_cgroup_ceiling_without_usage(proc_self, tmp_path, value, usage, caps): mount = tmp_path / 'memory' mount.mkdir() (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') (proc_self / 'cgroup').write_text('0::/\n') if value is not None: (mount / 'memory.max').write_text(value) + if usage is not None: + (mount / 'memory.current').write_text(usage) assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == caps - assert limits._cgroup_memory_headroom(proc_self) is None + assert limits._cgroup_memory_headroom(proc_self) == min(caps, default=None) @pytest.mark.parametrize('membership, root, filesystem', [ From 75c2997c6e23f462754f81088591350f09ca65d3 Mon Sep 17 00:00:00 2001 From: Jack Betteridge Date: Fri, 4 Dec 2026 00:59:35 +0000 Subject: [PATCH 11/11] arch: Refactor cgroups logic --- devito/arch/limits.py | 222 +++++++++++-------------- devito/operator/operator.py | 4 +- tests/test_limits.py | 322 +++++++++++++++++++++--------------- 3 files changed, 292 insertions(+), 256 deletions(-) diff --git a/devito/arch/limits.py b/devito/arch/limits.py index 5c3b15bbce..98141474ab 100644 --- a/devito/arch/limits.py +++ b/devito/arch/limits.py @@ -2,132 +2,113 @@ import os import re -from contextlib import suppress -from mmap import PAGESIZE +from functools import partial from pathlib import Path +from psutil import virtual_memory + from devito.logger import is_log_enabled_for, perf -from devito.tools import humanbytes, memoized_func +from devito.tools import humanbytes __all__ = ['cgroup_memory_limit', 'host_memory_available'] -_PROC_SELF = Path('/proc/self') -# On 64-bit Linux, cgroup v1 uses the number of whole pages that fit -# in LONG_MAX (2**63 - 1) bytes to represent an unlimited cap. -# The memory.limit_in_bytes file reports the size of those pages in bytes. -_CGROUP_V1_UNLIMITED_PAGES = (2**63 - 1) // PAGESIZE -_CGROUP_V1_UNLIMITED_BYTES = _CGROUP_V1_UNLIMITED_PAGES * PAGESIZE + +def is_memory_mount(entry, groups): + """Select valid mounts that expose the process's memory controller""" + location, filesystem = entry + # Check if the fields are valid + if len(location) >= 5 and len(filesystem) >= 3: + fstype, _, options = filesystem[:3] + return fstype in groups and ( + fstype == 'cgroup2' or 'memory' in options.split(',') + ) + return False -@memoized_func -def _cgroup_memory_mounts(mountinfo, fs): - """ - Return the root and mount point of each visible memory controller mount. +def cgroup_memory_query(): + """Estimate a host memory budget and usage in bytes for every known cgroup - In `/proc/self/mountinfo`, the root is the part of the cgroup hierarchy - exposed at the mount point. A mount may expose only a subtree. In v1, - the `memory` superblock option identifies the memory controller. + Never change the `_proc_self` kwarg, it is only required for testing """ - mounts = [] - for line in mountinfo.splitlines(): - location, _, filesystem = line.partition(' - ') - location, filesystem = location.split(), filesystem.split() - if len(location) < 5 or len(filesystem) < 3: - continue - kind, _, options = filesystem[:3] - if kind != fs or (kind == 'cgroup' and 'memory' not in options.split(',')): - continue - - # Mountinfo escapes whitespace and backslashes as octal sequences. - mounts.append(tuple( - Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), path)) - for path in location[3:5] - )) - - return tuple(mounts) - - -def _cgroup_memory_limits(proc_self): - """Yield each finite memory ceiling and its usage file up to the mount root.""" + # Read physical capacity and process cgroup metadata try: - groups = (proc_self / 'cgroup').read_text(errors='surrogateescape') - mountinfo = (proc_self / 'mountinfo').read_text(errors='surrogateescape') + memberships = Path('/proc/self/cgroup').read_text().splitlines() + mounts = Path('/proc/self/mountinfo').read_text().splitlines() except OSError: - return - - # Each /proc/self/cgroup entry gives a hierarchy ID, a list of controllers, - # and the process's group path. An empty list on hierarchy 0 denotes v2. - memberships = {} - for line in groups.split('\n'): - fields = line.split(':', 2) - if len(fields) != 3: - continue - hierarchy, controllers, group = fields - if 'memory' in controllers.split(','): - memberships['cgroup'] = Path(group) - elif hierarchy == '0' and not controllers: - memberships['cgroup2'] = Path(group) - - # On a hybrid system, the memory controller belongs to a single - # hierarchy. A v1 memory membership takes precedence. - v1 = 'cgroup' in memberships - fs = 'cgroup' if v1 else 'cgroup2' - group = memberships.get(fs) - if group is None or not group.is_absolute() or '..' in group.parts: - return - limit_name, usage_name = (('memory.limit_in_bytes', 'memory.usage_in_bytes') - if v1 else ('memory.max', 'memory.current')) - - for root, mountpoint in _cgroup_memory_mounts(mountinfo, fs): - if group == Path('/'): - # A private cgroup namespace reports its root as '/' even when - # mountinfo identifies the mount root by its host path. - relative = Path('.') - elif group.is_relative_to(root): - relative = group.relative_to(root) - else: - # A container can see a bind mount of its cgroup subtree while - # reporting its membership relative to a private cgroup root. - relative = group.relative_to('/') - try: - processes = (mountpoint / relative / 'cgroup.procs').read_text().split() - except OSError: - continue - if str(os.getpid()) not in processes: - continue - - for parent in (relative, *relative.parents): - path = mountpoint / parent - with suppress(OSError, ValueError): - limit = int((path / limit_name).read_text()) - if limit >= 0 and (not v1 or limit < _CGROUP_V1_UNLIMITED_BYTES): - yield limit, path / usage_name - - -def _cgroup_memory_headroom(proc_self): - """Return the tightest visible cgroup memory headroom in bytes. - - Read the current limit and usage of the group and each visible ancestor. - A parent's usage also includes sibling processes and cgroups. - Use the ceiling as an upper bound when usage is unavailable. - Return None when no finite ceiling is visible. - """ - headrooms = [] - for limit, usage_file in _cgroup_memory_limits(proc_self): - headroom = limit - with suppress(OSError, ValueError): - headroom -= max(0, int(usage_file.read_text())) - headrooms.append(max(0, headroom)) + memberships = mounts = [] + + # Identify membership in unified or v1 memory hierarchies + groups = {} + memberships = [line.split(':', 2) for line in memberships] + for hierarchy, controllers, path in (i for i in memberships if len(i) == 3): + if hierarchy == '0' and not controllers: + groups['cgroup2'] = Path(path) + elif 'memory' in controllers.split(','): + groups['cgroup'] = Path(path) + + # Select the memory mounts + mounts = filter( + partial(is_memory_mount, groups=groups), [ + (location.split(), filesystem.split()) + for location, _, filesystem in (line.partition(' - ') for line in mounts) + ] + ) - return min(headrooms, default=None) + # Resolve escaped mount paths and enumerate visible cgroup ancestors + limit_files = [] + for location, filesystem in mounts: + group = groups[filesystem[0]] + root, mount = [ + Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), i)) + for i in location[3:5] + ] + valid_group = group.is_absolute() and '..' not in group.parts + if valid_group and (group == Path('/') or group.is_relative_to(root)): + if group == Path('/'): # noqa: SIM108 + relative = Path('.') + else: + relative = group.relative_to(root) + # NOTE: + # Maximum memory allowed resides in memory.max or memory.limit_in_bytes + # Current memory usage resides in memory.current or memory.usage_in_bytes + if filesystem[0] == 'cgroup2': + filename = ('memory.max', 'memory.current') + else: + filename = ('memory.limit_in_bytes', 'memory.usage_in_bytes') + limit_files.extend( + (mount / parent / filename[0], mount / parent / filename[1]) + for parent in (relative, *relative.parents) + ) + + # Read capacity limits and usage falling back to those reported psutil + state = virtual_memory() + result = [(state.total, state.used)] + for path in limit_files: + try: + limit = path[0].read_text().strip() + except OSError: + limit = '' + try: + used = path[1].read_text().strip() + except OSError: + used = 0 + if limit.isdecimal(): + result.append((int(limit), int(used))) + + return result def cgroup_memory_limit(): - """Return the tightest visible cgroup memory ceiling in bytes, or None.""" - return min((limit for limit, _ in _cgroup_memory_limits(_PROC_SELF)), default=None) + """Return the lowest known cgroup memory ceiling in bytes""" + return min(cgroup_memory_query())[0] + + +def cgroup_memory_headroom(): + """Return the smallest available cgroup memory headroom in bytes""" + return min(limit - used for limit, used in cgroup_memory_query()) -def _slurm_integer(value): +def slurm_integer(value): """Read a nonnegative Slurm memory size or resource count. Zero represents an unset, invalid, or negative field. Callers treat zero @@ -139,32 +120,32 @@ def _slurm_integer(value): return 0 -@memoized_func -def _slurm_memory_bytes(memory, count='1', fallback_count=None): +def slurm_memory_bytes(memory, count='1', fallback_count=None): """Convert the selected Slurm memory request and local count to bytes.""" - units = _slurm_integer(count) or _slurm_integer(fallback_count) - budget = _slurm_integer(memory) * units + units = slurm_integer(count) or slurm_integer(fallback_count) + budget = slurm_integer(memory) * units return budget * 2**20 if budget else None -def _slurm_memory_limit(env): +def slurm_memory_limit(): + env = os.environ if not (env.get('SLURM_JOB_ID') or env.get('SLURM_JOBID')): return None if 'SLURM_MEM_PER_NODE' in env: - return _slurm_memory_bytes(env['SLURM_MEM_PER_NODE']) + return slurm_memory_bytes(env['SLURM_MEM_PER_NODE']) if 'SLURM_MEM_PER_CPU' in env: - return _slurm_memory_bytes( + return slurm_memory_bytes( env['SLURM_MEM_PER_CPU'], env.get('SLURM_CPUS_ON_NODE') ) - return _slurm_memory_bytes( + return slurm_memory_bytes( env.get('SLURM_MEM_PER_GPU'), env.get('SLURM_GPUS_ON_NODE'), env.get('SLURM_GPUS_PER_NODE') ) -def _host_memory_budget(node_available, cgroup, slurm): +def host_memory_budget(node_available, cgroup, slurm): limits = ((cgroup, 'cgroup'), (slurm, 'slurm')) limits = tuple((limit, reason) for limit, reason in limits if limit is not None) available, reason = min( @@ -176,7 +157,7 @@ def _host_memory_budget(node_available, cgroup, slurm): return available -def host_memory_available(node_available): +def host_memory_available(): """ Return available host memory in bytes. @@ -189,7 +170,6 @@ def host_memory_available(node_available): systemd scope, so also apply any local allocation reported in the Slurm environment. """ - return _host_memory_budget( - node_available, _cgroup_memory_headroom(_PROC_SELF), - _slurm_memory_limit(os.environ) + return host_memory_budget( + virtual_memory().available, cgroup_memory_headroom(), slurm_memory_limit() ) diff --git a/devito/operator/operator.py b/devito/operator/operator.py index 0799c3aac9..12c1f5f676 100644 --- a/devito/operator/operator.py +++ b/devito/operator/operator.py @@ -12,7 +12,7 @@ from sympy import sympify from devito.arch import ( - ANYCPU, Device, compiler_registry, get_visible_devices, host_memory_available, + Device, compiler_registry, get_visible_devices, host_memory_available, platform_registry ) from devito.data import default_allocator @@ -1517,7 +1517,7 @@ def nbytes_avail_mapper(self): nproc = self.grid.distributor.nprocs_local except AttributeError: nproc = 1 - mapper[host_layer] = host_memory_available(ANYCPU.memavail()) // nproc + mapper[host_layer] = host_memory_available() // nproc for layer in (host_layer, device_layer): if mapper.get(layer) is not None: diff --git a/tests/test_limits.py b/tests/test_limits.py index 989aa84207..be1603ab5c 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -1,162 +1,212 @@ import os import sys +from dataclasses import dataclass, field, replace from mmap import PAGESIZE from pathlib import Path from subprocess import run from textwrap import dedent +from types import SimpleNamespace +from unittest.mock import patch import pytest from devito.arch import limits from devito.logger import PERF -MIB = 2**20 + +@dataclass +class CgroupMount: + memory: dict = field(default_factory=dict) + version: int = 2 + root: str = '/' + group: str = '/' + membership: str | None = None + filesystem: str | None = None + procs_at: str | None = None @pytest.fixture -def proc_self(tmp_path): - proc = tmp_path / 'proc' / 'self' - proc.mkdir(parents=True) - return proc +def cgroup_fs(): + files = {} + host = SimpleNamespace(total=2**30, used=2**28) + templates = { + 1: ('7:memory:', 'cgroup cgroup rw,memory', + 'memory.limit_in_bytes', 'memory.usage_in_bytes'), + 2: ('0::', 'cgroup2 cgroup rw', 'memory.max', 'memory.current'), + } + + def read_text(path): + try: + return files[path] + except KeyError: + raise FileNotFoundError(path) from None + + def configure(*mounts): + files.clear() + memberships = [] + mountinfo = [] + + for index, mount in enumerate(mounts, start=1): + controller, filesystem, limit_file, usage_file = templates[mount.version] + path = Path(f'/sys/fs/cgroup/memory {index}') + escaped_path = str(path).replace(' ', r'\040') + membership = mount.membership + if membership is None: + membership = f'{controller}{mount.group}' + if mount.filesystem is not None: + filesystem = mount.filesystem + memberships.append(membership) + mountinfo.append(f'{index} 0 0:{index} {mount.root} {escaped_path} rw - ' + f'{filesystem}') + + if mount.procs_at is not None: + files[path / mount.procs_at / 'cgroup.procs'] = f'{os.getpid()}\n' + + for group, (ceiling, usage) in mount.memory.items(): + if ceiling is not None: + files[path / group / limit_file] = str(ceiling) + if usage is not None: + files[path / group / usage_file] = str(usage) + + files[Path('/proc/self/cgroup')] = '\n'.join(memberships) + files[Path('/proc/self/mountinfo')] = '\n'.join(mountinfo) + + with ( + patch.object(Path, 'read_text', autospec=True, side_effect=read_text), + patch.object(limits, 'virtual_memory', return_value=host), + ): + yield configure + + +def assert_cgroup_memory(*groups, ceiling, headroom): + assert limits.cgroup_memory_query() == [(2**30, 2**28), *groups] + assert limits.cgroup_memory_limit() == ceiling + assert limits.cgroup_memory_headroom() == headroom + + +@pytest.fixture(params=[1, 2], ids=['v1', 'v2']) +def cgroup_version(request): + return request.param + + +@pytest.mark.parametrize('root, job', [ + pytest.param('/', 'slurm/job_42', id='root-mount'), + pytest.param('/slurm', 'job_42', id='subtree-mount'), +]) +def test_cgroup_parent_headroom(cgroup_fs, cgroup_version, root, job): + mount = CgroupMount( + version=cgroup_version, root=root, group='/slurm/job_42/step', + memory={f'{job}/step': (800, 500), job: (1000, 900)}, + ) + cgroup_fs(mount) + assert_cgroup_memory((800, 500), (1000, 900), ceiling=800, headroom=100) + mount.memory[job] = (1000, 1100) + cgroup_fs(mount) + assert_cgroup_memory((800, 500), (1000, 1100), ceiling=800, headroom=-100) -def write_memory(group, limit, usage, *, v1=False): - group.mkdir(parents=True, exist_ok=True) - if v1: - (group / 'memory.limit_in_bytes').write_text(str(limit)) - (group / 'memory.usage_in_bytes').write_text(str(usage)) - else: - (group / 'memory.max').write_text(str(limit)) - (group / 'memory.current').write_text(str(usage)) - - -@pytest.mark.parametrize('root', ['/', '/slurm']) -@pytest.mark.parametrize('v1', [False, True]) -def test_cgroup_parent_headroom(proc_self, tmp_path, root, v1): - mount = tmp_path / 'memory with spaces' - escaped_mount = str(mount).replace(' ', r'\040') - membership = '7:memory:' if v1 else '0::' - filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' - (proc_self / 'mountinfo').write_text( - f'1 2 0:44 {root} {escaped_mount} rw - {filesystem}\n' + +def test_cgroup_memory_in_hybrid_hierarchy(cgroup_fs): + sentinel = 2**63 - PAGESIZE + unified = CgroupMount(group='/job_42', memory={'job_42': (60, 10)}) + legacy = CgroupMount( + version=1, root='/slurm', group='/slurm/job_42/task', + memory={'job_42/task': (sentinel, 300)}, ) - (proc_self / 'cgroup').write_text(f'{membership}/slurm/job_42/step\n') - job = mount / Path('/slurm/job_42').relative_to(root) - write_memory(job / 'step', 800, 500, v1=v1) - write_memory(job, 1000, 900, v1=v1) + cgroup_fs(unified, legacy) + assert_cgroup_memory((60, 10), (sentinel, 300), ceiling=60, headroom=50) - assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == [800, 1000] - assert limits._cgroup_memory_headroom(proc_self) == 100 + unified.memory['job_42'] = ('max', 10) + legacy.memory['job_42'] = (500, 375) + cgroup_fs(unified, legacy) + assert_cgroup_memory((sentinel, 300), (500, 375), ceiling=500, headroom=125) - write_memory(job, 1000, 1100, v1=v1) - assert limits._cgroup_memory_headroom(proc_self) == 0 +def test_cgroup_namespace_root(cgroup_fs, cgroup_version): + cgroup_fs(CgroupMount( + version=cgroup_version, root='/containers/123', memory={'.': (400, 168)}, + )) + assert_cgroup_memory((400, 168), ceiling=400, headroom=232) -def test_cgroup1_memory_in_hybrid_hierarchy(proc_self, tmp_path): - v1, v2 = tmp_path / 'memory', tmp_path / 'unified' - (proc_self / 'mountinfo').write_text( - f'1 2 0:44 / {v2} rw - cgroup2 cgroup rw\n' - f'3 2 0:45 /slurm {v1} rw - cgroup cgroup rw,memory\n' - ) - (proc_self / 'cgroup').write_text('7:memory:/slurm/job_42/task\n0::/job_42\n') - write_memory(v2 / 'job_42', 60, 10) - write_memory(v1 / 'job_42' / 'task', 2**63 - PAGESIZE, 300, v1=True) - assert not list(limits._cgroup_memory_limits(proc_self)) - assert limits._cgroup_memory_headroom(proc_self) is None - - write_memory(v1 / 'job_42', 500, 375, v1=True) - assert limits._cgroup_memory_headroom(proc_self) == 125 - - -@pytest.mark.parametrize('v1', [False, True]) -def test_cgroup_namespace_root(proc_self, tmp_path, v1): - mount = tmp_path / 'memory' - filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' - (proc_self / 'mountinfo').write_text( - f'1 2 0:44 /containers/123 {mount} rw - {filesystem}\n' - ) - (proc_self / 'cgroup').write_text('7:memory:/\n' if v1 else '0::/\n') - write_memory(mount, 400, 168, v1=v1) - # The bind mount exposes the namespace root even without cgroup.procs. - assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == [400] - assert limits._cgroup_memory_headroom(proc_self) == 232 +def test_cgroup_nested_namespace(cgroup_fs, cgroup_version): + cgroup_fs(CgroupMount( + version=cgroup_version, root='/containers/123', group='/step', + memory={'.': (400, 168)}, procs_at='step', + )) + assert_cgroup_memory(ceiling=2**30, headroom=3 * 2**28) -@pytest.mark.parametrize('v1', [False, True]) -def test_cgroup_nested_namespace(proc_self, tmp_path, v1): - mount = tmp_path / 'memory' - filesystem = 'cgroup cgroup rw,memory' if v1 else 'cgroup2 cgroup rw' - (proc_self / 'mountinfo').write_text( - f'1 2 0:44 /containers/123 {mount} rw - {filesystem}\n' - ) - (proc_self / 'cgroup').write_text('7:memory:/step\n' if v1 else '0::/step\n') - write_memory(mount, 400, 168, v1=v1) - step = mount / 'step' - step.mkdir() - (step / 'cgroup.procs').write_text(f'{os.getpid()}\n') - assert limits._cgroup_memory_headroom(proc_self) == 232 - - (step / 'cgroup.procs').write_text('') - assert limits._cgroup_memory_headroom(proc_self) is None - - -@pytest.mark.parametrize('value, usage, caps', [ - (None, None, []), - ('max', None, []), - ('-1', None, []), - ('malformed', None, []), - ('0', None, [0]), - ('2048', None, [2048]), - ('2048', 'malformed', [2048]), - ('2048', '-1', [2048]), +@pytest.mark.parametrize('value', [ + pytest.param(None, id='missing'), + pytest.param('max', id='unlimited'), + pytest.param('-1', id='negative'), + pytest.param('malformed', id='malformed'), ]) -def test_cgroup_ceiling_without_usage(proc_self, tmp_path, value, usage, caps): - mount = tmp_path / 'memory' - mount.mkdir() - (proc_self / 'mountinfo').write_text(f'1 2 0:44 / {mount} rw - cgroup2 cgroup rw\n') - (proc_self / 'cgroup').write_text('0::/\n') - if value is not None: - (mount / 'memory.max').write_text(value) - if usage is not None: - (mount / 'memory.current').write_text(usage) - - assert [cap for cap, _ in limits._cgroup_memory_limits(proc_self)] == caps - assert limits._cgroup_memory_headroom(proc_self) == min(caps, default=None) - - -@pytest.mark.parametrize('membership, root, filesystem', [ - ('malformed', '/', 'cgroup2 cgroup rw'), - ('0::/job', '/', ''), - ('0::/job', '/elsewhere', 'cgroup2 cgroup rw'), - ('5:cpu:/job', '/', 'cgroup cgroup rw,cpu'), - ('0::/../job', '/', 'cgroup2 cgroup rw'), +def test_cgroup_host_fallback_without_ceiling(cgroup_fs, value): + cgroup_fs(CgroupMount(memory={'.': (value, None)})) + assert_cgroup_memory(ceiling=2**30, headroom=3 * 2**28) + + +@pytest.mark.parametrize('limit', [0, 2048]) +def test_cgroup_ceiling_without_usage(cgroup_fs, limit): + cgroup_fs(CgroupMount(memory={'.': (limit, None)})) + assert_cgroup_memory((limit, 0), ceiling=limit, headroom=limit) + + +def test_cgroup_negative_usage(cgroup_fs): + cgroup_fs(CgroupMount(memory={'.': (2048, -1)})) + assert_cgroup_memory((2048, -1), ceiling=2048, headroom=2049) + + +def test_cgroup_malformed_usage(cgroup_fs): + cgroup_fs(CgroupMount(memory={'.': (2048, 'malformed')})) + with pytest.raises(ValueError, match='malformed'): + limits.cgroup_memory_query() + + +@pytest.mark.parametrize('mount', [ + pytest.param(CgroupMount(membership='malformed'), id='bad-membership'), + pytest.param(CgroupMount(group='/job', filesystem=''), id='missing-filesystem'), + pytest.param(CgroupMount(group='/job', root='/elsewhere'), id='different-root'), + pytest.param(CgroupMount(version=1, membership='5:cpu:/job', + filesystem='cgroup cgroup rw,cpu'), id='cpu-controller'), + pytest.param(CgroupMount(group='/../job'), id='parent-traversal'), ]) -def test_invalid_cgroup_metadata(proc_self, tmp_path, membership, root, filesystem): - mount = tmp_path / 'memory' - write_memory(mount, 0, 0) - (proc_self / 'cgroup').write_text(membership) - (proc_self / 'mountinfo').write_text(f'1 2 0:44 {root} {mount} rw - {filesystem}') - assert not list(limits._cgroup_memory_limits(proc_self)) - - -@pytest.mark.parametrize('env, mib', [ - ({}, None), - ({'SLURM_MEM_PER_NODE': '0'}, None), - ({'SLURM_MEM_PER_NODE': '-1'}, None), - ({'SLURM_MEM_PER_NODE': 'unavailable'}, None), - ({'SLURM_MEM_PER_NODE': '640'}, 640), - ({'SLURM_MEM_PER_CPU': '100', 'SLURM_CPUS_ON_NODE': '4', - 'SLURM_JOB_CPUS_PER_NODE': '72(x2),36', 'SLURM_NODEID': '0'}, 400), - ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_ON_NODE': '2', 'SLURM_GPUS': '8'}, 400), - ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_PER_NODE': '3'}, 600), - ({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS': '8'}, None), +def test_invalid_cgroup_metadata(cgroup_fs, mount): + cgroup_fs(replace(mount, memory={'.': (0, 0), 'job': (0, 0)})) + assert_cgroup_memory(ceiling=2**30, headroom=3 * 2**28) + + +@pytest.fixture(params=[ + pytest.param(({}, None), id='no-allocation'), + pytest.param(({'SLURM_MEM_PER_NODE': '0'}, None), id='zero-per-node'), + pytest.param(({'SLURM_MEM_PER_NODE': '-1'}, None), id='negative-per-node'), + pytest.param(({'SLURM_MEM_PER_NODE': 'unavailable'}, None), id='invalid-per-node'), + pytest.param(({'SLURM_MEM_PER_NODE': '640'}, 640), id='per-node'), + pytest.param(({ + 'SLURM_MEM_PER_CPU': '100', 'SLURM_CPUS_ON_NODE': '4', + 'SLURM_JOB_CPUS_PER_NODE': '72(x2),36', 'SLURM_NODEID': '0', + }, 400), id='per-cpu'), + pytest.param(({ + 'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_ON_NODE': '2', 'SLURM_GPUS': '8', + }, 400), id='per-gpu-local-count'), + pytest.param(({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS_PER_NODE': '3'}, 600), + id='per-gpu-fallback-count'), + pytest.param(({'SLURM_MEM_PER_GPU': '200', 'SLURM_GPUS': '8'}, None), + id='per-gpu-job-count-only'), ]) -def test_slurm_allocation_budget(env, mib): +def slurm_env(request): + env, mib = request.param + with patch.dict(os.environ, env, clear=True): + yield mib * 2**20 if mib is not None else None + + +def test_slurm_allocation_budget(slurm_env): # A launcher may leave scheduler variables behind outside a job. - assert limits._slurm_memory_limit(env) is None - expected = mib * MIB if mib is not None else None - assert limits._slurm_memory_limit(dict(env, SLURM_JOB_ID='42')) == expected + assert limits.slurm_memory_limit() is None + with patch.dict(os.environ, SLURM_JOB_ID='42'): + assert limits.slurm_memory_limit() == slurm_env @pytest.mark.parametrize('node, cgroup, slurm, budget, reason', [ @@ -166,9 +216,15 @@ def test_slurm_allocation_budget(env, mib): (100, 8, 16, 8, 'cgroup'), (2, 8, 4, 2, 'node'), ]) -def test_host_memory_budget(caplog, node, cgroup, slurm, budget, reason): - with caplog.at_level(PERF, logger='Devito'): - assert limits._host_memory_budget(node, cgroup, slurm) == budget +def test_host_memory_available(caplog, node, cgroup, slurm, budget, reason): + host = SimpleNamespace(available=node) + with ( + patch.object(limits, 'virtual_memory', return_value=host), + patch.object(limits, 'cgroup_memory_headroom', return_value=cgroup), + patch.object(limits, 'slurm_memory_limit', return_value=slurm), + caplog.at_level(PERF, logger='Devito'), + ): + assert limits.host_memory_available() == budget if reason is None: assert not caplog.messages else: