Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions devito/arch/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from .archinfo import * # noqa
from .compiler import * # noqa
from .limits import * # noqa
175 changes: 175 additions & 0 deletions devito/arch/limits.py
Original file line number Diff line number Diff line change
@@ -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()
)
5 changes: 3 additions & 2 deletions devito/operator/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading