Skip to content
Open
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
56 changes: 50 additions & 6 deletions grain/_src/python/ipc/shared_memory_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import threading
from typing import Any, Iterable

from absl import logging
from grain._src.core import tree_lib
import numpy as np
import numpy.typing as npt
Expand All @@ -42,6 +43,14 @@ def close_and_unlink_shm(self) -> None:
shm.unlink()


@dataclasses.dataclass(slots=True, frozen=True)
class AsyncDelSettings:
"""The settings in effect for asynchronous deletion of shared memory."""

num_threads: int
max_outstanding_requests: int


def _del_shm(shm: shared_memory.SharedMemory, unlink: bool) -> None:
shm.close()
if unlink:
Expand All @@ -63,6 +72,7 @@ class SharedMemoryArray(np.ndarray):
_lock: threading.Lock = threading.Lock()
_del_thread_pool: pool.ThreadPool | None = None
_outstanding_del_requests: threading.Semaphore | None = None
_async_del_settings: AsyncDelSettings | None = None

def __new__(
cls,
Expand Down Expand Up @@ -142,20 +152,54 @@ def enable_async_del(
faster, but it may also lead to OOM errors or hitting file descriptor
limits, since `max_outstanding_requests` shared memory objects and their
associated file descriptors may be buffered before deletion.

The settings are process-wide and only the first call in a process takes
effect. A later call with the same settings is a no-op. A later call with
different settings logs a warning and leaves the settings in effect
unchanged; use `async_del_settings` to read them.
"""
requested = AsyncDelSettings(
num_threads=num_threads,
max_outstanding_requests=max(max_outstanding_requests, num_threads),
)
with SharedMemoryArray._lock:
if not SharedMemoryArray._del_thread_pool:
max_outstanding_requests = max(max_outstanding_requests, num_threads)
SharedMemoryArray._del_thread_pool = pool.ThreadPool(num_threads)
SharedMemoryArray._outstanding_del_requests = threading.Semaphore(
max_outstanding_requests
)
if SharedMemoryArray._del_thread_pool:
in_effect = SharedMemoryArray._async_del_settings
if in_effect is not None and requested != in_effect:
logging.warning(
"enable_async_del(num_threads=%d, max_outstanding_requests=%d) "
"has no effect: asynchronous deletion is already enabled with "
"num_threads=%d, max_outstanding_requests=%d, and only the "
"first call in a process takes effect.",
requested.num_threads,
requested.max_outstanding_requests,
in_effect.num_threads,
in_effect.max_outstanding_requests,
)
return
SharedMemoryArray._del_thread_pool = pool.ThreadPool(num_threads)
SharedMemoryArray._outstanding_del_requests = threading.Semaphore(
requested.max_outstanding_requests
)
SharedMemoryArray._async_del_settings = requested

@classmethod
def async_del_settings(cls) -> AsyncDelSettings | None:
"""Returns the async deletion settings in effect.

Returns:
The settings applied by the first `enable_async_del` call in this
process, or None while deletion is synchronous (async deletion has not
been enabled).
"""
return cls._async_del_settings

# For use in tests.
@classmethod
def _disable_async_del(cls) -> None:
cls._del_thread_pool = None
cls._outstanding_del_requests = None
cls._async_del_settings = None

# Mocked in tests, so be careful refactoring.
@classmethod
Expand Down
78 changes: 78 additions & 0 deletions grain/_src/python/ipc/shared_memory_array_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,84 @@ def test_failed_async_del_releases_its_slot(self):

self.assertTrue(outstanding_del_requests.acquire(blocking=False))

def test_async_del_settings_none_until_enabled(self):
SharedMemoryArray._disable_async_del()
self.assertIsNone(SharedMemoryArray.async_del_settings())

def test_async_del_settings_first_enable(self):
SharedMemoryArray._disable_async_del()
self.addCleanup(SharedMemoryArray._disable_async_del)
SharedMemoryArray.enable_async_del(
num_threads=2, max_outstanding_requests=8
)
self.assertEqual(
SharedMemoryArray.async_del_settings(),
shared_memory_array.AsyncDelSettings(
num_threads=2, max_outstanding_requests=8
),
)

def test_async_del_settings_records_bound_raised_to_num_threads(self):
SharedMemoryArray._disable_async_del()
self.addCleanup(SharedMemoryArray._disable_async_del)
# The bound in effect is raised to at least num_threads; the recorded
# settings are the ones actually applied.
SharedMemoryArray.enable_async_del(
num_threads=4, max_outstanding_requests=2
)
self.assertEqual(
SharedMemoryArray.async_del_settings(),
shared_memory_array.AsyncDelSettings(
num_threads=4, max_outstanding_requests=4
),
)

def test_async_del_reenable_same_settings_is_quiet_noop(self):
SharedMemoryArray._disable_async_del()
self.addCleanup(SharedMemoryArray._disable_async_del)
SharedMemoryArray.enable_async_del(
num_threads=2, max_outstanding_requests=8
)
with self.assertNoLogs(level="WARNING"):
SharedMemoryArray.enable_async_del(
num_threads=2, max_outstanding_requests=8
)
self.assertEqual(
SharedMemoryArray.async_del_settings(),
shared_memory_array.AsyncDelSettings(
num_threads=2, max_outstanding_requests=8
),
)

def test_async_del_reenable_conflicting_settings_warns_and_keeps_first(self):
SharedMemoryArray._disable_async_del()
self.addCleanup(SharedMemoryArray._disable_async_del)
SharedMemoryArray.enable_async_del(max_outstanding_requests=8)
with self.assertLogs(level="WARNING") as logs:
SharedMemoryArray.enable_async_del(max_outstanding_requests=200)
self.assertTrue(
any(
"max_outstanding_requests=200" in line
and "max_outstanding_requests=8" in line
for line in logs.output
),
logs.output,
)
# The first call still wins.
self.assertEqual(
SharedMemoryArray.async_del_settings(),
shared_memory_array.AsyncDelSettings(
num_threads=1, max_outstanding_requests=8
),
)

def test_async_del_settings_cleared_on_disable(self):
SharedMemoryArray._disable_async_del()
SharedMemoryArray.enable_async_del(max_outstanding_requests=8)
self.assertIsNotNone(SharedMemoryArray.async_del_settings())
SharedMemoryArray._disable_async_del()
self.assertIsNone(SharedMemoryArray.async_del_settings())

def test_copy_and_open_shm_single_array(self):
arr = np.arange(10).astype(np.int32)
shm_struct = copy_to_shm(arr)
Expand Down
1 change: 1 addition & 0 deletions grain/multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# pylint: disable=unused-import

from grain._src.python.ipc.shared_memory_array import (
AsyncDelSettings,
SharedMemoryArray,
SharedMemoryArrayMetadata,
)
Expand Down