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 new file mode 100644 index 0000000000..98141474ab --- /dev/null +++ b/devito/arch/limits.py @@ -0,0 +1,175 @@ +"""Operating-system and scheduler limits for host resources.""" + +import os +import re +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 + +__all__ = ['cgroup_memory_limit', 'host_memory_available'] + + +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 + + +def cgroup_memory_query(): + """Estimate a host memory budget and usage in bytes for every known cgroup + + Never change the `_proc_self` kwarg, it is only required for testing + """ + # Read physical capacity and process cgroup metadata + try: + memberships = Path('/proc/self/cgroup').read_text().splitlines() + mounts = Path('/proc/self/mountinfo').read_text().splitlines() + except OSError: + 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) + ] + ) + + # 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 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): + """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(value or '0')) + except ValueError: + return 0 + + +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 = 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']) + if 'SLURM_MEM_PER_CPU' in env: + return slurm_memory_bytes( + env['SLURM_MEM_PER_CPU'], env.get('SLURM_CPUS_ON_NODE') + ) + + 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): + 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(): + """ + Return available host memory in bytes. + + 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. + """ + 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 70d700cba3..12c1f5f676 100644 --- a/devito/operator/operator.py +++ b/devito/operator/operator.py @@ -12,7 +12,8 @@ from sympy import sympify from devito.arch import ( - ANYCPU, Device, compiler_registry, get_visible_devices, platform_registry + Device, compiler_registry, get_visible_devices, host_memory_available, + platform_registry ) from devito.data import default_allocator from devito.exceptions import ( @@ -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() // 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..be1603ab5c --- /dev/null +++ b/tests/test_limits.py @@ -0,0 +1,255 @@ +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 + + +@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 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 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)}, + ) + cgroup_fs(unified, legacy) + assert_cgroup_memory((60, 10), (sentinel, 300), ceiling=60, headroom=50) + + 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) + + +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_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('value', [ + pytest.param(None, id='missing'), + pytest.param('max', id='unlimited'), + pytest.param('-1', id='negative'), + pytest.param('malformed', id='malformed'), +]) +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(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 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() 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', [ + (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_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: + 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 + )